diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml deleted file mode 100644 index 740ee4a..0000000 --- a/.github/workflows/release.yml +++ /dev/null @@ -1,236 +0,0 @@ -name: release - -# Build the self-contained joltc binary for each platform and attach it to the -# GitHub Release when a v* tag is pushed. The binary bundles the runtime, -# compiler, jolt-core + stdlib source, the Chez boots, and a launcher stub, so it -# runs AND compiles jolt apps with no Chez or cc on the user's machine (jolt-eaj). -# -# No Apple notarization, mirroring dirge: macOS users who download the tarball -# clear Gatekeeper quarantine once (`xattr -d com.apple.quarantine joltc`), or -# install via a Homebrew tap that de-quarantines on install. -on: - push: - tags: - - 'v*' - workflow_dispatch: {} # dry-run the build matrix without tagging - -permissions: - contents: write # create/update the GitHub Release and upload assets - -jobs: - build: - name: build ${{ matrix.target }} - runs-on: ${{ matrix.os }} - strategy: - fail-fast: false - matrix: - include: - - os: ubuntu-latest - target: x86_64-linux - shell: bash - # No x86_64-macos: GitHub is retiring the macos-13 Intel runner (jobs - # queue forever). Intel Macs build from source. macos-14 is arm64. - - os: macos-14 - target: aarch64-macos - shell: bash - - os: windows-latest - target: x86_64-windows - shell: msys2 {0} - defaults: - run: - shell: ${{ matrix.shell }} - steps: - - uses: actions/checkout@v5 - with: - submodules: recursive # vendor/irregex, used by the Chez regex shim - - # --- Linux: build Chez from source. The apt chezscheme ships petite+scheme - # only, with no kernel dev files (libkernel.a, scheme.h), which build-joltc - # needs to cc-link. Same setup as .github/workflows/tests.yml. --- - - name: Install build dependencies (Linux) - if: runner.os == 'Linux' - run: | - sudo apt-get update - sudo apt-get install -y build-essential git liblz4-dev zlib1g-dev libncurses-dev uuid-dev - - - name: Cache Chez Scheme (Linux) - if: runner.os == 'Linux' - id: cache-chez - uses: actions/cache@v4 - with: - path: /opt/chez - key: chez-${{ runner.os }}-v10.4.1-x11off - - - name: Build Chez Scheme from source (Linux) - if: runner.os == 'Linux' && steps.cache-chez.outputs.cache-hit != 'true' - run: | - git clone --depth 1 --branch v10.4.1 https://github.com/cisco/ChezScheme.git /tmp/chez-src - cd /tmp/chez-src - ./configure --installprefix=/opt/chez --threads --disable-x11 - make -j"$(nproc)" - sudo make install - sudo chown -R "$USER" /opt/chez - - - name: Put chez on PATH (Linux) - if: runner.os == 'Linux' - run: | - # Installed as `scheme`; the build invokes `chez`. A wrapper that execs - # scheme keeps argv0 so Chez finds its boot files, and sits next to - # scheme so build.ss derives the csv dir (libkernel.a/scheme.h) from it. - printf '#!/bin/sh\nexec /opt/chez/bin/scheme "$@"\n' > /opt/chez/bin/chez - chmod +x /opt/chez/bin/chez - echo '/opt/chez/bin' >> "$GITHUB_PATH" - - # --- macOS: Homebrew chezscheme ships `chez` plus the csv kernel dev files - # (libkernel.a, scheme.h, *.boot), which is all build-joltc needs. --- - - name: Install Chez Scheme (macOS) - if: runner.os == 'macOS' - run: brew install chezscheme lz4 - - # --- Windows: MSYS2/MinGW-w64 toolchain + Chez built from source (ta6nt). - # The whole job runs in the msys2 shell so cc/xxd/paths behave; the - # produced joltc.exe is a plain Windows binary (no MSYS runtime dep). --- - - name: Set up MSYS2 (Windows) - if: runner.os == 'Windows' - uses: msys2/setup-msys2@v2 - with: - msystem: MINGW64 - update: false - # inherit the runner PATH so GITHUB_PATH additions (the chez wrapper - # dir) are visible inside the msys2 shell - path-type: inherit - install: >- - git make vim unzip zip - mingw-w64-x86_64-gcc - mingw-w64-x86_64-lz4 - mingw-w64-x86_64-zlib - mingw-w64-x86_64-ntldd - - - name: Cache Chez Scheme (Windows) - if: runner.os == 'Windows' - id: cache-chez-win - uses: actions/cache@v4 - with: - path: chez-install - key: chez-${{ runner.os }}-v10.4.1-mingw64 - - - name: Build Chez Scheme from source (Windows) - if: runner.os == 'Windows' && steps.cache-chez-win.outputs.cache-hit != 'true' - run: | - git clone --depth 1 --branch v10.4.1 https://github.com/cisco/ChezScheme.git /tmp/chez-src - cd /tmp/chez-src - ./configure --threads - make -j"$(nproc)" - # `make install` drives the unix installsh through cmd and dies; the - # build tree has everything — assemble the layout by hand. Boot files - # sit next to scheme.exe (that's where the Windows kernel looks). - inst="$GITHUB_WORKSPACE/chez-install" - mkdir -p "$inst/bin" "$inst/csv" - cp ta6nt/bin/ta6nt/*.exe "$inst/bin/" - cp ta6nt/bin/ta6nt/*.dll "$inst/bin/" 2>/dev/null || true - cp ta6nt/boot/ta6nt/petite.boot ta6nt/boot/ta6nt/scheme.boot "$inst/bin/" - cp ta6nt/boot/ta6nt/petite.boot ta6nt/boot/ta6nt/scheme.boot "$inst/csv/" - cp ta6nt/boot/ta6nt/scheme.h "$inst/csv/" - cp ta6nt/boot/ta6nt/equates.h "$inst/csv/" 2>/dev/null || true - cp ta6nt/boot/ta6nt/libkernel.a "$inst/csv/" || { echo "libkernel.a not found:"; find ta6nt -name "*.a" -o -name "kernel*"; exit 1; } - - - name: Put chez on PATH (Windows) - if: runner.os == 'Windows' - run: | - bindir="$GITHUB_WORKSPACE/chez-install/bin" - { echo '#!/bin/sh'; echo "exec \"$bindir/scheme.exe\" \"\$@\""; } > "$bindir/chez" - chmod +x "$bindir/chez" - echo "$bindir" >> "$GITHUB_PATH" - echo "JOLT_CHEZ_CSV=$GITHUB_WORKSPACE/chez-install/csv" >> "$GITHUB_ENV" - # cc is the build's compiler name; alias it to mingw gcc - { echo '#!/bin/sh'; echo 'exec gcc "$@"'; } > "$bindir/cc" - chmod +x "$bindir/cc" - - - name: Show Chez version - run: chez --version - - # build-joltc compiles in a fresh Chez and cc-links; the checked-in seed is - # the compiler image, so no selfhost re-mint (that byte-fixpoint is a - # dev-machine check — see jolt-8479). `make joltc-release`, not `make joltc`. - - name: Build joltc (release) - run: make joltc-release - env: - # Bake the release tag into the binary (build-joltc falls back to - # `git describe` when this is empty, e.g. a workflow_dispatch dry run). - JOLT_VERSION: ${{ startsWith(github.ref, 'refs/tags/') && github.ref_name || '' }} - - - name: Inspect the binary (Windows) - if: runner.os == 'Windows' - run: | - set +e - ls -la target/release/ - ntldd target/release/joltc.exe 2>&1 | head -20 - ./target/release/joltc.exe -e '(+ 1 2)' - echo "exit=$?" - - # Sanity: the built binary runs (no Chez needed) and self-reports a value. - - name: Smoke the binary - run: | - out="$(./target/release/joltc -e '(reduce + (range 10))')" - test "$out" = "45" || { echo "joltc -e gave '$out', want 45"; exit 1; } - - # The binary is a self-contained COMPILER: it must `build` an app with no - # jolt source on disk. Run from an isolated dir (nothing but the tiny app) - # so a build that reaches for host/chez/*.ss on the filesystem fails here, - # not on a user's machine. - - name: Smoke a self-contained build - run: | - joltc="$(pwd)/target/release/joltc" - work="$(mktemp -d)" - mkdir -p "$work/app/src/app" - printf '{:paths ["src"]}\n' > "$work/app/deps.edn" - printf '(ns app.core)\n(defn -main [& _] (println "built:" (reduce + (range 10))))\n' \ - > "$work/app/src/app/core.clj" - ( cd "$work/app" && "$joltc" build -m app.core -o app ) - out="$("$work/app/app")" - test "$out" = "built: 45" || { echo "self-contained build ran '$out', want 'built: 45'"; exit 1; } - - # A built binary must also run the DYNAMIC require path: a namespace not - # in the static ns graph compiles from the source roots at runtime, so the - # boot's top-level defines must be visible to the runtime compiler's eval - # (issue #290: this died with "variable var-deref is not bound"). - - name: Smoke a runtime require in a built binary - run: | - joltc="$(pwd)/target/release/joltc" - work="$(mktemp -d)" - mkdir -p "$work/app/src/app" - printf '{:paths ["src"]}\n' > "$work/app/deps.edn" - printf '(ns app.extra)\n(defn greet [s] (str "Hello, " s "!"))\n' \ - > "$work/app/src/app/extra.clj" - printf '(ns app.core)\n(defn -main [& _]\n (println ((requiring-resolve (quote app.extra/greet)) "runtime")))\n' \ - > "$work/app/src/app/core.clj" - ( cd "$work/app" && "$joltc" build -m app.core -o app ) - out="$(cd "$work/app" && ./app)" - test "$out" = "Hello, runtime!" || { echo "runtime require ran '$out', want 'Hello, runtime!'"; exit 1; } - - - name: Package - run: | - ver="${GITHUB_REF_NAME}" - name="joltc-${ver}-${{ matrix.target }}" - mkdir -p "dist/${name}" - cp README.md LICENSE "dist/${name}/" - if [ "${{ runner.os }}" = "Windows" ]; then - cp target/release/joltc.exe "dist/${name}/joltc.exe" - ( cd dist && zip -r "${name}.zip" "${name}" && sha256sum "${name}.zip" > "${name}.zip.sha256" ) - else - cp target/release/joltc "dist/${name}/joltc" - tar -C dist -czf "dist/${name}.tar.gz" "${name}" - ( cd dist && shasum -a 256 "${name}.tar.gz" > "${name}.tar.gz.sha256" ) - fi - ls -la dist - - - name: Upload to the GitHub Release - if: startsWith(github.ref, 'refs/tags/') - uses: softprops/action-gh-release@v2 - with: - files: | - dist/*.tar.gz - dist/*.tar.gz.sha256 - dist/*.zip - dist/*.zip.sha256 - fail_on_unmatched_files: false diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index a3eff9c..0e712bc 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -1,7 +1,6 @@ name: tests -# Run the gate (make test) on every push and pull request. Chez is the sole -# substrate; the JVM is used only as the conformance oracle (certify). +# Run the full test suite (jpm test) on every push and pull request. on: push: pull_request: @@ -9,65 +8,50 @@ on: jobs: test: runs-on: ubuntu-latest + env: + JANET_VERSION: v1.41.2 # bump to match the version Jolt is developed against + # Per-file deadline for the clojure-test-suite battery. Finite files finish + # in well under 1s; the genuinely-infinite ones get killed at any deadline. + # A generous value gives slow CI runners headroom so a sub-second file + # spiking doesn't time out and drop total-pass below the baseline. + JOLT_SUITE_TIMEOUT: "20" steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@v4 with: - submodules: recursive # vendor/irregex, used by the Chez regex shim + # Submodules: vendor/sci (SCI bootstrap/runtime tests) and + # vendor/clojure-test-suite (the cross-dialect conformance battery, + # asserted against a baseline by clojure-test-suite-test.janet). + submodules: recursive - # Build Chez from source rather than the distro package: the apt - # chezscheme ships petite+scheme only, with no kernel dev files - # (libkernel.a, scheme.h), so `jolt build` (the buildsmoke gate) can't link - # a binary and would skip. The source build provides them, plus the libs the - # kernel links against. - - name: Install build dependencies - run: | - sudo apt-get update - sudo apt-get install -y build-essential git liblz4-dev zlib1g-dev libncurses-dev uuid-dev - - - name: Cache Chez Scheme - id: cache-chez + - name: Cache Janet build + id: cache-janet uses: actions/cache@v4 with: - path: /opt/chez - key: chez-${{ runner.os }}-v10.4.1-x11off + path: /tmp/janet + key: janet-${{ env.JANET_VERSION }}-${{ runner.os }} - - name: Build Chez Scheme from source - if: steps.cache-chez.outputs.cache-hit != 'true' + - name: Build Janet + if: steps.cache-janet.outputs.cache-hit != 'true' run: | - git clone --depth 1 --branch v10.4.1 https://github.com/cisco/ChezScheme.git /tmp/chez-src - cd /tmp/chez-src - # --disable-x11: the expression editor's X11 clipboard isn't needed and - # would pull an X11 build/link dep. - ./configure --installprefix=/opt/chez --threads --disable-x11 - make -j"$(nproc)" - sudo make install - sudo chown -R "$USER" /opt/chez + git clone --depth 1 --branch "$JANET_VERSION" https://github.com/janet-lang/janet.git /tmp/janet + make -C /tmp/janet - - name: Put chez on PATH + - name: Install Janet + run: sudo make -C /tmp/janet install + + - name: Install jpm run: | - # Installed as `scheme`; the gate invokes `chez`. A wrapper that execs - # scheme keeps argv0 so Chez finds its boot files. Placed next to scheme - # so build.ss derives the csv dir (libkernel.a/scheme.h) from it. - printf '#!/bin/sh\nexec /opt/chez/bin/scheme "$@"\n' > /opt/chez/bin/chez - chmod +x /opt/chez/bin/chez - echo '/opt/chez/bin' >> "$GITHUB_PATH" - /opt/chez/bin/chez --version + git clone --depth 1 https://github.com/janet-lang/jpm.git /tmp/jpm + # bootstrap.janet resolves jpm/cli.janet relative to the cwd, so it + # must run from inside the jpm checkout. + cd /tmp/jpm + sudo janet bootstrap.janet - - name: Install JDK + Clojure (certify oracle) - run: | - sudo apt-get install -y default-jdk rlwrap - # --retry + --fail so a transient CDN error retries instead of handing - # bash an HTML error page (a 2min timeout page flaked a run) - curl --fail --retry 5 --retry-delay 10 --retry-all-errors -L -O \ - https://github.com/clojure/brew-install/releases/latest/download/linux-install.sh - head -1 linux-install.sh | grep -q '^#!' || { echo "installer download corrupt"; cat linux-install.sh | head -5; exit 1; } - sudo bash linux-install.sh - clojure --version + - name: Janet version + run: janet -v - - name: Gate - # `make ci` runs the behavior gates (corpus/unit/smoke/buildsmoke/sci/ - # certify). buildsmoke now links a real binary (the source-built Chez has - # the kernel dev files). The self-host byte-fixpoint (make selfhost) is a - # dev-machine check — it only holds on the Chez that minted the seed. See - # jolt-8479. - run: make ci + - name: Build executable + run: jpm build + + - name: Run tests + run: jpm test diff --git a/.gitignore b/.gitignore index ab386cf..4b76022 100644 --- a/.gitignore +++ b/.gitignore @@ -1,8 +1,4 @@ -AGENTS.md -.DS_Store -CLAUDE.md build/ -target/ .clj-kondo/ .dirge/ .claude/ diff --git a/.gitmodules b/.gitmodules index e2374ec..959062d 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,6 +1,3 @@ -[submodule "vendor/irregex"] - path = vendor/irregex - url = https://github.com/ashinn/irregex.git [submodule "vendor/sci"] path = vendor/sci url = https://github.com/borkdude/sci.git diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..bc2ae10 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,96 @@ +# Agent Instructions + +This project uses **bd** (beads) for issue tracking. Run `bd prime` for full workflow context. + +> **Architecture in one line:** Issues live in a local Dolt database +> (`.beads/dolt/`); cross-machine sync uses `bd dolt push/pull` (a +> git-compatible protocol), stored under `refs/dolt/data` on your git +> remote — separate from `refs/heads/*` where your code lives. +> `.beads/issues.jsonl` is a passive export, not the wire protocol. +> +> See [SYNC_CONCEPTS.md](https://github.com/gastownhall/beads/blob/main/docs/SYNC_CONCEPTS.md) +> for the one-screen overview and anti-patterns (don't treat JSONL as the +> source of truth; don't `bd import` during normal operation; don't +> reach for third-party Dolt hosting before trying the default). + +## Quick Reference + +```bash +bd ready # Find available work +bd show # View issue details +bd update --claim # Claim work atomically +bd close # Complete work +bd dolt push # Push beads data to remote +``` + +## Non-Interactive Shell Commands + +**ALWAYS use non-interactive flags** with file operations to avoid hanging on confirmation prompts. + +Shell commands like `cp`, `mv`, and `rm` may be aliased to include `-i` (interactive) mode on some systems, causing the agent to hang indefinitely waiting for y/n input. + +**Use these forms instead:** +```bash +# Force overwrite without prompting +cp -f source dest # NOT: cp source dest +mv -f source dest # NOT: mv source dest +rm -f file # NOT: rm file + +# For recursive operations +rm -rf directory # NOT: rm -r directory +cp -rf source dest # NOT: cp -r source dest +``` + +**Other commands that may prompt:** +- `scp` - use `-o BatchMode=yes` for non-interactive +- `ssh` - use `-o BatchMode=yes` to fail instead of prompting +- `apt-get` - use `-y` flag +- `brew` - use `HOMEBREW_NO_AUTO_UPDATE=1` env var + + +## Beads Issue Tracker + +This project uses **bd (beads)** for issue tracking. Run `bd prime` to see full workflow context and commands. + +### Quick Reference + +```bash +bd ready # Find available work +bd show # View issue details +bd update --claim # Claim work +bd close # Complete work +``` + +### Rules + +- Use `bd` for ALL task tracking — do NOT use TodoWrite, TaskCreate, or markdown TODO lists +- Run `bd prime` for detailed command reference and session close protocol +- Use `bd remember` for persistent knowledge — do NOT use MEMORY.md files + +**Architecture in one line:** issues live in a local Dolt DB; sync uses `refs/dolt/data` on your git remote; `.beads/issues.jsonl` is a passive export. See https://github.com/gastownhall/beads/blob/main/docs/SYNC_CONCEPTS.md for details and anti-patterns. + +## Session Completion + +**When ending a work session**, you MUST complete ALL steps below. Work is NOT complete until `git push` succeeds. + +**MANDATORY WORKFLOW:** + +1. **File issues for remaining work** - Create issues for anything that needs follow-up +2. **Run quality gates** (if code changed) - Tests, linters, builds +3. **Update issue status** - Close finished work, update in-progress items +4. **PUSH TO REMOTE** - This is MANDATORY: + ```bash + git pull --rebase + git push + git status # MUST show "up to date with origin" + ``` +5. **Clean up** - Clear stashes, prune remote branches +6. **Verify** - All changes committed AND pushed +7. **Hand off** - Provide context for next session + +**CRITICAL RULES:** +- Work is NOT complete until `git push` succeeds +- NEVER stop before pushing - that leaves work stranded locally +- NEVER say "ready to push when you are" - YOU must push +- If push fails, resolve and retry until it succeeds + diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..cd553b9 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,70 @@ +# Project Instructions for AI Agents + +This file provides instructions and context for AI coding agents working on this project. + + +## Beads Issue Tracker + +This project uses **bd (beads)** for issue tracking. Run `bd prime` to see full workflow context and commands. + +### Quick Reference + +```bash +bd ready # Find available work +bd show # View issue details +bd update --claim # Claim work +bd close # Complete work +``` + +### Rules + +- Use `bd` for ALL task tracking — do NOT use TodoWrite, TaskCreate, or markdown TODO lists +- Run `bd prime` for detailed command reference and session close protocol +- Use `bd remember` for persistent knowledge — do NOT use MEMORY.md files + +**Architecture in one line:** issues live in a local Dolt DB; sync uses `refs/dolt/data` on your git remote; `.beads/issues.jsonl` is a passive export. See https://github.com/gastownhall/beads/blob/main/docs/SYNC_CONCEPTS.md for details and anti-patterns. + +## Session Completion + +**When ending a work session**, you MUST complete ALL steps below. Work is NOT complete until `git push` succeeds. + +**MANDATORY WORKFLOW:** + +1. **File issues for remaining work** - Create issues for anything that needs follow-up +2. **Run quality gates** (if code changed) - Tests, linters, builds +3. **Update issue status** - Close finished work, update in-progress items +4. **PUSH TO REMOTE** - This is MANDATORY: + ```bash + git pull --rebase + git push + git status # MUST show "up to date with origin" + ``` +5. **Clean up** - Clear stashes, prune remote branches +6. **Verify** - All changes committed AND pushed +7. **Hand off** - Provide context for next session + +**CRITICAL RULES:** +- Work is NOT complete until `git push` succeeds +- NEVER stop before pushing - that leaves work stranded locally +- NEVER say "ready to push when you are" - YOU must push +- If push fails, resolve and retry until it succeeds + + + +## Build & Test + +_Add your build and test commands here_ + +```bash +# Example: +# npm install +# npm test +``` + +## Architecture Overview + +_Add a brief overview of your project architecture_ + +## Conventions & Patterns + +_Add your project-specific conventions here_ diff --git a/LICENSE b/LICENSE index e48e096..4a729a7 100644 --- a/LICENSE +++ b/LICENSE @@ -1,179 +1,143 @@ -Eclipse Public License - v 2.0 +Eclipse Public License - v 1.0 - THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE - PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION - OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. +THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE +PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF +THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. 1. DEFINITIONS "Contribution" means: - a) in the case of the initial Contributor, the initial content - Distributed under this Agreement, and +a) in the case of the initial Contributor, the initial code and +documentation distributed under this Agreement, and - b) in the case of each subsequent Contributor: - i) changes to the Program, and - ii) additions to the Program; - where such changes and/or additions to the Program originate from - and are Distributed by that particular Contributor. A Contribution - "originates" from a Contributor if it was added to the Program by - such Contributor itself or anyone acting on such Contributor's behalf. - Contributions do not include changes or additions to the Program that - are not Modified Works. +b) in the case of each subsequent Contributor: -"Contributor" means any person or entity that Distributes the Program. +i) changes to the Program, and + +ii) additions to the Program; + +where such changes and/or additions to the Program originate from and +are distributed by that particular Contributor. A Contribution +'originates' from a Contributor if it was added to the Program by such +Contributor itself or anyone acting on such Contributor's behalf. +Contributions do not include additions to the Program which: (i) are +separate modules of software distributed in conjunction with the Program +under their own license agreement, and (ii) are not derivative works of +the Program. + +"Contributor" means any person or entity that distributes the Program. "Licensed Patents" mean patent claims licensable by a Contributor which are necessarily infringed by the use or sale of its Contribution alone or when combined with the Program. -"Program" means the Contributions Distributed in accordance with this +"Program" means the Contributions distributed in accordance with this Agreement. -"Recipient" means anyone who receives the Program under this Agreement -or any Secondary License (as applicable), including Contributors. - -"Derivative Works" shall mean any work, whether in Source Code or other -form, that is based on (or derived from) the Program and for which the -editorial revisions, annotations, elaborations, or other modifications -represent, as a whole, an original work of authorship. - -"Modified Works" shall mean any work in Source Code or other form that -results from an addition to, deletion from, or modification of the -contents of the Program, including, for purposes of clarity any new file -in Source Code form that contains any contents of the Program. Modified -Works shall not include works that contain only declarations, -interfaces, types, classes, structures, or files of the Program solely -in each case in order to link to, bind by name, or subclass the Program -or Modified Works thereof. - -"Distribute" means the acts of a) distributing or b) making available -in any manner that enables the transfer of a copy. - -"Source Code" means the form of a Program preferred for making -modifications, including but not limited to software source code, -documentation source, and configuration files. - -"Secondary License" means either the GNU General Public License, -Version 2.0, or any later versions of that license, including any -exceptions or additional permissions as identified by the initial -Contributor. +"Recipient" means anyone who receives the Program under this Agreement, +including all Contributors. 2. GRANT OF RIGHTS - a) Subject to the terms of this Agreement, each Contributor hereby - grants Recipient a non-exclusive, worldwide, royalty-free copyright - license to reproduce, prepare Derivative Works of, publicly display, - publicly perform, Distribute and sublicense the Contribution of such - Contributor, if any, and such Derivative Works. +a) Subject to the terms of this Agreement, each Contributor hereby +grants Recipient a non-exclusive, worldwide, royalty-free copyright +license to reproduce, prepare derivative works of, publicly display, +publicly perform, distribute and sublicense the Contribution of such +Contributor, if any, and such derivative works, in source code and +object code form. - b) Subject to the terms of this Agreement, each Contributor hereby - grants Recipient a non-exclusive, worldwide, royalty-free patent - license under Licensed Patents to make, use, sell, offer to sell, - import and otherwise transfer the Contribution of such Contributor, - if any, in Source Code or other form. This patent license shall - apply to the combination of the Contribution and the Program if, at - the time the Contribution is added by the Contributor, such addition - of the Contribution causes such combination to be covered by the - Licensed Patents. The patent license shall not apply to any other - combinations which include the Contribution. No hardware per se is - licensed hereunder. +b) Subject to the terms of this Agreement, each Contributor hereby +grants Recipient a non-exclusive, worldwide, royalty-free patent license +under Licensed Patents to make, use, sell, offer to sell, import and +otherwise transfer the Contribution of such Contributor, if any, in +source code and object code form. This patent license shall apply to the +combination of the Contribution and the Program if, at the time the +Contribution is added by the Contributor, such addition of the +Contribution causes such combination to be covered by the Licensed +Patents. The patent license shall not apply to any other combinations +which include the Contribution. No hardware per se is licensed +hereunder. - c) Recipient understands that although each Contributor grants the - licenses to its Contributions set forth herein, no assurances are - provided by any Contributor that the Program does not infringe the - patent or other intellectual property rights of any other entity. - Each Contributor disclaims any liability to Recipient for claims - brought by any other entity based on infringement of intellectual - property rights or otherwise. As a condition to exercising the - rights and licenses granted hereunder, each Recipient hereby - assumes sole responsibility to secure any other intellectual - property rights needed, if any. For example, if a third party - patent license is required to allow Recipient to Distribute the - Program, it is Recipient's responsibility to acquire that license - before distributing the Program. +c) Recipient understands that although each Contributor grants the +licenses to its Contributions set forth herein, no assurances are +provided by any Contributor that the Program does not infringe the +patent or other intellectual property rights of any other entity. Each +Contributor disclaims any liability to Recipient for claims brought by +any other entity based on infringement of intellectual property rights +or otherwise. As a condition to exercising the rights and licenses +granted hereunder, each Recipient hereby assumes sole responsibility to +secure any other intellectual property rights needed, if any. For +example, if a third party patent license is required to allow Recipient +to distribute the Program, it is Recipient's responsibility to acquire +that license before distributing the Program. - d) Each Contributor represents that to its knowledge it has - sufficient copyright rights in its Contribution, if any, to grant - the copyright license set forth in this Agreement. - - e) Notwithstanding the terms of any Secondary License, no - Contributor makes additional grants to any Recipient (other than - those set forth in this Agreement) as a result of such Recipient's - receipt of the Program under the terms of a Secondary License - (if permitted under the terms of Section 3). +d) Each Contributor represents that to its knowledge it has sufficient +copyright rights in its Contribution, if any, to grant the copyright +license set forth in this Agreement. 3. REQUIREMENTS -3.1 If a Contributor Distributes the Program in any form, then: +A Contributor may choose to distribute the Program in object code form +under its own license agreement, provided that: - a) the Program must also be made available as Source Code, in - accordance with section 3.2, and the Contributor must accompany - the Program with a statement that the Source Code for the Program - is available under this Agreement, and informs Recipients how to - obtain it in a reasonable manner on or through a medium customarily - used for software exchange; and +a) it complies with the terms and conditions of this Agreement; and - b) the Contributor may Distribute the Program under a license - different than this Agreement, provided that such license: - i) effectively disclaims on behalf of all other Contributors all - warranties and conditions, express and implied, including - warranties or conditions of title and non-infringement, and - implied warranties or conditions of merchantability and fitness - for a particular purpose; +b) its license agreement: - ii) effectively excludes on behalf of all other Contributors all - liability for damages, including direct, indirect, special, - incidental and consequential damages, such as lost profits; +i) effectively disclaims on behalf of all Contributors all warranties +and conditions, express and implied, including warranties or conditions +of title and non-infringement, and implied warranties or conditions of +merchantability and fitness for a particular purpose; - iii) does not attempt to limit or alter the recipients' rights - in the Source Code under section 3.2; and +ii) effectively excludes on behalf of all Contributors all liability for +damages, including direct, indirect, special, incidental and +consequential damages, such as lost profits; - iv) requires any subsequent distribution of the Program by any - party to be under a license that satisfies the requirements - of this section 3. +iii) states that any provisions which differ from this Agreement are +offered by that Contributor alone and not by any other party; and -3.2 When the Program is Distributed as Source Code: +iv) states that source code for the Program is available from such +Contributor, and informs licensees how to obtain it in a reasonable +manner on or through a medium customarily used for software exchange. - a) it must be made available under this Agreement, or if the - Program (i) is combined with other material in a separate file or - files made available under a Secondary License, and (ii) the initial - Contributor attached to the Source Code the notice described in - Exhibit A of this Agreement, then the Program may be made available - under the terms of such Secondary Licenses, and +When the Program is made available in source code form: - b) a copy of this Agreement must be included with each copy of - the Program. +a) it must be made available under this Agreement; and -3.3 Contributors may not remove or alter any copyright, patent, -trademark, attribution notices, disclaimers of warranty, or limitations -of liability ("notices") contained within the Program from any copy of -the Program which they Distribute, provided that Contributors may add -their own appropriate notices. +b) a copy of this Agreement must be included with each copy of the +Program. + +Contributors may not remove or alter any copyright notices contained +within the Program. + +Each Contributor must identify itself as the originator of its +Contribution, if any, in a manner that reasonably allows subsequent +Recipients to identify the originator of the Contribution. 4. COMMERCIAL DISTRIBUTION Commercial distributors of software may accept certain responsibilities with respect to end users, business partners and the like. While this -license is intended to facilitate the commercial use of the Program, -the Contributor who includes the Program in a commercial product -offering should do so in a manner which does not create potential -liability for other Contributors. Therefore, if a Contributor includes -the Program in a commercial product offering, such Contributor -("Commercial Contributor") hereby agrees to defend and indemnify every -other Contributor ("Indemnified Contributor") against any losses, -damages and costs (collectively "Losses") arising from claims, lawsuits -and other legal actions brought by a third party against the Indemnified +license is intended to facilitate the commercial use of the Program, the +Contributor who includes the Program in a commercial product offering +should do so in a manner which does not create potential liability for +other Contributors. Therefore, if a Contributor includes the Program in +a commercial product offering, such Contributor ("Commercial +Contributor") hereby agrees to defend and indemnify every other +Contributor ("Indemnified Contributor") against any losses, damages and +costs (collectively "Losses") arising from claims, lawsuits and other +legal actions brought by a third party against the Indemnified Contributor to the extent caused by the acts or omissions of such -Commercial Contributor in connection with its distribution of the Program -in a commercial product offering. The obligations in this section do not -apply to any claims or Losses relating to any actual or alleged -intellectual property infringement. In order to qualify, an Indemnified -Contributor must: a) promptly notify the Commercial Contributor in -writing of such claim, and b) allow the Commercial Contributor to control, -and cooperate with the Commercial Contributor in, the defense and any -related settlement negotiations. The Indemnified Contributor may -participate in any such claim at its own expense. +Commercial Contributor in connection with its distribution of the +Program in a commercial product offering. The obligations in this +section do not apply to any claims or Losses relating to any actual or +alleged intellectual property infringement. In order to qualify, an +Indemnified Contributor must: a) promptly notify the Commercial +Contributor in writing of such claim, and b) allow the Commercial +Contributor to control, and cooperate with the Commercial Contributor +in, the defense and any related settlement negotiations. The Indemnified +Contributor may participate in any such claim at its own expense. For example, a Contributor might include the Program in a commercial product offering, Product X. That Contributor is then a Commercial @@ -181,97 +145,80 @@ Contributor. If that Commercial Contributor then makes performance claims, or offers warranties related to Product X, those performance claims and warranties are such Commercial Contributor's responsibility alone. Under this section, the Commercial Contributor would have to -defend claims against the other Contributors related to those performance -claims and warranties, and if a court requires any other Contributor to -pay any damages as a result, the Commercial Contributor must pay -those damages. +defend claims against the other Contributors related to those +performance claims and warranties, and if a court requires any other +Contributor to pay any damages as a result, the Commercial Contributor +must pay those damages. 5. NO WARRANTY -EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, AND TO THE EXTENT -PERMITTED BY APPLICABLE LAW, THE PROGRAM IS PROVIDED ON AN "AS IS" -BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR -IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF -TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR -PURPOSE. Each Recipient is solely responsible for determining the -appropriateness of using and distributing the Program and assumes all -risks associated with its exercise of rights under this Agreement, -including but not limited to the risks and costs of program errors, -compliance with applicable laws, damage to or loss of data, programs -or equipment, and unavailability or interruption of operations. +EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED +ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, +EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES +OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR +A PARTICULAR PURPOSE. Each Recipient is solely responsible for +determining the appropriateness of using and distributing the Program +and assumes all risks associated with its exercise of rights under this +Agreement, including but not limited to the risks and costs of program +errors, compliance with applicable laws, damage to or loss of data, +programs or equipment, and unavailability or interruption of operations. 6. DISCLAIMER OF LIABILITY -EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, AND TO THE EXTENT -PERMITTED BY APPLICABLE LAW, NEITHER RECIPIENT NOR ANY CONTRIBUTORS -SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST -PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE -EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE -POSSIBILITY OF SUCH DAMAGES. +EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR +ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING +WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR +DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED +HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 7. GENERAL If any provision of this Agreement is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of -the remainder of the terms of this Agreement, and without further -action by the parties hereto, such provision shall be reformed to the -minimum extent necessary to make such provision valid and enforceable. +the remainder of the terms of this Agreement, and without further action +by the parties hereto, such provision shall be reformed to the minimum +extent necessary to make such provision valid and enforceable. -If Recipient institutes patent litigation against any entity -(including a cross-claim or counterclaim in a lawsuit) alleging that the -Program itself (excluding combinations of the Program with other software -or hardware) infringes such Recipient's patent(s), then such Recipient's +If Recipient institutes patent litigation against any entity (including +a cross-claim or counterclaim in a lawsuit) alleging that the Program +itself (excluding combinations of the Program with other software or +hardware) infringes such Recipient's patent(s), then such Recipient's rights granted under Section 2(b) shall terminate as of the date such litigation is filed. -All Recipient's rights under this Agreement shall terminate if it -fails to comply with any of the material terms or conditions of this -Agreement and does not cure such failure in a reasonable period of -time after becoming aware of such noncompliance. If all Recipient's -rights under this Agreement terminate, Recipient agrees to cease use -and distribution of the Program as soon as reasonably practicable. -However, Recipient's obligations under this Agreement and any licenses -granted by Recipient relating to the Program shall continue and survive. +All Recipient's rights under this Agreement shall terminate if it fails +to comply with any of the material terms or conditions of this Agreement +and does not cure such failure in a reasonable period of time after +becoming aware of such noncompliance. If all Recipient's rights under +this Agreement terminate, Recipient agrees to cease use and distribution +of the Program as soon as reasonably practicable. However, Recipient's +obligations under this Agreement and any licenses granted by Recipient +relating to the Program shall continue and survive. Everyone is permitted to copy and distribute copies of this Agreement, -but in order to avoid inconsistency the Agreement is copyrighted and -may only be modified in the following manner. The Agreement Steward -reserves the right to publish new versions (including revisions) of -this Agreement from time to time. No one other than the Agreement -Steward has the right to modify this Agreement. The Eclipse Foundation -is the initial Agreement Steward. The Eclipse Foundation may assign the +but in order to avoid inconsistency the Agreement is copyrighted and may +only be modified in the following manner. The Agreement Steward reserves +the right to publish new versions (including revisions) of this +Agreement from time to time. No one other than the Agreement Steward has +the right to modify this Agreement. The Eclipse Foundation is the +initial Agreement Steward. The Eclipse Foundation may assign the responsibility to serve as the Agreement Steward to a suitable separate entity. Each new version of the Agreement will be given a distinguishing version number. The Program (including Contributions) may always be -Distributed subject to the version of the Agreement under which it was -received. In addition, after a new version of the Agreement is published, -Contributor may elect to Distribute the Program (including its -Contributions) under the new version. +distributed subject to the version of the Agreement under which it was +received. In addition, after a new version of the Agreement is +published, Contributor may elect to distribute the Program (including +its Contributions) under the new version. Except as expressly stated in +Sections 2(a) and 2(b) above, Recipient receives no rights or licenses +to the intellectual property of any Contributor under this Agreement, +whether expressly, by implication, estoppel or otherwise. All rights in +the Program not expressly granted under this Agreement are reserved. -Except as expressly stated in Sections 2(a) and 2(b) above, Recipient -receives no rights or licenses to the intellectual property of any -Contributor under this Agreement, whether expressly, by implication, -estoppel or otherwise. All rights in the Program not expressly granted -under this Agreement are reserved. Nothing in this Agreement is intended -to be enforceable by any entity that is not a Contributor or Recipient. -No third-party beneficiary rights are created under this Agreement. - -Exhibit A - Form of Secondary Licenses Notice - -"This Source Code may also be made available under the following -Secondary Licenses when the conditions for such availability set forth -in the Eclipse Public License, v. 2.0 are satisfied: {name license(s), -version(s), and exceptions or additional permissions here}." - - Simply including a copy of this Agreement, including this Exhibit A - is not sufficient to license the Source Code under Secondary Licenses. - - If it is not possible or desirable to put the notice in a particular - file, then You may include the notice in a location (such as a LICENSE - file in a relevant directory) where a recipient would be likely to - look for such a notice. - - You may add additional accurate notices of copyright ownership. +This Agreement is governed by the laws of the State of New York and the +intellectual property laws of the United States of America. No party to +this Agreement will bring a legal action under this Agreement more than +one year after the cause of action arose. Each party waives its rights +to a jury trial in any resulting litigation. diff --git a/Makefile b/Makefile deleted file mode 100644 index 5d87481..0000000 --- a/Makefile +++ /dev/null @@ -1,172 +0,0 @@ -# jolt — Clojure on Chez Scheme. Single substrate, no Janet. -# -# bin/joltc runs jolt directly off the checked-in seed (host/chez/seed/); there is no -# build step. `make test` is the full gate. `make remint` rebuilds the seed after a -# source change. - -.PHONY: test ci values corpus unit smoke buildsmoke staticnativesmoke selfhost sci cts certify ffi transient infer wp devirt fieldread numwp fieldnum protoret narrow directlink numeric inline shakesmoke remint joltc joltc-release joltc-debug joltcsmoke submodules - -# Every target needs the vendored submodules; fail with the fix, not a load error. -submodules: - @test -f vendor/irregex/irregex.scm || { \ - echo "vendor submodules missing; run: git submodule update --init --recursive"; exit 1; } - -# Full gate (dev machine). Includes the self-host byte-fixpoint, which only holds -# on the same Chez that minted the seed. -test: submodules selfhost ci - @echo "OK: all gates passed" - -# CI gate: behavior only. The checked-in seed is a minted artifact (like a -# lockfile) — it RUNS correctly on any Chez, but `selfhost` rebuilds it and a -# different Chez version may emit byte-different (gensym/order) output, so the -# byte-fixpoint is a dev-machine check, not a CI one (jolt-8479). -ci: submodules values corpus unit smoke buildsmoke staticnativesmoke sci cts ffi transient infer wp devirt fieldread numwp fieldnum protoret narrow directlink numeric inline certify - @echo "OK: CI gates passed" - -# Self-host fixpoint: bootstrap.ss rebuild == checked-in seed. -selfhost: - @sh host/chez/selfcheck.sh - -# Value-model unit tests (nil/truthiness/collections on Chez). -values: - @chez --script test/chez/values-test.ss - -# Corpus conformance vs JVM-sourced expecteds (allowlist + floor). -corpus: - @chez --script host/chez/run-corpus.ss - -# Host-specific unit cases. -unit: - @chez --script host/chez/run-unit.ss - -# Real-CLI smoke over bin/joltc. -smoke: - @sh host/chez/smoke.sh - -# `jolt build` produces a working standalone binary. -buildsmoke: - @sh host/chez/build-smoke.sh - -# `jolt build` cc-links a :jolt/native :static archive into the binary (the -# default), and --dynamic keeps the runtime load-shared-object path. -staticnativesmoke: - @sh host/chez/static-native-smoke.sh - -# Build joltc as a self-contained native binary into target//joltc. The -# binary bundles the runtime, compiler, jolt-core + stdlib source, the Chez boots, -# and a launcher stub, so it runs AND compiles jolt apps with no Chez or cc on the -# machine. Built on a dev/CI host that HAS Chez + cc. release = optimize-level 3, -# no inspector info, compressed; debug = optimize-level 0 + inspector + debug info. -joltc-release: - @chez --script host/chez/build-joltc.ss release target/release/joltc -joltc-debug: - @chez --script host/chez/build-joltc.ss debug target/debug/joltc -# Re-mint the seed first so the embedded compiler image is current, then both builds. -joltc: selfhost joltc-release joltc-debug - @echo "OK: target/release/joltc and target/debug/joltc built" - -# Self-build smoke: the distributed joltc compiles an app with Chez + cc removed. -joltcsmoke: - @sh host/chez/joltc-selfbuild-smoke.sh - -# SCI conformance: load borkdude/sci's source through joltc (floor-gated). -sci: - @chez --script host/chez/run-sci.ss - -# clojure-test-suite conformance: run the vendored jank-lang/clojure-test-suite -# per-namespace under joltc, gated on the per-namespace baseline -# (test/chez/cts-known-failures.txt). -cts: - @bash host/chez/cts.sh - -# FFI: bind native functions (typed foreign-procedure), memory, and that a -# :blocking call is collect-safe (a parked thread doesn't pin the collector). -ffi: - @chez --script test/chez/ffi-binding-test.ss - -# Transients: mutable backing, snapshot on persistent!, and linear-time builds. -transient: - @chez --script test/chez/transient-test.ss - -# Inference / success-type checking: drive jolt.passes.types directly and assert -# diagnostic counts + collected calls/escapes (the optimization pass the other -# gates don't exercise). -infer: - @chez --script host/chez/run-infer.ss - -# Whole-program param-type fixpoint: record types flowing across fn boundaries -# (a callee's param picks up its callers' ctor return types), the foundation the -# bare-index field reads + protocol devirtualization build on. -wp: - @chez --script host/chez/run-wp.ss - -# Protocol-call devirtualization: a monomorphic call resolves its impl by the -# inferred record tag (find-protocol-method) instead of routing through the -# protocol var; the result must match ordinary dispatch. -devirt: - @chez --script host/chez/run-devirt.ss - -# Native record field reads: a keyword lookup on a statically-known record reads -# the field by its declared slot (jrec-field-at) instead of jolt-get; the value -# must match, and a non-field key / default-arg form keeps the generic path. -fieldread: - @chez --script host/chez/run-fieldread.ss - -# Hintless whole-program double inference: a fn whose every call site passes a -# flonum has its param typed :double by the closed-world fixpoint and unboxed to -# fl-ops with no ^double hint; an integer caller leaves it generic, an escaped fn -# keeps :any. -numwp: - @chez --script host/chez/run-numwp.ss - -# Double record fields: a ^double-tagged field reads back as a flonum (coerced at -# construction and set!), so hintless arithmetic over those fields unboxes to fl-ops; -# an untagged field stays generic. -fieldnum: - @chez --script host/chez/run-fieldnum.ss - -# Protocol-method return inference: a method whose impls all return the same record -# type has a monomorphic return, so a (method recv ..) call types as that record and -# a field read off the result bare-indexes; a disagreeing impl keeps the generic path. -protoret: - @chez --script host/chez/run-protoret.ss - -# Nilable record types + flow-sensitive narrowing: a record-or-nil types as a nilable -# record (some?/nil? don't fold, so a runtime guard stays); inside (if (some? x) ..) -# the then-branch narrows x to non-nil, so its field reads bare-index and unbox. -narrow: - @chez --script host/chez/run-narrow.ss - -# Direct-linking emission: a closed-world build binds top-level app defs to jv$ -# Scheme bindings and routes app->app calls/refs to them, skipping var-deref + -# jolt-invoke; ^:dynamic/^:redef and nested defs opt out. -directlink: - @chez --script test/chez/directlink-test.ss - -# Hint-directed fast arithmetic: ^double/^long param hints (and float literals) -# lower arithmetic to Chez fl*/fx* ops; un-hinted integer code stays generic. -numeric: - @chez --script test/chez/numeric-test.ss - -# IR inlining: a small single-arity defn is spliced at call sites (under optimize), -# with ^double/^long entry/return coercions carried through via :coerce nodes. -inline: - @chez --script test/chez/inline-test.ss - -# Tree-shake soundness: build example apps (incl. deps.edn git-lib apps) default vs -# --tree-shake and require identical output. Slow (two builds per app); not in the -# default gate. Skips without the examples repo / Chez kernel dev files. -shakesmoke: - @sh host/chez/tree-shake-smoke.sh - -# JVM oracle: certify the corpus against reference Clojure. Skips if clojure absent. -certify: - @if command -v clojure >/dev/null 2>&1; then \ - clojure -M test/conformance/certify.clj; \ - else \ - echo "certify: clojure not on PATH — skipped"; \ - fi - -# Re-mint the seed after changing a seed source (reader/analyzer/backend/core). -remint: - @sh host/chez/remint.sh diff --git a/README.md b/README.md index 16c1f50..22e1d32 100644 --- a/README.md +++ b/README.md @@ -2,233 +2,255 @@ [![tests](https://github.com/jolt-lang/jolt/actions/workflows/tests.yml/badge.svg)](https://github.com/jolt-lang/jolt/actions/workflows/tests.yml) -A Clojure implementation on [Chez Scheme](https://cisco.github.io/ChezScheme/). -Jolt reads Clojure source, analyzes it to a host-neutral IR, emits Scheme, and -runs it on Chez. The compiler is self-hosted: it is written in Clojure -(`jolt-core/`) and compiles itself. It ships a Clojure-compatible standard library. - -## Install - -Grab the self-contained `joltc` binary (Linux/macOS/Windows) — it bundles the -runtime, compiler, and standard library, so there is nothing else to install. -Download the binary archive for your platform from the -[releases page](https://github.com/jolt-lang/jolt/releases) (`joltc--.tar.gz`, -or the `.zip` on Windows). The "Source code" archives GitHub attaches to every -release are not binaries — see [Build](#build) before using one. - -With Homebrew: - -```bash -brew install jolt-lang/jolt/jolt -``` - -Or with the install script (installs to `/usr/local/bin` by default; `--dir ` -and `--version ` override that): - -```bash -curl -sL https://raw.githubusercontent.com/jolt-lang/jolt/main/install | bash -``` - -Then `joltc -e '(+ 1 2)'`. To run from source instead (needs Chez), see -[Build](#build). - -## Requirements - -Only [Chez Scheme](https://cisco.github.io/ChezScheme/) (the gate invokes it as -`chez`). The conformance gate additionally uses Clojure on the JVM as an oracle, -but running jolt does not. +A Clojure implementation on top of [Janet](https://janet-lang.org). Jolt reads Clojure source and, by default, compiles each form to native Janet bytecode — falling back to a tree-walking interpreter for forms the compiler doesn't handle, so results always match the interpreter. It ships a Clojure-compatible standard library. The goal is a Janet-hosted [SCI](https://github.com/borkdude/sci)-style runtime with a minimal bootstrap. ## Build -There is no build step. The bootstrap seed (`host/chez/seed/{prelude,image}.ss`) -is checked in, so a fresh clone runs immediately: - ```bash -git clone --recurse-submodules https://github.com/jolt-lang/jolt.git +git clone https://github.com/jolt-lang/jolt.git cd jolt -bin/joltc -e '(+ 1 2)' # => 3 +git submodule update --init # pulls vendor/sci and vendor/clojure-test-suite +jpm build # builds build/jolt and build/jolt-deps ``` -The `--recurse-submodules` matters: jolt vendors its regex engine and test -suites as git submodules. In a checkout that's missing them (a plain -`git clone`, or after pulling a commit that adds one), fetch them with: - -```bash -git submodule update --init --recursive -``` - -Note that GitHub's auto-generated "Source code (zip/tar.gz)" archives on the -releases page do **not** contain submodules, so they can't run or build — -clone the repo instead (or grab a prebuilt binary from the same page). - -After changing a compiler source — the reader (`host/chez/reader.ss`), the -analyzer/IR/backend (`jolt-core/jolt/*.clj`), or the `clojure.core` overlay -(`jolt-core/clojure/core/*.clj`) — re-mint the seed: - -```bash -make remint # iterates host/chez/bootstrap.ss to a byte-fixpoint -``` +Requires `jpm` and a recent Janet (CI-tested against 1.41). See +[doc/building-and-deps.md](doc/building-and-deps.md) for build details, the +`jpm clean` caveat, how namespaces are resolved (`JOLT_PATH`), and pulling +Clojure libraries from a `deps.edn` with the `jolt-deps` tool. ## Run -```bash -bin/joltc -e EXPR # evaluate a Clojure expression and print the result +``` +build/jolt # start a REPL +build/jolt file.clj [args] # run a file (binds *command-line-args* and *file*) +build/jolt -e EXPR [args] # evaluate EXPR and print the result +build/jolt -m NS [args] # require NS and call its -main +build/jolt nrepl-server [addr] # start an nREPL server ([host:]port, default 7888) +build/jolt --version # print the version +build/jolt -h | --help # help ``` -```bash -$ bin/joltc -e '(->> (range 10) (filter even?) (map (fn [x] (* x x))) (reduce +))' -120 -$ bin/joltc -e '(/ 1 2)' -1/2 +The REPL accumulates multi-line forms until they balance: + +``` +user=> (defn fib [n] (if (< n 2) n (+ (fib (- n 1)) (fib (- n 2))))) +#'user/fib +user=> (map fib (range 10)) +(0 1 1 2 3 5 8 13 21 34) ``` -## REPL and editor integration +Running a file evaluates its top-level forms: -```bash -bin/joltc repl # a line REPL with the project's deps loaded -bin/joltc --nrepl-server [port] # an nREPL server (default 7888) for editors +``` +$ echo '(println "hello" (* 6 7))' > hello.clj +$ build/jolt hello.clj +hello 42 ``` -Both resolve the `deps.edn` in the current directory first, so the project's -source roots and native libraries are loaded — `(require '[my.ns])` works live. -`--nrepl-server` writes a `.nrepl-port` file in the project dir, so CIDER / Calva / Cursive -auto-detect the port; override it with the argument or `JOLT_NREPL_PORT`. +## Use as a library -The server runs in dev mode — calls deref their var, so redefining a function -takes effect on the next call without restarting the process. The built-in -handler speaks `clone`/`describe`/`eval`/`load-file`/`close`; heavier ops -(sessions, interruptible eval, completion) are added as nREPL middleware listed -in `deps.edn` under `:nrepl/middleware`. +```janet +(use jolt/api) + +(def ctx (init)) +(eval-string ctx "(+ 1 2)") # → 3 +(eval-string ctx "(map inc [1 2 3])") # → (2 3 4) ; a lazy seq, like Clojure +``` + +`(init)` returns a context with `clojure.core` loaded. Each context is isolated; use separate contexts for separate environments. + +### Evaluation pipeline: interpreted and compiled + +Every form passes through one router (`loader/eval-toplevel`) that decides *per +form* whether to tree-walk it or compile it to Janet bytecode. The shipped +runtime **compiles by default**; set `JOLT_INTERPRET=1` to force the interpreter. + +**Hybrid, always correct.** The compiler is incomplete by design: a form it can't +compile correctly throws `jolt/uncompilable`, and the router falls back to the +tree-walking interpreter (`eval-form`) for that form. So the result *always* +matches the interpreter — compilation is a transparent speedup, never a semantic +change. Only the compile step is guarded; runtime errors in compiled code +propagate normally (no double-evaluation, no hidden errors). + +What compiles: `def`/`defn`, multi-arity / named / variadic fns, `recur` (in +`loop` and directly in `fn`), `let`/`if`/`do`/`try`/`throw`/`quote`, map and +vector literals, and calls. What falls back to the interpreter: context-modifying +and definitional forms (`ns`, `defmacro`, `deftype`, `defprotocol`, +`defmulti`/`defmethod`, `reify`, `require`, `binding`, …), destructuring, regex +literals, and the handful of interpreter-only special forms. + +**Live redefinition.** Compiled global references deref through Jolt **var cells** +(Janet early-binds plain symbols, which would freeze redefinition), so redefining +a `def`/`defn` at the REPL is visible to already-compiled callers — Clojure's var +model. Hot numeric primitives (`+ - * < > <= >=`) emit native Janet ops, and +calls compile to direct Janet calls. + +```janet +(def ctx (init {:compile? true})) +(eval-string ctx "(defn fib [n] (if (< n 2) n (+ (fib (- n 1)) (fib (- n 2)))))") +(eval-string ctx "(fib 30)") ; → 832040, native Janet bytecode +``` + +For compute-heavy code the compiled path is dramatically faster than tree-walking, +at native Janet speed. + +**Validated at parity.** The conformance suite passes 258/258 under *all three* +execution paths — interpreter, compiler, and the self-hosted compiler +(`conformance-test.janet` runs all three in CI) — and the full clojure-test-suite +matches its baseline across ~4.6k assertions — evidence the hybrid path doesn't +diverge. + +**AOT.** `aot.janet` marshals a compiled namespace to a Janet bytecode image +(`save-ns`) and loads it back into a fresh context (`load-ns-image`), skipping +parse/analyze/emit/compile on reload. Core fns are referenced by name against the +baked-in runtime; only user bytecode and var cells are serialized. + +## Host interop + +Jolt exposes CLJS-style host interop through `.` on any Janet table or struct — a field holding a function is called with the receiver as the first argument: ```clojure -;; from your editor, against the running process: -(require '[myapp.core :as app]) -(app/start!) ; bring the app up -;; edit a handler, re-evaluate the defn — the running app sees it, no restart -(app/stop!) +(def obj {:greet (fn [self name] (str "Hello " name))}) +(. obj greet "Alice") ; → "Hello Alice" +(.-greet obj) ; field access (reader sugar for (. obj :greet)) ``` -## Compile a binary +### The `janet` interop bridge -`bin/joltc build` ahead-of-time compiles a project into a single self-contained -executable — the runtime, `clojure.core`, the standard library, the app, and its -`deps.edn` dependencies are linked in, so the result needs no Chez install, no -JVM, and no source on disk to run. +The whole Janet standard library is reachable from Clojure through an explicit +`janet` namespace segment, which marks every crossing into host code (where +Clojure semantics no longer hold): + +```clojure +(janet.os/clock) ; → a Janet module fn: os/clock +(janet.string/join ["a" "b"] ",") ; → janet `string/join` (NB: takes a Janet + ; tuple, not a Jolt vector — convert first) +(janet/slurp "deps.edn") ; → a Janet root builtin: slurp +(janet/type [1 2]) ; → :table +``` + +The rule is `janet/` for a Janet root binding and `janet./` +for a module binding. Because the boundary is explicit, you can tell at the call +site that a form drops into the host — and that values cross the boundary as +their Janet representations (a Jolt vector is a Janet table, etc.), so a Janet +function expecting a tuple needs an explicit conversion. The `jolt.interop`, +`jolt.shell`, and `jolt.http` namespaces are thin Clojure wrappers built on this. + +This bridge is what makes networking (and everything else in Janet's stdlib) +available to ordinary Clojure — for example, `jolt.nrepl` (below) is plain +Clojure over `janet.net/*`. + +```clojure +(require '[jolt.interop :as j]) +(j/janet-type [1 2]) ; → :tuple +(j/janet-table-keys {:a 1 :b 2}) ; → [:b :a] +``` + +## nREPL + +Jolt ships an [nREPL](https://nrepl.org) server and client (`jolt.nrepl`), +written in Clojure on top of the `janet.net/*` bridge. Start a server from the +CLI — it writes `.nrepl-port` so editors (CIDER, Calva, …) auto-connect: ```bash -bin/joltc build -m myapp.core -o myapp # compile myapp.core's -main into ./myapp -./myapp arg1 arg2 # runs anywhere; args reach -main +jolt nrepl-server # listen on 127.0.0.1:7888, write .nrepl-port +jolt nrepl-server 12345 # choose a port +jolt nrepl-server 0.0.0.0:12345 # choose host and port (alias: nrepl) ``` -Modes trade dynamism for speed: the default (release) build uses the proven code -generator; `--opt` also runs the inference + inlining + scalar-replacement passes -over the closed-world program; `--dev` is unoptimized. +Supported ops: `clone`, `describe`, `eval`, `load-file`, `close`, `ls-sessions`, +`interrupt` (acknowledged; an in-flight eval can't actually be interrupted), and +`eldoc`. `eval` streams `out`, reports the current `ns`, evaluates each form in +the message, and returns an `eval-error` status (the session stays usable) on +failure. One Jolt runtime backs the server and sessions share it, so `def`s +persist across a connection like a normal dev REPL. -Two opt-in closed-world flags cut dispatch cost and binary size: +It's also usable as a library — embed a server, or drive another nREPL as a +client: -```bash -bin/joltc build -m myapp.core --direct-link # app->app calls bind directly (no var lookup) -bin/joltc build -m myapp.core --tree-shake # ship only code reachable from -main +```clojure +(require '[jolt.nrepl :as nrepl]) +(def server (nrepl/start-server! {:port 7888})) +;; ... later ... +(nrepl/stop-server! server) + +(def c (nrepl/connect {:port 7888})) +(def session (nrepl/client-clone c)) +(nrepl/client-eval c "(+ 1 2)" session) ; → responses incl. {"value" "3"} +(nrepl/client-close c) ``` -`--tree-shake` walks the call graph across your app, its libraries, and -`clojure.core`, drops everything unreachable from `-main` (and the compiler itself -when the app never `eval`s), and typically removes 1–2 MB. It stays sound by bailing -out — keeping everything, and reporting which library is responsible — when reachable -code resolves vars by name at runtime (`eval`/`resolve`/`ns-resolve`/…). See -[docs/tools-deps.md](docs/tools-deps.md) and `docs/rfc/0007`. - -This needs Chez's kernel development files (`libkernel.a`, `scheme.h`) and a C -compiler. They come with a from-source Chez install; a distro `chezscheme` -package ships only the runtime, so `build` won't link a binary there. -RFC 0007 (`docs/rfc/`) covers the design and the three-mode model. - -## Standalone joltc binary - -`make` builds joltc itself into a single self-contained native binary — the -runtime, compiler, `jolt-core`/`stdlib` source, and the Chez boots are baked in, -so the result runs and `build`s jolt apps on a machine with neither Chez nor a C -compiler. Build it on a host that *does* have both. - -```bash -make joltc-release # => target/release/joltc (optimize-level 3, compressed) -make joltc-debug # => target/debug/joltc (optimize-level 0, inspector + debug info) -make joltc # re-mint the seed first, then both -``` - -`make joltc` re-mints the seed so the embedded compiler image is current before -linking; use `joltc-release`/`joltc-debug` directly to skip that when the seed is -already minted. Like `build`, both require Chez's kernel development files -(`libkernel.a`, `scheme.h`) and a C compiler. - -## Architecture - -A small Chez runtime (`host/chez/*.ss`: value model, persistent collections, seqs, -vars/namespaces, host interop) hosts a portable Clojure overlay split across two -source roots by *when* they load: - -- **`jolt-core/`** is baked into the seed — the compiler (`jolt-core/jolt/`: - reader/analyzer/IR/backend, plus `jolt.main`/`jolt.deps`) and `clojure.core` in - dependency-ordered tiers (`jolt-core/clojure/core/NN-*.clj`). Changing anything - here means re-minting the seed. -- **`stdlib/`** loads lazily at runtime off the source roots — the rest of the - standard library (`clojure.string`/`set`/`walk`/`edn`/`pprint`/…) plus the - `jolt.ffi` host library. Editing these needs no re-mint. - -`bin/joltc` loads the checked-in seed and the spine, then compiles and evaluates on -Chez (read → analyze → IR → emit → eval). `host/chez/bootstrap.ss` rebuilds that -seed from source on pure Chez; the build is a self-hosting fixpoint (a rebuild -reproduces the checked-in seed byte-for-byte). - ## Differences from Clojure -Jolt targets Clojure semantics but runs on Chez, not the JVM. Most portable -Clojure runs unchanged — persistent collections (32-way-trie vectors, HAMT -maps/sets), the numeric tower (exact integers, bignums, ratios, doubles), lazy -and infinite sequences, transducers, destructuring, multimethods with -hierarchies, protocols/records (`deftype`/`defrecord`/`reify`/`extend-protocol`), -metadata, namespaces, atoms, `future`/`promise`/`agent`/`pmap`, -`clojure.core.async`, runtime `eval`/`load-string`/`defmacro`, and the full -reader (`#()`, `#_`, `#?`, tagged literals, `#"…"`) all behave as on the JVM. -`=` is category-aware (`(= 3 3.0)` ⇒ `false`) and `==` is value-equality, as in -Clojure. The genuine divergences: +Jolt targets Clojure semantics but runs on Janet, not the JVM. The notable divergences: -- **No JVM, no Java interop.** No reflection, no `gen-class`/`proxy`. Interop - syntax (`Class.`, `Class/static`, `.method`) resolves only against a shimmed - subset of the `java.*` standard library; a class token is a name, not a loaded - class. See [docs/host-interop.md](docs/host-interop.md). To call C libraries - directly, use the `jolt.ffi` foreign-function interface (how the db and - http-client libraries bind SQLite/libpq and sockets/OpenSSL/zlib). -- **No `BigDecimal`.** `decimal?` is always false and there is no `M` literal; - the rest of the numeric tower matches the JVM. -- **No STM.** No `ref`/`dosync`/`alter`/`commute` — coordinated shared state uses - atoms (per-atom mutex, JVM-style CAS). The concurrency primitives above are - otherwise present and run on a shared heap. -- **Regex engine.** Patterns compile through - [irregex](https://github.com/ashinn/irregex) (vendored), not - `java.util.regex`; common patterns work, Java-specific features can differ. -- **Coverage.** `clojure.core` is implemented function by function against the - JVM-sourced conformance corpus — broad but not total; a namespace can load with - most functions working and a few not yet implemented. +- **Host platform.** No JVM and no Java interop — `import`, `gen-class`, `proxy` of Java classes, and `java.*` are unavailable. `instance?` recognizes a small set of built-in types (`clojure.lang.Atom`, `Number`, `String`, …). +- **Numbers.** Janet integers and doubles. `(/ 1 3)` is `0.3333…` and large products lose precision. No ratios or `BigDecimal` (`ratio?` is always false, `bigdec` falls back to a double); `bigint`/`biginteger` use Janet's 64-bit `int/s64`, not arbitrary precision. The reader still accepts Clojure's numeric literal syntaxes — the BigInt/BigDecimal suffixes (`42N`, `1.5M`), ratios (`1/2`), radixed integers (`2r1010`, `16rFF`), and exponents (`1e3`) — but reads them as plain Janet numbers (a ratio becomes its double quotient). The auto-promoting `+'`/`-'`/`*'`/`inc'`/`dec'` are aliases for the plain ops, since Janet numbers don't overflow. `quot`/`rem`/`mod` follow Clojure's sign rules. The symbolic values `##Inf`/`##-Inf`/`##NaN` read, and `infinite?`/`NaN?` work. Janet represents an integer and an integer-valued double identically, so `1` and `1.0` are indistinguishable: `(float?/double? 1.0)` is `false` and `(int? 1.0)` is `true` — `float?`/`double?` are true only for values with a fractional part or `##Inf`/`##NaN`. +- **Collections.** By default Jolt uses immutable persistent data structures: vectors are 32-way branching tries (structural-sharing persistent vectors with O(log₃₂ n) `conj`/`assoc`/`nth`), lists are persistent singly-linked cons cells (O(1) `conj`/`cons` prepend with structural sharing), and maps/sets are persistent hash structures. Value equality and sequence operations are Clojure-compatible, but hash-map/hash-set iteration order is unspecified and differs from Clojure — use `sorted-map`/`sorted-set` when order matters. +- **Mutable build mode.** Jolt can be compiled to use fast Janet-native *mutable* collections instead, via a build-time flag: `JOLT_MUTABLE=1 jpm build` (default `jpm build` is immutable). In mutable mode vectors and lists share one mutable array representation (so `conj` mutates in place and appends, and `vector?`/`list?` no longer distinguish them) — a performance/looseness trade-off. The default immutable build has full Clojure value semantics. +- **Concurrency / STM.** No refs, `dosync`, agents, or `send`; `locking` evaluates its body without real locking. Atoms, volatiles, promises, and delays are supported. +- **Futures.** `future` runs its body on a *real* OS thread (Janet's `ev/thread`), so it can use a second core for CPU-bound work — unlike the cooperatively-scheduled `go` blocks. `deref`/`@` parks until the result is ready (with the optional `(deref f timeout-ms timeout-val)` arity); `future?`, `future-done?`, `realized?`, `future-cancel`, and `future-cancelled?` are supported. Two important divergences from the JVM: (1) **snapshot semantics** — Janet threads have separate heaps, so the body and the state it closes over are *copied* to the worker thread and only the return value is copied back; mutating a captured atom does not propagate to the parent (communicate via the return value). (2) **no thread interruption** — Janet OS threads can't be cancelled mid-run, so `future-cancel` marks the *future* cancelled (deref then throws and the predicates flip) but the underlying computation still runs to completion in the background. As on the JVM, a live future thread keeps the process alive until it finishes (the JVM's non-daemon future pool behaves the same). +- **core.async.** `clojure.core.async` runs on Janet fibers and channels (`chan`, `go`, `go-loop`, `!`/`!!`, `close!`, `alts!`, `timeout`, `put!`/`take!`, `buffer`/`dropping-buffer`/`sliding-buffer`, and channel transducers via `(chan n xform)`). Because Janet fibers are stackful coroutines, a `go` block is just its body run in a fiber — no CPS/state-machine rewrite — so `!` work *anywhere*, including inside `try`, nested `fn`s, and loops (positions Clojure's `go` macro forbids). Go blocks are cooperatively scheduled on one OS thread, so parking (`…)`), and Unicode property classes (`\p{Lu}`). +- **Arrays.** Java-style arrays map onto Janet's native types: `byte-array` is a Janet buffer (contiguous, C-backed); `object-array`/`int-array`/`double-array`/etc. are Janet arrays. `aget`/`aset`/`alength`/`aclone` work over both. +- **Transients.** `transient`/`conj!`/`assoc!`/`dissoc!`/`disj!`/`pop!`/`persistent!` are real mutable scratch collections backed by Janet's native arrays and tables (vectors → arrays, maps/sets → tables), so building a collection with them avoids the per-step copying of the persistent path (notably for maps/sets). `persistent!` freezes back to a persistent value. +- **Not implemented.** JVM reflection, `proxy`, and the `clojure.repl`/`clojure.template` namespaces. + +Supported and Clojure-compatible: chars as a distinct type, lazy/infinite sequences, transducers, destructuring, multimethods with hierarchies, protocols/records (`deftype`/`defrecord`/`reify`/`extend-protocol`), metadata, namespaces, and the reader (`#()`, `#_`, `#?`, tagged literals, `#"…"`). ## Test -```bash -make test # the full gate -make corpus # conformance corpus vs the JVM-sourced spec -make unit # host-specific unit cases -make selfhost # bootstrap fixpoint (rebuild == checked-in seed) -make smoke # bin/joltc CLI smoke -make sci # load borkdude/sci's source through joltc (compat stress) -make ffi # HTTP-server GC-safety + http-client temp paths -make transient # transient mutation + linear-time builds -make certify # JVM oracle (skips if clojure is absent) +``` +jpm test # full suite (recurses test/) +janet test/spec/sequences-spec.janet # a single spec +janet test/integration/conformance-test.janet ``` -The conformance corpus (`test/chez/corpus.edn`) is a host-neutral language spec -whose expected values are sourced from reference JVM Clojure. See -[test/conformance/SPEC.md](test/conformance/SPEC.md). +Tests are organized in three layers: + +- **`test/spec/`** — the contract. Black-box, behavior-defining tables (one file + per public API area) that collectively pin down Jolt's defined behavior. This + is the authoritative description of what Jolt promises. +- **`test/integration/`** — cross-cutting and regression batteries: the Clojure + conformance suite (run in all three execution modes), SCI bootstrap/runtime + loading, jank conformance, the cross-dialect + [clojure-test-suite](https://github.com/jank-lang/clojure-test-suite) (a git + submodule at `vendor/clojure-test-suite`, run via a minimal `clojure.test` shim + and baseline-guarded), compile-mode tests, the library API, and a broad + systematic-coverage net. +- **`test/unit/`** — white-box tests for individual components (reader, + evaluator, types, persistent collections, regex, compiler). + +`test/support/harness.janet` provides the shared `defspec` table runner (cases +are `["label" expected actual]`, compared with Jolt's own `=`) plus +`expect=`/`expect-throws` for unit tests. + +The syntactic half of the contract — the surface syntax the reader accepts — is +specified as an EBNF grammar in [`doc/grammar.ebnf`](doc/grammar.ebnf), with +Jolt-vs-Clojure deviations noted inline. `test/spec/reader-syntax-spec.janet` +exercises it. + +### clojure-test-suite conformance + +The [clojure-test-suite](https://github.com/jank-lang/clojure-test-suite) battery +(vendored as a git submodule) runs ~3980 assertions green. Jolt validates its +arguments like Clojure — arithmetic on non-numbers, comparisons against `nil`, +out-of-range indices, malformed `conj!`/`assoc!`/`merge`, non-seqable +`first`/`seq`/`vec`, and lazy transformers (`map`/`filter`/…) realized over a +non-seqable all throw. The lazy seq fns return seqs (not vectors), so +`seq?`/`vector?`/`sequential?` of their results match Clojure. The assertions +that remain failing are accounted for by the platform/design differences above, +not by missing behavior: + +- **No bignum/ratio/BigDecimal** — `bigint`/`numerator`/`denominator`/`bigdec`, + the `big-int?`/auto-promotion checks, and the `2N`/`1/2`/`1.0M` literals read + but don't carry those exact types. +- **Integer/float identity** — Janet represents `1` and `1.0` identically, so + `quot`/`rem`/`mod`'s `double?`/`int?` result-type assertions and many + `float?`/`double?` cases can't distinguish them (`(str 0.0)` is `"0"`). +- **64-bit integers / Unicode** — `bit-and` etc. on full-width 64-bit constants + lose precision (doubles), and `subs`/`count` work on bytes, not code points. ## License -[Eclipse Public License 2.0](https://www.eclipse.org/legal/epl-2.0/) +[Eclipse Public License 1.0](https://opensource.org/licenses/EPL-1.0) diff --git a/bench/.gitignore b/bench/.gitignore deleted file mode 100644 index bd04223..0000000 --- a/bench/.gitignore +++ /dev/null @@ -1 +0,0 @@ -.cpcache/ diff --git a/bench/README.md b/bench/README.md deleted file mode 100644 index dffd3fc..0000000 --- a/bench/README.md +++ /dev/null @@ -1,120 +0,0 @@ -# jolt benchmark suite - -Benchmarks that isolate the workload axes jolt's optimizing passes target. The -ray tracer (`examples/ray-tracer`) is **float-compute-bound** — its time is -irreducible algorithmic math (hit-testing + transcendentals), and devirt, -allocation removal, and type-proving all measured **flat** on it. So it can't -tell us whether those passes work. These benchmarks make each pass's target -workload the *dominant* cost. - -Reference: the cross-language suites these draw from — -[Are We Fast Yet?](https://github.com/smarr/are-we-fast-yet) (Marr et al., DLS '16) -and the [Computer Language Benchmarks Game](https://benchmarksgame-team.pages.debian.net/benchmarksgame/). -The benchmarks are portable Clojure, so they also run on JVM Clojure for an -absolute reference. - -## Benchmarks - -| Benchmark | Axis | Pass it exercises | Source | -|---|---|---|---| -| `binary-trees` | allocation / GC pressure (escaping short-lived records) | scalar-replace, escape analysis | CLBG | -| `dispatch` | polymorphic (**megamorphic**) protocol dispatch | devirt, inline-cache | AWFY-style | -| `mono-dispatch` | **monomorphic** protocol dispatch (devirt/inline-cache *can* fire) | devirt, inline-cache | AWFY-style | -| `collections` | persistent map/vector churn (HAMT / 32-way tries) | persistent structures, transients | CLBG k-nucleotide-style | -| `mandelbrot` | pure float compute (tight arith loops, no alloc/dispatch) | native arith, loop codegen | CLBG | -| `fib` | recursion: function-call + integer-arith overhead | native arith, small-fn inlining | CLBG | - -What the ray tracer does **not** capture and these do: allocation as the -bottleneck (~7% there), megamorphic *and* monomorphic dispatch (its dispatch is -monomorphic and cheap), persistent-collection throughput (it uses fixed records, -no collections in the hot loop), and isolated compute/call overhead. - -Planned additions: Richards / DeltaBlue (heavier OO dispatch), NBody (float -control with record state), k-nucleotide proper. - -## Holistic scorecard - -`bench/run.sh` compiles each benchmark to an **optimized AOT binary** (`joltc build ---direct-link --opt`) and times it against JVM Clojure running the same portable -source — the jolt/JVM scorecard. jolt's optimizing passes fire only in a build; -`joltc run -m` is unoptimized, so the harness always builds. - -Indicative ratios (M-series, single isolated run — numbers are machine-specific, -regenerate locally), ascending: - -| benchmark | ratio | axis | -|---|---|---| -| `fib` | ~0.6× | call + integer arith | -| `collections` | ~3.5× | persistent map/vector churn | -| `mandelbrot` | ~7.5× | pure float compute | -| `binary-trees` | ~10× | escaping short-lived records (allocation/GC) | -| `dispatch` | ~12× | megamorphic protocol dispatch | -| `mono-dispatch` | ~15× | monomorphic protocol dispatch | - -- **Compute (~0.6–7.5×)** is the substrate floor: Chez is a native-compiling AOT - Scheme, not a profiling JIT. With native arith + direct-linking + inlining jolt - is at parity here — `fib` runs *faster* than JVM Clojure (no JIT warmup over a - short run), `collections` is within ~3.5×, and `mandelbrot` (~7.5×) is the - pure-tight-loop float ceiling that only native codegen moves further. -- **Dispatch & allocation (~10–15×)** are the remaining architectural gaps, though - the type-proving / native-record / bare-field-read work has collapsed them by an - order of magnitude (`binary-trees` ~140×→~10×, `mono-dispatch` ~330×→~15×). On a - *statically proven* monomorphic receiver — which whole-program inference now gives - for a record iterated out of a vector — devirt resolves the impl and a per-site - inline cache holds it (resolved once, not per call), so `mono-dispatch` is no - longer worse than megamorphic. The remaining lever is `dispatch`: a *megamorphic* - site has no static type, so it pays a full protocol-registry lookup every call - where the JVM uses a polymorphic inline cache — a runtime (receiver-type-keyed) - cache is the missing piece. `binary-trees` - nodes escape into the tree, so scalar-replace can't remove them — residual GC - pressure. - -## 64-bit integer arithmetic & generators (test.check) - -The AOT suite above is float-compute / dispatch / allocation bound; none of it -exercises **64-bit integer arithmetic**, which Chez can't hold in a fixnum -(61-bit), so genuine 64-bit values are heap bignums. The SplitMix PRNG behind -`clojure.test.check` is the worst case — every `rand-long` is ~8 bignum ops. These -were measured in **run mode** (`joltc run`, where per-site var-cell caching is on; -the AOT build keeps it off) against JVM Clojure on the same portable source. The -first two rows are isolating microbenchmarks; the rest are real test.check -generators. - -| workload | jolt | JVM | ratio | bound by | -|---|---|---|---|---| -| SplitMix `mix-64` (×100k) | 45ms | 14ms | ~3.2× | 64-bit integer arithmetic | -| deftype alloc + protocol dispatch (×100k) | 41ms | 5ms | ~8× | open-world dispatch | -| raw `split` + `rand-long` (×20k) | 74ms | 6ms | ~12× | bignum 64-bit + dispatch | -| `gen/large-integer` (×2k) | 108ms | 23ms | ~4.7× | arithmetic + rose-tree machinery | -| `(gen/vector gen/large-integer)` (×500) | 1289ms | 88ms | ~14.6× | element gen + gen machinery | - -Two no-C codegen levers collapsed the **arithmetic** half: emitting `bit-and`/ -`bit-or`/`bit-xor`/`bit-not` as inlined Chez `bitwise-*` primitives (they had gone -through a var-deref'd variadic overlay), and caching the resolved var cell per -reference site (a name lookup was ~45ns/access). Together they took `mix-64` from -~18× → ~3.2× JVM and the raw PRNG from ~30× → ~12×, and the generators ~1.6× each. - -The residual gap is **machinery, not arithmetic**: the open-world generator -deftype/protocol dispatch + rose-tree allocation (~8–10×) can't be devirtualized -without static types, and the raw 64-bit ops bottom out at the Chez bignum floor -(~20× a native long, substrate-inherent). A native SplitMix C/FFI shim would give -the PRNG ~27× but is the only path that needs C. - -## Running - -```sh -bench/run.sh # full suite + JVM scorecard -bench/run.sh fib # one benchmark, default size -bench/run.sh fib 32 # one benchmark, custom size -NO_JVM=1 bench/run.sh # jolt only (skip the JVM reference) -``` - -Needs Chez's kernel dev files (`libkernel.a` + `scheme.h`) and `cc` for the build, -like `jolt build`; set `JOLT_CHEZ_CSV` to override the detected csv dir. - -## A/B against a change - -To measure a pass, run the suite on `main`, then on the branch, back to back -(same machine, quiet). Each benchmark prints `runs: [...]` and `mean: N ms`; -compare the means. A pass is worth landing when it moves a benchmark whose axis it -targets, even if the ray tracer stays flat. diff --git a/bench/binary_trees.clj b/bench/binary_trees.clj deleted file mode 100644 index 28428ec..0000000 --- a/bench/binary_trees.clj +++ /dev/null @@ -1,53 +0,0 @@ -;; binary-trees (Computer Language Benchmarks Game) — an ALLOCATION/GC stress -;; test. Builds and discards millions of short-lived `Node` records; the nodes -;; ESCAPE (stored in the tree, walked later), so this is the regime escape analysis -;; targets and the ray tracer never exercises (~7% alloc). -;; -;; Portable Clojure: runs on jolt and JVM Clojure for cross-impl comparison. -;; bench/run.sh binary-trees 14 -(ns binary-trees) - -(defrecord Node [left right]) - -(defn make-tree [depth] - (if (zero? depth) - (->Node nil nil) - (->Node (make-tree (dec depth)) (make-tree (dec depth))))) - -(defn check-tree [node] - (let [l (:left node)] - (if (nil? l) - 1 - (+ (+ 1 (check-tree l)) (check-tree (:right node)))))) - -(defn run [max-depth] - (let [min-depth 4 - stretch-depth (inc max-depth) - _ (check-tree (make-tree stretch-depth)) - long-lived (make-tree max-depth)] - (loop [d min-depth acc 0] - (if (<= d max-depth) - (let [iterations (bit-shift-left 1 (+ (- max-depth d) min-depth)) - sum (loop [i 0 s 0] - (if (< i iterations) - (recur (inc i) (+ s (check-tree (make-tree d)))) - s))] - (recur (+ d 2) (+ acc sum))) - ;; touch the long-lived tree so it isn't dead-code-eliminated - (+ acc (check-tree long-lived)))))) - -(defn -main [& args] - (let [max-depth (if (seq args) (Integer/parseInt (first args)) 14)] - (dotimes [_ 2] (run (min max-depth 10))) ; warmup - (let [runs 3 - times (mapv (fn [_] - (let [t0 (System/nanoTime) - r (run max-depth) - ms (/ (- (System/nanoTime) t0) 1000000.0)] - [ms r])) - (range runs)) - mss (mapv first times) - mean (/ (reduce + mss) runs)] - (println "binary-trees depth" max-depth "checksum" (second (first times))) - (println "runs:" (mapv (fn [t] (/ (Math/round (* t 10.0)) 10.0)) mss)) - (println "mean:" (/ (Math/round (* mean 10.0)) 10.0) "ms")))) diff --git a/bench/collections.clj b/bench/collections.clj deleted file mode 100644 index 2c0304d..0000000 --- a/bench/collections.clj +++ /dev/null @@ -1,46 +0,0 @@ -;; collections — PERSISTENT-COLLECTION churn. Builds and reads persistent maps -;; and vectors (32-way hash/array tries) under heavy assoc/update/conj/lookup, a -;; word-count-style workload (cf. CLBG k-nucleotide). Exercises jolt's persistent -;; data structures and (eventually) transients — an axis the ray tracer (fixed -;; records, no collections in the hot loop) doesn't touch. -;; -;; Portable Clojure (jolt + JVM Clojure). -;; bench/run.sh collections 200000 -(ns collections) - -;; map churn: accumulate a frequency map over a stream of keys, then sum it back -(defn freq-map [n buckets] - (loop [i 0 m {}] - (if (< i n) - (recur (inc i) - (let [k (mod (* i 2654435761) buckets)] - (assoc m k (+ 1 (get m k 0))))) - m))) - -(defn sum-vals [m] - (reduce (fn [acc k] (+ acc (get m k))) 0 (keys m))) - -;; vector churn: conj many, then reduce -(defn vec-sum [n] - (let [v (loop [i 0 v []] (if (< i n) (recur (inc i) (conj v (mod i 1000))) v))] - (reduce + 0 v))) - -(defn run [n] - (let [m (freq-map n 4096)] - (+ (sum-vals m) (vec-sum (quot n 4))))) - -(defn -main [& args] - (let [n (if (seq args) (Integer/parseInt (first args)) 200000)] - (dotimes [_ 2] (run (quot n 4))) ; warmup - (let [runs 3 - times (mapv (fn [_] - (let [t0 (System/nanoTime) - r (run n) - ms (/ (- (System/nanoTime) t0) 1000000.0)] - [ms r])) - (range runs)) - mss (mapv first times) - mean (/ (reduce + mss) runs)] - (println "collections n" n "result" (second (first times))) - (println "runs:" (mapv (fn [t] (/ (Math/round (* t 10.0)) 10.0)) mss)) - (println "mean:" (/ (Math/round (* mean 10.0)) 10.0) "ms")))) diff --git a/bench/deps.edn b/bench/deps.edn deleted file mode 100644 index 5837a2a..0000000 --- a/bench/deps.edn +++ /dev/null @@ -1 +0,0 @@ -{:paths ["."]} diff --git a/bench/dispatch.clj b/bench/dispatch.clj deleted file mode 100644 index d60527b..0000000 --- a/bench/dispatch.clj +++ /dev/null @@ -1,56 +0,0 @@ -;; dispatch — a POLYMORPHIC-DISPATCH stress test. A protocol method is called in -;; a hot loop over a heterogeneous (megamorphic) collection of record types, with -;; minimal per-call work, so protocol dispatch dominates. This is the regime -;; devirtualization and the inline-cache target, and the one the ray -;; tracer can't reveal — its dispatch is monomorphic and a small fraction of the -;; float-math cost (devirt measured FLAT there). -;; -;; Portable Clojure (jolt + JVM Clojure). -;; bench/run.sh dispatch 20000 -(ns dispatch) - -(defprotocol Shape - (area [s]) - (sides [s])) - -(defrecord Circle [r] Shape (area [_] (* (* 3.14159 r) r)) (sides [_] 0)) -(defrecord Square [s] Shape (area [_] (* s s)) (sides [_] 4)) -(defrecord Triangle [b h] Shape (area [_] (* (* 0.5 b) h)) (sides [_] 3)) -(defrecord Rect [w h] Shape (area [_] (* w h)) (sides [_] 4)) - -(defn build-shapes [n] - (mapv (fn [i] - (let [k (mod i 4)] - (cond - (= k 0) (->Circle (+ 1 (mod i 7))) - (= k 1) (->Square (+ 1 (mod i 5))) - (= k 2) (->Triangle (+ 1 (mod i 3)) (+ 2 (mod i 6))) - :else (->Rect (+ 1 (mod i 4)) (+ 1 (mod i 8)))))) - (range n))) - -;; megamorphic: every element may be a different type -> the call site sees all 4 -(defn sum-area [shapes] - (reduce (fn [acc s] (+ (+ acc (area s)) (sides s))) 0.0 shapes)) - -(defn run [iters] - (let [shapes (build-shapes 1000)] - (loop [i 0 acc 0.0] - (if (< i iters) - (recur (inc i) (+ acc (sum-area shapes))) - acc)))) - -(defn -main [& args] - (let [iters (if (seq args) (Integer/parseInt (first args)) 20000)] - (dotimes [_ 2] (run (quot iters 4))) ; warmup - (let [runs 3 - times (mapv (fn [_] - (let [t0 (System/nanoTime) - r (run iters) - ms (/ (- (System/nanoTime) t0) 1000000.0)] - [ms r])) - (range runs)) - mss (mapv first times) - mean (/ (reduce + mss) runs)] - (println "dispatch iters" iters "result" (second (first times))) - (println "runs:" (mapv (fn [t] (/ (Math/round (* t 10.0)) 10.0)) mss)) - (println "mean:" (/ (Math/round (* mean 10.0)) 10.0) "ms")))) diff --git a/bench/fib.clj b/bench/fib.clj deleted file mode 100644 index 2457a6e..0000000 --- a/bench/fib.clj +++ /dev/null @@ -1,29 +0,0 @@ -;; fib — naive recursive Fibonacci: pure function-call + integer-arithmetic -;; throughput, with no allocation, dispatch, or collections. Isolates call -;; overhead and native integer arith, and is the natural target for -;; single-call-site / small-fn inlining and self-call direct-linking. -;; -;; Portable Clojure (jolt + JVM Clojure). -;; bench/run.sh fib 32 -(ns fib) - -(defn fib [n] - (if (< n 2) n (+ (fib (- n 1)) (fib (- n 2))))) - -(defn run [n] (fib n)) - -(defn -main [& args] - (let [n (if (seq args) (Integer/parseInt (first args)) 32)] - (dotimes [_ 2] (run (- n 6))) ; warmup - (let [runs 3 - times (mapv (fn [_] - (let [t0 (System/nanoTime) - r (run n) - ms (/ (- (System/nanoTime) t0) 1000000.0)] - [ms r])) - (range runs)) - mss (mapv first times) - mean (/ (reduce + mss) runs)] - (println "fib n" n "result" (second (first times))) - (println "runs:" (mapv (fn [t] (/ (Math/round (* t 10.0)) 10.0)) mss)) - (println "mean:" (/ (Math/round (* mean 10.0)) 10.0) "ms")))) diff --git a/bench/mandelbrot.clj b/bench/mandelbrot.clj deleted file mode 100644 index 0367f02..0000000 --- a/bench/mandelbrot.clj +++ /dev/null @@ -1,52 +0,0 @@ -;; mandelbrot — pure floating-point compute: for each point of an NxN grid, -;; iterate z = z^2 + c up to a cap and count iterations. No allocation, no -;; dispatch, no collections in the hot loop — just double arithmetic and tight -;; recur loops. This isolates the irreducible-math axis the ray tracer is bound -;; on (where devirt/alloc passes measured flat), so it tracks native-arith codegen -;; and loop quality directly. -;; -;; Portable Clojure (jolt + JVM Clojure). The jolt.png picture demo lives in -;; mandelbrot_png.clj so this file stays portable for the JVM reference run. -;; bench/run.sh mandelbrot 1000 -(ns mandelbrot) - -(defn count-point [cr ci cap] - (loop [i 0 zr 0.0 zi 0.0] - (if (or (>= i cap) (> (+ (* zr zr) (* zi zi)) 4.0)) - i - (recur (inc i) - (+ (- (* zr zr) (* zi zi)) cr) - (+ (* 2.0 (* zr zi)) ci))))) - -(defn run [n] - (let [cap 200 - nd (* 1.0 n)] - (loop [y 0 acc 0] - (if (< y n) - (let [ci (- (/ (* 2.0 y) nd) 1.0) - row (loop [x 0 a 0] - (if (< x n) - (let [cr (- (/ (* 2.0 x) nd) 1.5)] - (recur (inc x) (+ a (count-point cr ci cap)))) - a))] - (recur (inc y) (+ acc row))) - acc)))) - -(defn- run-bench [args] - (let [n (if (seq args) (Integer/parseInt (first args)) 1000)] - (dotimes [_ 2] (run (quot n 2))) ; warmup - (let [runs 3 - times (mapv (fn [_] - (let [t0 (System/nanoTime) - r (run n) - ms (/ (- (System/nanoTime) t0) 1000000.0)] - [ms r])) - (range runs)) - mss (mapv first times) - mean (/ (reduce + mss) runs)] - (println "mandelbrot n" n "result" (second (first times))) - (println "runs:" (mapv (fn [t] (/ (Math/round (* t 10.0)) 10.0)) mss)) - (println "mean:" (/ (Math/round (* mean 10.0)) 10.0) "ms")))) - -(defn -main [& args] - (run-bench args)) diff --git a/bench/mandelbrot_png.clj b/bench/mandelbrot_png.clj deleted file mode 100644 index f73d441..0000000 --- a/bench/mandelbrot_png.clj +++ /dev/null @@ -1,36 +0,0 @@ -;; mandelbrot picture demo — renders a real image of the set to a PNG via -;; jolt.png (FFI), reusing mandelbrot/count-point as the kernel. jolt-only (the -;; benchmark in mandelbrot.clj stays portable for the JVM reference). -;; joltc run -m mandelbrot-png [path] [size] -(ns mandelbrot-png - (:require [mandelbrot :as m] - [jolt.png :as png])) - -(defn- color - "Escape-iteration count -> RGB. In-set points (n>=cap) are black; faster - escapes run through a warm gradient." - [n cap] - (if (>= n cap) - [0 0 0] - (let [t (/ (double n) cap)] - [(int (* 255 (min 1.0 (* 3.0 t)))) - (int (* 255 (min 1.0 (max 0.0 (* 3.0 (- t 0.33)))))) - (int (* 255 (min 1.0 (max 0.0 (* 3.0 (- t 0.66))))))]))) - -(defn render! - "Render a size×size view of the Mandelbrot set to a PNG at path." - [path size] - (let [w size h size cap 1000 - img (png/image w h)] - (doseq [py (range h)] - (doseq [px (range w)] - (let [cr (- (* 3.5 (/ (double px) w)) 2.5) ; real ∈ [-2.5, 1.0] - ci (- (* 2.8 (/ (double py) h)) 1.4) ; imag ∈ [-1.4, 1.4] - [r g b] (color (m/count-point cr ci cap) cap)] - (png/put! img r g b)))) - (png/write img w h path) - (println "wrote" path (str w "×" h ", cap " cap)))) - -(defn -main [& args] - (render! (or (first args) "mandelbrot.png") - (if (second args) (Integer/parseInt (second args)) 600))) diff --git a/bench/mono_dispatch.clj b/bench/mono_dispatch.clj deleted file mode 100644 index dba72dd..0000000 --- a/bench/mono_dispatch.clj +++ /dev/null @@ -1,45 +0,0 @@ -;; mono-dispatch — protocol dispatch where every call site sees ONE record type -;; (monomorphic). This is the regime where devirtualization and a -;; call-site inline cache CAN fire — the megamorphic `dispatch` bench deliberately -;; defeats them, so this is its complement: it measures how close a proven/cached -;; monomorphic dispatch gets to a direct call. Same per-call work as `dispatch`. -;; -;; Portable Clojure (jolt + JVM Clojure). -;; bench/run.sh mono-dispatch 20000 -(ns mono-dispatch) - -(defprotocol Shape - (area [s]) - (sides [s])) - -(defrecord Circle [r] Shape (area [_] (* (* 3.14159 r) r)) (sides [_] 0)) - -;; homogeneous: every element is a Circle -> the call site is monomorphic -(defn build-shapes [n] - (mapv (fn [i] (->Circle (+ 1 (mod i 7)))) (range n))) - -(defn sum-area [shapes] - (reduce (fn [acc s] (+ (+ acc (area s)) (sides s))) 0.0 shapes)) - -(defn run [iters] - (let [shapes (build-shapes 1000)] - (loop [i 0 acc 0.0] - (if (< i iters) - (recur (inc i) (+ acc (sum-area shapes))) - acc)))) - -(defn -main [& args] - (let [iters (if (seq args) (Integer/parseInt (first args)) 20000)] - (dotimes [_ 2] (run (quot iters 4))) ; warmup - (let [runs 3 - times (mapv (fn [_] - (let [t0 (System/nanoTime) - r (run iters) - ms (/ (- (System/nanoTime) t0) 1000000.0)] - [ms r])) - (range runs)) - mss (mapv first times) - mean (/ (reduce + mss) runs)] - (println "mono-dispatch iters" iters "result" (second (first times))) - (println "runs:" (mapv (fn [t] (/ (Math/round (* t 10.0)) 10.0)) mss)) - (println "mean:" (/ (Math/round (* mean 10.0)) 10.0) "ms")))) diff --git a/bench/run.sh b/bench/run.sh deleted file mode 100755 index 73db4cc..0000000 --- a/bench/run.sh +++ /dev/null @@ -1,70 +0,0 @@ -#!/bin/sh -# Run the jolt benchmark suite against JVM Clojure and print a jolt/JVM scorecard. -# -# jolt's optimizing passes (direct-linking, inlining, scalar-replace, whole-program -# inference) fire only in an AOT BUILD — `joltc run -m` is unoptimized — so each -# benchmark is compiled to an optimized standalone binary and timed. JVM Clojure -# runs the same portable source for the absolute reference. Each benchmark prints -# `runs: [...]` and `mean: N ms`; the table shows the means and the jolt/JVM ratio. -# -# bench/run.sh # full suite + JVM scorecard -# bench/run.sh fib # one benchmark, default size -# bench/run.sh fib 32 # one benchmark, custom size -# NO_JVM=1 bench/run.sh # jolt only (skip the JVM reference) -# -# Building needs Chez's kernel dev files (libkernel.a + scheme.h) and a C compiler, -# the same as `jolt build`; set JOLT_CHEZ_CSV to override the detected csv dir. -set -e -cd "$(dirname "$0")" -root="$(cd .. && pwd)" -joltc="$root/bin/joltc" -export JOLT_PWD="$PWD" - -# Locate Chez's kernel dev files for the optimized build (as build-smoke.sh does). -csv="$JOLT_CHEZ_CSV" -if [ -z "$csv" ]; then - chez_bin="$(command -v chez || command -v scheme || command -v petite || true)" - if [ -n "$chez_bin" ]; then - base="$(cd "$(dirname "$chez_bin")/.." 2>/dev/null && pwd)" - for d in "$base"/lib/csv*/*/; do - [ -f "${d}libkernel.a" ] && csv="${d%/}" && break - done - fi -fi -if [ -z "$csv" ] || [ ! -f "$csv/libkernel.a" ] || [ ! -f "$csv/scheme.h" ] || ! command -v cc >/dev/null 2>&1; then - echo "error: the optimized build needs Chez kernel dev files (libkernel.a + scheme.h) and cc." >&2 - echo " set JOLT_CHEZ_CSV to the csv dir, e.g. \$(brew --prefix chezscheme)/lib/csv*/." >&2 - exit 1 -fi -export JOLT_CHEZ_CSV="$csv" - -bindir="$(mktemp -d)" -trap 'rm -rf "$bindir"' EXIT - -# name:default-arg, each sized to run in a few seconds. Axes: see README.md. -BENCHES="fib:30 mandelbrot:200 collections:30000 mono-dispatch:2000 dispatch:2000 binary-trees:14" - -run_one() { - ns="${1%%:*}"; arg="${2:-${1##*:}}" - if ! "$joltc" build -m "$ns" -o "$bindir/$ns" --direct-link --opt >/dev/null 2>&1; then - printf '%-16s jolt build FAILED\n' "$ns"; return - fi - jmean=$("$bindir/$ns" "$arg" 2>/dev/null | awk '/^mean:/{print $2}') - if [ -z "$NO_JVM" ]; then - vmean=$(clojure -Sdeps '{:paths ["."]}' -M -m "$ns" "$arg" 2>/dev/null | awk '/^mean:/{print $2}') - ratio=$(awk "BEGIN{ if (\"$vmean\"+0>0 && \"$jmean\"+0>0) printf \"%.1fx\", (\"$jmean\"+0)/(\"$vmean\"+0); else printf \"-\" }") - printf '%-16s jolt %9s ms jvm %8s ms %s\n' "$ns" "${jmean:--}" "${vmean:--}" "$ratio" - else - printf '%-16s jolt %9s ms\n' "$ns" "${jmean:--}" - fi -} - -if [ -n "$1" ]; then - spec="" - for s in $BENCHES; do [ "${s%%:*}" = "$1" ] && spec="$s"; done - [ -n "$spec" ] || { echo "unknown benchmark: $1 (have: ${BENCHES})" >&2; exit 1; } - run_one "$spec" "$2" -else - echo "jolt benchmark suite — optimized AOT binaries${NO_JVM:+ }${NO_JVM:-, vs JVM Clojure}" - for spec in $BENCHES; do run_one "$spec"; done -fi diff --git a/bin/joltc b/bin/joltc deleted file mode 100755 index 8b3bb2a..0000000 --- a/bin/joltc +++ /dev/null @@ -1,41 +0,0 @@ -#!/bin/sh -# joltc — the pure-Chez jolt runtime. NO Janet. -# -# Compiles and evaluates jolt (Clojure) on Chez using the checked-in bootstrap -# seed (host/chez/seed/). With only Chez installed it runs jolt end to end: -# -# joltc -e "(+ 1 2)" evaluate an expression -# joltc run -m app.core [args] resolve deps.edn, run a namespace's -main -# joltc -M:alias [args] run an alias's :main-opts -# joltc repl | path | REPL, print roots, or a deps.edn task -# -# The launcher cd's to the jolt repo root so the runtime's relative loads work; -# the user's original cwd (the project dir, where deps.edn lives) is passed in -# JOLT_PWD. -root="$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)" -export JOLT_PWD="${JOLT_PWD:-$PWD}" - -# Identify the Chez Scheme executable -while read -r CHEZ -do - if [ `which ${CHEZ}` ] - then - break; - fi -done </dev/null || echo dev)}" -cd "$root" || exit 1 -exec ${CHEZ} --script host/chez/cli.ss "$@" - diff --git a/doc/building-and-deps.md b/doc/building-and-deps.md new file mode 100644 index 0000000..fa6a499 --- /dev/null +++ b/doc/building-and-deps.md @@ -0,0 +1,117 @@ +# Building and dependencies + +How to build Jolt from source and how to pull Clojure libraries into a project. + +## Building + +```bash +git clone https://github.com/jolt-lang/jolt.git +cd jolt +git submodule update --init # vendor/sci (used by the SCI bootstrap tests) +jpm build +``` + +This produces two executables under `build/`: + +- **`jolt`** — the runtime: REPL, file/expr runner, nREPL server. The whole `.clj` + standard library (`clojure.string`/`set`/`walk`/`edn`/`zip`, `jolt.http`/ + `interop`/`shell`/`nrepl`) is baked into this binary at build time, so it loads + from any directory — the build artifact is self-contained. (`clojure.core` is + built into the runtime in Janet and auto-referred, so it's always available.) +- **`jolt-deps`** — a separate tool that resolves a `deps.edn` (see below). It + sits beside the runtime the way `jpm` sits beside `janet`; the runtime itself + knows nothing about deps.edn. + +Needs `jpm` and a recent Janet — developed and CI-tested against **1.41**. The +futures and core.async layers use Janet's threaded `ev/` channels (`ev/thread`, +`ev/thread-chan`), so older Janets may not run the full suite. + +`jpm build` doesn't always notice source changes; run `jpm clean && jpm build` +after editing `src/` to be sure the binaries are current. `jpm test` runs against +the source directly, so it never goes stale. + +## How namespaces are found + +`(require ...)` resolves a namespace to a file by searching an ordered list of +source roots — the stdlib first, then any extra roots — trying `.clj` then +`.cljc` (dots become directories, dashes become underscores). Extra roots +come from: + +- `JOLT_PATH` — a colon-separated list of directories (like a classpath), applied + at runtime; +- the `:paths` option to `init` when embedding Jolt as a library. + +If a namespace isn't found on any root, the loader falls back to the stdlib baked +into the binary — that's how `clojure.string` and friends resolve when you run +the binary outside the source tree. + +So you can point Jolt at a directory of Clojure source with no deps machinery at +all: + +```bash +JOLT_PATH=/path/to/lib/src build/jolt myfile.clj +``` + +## Dependencies via deps.edn + +`jolt-deps` reads a `deps.edn` in the current directory, fetches its +dependencies, and runs `jolt` with the resolved source directories on +`JOLT_PATH`. + +```bash +jolt-deps path # print the resolved roots (':'-joined) +jolt-deps run FILE [args] # resolve, then run `jolt FILE …` +jolt-deps repl # resolve, then start a REPL +jolt-deps -e EXPR [args] # resolve, then evaluate EXPR +``` + +`jolt-deps` launches the `jolt` binary it finds on `PATH` (override with +`$JOLT_BIN`). + +Example `deps.edn`: + +```clojure +{:paths ["src"] + :deps {weavejester/medley {:git/url "https://github.com/weavejester/medley" + :git/tag "1.0.0"} + my/helpers {:local/root "../helpers"}}} +``` + +```bash +jolt-deps run -m myapp.main +``` + +### What's supported + +- **git deps** — `{:git/url … :git/tag …}` or `{:git/url … :git/sha …}` (use a + full SHA; `git fetch` can't resolve a short one). Transitive deps from each + dependency's own `deps.edn` are resolved too. +- **local deps** — `{:local/root "../path"}`. +- The project's own `:paths` (default `["src"]`) are included. + +Resolution reuses jpm's git fetch and cache (a dependency is cloned once into +`jpm_tree/.cache` and reused). Resolved roots are cached on a hash of `deps.edn`, +so an unchanged `deps.edn` doesn't re-fetch. + +### What's not + +- **No Maven.** `:mvn/version` deps are ignored — git and local only. +- **Pure `clj`/`cljc` only.** A library that needs the JVM (Java interop, host + classes) or a `clojure.core` feature Jolt doesn't implement will fail to load + or fail at a call. Coverage is per-function: a namespace can load with most + functions working and a few not. + +### Bundling into one file + +`jolt uberscript OUT.clj -m NS` (or `jolt-deps uberscript …`, which resolves deps +first) bundles `NS` and every namespace it requires — your code plus its +dependencies — into a single `.clj` in dependency order, ending with a call to +`NS/-main`. The result runs on a plain `jolt` with no `JOLT_PATH`, no deps +fetched, and no jpm: + +```bash +jolt-deps uberscript app.clj -m myapp.main +jolt app.clj arg1 arg2 +``` + +See [`tools-deps.md`](tools-deps.md) for the design rationale. diff --git a/docs/grammar.ebnf b/doc/grammar.ebnf similarity index 82% rename from docs/grammar.ebnf rename to doc/grammar.ebnf index 874907a..dffffb1 100644 --- a/docs/grammar.ebnf +++ b/doc/grammar.ebnf @@ -3,11 +3,10 @@ =========================================================================== This grammar specifies the surface syntax accepted by Jolt's reader - (host/chez/reader.ss, with the portable half in jolt-core/jolt/reader.clj) — - the text that `read`/`read-string`/`load-string` turn into data/forms. It is - the syntactic half of Jolt's contract; the behavioural half lives in the - conformance corpus (test/chez/corpus.edn, see docs/spec/02-reader.md). Where - Jolt diverges from Clojure the difference is called out in a comment. + (src/jolt/reader.janet) — the text that `read`/`parse-string`/`load-string` + turn into data/forms. It is the syntactic half of Jolt's contract; the + behavioural half lives in test/spec/. Where Jolt diverges from Clojure the + difference is called out in a comment. Notation (ISO-ish EBNF): = definition | alternation @@ -51,12 +50,11 @@ collection = list | vector | map ; nil = "nil" ; boolean = "true" | "false" ; -(* Numbers. Jolt carries a real numeric tower (JVM parity): an integer literal - reads as an exact integer (arbitrary precision), a ratio a/b as an exact - Ratio, a decimal/exponent literal as a double. The BigDecimal suffix M reads - as a real BigDecimal (unscaled x 10^-scale) — 1.5M, 0.0M, 3M; class is - java.math.BigDecimal. The BigInt suffix N reads as an exact integer. Radixed - integers are computed by base; the symbolic floats ##Inf/##-Inf/##NaN are +(* Numbers. Jolt accepts Clojure's numeric literal syntaxes, but — since Jolt + numbers are Janet ints/doubles — it has no distinct bignum, ratio or + BigDecimal types: the BigInt suffix N and BigDecimal suffix M are read as the + plain number, a ratio a/b is read as its double quotient, and radixed + integers are computed by base. The symbolic floats ##Inf/##-Inf/##NaN are also read. (No octal-with-leading-0 literal.) *) number = symbolic-value | [ sign ] , ( radix-int | ratio | hex-int | decimal ) ; @@ -64,10 +62,10 @@ sign = "+" | "-" ; integer = digit , { digit } ; hex-int = "0" , ( "x" | "X" ) , hex-digit , { hex-digit } , [ "N" ] ; radix-int = integer , ( "r" | "R" ) , alnum , { alnum } ; (* base 2..36: 2r1010, 16rFF, 36rZ *) -ratio = integer , "/" , integer ; (* exact Ratio *) +ratio = integer , "/" , integer ; (* read as a double quotient *) decimal = integer , [ "." , digit , { digit } ] , [ exponent ] , [ num-suffix ] ; exponent = ( "e" | "E" ) , [ sign ] , digit , { digit } ; -num-suffix = "N" | "M" ; (* N = exact integer (BigInt); M = BigDecimal *) +num-suffix = "N" | "M" ; (* BigInt / BigDecimal in Clojure; plain number in Jolt *) symbolic-value = "##Inf" | "##-Inf" | "##NaN" ; digit = "0".."9" ; hex-digit = digit | "a".."f" | "A".."F" ; @@ -111,7 +109,7 @@ map-entry = form , ws , form ; (* an even number of forms *) (* -------------------------------------------------------------------------- Reader macros (prefix sugar). Each expands to a 2-element form - (op operand), e.g. 'x -> (quote x), @a -> (clojure.core/deref a). + (op operand), e.g. 'x -> (quote x), @a -> (deref a). -------------------------------------------------------------------------- *) reader-macro = quote | syntax-quote | unquote | unquote-splice @@ -121,17 +119,13 @@ quote = "'" , form ; (* (quote form) *) syntax-quote = "`" , form ; (* (syntax-quote form) *) unquote-splice = "~@" , form ; (* (unquote-splicing form) *) unquote = "~" , form ; (* (unquote form) *) -deref = "@" , form ; (* (clojure.core/deref form) — qualified, *) - (* so it derefs even where deref is shadowed *) +deref = "@" , form ; (* (deref form) *) metadata = "^" , meta-form , ws , form ; (* attach metadata to form *) meta-form = map | keyword | symbol | string ; (* Normalized like Clojure: a symbol or string is a type hint -> {:tag ...}; - a keyword -> {keyword true}; a map is used as-is. A keyword/symbol/string - meta-form on a symbol rides ON the symbol (it stays a bare symbol, so a hint - like ^String is transparent in params/lets/bodies). A MAP meta-form routes - through a runtime (with-meta form ...) even on a symbol, so a name - with ^{:map} metadata reads as a form, not a bare symbol — def/defn/defmacro/ns - unwrap that to the bare name (and attach the metadata). *) + a keyword -> {keyword true}; a map is used as-is. On a symbol the metadata + rides on the symbol (it stays a bare symbol, so a hint like ^String is + transparent in params/lets/bodies); other targets use a runtime with-meta. *) (* -------------------------------------------------------------------------- Dispatch forms — introduced by "#". @@ -153,7 +147,7 @@ anon-arg = "%" | "%" , digit , { digit } | "%&" ; var-quote = "#'" , symbol ; (* (var symbol) *) -(* Regex literal -> an irregex-backed regex value. +(* Regex literal -> a Janet PEG-backed regex value. Supported: groups, greedy/lazy quantifiers, (?:..), lookahead (?=..)/(?!..), alternation, anchors ^ $ \b \B, classes, (?i). NOT: lookbehind, backreferences, named groups. *) diff --git a/doc/self-hosting-architecture.md b/doc/self-hosting-architecture.md new file mode 100644 index 0000000..e208b87 --- /dev/null +++ b/doc/self-hosting-architecture.md @@ -0,0 +1,138 @@ +# Self-hosting architecture: portable jolt-core over a host runtime + +Design for splitting Jolt into a **portable Clojure-in-Clojure core** and a +**host runtime** (Janet today, another runtime tomorrow), so the language is +truly self-hosted and `jolt-core` can be lifted out and re-hosted. + +This is the design that must be right *before* writing the compiler in Clojure — +see [[self-hosting-compiler]] for the staged plan it plugs into. + +## What "truly self-hosted + portable" requires + +Two independent properties: + +1. **Self-hosted** — the compiler and most of `clojure.core` are written in + Clojure and compiled by Jolt itself. +2. **Portable** — that Clojure code (`jolt-core`) depends only on a small, + explicit **host contract**, never on Janet directly. Re-hosting means + implementing the contract for a new runtime; `jolt-core` is reused verbatim. + +The enemy is `jolt-core` calling `janet/tuple`, `make-vec`, `ns-find`, etc. +directly — that welds it to Janet. Every host dependency must go through the +contract. + +## Prior art (the seam everyone uses) + +- **Clojure (JVM).** `clojure.lang.*` (Java) is the host: `RT`/`Numbers` runtime + helpers, the `Compiler` (form → JVM bytecode), persistent data structures, + `Var`/`Namespace`, the reader. `clojure/core.clj` is the language, in Clojure. + Seam: ~20 primitive special forms + `RT` static methods. Everything else is + Clojure. +- **ClojureScript (self-hosted).** Two portable passes — `cljs.analyzer` + (form → AST **as data**, reading a **compiler-state map** of + namespaces/defs/macros, *not* host objects) and `cljs.compiler` (AST → JS, the + host-specific back end). `cljs.core` is Clojure compiled to JS. Platform splits + live in `.cljc` reader conditionals. This is the closest model to what we want: + **the analyzer is host-agnostic; only the back end and the runtime are + host-specific.** +- **Nanopass / Guile Tree-IL.** A high-level IR is the portability seam; multiple + back ends consume it. +- **ClojureCLR / ClojureDart / jank.** Same shape every time: portable analyzer + + host back end + host runtime. + +The invariant across all of them: **the IR (analyzer output) and a small runtime +protocol are the contract; the front end is portable, the back end and runtime +are per-host.** + +## Decisions (locked) + +- **Seam = a minimal host protocol.** `jolt-core` calls a small documented set of + host fns (in ns `jolt.host`): `resolve-sym`, `macro?`, `macroexpand-1`, + `current-ns`, `intern!`, plus the `RT` primitives. Each host provides `jolt.host` + (+ RT). Re-hosting = reimplement that handful of fns. The protocol *is* the + boundary; `jolt-core` never touches Janet directly. +- **Physical split now.** Portable Clojure lives under `jolt-core/` (a new source + root, embedded into the binary like the rest of the stdlib); host Janet code for + the new pipeline under `host/janet/`. Legacy host modules under `src/jolt/*.janet` + are the existing Janet host and get relocated under `host/janet/` in a later + mechanical pass (tracked) — not moved big-bang now, to keep the suite green. + +## The Jolt split + +``` +jolt-core/ PORTABLE Clojure — no Janet. Depends only on the contract. + ir the IR spec (data shapes the analyzer emits) + analyzer form -> IR (macroexpands; resolves via host protocol) + macros when/cond/->/defn/... (the macro library, in Clojure) + core clojure.core fns expressible in Clojure, over RT primitives + +host/janet/ THE HOST — Janet. Implements the contract. + reader text -> jolt forms + rt data structures + RT primitive fns (cons/first/+/get/apply…) + backend IR -> Janet forms -> Janet compile -> bytecode (the emitter) + cenv the compile-time host protocol impl (resolve/macro?/intern) + bootstrap load jolt-core, wire analyzer+backend into the loader + interop janet.* bridge +``` + +Two contracts cross the seam: + +### 1. The IR (analyzer → back end) +The existing `:op`-tagged AST, made **host-neutral**: +- `{:op :const :val v}`, `:if`, `:do`, `:let`, `:fn` (arities), `:invoke`, + `:vector`/`:map`/`:set`, `:quote`, `:throw`/`:try`, `:loop`/`:recur`. +- **Globals reference vars by NAME, not by host cell:** + `{:op :var :ns "clojure.core" :name "map"}`. (compiler.janet today embeds the + Janet var cell as a constant — that's a host leak and breaks AOT. Name-based + refs are both portable and AOT-friendly; the back end resolves the cell.) +- No embedded host function values. Calls to runtime primitives are + `{:op :rt :name "cons"}` resolved by the back end to the host's RT fn. + +### 2. The host contract (two protocols) +- **Compile-time (`cenv`)** — what the analyzer needs from the host while + analyzing: `(current-ns)`, `(resolve-sym sym) -> {:kind :var|:macro|:local|:special|:host, :ns, :name}`, + `(macroexpand-1 form)`, `(intern! ns sym meta)`. The analyzer calls only these; + it never touches Janet ns/var tables. (CLJS keeps this as pure data; we use a + small protocol — a minimal, documented boundary — because Jolt already has live + ns/var objects. The protocol *is* the seam.) +- **Runtime (`RT`)** — the primitive fns emitted code and `jolt-core` call by + stable name: arithmetic/compare, `cons/first/rest/seq/conj/get/assoc/count`, + `apply`, `=`, vector/map/set constructors, var deref/bind, keyword/symbol + construction. The back end maps each to the host (on Janet, mostly the existing + `core-*`). To re-host, implement this set. + +## Why name-based vars (not embedded cells) + +`compiler.janet` compiles a global ref to a closure over the Janet var cell. That +(a) is a Janet value baked into the IR — not portable, and (b) can't be marshaled +for AOT without the runtime-dict trick. Compiling instead to *resolve var by +(ns,name) at call time* through an RT primitive keeps redefinition live, makes the +IR host-neutral, and makes images trivially portable. The per-call lookup is the +cost; it can be cached/direct-linked later as an opt-in optimization. + +## Bootstrap & staging (keeps the suite green throughout) + +`compiler.janet` stays as the **bootstrap back end** until the Clojure pipeline is +proven. Order: + +1. **Freeze the IR** spec and refactor `compiler.janet`'s emit to consume + name-based `:var` (no behavior change; bootstrap still works). +2. **Define the host contract** (`cenv` + `RT`) and implement it on Janet, + exposed under a stable namespace the Clojure core can call. +3. **Write `jolt.analyzer` in Clojure** producing IR, against `cenv`. Diff its IR + against the Janet analyzer on the conformance corpus until identical. +4. **Janet back end consumes IR** from the Clojure analyzer; wire into the loader + behind a flag. Validate at parity (dual-mode conformance + clojure-test-suite). +5. **Flip** the loader to the Clojure analyzer + Janet back end; `compiler.janet` + shrinks to the back end only. +6. **Move `clojure.core`** macros then fns into `jolt-core` incrementally, each + compiled by the prior stage, isolating host bits behind `RT`. + +Guards at every step: the dual-mode conformance harness (interpret vs compile) +and the clojure-test-suite baseline. + +## The portability test + +When done, re-hosting Jolt to runtime X means writing only: `host/X/{reader, rt, +backend, cenv, bootstrap}`. `jolt-core/{ir, analyzer, macros, core}` is reused +unchanged. That is the concrete bar for "truly self-hosted and portable." diff --git a/doc/self-hosting-compiler.md b/doc/self-hosting-compiler.md new file mode 100644 index 0000000..ea21c56 --- /dev/null +++ b/doc/self-hosting-compiler.md @@ -0,0 +1,172 @@ +# Toward a self-hosting Jolt compiler + +Research and design notes for evolving Jolt from "interpreter + opt-in ad-hoc +compiler" toward a self-hosting Clojure-in-Clojure compiler that emits Janet +bytecode, keeps full REPL live-redefinition, and rests on a minimal Janet +bootstrap. This is a design doc, not a changelog — it describes where we are, the +prior art, the constraints we verified, and a recommended path. + +## The goal + +- **Self-hosting, Clojure-in-Clojure.** A small kernel in the host (Janet) is + enough to start; the rest of Clojure — including the compiler — is written in + Clojure and compiled by Jolt itself, growing the language as it compiles more + of itself. +- **Janet bytecode out.** Compiled code runs as native Janet bytecode (fast), + not tree-walking. +- **Full runtime flexibility.** `def`/`defn` redefinition, vars, protocols, + multimethods, and everything else stay live and redefinable at the REPL even + for compiled code. +- **Minimal host requirement.** Shrink what must exist in Janet to the + irreducible base. + +## Where Jolt is today + +- ~5,500 lines of **Janet** implement `clojure.core` (`core.janet`) and a + tree-walking interpreter (`evaluator.janet`); ~1k lines of **Clojure** are the + stdlib (`clojure.string/set/walk/…`, `jolt.*`). So the language is mostly in + the host, inverted from the Clojure-in-Clojure ideal. +- The interpreter (`eval-form`) is the complete reference path. +- The compiler (`compiler.janet`) — `analyze-form` (reader form → `:op` AST) → + `emit` (AST → Janet form) → Janet `compile`/`eval` — is now **on by default** + in the shipped runtime (`JOLT_INTERPRET=1` opts out). It is a *hybrid*: forms + it can't compile correctly throw `jolt/uncompilable` and fall back to the + interpreter (`loader/eval-toplevel`), so results always match the interpreter. + Validated at parity — conformance 218/218 under both interpret and compile, and + the clojure-test-suite under compile passes 3932 (vs the 3913 interpreter + baseline) across ~4.6k assertions. +- Done so far: var-indirection (globals deref through var cells, so compiled code + is REPL-redefinable); hybrid fallback; compilation of multi-arity / named / + variadic fns and `recur` inside `fn`; map and vector literal compilation + (mode-correct via `make-vec` / `build-map-literal`); resolution that mirrors + the interpreter (current ns → `clojure.core` → Janet-env fallback); and AOT + (`aot.janet`) that marshals a compiled namespace to a Janet bytecode image + against the baked-in runtime dictionary and loads it back. +- Still open — the actual self-hosting: the compiler and most of `clojure.core` + are still Janet. Rewriting them in Clojure (compiled by Jolt) is the remaining + Clojure-in-Clojure work. + +## What the host gives us (verified) + +Janet already is the backend and the AOT story — we don't need a custom bytecode +emitter: + +- `(compile form env source)` → a **function** (compiled bytecode). Jolt's job is + Clojure form → correct Janet form → `compile`. +- `marshal`/`unmarshal`, `make-image`/`load-image` → serialize a compiled + environment to a **bytecode image** and load it back: this is Phase 4 AOT. +- `asm`/`disasm` → bytecode assembler/disassembler if we ever want to bypass the + form layer (we shouldn't need to). + +**The catch we verified:** Janet *early-binds* top-level references. Compile +`(defn caller [] foo)`, then redefine `foo` — the compiled `caller` still returns +the old value. So emitting Jolt globals as plain Janet symbols (what the current +compiler largely does) is fundamentally incompatible with REPL redefinition. This +is the single most important design constraint below. + +## Prior art + +- **Clojure (JVM).** A Java runtime + compiler bootstraps `clojure.core`, which is + written in Clojure; thereafter Clojure compiles Clojure to JVM bytecode. Only + ~20 special forms are primitive; everything else is macros/functions. Crucially, + compiled call sites go **through Var objects** (a deref), so redefining a var is + visible to existing compiled callers — that's how speed and live redefinition + coexist. Clojure 1.8 added opt-in **direct linking** (inline the call, drop the + var indirection) for speed where you don't need redefinition (used for core in + production). AOT compiles namespaces to `.class` files. +- **ClojureScript self-hosting.** Two stages: an **analyzer** (source → AST plus + a "compiler state" map of namespaces/defs/macros) and a **compiler** (AST → JS). + `cljs.js` exposes compile/eval at runtime; bootstrapped CLJS compiles CLJS at + ~2× the JVM compiler. The host VM (JS engine) is the backend — the same shape we + want with Janet as the backend. +- **Nanopass (Chez Scheme).** A compiler as *many small passes* over *formally + specified* intermediate languages, with autogenerated boilerplate to recur + through unchanged forms and checks that each pass's output matches its grammar. + The lesson for "grow the language as it compiles itself": keep passes small and + IRs explicit so adding a form is local and verifiable. +- **Guile.** A Lisp on a bytecode VM: source → Tree-IL (high-level IR) → CPS + (optimization IR) → VM bytecode, with several front-end languages targeting + Tree-IL. The closest analog to "Lisp → bytecode on a VM." + +## Assessment: is the current approach the right one? + +The overall *shape* is right and matches ClojureScript: front-end (analyze → +emit) with the host VM as the backend, emitting host forms that the host compiles +to bytecode. Two things need to change to reach the goal: + +1. **Late binding for globals.** Compile a reference to a Jolt var as a **deref + through the var cell**, not as a Janet symbol. Jolt vars are already cells + (`{:jolt/type :jolt/var :root …}`); a compiled global call becomes roughly + `((var-root cell) args…)` instead of `(janet-symbol args…)`. Redefinition + updates the cell's root, so compiled callers see it — exactly Clojure's model. + One indirection per global call; locals and control flow stay direct and fast. + Offer opt-in **direct linking** for hot/AOT code that doesn't need redefinition. +2. **Move the compiler and core into Clojure.** Today both are Janet. Self-hosting + means the compiler is Clojure compiled by Jolt, and most of `clojure.core` is + Clojure. That's the bulk of the work and where the "language builds itself" + payoff lives. + +So: keep the emit-to-Janet target (it's correct and gives us bytecode + AOT for +free), fix global binding, and progressively self-host. + +## Recommended architecture + +**Pipeline (nanopass-lite).** Keep the data-driven `:op` AST and grow it as small, +named passes rather than one big walker: + +1. *read* — reader → forms (already have it). +2. *macroexpand* — fully expand to special forms + calls (the interpreter already + expands; share one expander). +3. *analyze* — forms → AST, resolving locals vs vars and tagging ops. +4. *(optional) optimize* — constant-fold, direct-link hot calls, etc. +5. *emit* — AST → Janet form, with globals as var-cell derefs. +6. *compile* — Janet `compile` → bytecode; `make-image` for AOT. + +Make each pass total over the IR so an unhandled node is an explicit gap, not a +silent miss. + +**The kernel (minimal Janet bootstrap).** The irreducible base that must exist in +the host before any Clojure can run: the reader; the value/representation layer +(vars, namespaces, symbols, keywords, persistent collections, chars); host +interop (the `janet.*` bridge); `fn`/`if`/`do`/`let`/`quote`/`def`/`loop`/`recur` +evaluation; and `compile`/`eval`. Everything else — the rest of `clojure.core`, +the macros, and the compiler — is Clojure loaded and (eventually) compiled by the +kernel. Today the kernel is far larger than this; shrinking it is a long game. + +**Hybrid interpret/compile (Phase 3, and a bootstrap safety net).** When a pass +can't yet compile a sub-form, emit a call back into the interpreter (`eval-form`) +for that sub-form instead of erroring. This lets the compiler be incomplete and +still correct (hot paths compile, cold/unsupported paths interpret), lets us grow +coverage incrementally, and de-risks the self-hosting bootstrap. + +**Live flexibility.** Vars stay first-class cells; compiled code derefs them; +`def` updates the root; protocol/multimethod dispatch stays dynamic. Direct +linking is opt-in, never the default, so the REPL is always live. + +## A staged path + +1. **Var-indirection in the emitter** — *done*. Global refs compile as var-cell + derefs, so a compiled `defn` is redefinable at the REPL. +2. **Hybrid fallback + coverage** (`jolt-1bj`) — *done*. Forms the compiler can't + compile throw `jolt/uncompilable` and fall back to the interpreter, so compile + mode is always correct. Covered: multi-arity/named/variadic fns, `recur` in + `fn`, map/vector literals, and resolution matching the interpreter. + Destructuring compiles via the shared `destructure` expander: the `fn`/`let`/ + `loop`/`defn` macros desugar to plain-symbol `fn*`/`let*`/`loop*`, so it no + longer falls back — and the primitives reject patterns outright, matching + Clojure (`jolt-f79`). +5. **Compile-by-default + AOT** (`jolt-7j9`) — *done, done out of order*. Once the + hybrid path was validated at parity, compilation was flipped on by default and + AOT images (`aot.janet`) landed. Done before 3–4 because it's the runtime + payoff and only needed the hybrid path to be correct, not self-hosting. +3. **Self-host the compiler** (`jolt-lcn`) — *open*. Rewrite `compiler.janet` as + Clojure (`jolt.compiler`) that Jolt compiles. Now the compiler is part of the + language it compiles. +4. **Shrink the kernel / core-in-Clojure** (`jolt-uqi`) — *open*. Move + `clojure.core` from Janet to Clojure incrementally, each piece compiled by the + previous stage — the language building itself — leaving a minimal Janet kernel. + +What remains (3 and 4) is the actual Clojure-in-Clojure rewrite: the largest part +of the work and where the "language builds itself" payoff lives. The correctness +and runtime foundations it needs — redefinable compiled code, an always-correct +hybrid path, compile-by-default, and AOT — are now in place. diff --git a/doc/tools-deps.md b/doc/tools-deps.md new file mode 100644 index 0000000..77f1e20 --- /dev/null +++ b/doc/tools-deps.md @@ -0,0 +1,91 @@ +# deps.edn support — design notes + +How Jolt loads pure-Clojure libraries from a `deps.edn`, and why it's built the +way it is. For how to *use* it, see [building-and-deps.md](building-and-deps.md). + +Scope, decided up front: + +- **git + local deps only** — no Maven/`~/.m2` resolution. +- **pure `clj`/`cljc`** — anything needing the JVM won't load or run; expected. +- **no classpath abstraction** — `require` just needs to find a dep's namespaces; + "the classpath" is an ordered list of source directories. +- **piggyback on jpm** — reuse jpm's git fetch + cache; don't write a package + manager. +- **separate tool** — resolution lives in `jolt-deps`, beside the runtime, the + way `jpm` sits beside `janet`. The `jolt` runtime knows nothing about deps.edn. + +## How jpm handles dependencies + +jpm's package code (`jpm/pm.janet`) splits into a fetch half and a build half, +and we use only the first: + +- **`resolve-bundle`** normalizes a dep spec to `{:url :tag :type :shallow}`, + accepting `:url`/`:repo` + `:tag`/`:sha`/`:commit`/`:ref`. A deps.edn + `{:git/url … :git/sha …}` maps straight onto it. +- **`download-bundle url :git tag shallow`** clones into a content-addressed cache + (`/.cache/git__`) and returns the path — + `git init` + `remote add` + fetch + reset, plus submodules. No build step. +- **`bundle-install`** is the half we skip: it then runs `project.janet` build + rules, which a Clojure lib doesn't have. It's cleanly separable from the clone. + +So jpm gives us git resolution and a cache for free; calling `download-bundle` +needs `jpm/config/load-default` first (it sets `gitpath` and the cache dyns). + +## How it works + +`src/jolt/deps.janet` reads `deps.edn` (Janet parses it directly — EDN and Janet +syntax overlap for the `:deps`/`:paths` subset), then walks `:deps`: + +- `:git/url` (+ `:git/sha` or `:git/tag`) → `resolve-bundle` + `download-bundle` + into `jpm_tree/.cache`; +- `:local/root` → the path as-is; +- `:mvn/*` and anything else → ignored. + +Each resolved dependency contributes its own `:paths` (default `["src"]`) as +source roots, and we recurse into its `deps.edn` for transitive deps. The result +is a de-duplicated, ordered list of directories. `resolve-deps-cached` memoizes +that list in the tree keyed on a hash of `deps.edn`, so an unchanged file doesn't +re-fetch. jpm is loaded lazily (`require`, not `import`) so it's pulled in only +when resolving — never embedded in a built binary. + +The loader (`evaluator.janet/find-ns-file`) resolves a namespace by searching the +context's `:source-paths` in order (the stdlib `src/jolt` first), trying `.clj` +then `.cljc`. Extra roots come from `JOLT_PATH` or `init`'s `:paths` option. + +`jolt-deps` (`src/jolt/deps_cli.janet`, its own `declare-executable`) ties it +together: it resolves the roots and runs the `jolt` binary with them on +`JOLT_PATH`. The runtime's only dependency interface is that env var. + +`jolt uberscript` bundles a namespace and everything it requires into one +standalone `.clj`. It requires the entry namespace and uses the order in which +the loader finishes loading files — a dependency finishes before the file that +required it, so the order is topological — then concatenates that source. The +baked-in stdlib is excluded (it's part of the runtime, not bundled). + +Gotcha worth remembering: the `jolt` CLI's context is built into its image at +build time, so `JOLT_PATH` is applied at runtime in `main`, not in `init` (whose +env read would be frozen at build). + +## Limitations + +- Pure `clj`/`cljc` only — JVM interop, host classes, and unimplemented + `clojure.core` corners fail. Coverage is per-function: a namespace can load with + most functions working and a few not. +- Source only; compiled `.class` files in a git dep are ignored. +- git `:git/sha` must be a full SHA (`git fetch` can't resolve a short one). + +## Conformance + +`test/integration/deps-conformance-test.janet` resolves a few real pure-`cljc` +git libraries and reports whether their namespaces load and a sample call works. +It's network-gated behind `JOLT_CONFORMANCE=1` so CI stays offline. Use it to +check a library against the current interpreter, and to drive fixes for whatever +gap a failure points at (the same loop as the clojure-test-suite battery). A +library fails when it relies on something Jolt doesn't provide — JVM interop, or +a regex feature like Unicode property classes (`\p{…}`). + +## Not yet + +- **Compiling deps into a binary image.** `uberscript` already produces a + standalone `.clj`; baking a project's dependencies directly into a custom + executable image is a heavier variant that isn't implemented. diff --git a/docs/MODULES.md b/docs/MODULES.md deleted file mode 100644 index 6fc5253..0000000 --- a/docs/MODULES.md +++ /dev/null @@ -1,97 +0,0 @@ -# Module map - -Where things live and what to read before changing them. Start here to answer -"where does feature X live?" and "what else do I need to touch?" - -## Areas - -| Area | Directory | Responsibility | Re-mint? | -| --- | --- | --- | --- | -| Chez runtime | `host/chez/*.ss` | The substrate: value model, persistent collections, seqs, vars/namespaces, host interop, native `clojure.core` shims, regex, FFI, IO, the **reader**. Composed by `rt.ss`. | only `reader.ss` | -| Compiler | `jolt-core/jolt/*.clj` | analyzer → IR → backend, the optimization passes, the CLI, the deps resolver, nREPL. Baked into the seed. | **yes** | -| `clojure.core` overlay | `jolt-core/clojure/core/NN-*.clj` | Portable `clojure.core` in dependency-ordered tiers (`00-syntax` … `50-io`); the `NN` prefix *is* the load order. | **yes** | -| Stdlib | `stdlib/clojure/*.clj` | Lazily-loaded portable namespaces (string/set/walk/edn/pprint/zip/test/data). | no | -| Build & tooling | `host/chez/build.ss`, `emit-image.ss`, `compile-eval.ss`, `loader.ss`, `cli.ss`, `bootstrap.ss` | AOT binary build, cross-compile, runtime eval/load, CLI spine, seed mint. | no (except via `reader.ss`) | -| Tests & gate | `test/chez/`, `test/conformance/`, `host/chez/run-*.ss`, `Makefile` | Corpus (JVM oracle), unit, per-feature tests. Every `make` target has a comment. | no | - -**The reader is in `host/chez/reader.ss`** (Scheme, a seed source) — *not* in -`jolt-core/jolt/` with the rest of the compiler. Re-mint applies to it. - -`rt.ss` is the runtime's load-order manifest: it `(load …)`s every shim in -dependency order with a per-file comment. Read it to see how the runtime is -composed and where a given `.ss` fits. - -## `host/chez/*.ss` by family - -- **Value model**: `values.ss` (nil/numbers/keywords/symbols), `collections.ss` - (persistent vec + HAMT map/set), `seq.ss` + `lazy-bridge.ss` (seqs, lazy-seqs), - `transients.ss`, `records.ss` + `records-interop.ss`. -- **Native `clojure.core` shims**: `natives-*.ss` (array/coll/format/meta/misc/num/ - queue/reader/seq/str/transduce), plus `predicates.ss`, `converters.ss`, `printing.ss`. -- **Vars / namespaces / dynamics**: `vars.ss`, `ns.ss`, `dyn-binding.ss` (the - thread-local binding stack), `dynamic-var-defaults.ss` (a few `*…*` constant defaults), - `atoms.ss`, `multimethods.ss`. -- **Host interop**: `host-class.ss` (class tokens + method dispatch), - `host-static.ss` (interop registry core) + `host-static-methods.ss` (`Class/member` - statics) + `host-static-classes.ss` (instantiable object classes), `host-table.ss`, - `host-contract.ss` (the `jolt.host` seam the compiler resolves against), - `dot-forms.ss`, `records-interop.ss`. -- **Scalars / misc**: `regex.ss` (vendored irregex), `math.ss`, `inst-time.ss`, - `bigdec.ss`, `syntax-quote.ss`. -- **IO / system / concurrency / FFI**: `io.ss`, `png.ss`, `concurrency.ss`, - `async.ss`, `ffi.ss`. -- **Compiler entry on Chez**: `reader.ss`, `compile-eval.ss`, `emit-image.ss`, - `loader.ss`, `cli.ss`, `build.ss`, `bootstrap.ss`. - -## Where is a `clojure.core` fn implemented? - -Two homes, with a defined precedence: - -1. **Native shim** — a `(def-var! "clojure.core" "name" …)` in a `host/chez/*.ss` - (hot/representation-coupled fns: `first`, `get`, `=`, the predicates). -2. **Overlay** — a `defn` in a `jolt-core/clojure/core/NN-*.clj` tier (most of - `clojure.core`, in portable Clojure). -3. **`post-prelude.ss`** re-asserts a handful of natives *after* the overlay loads, - so the native version wins (the overlay's value-reading versions are wrong for - Chez-native chars/atoms/etc.). Each entry there says why. - -`grep 'def-var! "clojure.core" "frequencies"' host/chez` and -`grep -rn 'defn frequencies' jolt-core/clojure/core` to find a given fn. See -[seed-overlay-registry.md](seed-overlay-registry.md) for the shadowing mechanism. - -## Cross-cutting features — touch points - -A feature's *core* lives in one file; these are the other files you must keep in -sync when changing it. - -- **Tree-shaking / DCE** (`--tree-shake`): `emit-image.ss` (the `dce-*` helpers + - record producers) and `build.ss` (`bld-shake-all` reachability + the manifest - splice in `bld-emit-runtime`); the flag in `main.clj`; validated by - `host/chez/tree-shake-smoke.sh` (`make shakesmoke`) and `build-smoke.sh`. See - [tools-deps.md](tools-deps.md#tree-shaking). -- **Direct-linking** (`--direct-link`): `backend_scheme.clj` (`direct-link?`, - `emit-top-form`, the `jv$` bindings); `build.ss` turns it on; `main.clj` the - flag; `test/chez/directlink-test.ss`. -- **Numeric fl*/fx\*** (`^double`/`^long` hints): `jolt-core/jolt/passes/numeric.clj` - (the hint-directed pass + loop-counter + `:coerce`); `backend_scheme.clj` - (`dbl-ops`/`lng-ops` op strings, `emit-numeric`, entry/return coercion); - `analyzer.clj` (`nhint-of`, `:nhints`, `with-ret-nhint`); `host-contract.ss` - (`:num-ret` on resolve); `rt.ss` (`jolt->fx`); `test/chez/numeric-test.ss`. -- **IR inlining** (under `--opt`): `passes/inline.clj` (splice) + `passes.clj` - (stash) + `host-contract.ss` (`inline-ir`/`stash-inline!`); `test/chez/inline-test.ss`. -- **Multimethods**: `host/chez/multimethods.ss` (dispatch) + the overlay - `defmulti`/`defmethod` macros + `host-contract.ss` late-bind. -- **AOT namespace context** (`jolt build`): `build.ss` (`bld-ns-prelude`) emits - `(set-chez-ns! ns)` + `chez-register-alias!` per app namespace (both the normal - and tree-shake emit paths), matching the loader's per-file ns context; - `test/chez/build-app` (`make buildsmoke`). -- **Deps resolution**: `jolt-core/jolt/deps.clj` (the only file) + `main.clj` - (applies the roots) + `loader.ss` (the `require` path). - -## Conventions you must preserve - -See **CLAUDE.md → "Conventions & Patterns"** for the load-bearing rules: the -re-mint trigger, the tier macro-ordering rule, the `get`-on-your-own-wrapper trap, -`:jolt/type`-as-a-key parsing, the `var-deref` calling convention (the compiler is -reached from the `.ss` runtime by string lookup, so a public `defn` with no -in-Clojure callers can still be live), and the writing style. diff --git a/docs/building-and-deps.md b/docs/building-and-deps.md deleted file mode 100644 index c8b82e9..0000000 --- a/docs/building-and-deps.md +++ /dev/null @@ -1,113 +0,0 @@ -# Building and dependencies - -How to run Jolt from source and how to pull Clojure libraries into a project. - -## Running - -```bash -git clone https://github.com/jolt-lang/jolt.git -cd jolt -git submodule update --init # vendor/sci (used by the SCI bootstrap tests) -bin/joltc -e '(println "hello")' -``` - -There is **no build step**. `bin/joltc` (`host/chez/cli.ss`) loads the -checked-in bootstrap seed (`host/chez/seed/{prelude,image}.ss`) plus the spine -and compiles+evals on Chez (read → analyze → IR → emit → eval), so a fresh -clone runs immediately. The whole `.clj` standard library -(`clojure.string`/`set`/`walk`/`edn`/`pprint`/…) and `clojure.core` are part of -the overlay, so they're always available. - -`bin/joltc` is both the runtime (REPL, file/expr runner) and the dependency -front-end (`deps.edn` resolution, see below). A run with no `deps.edn` never -touches the resolver. - -The bootstrap seed is **checked in**. After changing a seed source — the reader -(`host/chez/reader.ss`), the analyzer/IR/backend (`jolt-core/jolt/*.clj`), or the -`clojure.core` overlay (`jolt-core/clojure/core/*.clj`) — re-mint the seed with -`make remint` (it iterates `host/chez/bootstrap.ss` to a byte-fixpoint), or -`make selfhost` fails. Runtime-only `host/chez/*.ss` shims don't need a re-mint. - -## How namespaces are found - -`(require ...)` resolves a namespace to a file by searching an ordered list of -source roots — the stdlib first, then any extra roots — trying `.clj` then -`.cljc` (dots become directories, dashes become underscores). Extra roots -come from: - -- `JOLT_PATH` — a colon-separated list of directories (like a classpath), applied - at runtime; -- the `:paths` option to `init` when embedding Jolt as a library. - -If a namespace isn't found on any root, the loader falls back to the stdlib in -the overlay — that's how `clojure.string` and friends resolve when you run -outside the source tree. - -So you can point Jolt at a directory of Clojure source with no deps machinery at -all: - -```bash -JOLT_PATH=/path/to/lib/src bin/joltc run myfile.clj -``` - -## Dependencies via deps.edn - -`bin/joltc` reads a `deps.edn` in the current directory, fetches its -dependencies, and prepends the resolved source directories to the source roots -for the run. The CLI commands (`jolt.deps` + `jolt.main`): - -```bash -bin/joltc run -m NS [args] # resolve deps.edn, load NS, call its -main -bin/joltc run FILE # resolve deps.edn, load a Clojure file -bin/joltc -M:alias [args] # run the alias's :main-opts -bin/joltc -A:alias [args] # add the alias's paths/deps, then run the rest -bin/joltc repl # start a line REPL (project deps + native libs loaded) -bin/joltc --nrepl-server [port] # start an nREPL server (default 7888) for editors -bin/joltc path # print the resolved source roots (':'-joined) -bin/joltc # run a deps.edn :tasks entry -``` - -Example `deps.edn`: - -```clojure -{:paths ["src"] - :deps {weavejester/medley {:git/url "https://github.com/weavejester/medley" - :git/sha ""} - my/helpers {:local/root "../helpers"}}} -``` - -```bash -bin/joltc run -m myapp.main -``` - -### What's supported - -- **git deps** — `{:git/url … :git/sha …}` (use a full SHA; `git fetch` can't - resolve a short one), with an optional `:deps/root` for a subdirectory. - Transitive deps from each dependency's own `deps.edn` are resolved too. -- **local deps** — `{:local/root "../path"}`. -- The project's own `:paths` (default `["src"]`) are included. -- **aliases** — `:aliases {:dev {:extra-paths ["dev"] :extra-deps {…} - :main-opts ["-e" "…"]}}`, selected with `-A:dev` (or several: `-A:dev:test`). - `:extra-paths`/`:extra-deps` accumulate across selected aliases; - `:main-opts` is last-wins and runs via `-M:alias`. -- **tasks** — `:tasks {clean "rm -rf target" test {:main-opts ["-m" "…"]}}`. - A string task is a shell command; a map task runs jolt with its `:main-opts`. - Run one with `bin/joltc `. - -Resolution is breadth-first, so a top-level coordinate always beats a transitive -one for the same lib. - -Git clones land in a global, sha-immutable cache shared across projects — -`$JOLT_GITLIBS`, else `~/.jolt/gitlibs`. - -### What's not - -- **No Maven.** `:mvn/version` deps are skipped with a warning — git and local - only. -- **Pure `clj`/`cljc` only.** A library that needs the JVM (Java interop, host - classes) or a `clojure.core` feature Jolt doesn't implement will fail to load - or fail at a call. Coverage is per-function: a namespace can load with most - functions working and a few not. - -See [`tools-deps.md`](tools-deps.md) for the design rationale. diff --git a/docs/host-interop.md b/docs/host-interop.md deleted file mode 100644 index 8c2277f..0000000 --- a/docs/host-interop.md +++ /dev/null @@ -1,271 +0,0 @@ -# Host interop and JVM standard-library shims - -Jolt runs on Chez Scheme, not the JVM, so there are no real Java classes behind -interop forms. Instead the runtime ships shims for the slice of the JVM standard -library that portable Clojure code reaches for, so libraries written against -`clojure.core` and common `java.*` classes run unchanged. The Clojure interop -syntax works against these shims: - -```clojure -(Math/sqrt 2) ; static call -Math/PI ; static field -(StringBuilder.) ; constructor -(.append sb "x") ; instance method -(instance? String "hi") ; class token -``` - -A class token (`String`, `java.util.UUID`, …) resolves to a name; there is no -reflection and no class hierarchy. `(class x)` returns the JVM class name for the -scalar/collection types Clojure programs compare against (`"java.lang.Long"`, -`"java.lang.String"`, and so on). - -## Source layering: JVM-specific code lives in the java layer - -Keep anything JVM-specific in `host/chez/java/`. The rest of the runtime stays -JVM-free, and the compiler in `jolt-core/` is JVM-free by construction. - -- `host/chez/java/` holds the JVM model: the `java.*` mirrors, the class tokens - and class hierarchy, `(class x)`/`(type x)`/`instance?`, exception classes, the - interop dispatch for `.method`/`Class/static`/`(Class.)`. If a value or name - only means something because the JVM has it, it belongs here. -- The rest of `host/chez/` is the host-neutral runtime — the value model - (`values.ss`, `collections.ss`, `seq.ss`), reader, vars, multimethods, meta. It - speaks jolt's own taxonomy (`:string`, `:vector`, `:jolt/inst`), never JVM class - names. -- `jolt-core/` (the Clojure compiler + `clojure.core` overlay) emits and reasons - in that taxonomy only. The JVM mapping happens *after*, in the java layer. - -The worked example is `type`. The core layer (`natives-meta.ss`) computes the -keyword taxonomy and binds it as `__type-tag` — that's what `print-method` and the -reader dispatch on, with no JVM in scope. The java layer (`java/host-class.ss`) -then rebinds the public `clojure.core/type` to Clojure's `(or (:type meta) (class -x))`, mapping `:jolt/inst` → `java.util.Date` and so on, right next to `(class -…)`. So the compiler keeps emitting `:jolt/inst`; the java layer remaps it. - -When you add interop behaviour, prefer registering it through the generic hooks a -java-layer file already uses — `register-class-arm!` for `(class x)`, -`register-instance-check-arm!` for `instance?`, `register-eq-arm!` for value -equality — rather than threading a JVM concept back into a host-neutral file. A -new `java.*` shim is a new file under `host/chez/java/` loaded from `rt.ss`, not a -branch added to `collections.ss` or `seq.ss`. - -## What's shimmed - -This is the surface today, not the whole JVM. Methods not listed generally -aren't implemented; a few are accepted but no-ops (noted inline). - -### Numbers and language - -- **`java.lang.Math`** — `sqrt` `cbrt` `pow` `exp` `log` `log10` `floor` `ceil` - `round` `abs` `max` `min` `sin` `cos` `tan` `asin` `acos` `atan` `signum` - `random`; fields `PI`, `E`. (`clojure.math` mirrors these as functions.) -- **`Long` / `Integer`** — `parseLong`/`parseInt`/`valueOf` (optional radix), - `MAX_VALUE`, `MIN_VALUE`; `(Integer. x)`. -- **`Double` / `Float`** — `parseDouble`, `valueOf`, `toString`, `isNaN`, - `isInfinite`, the `*_VALUE`/`*_INFINITY`/`NaN` fields; `(Double. s)`. -- **`Boolean`** — `parseBoolean`, `TRUE`, `FALSE`. -- **`Character`** — `isUpperCase` `isLowerCase` `isDigit` `isWhitespace` (ASCII). -- **Boxed-number methods** — every number answers `.intValue` `.longValue` - `.doubleValue` `.floatValue` `.byteValue` `.shortValue` `.toString` - `.hashCode` (integer projections wrap modulo their width, as on the JVM). -- **`java.lang.System`** — `currentTimeMillis` `nanoTime` `exit` `getProperty` - `setProperty` `clearProperty` `getProperties` `getenv` `gc` (a full Chez - collection — clears weak references and fires their queues). -- **`java.lang.Thread`** — real OS threads over Chez `fork-thread`, sharing the - one heap (a captured atom/var is shared): `(Thread. thunk)` + `start` / `join` / - `run` / `isAlive`; plus `sleep` (real), `yield`/`interrupted`/`interrupt` - (no-ops), `currentThread`. -- **`java.util.concurrent.CountDownLatch`** — `(CountDownLatch. n)` + `countDown` - / `await` / `getCount`, a real counting barrier (mutex + condition). -- **`java.lang.ref.SoftReference` / `WeakReference` + `ReferenceQueue`** — genuine - GC reclamation: the referent is held through a Chez weak pair, so the collector - reclaims it once unreachable (`.get` then returns nil) and a guardian enqueues - the reference on its `ReferenceQueue` (`poll`). Chez has no reference softer than - weak, so a `SoftReference` clears on unreachability, not memory pressure — eager, - but real eviction (core.cache's SoftCache). -- **`java.lang.Object`** — `(Object.)` as a fresh-identity sentinel; `.toString` - `.hashCode` `.equals` `.getClass` work on any value. -- **`java.lang.Class`** — `forName` (throws a catchable `ClassNotFoundException` - for a class jolt can't back, so `(try (Class/forName "opt.Dep") (catch …))` - dependency probes work). There is no reflection, but a few common interfaces - carry a modeled ancestry so `(supers c)` / `(ancestors c)` answer like the JVM — - e.g. `(ancestors (class f))` for a function yields `Runnable` and `Callable`, - the check `core.memoize` uses to validate a memoizable argument. - -### Strings and text - -- **`java.lang.String`** statics — `valueOf`, `format` (the `clojure.core/format` - engine; `String/format` with a leading locale is accepted). Instance methods - go through `clojure.string` / the native string ops. -- **`StringBuilder`** — `append` `toString` `length` `charAt` `setLength`. -- **`java.text.NumberFormat`** — `getInstance` `getNumberInstance` - `getIntegerInstance`; `.format`, `.setGroupingUsed`, - `.setMinimum/MaximumFractionDigits`. -- **`java.util.StringTokenizer`** — `hasMoreTokens` `countTokens` `nextToken`. -- **`java.util.regex.Pattern`** — `compile` (with `Pattern/MULTILINE`), `quote`; - `.split`, `.pattern`. (`#"…"` literals and `clojure.string` regex fns are the - usual entry points.) - -### Collections (mutable) - -- **`java.util.ArrayList`** — `add` `get` `set` `size` `isEmpty` `remove` `clear` - `contains` `toArray` `iterator`. -- **`java.util.HashMap`** / **`java.util.concurrent.ConcurrentHashMap`** — `put` - `get` `getOrDefault` `containsKey` `containsValue` `size` `isEmpty` `remove` - `clear` `putAll` `keySet` `values` `entrySet`; `clojure.core`'s `get` / `count` / - `contains?` also read them. (One shared heap, so the plain mutable map serves the - concurrent one.) - -### I/O - -- **`java.io.File`** — `(File. path)` / `(File. parent child)`. A File keeps the - path as given (`(.getPath (File. "rel"))` is `"rel"`, `.isAbsolute` false); a - relative path resolves against `JOLT_PWD` only when the filesystem is touched. - Methods: `getPath` `getName` `getParent` `getParentFile` `getAbsolutePath` - `getAbsoluteFile` `getCanonicalPath` `getCanonicalFile` `toURI` `toURL` - `exists` `isDirectory` `isFile` `isAbsolute` `isHidden` `length` `lastModified` - `canRead` `canWrite` `canExecute` `list` `listFiles` `mkdir` `mkdirs` `delete` - `createNewFile` `renameTo` `compareTo` `equals` `hashCode`. Statics: - `File/separator` `File/separatorChar` `File/pathSeparator` `File/createTempFile` - `File/listRoots`. -- **Byte streams** — `FileInputStream` / `FileOutputStream` (over a path/File, - `append` arg), `ByteArrayInputStream` / `ByteArrayOutputStream` - (`toByteArray`/`toString`/`size`/`reset`), `BufferedInputStream` / - `BufferedOutputStream`. `read`/`read(byte[])`, `write(int)`/`write(byte[])`, - `flush`, `close`. Each is a Chez binary port underneath. -- **Char streams** — `FileReader` / `InputStreamReader` (read a byte stream as - UTF-8), `FileWriter` / `OutputStreamWriter`, `BufferedReader` (`readLine`, - `lines`) / `BufferedWriter` (`newLine`), `StringReader` / `StringWriter` / - `PushbackReader`. -- **`clojure.java.io`** — `file` `as-file` `reader` `writer` `input-stream` - `output-stream` `copy` (byte-exact for byte sources) `make-parents` - `delete-file` `resource` `as-url`. `slurp`/`spit`/`line-seq`/`with-open` work - over all of the above. -- **`java.lang.ClassLoader`** — `getSystemClassLoader`, `.getResource`, - `.getResourceAsStream` (resolved against the source roots). - -### Time and date - -- **`java.util.Date`** — `(Date.)` / `(Date. ms)`; `getTime` `toInstant` - `toLocalDate(Time)` `before` `after` `equals` `toString` (RFC 3339). -- **`java.time`** — `Instant` (`now`, `ofEpochMilli`, `toEpochMilli`, `atZone`), - `LocalDateTime`, `ZoneId`, `DateTimeFormatter` (`ofPattern`, `ISO_LOCAL_*`, - localized styles), `FormatStyle`. -- **`java.text.SimpleDateFormat`** — `(SimpleDateFormat. pattern)`; `parse` - `format` `toPattern` `applyPattern` (`setTimeZone`/`setLenient` accepted but - ignored — formatting is UTC). -- **`java.util.TimeZone`** / **`java.util.Locale`** — constructed and passed - through; only UTC is honored for formatting. - -### Net, encoding, misc - -- **`java.net.URL`** — `(URL. spec)`; `toString` `toExternalForm` `getProtocol` - `getPath` `getFile`. -- **`java.net.URI`** — full component accessors (`getScheme` `getHost` `getPort` - `getPath` `getQuery` `getFragment`, raw variants, `isAbsolute`). -- **`java.util.Base64`** — `getEncoder`/`getDecoder` with `encode`, - `encodeToString`, `decode`. -- **`java.nio.charset.Charset`** — `forName`. -- **`java.util.UUID`** — `randomUUID`, `fromString`; `(UUID. s)`. -- **Exceptions** — `Throwable` `Exception` `RuntimeException` - `IllegalArgumentException` `IllegalStateException` `IOException` - `NumberFormatException` `ArithmeticException` `NullPointerException` - `ClassCastException` `IndexOutOfBoundsException` `FileNotFoundException` - `UnsupportedOperationException` `Error` `AssertionError` and the common network - exceptions, each with the `(E.)` / `(E. msg)` / `(E. msg cause)` / `(E. cause)` - constructors. `try` dispatches its `catch` clauses by class in order, respecting - the exception supertype hierarchy (`(catch Exception e …)` catches a - `RuntimeException` but not an `Error`); a thrown value matching no clause - re-throws. An untyped host condition (e.g. from `(/ 1 0)`) is caught by a - `RuntimeException`/`Exception`/`Throwable` clause. - -What's deliberately absent: STM (`clojure.lang.LockingTransaction/isRunning` -returns `false`), reflection, `gen-class`/`proxy` of Java classes, and -`BigDecimal`. - -## Adding your own shim from a library - -The built-in shims above are baked into the seed. A library or project can -register its **own** host classes at load time — no seed re-mint, no host edits. -Put the registration calls at the top level of a namespace your code requires. -Four functions (in `clojure.core`) plus the tagged-table seam (in `jolt.host`) -cover it. - -`__register-class-ctor!` makes `(Name. …)` work; `__register-class-statics!` -makes `Name/field` and `(Name/method …)` work; `__register-class-methods!` -attaches instance methods to a tagged value; `__register-instance-check!` teaches -`instance?` about your class. **Method and static names are strings** (they match -the literal name in the interop form). - -A stateful object is a *tagged table* — `jolt.host/tagged-table` creates one, -`ref-put!`/`ref-get` set and read its fields. Read the tag back with -`jolt.host/ref-get` (or test it with `jolt.host/table?`); a plain `get` / -keyword lookup deliberately can't see a wrapper's own `:jolt/type`. - -```clojure -(ns mylib.greeter - (:require [jolt.host :as host])) - -;; (Greeter. name) -> a tagged value carrying its name -(__register-class-ctor! "Greeter" - (fn [name] (-> (host/tagged-table :greeter) - (host/ref-put! :name name)))) - -;; (.hello g) -> instance method, keyed by the literal method name -(__register-class-methods! :greeter - {"hello" (fn [self] (str "hi " (host/ref-get self :name)))}) - -;; Greeter/VERSION (field) and (Greeter/make x) (static method) -(__register-class-statics! "Greeter" - {"VERSION" "1.0" - "make" (fn [name] (Greeter. name))}) - -;; (instance? Greeter x) -(__register-instance-check! - (fn [class-name v] - (when (= class-name "Greeter") - (and (host/table? v) (= :greeter (host/ref-get v :jolt/type)))))) -``` - -```clojure -(.hello (Greeter. "ada")) ;=> "hi ada" -Greeter/VERSION ;=> "1.0" -(.hello (Greeter/make "bob")) ;=> "hi bob" -(instance? Greeter (Greeter. "x")) ;=> true -``` - -An instance-check predicate returns `true`/`false` to decide, or `nil` to defer -to the next registered check and the built-ins — so several libraries can -register checks without clobbering each other. This is the mechanism jolt's -HTTP client library uses to emulate `java.net.URL` and `HttpURLConnection` so -`clj-http-lite` runs unchanged. - -`__register-instance-check!` answers one `(instance? Foo x)` question. When a -class belongs to a *hierarchy* — a custom exception that should be caught as an -`IOException`, or a value that should match `(instance? SomeInterface x)` across -its whole supertype chain and dispatch a protocol extended to any of those -supertypes — declare its direct supers once with `jolt.host/register-class-supers!` -instead. `instance?`, `isa?`, `supers`/`ancestors`, and `extend-protocol` -dispatch all derive from the one declaration (supers are given by canonical name; -transitivity is computed): - -```clojure -;; a library's exception type that catch/instance? should treat as an IOException -(jolt.host/register-class-supers! "com.acme.RetryExhaustedException" - ["java.io.IOException"]) - -(throw (jolt.host/throwable "com.acme.RetryExhaustedException" "gave up")) -;; (catch java.io.IOException e …) now matches it; (instance? java.lang.Exception e) is true -``` - -deftype/defrecord classes join the same graph automatically at definition: a -record's ancestry carries the record interfaces (`clojure.lang.IRecord`, -`IPersistentMap`, `Associative`, …), a bare deftype carries -`clojure.lang.IType`, and every protocol the type implements inline appears as -an implemented interface — so `(ancestors MyRecord)`, `(isa? MyRecord -clojure.lang.IPersistentMap)`, and hierarchy relationships `derive`d on a -class's supers all answer like the JVM. - -Extending a *built-in* class instead (adding a method to core's `String` shim, -say) means editing the relevant `host/chez/*.ss` file and running `make remint` -— see [building-and-deps.md](building-and-deps.md). diff --git a/docs/libraries.md b/docs/libraries.md deleted file mode 100644 index e5c7fec..0000000 --- a/docs/libraries.md +++ /dev/null @@ -1,80 +0,0 @@ -# Clojure libraries known to work with Jolt - -Libraries confirmed to load and pass their conformance checks on Jolt. A library -listed here works. See the [examples](https://github.com/jolt-lang/examples), -e.g. the [ring-app example](https://github.com/jolt-lang/examples/tree/main/ring-app). - -* [aero](https://github.com/juxt/aero) — EDN configuration with tag literals - (`#ref`/`#env`/`#or`/`#profile`/`#long`/…) -* [config](https://github.com/yogthos/config) — environment configuration -* [Selmer](https://github.com/yogthos/Selmer) — Django-style templates -* [medley](https://github.com/weavejester/medley) — collection utilities -* [cuerdas](https://github.com/funcool/cuerdas) — string manipulation -* [ring-core](https://github.com/ring-clojure/ring) — via `:deps/root "ring-core"`, - on the ring-app example -* [ring-codec](https://github.com/ring-clojure/ring-codec) — URL/form encoding -* [ring-defaults](https://github.com/ring-clojure/ring-defaults) — the standard - middleware stack (params, static resources + content-type, session, security - headers); its session/CSRF crypto comes from - [jolt-lang/jolt-crypto](https://github.com/jolt-lang/jolt-crypto) (OpenSSL) -* [reitit-core](https://github.com/metosin/reitit) — data-driven routing; the - `reitit.Trie` Java class is mirrored by - [jolt-lang/router](https://github.com/jolt-lang/router). -* [integrant](https://github.com/weavejester/integrant) — data-driven system - configuration (`#ig/ref`), with its - [dependency](https://github.com/weavejester/dependency) and - [meta-merge](https://github.com/weavejester/meta-merge) deps -* [honeysql](https://github.com/seancorfield/honeysql) — SQL formatter and helpers -* [clojure.jdbc](https://github.com/yogthos/clojure.jdbc) — via - [jolt-lang/db](https://github.com/jolt-lang/db)'s `jdbc.core`, over the built-in - SQLite access (libsqlite3 via Chez's FFI) -* [tools.logging](https://github.com/clojure/tools.logging) — runs verbatim over a - native `clojure.tools.logging.impl` stderr backend -* [migratus](https://github.com/yogthos/migratus) — database migrations over - [jolt-lang/db](https://github.com/jolt-lang/db) -* [malli](https://github.com/metosin/malli) — data schema validation, on the - malli-app example. -* [markdown-clj](https://github.com/yogthos/markdown-clj) — Markdown → HTML, on the - markdown-app example -* [hiccup](https://github.com/weavejester/hiccup) — HTML from Clojure data, on the - hiccup-app example -* [clojure.data.json](https://github.com/clojure/data.json) — JSON reading and writing -* [clojure.spec.alpha](https://github.com/clojure/spec.alpha) — data specs -* [core.match](https://github.com/clojure/core.match) — pattern matching. -* [core.cache](https://github.com/clojure/core.cache) — caching (Basic/FIFO/LRU/ - LU/TTL/Soft + the wrapped atom API), over - [data.priority-map](https://github.com/clojure/data.priority-map). -* [core.memoize](https://github.com/clojure/core.memoize) — function memoization - over [core.cache](https://github.com/clojure/core.cache). -* [core.async](https://github.com/clojure/core.async) — CSP channels and `go` blocks - (`!`/`alts!`, `pipeline`, `mult`/`mix`/`pub`/`sub`) on real OS threads. -* [core.logic](https://github.com/clojure/core.logic) — relational logic programming - (unification, `run`/`fresh`/`conde`, finite domains). -* [math.combinatorics](https://github.com/clojure/math.combinatorics) — permutations, - combinations, subsets, selections, cartesian products, partitions. -* [core.contracts](https://github.com/clojure/core.contracts) — programming by - contract (`contract`/`with-constraints`/`provide`), over - [core.unify](https://github.com/clojure/core.unify). -* [data.zip](https://github.com/clojure/data.zip) — zipper navigation, including - `clojure.data.zip.xml`; XML parsing via [jolt-lang/xml](https://github.com/jolt-lang/xml) - (which now ships `clojure.xml/parse`). -* [data.csv](https://github.com/clojure/data.csv) — reading and writing CSV. -* [data.codec](https://github.com/clojure/data.codec) — base64 encode/decode over - byte arrays. -* [data.priority-map](https://github.com/clojure/data.priority-map) — priority - maps (incl. keyfn / custom comparator), with `subseq`/`rsubseq`. -* [tools.macro](https://github.com/clojure/tools.macro) — local macros - (`macrolet`/`symbol-macrolet`), `mexpand`/`mexpand-all`. -* [algo.monads](https://github.com/clojure/algo.monads) — monad macros and - monads (maybe/seq/state/writer/reader/…), over - [tools.macro](https://github.com/clojure/tools.macro). -* [test.check](https://github.com/clojure/test.check) — property-based testing - (generators, `quick-check`, shrinking). -* [tools.reader](https://github.com/clojure/tools.reader) — a Clojure reader in - Clojure (edn + full reader, indexing/pushback reader types). -* [rewrite-clj](https://github.com/clj-commons/rewrite-clj) — parse/rewrite Clojure - source while preserving whitespace and comments (nodes + zipper), over - [tools.reader](https://github.com/clojure/tools.reader). -* [tick](https://github.com/juxt/tick) — date/time over Jolt's `java.time`; - `#time/…` literals via `time-literals`. -* [transit-jolt](https://github.com/jolt-lang/transit-jolt) — Transit (JSON) read/write diff --git a/docs/rfc/0001-language-specification.md b/docs/rfc/0001-language-specification.md deleted file mode 100644 index bc078f9..0000000 --- a/docs/rfc/0001-language-specification.md +++ /dev/null @@ -1,179 +0,0 @@ -# RFC 0001 — A Specification for the Clojure Language - -- **Status**: Draft -- **Champions**: jolt maintainers -- **Created**: 2026-06-10 - -## Summary - -Produce a normative, implementation-independent specification of the Clojure -language — the reader, the evaluation model, the special forms, the data types -and their equality/hashing/ordering contracts, sequences and laziness, and the -`clojure.core` library — to the standard set by R7RS Scheme and the Racket -reference. The specification is developed *in this repository*, validated -continuously by jolt's executable conformance suite, and intended to be useful -to every alternative implementation (ClojureScript, jank, babashka/sci, -Basilisp, ClojureCLR, jolt). - -## Motivation - -Clojure has no specification. The language is defined by: - -1. the reference JVM implementation's source, -2. docstrings (frequently silent on edge cases), -3. community folklore (ClojureDocs examples, mailing-list threads), -4. each alternative implementation's reverse-engineering effort. - -Every alternative implementation independently re-derives answers to the same -questions — *what does `(nth coll nil)` do? is `(first "")` an error? does -`conj` on `nil` produce a list or vector? in what order does `reduce-kv` visit -a map?* — and they routinely diverge. The cross-dialect -[clojure-test-suite](https://github.com/jank-lang/clojure-test-suite) exists -precisely because these divergences are real and frequent: it currently -encodes hundreds of edge-case assertions that no normative document captures. - -Building jolt's self-hosted compiler forced us to answer these questions -one at a time (the conformance harness runs every behavior through three -independent execution paths and demands agreement). That work product — over -300 three-way-validated conformance assertions, ~1,500 behavioral spec cases, -and a frozen catalog of which forms are language vs. host — is the seed of a -specification, currently trapped in test files. This RFC proposes promoting it -into prose with normative force. - -### Why us / why now - -A useful spec needs an implementation that can *afford* to be strict. The -reference implementation can't adopt a spec retroactively without breaking -changes; an alternative implementation chasing drop-in compatibility can't -deviate from the reference even where the reference is accidental. jolt's -goals (self-hosted, minimal seed, multiple execution paths that must agree) -already require us to decide, for every form, *what the contract is* — we are -writing the spec anyway, in test form. The marginal cost of writing it down -properly is small; the value to the ecosystem is large. - -## Goals - -1. **Normative core**: reader grammar, evaluation model, all special forms, - data types with equality/hashing/ordering contracts, seq/laziness - contracts, namespaces/vars, and per-var entries for the portable - `clojure.core` surface. -2. **Executable**: every normative statement is paired with at least one - conformance test. The spec and the suite are maintained together; a spec - claim without a test is marked `unverified`. -3. **Host classification**: every `clojure.core` var is classified - **portable** (specified normatively), **host-dependent** (interface - specified, behavior host-defined — e.g. `slurp`, `*out*`), or - **JVM-specific** (documented as outside the portable language — e.g. - `bases`, `definline`, agents/STM as currently scoped). -4. **Versioned against reference Clojure**: each spec edition states the - reference version it describes (initially 1.12) and records *deliberate* - divergences (e.g. where reference behavior is accidental — these become - labeled "implementation-defined" with the reference behavior noted). -5. **Useful to other implementations**: no jolt-specific concepts in - normative text. jolt appears only in conformance-suite references. - -## Non-goals - -- Specifying the JVM interop surface (`proxy`, `gen-class`, `.`-forms beyond - their syntax), agents, STM refs, or the Java class hierarchy mapping. - These are catalogued as host/JVM surface, not specified. -- Specifying `clojure.spec`, `core.async`, or other contrib libraries - (candidates for later, separate documents). -- Changing the language. The spec describes Clojure as it is; divergence - decisions document reality, they don't invent semantics. -- Replacing clojure-test-suite — we contribute to it and cite it. - -## The specification document - -Lives in `docs/spec/`. Shape (mirroring R7RS chapters): - -| § | Document | Content | -|---|---|---| -| 0 | `00-front-matter.md` | conformance terms (RFC 2119), entry format, host classification | -| 1 | `01-evaluation.md` | evaluation model: forms, environments, vars, macroexpansion order | -| 2 | `02-reader.md` | lexical syntax: formal grammar, all reader macros, reader conditionals | -| 3 | `03-special-forms.md` | the special forms, one normative entry each | -| 4 | `04-data-types.md` | nil/booleans/numbers/strings/chars/keywords/symbols/colls; equality, hashing, ordering | -| 5 | `05-sequences.md` | the seq abstraction, laziness contract, realization boundaries | -| 6 | `06-namespaces-vars.md` | namespaces, vars, dynamic binding, resolution | -| 7 | `07-polymorphism.md` | protocols, records/types, multimethods, hierarchies | -| 8 | `08-macros.md` | defmacro, syntax-quote/hygiene, `&env`/`&form` | -| 9 | `09-core-library.md` | normative per-var entries for the portable surface | -| A | `coverage.md` | generated status dashboard: 694 vars × {specified, tested, implemented, classification} | - -### The normative entry format - -Every special form and library var gets an entry with these fields -(exemplars in `03-special-forms.md` and `09-core-library.md`): - -``` -### name -Signature(s), since-version -1. Semantics — numbered MUST/SHOULD statements -2. Edge cases — nil, empty, bounds, wrong-type behavior (normative) -3. Errors — what MUST throw, and when error type is implementation-defined -4. Examples — executable, drawn from ClojureDocs where community-validated -5. Conformance — test IDs that verify each numbered statement -``` - -### Evidence sources, in priority order - -1. **Differential testing** against reference Clojure 1.12 (the ground truth - for behavior questions). -2. **clojure-test-suite** (cross-dialect agreement = portable semantics; - dialect splits = host-dependent candidates). -3. **ClojureDocs export** (`clojuredocs-export.edn`, 694 core vars, 648 with - community examples) — examples become spec examples after verification. -4. **jank's language test corpus** (~800 per-form tests under - `test/jank/{form,call,metadata,reader-macro,syntax-quote,var}`) — the - per-construct granularity model for §2–§3 conformance. -5. Reference implementation source — last resort, for intent. - -## Current baseline (measured 2026-06-10) - -- ClojureDocs inventory: **694** `clojure.core` vars (648 with examples). -- jolt implements **572**; **373 (66%)** are exercised by the behavioral - spec/conformance suites; 139 implemented-but-untested. -- Initial classification of the 182 unimplemented: ~31 dynamic vars, ~20 - agents/taps, ~11 STM, ~15 special-form docs, ~105 to adjudicate - (genuinely-portable gaps spotted already: `compare`, `any?`, `update-keys`, - `update-vals`, `parse-long`, `parse-double`, `parse-boolean`, - `partitionv`, `splitv-at`, `macroexpand`, `time`, `with-redefs`). -- Conformance: 302 assertions × 3 execution paths; ~1,500 behavioral cases; - clojure-test-suite ≥ 4081/4707 assertions. - -## Process - -1. **Section by section**, in chapter order. §2 (reader) and §3 (special - forms) first — they are the smallest closed sets and jank's corpus gives - per-construct conformance shape immediately. -2. Each PR that adds/edits normative text MUST add or cite the conformance - tests for every numbered statement, and update `coverage.md`. -3. Divergences from reference Clojure discovered during writing get filed, - then either fixed in jolt or recorded as a labeled divergence — never - silently spec'd to jolt's behavior. -4. Editions: spec snapshots versioned independently of jolt releases - (`Clojure Language Specification, Draft N`). -5. When a chapter stabilizes, solicit review from other implementations - (jank, babashka, Basilisp maintainers) before marking it Stable. - -## Alternatives considered - -- **Contribute prose to clojure-test-suite instead**: the suite is the right - *conformance* home but tests can't express rationale, classification, or - grammar; both are needed and they cross-reference. -- **Spec only what jolt implements**: rejected — the host classification of - the *full* 694-var surface is half the value. -- **EDN/data-format spec only** (edn already has a loose spec): far too - narrow; the evaluation model and core library are where divergence lives. - -## Open questions - -1. Numerics: the reference has longs/doubles/ratios/BigInt with promotion - rules; CLJS has JS numbers. Resolved: jolt carries the Scheme numeric tower - (exact integers/bignums, exact ratios, flonum doubles), matching the - reference's tower — see the numerics note in §4. -2. Where do `*print-length*`-style dynamic vars land — host-dependent - interface or portable with defaults? -3. License/venue if the spec outgrows this repo (likely CC-BY; separate repo - once §1–§3 stabilize). diff --git a/docs/rfc/0002-reader-conditional-features.md b/docs/rfc/0002-reader-conditional-features.md deleted file mode 100644 index 98affb3..0000000 --- a/docs/rfc/0002-reader-conditional-features.md +++ /dev/null @@ -1,95 +0,0 @@ -# RFC 0002 — Reader-Conditional Feature Set - -- **Status**: Superseded (2026-06-25) — jolt now includes `:clj` in the default - set; see the note below. -- **Created**: 2026-06-10 -- **Spec**: `docs/spec/02-reader.md` §2.3 S18 - -> **Update (2026-06-25).** The default set is now **`#{:jolt :clj :default}`** — -> `:clj` is satisfied by default. The clj ecosystem's `.cljc` libraries gate -> their host code behind `#?(:clj …)` with no `:jolt`/`:default` fallback, so -> the conformance libraries (core.cache, core.match, tick, malli, …) only load -> with `:clj` present; requiring an opt-in for each was friction with no payoff -> once jolt's `clojure.lang.*`/`java.*` emulation was broad enough to run those -> `:clj` branches. Matching is still by **clause order**, so a library can place -> a `:jolt` branch first to override. There is no `JOLT_FEATURES` environment -> variable; a loading context overrides the set at runtime with -> `reader-features-set!`. The rest of this RFC is the original (reverted) -> design. - -## Summary - -jolt's reader-conditional feature set is **`#{:jolt :default}`**, matched in -**clause order** (the first clause whose key the platform satisfies wins). -A loading context may opt a foreign, clj-targeted library into `:clj` -compatibility via `reader-features-set!` (or process-wide via the -`JOLT_FEATURES` environment variable). jolt does **not** satisfy `:clj` by -default. - -## Background - -`#?(:clj … :cljs … :default …)` selects a branch by platform feature at read -time. Until now jolt satisfied `:clj` — a compatibility shortcut inheriting -the JVM branches of `.cljc` files, on the theory that the `:clj` branch is -usually the "main" implementation. Each dialect chooses its own policy: -ClojureScript satisfies only `:cljs`; jank uses `:jank`; babashka includes -`:clj` because it genuinely is JVM-Clojure-compatible to a deep degree. - -Two defects forced the decision: - -1. jolt is *not* JVM-compatible where it matters for `:clj` branches: they - contain interop (`java.util.*`, `deftype` over JVM classes) and encode - JVM-specific *expectations* in tests (e.g. `parse-uuid`'s reference - permissiveness), both of which jolt fails. -2. The old implementation also matched by **key priority** (`:clj` first, - then `:default`) rather than clause order — `#?(:default 5 :clj 6)` read - as `6`, diverging from Clojure on all platforms. - -## Decision and evidence - -Measured A/B over the cross-dialect clojure-test-suite (identical tree, -2026-06-10): - -| Feature set | Assertions reached | Pass | Fail | Error | Clean files | -|---|---|---|---|---|---| -| `clj, default` (old) | 4967 | 4324 | 524 | 119 | 78 | -| `jolt, default` (new) | **5069** | **4470** | **518** | **81** | **86** | - -The portable convention reads *more* of the suite (`:default` branches were -being shadowed by `:clj` ones jolt can't satisfy) and improves every metric: -+146 passes, −38 errors, +8 clean files. The `:clj` shortcut was a net -liability, not a compatibility win. - -The opposing case — loading real-world clj-targeted libraries — is real: -SCI's `.cljc` sources select their implementation via `#?(:clj …)`/`:cljs` -with no `:jolt` branches, and fail to load under the portable set. That is a -property of the **loading context**, not of the platform: the resolution is -per-context opt-in, exactly how the SCI bootstrap now loads -(`(reader-features-set! ["jolt" "clj" "default"])`). - -## Specification (normative, mirrored in spec §2.3 S18) - -1. The platform feature set is implementation-defined and MUST be - documented. jolt's is `#{:jolt :default}`. -2. Matching MUST be by clause order: the first clause whose key is in the - feature set wins. `:default` matches on every platform. - `#?(:default 5 :clj 6)` is `5` everywhere. -3. An unmatched conditional reads as nothing (no form); an unmatched - `#?@(…)` splices nothing. -4. Implementations SHOULD provide a per-loading-context override so foreign - libraries written for other dialects can be read under a compatibility - set; using it is a deliberate, scoped decision (jolt: - `reader-features-set!` / `JOLT_FEATURES`). - -## Consequences - -- Suite baselines re-measured and raised: `baseline-pass` 4324 → 4470, - `baseline-clean-files` 78 → 86. -- Reader tests assert the portable set + clause-order semantics, plus one - opt-in round-trip through `reader-features-set!`. -- Loading clj-ecosystem libraries via deps requires deciding their feature - set; the deps loader currently inherits the process default — a future - refinement is per-dependency feature configuration (filed with the deps - work). -- `.cljc` authors targeting jolt can write `:jolt` branches and rely on - `:default` fallbacks. diff --git a/docs/rfc/0003-transients.md b/docs/rfc/0003-transients.md deleted file mode 100644 index cee6dc5..0000000 --- a/docs/rfc/0003-transients.md +++ /dev/null @@ -1,108 +0,0 @@ -# RFC 0003: Transients — semantics and the Chez mutable backing - -Status: accepted (design note) - -This note pins down what transients *are* in Jolt, where their behavior -deviates from JVM Clojure and why, and how the transient machinery is -represented in the Chez runtime. It exists so the design doesn't revisit -transients every round. - -## What a transient is in Jolt - -A transient is a Chez record (`jolt-transient`, `host/chez/transients.ss`) -wrapping *true mutable* host backing, snapshotted to the immutable collection on -`persistent!`. The backing is per kind: - -- transient vector — a growable Scheme vector (a capacity buffer plus a fill - count `n`). `conj!`/`pop!` are in-place, amortized O(1); the buffer doubles on - growth. -- transient map — a Chez hashtable keyed by `key-hash` / `jolt=` - (value-equality, nil-safe). Hashing by value keeps collection keys comparing - across representations. -- transient set — a Chez hashtable of elements. -- `cow` — a copy-on-write fallback for anything else (e.g. a sorted coll). - -`transient` accepts pvecs, pmaps, psets, and the exotic colls handled by the -`cow` path. Each kind copies its source into the matching mutable backing once. - -The bang ops (`conj!`, `assoc!`, `dissoc!`, `disj!`, `pop!`) mutate that backing -in place and return the transient — O(1) per op (amortized for the vector push). -`persistent!` snapshots a persistent value from the backing (folding the -hashtable into a pmap/pset, handing off the buffer as a pvec) and invalidates the -transient (the record's active flag clears; any further bang op or a second -`persistent!` throws "transient used after persistent!", matching Clojure's -invalidation contract). - -Read ops work on an active transient where Clojure supports them: `get`, -`contains?`, `count`, and `nth` (vector kind) see through the transient. -`seq` on a transient is not supported, as in Clojure. - -## Deviations from JVM Clojure (deliberate) - -**O(n) edges, O(1) middle.** Clojure's `(transient v)` is O(1) — the transient -*shares* the persistent trie and marks nodes editable; `persistent!` is O(1) -too. Jolt's `transient` copies the source into a mutable buffer/hashtable (O(n)) -and `persistent!` snapshots back (O(n)). The bang ops in between are host-mutable -O(1), which is *faster* per-op than trie editing. So the asymptotics of the usual -pattern - - (persistent! (reduce conj! (transient []) coll)) - -are identical (O(n) total either way) with a better constant in the loop and a -worse constant at the two edges. The pattern transients exist for — batch -construction — is fully served. What is NOT served is transient-editing a -*large* collection to change a few keys: that's O(n) in Jolt vs O(log n) in -Clojure, because `transient` copies the source into a growable Scheme vector / -Chez hashtable and `persistent!` snapshots it back. - -**No thread-ownership check.** JVM Clojure ≥1.7 also dropped the owner-thread -assertion (for fork/join), keeping only "don't use after persistent!", which -Jolt enforces. A transient handed across threads is a data race exactly as in -Clojure — documented, not checked, same as the JVM. - -**`(conj!)` / `(conj! t)` arities** follow Clojure's transducer-era contract: -zero args makes a fresh `(transient [])`, one arg returns it untouched. -`assoc!` tolerates a dangling final key (treated as `k nil`), matching the -lenient kvs walk of Jolt's `assoc`. - -**No transient sorted variants** — same as Clojure. One leniency: Clojure -throws on `(transient '(1))`, but Jolt routes a list through the `cow` fallback -path, yielding a transient. Harmless but non-Clojure; tighten if it ever -bites. - -## Why transients live in the host - -Transients are part of the value/representation layer in the Chez runtime -(`host/chez/transients.ss`), not the portable `clojure.core` overlay, on three -grounds: - -1. **They are the mutation kernel.** A transient's entire value is direct - mutation of a host buffer/hashtable. The overlay has no mutation seam of its - own. Re-expressing the bang ops in Clojure would mean either growing the host - surface one-for-one (a host-vector-push, a host-hashtable-put, …, i.e. moving - the same code behind more indirection) or simulating mutation over persistent - values (defeating the point of transients). - -2. **They sit under the collection dispatch.** `conj`/`assoc`/`get`/`count`/ - `contains?` see through a transient. Hoisting the transient ops above that - dispatch would put a compiled-Clojure call inside the hottest paths for no - semantic gain — transients have no semantics to *fix*. - -3. **The value layer is the host's job.** The persistent collections and, with - them, their mutable scratch counterparts, live in the Chez runtime alongside - the value model. Transients are representation, not library. - -What lives in the overlay: anything *derived* — e.g. `into`'s transient-using -fast path, or `update!`-style conveniences — is plain Clojure over -`transient`/bang-ops/`persistent!`. - -## Future work - -- The persistent map/set are a bitmap HAMT with structural sharing - (`host/chez/collections.ss`), so Clojure-style O(1) `transient`/`persistent!` - via editable nodes is a real option there — an internal change behind the same - surface, not a semantics change. The persistent vector is a flat - copy-on-write Scheme vector rather than a trie, so the transient surface for - it stays the copy-to-growable-vector path. -- `transient?` (Jolt extension, useful in tests) stays; Clojure has no public - predicate, so it must not leak into portability-sensitive code. diff --git a/docs/rfc/0004-type-hints.md b/docs/rfc/0004-type-hints.md deleted file mode 100644 index 4fa2e3e..0000000 --- a/docs/rfc/0004-type-hints.md +++ /dev/null @@ -1,147 +0,0 @@ -# RFC 0004: Type hints and keyword-lookup specialization - -Status: accepted (design note) - -This note describes how Jolt treats Clojure type hints, and the one place it -uses them: a `^:struct` or `^Record` hint on a local lets a constant-keyword -lookup skip its runtime representation guard. It records the rationale, the -soundness contract, the checked mode for catching inaccurate hints, and the -measured effect, so later work does not relitigate it. - -## Background: why the lookup carries a guard - -A Jolt map value has several runtime representations (see RFC on collections and -`host/chez/collections.ss`): a persistent hash map (a bitmap HAMT) for the -general case, plus sorted maps, transients, and record/deftype instances. A -record instance is a Chez record (`jrec`) whose fields are read directly off the -record's storage, while a HAMT lookup runs the full `jolt=`/`jolt-hash`-keyed -collection path. - -A constant-keyword lookup `(:k m)` compiles to a guarded form: it inspects the -subject's representation and routes a HAMT/sorted/transient/lazy-seq value to the -full `jolt-get` semantics, while a record/raw-get-safe value takes the direct -field read, which matches `jolt-get` for keyword keys. The guard is correct and -cheap, but on a raw-get-safe value it is wasted work: profiling the ray tracer (a -naive all-maps program) found keyword lookups are about half of a render, and the -guard is the only avoidable part of each one. - -Dropping the guard is only safe when the subject is known to be a plain -struct/record rather than a tagged collection. Jolt does not infer that -inter-procedurally (it would be unsound across a dynamic language's call -boundaries). A type hint supplies the same fact soundly, as a programmer -assertion. - -## What the hints mean - -Two hints on a local resolve to the "plain struct/record" assertion, which we -call the `:struct` hint internally: - -- `^:struct` — the value is a plain struct or record map. There is no Clojure - keyword with this meaning (Clojure's type hints are class names), so this is a - Jolt-specific metadata flag, analogous to `^:dynamic`. -- `^Name` where `Name` is a `defrecord`/`deftype`. Both forms define a `->Name` - positional constructor, so the analyzer treats a tag whose `->Name` resolves - as a record type. Record instances are raw-get-safe, so the lookup drops the - guard. A `^String`, `^long`, or any other non-record tag is not a record and - is ignored, exactly as before. - -Every other hint parses and is inert, matching Clojure (S12b in the reader -spec). A hint never changes a program's result; it only permits an -optimization. - -## How it flows - -The reader already keeps `^hint` metadata on the binding symbol and is otherwise -transparent (`host/chez/reader.ss`). The change threads that fact to the lookup -site: - -1. The analyzer (`jolt-core/jolt/analyzer.clj`) records a `:struct` hint per - local in its env when a param or `let` binding carries `^:struct` or a - record-type tag, and attaches `:hint :struct` to that local's `:local` IR - node. Resolving a record-type tag uses the host contract function - `record-type?` (`jolt.host`, backed by `host/chez/host-contract.ss`), which - checks for the `->Name` constructor. -2. The back end (`jolt-core/jolt/backend_scheme.clj`) emits the direct field read - when the lookup subject is a `:local` carrying the hint, and the guarded form - otherwise. The unhinted path is identical to before. -3. The inline pass (`jolt-core/jolt/passes.clj`) propagates the hint: when it - binds a non-trivial call argument to a fresh local, it carries the called - function's parameter hint onto that local, so lookups inside the spliced body - keep the direct path. Without this, inlining a hinted function would erase the - benefit, because the hinted parameter is replaced by an unhinted temporary. - -The same machinery covers both `(:k m)` and `(get m :k [default])` when the key -is a constant keyword. A `get` with a variable, numeric, or string key falls -through to `jolt-get` unchanged. - -## Record hints across namespaces, and as inference seeds - -A `^RecordType` hint does two things beyond dropping the lookup guard. - -**It carries the specific type, not just "a struct".** The guard-skip only needs -to know the value is raw-get-safe (`:struct`), but the structural inference (RFC -0005) wants the actual record type so a field read gets the field's type — -`(:origin ray)` on a `^Ray ray` is a `Vec3`, not `:any`. A record hint on a -parameter is resolved to the record's constructor key and used to **seed the -inference's parameter type**. That is what keeps a record parameter's reads typed -across a namespace boundary *without* whole-program inference (RFC 0005, -"Cross-namespace inference") — the open-world counterpart to the whole-program -pass. Hinting only the public entry point is not enough; the hint has to be on -the function where the hot reads actually happen. - -**It resolves across namespaces.** A hint may name a record defined in another -namespace, in either spelling — `^Vec3` where the type is `:refer`-ed, or -`^v/Vec3` where the namespace is `:as`-aliased. Resolution (`record-ctor-key`, -a `jolt.host` contract function backed by `host/chez/host-contract.ss`) runs -against the *compile* namespace and maps the type to its home constructor key -through a constructor-value index — keyed by the constructor value, not a var's -namespace, so a `:refer`-interned var (whose namespace is the referring one) -still resolves home. The reader keeps a tag's namespace qualifier (`^v/Vec3` → -`"v/Vec3"`, not `"Vec3"`) so the aliased spelling has something to resolve. Both -`defrecord` field hints and function parameter hints use this resolution. - -## Soundness and the checked mode - -An accurate hint is correctness-preserving by construction: for a struct or -record the bare get equals the guarded result. An inaccurate hint (asserting -`^:struct` for a value that is actually a phm) makes the raw get return the wrong -thing. This is the same contract as a wrong Clojure `^String`, except that a -wrong Jolt hint fails silently rather than throwing. - -To make a lie visible without taxing the fast path, `JOLT_CHECK_HINTS=1` keeps -the guard but throws on the tagged arm with a message naming the local and key: - -``` -type hint violated on `m`: (:a m) — value is a -phm/sorted/transient/lazy-seq, not the plain struct/record the -^:struct/^Record hint asserts -``` - -This is a development aid, off by default, with zero cost to normal builds (the -flag is read when the lookup is compiled, and the bare get is emitted when it is -off). The flag is part of the image-cache fingerprint. - -## Coverage - -Type hints parse in every position Clojure accepts them and are inert except for -the optimization above. This matches Clojure's "parse and otherwise do nothing" -model, with the difference that Clojure additionally uses hints to avoid -reflection and select primitive arithmetic, which do not apply to the Chez host. - -## Measured effect - -On the ray tracer (`~/src/examples/ray-tracer`, all values are `{:r :g :b}`-style -maps), with inlining on and the hot parameters hinted, a render goes from 13.3s -to 10.9s, about 1.22x, taking it to roughly 7.8x the JVM from 9.4x after the -inline pass. A seeded render produces an identical pixel checksum hinted and -unhinted, confirming the hints are correctness-preserving on the full pipeline. - -## Status and non-goals - -Implemented. Not pursued: inter-procedural shape inference (unsound in a dynamic -language without a guard, which costs as much as the one being removed) and a -shape-based "hidden class" representation (profiling showed allocation is about -1% of the workload, so a cheaper allocation would not help, and an escaping-map -lookup through a runtime shape check costs about the same as the guard it would -replace). The hint is the sound, opt-in lever on the part of the cost that can -move. diff --git a/docs/rfc/0005-structural-type-inference.md b/docs/rfc/0005-structural-type-inference.md deleted file mode 100644 index f707091..0000000 --- a/docs/rfc/0005-structural-type-inference.md +++ /dev/null @@ -1,303 +0,0 @@ -# RFC 0005 — Structural collection-type inference - -- **Status**: Implemented. Ray tracer 12.8s to 11.0s hint-free, - matching the explicit `^:struct` version; render checksum unchanged. -- **Champions**: jolt maintainers -- **Created**: 2026-06-13 - -## Summary - -Replace jolt's ad-hoc inference lattice with a single recursive **structural -type**, so that the type of a value mirrors the tree shape of the data it -describes. A struct-map carries its field types, a vector its element type, a -function its parameter and return types, recursively. A keyword lookup returns -the looked-up field's type, so nested access like `(:r (:direction ray))` is -typed end to end. This unifies the two facts the current inference tracks -inconsistently (a vector's element type, but not a map's field types), subsumes -the existing inference passes as special cases, and -closes the remaining ray-tracer gap without a hint. The system is a -soft-typing-style inference: it never rejects a program, it assigns a concrete -type only when it can prove one, and it falls back to `:any` (and the existing -runtime guard) everywhere else. - -## Motivation - -The existing inference specializes a collection access (drops the -`:jolt/type` guard, emits `pv-count`, and so on) when it can prove the -collection's type. It works, it is sound, and it is fully dynamic-fallback -safe. But its type lattice grew ad hoc: - -- `:struct-map` means "a raw-get-safe map" but carries **no field types**. -- `{:vec ELEM}` carries its **element type**. - -These are the same idea applied to two kinds of child in the data tree, but -only one is tracked. The cost is concrete: in the ray tracer a lookup result -like `(:direction ray)` is typed `:any`, so `(:r (:direction ray))` keeps its -guard, and the `vec3` functions (called all day with such values) cannot be -typed, so the inference reaches only about 3% where the explicit `^:struct` -hint reaches 22%. The hint wins precisely because it asserts the field/param -shape the inference fails to derive. - -The fix is to make the type a structural tree, tagged as precisely as provable. -Then `:struct` tracking and field tracking are one mechanism, the special cases -collapse into one signature table, and nested access is typed by construction. - -## The type lattice - -A type `T` is one of: - -- A scalar tag: `:num`, `:str`, `:kw`, `:bool`, `:char`. (Optionally a coarser - `:nonnil` for "provably not nil and not false", which is what the struct-vs-phm - decision needs; see below.) -- `:nil`. -- `{:struct {field -> T}}` — a raw-get-safe map (a record) whose - field `k` has type `(fields k)` or `:any` if absent. The degenerate - `{:struct {}}` is "a struct, fields unknown" and replaces today's - `:struct-map`. -- `{:vec T}` — a vector whose elements have type `T`. -- `{:set T}` — a set of `T`. -- `:phm` — a persistent hash map (NOT raw-get-safe; distinct from `:struct`). -- `{:fn {:params [T...] :ret T}}` — a function (optional precision; the current - flat param/return inference is the zero-arity-detail version of this). -- `:any` — the top. Anything not provably more specific. -- `:bottom` (represented as the absence of a type / `nil` internally) — the - identity for join, used to seed the fixpoint. - -Types are immutable values comparable by structural equality, exactly like the -current `{:vec ELEM}` representation, so they flow across the portable -inference and the host unchanged. - -### Join (least upper bound) - -``` -join(T, T) = T -join(bottom, T) = T -join({:struct a}, {:struct b}) = {:struct {k -> join(a[k]?:any, b[k]?:any) for k in keys(a) ∪ keys(b)}} -join({:vec a}, {:vec b}) = {:vec join(a, b)} -join({:set a}, {:set b}) = {:set join(a, b)} -join(_, _) = :any ; different constructors -``` - -Two struct types join field-wise; a field present in only one side becomes -`:any` in the result (it might be absent, so a lookup of it is not provably -typed). This is the standard record lattice. - -### Termination: depth cap - -Structural types of recursive data (a tree node that contains a tree node, a -cons cell) would be infinite. To keep types finite and the inter-procedural -fixpoint terminating, structural types are **depth-capped**: beyond a small -depth `D` (proposed `D = 4`) a child type is `:any`. Construction and join both -truncate at `D`. With the cap the lattice has finite height, so the monotone -fixpoint converges. The ray tracer's shapes (vec3 inside ray inside hit-info) -are depth 2 to 3, well inside the cap. - -## Inference rules - -Inference is a forward pass producing `[type node']` for each IR node (the -existing shape), threaded with a local type environment and the -inter-procedural state. The rules are uniform over the structural -type: - -- **Literals.** `{:k v ...}` with constant scalar keys and struct-safe values - builds `{:struct {:k type(v) ...}}`; otherwise `:phm`. `[a b ...]` builds - `{:vec (join type(a) type(b) ...)}`. `#{...}` builds `{:set ...}`. Scalars - build their scalar tag. (The struct-vs-phm condition is the same as the back - end's: scalar keys, and every value provably non-nil and non-false.) -- **Lookup returns the field type.** `(:k m)` / `(get m :k)` where - `m : {:struct fs}` returns `(fs :k)` or `:any`. This is the single rule that - makes nesting work and that unifies field tracking with `:struct` tracking. -- **Indexing returns the element type.** `(nth v i)` / `(v i)` where - `v : {:vec T}` returns `T`. `(first v)` / `(peek v)` likewise. -- **Flow.** `let`/`loop` bind init types; `if` joins the branch types; `do` - takes the tail type. (As today.) -- **Calls use signatures.** Every call result type comes from the callee's - signature: core fns from a fixed signature table (below), user fns from the - inter-procedural fixpoint's inferred signature. - -The inter-procedural fixpoint, recompile, escape gate, and closed-world -assumption are unchanged. They now propagate structural types instead of flat -tags. - -## Core function signatures - -The current special cases (`truthy-ret-fns`, `vector-ret-fns`, `elem-fns`, -`hof-table`, and the `conj`/`range`/`reduce`/`mapv` branches) collapse into one -table of **type schemes**, possibly parametric: - -``` -inc, dec, +, -, *, /, mod, ... : (... :num) -> :num -count : (Coll) -> :num -nth : ∀T. ({:vec T}, :num) -> T (3-arg adds a default: -> join(T, default)) -get : ∀T. ({:struct fs}, :k) -> (fs :k) ; const key -first,peek : ∀T. ({:vec T}) -> T -conj : ∀T. ({:vec T}, x) -> {:vec join(T, type(x))} -assoc : ({:struct fs}, :k, v) -> {:struct (assoc fs :k type(v))} ; const key -vec, mapv : ... -> {:vec ...} -range : (...) -> {:vec :num} -rand-nth : ∀T. ({:vec T}) -> T -map, filter, mapv, filterv, reduce, ... ; see HOFs -``` - -Parametric schemes (the `∀T`) are where polymorphism actually matters, and they -give the element/field propagation for free. **Higher-order functions are just -schemes whose parameter is itself a function type**: `reduce`'s scheme says its -function argument is `(Acc, Elem) -> Acc` applied to the collection's element -type, so the closure's element parameter is typed by applying the scheme, -replacing the hand-written `hof-table`. - -## Hints as seeds - -`^:struct x` seeds `x : {:struct {}}` (a struct, fields unknown) at a unit -boundary the inference cannot see across. A future extension could allow a shape -hint `^{:r :num :g :num :b :num}` to seed field types, but once inference is -structural this is rarely needed; the hint stays the escape hatch for genuinely -dynamic boundaries, exactly as today. - -## Soundness - -Unchanged in spirit from the current system: a concrete type is assigned only -when proven (a literal genuinely has those fields; a fn provably returns that -shape), and everything unprovable is `:any`, which keeps the dynamic guard. A -wrong specialization is therefore impossible. The inter-procedural part keeps -the closed-world (optimization-mode) assumption already adopted, which is sound -under whole-program / source-distribution compilation. - -## Compilation modes and defaults - -Direct-linking — and the inference and specialization it enables — is the -**default for running a program** and stays **off for interactive work**, chosen -by the CLI run mode rather than a global opt-in flag: - -| mode | linking | whole-program | -|---|---|---| -| `-m` / `-M NS` (program entry) | direct (default) | **auto** (closed world) | -| `FILE` / `-f` / stdin (`-`) | direct (default) | no (per-namespace) | -| `repl`, `-e`, `nrepl-server` | indirect / open | no | - -A program run is a closed world — every namespace is required, then the code -runs to completion — so it direct-links: user code gets inlining, record shapes, -and the inference's specialization. A `-m` / `-M` entry is the exact point where -all requires are done and `-main` is about to run, so the whole-program -cross-namespace pass (below) runs there automatically. Interactive modes stay -open: a REPL, `-e`, and the nREPL server must let you redefine vars — which -direct-linking seals against — so they keep the indirect, live-deref path. - -Env overrides, all winning over the mode default: - -- `JOLT_NO_DIRECT_LINK=1` — force the open/indirect path even for a program run - (runtime redefinition, hot-reload, self-modifying code). -- `JOLT_NO_WHOLE_PROGRAM=1` — keep direct-linking but skip the whole-program - pass (per-namespace inference only). -- `JOLT_DIRECT_LINK=1` — force direct-linking on even in an interactive mode. -- `JOLT_WHOLE_PROGRAM=1` — force the whole-program pass on in any direct-linked - mode. -- `JOLT_NO_SHAPE=1` — disable the record/shape representation under direct-linking. - -What direct-linking gives up is what Clojure's `:direct-linking` and jank's -`-Odirect-call` give up: a direct call embeds its callee, so redefining the -callee is not seen by already-compiled callers. Whole-program additionally -const-links stable vars (data defs, record types, `^:redef`), extending the same -trade. That is why the interactive modes stay open and the opt-outs exist. - -### Cross-namespace inference - -Per-namespace inference (a `FILE` run, or any namespace under -`JOLT_NO_WHOLE_PROGRAM`) types a function's parameters from the call sites it can -see **within that namespace**. A function whose record parameter is supplied by a -caller in *another* namespace is left `:any`, its field reads keep the guard, and -the values derived from it widen — so a decomposed program is markedly slower -than the same code in one namespace (measured at ~3.7× on the ray tracer split -across five namespaces). The information exists in the program; per-namespace -compilation just can't see a caller in a not-yet-loaded namespace. Two ways to -supply it: - -1. **Whole-program** (auto for `-m` / `-M`) runs one closed-world inference - fixpoint over every loaded namespace before `-main`, typing each parameter - from its call sites wherever they live. Namespaces required later (inside - `-main`) fall back to per-namespace inference. -2. **Parameter type hints** (`^RecordType`, RFC 0004) declare the type directly, - so it also works in the open world — REPL, library code that must be fast for - any caller, and hot-reloading servers — where the world cannot be closed. - -## Relationship to Hindley-Milner and soft typing - -This is HM-shaped with two deliberate departures, which is the textbook -definition of **soft typing** (Wright and Cartwright, "A Practical Soft Type -System for Scheme", 1997 — HM extended with union types and a dynamic type). - -Taken from HM: - -- The **structural type language** (records, vectors, functions as type - constructors). This is the "tree of types". -- **Constraint propagation** and **type schemes** for the core library (the - `∀T` signatures). That parametric polymorphism is exactly what HM provides, - and it is where it matters (generic collection functions like `nth`, - `reduce`, `map`). - -Changed, on purpose: - -- Replace "unify or **fail**" with "**join over a lattice whose top is `:any`**". - The inference never rejects a program; an unprovable spot becomes `:any` and - keeps the runtime guard. This is the "fall back to dynamic when in doubt" - policy made principled. -- **Monovariant** for user functions (the inter-procedural fixpoint plus - inlining cover the practical polymorphism); parametric schemes are kept only - for core functions. - -So: HM structural types and constraint propagation and core-fn schemes, solved -by lattice join with a dynamic top instead of unification-or-fail. Other AOT -inferencers for dynamic languages do the whole-program version of the same -thing (RPython's annotator, Crystal's global inference, Shed Skin), all with a -union/dynamic fallback. - -## Implementation and migration - -This is a refactor that **simplifies** the current code: it deletes the ad-hoc -tag soup and the per-op special cases and replaces them with one recursive type -plus a signature table. - -1. Define the structural type, `join`, the depth cap, and the predicates - (`struct-safe?`, `field-type`, `elem-type`) in `jolt.passes`. -2. Rewrite `infer` so each op produces/consumes structural types: literals - build shapes; `(:k m)` returns the field type; calls consult the signature - table. -3. Move the core-fn knowledge into a signature table (subsumes the existing - tables and HOF handling). -4. The back end keeps reading the use-site type to specialize (guard drop for - `{:struct}`, `pv-count`/`pv-nth` for `{:vec}`), now uniformly. -5. Keep the inter-procedural fixpoint, recompile, escape gate, and triggering as - is; they propagate structural types. - -The phases land incrementally behind the same optimization-mode gate, each -verified against conformance (three modes), the full test gate, and the -ray-tracer benchmark, exactly as the current phases were. - -## Design problems and open questions - -- **Recursion / termination.** Handled by the depth cap (`D = 4`). Open - question: is a fixed cap better than proper recursive (mu) types? A cap is - simpler and sound; mu-types are more precise but add complexity. Proposed: - start with the cap. -- **Compile-time cost.** Structural types are larger and the fixpoint does more - work. Mitigations: the depth cap bounds type size; inference runs only in - optimization mode; the fixpoint iteration count stays bounded. Needs - measurement on a large namespace (clojure.core itself) to confirm acceptable. -- **Heterogeneous data.** `[1 "a"]` joins to `{:vec :any}`; a map whose field - varies across branches joins that field to `:any`. Correct degradation, not a - problem, but worth stating. -- **Non-constant keys.** `(assoc m k v)` / `(:k m)` with a non-constant `k` - cannot track a specific field; the result degrades to `{:struct {}}` or - `:phm` as appropriate. Field tracking only applies to constant scalar keys. -- **`false`/`nil` field values.** A map literal is `{:struct ...}` only when - every value is provably non-nil and non-false (the back end stores such maps - as a phm). The `:nonnil` tag (or a per-type "provably truthy" predicate) is - what the literal rule needs; this must be carried correctly or struct - inference is unsound. -- **Function-type precision.** `{:fn ...}` is optional. The current flat - param/return inference is enough for the collection-specialization goal; - full function types matter more for the type-checker (RFC 0006) and could be - deferred. -- **Closed-world boundary.** Inherited from the inter-procedural pass: - param/return inference assumes the compiled unit is the whole program. - Documented there; unchanged. diff --git a/docs/rfc/0006-success-type-checking.md b/docs/rfc/0006-success-type-checking.md deleted file mode 100644 index 00688d4..0000000 --- a/docs/rfc/0006-success-type-checking.md +++ /dev/null @@ -1,232 +0,0 @@ -# RFC 0006 — Compile-time detection of provably-wrong code (success typing) - -- **Status**: Implemented. Core-fn error domains (arithmetic on non-numbers, - count/first/rest/next/seq/nth on non-seqable scalars), `JOLT_TYPE_CHECK= - off|warn|error`. Follow-ups landed: bounded scalar **unions** so a - use is reported only when every member is in the error domain; **user-fn - error domains** behind `JOLT_TYPE_CHECK_USER` (closed-world); - precise **file:line:col** locations. The checker is now one - inference walk (folded into `infer`), and is **on by default in direct-link - builds** — where it piggybacks on the specialization inference for ~free — - and opt-in (`JOLT_TYPE_CHECK`) in plain builds. -- **Champions**: jolt maintainers -- **Created**: 2026-06-13 -- **Depends on**: RFC 0005 (structural collection-type inference) - -## Summary - -Reuse the structural type inference of RFC 0005 as a **loose type checker**: at -compile time, flag code that is *provably* wrong, accept everything that is -merely ambiguous, and never produce a false positive. Concretely, when an -expression's inferred type is concrete and the operation applied to it would -throw at runtime for that type (for example passing a string where a function -only ever operates on numbers), report a clear compile-time error pointing at -the offending form, with the inferred type and what was expected. When the type -is `:any`, a union that includes a valid case, or beyond the inference's depth -cap, accept it silently. This is **success typing** (the discipline behind -Erlang's Dialyzer), applied to jolt for free on top of the inference we already -need for optimization. - -## Motivation - -Once the compiler tracks concrete types for many values (RFC 0005), it can see -some programs that cannot possibly be correct: `(inc "x")`, `(first 5)`, -`(count :k)`, `(/ 1 "two")`. Today these compile and fail at runtime, often far -from the cause. Reporting them at compile time, with a precise location and -message, turns a class of runtime crashes into immediate, actionable feedback, -at no extra inference cost. - -The design constraint the user set is the right one and is exactly success -typing's contract: **accept ambiguous cases, reject only provably-wrong ones.** -A checker that never lies about errors is one developers trust and that does not -get in the way of correct-but-untypeable dynamic code. - -## Principle: success typing, never a false positive - -Success typing (Lindahl and Sagonas, "Practical Type Inference Based on Success -Typings", 2006; the basis of Dialyzer) inverts the usual type-checker stance. -A normal checker accepts only what it can prove correct and rejects the rest -(false positives on dynamic code). A success typer accepts everything that -*could* be correct and rejects only what *cannot* be correct under any -execution. It is sound for **rejection**: if it reports an error, the code is -genuinely wrong. It is intentionally incomplete: it misses errors it cannot -prove. That is the correct trade for a dynamic language, and it matches the -user's "accept ambiguous, reject provably wrong". - -Mapped onto jolt: - -- The inference assigns a value a concrete type only when it can prove it - (RFC 0005). Unprovable is `:any`. -- A use site is reported **iff** the argument's inferred type is concrete and - lies entirely outside the operation's accepted domain, where the operation - *throws* on that domain (not merely returns a benign default). -- `:any`, a depth-capped child, or a union that includes an accepted type is - **never** reported. - -## What "provably wrong" means - -The checker needs, per operation it understands, an **error domain**: the set -of argument types for which the operation throws at runtime. This is narrower -than "the types it is documented to accept", because Clojure is lenient in many -places and flagging a benign case would be a false positive: - -- `(get 5 :k)` returns `nil`, it does not throw. NOT reported. -- `(:k 5)` returns `nil`. NOT reported. -- `(count 5)` throws ("count not supported on number"). Reported when the - argument is provably a non-countable scalar. -- `(first 5)` throws (not seqable). Reported for a provably non-seqable scalar. -- `(inc "x")`, `(+ 1 "x")` throw. Reported when an argument is provably a - non-number (`:str`, `:kw`, `:struct`, `:vec`, ...). -- `(nth 5 0)` throws. Reported for a provably non-indexable scalar. - -So the checker ships a curated table of the clearest throwing operations with -their error domains. It starts small (arithmetic on non-numbers, seq/`count`/ -`nth`/`first` on non-seqables) and grows conservatively. Anything not in the -table is not checked, which is safe (no false positive). - -A use site is reported only when: - -1. the argument's inferred type `T` is concrete (not `:any`, not a union that - includes an accepted type, not truncated by the depth cap), and -2. `T` is in the operation's error domain (the operation provably throws on `T`). - -## Examples - -```clojure -(inc "x") ; ERROR: inc expects a number, got a string -(let [n "x"] (inc n)) ; ERROR: same, n inferred :str -(count :foo) ; ERROR: count not supported on :kw -(first 42) ; ERROR: 42 is not seqable -(:k 5) ; accepted (returns nil, not an error) -(inc (rand-nth coll)) ; accepted if the element type is :any/unknown -(inc (if c 1 "x")) ; accepted: union {:num, :str} includes :num (ambiguous) -(defn f [n] (inc n)) ... ; if f is ALWAYS called with strings in-unit, ERROR at the call; - ; if its callers are unknown/varied, accepted -``` - -## Error reporting - -A reported error includes: - -- the source location (`file:line:col`) of the offending form; -- the operation and the parameter position; -- the inferred type of the argument, rendered readably (`:str`, - `{:struct {:r :num}}`, `{:vec :any}`); -- what the operation requires (`a number`, `a seqable`). - -Example: - -``` -type error scene.clj:42:18: `inc` requires a number, but argument 1 is a string -``` - -Errors are attributed to the form the user wrote. For macro-expanded code, the -checker reports at the original form's recorded position (the loader already -tracks `:error-pos`), never at synthesized internals. - -## Strictness levels - -`JOLT_TYPE_CHECK` controls behavior: - -- **off** — no checking. -- **warn** — report to stderr, do not fail compilation. **The default in - direct-link builds**, where checking rides the specialization inference for - ~free; opt-in elsewhere. -- **error** — fail compilation on a provable type error. Opt-in for CI / strict - builds. - -When `JOLT_TYPE_CHECK` is unset, checking is **on (`warn`) in direct-link -builds** and **off in plain REPL/dev builds** (where it would cost a standalone -inference pass, ~2.6× compile). `JOLT_TYPE_CHECK_USER` additionally enables -reporting against inferred user-function domains (closed-world; see below). - -Because the checker only fires on provable errors, even `error` mode cannot -break a correct program: a correct program has no provable type errors to -report. (A correct-but-untypeable program is simply not reported, since its -types degrade to `:any`.) - -## Soundness of rejection (no false positives) - -The whole value of this feature is that a reported error is real. The -guarantees: - -- The inference assigns concrete types only when provable (RFC 0005). So a - concrete `T` at a use site is a genuine lower bound on what flows there in the - analyzed world. -- The error-domain table lists only operations that genuinely throw on the - listed types, verified against the runtime. -- Ambiguity is always accepted: `:any`, unions containing an accepted type, and - depth-capped children are never reported. - -Two boundaries need care and bound where the checker is allowed to fire: - -- **Closed-world / redefinition.** Inter-procedural argument types assume the - compiled unit is the whole program (inherited from RFC 0005). For the checker, - this means a reported error on a *user* function's parameter is only as sound - as that assumption. The conservative initial policy: only report against - **core-function** error domains (stable, not redefinable) and against types - derived without crossing an open boundary. Reporting against inferred user-fn - signatures is a later, opt-in escalation. -- **Macros / generated code.** Check post-expansion IR but report at the user's - source location, and suppress reports inside expansions the user did not - write (or attribute them to the macro call site). - -## Relationship to other systems - -- **Dialyzer / success typing** (Erlang): the direct model — sound for - rejection, no false positives, accepts the ambiguous. -- **Typed Clojure / core.typed**: opt-in *sound* gradual typing that rejects - what it cannot prove correct; the opposite trade (false positives on dynamic - code), which is why we do not follow it. -- **clj-kondo**: a popular Clojure linter that flags some obvious type misuses - syntactically; this RFC subsumes the type-driven subset with inference-backed - precision and no false positives. - -## Implementation - -The checker is a thin pass over the same inference results: - -1. After (or during) inference, walk the IR. At each call to an operation in - the error-domain table, look at the inferred type of each checked argument. -2. If concrete and in the error domain, record a diagnostic with location, the - inferred type, and the expected domain. -3. Emit diagnostics per the strictness level. - -It adds no new inference; it consumes RFC 0005's types and a small curated -table. It can ship after RFC 0005 lands, starting in `warn` mode with the -smallest high-confidence table (arithmetic and seq/count/nth/first), and grow. - -## Design problems and open questions - -- **Curating the error domain.** The table must list only genuinely-throwing - cases. Getting it wrong (listing a lenient op) yields false positives, which - destroys trust. Mitigation: start tiny, test each entry against the runtime, - grow slowly. Open question: derive the table from the same machinery the - runtime uses, to avoid drift? -- **Unions.** *Resolved.* The lattice has a bounded scalar union - `{:union #{T...}}` (cap 4); differing if-branches form a union instead of - collapsing to `:any`, and a use is reported only when *every* member is in the - error domain. Unions are opaque to structural specialization, so codegen is - unchanged. -- **User-function signatures.** *Resolved, opt-in.* Behind - `JOLT_TYPE_CHECK_USER`: the checker re-checks a registered non-redefinable - user fn's body with one parameter bound to its concrete argument type; a - diagnostic the all-`:any` body did not have means that argument is provably - wrong. Monotonic, so still no false positives; closed-world, hence opt-in. -- **Negative/never types.** *Resolved.* Calling a provably - non-callable value (`:num`/`:str` — keywords/maps/vectors/sets are IFn) is - reported at the default level; wrong-arity to a registered single-fixed-arity - user fn is reported under the `JOLT_TYPE_CHECK_USER` opt-in. A union callee is - flagged only when every member is non-callable. -- **Position vs intent.** *Resolved.* The reader records each list - form's absolute offset (identity-keyed, so positions survive macroexpansion - exactly when the user's sub-form is spliced through); the analyzer stamps it - onto `:invoke` nodes, the checker carries it into each diagnostic, and the - back end renders `file:line:col`. Inlining/scalar-replace preserve it via - `assoc`. -- **Interaction with the optimization gate.** *Resolved (jolt audit).* The - checker is one inference walk folded into `infer`. In direct-link builds it - piggybacks on the specialization inference that already runs (~free, default - on); in plain builds it runs as a standalone pass only when `JOLT_TYPE_CHECK` - is set. "Run inference for checking" and "specialize from inference" are the - same walk now, gated by a `checking?` flag. diff --git a/docs/rfc/0007-compilation-modes-and-binary-output.md b/docs/rfc/0007-compilation-modes-and-binary-output.md deleted file mode 100644 index 53ee2b3..0000000 --- a/docs/rfc/0007-compilation-modes-and-binary-output.md +++ /dev/null @@ -1,186 +0,0 @@ -# RFC 0007 — Compilation modes and binary output - -- **Status**: Draft. No code yet; this fixes the design before Phase 4 work - (beads `jolt-cf1q.5`) starts. -- **Champions**: jolt maintainers -- **Created**: 2026-06-22 - -## Summary - -Give jolt a `jolt build` command that emits a standalone executable, and a -three-mode model that trades dynamism for speed: - -- **dev** — open/indirect linking, redefinition works, no perf focus. What - `repl`/`-e`/`nrepl` already are. -- **release** (default for a built program) — direct-linked, closed-world, - per-namespace inference. Fast, still a recognizable Clojure runtime. -- **optimized** — whole-program inference, `fl*`/`fx*` typed emission, Chez - whole-program optimization. Fastest, sacrifices dynamic redefinition. - -All three already have their machinery in the tree — the inference and inline -passes were ported into `jolt-core/jolt/passes/`. What is missing is (a) a code -path that writes emitted Scheme to disk and AOT-compiles it instead of -eval'ing it in process, and (b) a switch that turns the dormant passes on. This -RFC specifies both. - -## Motivation - -The Janet host could produce binaries (`jolt uberscript` with dead-code -elimination, `jolt cgen-build` for a single native binary). The Chez rehost -dropped that machinery with the Janet host — it was Janet-specific (IR→C made -sense when the host was Janet). On Chez the natural target is Chez's own native -compiler, so the old emitters were deleted rather than re-pointed. - -The result today: `bin/joltc` only ever loads the checked-in seed and -compile-evals in process. `jolt.main/-main` dispatches `run / -M / -A / repl / -nrepl / task` and nothing else. There is no way to ship an app as a binary, and -the optimization passes are inert — `jolt.host/inline-enabled?` is a stub -returning `#f` (`host/chez/host-contract.ss:283`), so every call links -indirectly and nothing inlines. Jolt on Chez runs only in what this RFC calls -dev mode. - -The passes themselves survived intact: - -- `jolt/passes/types.clj` — structural collection-type inference (RFC 0005) + - success-type checking (RFC 0006). -- `jolt/passes/inline.clj` — inline + flatten-lets + scalar-replace, already - gated "direct-link only". -- `jolt/passes/fold.clj` — const-fold, including predicate folding. - -So this is not a port of lost code. It is wiring: a build front-end, a -file-emitting back-end path, and a mode switch over passes that already exist. - -## The three modes - -| Mode | Linking | Inference | Redefinition | Driver | -|---|---|---|---|---| -| **dev** | indirect (var-deref per call) | off | yes | `repl`, `-e`, `nrepl`, `run` of a file by default | -| **release** | direct, closed-world | per-namespace | no (closed world) | `jolt build` default | -| **optimized** | direct + whole-program | whole-program fixpoint, `fl*`/`fx*` | no | `jolt build --opt` / `-M`-style entry | - -The modes are points on one axis (how much the back end may assume is fixed), -not three code paths. Each mode is a setting of two independent knobs the passes -already understand: - -- **direct-link?** — may a call to a var compile to a direct procedure - reference instead of a `var-deref`? Enables inlining and call-site folding. - Opt-out is per-target: a `^:redef` or `^:dynamic` var always links indirect. -- **whole-program?** — does inference see the whole reachable program at once - (closed world), so a record param's callers in other namespaces are visible - and its field reads specialize? Without it, inference is per-namespace and a - cross-ns param de-specializes to `:any` (the cross-ns penalty documented in - the `cross-ns-param-penalty` memory; declared `^RecordType` hints are the - open-world escape hatch). - -``` -dev: direct-link? = false whole-program? = false -release: direct-link? = true whole-program? = false -optimized: direct-link? = true whole-program? = true -``` - -`fl*`/`fx*` typed emission (unchecked flonum/fixnum Scheme ops) rides on -optimized: only whole-program inference proves the types that make dropping the -numeric-tower dispatch sound. Release keeps the tower. - -## CLI surface - -``` -jolt build [-m NS | FILE] [-o OUT] [--opt] [--dev] -``` - -- Resolves `deps.edn` exactly as `run` does (reuse `jolt.deps`). -- Default mode is **release**. `--opt` selects optimized; `--dev` builds an - unoptimized binary (useful to ship a debuggable build, not for the REPL). -- `-o` names the output (default the entry ns / file stem). -- Output is a single executable: a Chez boot file plus the compiled program, - launched by a thin wrapper, or a fully linked image where the platform allows. - App libraries are baked in — no source roots needed at runtime. - -Env opt-outs for the build (mirrors the Janet knobs, now keyed off the mode -rather than the run): `JOLT_NO_DIRECT_LINK` forces open linking even in a build, -`JOLT_NO_WHOLE_PROGRAM` keeps direct-link but per-namespace, `JOLT_WHOLE_PROGRAM=1` -forces whole-program. These already name the two knobs above. - -## Emission pipeline - -The in-process spine today (`host/chez/compile-eval.ss`) is, per form: - -``` -source → read → analyze (→ IR) → emit (→ Scheme string) → (eval (read …)) -``` - -`jolt build` keeps everything up to `emit` and replaces the per-form `eval` with -accumulate-then-compile: - -1. **Assemble the program.** Starting from the entry ns's `-main`, load the - transitive `require` graph (the loader already does this) and collect every - reachable top-level form, in dependency order, with its compile namespace. -2. **Dead-code elimination.** Re-target the uberscript DCE idea: compute - reachability from `-main` plus non-prunable forms, drop dead `defn`/`defn-`. - Bail to keep-all on `resolve`/`ns-resolve`/`requiring-resolve`/`find-var`/ - `intern`/`eval`/`load-string` (anything that defeats static reachability); - keep and scan `defmethod`/`defrecord`/`extend` bodies so dispatch targets - stay live. -3. **Emit to a file.** Run `analyze → emit` for each surviving form under the - mode's knobs, concatenating the Scheme strings into one program source (the - core overlay prelude first, exactly as the seed image is built today). -4. **Compile.** Feed that source to Chez `compile-program` (release) or - `compile-whole-program` (optimized, which also lets Chez cross-module - inline), producing a compiled object, then link a boot file / wrapper into - the final executable. - -Steps 3–4 are the only genuinely new back-end code. Step 2 is a re-port of a -deleted pass. Steps before them already run on every `joltc` invocation. - -## Turning the passes on - -`inline-enabled?` is the existing gate. Today `host-contract.ss` hardwires it to -`#f`. Under this RFC the build sets it (and a parallel `whole-program?` flag) -from the chosen mode before compiling, so: - -- release: `inline-enabled?` → true, whole-program off. Per-ns inference and - inlining light up; `fl*`/`fx*` stays off. -- optimized: both on; the types pass runs its whole-program fixpoint and the - back end may emit unchecked numeric ops where a flonum/fixnum is proven. - -No new pass is required to reach release — it is the ported passes, ungated. - -## Staging - -1. **Spike (de-risk Chez AOT).** Emit a trivial whole program to disk and prove - `compile-program` + boot/static link yields a standalone binary that runs. - This is the only real unknown. -2. **`jolt build` release.** Front-end + file-emitting back-end path + flip - `inline-enabled?` from the mode. Gate against the bench/corpus suites; binary - output must pass the corpus a `run` passes. -3. **DCE.** Re-port the reachability pass; gate with a test like the old - `uberscript-dce` case. -4. **Optimized.** Whole-program flag, `compile-whole-program`, `fl*`/`fx*` - emission. Gate on the bench suite (ray tracer, binary-trees) for size and - speed vs the spike baseline. - -Each stage is TDD against the existing gates (`make test`, `make corpus`, the -`bench/` programs). Modes land behind the build command, so dev — the only mode -today — is unaffected until a stage proves out. - -## Open questions - -- **Static vs. boot-file linking.** A fully static Chez image is the smallest, - most portable artifact but the most work to link; a boot file plus a stub - launcher is the easy first cut. Spike decides which step 1 targets. -- **FFI in a built binary.** `jolt.ffi` loads native libraries at runtime; a - closed-world build still needs that to work. The build must bake the FFI - Clojure side and keep dynamic `dlopen` at run time. -- **Macro and `eval` at runtime.** Release/optimized are closed-world, but an - app that calls `eval`/`load-string` needs the compiler present. Either ship - the compiler image in the binary (larger) or reject those builds (the DCE - bail-out already detects the calls). - -## Prior art in this repo - -The optimization design these modes turn on is RFC 0004 (type hints), RFC 0005 -(structural inference), RFC 0006 (success checking). The linking model — direct -linking as a per-unit property, `^:redef`/`^:dynamic` as the only opt-out — and -the cross-ns specialization penalty are recorded in beads memories -(`jolt-linking-model`, `cross-ns-param-penalty`). Phase 4 (`jolt-cf1q.5`) is the -tracking issue. diff --git a/docs/rfc/README.md b/docs/rfc/README.md deleted file mode 100644 index 083d9c3..0000000 --- a/docs/rfc/README.md +++ /dev/null @@ -1,21 +0,0 @@ -# RFCs - -Design notes for non-obvious language and compiler decisions. An RFC records *why* -a thing is built the way it is; the code is the source of truth for *how*. - -| # | Title | Status | Governs | -| --- | --- | --- | --- | -| [0001](0001-language-specification.md) | A Specification for the Clojure Language | Draft | The conformance target — what "is Clojure" means for jolt. | -| [0002](0002-reader-conditional-features.md) | Reader-Conditional Feature Set | Accepted | `#?(...)` feature keys (`:jolt`, `:clj`, `:default`). | -| [0003](0003-transients.md) | Transients | Accepted | `transient`/`persistent!` semantics + the Chez mutable backing. | -| [0004](0004-type-hints.md) | Type hints + keyword-lookup specialization | Accepted | `^Type`/`^:struct` hints → the bare-`get` fast path. | -| [0005](0005-structural-type-inference.md) | Structural collection-type inference | Implemented | The `:struct`/`:vec`/`:set` lattice in `passes/types`. | -| [0006](0006-success-type-checking.md) | Success typing (provably-wrong-code detection) | Implemented | The error-domain checker in `passes/types`. | -| [0007](0007-compilation-modes-and-binary-output.md) | Compilation modes + binary output | Implemented (doc lags) | `release`/`--opt`/`--dev`, `--direct-link`, `--tree-shake`. | - -RFC 0007's own status line still says "Draft, no code yet" — that is stale: -direct-linking and tree-shaking shipped (see [tools-deps.md](../tools-deps.md) and -`backend_scheme.clj` / `build.ss`). Two compiler features that grew alongside it — -**IR inlining** (`passes/inline.clj`, under `--opt`) and **numeric `fl*`/`fx*` -lowering** from `^double`/`^long` hints (`passes/numeric.clj`) — are not yet written -up as RFCs; their touch points are in [../MODULES.md](../MODULES.md). diff --git a/docs/seed-overlay-registry.md b/docs/seed-overlay-registry.md deleted file mode 100644 index 9218c9f..0000000 --- a/docs/seed-overlay-registry.md +++ /dev/null @@ -1,45 +0,0 @@ -# Seed ↔ Overlay Registry - -Jolt is Clojure on Chez Scheme. `clojure.core` is built from two tiers that both -define `clojure.core`-facing vars, and for a handful of names *both* tiers carry -a definition. This document records how the two tiers relate and which copy is -authoritative. - -## The two tiers - -- **Native shims** (`host/chez/natives-*.ss`) bind a set of `clojure.core` vars - directly to Scheme runtime values via `def-var!` — collection constructors, - seq fns, numeric/string ops, and so on. These cover names the overlay assumes - exist as bare `clojure.core` vars but does not define itself. -- **The Clojure overlay** (`jolt-core/clojure/core/NN-*.clj`) defines the rest of - `clojure.core` in dependency-ordered tiers, loaded in order: `00-syntax`, - `00-kernel`, `10-seq`, `20-coll`, `25-sorted`, `30-macros`, `40-lazy`, `50-io`. - -The overlay loads after the native shims. When an overlay tier `(defn X …)` for a -name a native shim already bound, the **overlay def shadows the native binding** — -user code sees the overlay copy. The native binding then survives only if some -other native/runtime code still calls the Scheme value directly. - -So a name's *home* is determined by two facts: - -1. is it bound by a native shim? (the Scheme value is reachable from the runtime) -2. does an overlay tier `(defn X …)`? (the overlay copy is what user code sees) - -## The compiled seed - -`clojure.core` is compiled ahead of time into the checked-in seed -(`host/chez/seed/{prelude,image}.ss`) as Scheme `def-var!` forms. The seed's -source twin is the overlay (`jolt-core/clojure/core/*.clj` plus the stdlib -namespaces under `stdlib/clojure/`); `host/chez/emit-image.ss` re-emits the -prelude from those sources on Chez. The build is a byte-fixpoint: rebuilding from -an up-to-date seed reproduces it exactly. - -## Consistency guard - -There is no separate drift-check test for the registry. The self-hosting -fixpoint is the guard: after changing a seed source (a core tier, the compiler -namespaces, the host contract, the reader, or `emit-image.ss`) you must re-mint -the seed (`make remint`), and `make selfhost` fails if the checked-in seed and -its sources have drifted. So if the overlay's shadowing relationship changes, the -re-minted prelude changes with it, and the fixpoint check keeps source and seed -in agreement. diff --git a/docs/spec/00-front-matter.md b/docs/spec/00-front-matter.md deleted file mode 100644 index 1e974952..0000000 --- a/docs/spec/00-front-matter.md +++ /dev/null @@ -1,88 +0,0 @@ -# Clojure Language Specification — Front Matter - -**Edition**: Draft 1 · **Describes**: Clojure 1.12 (reference) · **Status**: in progress - -This document specifies the Clojure programming language independently of any -implementation. See `docs/rfc/0001-language-specification.md` for motivation, -process, and scope. - -## 1. Conformance terminology - -The key words **MUST**, **MUST NOT**, **SHOULD**, **SHOULD NOT**, and **MAY** -are to be interpreted as described in RFC 2119. - -- A statement marked **MUST** is normative: a conforming implementation - exhibits exactly this behavior, and the conformance suite tests it. -- **implementation-defined** marks behavior a conforming implementation must - document but may choose (e.g. the concrete error type thrown where the - reference throws a JVM exception class). -- **host-defined** marks behavior delegated to the host platform (e.g. what - `slurp` accepts as a source). -- **⚠ reference-divergence** marks a place where this spec deliberately - differs from observed reference behavior, with rationale; the reference - behavior is always recorded alongside. - -## 2. Classification of the core surface - -Every `clojure.core` var carries exactly one classification (dashboard: -`coverage.md`): - -| Class | Meaning | Spec treatment | -|---|---|---| -| **portable** | semantics independent of host | full normative entry (§9) | -| **host-dependent** | portable *interface*, host-defined behavior | interface entry; behavior host-defined | -| **JVM-specific** | meaningful only on the JVM | catalogued in Appendix; not specified | - -Initial classifications are mechanical and reviewable; reclassification is an -ordinary spec change. - -## 3. The normative entry format - -Each special form (§3) and portable var (§9) is specified as: - -``` -### name — since -(signature ...) (signature ...) - -Semantics - S1. - S2. ... -Edge cases - E1. -Errors - X1. -Examples - -Conformance - S1 → /; E1 → ... (statements without a test: UNVERIFIED) -``` - -The **Conformance** field is load-bearing: every numbered statement names the -test(s) that verify it. A normative statement with no test is labeled -`UNVERIFIED` and is a defect in the spec. - -## 4. Evidence and verification - -Behavioral questions are settled in this order: differential testing against -the reference implementation → cross-dialect agreement in clojure-test-suite -→ ClojureDocs community examples (verified before inclusion) → reference -source (for intent). Conformance tests live in this repository -(the corpus `test/chez/corpus.edn`, run on Chez via `host/chez/run-corpus.ss` -and certified against reference JVM Clojure by `test/conformance/certify.clj`) -and in the cross-dialect clojure-test-suite. - -## 5. Chapter plan - -| § | File | Status | -|---|---|---| -| 1 | `01-evaluation.md` | planned | -| 2 | `02-reader.md` | **drafted** (grammar + reader-macro catalog; 2 divergences open) | -| 3 | `03-special-forms.md` | **exemplars written** (`if`, `let*`); catalog complete | -| 4 | `04-data-types.md` | planned (numeric-tower design note required) | -| 5 | `05-sequences.md` | planned (laziness contract from jolt Phase-5 work) | -| 6 | `06-namespaces-vars.md` | planned | -| 7 | `07-polymorphism.md` | planned | -| 8 | `08-macros.md` | planned | -| 9 | `09-core-library.md` | **exemplars written** (`first`, `reduce`, `parse-uuid`) | -| A | `coverage.md` | **generated** (regenerate: `python3 tools/spec_coverage.py`) | diff --git a/docs/spec/02-reader.md b/docs/spec/02-reader.md deleted file mode 100644 index 169bae5..0000000 --- a/docs/spec/02-reader.md +++ /dev/null @@ -1,255 +0,0 @@ -# §2 The Reader (Lexical Syntax) - -**Status**: token grammar drafted; reader-macro catalog complete with -normative entries; #inst and literal-collapse divergences resolved. -Conformance: jolt `reader-forms-spec` + `reader-syntax-spec` (granularity -model: jank's per-construct corpus, 62 files under -`test/jank/{reader-macro,syntax-quote}` — adapted rows cited per entry). - -The reader maps a stream of characters to *forms* (data). Reading is -independent of evaluation: every form the reader produces is a value of the -language (§4), and `read-string` exposes the reader as a function. Evaluation -of forms is §1's concern; only `quote`-family reader macros reference it here. - -## 2.1 Tokens - -Whitespace is space, tab, newline, return, **and comma** (`,` is whitespace — -S1). A `;` begins a comment to end of line (S2). Tokens: - -``` -form := literal | symbol | keyword | list | vector | map | set - | reader-macro-form -list := '(' form* ')' -vector := '[' form* ']' -map := '{' (form form)* '}' -literal := nil | boolean | number | string | character -nil := 'nil' boolean := 'true' | 'false' -``` - -- S3. A map literal MUST contain an even number of forms; duplicate keys - MUST be an error at read time. -- S4. A set literal (`#{…}`, §2.3) with duplicate elements MUST be an error - at read time. - -### Numbers - -``` -integer := ['+'|'-'] (digits | '0' [xX] hexdigits | '0' octdigits | radixR digits) -float := ['+'|'-'] digits '.' digits? exponent? | ['+'|'-'] digits exponent -ratio := ['+'|'-'] digits '/' digits ; host-numeric-tower (§4 note) -exponent := [eE] ['+'|'-'] digits -``` - -- S5. Trailing `N` (BigInt) and `M` (BigDecimal) suffixes are part of the - grammar; their value semantics are the §4 numeric-tower question. - Implementations without those towers SHOULD read them as the nearest - numeric type and MUST document the choice. The Chez host carries the full - tower: `N` reads as an exact integer (arbitrary precision) and `M` as a real - BigDecimal — `1.5M`, `0.0M`, `3M` — with value equality ignoring scale - (`1.0M = 1.00M`), `(class 1.5M)` ⇒ `java.math.BigDecimal`, and `decimal?` true. - -### Symbols and keywords - -``` -symbol := name | ns '/' name ; '/' alone names the division fn -keyword := ':' name | ':' ns '/' name | '::' name | '::' alias '/' name -``` - -- S6. Symbol constituent characters: alphanumerics and `* + ! - _ ' ? < > = - . $ & %` (with `%` and `&` further constrained inside `#()`); a symbol - MUST NOT begin with a digit; `.` and `/` have positional restrictions. -- S7. `::kw` MUST resolve to the current namespace at *read* time - (`::k` in ns `user` reads as `:user/k`); `::alias/k` resolves `alias` through - the current namespace's aliases. (Clojure raises a read error for an unknown - alias; jolt reads it as `:alias/k`.) - -### Strings and characters - -- S8. Strings are `"…"` with escapes `\" \\ \n \t \r \b \f \uNNNN \oNNN`. -- S9. Character literals: `\c`, the named set `\newline \space \tab - \return \backspace \formfeed`, unicode `\uNNNN`, octal `\oNNN`. - -**Conformance** (2.1): jolt `reader-syntax-spec` "dispatch & sugar"; -clojure-test-suite reader files; jank `form/*` literal dirs. S3/S4 duplicate -checks → UNVERIFIED (rows to add). - -## 2.2 Quote-family reader macros - -| Sugar | Reads as | | -|---|---|---| -| `'form` | `(quote form)` | S10 | -| `@form` | `(clojure.core/deref form)` | S11 | -| `^meta form` | form with metadata attached (see below) | S12 | -| `#'sym` | `(var sym)` | S13 | -| `` `form `` | syntax-quote (§2.4) | | -| `~form`, `~@form` | unquote / unquote-splicing — only within syntax-quote (S14: MUST error outside) | | - -- S11. `@form` reads as `(clojure.core/deref form)` — the operator is the - fully-qualified `clojure.core/deref`, not a bare `deref`, so `@x` still - dereferences in a namespace that excludes and rebinds `deref` - (`(ns … (:refer-clojure :exclude [deref]))`), matching Clojure. -- S12a. `^:kw form` ≡ `^{:kw true} form`; `^Sym form` ≡ `^{:tag Sym} form`; - `^"str"` ≡ `^{:tag "str"} form`. Multiple `^` stack, rightmost innermost, - merged left-over-right. -- S12b. Type hints are semantically transparent: a hint MUST NOT change a - program's result. Hints parse in every position they do in Clojure (params, - `let` bindings, `def` names, return position, arbitrary forms) and are - otherwise inert. As a non-normative optimization, jolt recognizes two hints - on a local as an assertion that a constant-keyword lookup may skip its - runtime representation guard: `^:struct` (a plain struct/record map) and - `^Name` where `Name` is a `defrecord`/`deftype`. The assertion is the - programmer's (an inaccurate hint yields a wrong lookup, like a wrong Clojure - `^String`); `JOLT_CHECK_HINTS=1` turns a violated hint into an error at no - cost to unchecked builds. See RFC 0004. -- S13a. `#'ns/sym` MUST denote the same var as `(var ns/sym)`: - `(= (var clojure.core/str) #'clojure.core/str)` is true. - -**Conformance**: jolt `reader-forms-spec` "var-quote #'", "metadata ^", -"syntax-quote"; jank `var-quote/pass-qualified.jank`, `metadata/*`. - -## 2.3 Dispatch (`#`) reader macros - -| Form | Meaning | Entry | -|---|---|---| -| `#{…}` | set literal | S4 above | -| `#"…"` | regex literal — reads to a regex value; escaping is regex-level, not string-level (single `\d`) | S15 | -| `#(…)` | anonymous fn | S16 below | -| `#_form` | discard | S17 below | -| `#?(…)` / `#?@(…)` | reader conditional (+splicing) | S18 below | -| `##Inf ##-Inf ##NaN` | symbolic floats | S19 | -| `#tag form` | tagged literal | S20 below | -| `#! …` | shebang comment line (implementations SHOULD accept) | | - -### S16 — anonymous function `#(…)` - -- `#(body)` reads as `(fn [args…] (body))` with parameters derived from the - `%`-symbols appearing in body: `%`≡`%1`, `%n` positional, `%&` the rest - parameter. Arity = highest `%n` mentioned (plus rest if `%&`). -- The `%`-symbols are collected from the WHOLE body, recursing through every - nested form including vector, map and set literals — `#(assoc {} :k %)`, - `#(hash-set % %2)` and `#(get {:t %} :t)` all see their `%`s. (A reader that - scanned only call forms would miscompile `#(identity {:text %})` as a 0-arg fn.) -- The synthesized parameters are auto-gensyms (their names carry the `#` suffix, - like Clojure's `p1__N#`), so an `#()` written inside a syntax-quote survives: - the params are mapped consistently and left unqualified rather than being - qualified to the current namespace (a qualified symbol is not a valid - parameter). E.g. `` `(map #(inc %) xs) `` expands correctly inside a macro. -- `#()` literals MUST NOT nest. - -```clojure -(#(+ %1 %2) 1 2) ;=> 3 -(apply #(apply + %&) [1 2 3]) ;=> 6 -(map #(* % %) [1 2]) ;=> (1 4) -``` - -### S17 — discard `#_` - -- `#_form` reads and discards the next form entirely (it is never evaluated). -- Discards compose: `#_ #_ a b` discards two following forms. -- `#_` inside collection literals removes the element: `[1 #_2 3]` ⇒ `[1 3]`. - -### S18 — reader conditionals - -- `#?(:feat₁ f₁ :feat₂ f₂ …)` reads as the form of the first feature key the - platform satisfies, else nothing. `:default` matches any platform. - `#?@(…)` splices a sequential form into the surrounding context. -- Feature keys are implementation-defined; each implementation MUST document - its feature set, and SHOULD follow the portable convention *own dialect key - + `:default`*. Matching MUST be by **clause order** — the first clause whose - key the platform satisfies wins (`#?(:default 5 :clj 6)` is `5` everywhere) - — not by key priority. Implementations SHOULD provide a per-loading-context - compatibility override for foreign-dialect libraries. (jolt: - `#{:jolt :clj :default}` — jolt emulates `clojure.lang.*`/`java.*`, so it - reads the `:clj` branch of a `.cljc` library by default; a library can put a - `:jolt` branch first to override, or a loading context can call - `reader-features-set!`. History in RFC 0002.) -- Reader conditionals MUST be an error outside `.cljc`-style reading unless - the implementation documents otherwise. - -### S19 — symbolic values - -`##Inf`, `##-Inf`, `##NaN` read as the IEEE-754 values. `(= ##NaN ##NaN)` is -false; `(NaN? ##NaN)` is true. - -### S20 — tagged literals - -- `#tag form`: the reader resolves `tag` in the data-reader table and MUST - apply the reader function to the *read* form, yielding its result as the - read value. An unknown tag MUST be a read error (jank - `fail-unsupported-tag`). -- Built-in tags every implementation MUST provide: `#uuid "…"` → a UUID - value (§9 `parse-uuid` semantics — round-trips through printing), and - `#inst "…"` → an instant value: RFC3339 with partial-timestamp defaults - (`#inst "2020"` ≡ `#inst "2020-01-01T00:00:00.000-00:00"`), equality by - instant (offset-normalized), `inst?`/`inst-ms` (epoch milliseconds), printed - canonically as `#inst "yyyy-MM-ddThh:mm:ss.fff-00:00"` and round-tripping. A - malformed timestamp MUST be an error. - -**Conformance** (2.3): jolt `reader-forms-spec` "#() (% %N %&)" + new rows -(symbolic values, stacked discard, conditionals); `uuid-spec` reader-literal -group; jank `reader-macro/{function,regex,uuid,symbolic-value}/*`, -`fail-unsupported-tag.jank`. - -## 2.4 Syntax-quote - -Syntax-quote (`` ` ``) is read-level template construction with namespace -resolution: - -- S21. Inside syntax-quote, an unqualified symbol that resolves in - `clojure.core` MUST be qualified to `clojure.core/sym`; a symbol resolving - through a namespace alias MUST be qualified to the aliased namespace; an - unresolved symbol MUST be qualified to the current namespace. Special-form - names stay bare. -- S22. `sym#` generates a fresh symbol, stable *within one syntax-quote - template* (all `sym#` in the same template denote the same generated - symbol; distinct templates generate distinct symbols). -- S23. `~form` inserts the value of `form`; `~@form` splices a sequential - value; `~'sym` is the idiom for an intentionally-unqualified symbol. -- S24. Syntax-quote distributes through collection literals (vectors, maps, - sets) — qualification and unquoting apply inside them. -- S25. A syntax-quoted self-evaluating literal is the literal, collapsed at - read time — so nested/adjacent backticks over literals are inert: - `(= "meow" ```"meow")` is true. General nested syntax-quote over symbols - and collections expands recursively (quasiquote semantics) — that general - case remains UNVERIFIED pending dedicated conformance rows. - -**Conformance**: jolt `reader-forms-spec` "syntax-quote" (gensym, unquote, -splice) + conformance "syntax-quote fully-qualifies"; jank -`syntax-quote/{pass-gensym,pass-namespace-resolution,pass-resolve-alias, -unquote,unquote-splice}/*`. S25 → UNVERIFIED. - -## 2.5 What the reader is not - -The reader performs **no macroexpansion and no evaluation** (tagged-literal -reader functions are the deliberate exception, S20). Forms read identically -whether or not they will be evaluated; `read-string` of any printable value -`v` followed by evaluation yields a value equal to `v` for the -self-evaluating types (§4 print/read round-trip contract). - -## Strict tokens and edn mode - -The reader rejects what the reference rejects (corpus `edn / strictness`, -`reader / strict tokens`): - -- A token that starts like a number but doesn't parse as one is - NumberFormatException, never a symbol: `1a`, `08` (a leading zero demands - octal digits; `042` is 34), `0x2g`, `2r2`. A ratio's parts are plain digit - runs (`1/-1` is invalid); a zero denominator is ArithmeticException. -- Empty ns/name parts are invalid tokens: `:`, `::`, `foo/`, `/foo`, `:/foo`. - `/` (division), `ns//` and `:/` (a name of exactly `/`) are valid. -- Map literals with duplicate keys and set literals with duplicate elements - throw IllegalArgumentException at read. -- An unsupported string escape (`"\q"`) and an octal escape past `\377` - (string or `\o` char) throw. A stray close delimiter at top level is - "Unmatched delimiter". `\r` terminates a line comment like `\n`. -- `#inst` validates its calendar fields progressively (month 1–12, day valid - for the month including leap years, hour < 24, minute < 60); `#uuid` - demands canonical 8-4-4-4-12 hex. - -clojure.edn adds on top of that (`__read-form-edn` seam): auto-resolved -keywords (`::k`) are invalid (no resolution context), each `#_` discarded -form is validated through the same `:readers`/`:default` pipeline (an -unreadable tagged element throws even when discarded), `M` literals -construct BigDecimals, lists satisfy `list?`, and end-of-input honors the -`:eof` option — an opts map without `:eof` makes EOF an error, while the -no-opts arity returns nil. diff --git a/docs/spec/03-special-forms.md b/docs/spec/03-special-forms.md deleted file mode 100644 index 3a19e3f..0000000 --- a/docs/spec/03-special-forms.md +++ /dev/null @@ -1,155 +0,0 @@ -# §3 Special Forms - -**Status**: catalog complete; normative exemplars for `if` and `let*`; the -remaining entries follow the same format (tracked in `coverage.md`). - -A *special form* is a form whose head symbol is evaluated by rule rather than -by function application or macroexpansion. The special forms of Clojure are: - -> `def` · `if` · `do` · `let*` · `fn*` · `loop*` · `recur` · `quote` · `var` -> · `throw` · `try`/`catch`/`finally` · `set!` · `monitor-enter` · -> `monitor-exit` (host) · the interop forms `.` and `new` (host) - -`let`, `fn`, `loop`, `and`, `or`, `when`, … are **macros** over these (§8); -implementations MUST treat them as redefinable macros, not additional special -forms. `monitor-enter`/`monitor-exit`, `.` and `new` are host forms: their -syntax is specified here, their behavior is host-defined. - -Special-form head symbols are not shadowable: a binding named `if` does not -change the meaning of `(if ...)` in operator position. ⚠ This matches the -reference; it differs from Scheme. A local *may* legally be named like a special -form and used in value position (`(let [if 5] if)` ⇒ `5`); only operator -position is reserved. **Macros, unlike special forms, ARE shadowable** by a local -(`(let [when (fn ...)] (when 1 2))` calls the local). - -A list form in operator position is resolved in this order (the canonical -read → **macroexpand** → analyze pipeline): a local binding shadows everything; -otherwise a macro head is expanded and the result re-analyzed; otherwise a -special-form head is parsed by rule; otherwise the form is a function -application. Macroexpansion therefore happens *before* special-form dispatch, so -a macro is never mistaken for a special form (and vice versa). - ---- - -### if — since 1.0 - -``` -(if test then) -(if test then else) -``` - -**Semantics** - -- S1. `test` MUST be evaluated first, exactly once. -- S2. Every value other than `nil` and `false` is *logically true*. If the - value of `test` is logically true, `then` MUST be evaluated and its value - returned; otherwise `else` (or `nil` when absent) MUST be evaluated and its - value returned. -- S3. The branch not taken MUST NOT be evaluated. -- S4. `if` MUST be usable in tail position with respect to `recur` (§3 - `recur`): an `if` whose branch is a `recur` form is a valid recur target - path. - -**Edge cases** - -- E1. `(if test then)` with a logically false `test` evaluates to `nil`. -- E2. The empty collections (`()`, `[]`, `{}`, `#{}`), the number `0`, and - the empty string `""` are logically **true** (only `nil`/`false` are - false). ⚠ This differs from several Lisps and is a frequent divergence - source in alternative implementations. - -**Errors** - -- X1. `(if)` and `(if test)` with fewer than two argument forms, or more - than three, MUST be a compile-time error. - -**Examples** - -```clojure -(if 0 :t :f) ;=> :t -(if "" :t :f) ;=> :t -(if nil :t :f) ;=> :f -(if false :t) ;=> nil -``` - -**Conformance** - -S1–S3, E1–E2 → jolt `forms-spec` "if/do/def" group; truthiness group in -`truthiness-spec`; clojure-test-suite `core_test/if.cljc`. S4 → `forms-spec` -fn/loop recur cases. X1 → `forms-spec` "if arity (X1)" (0/1/4-arg forms throw -in both the analyzer and the interpreter). - ---- - -### let* — since 1.0 - -``` -(let* [sym₁ init₁ … symₙ initₙ] body…) -``` - -`let*` is the primitive sequential-binding form. The user-facing `let` macro -adds destructuring and expands to `let*` (§8); `let*` itself accepts **only -simple symbols** in binding positions. - -**Semantics** - -- S1. Each `initᵢ` MUST be evaluated in order, exactly once, in an - environment where `sym₁…symᵢ₋₁` are bound to their values (sequential - scope, as Scheme `let*`). -- S2. The body forms MUST be evaluated in order with all bindings in scope; - the value of the last body form is the value of the `let*` form. An empty - body evaluates to `nil`. -- S3. A later binding MAY rebind the same symbol; each binding creates a new - lexical binding visible from the next init onward (no mutation of the - earlier binding is implied). -- S4. Bindings are lexical and immutable: there is no form that assigns to a - `let*`-bound local. (Closures capture bindings by value; see §3 `fn*`.) -- S5. The binding vector MUST be a vector literal with an even number of - forms. - -**Edge cases** - -- E1. `(let* [] body)` is valid and equivalent to `(do body…)`. -- E2. Binding a symbol that names a var shadows the var for the lexical - extent of the body; `(var sym)` within that extent still denotes the var. - -**Errors** - -- X1. An odd number of binding forms MUST be a compile-time error. -- X2. A non-symbol in a binding position (e.g. a destructuring pattern) MUST - be a compile-time error for `let*` — destructuring belongs to the `let` - macro. ("Bad binding form, expected symbol" in the reference.) - -**Examples** - -```clojure -(let* [a 1 b (+ a 1)] (* a b)) ;=> 2 -(let* [x 1 x (inc x)] x) ;=> 2 -(let* [] 42) ;=> 42 -``` - -**Conformance** - -S1–S3, E1 → jolt `forms-spec` let group; clojure-test-suite -`core_test/let.cljc`; jank corpus `form/let/*`. X2 → jolt -`destructuring-spec` "primitives reject patterns". S4, X1 → UNVERIFIED -(cases to add). - ---- - -## Remaining entries (format above; status in coverage.md) - -| Form | Notes for the entry author | -|---|---| -| `def` | var creation vs re-binding; metadata on the name; `(def x)` unbound; return value is the var | -| `do` | empty `(do)` → nil; top-level `do` splices for compilation units (important and under-documented) | -| `fn*` | arities, variadic `&`, closure capture, self-name, simple-symbol params only, recur target | -| `loop*` | recur arity must match bindings; recur rebinds in place | -| `letfn` | mutually-recursive local fns (`letrec*` semantics — a fn body sees every binding, not only earlier ones). jolt treats `letfn` as a primitive special, not the reference's `letfn` macro → `letfn*` indirection; behavior is identical | -| `recur` | tail-position rule (normative definition of tail position needed), across `if`/`do`/`let*`/`try` interactions | -| `quote` | self-evaluation table: which literals are self-evaluating unquoted | -| `var` | `#'` reader sugar; resolution at compile time | -| `throw` | any value vs Throwable — host question; jolt/cljs allow data, reference requires Throwable → classification needed | -| `try/catch/finally` | catch dispatch order, `:default`-style catch-all is a dialect extension (⚠ divergence note), finally evaluation guarantees, value of try | -| `set!` | three targets, all implemented: `(set! *var* val)` sets the var's innermost thread binding (else root); `(set! field val)` inside a `deftype` method mutates a `^:unsynchronized-mutable`/`^:volatile-mutable` field in place; `(set! (.-field obj) val)` does the same via interop syntax. Returns val | -| `.` / `new` | syntax only; behavior host-defined | diff --git a/docs/spec/09-core-library.md b/docs/spec/09-core-library.md deleted file mode 100644 index 2d9138e..0000000 --- a/docs/spec/09-core-library.md +++ /dev/null @@ -1,366 +0,0 @@ -# §9 The Core Library - -**Status**: entry format fixed; exemplars for `first`, `reduce`, `parse-uuid`. -The full portable surface (≈500 vars after classification, dashboard in -`coverage.md`) is filled in chapter-by-chapter using this format. - -Entries specify *behavioral contracts*, not implementations. Performance -characteristics are specified only where the language community relies on -them (e.g. vector `nth` is "effectively constant time" — SHOULD-level). - ---- - -## Collection return types & laziness (cross-cutting) - -Two contracts hold across the sequence library and are not restated per entry. - -**Return-type fidelity.** A function returns the same *kind* of collection the -reference does — value equality is not enough, since `(= [0 1] '(0 1))`. - -- Sequence transformations return **seqs** (lazy unless noted): `map`, `filter`, - `remove`, `keep`, `mapcat`, `take`/`drop` and their `-while` forms, `partition`, - `partition-all`, `partition-by`, `interpose`, `dedupe`, `distinct`, `concat`, - `reductions`, `cons`, `rest`, `sequence`. The *elements* of `partition` / - `partition-all` / `partition-by` are themselves seqs, not vectors. -- The vector variants return **vectors**: `mapv`, `filterv`, `vec`, `subvec`, - `partitionv`, `partitionv-all`, `splitv-at`. `split-at` / `split-with` return a - 2-vector `[take drop]`. A transducer applied eagerly (`into []`, the - `partition-all` transducer's chunks) yields vectors. -- Type-preserving functions return the input's type: `replace` over a vector is a - vector, over any other seqable a (lazy) seq; `empty`/`into (empty coll)` keep the - collection kind; `set`/`into #{}` return sets; `into {}`/`select-keys`/`zipmap`/ - `frequencies`/`group-by`/`merge` return maps (`group-by` values are vectors). - -**Laziness.** The lazy sequence functions — including `sequence`, `eduction`, and -`mapcat` — MUST consume their source incrementally and so terminate on an infinite -or unbounded source when only a prefix is demanded: `(first (sequence (map inc) -(range)))` and `(take n (mapcat f (range)))` return without realizing the whole -source. `(apply concat coll-of-colls)` is likewise lazy in its argument seq. The -eager consumers (`reduce`, `into`, `count`, `vec`, `doall`) realize the demanded -portion fully. - -These are exercised by the `seq / lazy over infinite` and the per-fn type-predicate -rows in the conformance corpus. - ---- - -### first — since 1.0 - -``` -(first coll) -``` - -**Semantics** - -- S1. MUST return the first element of `(seq coll)`. -- S2. If `(seq coll)` is `nil` (i.e. `coll` is empty or `nil`), MUST return - `nil`. -- S3. MUST accept anything *seqable* (§5): seqs, lists, vectors, maps - (yielding map entries), sets, strings (yielding characters), `nil`. -- S4. On a lazy sequence, MUST realize at most the first element (§5 - laziness contract). - -**Edge cases** - -- E1. `(first nil)` ⇒ `nil`; `(first [])` ⇒ `nil`; `(first "")` ⇒ `nil`. -- E2. A `nil` or `false` first *element* is returned as-is — callers cannot - distinguish "empty" from "first element is nil" via `first` alone (that is - what `seq` is for). -- E3. On a map, the element is a map entry; on an unordered collection (map, - set) *which* element is first is implementation-defined but MUST be - consistent with that collection's seq order for the same collection value. - -**Errors** - -- X1. A non-seqable argument (e.g. a number) MUST throw. - -**Examples** - -```clojure -(first [1 2 3]) ;=> 1 -(first '()) ;=> nil -(first "ab") ;=> \a -(first {:a 1}) ;=> [:a 1] -(first [nil 2]) ;=> nil -``` - -**Conformance** - -S1–S3, E1–E2 → jolt `sequences-spec` "seq / access"; clojure-test-suite -`core_test/first.cljc`. S4 → jolt `lazy-seqs-spec` counter cases. X1 → -clojure-test-suite `core_test/first.cljc` (throwing cases). - ---- - -### reduce — since 1.0 - -``` -(reduce f coll) -(reduce f init coll) -``` - -**Semantics** - -- S1. With `init`: MUST return `init` if `(seq coll)` is nil; otherwise MUST - return `(f … (f (f init e₁) e₂) … eₙ)`, applying `f` left-to-right over the - elements, exactly once each. -- S2. Without `init`: if `coll` is empty, MUST return `(f)` (f called with - no arguments); if `coll` has one element, MUST return that element - *without calling `f`*; otherwise as S1 with `init = e₁` over `e₂…eₙ`. -- S3. **Reduced short-circuit**: if any intermediate result is a `reduced` - value, iteration MUST stop and the dereferenced value MUST be returned - immediately; `f` MUST NOT be called again. -- S4. `reduce` is eager: it MUST fully realize the consumed portion of a - lazy `coll` (to the end, or to the `reduced` point). - -**Edge cases** - -- E1. `(reduce f nil)` ⇒ `(f)`; `(reduce f init nil)` ⇒ `init`. -- E2. A `reduced` value as the *initial* `init` is NOT unwrapped before the - first call in the reference — ⚠ under-documented; differential result to - pin down and test before this entry is marked verified. -- E3. Visit order over maps is entry order of the map's seq; - over vectors/lists/seqs it is sequential order (normative). - -**Errors** - -- X1. Without `init`, on an empty coll, if `f` has no zero-arg arity the - call `(f)` MUST throw (arity error). - -**Examples** - -```clojure -(reduce + [1 2 3 4]) ;=> 10 -(reduce + 10 [1 2 3 4]) ;=> 20 -(reduce + []) ;=> 0 ; (+) is 0 -(reduce + [5]) ;=> 5 ; f not called -(reduce (fn [a x] (if (> a 2) (reduced a) (+ a x))) 0 [1 2 3 4 5]) ;=> 3 -``` - -**Conformance** - -S1–S3, E1 → jolt `sequences-spec` "map filter reduce" group + -`transducers-spec` "reduce honors reduced"; clojure-test-suite -`core_test/reduce.cljc`. S2 (single-element, f-not-called) → jolt conformance -"reduce single no init". E2 → UNVERIFIED (differential test to add). S4 → -`lazy-seqs-spec`. - ---- - -### parse-uuid — since 1.11 - -``` -(parse-uuid s) -``` - -**Semantics** - -- S1. If `s` is a string in canonical UUID form — five groups of hex digits - of lengths 8, 4, 4, 4, 12 separated by `-` — MUST return a UUID value `u` - such that `(uuid? u)` is true and `(str u)` is the lowercase form of `s`. -- S2. Parsing MUST be case-insensitive and equality on the results - case-insensitive: `(= (parse-uuid s) (parse-uuid (upper-case s)))` is true. -- S3. If `s` is a string not in canonical form, MUST return `nil`. - ⚠ reference-divergence: reference Clojure (java.util.UUID) additionally - accepts non-canonical forms like `"0-0-0-0-0"`; ClojureScript and other - dialects are strict. This spec adopts **strict** (the cross-dialect - behavior); the reference's permissiveness is recorded as host leniency. -- S4. UUID values MUST support value equality, hashing (usable as map keys - and set members), `str` (lowercase canonical form), and print as the - tagged literal `#uuid "…"` such that the printed form reads back equal - (§2 tagged literals). - -**Edge cases** - -- E1. `""`, over-long, truncated, non-hex characters, and misplaced dashes - ⇒ `nil`. - -**Errors** - -- X1. A non-string argument MUST throw. - -**Examples** - -```clojure -(parse-uuid "b6883c0a-0342-4007-9966-bc2dfa6b109e") ;=> #uuid "b6883c0a-…" -(uuid? *1) ;=> true -(parse-uuid "df0993") ;=> nil -(parse-uuid 1000) ;; throws -``` - -**Conformance** - -S1–S4, E1, X1 → jolt `uuid-spec` (30 cases) + 6 three-path conformance -cases; clojure-test-suite `core_test/parse_uuid.cljc`, -`core_test/uuid_qmark.cljc`, `core_test/random_uuid.cljc`. - ---- - -### clojure.template/apply-template, clojure.test/are — since 1.1 - -``` -(apply-template argv expr values) -(are argv expr & args) -``` - -**Semantics** - -- S1. `apply-template` MUST replace every occurrence of each `argv` symbol - in `expr` with its corresponding value by structural walk (postwalk symbol - substitution), not by lexical binding. Occurrences inside `quote` and at - any nesting depth substitute: `(apply-template '[x] '(f 'x) '[if])` ⇒ - `(f 'if)`. -- S2. `do-template` MUST partition `args` by `(count argv)` and expand to a - `do` of one substituted `expr` per group. -- S3. `clojure.test/are` MUST expand through `do-template` with `expr` - wrapped in `is`. Consequently `(are [x] (special-symbol? 'x) if def)` - asserts `(special-symbol? 'if)` and `(special-symbol? 'def)` — a - let-binding implementation is non-conforming (the quoted symbol would not - substitute). - -**Errors** - -- X1. `are` MUST throw at macroexpansion when `(count args)` is not a - positive multiple of a non-empty `(count argv)` (empty/empty is allowed). -- X2. `apply-template` MUST throw when `argv` is not a vector of symbols. - -**Conformance** - -S1–S3 → `test/chez/clojure-test.clj` (are with quoted template var); -clojure-test-suite `core_test/special_symbol_qmark.cljc` and every -`are`-based suite namespace. - ---- - -### make-hierarchy, derive, underive, isa?, parents, ancestors, descendants — since 1.0 - -``` -(make-hierarchy) -(derive tag parent) (derive h tag parent) -(underive tag parent) (underive h tag parent) -(isa? child parent) (isa? h child parent) -(parents tag) (ancestors tag) (descendants tag) ; + (f h tag) forms -``` - -**Semantics** - -- S1. A hierarchy is a pure value `{:parents {tag #{...}} :ancestors {...} - :descendants {...}}`; the 3-arity forms are pure, the shorter arities read and - mutate the global hierarchy. -- S2. `isa?` is true when `(= child parent)`, when the host type system says - parent is assignable from child (both classes), when the relationship was - `derive`d — including a relationship derived on one of a class child's - supers — or component-wise for equal-length vectors. -- S3. Class tags answer through the host type hierarchy: `(parents c)` includes - the class's direct supers (`bases` — a concrete class's chain roots at - `java.lang.Object`, an interface's does not); `(ancestors c)` is the - transitive set plus anything `derive`d on the class or its supers. A - deftype/defrecord class's ancestry includes its implemented protocol - interfaces and, for records, the record interfaces - (`clojure.lang.IRecord`/`IPersistentMap`/`Associative`/…; `clojure.lang.IType` - for a bare deftype). -- S4. `derive` returns the updated hierarchy (3-arity) or nil (2-arity); - deriving a relationship that already holds transitively, or one that would - create a cycle, throws. - -**Errors** - -- X1. `derive` asserts its argument shapes: parent must be a namespaced Named - value; tag must be a class or a Named value (namespaced in the 2-arity - global form); `(derive h tag tag)` fails the `not=` assert. AssertionError. -- X2. `underive`/`derive` with a non-hierarchy `h` throw at the parents - lookup (the map is called as a function, like the reference). -- X3. `(descendants h SomeClass)` throws UnsupportedOperationException - ("Can't get descendants of classes") — Java type inheritance is not - enumerable downward. - -**Conformance** - -S1–S4, X1–X3 → corpus `hierarchy / *` rows; clojure-test-suite -`core_test/{derive,underive,isa_…,parents,ancestors,descendants}.cljc` -(all fully passing). - ---- - -### atom, add-watch, remove-watch, set-validator!, get-validator — since 1.0 - -``` -(atom x & {:keys [meta validator]}) -(add-watch iref key f) (remove-watch iref key) -(set-validator! iref f) (get-validator iref) -``` - -**Semantics** - -- S1. Watches, validators, and reference metadata are one contract (the JVM's - ARef/IRef) shared by atoms, vars, and agents. `add-watch`/`remove-watch` - return the reference; re-adding a key replaces that watch in place. -- S2. A watch is called `(f key ref old new)` after a state change: atom - swap!/reset!/compare-and-set!, var ROOT changes (`def` on a watched var, - `var-set` outside a thread binding, `alter-var-root` — a thread-binding set - does not notify), and each agent action's state change. -- S3. A validator gates every state change and, via the `:validator` ctor - option, the initial value — an invalid initial value never constructs the - reference. -- S4. The `:meta` ctor option attaches reference metadata (`meta` reads it, - `alter-meta!`/`reset-meta!` update it); nil is allowed. - -**Errors** - -- X1. A rejected value (validator returns logical false or the ctor option - fails on the initial value) throws IllegalStateException "Invalid reference - state". -- X2. A non-map `:meta` ctor option throws ClassCastException. - -**Conformance** - -S1–S4, X1–X2 → corpus `iref / *` rows; clojure-test-suite -`core_test/{atom,add-watch,remove-watch}.cljc` (the remaining baselined error -in the watch namespaces is their STM `ref` section — refs are out of scope, -`stm-refs` in `coverage.md`). - ---- - -### clojure.string coercion, some-fn, ifn? — since 1.2/1.3 - -``` -(clojure.string/upper-case s) … (some-fn p & ps) (ifn? x) -``` - -**Semantics** - -- S1. The clojure.string case fns and searches (`upper-case`, `lower-case`, - `capitalize`, `starts-with?`, `ends-with?`, `includes?`, `index-of`, - `replace`) take any Object `s` through its `toString`, like the reference's - `^CharSequence`+`.toString` signatures: `(upper-case :kw)` is `":KW"`, - `(capitalize 1)` is `"1"`. nil throws (method call on null); a nil `substr` - throws. -- S2. `some-fn` follows the reference arities: at least one predicate - (`(some-fn)` is an arity error) and the returned fn chains with `or`, so a - no-match result is the last predicate's own falsy value (`false` stays - `false`). -- S3. `ifn?` covers fns, keywords, symbols, maps, sets, vectors, vars, - multimethods, promises (invoking a promise delivers it), and a - deftype/defrecord implementing `clojure.lang.IFn`'s `invoke`. -- S4. A `defmulti`/`defmethod` deferred inside a fn body interns/resolves in - the namespace it was WRITTEN in (the macros bake their expansion ns), not - whatever namespace is current when it runs. - -**Conformance** - -S1–S4 → corpus `string / toString coercion`, `core / some-fn`, `core / ifn?`, -`multimethods / deferred definition`; clojure-test-suite string/some-fn/ -ifn-qmark/boolean-qmark/reduce namespaces (all fully passing). - ---- - -## Authoring notes - -- Source examples from the ClojureDocs export (`clojuredocs-export.edn`, - 648 core vars have community examples) — but every example is verified - against the reference before inclusion. -- When writing an entry surfaces a behavior question, settle it by - differential test first; if dialects split, that's a classification - decision (host-dependent / divergence note), not a coin flip. -- An entry is **Verified** when no field carries UNVERIFIED; `coverage.md` - tracks per-var status. diff --git a/docs/spec/README.md b/docs/spec/README.md deleted file mode 100644 index 1dfecab..0000000 --- a/docs/spec/README.md +++ /dev/null @@ -1,55 +0,0 @@ -# The Clojure Language Specification (Draft) - -A normative, implementation-independent specification of the Clojure -language, developed alongside jolt's self-hosted compiler and validated by -its executable conformance suites. **Why**: Clojure has no spec — every -alternative implementation re-derives semantics from the reference -implementation and folklore. See the RFC for motivation, scope, evidence -sources, and process: [`../rfc/0001-language-specification.md`](../rfc/0001-language-specification.md). - -## Documents - -| Doc | Content | Status | -|---|---|---| -| [`00-front-matter.md`](00-front-matter.md) | conformance terms, entry format, host classification | drafted | -| [`02-reader.md`](02-reader.md) | token grammar + reader-macro catalog | drafted | -| `01`, `04`–`08` | see chapter plan in front matter | planned | -| [`03-special-forms.md`](03-special-forms.md) | special-form catalog + normative exemplars (`if`, `let*`) | exemplars | -| [`09-core-library.md`](09-core-library.md) | per-var entry format + exemplars (`first`, `reduce`, `parse-uuid`) | exemplars | -| [`coverage.md`](coverage.md) | generated dashboard over the 694-var surface | generated | -| [`../grammar.ebnf`](../grammar.ebnf) | reader surface syntax (EBNF), companion to `02-reader.md` | reference | - -Regenerate the dashboard after surface changes: -`python3 tools/spec_coverage.py` (reads `tools/clojuredocs-export.json` and -probes a working jolt checkout via `bin/joltc`). - -## Current numbers (2026-06-22) - -Of the 694 `clojure.core` vars in the ClojureDocs inventory, jolt interns 574. -Broadly: - -- **568** implemented in jolt *and* exercised by the behavioral suites -- **6** implemented but not directly tested — each gets a test with its spec entry -- **6** portable but absent from jolt's resolvable surface (the REPL history - vars `*1`/`*2`/`*3`/`*e`, plus `letfn`/`re-groups`, which work but aren't - interned where `resolve` can see them) — tracked as gaps -- the rest classified host/JVM/concurrency (see the dashboard for the full - per-var breakdown — it is the source of truth) - -## How this connects to the test suites - -- `test/chez/corpus.edn` — the host-neutral behavioral corpus, one row per - case (`{:suite :label :expected :actual}`). The Chez compiler evaluates each - case via `host/chez/run-corpus.ss` (run with `make corpus`), and - `test/conformance/certify.clj` certifies every `:expected` against reference - JVM Clojure (run with `make certify`). Spec entries cite these cases. -- `test/conformance/` — the certification tooling and classified divergences - (`certify.clj`, `known-divergences.edn`); see its `README.md` and `SPEC.md`. -- `vendor/clojure-test-suite` — the cross-dialect suite (≥4081 assertions - passing); dialect splits there are classification evidence. -- jank's per-construct corpus (`~/src/jank/compiler+runtime/test/jank`) is - the granularity model for §2/§3 conformance. - -The invariant: **every numbered normative statement names its conformance -test**, or is marked UNVERIFIED. The spec cannot drift from the -implementations that check it. diff --git a/docs/spec/coverage.md b/docs/spec/coverage.md deleted file mode 100644 index cad2def..0000000 --- a/docs/spec/coverage.md +++ /dev/null @@ -1,721 +0,0 @@ -# Appendix A — Coverage Dashboard (generated) - -Generated 2026-06-26 by `tools/spec_coverage.py` — do not edit by hand. - -Surface: **694** clojure.core vars (ClojureDocs export; 648 with -community examples). jolt interns 594 of them. - -| Status | Count | Meaning | -|---|---|---| -| implemented+tested | 590 | in jolt and exercised by spec/conformance | -| implemented-untested | 4 | in jolt, no direct test — spec entries will add them | -| resolvable-not-interned | 0 | works in code but invisible to ns introspection (conformance finding) | -| missing-portable | 0 | portable semantics, jolt lacks it — implementation gap | -| special-form | 16 | specified in §3, not a library var | -| dynamic-var | 11 | classification needed: portable default vs host-dependent | -| agents-taps | 16 | out of scope pending concurrency design note | -| stm-refs | 11 | out of scope pending concurrency design note | -| jvm-specific | 46 | catalogued, not specified | - -Classifications are initial and mechanical — reclassifying is an ordinary -spec change. A var is *Verified* only when its §9 entry exists and carries no -UNVERIFIED field; that column will be added as entries land. - -## Per-var status - -| Var | Status | ClojureDocs examples | -|---|---|---| -| `*` | implemented+tested | ✓ | -| `*'` | implemented+tested | ✓ | -| `*1` | implemented+tested | ✓ | -| `*2` | implemented+tested | ✓ | -| `*3` | implemented+tested | ✓ | -| `*agent*` | dynamic-var | ✓ | -| `*allow-unresolved-vars*` | dynamic-var | ✓ | -| `*assert*` | implemented+tested | ✓ | -| `*clojure-version*` | implemented+tested | ✓ | -| `*command-line-args*` | implemented-untested | ✓ | -| `*compile-files*` | implemented+tested | ✓ | -| `*compile-path*` | dynamic-var | ✓ | -| `*compiler-options*` | dynamic-var | ✓ | -| `*data-readers*` | implemented+tested | ✓ | -| `*default-data-reader-fn*` | implemented+tested | ✓ | -| `*e` | implemented+tested | ✓ | -| `*err*` | implemented+tested | ✓ | -| `*file*` | implemented-untested | ✓ | -| `*flush-on-newline*` | implemented+tested | | -| `*fn-loader*` | dynamic-var | | -| `*in*` | implemented+tested | | -| `*math-context*` | implemented+tested | | -| `*ns*` | implemented+tested | ✓ | -| `*out*` | implemented+tested | ✓ | -| `*print-dup*` | implemented+tested | ✓ | -| `*print-length*` | implemented+tested | ✓ | -| `*print-level*` | implemented+tested | ✓ | -| `*print-meta*` | implemented+tested | ✓ | -| `*print-namespace-maps*` | implemented-untested | ✓ | -| `*print-readably*` | implemented+tested | ✓ | -| `*read-eval*` | implemented+tested | ✓ | -| `*reader-resolver*` | dynamic-var | | -| `*repl*` | dynamic-var | | -| `*source-path*` | dynamic-var | ✓ | -| `*suppress-read*` | dynamic-var | | -| `*unchecked-math*` | implemented+tested | ✓ | -| `*use-context-classloader*` | dynamic-var | ✓ | -| `*verbose-defrecords*` | dynamic-var | | -| `*warn-on-reflection*` | implemented+tested | ✓ | -| `+` | implemented+tested | ✓ | -| `+'` | implemented+tested | ✓ | -| `-` | implemented+tested | ✓ | -| `-'` | implemented+tested | ✓ | -| `->` | implemented+tested | ✓ | -| `->>` | implemented+tested | ✓ | -| `->ArrayChunk` | jvm-specific | | -| `->Eduction` | implemented+tested | | -| `->Vec` | jvm-specific | | -| `->VecNode` | jvm-specific | | -| `->VecSeq` | jvm-specific | | -| `-cache-protocol-fn` | jvm-specific | | -| `-reset-methods` | jvm-specific | | -| `.` | special-form | ✓ | -| `..` | implemented+tested | ✓ | -| `/` | implemented+tested | ✓ | -| `<` | implemented+tested | ✓ | -| `<=` | implemented+tested | ✓ | -| `=` | implemented+tested | ✓ | -| `==` | implemented+tested | ✓ | -| `>` | implemented+tested | ✓ | -| `>=` | implemented+tested | ✓ | -| `EMPTY-NODE` | jvm-specific | | -| `Inst` | jvm-specific | | -| `NaN?` | implemented+tested | ✓ | -| `PrintWriter-on` | jvm-specific | ✓ | -| `StackTraceElement->vec` | jvm-specific | ✓ | -| `Throwable->map` | jvm-specific | ✓ | -| `abs` | implemented+tested | ✓ | -| `accessor` | jvm-specific | ✓ | -| `aclone` | implemented+tested | ✓ | -| `add-classpath` | jvm-specific | ✓ | -| `add-tap` | agents-taps | ✓ | -| `add-watch` | implemented+tested | ✓ | -| `agent` | implemented+tested | ✓ | -| `agent-error` | implemented+tested | ✓ | -| `agent-errors` | agents-taps | | -| `aget` | implemented+tested | ✓ | -| `alength` | implemented+tested | ✓ | -| `alias` | implemented+tested | ✓ | -| `all-ns` | implemented+tested | ✓ | -| `alter` | stm-refs | ✓ | -| `alter-meta!` | implemented+tested | ✓ | -| `alter-var-root` | implemented+tested | ✓ | -| `amap` | jvm-specific | ✓ | -| `ancestors` | implemented+tested | ✓ | -| `and` | implemented+tested | ✓ | -| `any?` | implemented+tested | ✓ | -| `apply` | implemented+tested | ✓ | -| `areduce` | jvm-specific | ✓ | -| `array-map` | implemented+tested | ✓ | -| `as->` | implemented+tested | ✓ | -| `aset` | implemented+tested | ✓ | -| `aset-boolean` | implemented+tested | ✓ | -| `aset-byte` | implemented+tested | ✓ | -| `aset-char` | implemented+tested | ✓ | -| `aset-double` | implemented+tested | ✓ | -| `aset-float` | implemented+tested | ✓ | -| `aset-int` | implemented+tested | ✓ | -| `aset-long` | implemented+tested | ✓ | -| `aset-short` | implemented+tested | ✓ | -| `assert` | implemented+tested | ✓ | -| `assoc` | implemented+tested | ✓ | -| `assoc!` | implemented+tested | ✓ | -| `assoc-in` | implemented+tested | ✓ | -| `associative?` | implemented+tested | ✓ | -| `atom` | implemented+tested | ✓ | -| `await` | implemented+tested | ✓ | -| `await-for` | agents-taps | ✓ | -| `await1` | agents-taps | | -| `bases` | jvm-specific | ✓ | -| `bean` | implemented+tested | ✓ | -| `bigdec` | implemented+tested | ✓ | -| `bigint` | implemented+tested | ✓ | -| `biginteger` | implemented+tested | ✓ | -| `binding` | implemented+tested | ✓ | -| `bit-and` | implemented+tested | ✓ | -| `bit-and-not` | implemented+tested | ✓ | -| `bit-clear` | implemented+tested | ✓ | -| `bit-flip` | implemented+tested | ✓ | -| `bit-not` | implemented+tested | ✓ | -| `bit-or` | implemented+tested | ✓ | -| `bit-set` | implemented+tested | ✓ | -| `bit-shift-left` | implemented+tested | ✓ | -| `bit-shift-right` | implemented+tested | ✓ | -| `bit-test` | implemented+tested | ✓ | -| `bit-xor` | implemented+tested | ✓ | -| `boolean` | implemented+tested | ✓ | -| `boolean-array` | implemented+tested | ✓ | -| `boolean?` | implemented+tested | ✓ | -| `booleans` | implemented+tested | ✓ | -| `bound-fn` | implemented+tested | ✓ | -| `bound-fn*` | implemented+tested | ✓ | -| `bound?` | implemented+tested | ✓ | -| `bounded-count` | implemented+tested | ✓ | -| `butlast` | implemented+tested | ✓ | -| `byte` | implemented+tested | ✓ | -| `byte-array` | implemented+tested | ✓ | -| `bytes` | implemented+tested | ✓ | -| `bytes?` | implemented+tested | ✓ | -| `case` | implemented+tested | ✓ | -| `cast` | jvm-specific | ✓ | -| `cat` | implemented+tested | ✓ | -| `catch` | special-form | ✓ | -| `char` | implemented+tested | ✓ | -| `char-array` | implemented+tested | ✓ | -| `char-escape-string` | implemented+tested | ✓ | -| `char-name-string` | implemented+tested | ✓ | -| `char?` | implemented+tested | ✓ | -| `chars` | implemented+tested | ✓ | -| `chunk` | implemented+tested | ✓ | -| `chunk-append` | implemented+tested | ✓ | -| `chunk-buffer` | implemented+tested | ✓ | -| `chunk-cons` | implemented+tested | ✓ | -| `chunk-first` | implemented+tested | ✓ | -| `chunk-next` | implemented+tested | ✓ | -| `chunk-rest` | implemented+tested | ✓ | -| `chunked-seq?` | implemented+tested | ✓ | -| `class` | implemented+tested | ✓ | -| `class?` | implemented+tested | ✓ | -| `clear-agent-errors` | agents-taps | | -| `clojure-version` | implemented+tested | ✓ | -| `coll?` | implemented+tested | ✓ | -| `comment` | implemented+tested | ✓ | -| `commute` | stm-refs | ✓ | -| `comp` | implemented+tested | ✓ | -| `comparator` | implemented+tested | ✓ | -| `compare` | implemented+tested | ✓ | -| `compare-and-set!` | implemented+tested | ✓ | -| `compile` | jvm-specific | ✓ | -| `complement` | implemented+tested | ✓ | -| `completing` | implemented+tested | ✓ | -| `concat` | implemented+tested | ✓ | -| `cond` | implemented+tested | ✓ | -| `cond->` | implemented+tested | ✓ | -| `cond->>` | implemented+tested | ✓ | -| `condp` | implemented+tested | ✓ | -| `conj` | implemented+tested | ✓ | -| `conj!` | implemented+tested | ✓ | -| `cons` | implemented+tested | ✓ | -| `constantly` | implemented+tested | ✓ | -| `construct-proxy` | implemented+tested | ✓ | -| `contains?` | implemented+tested | ✓ | -| `count` | implemented+tested | ✓ | -| `counted?` | implemented+tested | ✓ | -| `create-ns` | implemented+tested | ✓ | -| `create-struct` | jvm-specific | ✓ | -| `cycle` | implemented+tested | ✓ | -| `dec` | implemented+tested | ✓ | -| `dec'` | implemented+tested | ✓ | -| `decimal?` | implemented+tested | ✓ | -| `declare` | implemented+tested | ✓ | -| `dedupe` | implemented+tested | ✓ | -| `def` | special-form | ✓ | -| `default-data-readers` | implemented+tested | ✓ | -| `definline` | jvm-specific | | -| `definterface` | implemented+tested | ✓ | -| `defmacro` | special-form | ✓ | -| `defmethod` | implemented+tested | ✓ | -| `defmulti` | implemented+tested | ✓ | -| `defn` | implemented+tested | ✓ | -| `defn-` | implemented+tested | ✓ | -| `defonce` | implemented+tested | ✓ | -| `defprotocol` | implemented+tested | ✓ | -| `defrecord` | implemented+tested | ✓ | -| `defstruct` | jvm-specific | ✓ | -| `deftype` | implemented+tested | ✓ | -| `delay` | implemented+tested | ✓ | -| `delay?` | implemented+tested | ✓ | -| `deliver` | implemented+tested | ✓ | -| `denominator` | implemented+tested | ✓ | -| `deref` | implemented+tested | ✓ | -| `derive` | implemented+tested | ✓ | -| `descendants` | implemented+tested | ✓ | -| `destructure` | implemented+tested | ✓ | -| `disj` | implemented+tested | ✓ | -| `disj!` | implemented+tested | ✓ | -| `dissoc` | implemented+tested | ✓ | -| `dissoc!` | implemented+tested | ✓ | -| `distinct` | implemented+tested | ✓ | -| `distinct?` | implemented+tested | ✓ | -| `do` | special-form | ✓ | -| `doall` | implemented+tested | ✓ | -| `dorun` | implemented+tested | ✓ | -| `doseq` | implemented+tested | ✓ | -| `dosync` | stm-refs | ✓ | -| `dotimes` | implemented+tested | ✓ | -| `doto` | implemented+tested | ✓ | -| `double` | implemented+tested | ✓ | -| `double-array` | implemented+tested | ✓ | -| `double?` | implemented+tested | ✓ | -| `doubles` | implemented+tested | ✓ | -| `drop` | implemented+tested | ✓ | -| `drop-last` | implemented+tested | ✓ | -| `drop-while` | implemented+tested | ✓ | -| `eduction` | implemented+tested | ✓ | -| `empty` | implemented+tested | ✓ | -| `empty?` | implemented+tested | ✓ | -| `ensure` | stm-refs | ✓ | -| `ensure-reduced` | implemented+tested | ✓ | -| `enumeration-seq` | implemented+tested | ✓ | -| `error-handler` | agents-taps | ✓ | -| `error-mode` | agents-taps | ✓ | -| `eval` | implemented+tested | ✓ | -| `even?` | implemented+tested | ✓ | -| `every-pred` | implemented+tested | ✓ | -| `every?` | implemented+tested | ✓ | -| `ex-cause` | implemented+tested | ✓ | -| `ex-data` | implemented+tested | ✓ | -| `ex-info` | implemented+tested | ✓ | -| `ex-message` | implemented+tested | ✓ | -| `extend` | implemented+tested | ✓ | -| `extend-protocol` | implemented+tested | ✓ | -| `extend-type` | implemented+tested | ✓ | -| `extenders` | implemented+tested | ✓ | -| `extends?` | implemented+tested | ✓ | -| `false?` | implemented+tested | ✓ | -| `ffirst` | implemented+tested | ✓ | -| `file-seq` | implemented+tested | ✓ | -| `filter` | implemented+tested | ✓ | -| `filterv` | implemented+tested | ✓ | -| `finally` | special-form | ✓ | -| `find` | implemented+tested | ✓ | -| `find-keyword` | implemented+tested | ✓ | -| `find-ns` | implemented+tested | ✓ | -| `find-protocol-impl` | jvm-specific | | -| `find-protocol-method` | jvm-specific | | -| `find-var` | implemented+tested | ✓ | -| `first` | implemented+tested | ✓ | -| `flatten` | implemented+tested | ✓ | -| `float` | implemented+tested | ✓ | -| `float-array` | implemented+tested | ✓ | -| `float?` | implemented+tested | ✓ | -| `floats` | implemented+tested | ✓ | -| `flush` | implemented+tested | ✓ | -| `fn` | implemented+tested | ✓ | -| `fn?` | implemented+tested | ✓ | -| `fnext` | implemented+tested | ✓ | -| `fnil` | implemented+tested | ✓ | -| `for` | implemented+tested | ✓ | -| `force` | implemented+tested | ✓ | -| `format` | implemented+tested | ✓ | -| `frequencies` | implemented+tested | ✓ | -| `future` | implemented+tested | ✓ | -| `future-call` | implemented+tested | ✓ | -| `future-cancel` | implemented+tested | ✓ | -| `future-cancelled?` | implemented+tested | ✓ | -| `future-done?` | implemented+tested | ✓ | -| `future?` | implemented+tested | ✓ | -| `gen-class` | jvm-specific | ✓ | -| `gen-interface` | jvm-specific | ✓ | -| `gensym` | implemented+tested | ✓ | -| `get` | implemented+tested | ✓ | -| `get-in` | implemented+tested | ✓ | -| `get-method` | implemented+tested | ✓ | -| `get-proxy-class` | implemented+tested | ✓ | -| `get-thread-bindings` | implemented+tested | ✓ | -| `get-validator` | implemented+tested | ✓ | -| `group-by` | implemented+tested | ✓ | -| `halt-when` | implemented+tested | ✓ | -| `hash` | implemented+tested | ✓ | -| `hash-combine` | implemented+tested | ✓ | -| `hash-map` | implemented+tested | ✓ | -| `hash-ordered-coll` | implemented+tested | ✓ | -| `hash-set` | implemented+tested | ✓ | -| `hash-unordered-coll` | implemented+tested | ✓ | -| `ident?` | implemented+tested | ✓ | -| `identical?` | implemented+tested | ✓ | -| `identity` | implemented+tested | ✓ | -| `if` | special-form | ✓ | -| `if-let` | implemented+tested | ✓ | -| `if-not` | implemented+tested | ✓ | -| `if-some` | implemented+tested | ✓ | -| `ifn?` | implemented+tested | ✓ | -| `import` | implemented+tested | ✓ | -| `in-ns` | implemented+tested | ✓ | -| `inc` | implemented+tested | ✓ | -| `inc'` | implemented+tested | ✓ | -| `indexed?` | implemented+tested | ✓ | -| `infinite?` | implemented+tested | ✓ | -| `init-proxy` | implemented+tested | ✓ | -| `inst-ms` | implemented+tested | ✓ | -| `inst-ms*` | implemented+tested | | -| `inst?` | implemented+tested | ✓ | -| `instance?` | implemented+tested | ✓ | -| `int` | implemented+tested | ✓ | -| `int-array` | implemented+tested | ✓ | -| `int?` | implemented+tested | ✓ | -| `integer?` | implemented+tested | ✓ | -| `interleave` | implemented+tested | ✓ | -| `intern` | implemented+tested | ✓ | -| `interpose` | implemented+tested | ✓ | -| `into` | implemented+tested | ✓ | -| `into-array` | implemented+tested | ✓ | -| `ints` | implemented+tested | ✓ | -| `io!` | stm-refs | ✓ | -| `isa?` | implemented+tested | ✓ | -| `iterate` | implemented+tested | ✓ | -| `iteration` | jvm-specific | ✓ | -| `iterator-seq` | implemented+tested | ✓ | -| `juxt` | implemented+tested | ✓ | -| `keep` | implemented+tested | ✓ | -| `keep-indexed` | implemented+tested | ✓ | -| `key` | implemented+tested | ✓ | -| `keys` | implemented+tested | ✓ | -| `keyword` | implemented+tested | ✓ | -| `keyword?` | implemented+tested | ✓ | -| `last` | implemented+tested | ✓ | -| `lazy-cat` | implemented+tested | ✓ | -| `lazy-seq` | implemented+tested | ✓ | -| `let` | implemented+tested | ✓ | -| `letfn` | implemented+tested | ✓ | -| `line-seq` | implemented+tested | ✓ | -| `list` | implemented+tested | ✓ | -| `list*` | implemented+tested | ✓ | -| `list?` | implemented+tested | ✓ | -| `load` | implemented+tested | ✓ | -| `load-file` | implemented-untested | ✓ | -| `load-reader` | jvm-specific | ✓ | -| `load-string` | implemented+tested | ✓ | -| `loaded-libs` | jvm-specific | ✓ | -| `locking` | implemented+tested | ✓ | -| `long` | implemented+tested | ✓ | -| `long-array` | implemented+tested | ✓ | -| `longs` | implemented+tested | ✓ | -| `loop` | implemented+tested | ✓ | -| `macroexpand` | implemented+tested | ✓ | -| `macroexpand-1` | implemented+tested | ✓ | -| `make-array` | implemented+tested | ✓ | -| `make-hierarchy` | implemented+tested | ✓ | -| `map` | implemented+tested | ✓ | -| `map-entry?` | implemented+tested | ✓ | -| `map-indexed` | implemented+tested | ✓ | -| `map?` | implemented+tested | ✓ | -| `mapcat` | implemented+tested | ✓ | -| `mapv` | implemented+tested | ✓ | -| `max` | implemented+tested | ✓ | -| `max-key` | implemented+tested | ✓ | -| `memfn` | implemented+tested | ✓ | -| `memoize` | implemented+tested | ✓ | -| `merge` | implemented+tested | ✓ | -| `merge-with` | implemented+tested | ✓ | -| `meta` | implemented+tested | ✓ | -| `method-sig` | jvm-specific | ✓ | -| `methods` | implemented+tested | ✓ | -| `min` | implemented+tested | ✓ | -| `min-key` | implemented+tested | ✓ | -| `mix-collection-hash` | jvm-specific | | -| `mod` | implemented+tested | ✓ | -| `monitor-enter` | special-form | | -| `monitor-exit` | special-form | | -| `munge` | implemented+tested | ✓ | -| `name` | implemented+tested | ✓ | -| `namespace` | implemented+tested | ✓ | -| `namespace-munge` | implemented+tested | ✓ | -| `nat-int?` | implemented+tested | ✓ | -| `neg-int?` | implemented+tested | ✓ | -| `neg?` | implemented+tested | ✓ | -| `new` | special-form | ✓ | -| `newline` | implemented+tested | ✓ | -| `next` | implemented+tested | ✓ | -| `nfirst` | implemented+tested | ✓ | -| `nil?` | implemented+tested | ✓ | -| `nnext` | implemented+tested | ✓ | -| `not` | implemented+tested | ✓ | -| `not-any?` | implemented+tested | ✓ | -| `not-empty` | implemented+tested | ✓ | -| `not-every?` | implemented+tested | ✓ | -| `not=` | implemented+tested | ✓ | -| `ns` | implemented+tested | ✓ | -| `ns-aliases` | implemented+tested | ✓ | -| `ns-imports` | implemented+tested | ✓ | -| `ns-interns` | implemented+tested | ✓ | -| `ns-map` | implemented+tested | ✓ | -| `ns-name` | implemented+tested | ✓ | -| `ns-publics` | implemented+tested | ✓ | -| `ns-refers` | implemented+tested | ✓ | -| `ns-resolve` | implemented+tested | ✓ | -| `ns-unalias` | implemented+tested | ✓ | -| `ns-unmap` | implemented+tested | ✓ | -| `nth` | implemented+tested | ✓ | -| `nthnext` | implemented+tested | ✓ | -| `nthrest` | implemented+tested | ✓ | -| `num` | implemented+tested | ✓ | -| `number?` | implemented+tested | ✓ | -| `numerator` | implemented+tested | ✓ | -| `object-array` | implemented+tested | ✓ | -| `odd?` | implemented+tested | ✓ | -| `or` | implemented+tested | ✓ | -| `parents` | implemented+tested | ✓ | -| `parse-boolean` | implemented+tested | ✓ | -| `parse-double` | implemented+tested | ✓ | -| `parse-long` | implemented+tested | ✓ | -| `parse-uuid` | implemented+tested | ✓ | -| `partial` | implemented+tested | ✓ | -| `partition` | implemented+tested | ✓ | -| `partition-all` | implemented+tested | ✓ | -| `partition-by` | implemented+tested | ✓ | -| `partitionv` | implemented+tested | | -| `partitionv-all` | implemented+tested | | -| `pcalls` | implemented+tested | ✓ | -| `peek` | implemented+tested | ✓ | -| `persistent!` | implemented+tested | ✓ | -| `pmap` | implemented+tested | ✓ | -| `pop` | implemented+tested | ✓ | -| `pop!` | implemented+tested | ✓ | -| `pop-thread-bindings` | implemented+tested | | -| `pos-int?` | implemented+tested | ✓ | -| `pos?` | implemented+tested | ✓ | -| `pr` | implemented+tested | ✓ | -| `pr-str` | implemented+tested | ✓ | -| `prefer-method` | implemented+tested | ✓ | -| `prefers` | implemented+tested | ✓ | -| `primitives-classnames` | jvm-specific | ✓ | -| `print` | implemented+tested | ✓ | -| `print-ctor` | jvm-specific | ✓ | -| `print-dup` | implemented+tested | ✓ | -| `print-method` | implemented+tested | ✓ | -| `print-simple` | jvm-specific | ✓ | -| `print-str` | implemented+tested | ✓ | -| `printf` | implemented+tested | ✓ | -| `println` | implemented+tested | ✓ | -| `println-str` | implemented+tested | ✓ | -| `prn` | implemented+tested | ✓ | -| `prn-str` | implemented+tested | ✓ | -| `promise` | implemented+tested | ✓ | -| `proxy` | implemented+tested | ✓ | -| `proxy-call-with-super` | implemented+tested | | -| `proxy-mappings` | implemented+tested | ✓ | -| `proxy-name` | jvm-specific | | -| `proxy-super` | implemented+tested | ✓ | -| `push-thread-bindings` | implemented+tested | | -| `pvalues` | implemented+tested | ✓ | -| `qualified-ident?` | implemented+tested | ✓ | -| `qualified-keyword?` | implemented+tested | ✓ | -| `qualified-symbol?` | implemented+tested | ✓ | -| `quot` | implemented+tested | ✓ | -| `quote` | special-form | ✓ | -| `rand` | implemented+tested | ✓ | -| `rand-int` | implemented+tested | ✓ | -| `rand-nth` | implemented+tested | ✓ | -| `random-sample` | implemented+tested | ✓ | -| `random-uuid` | implemented+tested | ✓ | -| `range` | implemented+tested | ✓ | -| `ratio?` | implemented+tested | ✓ | -| `rational?` | implemented+tested | ✓ | -| `rationalize` | implemented+tested | ✓ | -| `re-find` | implemented+tested | ✓ | -| `re-groups` | implemented+tested | ✓ | -| `re-matcher` | implemented+tested | ✓ | -| `re-matches` | implemented+tested | ✓ | -| `re-pattern` | implemented+tested | ✓ | -| `re-seq` | implemented+tested | ✓ | -| `read` | implemented+tested | ✓ | -| `read+string` | implemented+tested | ✓ | -| `read-line` | implemented+tested | ✓ | -| `read-string` | implemented+tested | ✓ | -| `reader-conditional` | implemented+tested | ✓ | -| `reader-conditional?` | implemented+tested | ✓ | -| `realized?` | implemented+tested | ✓ | -| `record?` | implemented+tested | ✓ | -| `recur` | special-form | ✓ | -| `reduce` | implemented+tested | ✓ | -| `reduce-kv` | implemented+tested | ✓ | -| `reduced` | implemented+tested | ✓ | -| `reduced?` | implemented+tested | ✓ | -| `reductions` | implemented+tested | ✓ | -| `ref` | stm-refs | ✓ | -| `ref-history-count` | stm-refs | ✓ | -| `ref-max-history` | stm-refs | | -| `ref-min-history` | stm-refs | ✓ | -| `ref-set` | stm-refs | ✓ | -| `refer` | implemented+tested | ✓ | -| `refer-clojure` | implemented+tested | ✓ | -| `reify` | implemented+tested | ✓ | -| `release-pending-sends` | agents-taps | ✓ | -| `rem` | implemented+tested | ✓ | -| `remove` | implemented+tested | ✓ | -| `remove-all-methods` | implemented+tested | ✓ | -| `remove-method` | implemented+tested | ✓ | -| `remove-ns` | implemented+tested | ✓ | -| `remove-tap` | agents-taps | | -| `remove-watch` | implemented+tested | ✓ | -| `repeat` | implemented+tested | ✓ | -| `repeatedly` | implemented+tested | ✓ | -| `replace` | implemented+tested | ✓ | -| `replicate` | implemented+tested | ✓ | -| `require` | implemented+tested | ✓ | -| `requiring-resolve` | jvm-specific | ✓ | -| `reset!` | implemented+tested | ✓ | -| `reset-meta!` | implemented+tested | ✓ | -| `reset-vals!` | implemented+tested | ✓ | -| `resolve` | implemented+tested | ✓ | -| `rest` | implemented+tested | ✓ | -| `restart-agent` | implemented+tested | ✓ | -| `resultset-seq` | jvm-specific | ✓ | -| `reverse` | implemented+tested | ✓ | -| `reversible?` | implemented+tested | ✓ | -| `rseq` | implemented+tested | ✓ | -| `rsubseq` | implemented+tested | ✓ | -| `run!` | implemented+tested | ✓ | -| `satisfies?` | implemented+tested | ✓ | -| `second` | implemented+tested | ✓ | -| `select-keys` | implemented+tested | ✓ | -| `send` | implemented+tested | ✓ | -| `send-off` | implemented+tested | ✓ | -| `send-via` | agents-taps | ✓ | -| `seq` | implemented+tested | ✓ | -| `seq-to-map-for-destructuring` | implemented+tested | ✓ | -| `seq?` | implemented+tested | ✓ | -| `seqable?` | implemented+tested | ✓ | -| `seque` | implemented+tested | ✓ | -| `sequence` | implemented+tested | ✓ | -| `sequential?` | implemented+tested | ✓ | -| `set` | implemented+tested | ✓ | -| `set!` | special-form | ✓ | -| `set-agent-send-executor!` | agents-taps | ✓ | -| `set-agent-send-off-executor!` | agents-taps | ✓ | -| `set-error-handler!` | agents-taps | ✓ | -| `set-error-mode!` | agents-taps | ✓ | -| `set-validator!` | implemented+tested | ✓ | -| `set?` | implemented+tested | ✓ | -| `short` | implemented+tested | ✓ | -| `short-array` | implemented+tested | ✓ | -| `shorts` | implemented+tested | ✓ | -| `shuffle` | implemented+tested | ✓ | -| `shutdown-agents` | agents-taps | ✓ | -| `simple-ident?` | implemented+tested | ✓ | -| `simple-keyword?` | implemented+tested | ✓ | -| `simple-symbol?` | implemented+tested | ✓ | -| `slurp` | implemented+tested | ✓ | -| `some` | implemented+tested | ✓ | -| `some->` | implemented+tested | ✓ | -| `some->>` | implemented+tested | ✓ | -| `some-fn` | implemented+tested | ✓ | -| `some?` | implemented+tested | ✓ | -| `sort` | implemented+tested | ✓ | -| `sort-by` | implemented+tested | ✓ | -| `sorted-map` | implemented+tested | ✓ | -| `sorted-map-by` | implemented+tested | ✓ | -| `sorted-set` | implemented+tested | ✓ | -| `sorted-set-by` | implemented+tested | ✓ | -| `sorted?` | implemented+tested | ✓ | -| `special-symbol?` | implemented+tested | ✓ | -| `spit` | implemented+tested | ✓ | -| `split-at` | implemented+tested | ✓ | -| `split-with` | implemented+tested | ✓ | -| `splitv-at` | implemented+tested | | -| `str` | implemented+tested | ✓ | -| `stream-into!` | jvm-specific | | -| `stream-reduce!` | jvm-specific | | -| `stream-seq!` | jvm-specific | | -| `stream-transduce!` | jvm-specific | | -| `string?` | implemented+tested | ✓ | -| `struct` | jvm-specific | ✓ | -| `struct-map` | jvm-specific | ✓ | -| `subs` | implemented+tested | ✓ | -| `subseq` | implemented+tested | ✓ | -| `subvec` | implemented+tested | ✓ | -| `supers` | implemented+tested | ✓ | -| `swap!` | implemented+tested | ✓ | -| `swap-vals!` | implemented+tested | ✓ | -| `symbol` | implemented+tested | ✓ | -| `symbol?` | implemented+tested | ✓ | -| `sync` | stm-refs | | -| `tagged-literal` | implemented+tested | ✓ | -| `tagged-literal?` | implemented+tested | | -| `take` | implemented+tested | ✓ | -| `take-last` | implemented+tested | ✓ | -| `take-nth` | implemented+tested | ✓ | -| `take-while` | implemented+tested | ✓ | -| `tap>` | agents-taps | ✓ | -| `test` | implemented+tested | ✓ | -| `the-ns` | implemented+tested | ✓ | -| `thread-bound?` | implemented+tested | ✓ | -| `throw` | special-form | ✓ | -| `time` | implemented+tested | ✓ | -| `to-array` | implemented+tested | ✓ | -| `to-array-2d` | implemented+tested | ✓ | -| `trampoline` | implemented+tested | ✓ | -| `transduce` | implemented+tested | ✓ | -| `transient` | implemented+tested | ✓ | -| `tree-seq` | implemented+tested | ✓ | -| `true?` | implemented+tested | ✓ | -| `try` | special-form | ✓ | -| `type` | implemented+tested | ✓ | -| `unchecked-add` | implemented+tested | ✓ | -| `unchecked-add-int` | implemented+tested | ✓ | -| `unchecked-byte` | implemented+tested | ✓ | -| `unchecked-char` | implemented+tested | | -| `unchecked-dec` | implemented+tested | ✓ | -| `unchecked-dec-int` | implemented+tested | ✓ | -| `unchecked-divide-int` | implemented+tested | ✓ | -| `unchecked-double` | implemented+tested | ✓ | -| `unchecked-float` | implemented+tested | ✓ | -| `unchecked-inc` | implemented+tested | ✓ | -| `unchecked-inc-int` | implemented+tested | ✓ | -| `unchecked-int` | implemented+tested | ✓ | -| `unchecked-long` | implemented+tested | ✓ | -| `unchecked-multiply` | implemented+tested | ✓ | -| `unchecked-multiply-int` | implemented+tested | | -| `unchecked-negate` | implemented+tested | ✓ | -| `unchecked-negate-int` | implemented+tested | ✓ | -| `unchecked-remainder-int` | implemented+tested | | -| `unchecked-short` | implemented+tested | ✓ | -| `unchecked-subtract` | implemented+tested | ✓ | -| `unchecked-subtract-int` | implemented+tested | ✓ | -| `underive` | implemented+tested | ✓ | -| `unquote` | jvm-specific | ✓ | -| `unquote-splicing` | jvm-specific | ✓ | -| `unreduced` | implemented+tested | ✓ | -| `unsigned-bit-shift-right` | implemented+tested | ✓ | -| `update` | implemented+tested | ✓ | -| `update-in` | implemented+tested | ✓ | -| `update-keys` | implemented+tested | ✓ | -| `update-proxy` | implemented+tested | ✓ | -| `update-vals` | implemented+tested | ✓ | -| `uri?` | implemented+tested | ✓ | -| `use` | implemented+tested | ✓ | -| `uuid?` | implemented+tested | ✓ | -| `val` | implemented+tested | ✓ | -| `vals` | implemented+tested | ✓ | -| `var` | special-form | ✓ | -| `var-get` | implemented+tested | ✓ | -| `var-set` | implemented+tested | ✓ | -| `var?` | implemented+tested | ✓ | -| `vary-meta` | implemented+tested | ✓ | -| `vec` | implemented+tested | ✓ | -| `vector` | implemented+tested | ✓ | -| `vector-of` | jvm-specific | ✓ | -| `vector?` | implemented+tested | ✓ | -| `volatile!` | implemented+tested | ✓ | -| `volatile?` | implemented+tested | ✓ | -| `vreset!` | implemented+tested | ✓ | -| `vswap!` | implemented+tested | ✓ | -| `when` | implemented+tested | ✓ | -| `when-first` | implemented+tested | ✓ | -| `when-let` | implemented+tested | ✓ | -| `when-not` | implemented+tested | ✓ | -| `when-some` | implemented+tested | ✓ | -| `while` | implemented+tested | ✓ | -| `with-bindings` | implemented+tested | ✓ | -| `with-bindings*` | implemented+tested | ✓ | -| `with-in-str` | implemented+tested | ✓ | -| `with-loading-context` | jvm-specific | | -| `with-local-vars` | implemented+tested | ✓ | -| `with-meta` | implemented+tested | ✓ | -| `with-open` | implemented+tested | ✓ | -| `with-out-str` | implemented+tested | ✓ | -| `with-precision` | implemented+tested | ✓ | -| `with-redefs` | implemented+tested | ✓ | -| `with-redefs-fn` | implemented+tested | ✓ | -| `xml-seq` | implemented+tested | ✓ | -| `zero?` | implemented+tested | ✓ | -| `zipmap` | implemented+tested | ✓ | diff --git a/docs/tools-deps.md b/docs/tools-deps.md deleted file mode 100644 index cba1912..0000000 --- a/docs/tools-deps.md +++ /dev/null @@ -1,216 +0,0 @@ -# deps.edn support — design notes - -How Jolt loads pure-Clojure libraries from a `deps.edn`, and why it's built the -way it is. For how to *use* it, see [building-and-deps.md](building-and-deps.md). - -Scope, decided up front: - -- **git + local deps only** — no Maven/`~/.m2` resolution. -- **pure `clj`/`cljc`** — anything needing the JVM won't load or run; expected. -- **no classpath abstraction** — `require` just needs to find a dep's namespaces; - "the classpath" is an ordered list of source directories. -- **own resolver, own reader** — `deps.edn` is read by jolt's own reader, and git - fetch/cache is a thin shell-out to `git`; no external package manager. -- **deps-agnostic runtime core** — resolution is a CLI front-end concern, not a - runtime one. The runtime knows nothing about `deps.edn`; it only consumes a - list of source roots. The CLI resolves a `deps.edn` into those roots before - running. - -## How resolution works - -`jolt.deps` (`jolt-core/jolt/deps.clj`) reads `deps.edn` (jolt's own reader -parses the EDN), then walks `:deps`: - -- `:git/url` + `:git/sha` (+ optional `:deps/root`) → clone the sha into the git - cache and contribute the checkout (or its `:deps/root` subdir); -- `:local/root` → the path as-is; -- `:mvn/*` → skipped with a warning; -- anything else → ignored. - -git resolution shells out to `git` through `jolt.host/sh` — `git init` + remote -add + fetch + reset at the requested sha. Clones land in a global, sha-immutable -cache (`$JOLT_GITLIBS`, else `~/.jolt/gitlibs`) shared across projects, the -`tools.gitlibs` `~/.gitlibs` model. - -Each resolved dependency contributes its own `:paths` (default `["src"]`) as -source roots; the walk is **breadth-first** so every top-level coordinate -registers before any transitive one — a top-level pin always wins, matching -tools.deps. The result is a de-duplicated, ordered list of directories. - -Two tools.deps features are mirrored in reduced form. **Aliases**: `:aliases` -entries supply `:extra-paths`/`:extra-deps` (accumulate across the aliases -selected with `-A:a:b`) and `:main-opts` (last-wins, run with `-M:alias`). -**Tasks**: the honest subset of babashka's — a string task is a shell command, a -map task is `{:main-opts […]}`; bare Clojure expressions aren't a separate task -form. - -## How the CLI ties it together - -`jolt.main` (`jolt-core/jolt/main.clj`) is the CLI dispatch. Driven by `cli.ss`, -it resolves the project (`jolt.deps/resolve-project`), prepends the resolved -roots, and de-sugars the argv into a run: - -- `run -m NS args` → load `NS`, call its `-main`; -- `run FILE` → load the file; -- `-M:alias` → run the alias's `:main-opts`; -- `-A:alias` → add the alias's paths/deps, then run the rest; -- `repl` → a line REPL; -- `path` → print the resolved roots; -- `build -m NS [-o OUT] [--opt|--dev]` → AOT-compile the app into a standalone binary; -- `` → run a `deps.edn` `:tasks` entry. - -The resolver lives in the overlay alongside the runtime, but the runtime's only -dependency interface is the list of source roots it's handed. - -## Native libraries - -A library that binds C declares the shared objects it needs under `:jolt/native`, -so `jolt.main` loads them before the namespace is required and its `foreign-fn` -bindings resolve. Each entry is a map — `{:name "sqlite3" :darwin -["libsqlite3.0.dylib" …] :linux ["libsqlite3.so.0" …]}` — with optional -`:optional true` (absence is fine, a feature-gated dep) and `:process true` (use -the running process's own symbols, e.g. libc sockets, no external file). A -project inherits its dependencies' `:jolt/native`. - -### Static vs dynamic linking - -When you `joltc build`, a native lib is **statically linked** into the binary by -default if the spec carries a `:static` archive — so the executable calls the C -code with no shared object present at runtime. Add `:static` alongside the runtime -candidates: - -```clojure -{:name "sqlite3" - :static {:archive "/opt/homebrew/lib/libsqlite3.a"} ; or {:lib "sqlite3" :libdir "/usr/lib"} - :darwin ["libsqlite3.0.dylib"] ; still used by `run`/`repl` and by --dynamic - :linux ["libsqlite3.so.0"]} -``` - -`:static {:archive PATH}` force-loads the whole `.a` and is the reliable -cross-platform form. `:static {:lib NAME :libdir DIR}` links `-lNAME` (with a -`-Bstatic` preference on Linux); on macOS, which has no `-Bstatic`, prefer the -archive form. A spec with no `:static` (or a build passed `--dynamic`, or -`:jolt/build {:dynamic-natives true}`) keeps the old behavior — the shared object -is loaded at startup via `load-shared-object`. - -Static linking needs a C compiler (`cc`) on `PATH` at build time (plus the C libs -the Chez kernel links — lz4, zlib, ncurses). The distributed `joltc` bundles the -Chez kernel, so it re-links the launcher stub with the archive baked in — no -external Chez, just `cc`. Without a `cc`, a `:static` lib fails with a message -pointing you to install one or pass `--dynamic`. Keep a `:darwin`/`:linux` -candidate on any `:static` spec so `run`/`repl` (which have no static binary) can -still load it. - -## Standalone binaries - -`joltc build -m NS` compiles the app and every library into one executable (the -runtime + compiler are baked in). Resolved `:jolt/native` libs are statically -linked in (or loaded at startup — see [Native libraries](#native-libraries)), so -an FFI app — sockets, SQLite — runs with no jolt or Chez on the path. - -Output goes under the project's `target/`, cargo-style: `target/release/` -by default and with `--opt`, `target/debug/` with `--dev` (the -`.build` scratch dir sits beside it). `-o PATH` overrides — absolute as-is, -relative against the project dir. Paths resolve against the project (`JOLT_PWD`), -not the CLI's cwd, since `bin/joltc` runs from the jolt repo. - -`:jolt/build {:embed ["resources" …]}` bakes those directories' files into the -binary; `io/resource` serves them from the image with no files on disk. Resources -not embedded resolve at runtime against `JOLT_PWD` (or the cwd), so the -ship-the-binary-with-its-`resources/`-dir model also works. Files read through -`io/file` (e.g. a `config.edn` a config library loads) stay external by design — -edit them without rebuilding. - -A standalone build needs Chez's kernel dev files (`libkernel.a`, `scheme.h`) and -a C compiler; `JOLT_CHEZ_CSV` overrides the auto-detected `csv/` -dir. `--opt` turns on the inference/flatten/scalar-replace passes; the default -`release` mode is const-fold only. - -`--direct-link` (or `:jolt/build {:direct-link true}`) opts into a closed world: a -call between the app's own functions binds to its target directly, skipping the var -lookup and generic dispatch a runtime call pays — at the cost of runtime -redefinition of those vars and `eval`/`load-string`. It's off by default, so -ordinary builds (including `release` and `--opt`) stay dynamically linked. A var -marked `^:redef` or `^:dynamic` stays indirect even under `--direct-link`, and calls -into `clojure.core` stay indirect in every mode. - -## Tree-shaking - -`--tree-shake` (or `:jolt/build {:tree-shake true}`) ships only the code reachable -from `-main`. The build constructs one call graph spanning the app, every resolved -library, and the `clojure.core`/stdlib prelude, then keeps `-main`, every -side-effecting top-level form (so a `defmethod`/`defrecord`/protocol registration -keeps its targets live), and everything reachable from those — dropping the rest. A -reference counts whether it's a call or a value (`#'x`, a fn passed to `map`, a fn -stored in a map): any reference keeps its target live, so nothing reachable is ever -dropped. An app that never compiles at runtime (no reachable `eval`/`load-string`) -also drops the analyzer and back end from the binary. Typical savings are 1–2 MB; -behaviour is unchanged. - -**It bails — keeps everything — when reachable code resolves a var by name at -runtime** (`eval`, `resolve`, `ns-resolve`, `requiring-resolve`, `find-var`, -`intern`, `load-string`, `load-file`). A static call graph can't follow a runtime -`resolve`, so dropping anything would be unsound. The build prints which definitions -forced the bail: - -``` -jolt build: tree-shake skipped (reachable code resolves vars at runtime): - selmer.filters/generate-json -> clojure.core/resolve - clojure.tools.logging/call-str -> clojure.core/ns-resolve -``` - -These are almost always libraries, not your code — `resolve` is how mature Clojure -libraries implement plugin systems and optional integrations (a logging backend -chosen at runtime, a template filter that lazily loads an optional dependency). On -the JVM that costs nothing; in a closed-world binary it defeats reachability. To make -an app tree-shakeable, keep runtime resolution off the *reachable* path: a backend -that's fixed on jolt can be referenced directly rather than resolved (the jolt -`tools.logging` port dropped the JVM's dynamic factory selection for exactly this), -and an optional integration you don't use can be dropped or hard-wired. Unreached -`resolve`-using code is shaken away like anything else — only resolution on the live -path triggers the bail. - -The closed-world soundness model follows Stalin's dead-code analysis: in a program -with no `eval`, a definition is live iff it is referenced (called or as a value) from -a root, transitively. - -## Limitations - -- Pure `clj`/`cljc` only — JVM interop, host classes, and unimplemented - `clojure.core` corners fail. Coverage is per-function: a namespace can load with - most functions working and a few not. -- Source only; compiled `.class` files in a git dep are ignored. -- git `:git/sha` must be a full SHA (`git fetch` can't resolve a short one). - -## Stack traces - -An uncaught error prints the message, the top-level source location, and — when -frames are available — a `trace:` backtrace. In an AOT `jolt build --direct-link` -binary the frames map to `ns/name (file:line)`; on the runtime eval path they are -the surviving fn names. Tail-call optimization erases tail-called frames, so the -default trace shows only the non-tail spine. - -A fuller **tail-frame history** recovers the frames TCO erases: each compiled fn -records itself on entry into a bounded ring-of-rings buffer, so the trace shows -TCO-elided frames (including the immediate error site) while a tight tail loop -stays bounded and its non-tail caller context is preserved. - -It is **on by default in REPL-driven development** — a `repl` or nREPL session -turns it on, so an error in code you evaluate or reload shows a tail-frame trace -with no setup. Because the recording is baked in at compile time, only code -compiled while a session is live is traced; reload a namespace to trace code that -was already loaded (e.g. an app's initial `-M:run` load before its nREPL started). - -Elsewhere it is off (a small per-call cost, and never emitted into a `jolt build` -binary). Override with the environment: `JOLT_TRACE=1` forces it on for a whole -run — including a plain `-M:run`, so the app's own load is traced — and -`JOLT_TRACE=0` forces it off, even in a REPL/nREPL session. - -## Conformance - -The known-working libraries (see [libraries.md](libraries.md)) and the -[examples](https://github.com/jolt-lang/examples) exercise real pure-`cljc` git -libraries end to end — resolving them from git, loading their namespaces, and -running sample calls. A library fails when it relies on something Jolt doesn't -provide — JVM interop, or a regex feature like Unicode property classes -(`\p{…}`). diff --git a/host/chez/atoms.ss b/host/chez/atoms.ss deleted file mode 100644 index 5fcd27c..0000000 --- a/host/chez/atoms.ss +++ /dev/null @@ -1,221 +0,0 @@ -;; atoms — host-coupled mutable reference cells for the Chez host. -;; -;; atom/deref/swap!/reset! are host primitives (not the clojure.core overlay), -;; so the runtime provides native shims, def-var!'d into clojure.core. They -;; lower to var-deref in prelude mode. The hierarchy machinery -;; (global-hierarchy = (atom (make-hierarchy))) calls `atom` at the prelude's -;; LOAD time, so without this shim the whole prelude fails to load. -;; -;; compare-and-set!/swap-vals!/reset-vals! are overlay fns over the native kernel -;; in the live system; provided here natively too so the host is self-sufficient -;; for atoms without the full prelude (the overlay versions, when the full prelude -;; loads, override these but compose the same native kernel). - -;; watches is an alist of (key . watch-fn); validator is a jolt fn or jolt-nil. -;; The peripheral ops + the notify/validate behaviour live natively here, and -;; post-prelude.ss re-asserts them over the overlay's def-var!. -;; `lock` is a per-atom mutex guarding the read-modify-write critical sections, -;; so swap!/reset!/compare-and-set! are atomic under real OS threads -;; (futures/go blocks share the heap). The user fn in swap! runs OUTSIDE the lock -;; (a CAS retry loop, like the JVM) so it never deadlocks on re-entrant access and -;; a watch/validator can deref the same atom. -(define-record-type jolt-atom - (fields (mutable val) (mutable watches) (mutable validator) lock) - (nongenerative jolt-atom-v3)) - -;; a rejected reference value is IllegalStateException, like ARef.validate. -(define (jolt-iref-state-throw) - (jolt-throw (jolt-host-throwable "java.lang.IllegalStateException" "Invalid reference state"))) - -;; (atom init :meta m :validator f) — the ARef ctor contract: the validator runs -;; against the initial value (an invalid init never constructs), :meta must be a -;; map (anything else is the JVM's IPersistentMap cast failure). -(define (jolt-atom-new v . opts) - (let loop ((o opts) (validator jolt-nil) (m #f)) - (cond - ((or (null? o) (null? (cdr o))) - (let ((a (make-jolt-atom v '() validator (make-mutex)))) - (jolt-atom-validate a v) - (when (and m (not (jolt-nil? m))) - (unless (jolt-map? m) - (jolt-throw (jolt-host-throwable - "java.lang.ClassCastException" - (string-append "class " (jolt-class-name m) - " cannot be cast to class clojure.lang.IPersistentMap")))) - (hashtable-set! meta-table a m)) - a)) - ((and (keyword-t? (car o)) (string=? (keyword-t-name (car o)) "validator")) - (loop (cddr o) (cadr o) m)) - ((and (keyword-t? (car o)) (string=? (keyword-t-name (car o)) "meta")) - (loop (cddr o) validator (cadr o))) - (else (loop (cddr o) validator m))))) - -;; validate a candidate value: a non-nil validator that returns falsey rejects. -(define (jolt-atom-validate a v) - (let ((vf (jolt-atom-validator a))) - (when (and (not (jolt-nil? vf)) (jolt-not (jolt-invoke vf v))) - (jolt-iref-state-throw)))) - -;; notify each watch (k ref old new), in insertion order (alist is reverse-built, -;; so walk it reversed to match add order). -(define (jolt-atom-notify a old new) - (for-each (lambda (kv) (jolt-invoke (cdr kv) (car kv) a old new)) - (reverse (jolt-atom-watches a)))) - -;; deref reads an atom; it also unwraps a `reduced` (Clojure @(reduced x) => x, -;; which the overlay's `unreduced` relies on). The reduced record is in seq.ss. -(define (jolt-deref x) - (cond - ((jolt-atom? x) (jolt-atom-val x)) - ((jolt-reduced? x) (jolt-reduced-val x)) - (else (error #f "deref: unsupported reference type" x)))) - -;; CAS the val from `old` to `nv` by identity (eq?), atomically. Returns #t on -;; success. The compute step (f) runs outside this, so we re-check under the lock. -(define (jolt-atom-cas! a old nv) - (with-mutex (jolt-atom-lock a) - (if (eq? (jolt-atom-val a) old) - (begin (jolt-atom-val-set! a nv) #t) - #f))) - -;; (swap! a f arg*): JVM-style CAS loop — read, compute f OUTSIDE the lock, then -;; atomically compare-and-set; retry if another thread changed it. Validate the -;; new value before storing, notify watches after. -(define (jolt-swap! a f . args) - (let retry () - (let* ((old (jolt-atom-val a)) - (nv (apply jolt-invoke f old args))) - (jolt-atom-validate a nv) - (if (jolt-atom-cas! a old nv) - (begin (jolt-atom-notify a old nv) nv) - (retry))))) - -(define (jolt-reset! a v) - (jolt-atom-validate a v) - (let ((old (with-mutex (jolt-atom-lock a) - (let ((o (jolt-atom-val a))) (jolt-atom-val-set! a v) o)))) - (jolt-atom-notify a old v) - v)) - -;; compare-and-set! keeps jolt= (value) semantics, done atomically under the lock. -(define (jolt-compare-and-set! a oldv newv) - (jolt-atom-validate a newv) - (let ((swapped (with-mutex (jolt-atom-lock a) - (if (jolt= (jolt-atom-val a) oldv) - (begin (jolt-atom-val-set! a newv) #t) - #f)))) - (when swapped (jolt-atom-notify a oldv newv)) - swapped)) - -(define (jolt-swap-vals! a f . args) - (let retry () - (let* ((old (jolt-atom-val a)) - (nv (apply jolt-invoke f old args))) - (jolt-atom-validate a nv) - (if (jolt-atom-cas! a old nv) - (begin (jolt-atom-notify a old nv) (jolt-vector old nv)) - (retry))))) - -(define (jolt-reset-vals! a v) - (jolt-atom-validate a v) - (let ((old (with-mutex (jolt-atom-lock a) - (let ((o (jolt-atom-val a))) (jolt-atom-val-set! a v) o)))) - (jolt-atom-notify a old v) - (jolt-vector old v))) - -;; --- watches / validators: the IRef seam -------------------------------------- -;; On the JVM these are the ARef contract shared by atom/var/agent/ref. The atom -;; keeps its record slots (the hot swap!/reset! path); every OTHER watchable -;; reference type registers a predicate here and stores its watches/validator in -;; identity-keyed side tables. A ref type makes itself notify by calling -;; iref-notify at its mutation points (vars do at root set). -(define iref-arms '()) -(define (register-iref-arm! pred) (set! iref-arms (cons pred iref-arms))) -(define (iref? r) - (let loop ((as iref-arms)) - (cond ((null? as) #f) (((car as) r) #t) (else (loop (cdr as)))))) -(define iref-watch-tbl (make-weak-eq-hashtable)) -(define iref-validator-tbl (make-weak-eq-hashtable)) -(define (iref-notify r old new) - (for-each (lambda (kv) (jolt-invoke (cdr kv) (car kv) r old new)) - (reverse (hashtable-ref iref-watch-tbl r '())))) -(define (iref-validate r v) - (let ((vf (hashtable-ref iref-validator-tbl r jolt-nil))) - (when (and (not (jolt-nil? vf)) (jolt-not (jolt-invoke vf v))) - (jolt-iref-state-throw)))) - -;; add-watch interns (key . fn) (replacing any existing key, keeping order); -;; remove-watch drops it; both return the reference. set-validator! installs a -;; validator and validates the CURRENT value immediately (Clojure throws if it's -;; already invalid); get-validator reads the slot. -(define (jolt-watch-add alist key f) - (cons (cons key f) (remp (lambda (kv) (jolt=2 (car kv) key)) alist))) -(define (jolt-add-watch a key f) - (cond - ((jolt-atom? a) - (jolt-atom-watches-set! a (jolt-watch-add (jolt-atom-watches a) key f)) - a) - ((iref? a) - (hashtable-set! iref-watch-tbl a (jolt-watch-add (hashtable-ref iref-watch-tbl a '()) key f)) - a) - (else (error #f "add-watch: not a watchable reference" a)))) -(define (jolt-remove-watch a key) - (cond - ((jolt-atom? a) - (jolt-atom-watches-set! a - (remp (lambda (kv) (jolt=2 (car kv) key)) (jolt-atom-watches a))) - a) - ((iref? a) - (hashtable-set! iref-watch-tbl a - (remp (lambda (kv) (jolt=2 (car kv) key)) (hashtable-ref iref-watch-tbl a '()))) - a) - (else (error #f "remove-watch: not a watchable reference" a)))) -(define (jolt-set-validator! a f) - (let ((vf (if (jolt-nil? f) jolt-nil f))) - (cond - ((jolt-atom? a) - (when (and (not (jolt-nil? vf)) (jolt-not (jolt-invoke vf (jolt-atom-val a)))) - (jolt-iref-state-throw)) - (jolt-atom-validator-set! a vf)) - ((iref? a) - (when (and (not (jolt-nil? vf)) (jolt-not (jolt-invoke vf (jolt-deref a)))) - (jolt-iref-state-throw)) - (hashtable-set! iref-validator-tbl a vf)) - (else (error #f "set-validator!: not a reference" a))) - jolt-nil)) -(define (jolt-get-validator a) - (cond ((jolt-atom? a) (jolt-atom-validator a)) - ((iref? a) (hashtable-ref iref-validator-tbl a jolt-nil)) - (else jolt-nil))) - -;; vars are watchable IRefs: a root change (def / var-set on the root / -;; alter-var-root) validates and notifies like Var.bindRoot. The def-var! wrap -;; pays two weak-table probes per def and only does IRef work on a watched var. -(register-iref-arm! var-cell?) -(define def-var!-pre-iref def-var!) -(set! def-var! - (lambda (ns name v) - (let ((c (jolt-var ns name))) - (if (or (pair? (hashtable-ref iref-watch-tbl c '())) - (not (jolt-nil? (hashtable-ref iref-validator-tbl c jolt-nil)))) - (let ((old (var-cell-root c))) - (iref-validate c v) - (let ((r (def-var!-pre-iref ns name v))) - (iref-notify c old v) - r)) - (def-var!-pre-iref ns name v))))) - -(def-var! "clojure.core" "atom" jolt-atom-new) -(def-var! "clojure.core" "deref" jolt-deref) -(def-var! "clojure.core" "swap!" jolt-swap!) -(def-var! "clojure.core" "reset!" jolt-reset!) -(def-var! "clojure.core" "compare-and-set!" jolt-compare-and-set!) -(def-var! "clojure.core" "swap-vals!" jolt-swap-vals!) -(def-var! "clojure.core" "reset-vals!" jolt-reset-vals!) -(def-var! "clojure.core" "atom?" jolt-atom?) -;; peripheral ops: the overlay (20-coll) re-defs these over jolt.host/ref-put!, -;; which fails on an atom record — post-prelude.ss re-asserts the natives. -(def-var! "clojure.core" "add-watch" jolt-add-watch) -(def-var! "clojure.core" "remove-watch" jolt-remove-watch) -(def-var! "clojure.core" "set-validator!" jolt-set-validator!) -(def-var! "clojure.core" "get-validator" jolt-get-validator) diff --git a/host/chez/bootstrap.ss b/host/chez/bootstrap.ss deleted file mode 100644 index 2c4e451..0000000 --- a/host/chez/bootstrap.ss +++ /dev/null @@ -1,41 +0,0 @@ -;; bootstrap.ss — the pure-Chez self-build. -;; -;; Given a SEED (prelude, image) pair — the bootstrap compiler, checked in under -;; host/chez/seed/ — it loads them, then rebuilds the clojure.core prelude AND the -;; compiler image from the .clj/.ss sources using the on-Chez compiler -;; (emit-image.ss), writing fresh artifacts: read -> analyze -> emit all run on -;; Chez. The seed is a JOINT fixpoint, so a rebuild from an up-to-date seed -;; reproduces it byte-for-byte (`make selfhost` checks this); when the sources -;; change, run it twice to reconverge and re-mint the seed. -;; -;; Run from the repo root: -;; chez --script host/chez/bootstrap.ss SEED-PRELUDE SEED-IMAGE OUT-PRELUDE OUT-IMAGE -(import (chezscheme)) - -(define bs-args (cdr (command-line))) ; drop the script name -(when (< (length bs-args) 4) - (display "usage: bootstrap.ss SEED-PRELUDE SEED-IMAGE OUT-PRELUDE OUT-IMAGE\n") - (exit 2)) -(define bs-seed-prelude (list-ref bs-args 0)) -(define bs-seed-image (list-ref bs-args 1)) -(define bs-out-prelude (list-ref bs-args 2)) -(define bs-out-image (list-ref bs-args 3)) - -;; Load the runtime + the SEED compiler (prelude for macros, image for the -;; analyzer/emitter), exactly as the spine assembles a program. -(load "host/chez/rt.ss") -(set-chez-ns! "clojure.core") -(load bs-seed-prelude) -(load "host/chez/post-prelude.ss") -(set-chez-ns! "user") -(load "host/chez/host-contract.ss") -(load bs-seed-image) -(load "host/chez/compile-eval.ss") -(load "host/chez/emit-image.ss") - -;; Rebuild both artifacts from source ON CHEZ and write them out. -(let ((p (open-output-file bs-out-prelude 'replace))) - (put-string p (jolt-emit-prelude)) (close-port p)) -(let ((p (open-output-file bs-out-image 'replace))) - (put-string p (jolt-emit-image)) (close-port p)) -(display "bootstrap: rebuilt prelude + compiler image on Chez\n") diff --git a/host/chez/build-joltc.ss b/host/chez/build-joltc.ss deleted file mode 100644 index 12612a1..0000000 --- a/host/chez/build-joltc.ss +++ /dev/null @@ -1,264 +0,0 @@ -;; build-joltc.ss — build joltc itself as a self-contained native binary (jolt-eaj). -;; -;; chez --script host/chez/build-joltc.ss -;; profile: "release" | "debug" out-path: e.g. target/release/joltc -;; -;; Runs on a dev/CI machine that HAS Chez + cc. Produces a binary that needs -;; NEITHER: it bakes the full runtime + compiler image + all jolt-core/stdlib -;; source + the Chez petite/scheme boots + a prebuilt launcher stub into one -;; cc-linked executable, so the resulting joltc can run AND `build` jolt apps on -;; its own. joltc itself is cc-linked (not appended) so its signature stays clean -;; for Homebrew/codesign, like dirge's binaries; only the apps it later builds use -;; the appended-stub path (host/chez/build.ss build-self-contained). -;; -;; Pipeline: -;; 0. cc-compile host/chez/stub/launcher.c against the Chez kernel. -;; 1. emit flat.ss = runtime + compiler image (cli.ss load order) + inlined -;; build.ss + every jolt-core/stdlib file as a baked string literal + the -;; joltc launcher. -;; 2. in-process compile-file + make-boot-file (profile Chez settings), error -;; restored around the call (the runtime shadows it; regex.ss/%chez-error). -;; 3. xxd the joltc boot + petite/scheme boots + stub into C arrays, generate -;; main.c, cc-link -> out-path. The launcher reads the petite/scheme/stub -;; arrays via FFI on `build` (jolt-materialize-bundles!). - -(import (chezscheme)) - -(load "host/chez/rt.ss") -(set-chez-ns! "clojure.core") -(load "host/chez/seed/prelude.ss") -(load "host/chez/post-prelude.ss") -(set-chez-ns! "user") -(load "host/chez/host-contract.ss") -(load "host/chez/seed/image.ss") -(load "host/chez/compile-eval.ss") -(load "host/chez/png.ss") -(load "host/chez/loader.ss") -(load "host/chez/java/ffi.ss") -(set-source-roots! (list "jolt-core" "stdlib")) -(load "host/chez/build.ss") ; bld-* helpers, ei-* (emit-image), dce - -(define jb-args (cdr (command-line))) -(define jb-profile (if (pair? jb-args) (car jb-args) "release")) -(define jb-out (if (and (pair? jb-args) (pair? (cdr jb-args))) (cadr jb-args) - (string-append "target/" jb-profile "/joltc"))) -(define jb-release? (string=? jb-profile "release")) -(unless (or jb-release? (string=? jb-profile "debug")) - (error 'build-joltc "profile must be \"release\" or \"debug\"" jb-profile)) - -;; Version baked into the binary's saved heap. Prefer $JOLT_VERSION (CI sets it to -;; the release tag); else derive it from git in this checkout; else "dev". -(define jb-version - (let ((env (getenv "JOLT_VERSION"))) - (if (and env (> (string-length env) 0)) - env - (let ((s (bld-sh-capture "git describe --tags --always --dirty 2>/dev/null"))) - (if (> (string-length s) 0) s "dev"))))) - -(define jb-build (string-append jb-out ".build")) -(bld-check-toolchain) -(bld-system (string-append "mkdir -p '" (path-parent jb-out) "' '" jb-build "'")) - -;; --- 0. compile the launcher stub ------------------------------------------- -(define jb-stub (string-append jb-build "/launcher")) -(display "build-joltc: compiling launcher stub\n") -(bld-system (string-append - "cc -O2 -I'" bld-csv-dir "' 'host/chez/stub/launcher.c' '" - bld-csv-dir "/libkernel.a' -o '" jb-stub "' " (bld-link-libs))) - -;; --- 1. emit flat.ss -------------------------------------------------------- -(define jb-flat-ss (string-append jb-build "/flat.ss")) -(define (str-suffix? s suf) - (let ((n (string-length s)) (m (string-length suf))) - (and (>= n m) (string=? (substring s (- n m) n) suf)))) - -;; Bake every jolt-core/stdlib source file as an in-heap string literal keyed by -;; its root-relative path ("jolt/main.clj", "clojure/string.clj") — exactly what -;; resolve-on-roots probes. Literals (not read-file-string at startup) because -;; flat.ss top-level forms run at every startup, with no source on disk. -(define (jb-emit-source-embeds out) - (for-each - (lambda (root) - (for-each - (lambda (rp) - (let ((rel (car rp)) (abs (cdr rp))) - (when (or (str-suffix? rel ".clj") (str-suffix? rel ".cljc")) - (put-string out (string-append - "(register-embedded-resource! " (ei-str-lit rel) " " - (ei-str-lit (read-file-string abs)) ")\n"))))) - (bld-walk-files root "" '()))) - (list "jolt-core" "stdlib"))) - -;; Embed every runtime .ss the build inlines into an app (the transitive closure of -;; the manifest's loads: rt.ss + all it loads, the seed, compile-eval, loader, ffi, -;; png, vendored irregex). Keyed by the exact path the (load "…") forms use, so -;; build.ss's bld-source-string reads them from the binary with no jolt source on -;; disk. Traversal mirrors bld-emit-runtime/bld-inline-line via the same -;; bld-file-lines + bld-load-path, so the embedded set is exactly what build reads. -(define (jb-collect-load-paths) - (let ((seen (make-hashtable string-hash string=?)) (order '())) - (define (walk path) - (when (and path (not (hashtable-ref seen path #f))) - (hashtable-set! seen path #t) - (set! order (cons path order)) - (for-each (lambda (l) (walk (bld-load-path l))) (bld-file-lines path)))) - (for-each (lambda (entry) (when (string? entry) (walk (bld-load-path entry)))) - bld-runtime-manifest) - (for-each (lambda (kv) (walk (bld-load-path (cdr kv)))) bld-tagged-loads) - (reverse order))) - -(define (jb-emit-runtime-embeds out) - (for-each - (lambda (path) - (put-string out (string-append - "(register-embedded-resource! " (ei-str-lit path) " " - (ei-str-lit (read-file-string path)) ")\n"))) - (jb-collect-load-paths))) - -;; The launcher (Chez scheme-start): replicates host/chez/cli.ss but reads argv -;; from the scheme-start lambda and has no repo root to cd into (all source is -;; embedded; JOLT_PWD defaults to cwd via io/jolt.main). build.ss is already -;; inlined, so `build` dispatches straight to jolt.host/build-binary after the -;; bundled boots/stub are materialized from the binary's own C arrays. -(define (jb-emit-launcher out) - (put-string out " -;; Materialize the bundled Chez boots + launcher stub (cc-linked into this binary -;; as C arrays) into the embedded-bytes store, so build-self-contained can spill -;; them. Done lazily on `build` only. -(define (jolt-materialize-bundles!) - (load-shared-object #f) - (let ((memcpy (foreign-procedure \"memcpy\" (u8* uptr uptr) void*))) - (for-each - (lambda (spec) - (let* ((len (foreign-ref 'unsigned-int (foreign-entry (caddr spec)) 0)) - (bv (make-bytevector len))) - (memcpy bv (foreign-entry (cadr spec)) len) - (register-embedded-bytes! (car spec) bv))) - '((\"csv/petite.boot\" \"jolt_petite_boot\" \"jolt_petite_boot_len\") - (\"csv/scheme.boot\" \"jolt_scheme_boot\" \"jolt_scheme_boot_len\") - (\"stub/launcher\" \"jolt_stub\" \"jolt_stub_len\") - (\"csv/scheme.h\" \"jolt_scheme_h\" \"jolt_scheme_h_len\") - (\"csv/libkernel.a\" \"jolt_libkernel_a\" \"jolt_libkernel_a_len\") - (\"stub/launcher.c\" \"jolt_launcher_c\" \"jolt_launcher_c_len\"))))) - -(suppress-greeting #t) -(scheme-start - (lambda args - (set-source-roots! (list \"jolt-core\" \"stdlib\")) - ;; JOLT_TRACE at RUNTIME (the env is unset at heap-build), before any app ns - ;; compiles, so a `-M:run` traces the app's own code. - (jolt-trace-init-from-env!) - (guard (v (#t (jolt-report-throwable v (current-error-port)) (exit 1))) - (cond - ((and (= (length args) 2) (string=? (car args) \"-e\")) - (let ((result (jolt-final-str - (jolt-compile-eval (string-append \"(do \" (cadr args) \")\") \"user\")))) - (unless (string=? result \"\") (display result) (newline)))) - (else - (when (and (pair? args) (string=? (car args) \"build\")) - (jolt-materialize-bundles!)) - (load-namespace \"jolt.main\") - (apply jolt-invoke (var-deref \"jolt.main\" \"-main\") args)))) - (exit 0))) -")) - -(display "build-joltc: emitting flat source\n") -(let ((out (open-output-file jb-flat-ss 'replace))) - ;; full runtime + compiler image: keep the compiler (joltc evals at runtime). - (bld-emit-runtime out #f #f) - (put-string out "\n;; === build driver (inlined for self-contained `jolt build`) ===\n") - (bld-inline-line "(load \"host/chez/build.ss\")" out 0) - (put-string out "\n;; === embedded runtime source (self-contained `build` reads these) ===\n") - (jb-emit-runtime-embeds out) - (put-string out "\n;; === embedded jolt-core + stdlib source ===\n") - (jb-emit-source-embeds out) - ;; Bake the version into the saved heap (runs at heap-build; loader.ss defined - ;; jolt-baked-version above, so this set! resolves). - (put-string out (string-append "\n;; === baked version ===\n(set! jolt-baked-version " - (ei-str-lit jb-version) ")\n")) - (put-string out "\n;; === joltc launcher ===\n") - (jb-emit-launcher out) - (close-port out)) - -;; --- 2. compile + boot in a FRESH Chez (profile Chez settings) -------------- -;; joltc is a compiler/REPL: it evals jolt-compiled Scheme at runtime, which must -;; resolve the runtime's top-level procedures (var-deref, jolt-inc, …) through the -;; boot's interaction-environment. compile-file's top-level defines are visible -;; there only when compiled in the REAL interaction-environment, and `error` (and -;; other primitives the inlined runtime references before redefining) bind to the -;; kernel primitive only when compiled against a clean chezscheme env. A fresh -;; Chez process gives both at once — exactly the legacy build-with-cc pass. The -;; in-process compile in build.ss/build-self-contained is for the distributed -;; joltc building (non-eval) apps, where no Chez is available. -(define jb-flat-so (string-append jb-build "/flat.so")) -(define jb-boot (string-append jb-build "/joltc.boot")) -(define jb-bool (lambda (b) (if b "#t" "#f"))) -(display (string-append "build-joltc: compiling (" jb-profile " profile)\n")) -(let ((cs (string-append jb-build "/compile.ss"))) - (let ((p (open-output-file cs 'replace))) - (put-string p - (string-append - "(import (chezscheme))\n" - "(optimize-level " (if jb-release? "3" "0") ")\n" - "(generate-inspector-information " (jb-bool (not jb-release?)) ")\n" - "(generate-procedure-source-information " (jb-bool (not jb-release?)) ")\n" - "(debug-on-exception " (jb-bool (not jb-release?)) ")\n" - "(fasl-compressed " (jb-bool jb-release?) ")\n" - "(compile-file " (ei-str-lit jb-flat-ss) " " (ei-str-lit jb-flat-so) ")\n" - "(make-boot-file " (ei-str-lit jb-boot) " '()\n " - (ei-str-lit (string-append bld-csv-dir "/petite.boot")) "\n " - (ei-str-lit (string-append bld-csv-dir "/scheme.boot")) "\n " - (ei-str-lit jb-flat-so) ")\n")) - (close-port p)) - (bld-system (string-append bld-chez " --script '" cs "'"))) - -;; --- 3. embed boots/stub as C arrays + cc-link ------------------------------ -;; xxd a file into header H and rename its symbol to NAME / NAME_len. -(define (jb-c-array file h name) - (bld-system (string-append "xxd -i '" file "' > '" h "'")) - (bld-system (string-append - "sed -i.bak -E 's/unsigned char [A-Za-z0-9_]+\\[\\]/unsigned char " name "[]/; " - "s/unsigned int [A-Za-z0-9_]+_len/unsigned int " name "_len/' '" h "'"))) - -(display "build-joltc: embedding boots + stub, linking\n") -(jb-c-array jb-boot (string-append jb-build "/boot_data.h") "jolt_boot") -(jb-c-array (string-append bld-csv-dir "/petite.boot") (string-append jb-build "/petite_data.h") "jolt_petite_boot") -(jb-c-array (string-append bld-csv-dir "/scheme.boot") (string-append jb-build "/scheme_data.h") "jolt_scheme_boot") -(jb-c-array jb-stub (string-append jb-build "/stub_data.h") "jolt_stub") -;; Also bundle the Chez kernel (libkernel.a + scheme.h) and the launcher source, -;; so a `build` with :static native libs can re-link a custom stub with those -;; archives baked in — the appended-stub path can't add object code to a prebuilt -;; stub, so it relinks (build.ss bld-relink-stub). Needs the system cc at build. -(jb-c-array (string-append bld-csv-dir "/scheme.h") (string-append jb-build "/schemeh_data.h") "jolt_scheme_h") -(jb-c-array (string-append bld-csv-dir "/libkernel.a") (string-append jb-build "/libkernel_data.h") "jolt_libkernel_a") -(jb-c-array "host/chez/stub/launcher.c" (string-append jb-build "/launcherc_data.h") "jolt_launcher_c") - -(define jb-main-c (string-append jb-build "/main.c")) -(let ((mc (open-output-file jb-main-c 'replace))) - (put-string mc - (string-append - "#include \"scheme.h\"\n" - "#include \"boot_data.h\"\n" - "#include \"petite_data.h\"\n" - "#include \"scheme_data.h\"\n" - "#include \"stub_data.h\"\n" - "#include \"schemeh_data.h\"\n" - "#include \"libkernel_data.h\"\n" - "#include \"launcherc_data.h\"\n" - "int main(int argc, char *argv[]) {\n" - " Sscheme_init(0);\n" - " Sregister_boot_file_bytes(\"jolt\", jolt_boot, jolt_boot_len);\n" - " Sbuild_heap(0, 0);\n" - " int status = Sscheme_start(argc, (const char **)argv);\n" - " Sscheme_deinit();\n return status;\n}\n")) - (close-port mc)) - -;; -rdynamic puts the embedded jolt_* boot/stub symbols in the dynamic symbol -;; table so `build` can foreign-entry them to spill the bundled Chez boots. On -;; Linux dlsym can't see executable symbols otherwise (macOS exports them anyway). -(bld-system (string-append - ;; the embedded jolt_* arrays must be foreign-entry-visible at runtime: - ;; -rdynamic on ELF; on Windows an exe needs an export table (GetProcAddress). - "cc -O2 " (if bld-nt? "-Wl,--export-all-symbols " "-rdynamic ") "-I'" bld-csv-dir "' -I'" jb-build "' '" jb-main-c "' '" - bld-csv-dir "/libkernel.a' -o '" jb-out "' " (bld-link-libs))) -(display (string-append "build-joltc: wrote " jb-out "\n")) diff --git a/host/chez/build-smoke.sh b/host/chez/build-smoke.sh deleted file mode 100755 index 76b4f50..0000000 --- a/host/chez/build-smoke.sh +++ /dev/null @@ -1,170 +0,0 @@ -#!/bin/sh -# build smoke: `jolt build` compiles a multi-namespace app (macro + cross-ns + -# clojure.string) into a standalone binary, which then runs with no jolt source -# or Chez install on the path — args reach -main, output matches. -root="$(CDPATH= cd -- "$(dirname -- "$0")/../.." && pwd)" -cd "$root" - -# Preflight: a standalone build needs Chez's kernel dev files (libkernel.a + -# scheme.h) and a C compiler. A distro chezscheme package ships neither, so on -# such hosts (CI included) skip — like `certify` skips without Clojure. Pin the -# csv dir we validate so the build uses exactly it. -csv="$JOLT_CHEZ_CSV" -if [ -z "$csv" ]; then - chez_bin="$(command -v chez || command -v scheme || command -v petite || true)" - if [ -n "$chez_bin" ]; then - base="$(cd "$(dirname "$chez_bin")/.." 2>/dev/null && pwd)" - for d in "$base"/lib/csv*/*/; do - [ -f "${d}libkernel.a" ] && csv="${d%/}" && break - done - fi -fi -if ! command -v cc >/dev/null 2>&1 || [ -z "$csv" ] || [ ! -f "$csv/scheme.h" ] || [ ! -f "$csv/libkernel.a" ]; then - echo "build smoke: skipped (Chez kernel dev files or C compiler not available)" - exit 0 -fi -export JOLT_CHEZ_CSV="$csv" - -app="$root/test/chez/build-app" -out="$(mktemp -d)/app-bin" -trap 'rm -rf "$(dirname "$out")"' EXIT - -echo "build smoke: compiling app.core -> $out" -if ! JOLT_PWD="$app" bin/joltc build -m app.core -o "$out" >/dev/null 2>&1; then - echo " FAIL: jolt build exited non-zero" - exit 1 -fi -[ -x "$out" ] || { echo " FAIL: no executable produced"; exit 1; } - -# Run from a neutral cwd with args. The first line is an embedded resource -# (deps.edn :jolt/build :embed), proving io/resource resolves from the binary with -# no resources/ dir on disk; the rest exercise a macro, cross-ns, and args. -got="$(cd / && "$out" alpha bb ccc 2>&1)" -want='embedded resource ok -HELLO FROM A BUILT BINARY! -HELLO FROM A BUILT BINARY! -args: [alpha bb ccc] -sum: 10 -greet-default: greet:default -greet-loud: greet:loud -greet-soft: greet:soft' -if [ "$got" != "$want" ]; then - echo " FAIL: binary output mismatch" - echo "--- want ---"; echo "$want" - echo "--- got ----"; echo "$got" - exit 1 -fi - -# Optimized mode (inference + flatten + scalar-replace) must produce the same -# result — a sanity check that the passes don't miscompile this app. -if ! JOLT_PWD="$app" bin/joltc build -m app.core -o "$out" --opt >/dev/null 2>&1; then - echo " FAIL: jolt build --opt exited non-zero"; exit 1 -fi -got_opt="$(cd / && "$out" alpha bb ccc 2>&1)" -if [ "$got_opt" != "$want" ]; then - echo " FAIL: --opt binary output mismatch" - echo "--- got ----"; echo "$got_opt" - exit 1 -fi - -# Closed-world direct-linking (opt-in): same result, and the cross-namespace call -# (app.core -> app.util/shout) must lower to a direct jv$ binding, not var-deref. -if ! JOLT_PWD="$app" bin/joltc build -m app.core -o "$out" --direct-link >/dev/null 2>&1; then - echo " FAIL: jolt build --direct-link exited non-zero"; exit 1 -fi -got_dl="$(cd / && "$out" alpha bb ccc 2>&1)" -if [ "$got_dl" != "$want" ]; then - echo " FAIL: --direct-link binary output mismatch" - echo "--- got ----"; echo "$got_dl" - exit 1 -fi -if ! grep -q '(jv\$app.util\$shout' "$out.build/flat.ss"; then - echo " FAIL: --direct-link did not emit a direct app->app call"; exit 1 -fi -# A direct-link build registers fn sources, so an uncaught throw prints a Clojure -# stack trace mapping each native frame back to ns/name (file:line). -if ! grep -q 'jolt-register-source!' "$out.build/flat.ss"; then - echo " FAIL: --direct-link did not emit source registrations"; exit 1 -fi -boom_err="$(cd / && "$out" --boom 2>&1 >/dev/null)" -for frame in 'app.util/deep-boom' 'app.util/mid-boom' 'app.core/-main'; do - if ! printf '%s' "$boom_err" | grep -q "$frame"; then - echo " FAIL: stack trace missing frame $frame" - echo "--- got ----"; echo "$boom_err" - exit 1 - fi -done -# A built binary runs -main with *ns* = user, like clojure.main — so a runtime -# resolve of an aliased symbol is nil (the alias lives in the entry ns, not user), -# matching the JVM and interpreted joltc rather than the entry ns's alias table. A -# separate app: `resolve` defeats tree-shaking, so keep it out of the shake test's -# app above. -nsp="$(dirname "$out")/nsparity" -mkdir -p "$nsp/src/nsp" -printf '{:paths ["src"]}\n' > "$nsp/deps.edn" -printf '(ns nsp.lib)\n(defn thing [] 1)\n' > "$nsp/src/nsp/lib.clj" -printf '(ns nsp.main (:require [nsp.lib :as l]))\n(defn -main [& _]\n (println "ns:" (str *ns*))\n (println "resolve:" (pr-str (resolve (quote l/thing))))\n (println "ns-resolve:" (pr-str (ns-resolve (quote nsp.lib) (quote thing)))))\n' > "$nsp/src/nsp/main.clj" -nspout="$(dirname "$out")/nsparity-bin" -if ! JOLT_PWD="$nsp" bin/joltc build -m nsp.main -o "$nspout" >/dev/null 2>&1; then - echo " FAIL: jolt build of the ns-parity app exited non-zero"; exit 1 -fi -nsp_out="$(cd / && "$nspout" 2>&1)" -if ! printf '%s' "$nsp_out" | grep -q 'ns: user' \ - || ! printf '%s' "$nsp_out" | grep -q '^resolve: nil' \ - || ! printf '%s' "$nsp_out" | grep -q "ns-resolve: #'nsp.lib/thing"; then - echo " FAIL: built binary -main ns parity — want 'ns: user', 'resolve: nil', ns-resolve found" - echo "--- got ----"; echo "$nsp_out" - exit 1 -fi -# Tree-shaking (opt-in): same result, and an unreachable def (the `twice` macro, -# expanded at AOT and never called at runtime) is dropped. -if ! JOLT_PWD="$app" bin/joltc build -m app.core -o "$out" --tree-shake >/dev/null 2>&1; then - echo " FAIL: jolt build --tree-shake exited non-zero"; exit 1 -fi -got_ts="$(cd / && "$out" alpha bb ccc 2>&1)" -if [ "$got_ts" != "$want" ]; then - echo " FAIL: --tree-shake binary output mismatch" - echo "--- got ----"; echo "$got_ts" - exit 1 -fi -if grep -q 'def-var! "app.util" "twice"' "$out.build/flat.ss"; then - echo " FAIL: --tree-shake did not drop the unreachable twice macro"; exit 1 -fi -# The app never evals, so the compiler image (analyzer/back end) is dropped. -if grep -q 'def-var! "jolt.analyzer"' "$out.build/flat.ss"; then - echo " FAIL: --tree-shake kept the compiler image in a no-eval app"; exit 1 -fi -# Core is shaken: a clojure.core overlay fn this app never uses is dropped. -if grep -q 'def-var! "clojure.core" "group-by"' "$out.build/flat.ss"; then - echo " FAIL: --tree-shake kept an unreachable clojure.core fn (group-by)"; exit 1 -fi -# A registered data reader that returns a CODE form must be compiled into the -# binary (the emit path applies it too, not just the interpreted loader): the -# datareader-app's #code literal builds to 42, not the literal list. -drapp="$root/test/chez/datareader-app" -drout="$(dirname "$out")/dr-bin" -if ! JOLT_PWD="$drapp" bin/joltc build -m drtest.main -o "$drout" >/dev/null 2>&1; then - echo " FAIL: jolt build of a data-reader app exited non-zero"; exit 1 -fi -got_dr="$(cd / && "$drout" 2>&1 | tail -1)" -if [ "$got_dr" != "42" ]; then - echo " FAIL: built #code data reader — want 42, got \`$got_dr\`"; exit 1 -fi - -# A script namespace with no -main (just top-level side effects) must build and -# run its top-level forms, then exit cleanly — not crash calling a nil -main. -nomain="$(dirname "$out")/nomain" -mkdir -p "$nomain/src" -printf '{:paths ["src"]}\n' > "$nomain/deps.edn" -printf '(ns script)\n(println "no-main script ran")\n' > "$nomain/src/script.clj" -nmout="$(dirname "$out")/nomain-bin" -if ! JOLT_PWD="$nomain" bin/joltc build -m script -o "$nmout" >/dev/null 2>&1; then - echo " FAIL: jolt build of a no-main script exited non-zero"; exit 1 -fi -got_nm="$(cd / && "$nmout" 2>&1)"; rc_nm=$? -if [ "$got_nm" != "no-main script ran" ] || [ "$rc_nm" != "0" ]; then - echo " FAIL: no-main script binary — want 'no-main script ran' rc 0, got \`$got_nm\` rc $rc_nm" - exit 1 -fi - -echo "build smoke: passed (release + optimized + direct-link + tree-shake + compiler+core shake + data-reader + no-main)" diff --git a/host/chez/build.ss b/host/chez/build.ss deleted file mode 100644 index 2f60edd..0000000 --- a/host/chez/build.ss +++ /dev/null @@ -1,751 +0,0 @@ -;; build.ss — `jolt build`: AOT-compile an app into a standalone executable. -;; -;; Loaded on demand by cli.ss when the command is `build`. Defines the host -;; primitive jolt.host/build-binary, which jolt.main's build command calls after -;; resolving the project's deps + source roots. -;; -;; The pipeline (Phase 4 stage 2): -;; 1. load the entry namespace — registers its macros/vars and follows requires, -;; recording the app namespaces in dependency order (loader's ns-loaded-hook). -;; 2. re-emit each app namespace to Scheme (the emit-image cross-compile path), -;; now that its macros are registered. -;; 3. textually inline the cli.ss runtime load sequence into one flat source, -;; append the app emission + a launcher that calls the entry's -main. -;; 4. compile-file -> make-boot-file -> embed the boot as C bytes -> cc-link -;; against libkernel.a into a single self-contained binary. -;; -;; emit-image.ss supplies the cross-compiler (ei-* helpers); it's loaded here so a -;; normal run never pays for it. - -(load "host/chez/emit-image.ss") -(load "host/chez/dce.ss") - -;; --- shell helpers ---------------------------------------------------------- -;; Run a command, return its stdout as one trimmed string ("" on no output). -(define (bld-sh-capture cmd) - (let* ((p (process (bld-sh-wrap cmd))) (in (car p))) - (let loop ((acc '())) - (let ((l (get-line in))) - (if (eof-object? l) - (begin (close-port in) - ;; rejoin with newlines (get-line stripped them). Callers use - ;; single-line output; this just avoids silently concatenating - ;; two lines into one corrupt token if a command emits more. - (let ((ls (reverse acc))) - (if (null? ls) "" - (fold-left (lambda (s x) (string-append s "\n" x)) (car ls) (cdr ls))))) - (loop (cons l acc))))))) - -(define (bld-system cmd) - (let ((rc (system (bld-sh-wrap cmd)))) - (unless (zero? rc) - (error 'jolt-build (string-append "command failed (" (number->string rc) "): " cmd))))) - -;; mkdir -p without a subprocess (the self-contained build shells out to nothing). -(define (bld-mkdir-p dir) - (unless (or (string=? dir "") (string=? dir "/") (string=? dir ".") (file-exists? dir)) - (bld-mkdir-p (path-parent dir)) - (guard (e (#t #f)) (mkdir dir)))) - -(define (bld-contains? s sub) - (let ((ns (string-length s)) (nsub (string-length sub))) - (let loop ((i 0)) - (cond ((> (+ i nsub) ns) #f) - ((string=? (substring s i (+ i nsub)) sub) #t) - (else (loop (+ i 1))))))) - -;; --- toolchain discovery ---------------------------------------------------- -(define bld-machine (symbol->string (machine-type))) -(define bld-osx? (bld-contains? bld-machine "osx")) -(define bld-nt? (bld-contains? bld-machine "nt")) - -;; Chez's system/process run through cmd.exe on Windows; every build command -;; here is written for sh (MSYS2 provides it). On nt, spill the command to a -;; script and run `sh ` — workspace paths carry no spaces, and the -;; script file sidesteps cmd's quoting entirely. Identity elsewhere. -(define bld-shell-counter 0) -(define (bld-sh-wrap cmd) - (if bld-nt? - (let* ((tmp (or (getenv "TEMP") (getenv "TMP") ".")) - (f (begin (set! bld-shell-counter (+ bld-shell-counter 1)) - (string-append tmp "\\jolt-sh-" - (number->string bld-shell-counter) ".sh")))) - (let ((p (open-output-file f 'replace))) - (put-string p cmd) - (close-port p)) - (string-append "sh " f)) - cmd)) - -;; The Chez executable, for the isolated compile pass (see build-binary step 4). -(define bld-chez - (let ((p (bld-sh-capture "command -v chez || command -v scheme || command -v petite"))) - (if (> (string-length p) 0) p "chez"))) - -;; Chez version off (scheme-version) "Chez Scheme Version X.Y.Z" — last token. -(define bld-version - (let* ((s (scheme-version)) (n (string-length s))) - (let loop ((i n)) - (if (or (= i 0) (char=? (string-ref s (- i 1)) #\space)) - (substring s i n) - (loop (- i 1)))))) - -;; The csv/ dir holding scheme.h, libkernel.a, *.boot. Derived from -;; the chez executable's location; JOLT_CHEZ_CSV overrides. -(define bld-csv-dir - (let ((env (getenv "JOLT_CHEZ_CSV"))) - (or (and env (> (string-length env) 0) env) - (let* ((bindir (bld-sh-capture "dirname \"$(command -v chez || command -v scheme || command -v petite)\"")) - (cand (string-append bindir "/../lib/csv" bld-version "/" bld-machine))) - cand)))) - -(define (bld-have-cc?) - (> (string-length (bld-sh-capture "command -v cc")) 0)) - -(define (bld-check-toolchain) - (for-each - (lambda (f) - (let ((p (string-append bld-csv-dir "/" f))) - (unless (file-exists? p) - (error 'jolt-build (string-append "Chez build file missing: " p - "\nSet JOLT_CHEZ_CSV to the csv/ dir."))))) - '("scheme.h" "libkernel.a" "petite.boot" "scheme.boot"))) - -;; Link flags. macOS Homebrew layout for the kernel's lz4/zlib/ncurses deps. -(define (bld-link-libs) - (cond - (bld-osx? - (let ((lz4 (bld-sh-capture "brew --prefix lz4 2>/dev/null"))) - (string-append - (if (> (string-length lz4) 0) (string-append "-L" lz4 "/lib ") "") - "-llz4 -lz -lncurses -framework Foundation -liconv -lm"))) - ;; Windows (ta6nt, MinGW-w64 under MSYS2): the Chez kernel pulls in - ;; compression, winsock, COM/UUID, and the registry. - (bld-nt? - ;; -static: a single-file exe (no libwinpthread/libgcc/lz4 DLL deps) — - ;; required for a distributable binary and for TLS init consistency. - "-static -llz4 -lz -lws2_32 -lrpcrt4 -lole32 -luuid -ladvapi32 -luser32 -lshell32 -lm") - ;; Linux: the Chez kernel pulls in compression (lz4/z), the expression - ;; editor (ncurses + terminfo), threads, dlopen, libuuid, and clock_gettime. - (else "-llz4 -lz -lncurses -ltinfo -ldl -lm -lpthread -luuid -lrt"))) - -;; --- runtime manifest (mirrors host/chez/cli.ss's load order) --------------- -;; A line is either literal Scheme text to inline, or a tag whose emission the build -;; controls: 'prelude (the clojure.core blob, replaced by the shaken core under -;; tree-shake), 'image + 'compile-eval (the compiler, dropped for a no-eval app). -;; Tagging keeps the splice/drop decisions off fragile substring matching. -(define bld-runtime-manifest - (list - "(load \"host/chez/rt.ss\")" - "(set-chez-ns! \"clojure.core\")" - 'prelude - "(load \"host/chez/post-prelude.ss\")" - "(set-chez-ns! \"user\")" - "(load \"host/chez/host-contract.ss\")" - 'image - 'compile-eval - "(load \"host/chez/png.ss\")" - "(load \"host/chez/loader.ss\")" - "(load \"host/chez/java/ffi.ss\")" - "(set-source-roots! (list \"jolt-core\" \"stdlib\"))")) - -(define bld-tagged-loads - '((prelude . "(load \"host/chez/seed/prelude.ss\")") - (image . "(load \"host/chez/seed/image.ss\")") - (compile-eval . "(load \"host/chez/compile-eval.ss\")"))) - -;; A single-line top-level `(load "PATH")` -> PATH, else #f. -(define (bld-load-path line) - (let ((s (let trim ((i 0)) - (if (and (< i (string-length line)) - (memv (string-ref line i) '(#\space #\tab))) - (trim (+ i 1)) - (substring line i (string-length line)))))) - (and (>= (string-length s) 7) - (string=? (substring s 0 6) "(load ") - (let* ((q1 (let scan ((i 6)) (if (char=? (string-ref s i) #\") i (scan (+ i 1))))) - (q2 (let scan ((i (+ q1 1))) (if (char=? (string-ref s i) #\") i (scan (+ i 1)))))) - (substring s (+ q1 1) q2))))) - -;; runtime source for PATH: from the binary's embedded store if present (a -;; self-contained joltc building an app, with no jolt checkout on disk), else read -;; from disk (running from a source checkout). build-joltc embeds every runtime -;; .ss the manifest inlines, so `build` never touches the filesystem for them. -(define (bld-source-string path) - (let ((emb (hashtable-ref embedded-resources path #f))) - (if (string? emb) emb (read-file-string path)))) - -(define (bld-string-lines s) - (let ((n (string-length s))) - (let loop ((i 0) (start 0) (acc '())) - (cond ((>= i n) (reverse (if (> i start) (cons (substring s start i) acc) acc))) - ((char=? (string-ref s i) #\newline) - (loop (+ i 1) (+ i 1) (cons (substring s start i) acc))) - (else (loop (+ i 1) start acc)))))) - -(define (bld-file-lines path) (bld-string-lines (bld-source-string path))) - -;; Emit one line to OUT, recursively inlining a `(load ...)` of a repo file. -(define (bld-inline-line line out depth) - (when (> depth 50) (error 'jolt-build "load nesting too deep")) - (let ((p (bld-load-path line))) - (if p - (for-each (lambda (l) (bld-inline-line l out (+ depth 1))) (bld-file-lines p)) - (begin (put-string out line) (put-string out "\n"))))) - -;; Inline the runtime manifest, dispatching on the manifest tags. core-strs (the -;; shaken clojure.core defs, or #f) replaces the 'prelude blob; drop-compiler? (a -;; closed AOT app that never compiles from source) omits 'image + 'compile-eval — -;; the analyzer/back end are dead weight in the binary (~0.8MB). -(define (bld-emit-runtime out drop-compiler? core-strs) - (for-each - (lambda (entry) - (cond - ((eq? entry 'prelude) - (if core-strs - (for-each (lambda (s) (put-string out s) (put-string out "\n")) core-strs) - (bld-inline-line (cdr (assq 'prelude bld-tagged-loads)) out 0))) - ((memq entry '(image compile-eval)) - (unless drop-compiler? (bld-inline-line (cdr (assq entry bld-tagged-loads)) out 0))) - (else (bld-inline-line entry out 0)))) - bld-runtime-manifest)) - -;; --- app emission ----------------------------------------------------------- -;; Re-emit one app namespace to a list of Scheme strings: optimize (run-passes) -;; and stay strict — a form that fails to emit must fail the build, not vanish. -;; The loop itself is emit-image's ei-emit-ns* (optimize? #t, guard? #f). -(define (bld-emit-ns ns-name src) (ei-emit-ns* ns-name src #t #f)) - -;; --- whole-program inference pre-pass --------------------------------------- -;; Analyze every app form (all namespaces, deps-first) to IR and run the -;; closed-world param-type fixpoint, so each fn's param types pick up the record -;; types its callers pass. The per-ns emit below then bare-indexes field reads and -;; devirtualizes protocol calls at those sites (the back end reads the resulting -;; :hint/:devirt annotations). Optimized builds only; registries come from the -;; runtime tables populated as the app loaded. -(define jolt-wp-infer! (var-deref "jolt.passes.types" "wp-infer!")) -(define jolt-wp-set-record-shapes! (var-deref "jolt.passes.types" "set-record-shapes!")) -(define jolt-wp-set-proto-methods! (var-deref "jolt.passes.types" "set-protocol-methods!")) -(define jolt-wp-host-record-shapes (var-deref "jolt.host" "record-shapes")) -(define jolt-wp-host-proto-methods (var-deref "jolt.host" "protocol-methods")) - -(define (bld-wp-infer! ordered) - (jolt-wp-set-record-shapes! (jolt-wp-host-record-shapes #f)) - (jolt-wp-set-proto-methods! (jolt-wp-host-proto-methods #f)) - (let ((nodes '())) - (for-each - (lambda (nf) - (set-chez-ns! (car nf)) - (let ((src (ldr-read-source (cdr nf)))) - (parameterize ((rdr-source-file (cdr nf))) - (for-each - (lambda (f) - (ce-scan-requires! f (car nf)) - (unless (or (ei-ns-form? f) (ce-macro-form? f)) - (guard (e (#t #f)) - (set! nodes (cons (jolt-ce-analyze (make-analyze-ctx (car nf)) f) nodes))))) - (ei-read-all src))))) - ordered) - (jolt-wp-infer! (apply jolt-vector (reverse nodes))))) - -;; Strings emitted before each app ns's forms, replaying what the source loader -;; does per file: (1) set chez-current-ns so runtime ns-sensitive setup forms -;; (defmulti/defmethod resolve their target var through it) land in the right ns; -;; (2) register the ns's :as aliases so a quoted alias resolves at runtime — a -;; (defmethod ig/foo …) passes 'ig/foo to defmethod-setup, which needs ig -> the -;; real ns, but the build strips the (ns …) form that would register it. -(define (bld-scan-spec! ns-name spec emit!) - (let ((items (cond ((pvec? spec) (seq->list spec)) - ((and (cseq? spec) (cseq-list? spec)) (seq->list spec)) - (else '())))) - (when (and (pair? items) (symbol-t? (car items))) - (let ((target (symbol-t-name (car items)))) - (let loop ((xs (cdr items))) - (when (and (pair? xs) (pair? (cdr xs))) - (let ((k (car xs)) (v (cadr xs))) - (when (keyword? k) - (cond - ((and (string=? (keyword-t-name k) "as") (symbol-t? v)) - (emit! (string-append "(chez-register-alias! " (ei-str-lit ns-name) - " " (ei-str-lit (symbol-t-name v)) - " " (ei-str-lit target) ")"))) - ;; :refer [a b] / :refer :all — a defmethod on a referred multifn - ;; resolves the bare name through the refer table at runtime. - ((or (string=? (keyword-t-name k) "refer") (string=? (keyword-t-name k) "only")) - (cond - ((and (keyword? v) (string=? (keyword-t-name v) "all")) - (emit! (string-append "(chez-register-refer-all! " (ei-str-lit ns-name) - " " (ei-str-lit target) ")"))) - ((or (pvec? v) (and (cseq? v) (cseq-list? v))) - (for-each (lambda (n) - (when (symbol-t? n) - (emit! (string-append "(chez-register-refer! " (ei-str-lit ns-name) - " " (ei-str-lit (symbol-t-name n)) - " " (ei-str-lit target) ")")))) - (seq->list v)))))))) - (loop (cddr xs)))))))) - -(define (bld-ns-prelude ns-name src) - (let ((acc (list (string-append "(set-chez-ns! " (ei-str-lit ns-name) ")"))) - (nsf (let loop ((fs (ei-read-all src))) - (cond ((null? fs) #f) - ((ei-ns-form? (car fs)) (car fs)) - (else (loop (cdr fs))))))) - (when nsf - (for-each - (lambda (clause) - (when (and (cseq? clause) (cseq-list? clause)) - (let ((citems (seq->list clause))) - (when (and (pair? citems) (keyword? (car citems)) - (let ((kn (keyword-t-name (car citems)))) - (or (string=? kn "require") (string=? kn "use")))) - (for-each (lambda (spec) - (bld-scan-spec! ns-name spec - (lambda (s) (set! acc (cons s acc))))) - (cdr citems)))))) - (seq->list nsf))) - (reverse acc))) - -;; --- bundling: native libs + resources -------------------------------------- -;; A jolt seq of jolt strings -> a Scheme list of Scheme strings. -(define (bld-strs x) (map jolt-str-render-one (seq->list x))) - -;; Emit native-library loads. `natives` is the encoded jolt seq jolt.main/ -;; encode-natives produced: each entry is ["process"] | ["static" form…] | -;; ["req" cand…] | ["opt" cand…]. `which` selects 'required (process + static + -;; req) or 'optional. Required loads are emitted before the app forms (the app's -;; defcfn foreign-procedures resolve their symbols at top-level eval during -;; startup, so the libs must be loaded first); a load-shared-object failure there -;; is fatal — correct for a required lib. A "static" lib is cc-linked into the -;; binary (see bld-native-link-flags), so its symbols are already in the process: -;; it loads them the same way a "process" lib does. Optional loads run in the -;; scheme-start launcher, where guard catches a missing lib (an optional lib's -;; namespace is only present when the app requires it, so its foreign-procedures -;; aren't among the baked top-level forms). -(define (bld-emit-natives out natives which) - (for-each - (lambda (entry) - (let* ((parts (bld-strs entry)) (kind (car parts)) (cands (cdr parts)) - (cand-lits (fold-left (lambda (s c) (string-append s (ei-str-lit c) " ")) "" cands))) - (cond - ((and (eq? which 'required) (or (string=? kind "process") (string=? kind "static"))) - (put-string out "(jolt-build-load-native '() #f #t)\n")) - ((and (eq? which 'required) (string=? kind "req")) - (put-string out (string-append "(jolt-build-load-native (list " cand-lits ") #f #f)\n"))) - ((and (eq? which 'optional) (string=? kind "opt")) - (put-string out (string-append "(jolt-build-load-native (list " cand-lits ") #t #f)\n")))))) - (seq->list natives))) - -;; The cc link fragment for the "static" natives: each archive must be FORCE-loaded -;; (the linker would otherwise drop an archive member main.c never references) and, -;; on Linux, the executable's symbols exported into the dynamic table so the -;; startup (load-shared-object #f) + foreign-procedure can resolve them (-rdynamic, -;; added by build-with-cc when this fragment is non-empty). Returns "" when no lib -;; is statically linked. Entry forms: ["static" "archive" path] | ["static" "lib" -;; name libdir]. -(define (bld-native-link-flags natives) - (fold-left - (lambda (acc entry) - (let ((parts (bld-strs entry))) - (if (string=? (car parts) "static") - (string-append acc " " (bld-one-static-link (cdr parts))) - acc))) - "" (seq->list natives))) - -;; A statically-linked native is only in the OUTPUT binary, but build step 1 -;; evaluates the app's `foreign-procedure` forms in THIS process (to register its -;; macros/vars), and Chez resolves a foreign entry eagerly. So make the archive's -;; symbols resolvable here: build a throwaway shared object from it (force-loading -;; every member) and load it. The output binary still cc-links the static archive; -;; this temp .so is build-time only. Only the "archive" form is preloaded — the -;; "lib" form names a system library the OS loader already finds by soname. -(define (bld-preload-static-natives! natives builddir) - (let ((n 0)) - (for-each - (lambda (entry) - (let ((parts (bld-strs entry))) - (when (and (string=? (car parts) "static") (string=? (cadr parts) "archive")) - (let* ((archive (caddr parts)) - (so (string-append builddir "/native-" (number->string n) - (if bld-osx? ".dylib" ".so")))) - (set! n (+ n 1)) - (bld-system - (if bld-osx? - (string-append "cc -dynamiclib -undefined dynamic_lookup -Wl,-all_load '" - archive "' -o '" so "'") - (string-append "cc -shared -Wl,--whole-archive '" archive - "' -Wl,--no-whole-archive -Wl,--unresolved-symbols=ignore-all -o '" so "'"))) - (load-shared-object so))))) - (seq->list natives)))) - -(define (bld-one-static-link form) - (let ((kind (car form))) - (cond - ((string=? kind "archive") - (let ((path (cadr form))) - (if bld-osx? - (string-append "-Wl,-force_load," path) - (string-append "-Wl,--whole-archive " path " -Wl,--no-whole-archive")))) - ((string=? kind "lib") - (let* ((lib (cadr form)) (dir (caddr form)) - (L (if (> (string-length dir) 0) (string-append "-L" dir " ") ""))) - ;; -Bstatic forces the .a over a .so of the same -l name (GNU ld). macOS's - ;; ld64 has no -Bstatic; there an :archive path is the reliable form. - (if bld-osx? - (string-append L "-l" lib) - (string-append L "-Wl,-Bstatic -l" lib " -Wl,-Bdynamic")))) - (else "")))) - -;; Walk an embed root recursively; return (resource-name . abspath) pairs, where -;; resource-name is the "/"-joined path under the root (what io/resource is asked for). -(define (bld-walk-files root rel acc) - (let ((dir (if (string=? rel "") root (string-append root "/" rel)))) - (fold-left - (lambda (acc name) - (let* ((relpath (if (string=? rel "") name (string-append rel "/" name))) - (full (string-append root "/" relpath))) - (if (file-directory? full) - (bld-walk-files root relpath acc) - (cons (cons relpath full) acc)))) - acc - (directory-list dir)))) - -;; Emit register-embedded-resource! per file under each embed dir. Emitted BEFORE -;; the app forms so the (read-file-string ABSPATH) runs at heap build — the file's -;; contents bake into the boot image and io/resource serves them with no file on -;; disk. ABSPATH only has to exist at build time. -(define (bld-emit-embeds out embed-dirs) - (for-each - (lambda (root) - (when (file-directory? root) - (for-each - (lambda (rp) - (put-string out (string-append - "(register-embedded-resource! " (ei-str-lit (car rp)) - " (read-file-string " (ei-str-lit (cdr rp)) "))\n"))) - (bld-walk-files root "" '())))) - (bld-strs embed-dirs))) - -;; --- the build -------------------------------------------------------------- -;; entry-ns: the app's main namespace (a string). out-path: the binary to write. -;; mode: "dev" | "release" | "optimized". Every form runs through jolt.passes/ -;; run-passes (const-fold always; inline + type inference when optimized turns on -;; direct-linking). Deps + source roots are already applied by the caller. -;; natives: encoded :jolt/native libs to load at startup. embed-dirs: dirs whose -;; files bake into the binary (single-file). ext-roots: project-relative io/resource -;; roots resolved at runtime against JOLT_PWD (ship-alongside resources). -;; direct-link?: opt-in closed-world direct-linking (app->app calls bind directly, -;; no runtime redefinition). Off by default in every mode — release stays -;; dynamically linked. -(define (bld-suffix? s suf) - (let ((n (string-length s)) (m (string-length suf))) - (and (>= n m) (string=? (substring s (- n m) n) suf)))) -(define (build-binary entry-ns out-path mode natives embed-dirs ext-roots direct-link? tree-shake?) - ;; Windows executables carry .exe; normalize here so the append-payload and - ;; cc paths agree and the shell can run the result. - (let ((out-path (if (and bld-nt? (not (bld-suffix? out-path ".exe"))) - (string-append out-path ".exe") - out-path))) - ;; The self-contained path (jolt-embedded-bytes "stub/launcher") needs no csv - ;; kernel files, no Chez, no cc — only the legacy cc path does. - (unless (jolt-embedded-bytes "stub/launcher") (bld-check-toolchain)) - (when (> (string-length (bld-native-link-flags natives)) 0) - ;; :static natives are cc-linked into the binary, so a C compiler must be on - ;; PATH — the self-contained joltc bundles the Chez kernel (libkernel.a + - ;; scheme.h) and relinks a custom stub (see build-self-contained), but still - ;; needs the system cc for that link. Fail early (before the app's foreign- - ;; procedure forms eval below) with an actionable message. - (unless (bld-have-cc?) - (error 'jolt-build - "static native linking needs a C compiler (cc) on PATH; install one, or pass --dynamic to load the library at runtime.")) - ;; Preload static archives' symbols into this process so step 1's foreign- - ;; procedure evals resolve; the .build dir must exist first. - (bld-mkdir-p (string-append out-path ".build")) - (bld-preload-static-natives! natives (string-append out-path ".build"))) - ;; 1. record app namespaces in dependency order as they finish loading. - (let ((app-order '())) - (set-ns-loaded-hook! - (lambda (name file) (set! app-order (cons (cons name file) app-order)))) - (load-namespace entry-ns) - (set-ns-loaded-hook! (lambda (name file) #f)) - (let ((ordered (reverse app-order))) ; deps first, entry last - (when (null? ordered) - (error 'jolt-build (string-append "no source namespace loaded for " entry-ns - " — is it on the source roots?"))) - ;; 2. emit each app namespace. `optimized` turns on the inference + flatten - ;; + scalar-replace passes; release/dev get const-fold only. - ;; direct-link? (opt-in) commits to a closed world: app->app calls bind - ;; directly, giving up runtime redefinition of those vars. Off by default in - ;; every mode. The defined-set accumulates across the dependency-ordered - ;; namespaces, so a dep's defs are direct-linkable by the time the entry that - ;; calls them is emitted. - ;; set-optimize!/set-direct-link! are process-global flags in the back end; - ;; dynamic-wind guarantees they revert even if a strict form errors mid-emit - ;; (a failing form errors the build by design), so the compiler isn't left in - ;; optimize/direct-link mode for a later caller. - (let*-values - (((core-strs app-strs drop-compiler?) - (dynamic-wind - (lambda () - (set-optimize! (string=? mode "optimized")) - (when direct-link? - ((var-deref "jolt.backend-scheme" "set-direct-link!") #t) - ((var-deref "jolt.backend-scheme" "direct-link-reset!"))) - ;; whole-program param-type fixpoint before per-form emit - (when (string=? mode "optimized") (bld-wp-infer! ordered))) - (lambda () - ;; A #tag data-reader literal must compile in the binary the same as - ;; it loads interpreted — apply the reader rewrite to each emitted - ;; form too (no-op unless the app registered data readers). - (parameterize ((ei-emit-form-hook - (lambda (form) (if data-readers-active (ldr-apply-readers form) form)))) - (if tree-shake? - (dce-shake - (dce-blob-records "host/chez/seed/prelude.ss") - (apply append - (map (lambda (nf) - ;; ns-prelude forms (always kept, no fqn/refs) set the - ;; ns + register aliases before this ns's forms; dce - ;; keeps original order. - (let ((src (ldr-read-source (cdr nf)))) - (parameterize ((rdr-source-file (cdr nf))) - (append - (map (lambda (s) (dce-rec #t #f '() s)) - (bld-ns-prelude (car nf) src)) - (ei-emit-ns-records (car nf) src))))) - ordered)) - (string-append entry-ns "/-main")) - (values #f - (apply append - (map (lambda (nf) - (let ((src (ldr-read-source (cdr nf)))) - (parameterize ((rdr-source-file (cdr nf))) - (append (bld-ns-prelude (car nf) src) - (bld-emit-ns (car nf) src))))) - ordered)) - #f)))) - (lambda () - (set-optimize! #f) - ((var-deref "jolt.backend-scheme" "set-direct-link!") #f))))) - (when drop-compiler? (display "jolt build: dropping compiler image (no runtime eval)\n")) - (let* ((builddir (string-append out-path ".build")) - (flat-ss (string-append builddir "/flat.ss")) - (flat-so (string-append builddir "/flat.so")) - (boot (string-append builddir "/jolt.boot")) - (boot-h (string-append builddir "/boot_data.h")) - (main-c (string-append builddir "/main.c"))) - (bld-mkdir-p builddir) - ;; 3. flat source = runtime + app + launcher. - (let ((out (open-output-file flat-ss 'replace))) - (bld-emit-runtime out drop-compiler? core-strs) - ;; Load native libs, bake embedded resources, and point source roots at - ;; the build-time app roots — all BEFORE the app forms. The app's - ;; top-level forms run at binary startup (Sbuild_heap), and they include - ;; foreign-procedure evals (a library's defcfn) and (slurp (io/resource …)) - ;; reads. So the libraries must be loaded and resources resolvable by the - ;; time those forms run, not later in the scheme-start launcher. - (put-string out "\n;; === native libraries (required) ===\n") - (bld-emit-natives out natives 'required) - (put-string out "\n;; === embedded resources ===\n") - (bld-emit-embeds out embed-dirs) - (put-string out (string-append - "(set-source-roots! (list " - (fold-left (lambda (s r) (string-append s (ei-str-lit r) " ")) "" - (get-source-roots)) - "))\n")) - (put-string out "\n;; === app ===\n") - (for-each (lambda (s) (put-string out s) (put-string out "\n")) app-strs) - ;; The launcher runs as Chez's scheme-start (so argv reaches -main — - ;; top-level boot forms run during heap build, before args are set), and - ;; suppresses the interactive greeting. It resets source roots to the - ;; app's resource dirs resolved against JOLT_PWD (or cwd) so a runtime - ;; io/resource that wasn't embedded still resolves next to the binary. - (put-string out "\n;; === launcher ===\n") - (put-string out "(suppress-greeting #t)\n") - (put-string out "(scheme-start\n (lambda args\n") - (bld-emit-natives out natives 'optional) - (put-string out (string-append - " (let ((base (or (getenv \"JOLT_PWD\") \".\")))\n" - " (set-source-roots!\n" - " (append (map (lambda (r) (string-append base \"/\" r)) (list " - (fold-left (lambda (s r) (string-append s (ei-str-lit r) " ")) "" (bld-strs ext-roots)) - "))\n" - " (list \"jolt-core\" \"stdlib\"))))\n")) - (put-string out (string-append - ;; Call -main only if the entry namespace defines one; - ;; a script ns (top-level side effects, no -main) has - ;; already run its forms at heap build, so invoking a nil - ;; -main would crash ("nil cannot be cast to IFn") — just - ;; exit cleanly instead. - " (let ((maincell (var-cell-lookup " (ei-str-lit entry-ns) " \"-main\")))\n" - ;; render an uncaught throw (+ Clojure backtrace) instead - ;; of Chez's opaque dump, then exit non-zero. - " (guard (v (#t (jolt-report-throwable v (current-error-port)) (exit 1)))\n" - ;; Loading the app left the current ns at the entry ns; reset - ;; it to `user` before -main, matching clojure.main (*ns* is - ;; `user` when a `-m` -main runs, so a runtime resolve of an - ;; aliased symbol behaves the same as on the JVM / interpreted - ;; joltc, not off the entry ns's alias table). - " (set-chez-ns! \"user\")\n" - " (when (and maincell (var-cell-defined? maincell))\n" - " (apply jolt-invoke (var-cell-root maincell) args))))\n" - " (exit 0)))\n")) - (close-port out)) - ;; 4. compile -> boot -> link. Two paths, chosen by whether this process - ;; carries the bundled Chez boots + launcher stub: - ;; - SELF-CONTAINED (the distributed joltc, jolt-eaj): compile-file + - ;; make-boot-file run IN PROCESS (the compiler is resident — joltc is - ;; built from scheme.boot), then the boot is appended to a copy of the - ;; embedded stub. No external Chez, no cc. - ;; - LEGACY (dev bin/joltc): spawn a fresh Chez for compile-file/ - ;; make-boot-file, then xxd the boot into a C array and cc-link against - ;; libkernel.a. Kept so `make buildsmoke` still exercises the cc path. - (if (jolt-embedded-bytes "stub/launcher") - (build-self-contained entry-ns out-path mode builddir flat-ss flat-so boot - (bld-native-link-flags natives)) - (build-with-cc entry-ns out-path mode builddir flat-ss flat-so boot boot-h main-c - (bld-native-link-flags natives))))))))) - -;; --- self-contained link (in-process compile + append the boot to the stub) --- -;; compile-file runs against the DEFAULT interaction environment, so the boot's -;; top-level defines land in the real symbol cells — the runtime compiler's -;; eval'd code must resolve them (var-deref, jolt-invoke, the jolt-n* macros) -;; when the built binary dynamically requires a namespace. Compiling in a clean -;; copy-environment instead orphans every define in locations eval can't see, -;; and the binary dies with "variable var-deref is not bound" the moment a -;; runtime require compiles source. -;; -;; The default env has a wrinkle the legacy fresh-Chez path doesn't: THIS -;; process's cells hold jolt's redefinitions of some kernel names (`error`, -;; regex.ss), so references to them compile as cell reads — and a read that -;; runs before the redefining form would find the fresh binary's cell unbound. -;; The prologue closes that: it first binds each redefined kernel name's cell -;; to its kernel value, making the boot's earliest reads identical to the -;; legacy path's primitive references. - -;; every top-level (define nm …)/(define (nm …) …) name in the flat file that -;; shadows a scheme-environment VARIABLE (syntax names don't eval; skip them). -(define (bld-kernel-prologue flat-ss) - (let ((seen (make-eq-hashtable)) - (kenv (scheme-environment)) - (names '())) - (let ((ip (open-input-file flat-ss))) - (let loop () - (let ((f (read ip))) - (unless (eof-object? f) - (when (and (pair? f) (eq? (car f) 'define) (pair? (cdr f))) - (let* ((h (cadr f)) - (nm (if (pair? h) (car h) h))) - (when (and (symbol? nm) - (not (hashtable-ref seen nm #f)) - (guard (e (#t #f)) (begin (eval nm kenv) #t))) - (hashtable-set! seen nm #t) - (set! names (cons nm names))))) - (loop)))) - (close-port ip)) - (apply string-append - (map (lambda (nm) - (let ((s (symbol->string nm))) - (string-append "(define " s " (eval '" s " (scheme-environment)))\n"))) - (reverse names))))) - -;; prepend the prologue to the flat file in place. -(define (bld-prepend-prologue! flat-ss) - (let ((prologue (bld-kernel-prologue flat-ss)) - (body (read-file-string flat-ss))) - (let ((out (open-output-file flat-ss 'replace))) - (put-string out ";; kernel-name cells pre-bound so early reads match the kernel primitives\n") - (put-string out prologue) - (put-string out body) - (close-port out)))) - -(define (build-self-contained entry-ns out-path mode builddir flat-ss flat-so boot native-link) - (let ((petite (string-append builddir "/petite.boot")) - (scheme (string-append builddir "/scheme.boot"))) - (jolt-spill-embedded! "csv/petite.boot" petite) - (jolt-spill-embedded! "csv/scheme.boot" scheme) - (display (string-append "jolt build: compiling " entry-ns " (" mode " mode, self-contained)\n")) - (bld-prepend-prologue! flat-ss) - (compile-file flat-ss flat-so) - (make-boot-file boot '() petite scheme flat-so) - ;; The stub is the native launcher the boot is appended to. With no :static - ;; natives it's the prebuilt one bundled in joltc (no cc needed); with :static - ;; natives it's re-linked here from the bundled kernel + launcher source so the - ;; archives are baked in and their symbols resolve in the running binary. - (if (> (string-length native-link) 0) - (bld-relink-stub builddir native-link out-path) - (jolt-spill-embedded! "stub/launcher" out-path)) - ;; link: stub bytes ++ boot ++ frame, then make it executable. - (jolt-append-payload! out-path (read-file-bytes boot)) - (jolt-chmod-755 out-path) - (display (string-append "jolt build: wrote " out-path "\n")) - (when bld-osx? - (display (string-append - "jolt build: note — on macOS this binary is unsigned; to share it,\n" - " `xattr -d com.apple.quarantine " out-path "` on the target, or sign it.\n"))))) - -;; Re-link the launcher stub with the app's static native archives baked in, to -;; OUT-PATH. The self-contained joltc bundles the Chez kernel (libkernel.a), -;; header, and launcher source; spill them and drive the system cc — the same link -;; build-joltc.ss ran once at joltc-build time, plus the force-load archive flags -;; (native-link) and, on Linux, -rdynamic so the baked-in symbols stay dlsym- -;; visible for (load-shared-object #f) + foreign-procedure at startup. -(define (bld-relink-stub builddir native-link out-path) - (let ((h (string-append builddir "/scheme.h")) - (lk (string-append builddir "/libkernel.a")) - (lc (string-append builddir "/launcher.c"))) - (jolt-spill-embedded! "csv/scheme.h" h) - (jolt-spill-embedded! "csv/libkernel.a" lk) - (jolt-spill-embedded! "stub/launcher.c" lc) - (display "jolt build: relinking launcher stub with static native libraries\n") - (bld-system (string-append - "cc -O2 " (if bld-osx? "" "-rdynamic ") - "-I'" builddir "' '" lc "' '" lk "' -o '" out-path "' " - (bld-link-libs) native-link)))) - -;; --- legacy cc link (dev bin/joltc): fresh Chez compile + xxd + cc ------------ -(define (build-with-cc entry-ns out-path mode builddir flat-ss flat-so boot boot-h main-c native-link) - (display (string-append "jolt build: compiling " entry-ns " (" mode " mode)\n")) - (let ((cs (string-append builddir "/compile.ss"))) - (let ((p (open-output-file cs 'replace))) - (put-string p - (string-append - "(import (chezscheme))\n" - "(compile-file " (ei-str-lit flat-ss) " " (ei-str-lit flat-so) ")\n" - "(make-boot-file " (ei-str-lit boot) " '()\n " - (ei-str-lit (string-append bld-csv-dir "/petite.boot")) "\n " - (ei-str-lit (string-append bld-csv-dir "/scheme.boot")) "\n " - (ei-str-lit flat-so) ")\n")) - (close-port p)) - (bld-system (string-append bld-chez " --script '" cs "'"))) - (bld-system (string-append "xxd -i '" boot "' > '" boot-h "'")) - ;; The xxd symbol is derived from the path; normalize to jolt_boot. - (bld-system (string-append - "sed -i.bak -E 's/unsigned char [A-Za-z0-9_]+\\[\\]/unsigned char jolt_boot[]/; " - "s/unsigned int [A-Za-z0-9_]+_len/unsigned int jolt_boot_len/' '" boot-h "'")) - (let ((mc (open-output-file main-c 'replace))) - (put-string mc - (string-append - "#include \"scheme.h\"\n#include \"boot_data.h\"\n" - "int main(int argc, char *argv[]) {\n" - " Sscheme_init(0);\n" - " Sregister_boot_file_bytes(\"jolt\", jolt_boot, jolt_boot_len);\n" - " Sbuild_heap(0, 0);\n" - " int status = Sscheme_start(argc, (const char **)argv);\n" - " Sscheme_deinit();\n return status;\n}\n")) - (close-port mc)) - ;; -rdynamic (Linux) exports the executable's symbols into the dynamic table so - ;; a statically-linked native lib's symbols resolve via (load-shared-object #f) - ;; at startup. macOS keeps unstripped executable symbols dlsym-visible already. - (bld-system (string-append - "cc -O2 " (if (and (not bld-osx?) (> (string-length native-link) 0)) "-rdynamic " "") - "-I'" bld-csv-dir "' '" main-c "' '" bld-csv-dir "/libkernel.a' " - "-o '" out-path "' " (bld-link-libs) native-link)) - (display (string-append "jolt build: wrote " out-path "\n"))) - -(def-var! "jolt.host" "build-binary" - (lambda (entry out mode natives embed-dirs ext-roots direct-link? tree-shake?) - (build-binary (jolt-str-render-one entry) - (jolt-str-render-one out) - (jolt-str-render-one mode) - natives embed-dirs ext-roots (jolt-truthy? direct-link?) (jolt-truthy? tree-shake?)) - jolt-nil)) diff --git a/host/chez/cli.ss b/host/chez/cli.ss deleted file mode 100644 index 7d978af..0000000 --- a/host/chez/cli.ss +++ /dev/null @@ -1,90 +0,0 @@ -;; cli.ss — the jolt runtime. -;; -;; Loads the checked-in seed (host/chez/seed/{prelude,image}.ss — the bootstrap -;; compiler) and the spine, then either evaluates a -e expression or dispatches a -;; CLI command (run/-M/repl/path/task) through jolt.main. The loader -;; (loader.ss) turns `require` into real file loading off the source roots, so a -;; multi-file project with deps.edn dependencies runs end to end. -;; -;; Run from the repo root (bin/joltc cd's there); the project dir is JOLT_PWD. -(import (chezscheme)) - -(define cli-args (cdr (command-line))) ; drop the script name - -;; Fail early and actionably when the vendored submodules aren't checked out — -;; a plain `git clone` or GitHub's auto-generated "Source code" release archive -;; lacks them, and the raw failure ("load failed for vendor/irregex/irregex.scm") -;; doesn't say how to fix it. (The self-contained joltc binary embeds these and -;; never runs this file.) -(unless (file-exists? "vendor/irregex/irregex.scm") - (display "jolt: vendor submodules are missing (vendor/irregex). -" (current-error-port)) - (display "GitHub's 'Source code' release archives don't include submodules. -" (current-error-port)) - (display "Clone the repo instead: -" (current-error-port)) - (display " git clone --recurse-submodules https://github.com/jolt-lang/jolt.git -" (current-error-port)) - (display "or, in an existing checkout: -" (current-error-port)) - (display " git submodule update --init --recursive -" (current-error-port)) - (exit 1)) - -(load "host/chez/rt.ss") -(set-chez-ns! "clojure.core") -(load "host/chez/seed/prelude.ss") -(load "host/chez/post-prelude.ss") -(set-chez-ns! "user") -(load "host/chez/host-contract.ss") -(load "host/chez/seed/image.ss") -(load "host/chez/compile-eval.ss") -(load "host/chez/png.ss") ; jolt.png — a baked namespace before the snapshot -(load "host/chez/loader.ss") -;; jolt.ffi host primitives (memory / library loading) load AFTER the loader's -;; baked-ns snapshot, so a library's (require '[jolt.ffi]) still loads jolt.ffi's -;; Clojure side (the foreign-fn / defcfn macros, stdlib/jolt/ffi.clj). -(load "host/chez/java/ffi.ss") ; jolt.ffi (FFI: a library binds native code) - -;; jolt.main + jolt.deps live under jolt-core; keep them (and stdlib) on the -;; roots so the CLI's own namespaces — and any jolt.* an app pulls in — resolve. -;; A project's resolved deps roots are prepended to these by jolt.main. -(set-source-roots! (list "jolt-core" "stdlib")) - -;; Render an uncaught jolt throw (any value, not just a Chez condition) to stderr -;; and exit non-zero, instead of Chez's opaque "non-condition value" dump. The -;; message/ex-data/cause + a mapped Clojure backtrace come from the shared -;; renderer (source-registry.ss); the cli adds the top-level source location. -(define (jolt-report-uncaught raw) - (let ((v (jolt-unwrap-throw raw)) - (port (current-error-port))) - (jolt-render-throwable v port) - ;; The top-level form that was evaluating when this propagated (file:line:col). - (let ((loc (jolt-current-source-string))) - (when loc (display " at " port) (display loc port) (newline port))) - (let ((bt (jolt-backtrace-string v))) - (when bt (display " trace:\n" port) (display bt port))) - (exit 1))) - -;; JOLT_TRACE opt-in, at runtime (before any app ns compiles) so the app is traced. -(jolt-trace-init-from-env!) - -(guard (v (#t (jolt-report-uncaught v))) - (cond - ;; -e EXPR — evaluate one expression and print it (blank for nil). Wrapped in - ;; (do …) so a multi-form string evaluates every form and returns the last. - ((and (= (length cli-args) 2) (string=? (car cli-args) "-e")) - (let ((result (jolt-final-str - (jolt-compile-eval (string-append "(do " (cadr cli-args) ")") "user")))) - (unless (string=? result "") - (display result) (newline)))) - ;; otherwise dispatch the argv through jolt.main/-main - (else - ;; `build` AOT-compiles an app to a standalone binary — load the build - ;; driver (the cross-compiler emitter) on demand so a normal run never pays - ;; for it. It defines jolt.host/build-binary, which jolt.main's build cmd calls. - (when (and (pair? cli-args) (string=? (car cli-args) "build")) - (load "host/chez/build.ss")) - (load-namespace "jolt.main") - (let ((mainv (var-deref "jolt.main" "-main"))) - (apply jolt-invoke mainv cli-args))))) diff --git a/host/chez/collections.ss b/host/chez/collections.ss deleted file mode 100644 index d2ae770..0000000 --- a/host/chez/collections.ss +++ /dev/null @@ -1,606 +0,0 @@ -;; persistent collections on the Chez RT. -;; -;; The vector / map / set the emitted programs construct from literals and -;; operate on via the lowered leaf ops (conj/get/nth/count/assoc/...). Loaded by -;; rt.ss after values.ss; jolt=2 / jolt-hash (values.ss) call into the -;; jolt-coll? / jolt-coll=? / jolt-coll-hash hooks defined here (forward refs, -;; resolved at run time — nothing is CALLED during load). -;; -;; The persistent vector is a copy-on-write Scheme vector and the map/set are a -;; bitmap HAMT. They live in Scheme; correctness, not perf, is the gate. - -;; ============================================================================ -;; small immutable-vector helpers (manual; avoid stdlib arg-order ambiguity) -;; ============================================================================ -(define (vec-copy-range v start end) - (let ((out (make-vector (fx- end start)))) - (let loop ((i start)) - (when (fx=? i (pv-tailoff (pvec-cnt p))) - (pvec-tail p) - (let loop ((node (pvec-root p)) (level (pvec-shift p))) - (if (fx>? level 0) - (loop (vector-ref node (fxand (fxsra i level) pv-mask)) (fx- level pv-bits)) - node)))) - -;; jolt models every number as a double, so vector indices arrive as flonums — -;; coerce an integer-valued index to a Scheme fixnum before bounds math. -(define (->idx i) (if (fixnum? i) i (if (flonum? i) (exact (floor i)) i))) -(define (pvec-count p) (pvec-cnt p)) -(define (pvec-nth-d p i d) - (let ((i (->idx i))) - (if (and (fixnum? i) (fx>=? i 0) (fx? (fxsra cnt pv-bits) (fxsll 1 shift)) - ;; root overflow: grow the trie a level - (mk-pvec (fx+ cnt 1) (fx+ shift pv-bits) - (vector (pvec-root p) (pv-new-path shift tail-node)) - (vector x) #f) - (mk-pvec (fx+ cnt 1) shift - (pv-push-tail cnt shift (pvec-root p) tail-node) - (vector x) #f)))))) - -(define (pv-assoc-trie level node i x) - (if (fx=? level 0) - (vec-set node (fxand i pv-mask) x) - (let ((subidx (fxand (fxsra i level) pv-mask))) - (vec-set node subidx (pv-assoc-trie (fx- level pv-bits) (vector-ref node subidx) i x))))) -(define (pvec-assoc p i x) ; i in [0,count]; =count appends - (let ((i (->idx i)) (cnt (pvec-cnt p))) - (cond - ((fx=? i cnt) (pvec-conj p x)) - ((and (fx>=? i 0) (fx=? i (pv-tailoff cnt)) - (mk-pvec cnt (pvec-shift p) (pvec-root p) - (vec-set (pvec-tail p) (fxand i pv-mask) x) #f) - (mk-pvec cnt (pvec-shift p) - (pv-assoc-trie (pvec-shift p) (pvec-root p) i x) (pvec-tail p) #f))) - (else (jolt-throw (jolt-host-throwable "java.lang.IndexOutOfBoundsException" "vector index out of bounds")))))) -(define (pvec-peek p) - (let ((n (pvec-cnt p))) (if (fx=? n 0) jolt-nil (pvec-nth-d p (fx- n 1) jolt-nil)))) -;; pop the last trie chunk back into the tail; #f means the subtree emptied. -(define (pv-pop-tail cnt level node) - (let ((subidx (fxand (fxsra (fx- cnt 2) level) pv-mask))) - (cond - ((fx>? level pv-bits) - (let ((newchild (pv-pop-tail cnt (fx- level pv-bits) (vector-ref node subidx)))) - (cond ((and (not newchild) (fx=? subidx 0)) #f) - (newchild (vec-set node subidx newchild)) - (else (vec-take node subidx))))) - ((fx=? subidx 0) #f) - (else (vec-take node subidx))))) -(define (pvec-pop p) - (let ((cnt (pvec-cnt p)) (shift (pvec-shift p))) - (cond - ((fx=? cnt 0) (error 'pop "can't pop empty vector")) - ((fx=? cnt 1) empty-pvec) - ((fx>? (fx- cnt (pv-tailoff cnt)) 1) - (mk-pvec (fx- cnt 1) shift (pvec-root p) (vec-drop-last (pvec-tail p)) #f)) - (else - (let* ((new-tail (pv-chunk-for p (fx- cnt 2))) - (popped (pv-pop-tail cnt shift (pvec-root p))) - (new-root (or popped pv-empty-node))) - (if (and (fx>? shift pv-bits) (fxvector xs))) -(define (make-map-entry k v) (make-pvec (vector k v) #t)) -(define (jolt-map-entry? x) (and (pvec? x) (pvec-ent x) #t)) - -;; ============================================================================ -;; bitmap HAMT — keys hashed by jolt-hash, leaves compared by jolt= -;; arr slot is one of: leaf (cons k v) | hnode (branch) | hcoll (hash bucket) -;; ============================================================================ -(define-record-type hnode (fields bm arr) (nongenerative chez-hnode-v1)) -(define-record-type hcoll (fields hash alist) (nongenerative chez-hcoll-v1)) -(define empty-hnode (make-hnode 0 (vector))) -(define hmask #x3FFFFFFFFFFFFFF) ; 58-bit non-negative hash window -(define max-shift 55) -;; bitwise-and (not fxand): jolt-hash is set!-decorated per type (records/inst/ -;; sorted return their own hash) and Chez's equal-hash can yield a BIGNUM, so a -;; key's hash isn't guaranteed to be a fixnum. Masking with the 58-bit window via -;; the generic bitwise-and always lands in fixnum range for the HAMT's fx slicing. -(define (key-hash k) (bitwise-and (jolt-hash k) hmask)) -(define (chunk h shift) (fxand (fxsra h shift) 31)) -(define (bitpos h shift) (fxsll 1 (chunk h shift))) -(define (popcount n) (let loop ((n n) (c 0)) (if (fx=? n 0) c (loop (fxand n (fx- n 1)) (fx+ c 1))))) -(define (arr-index bm bit) (popcount (fxand bm (fx- bit 1)))) - -;; jolt= alist ops (for hash-collision buckets) -(define (assoc-jolt k al) (cond ((null? al) #f) ((jolt= (caar al) k) (car al)) (else (assoc-jolt k (cdr al))))) -(define (alist-replace k v al) (if (jolt= (caar al) k) (cons (cons k v) (cdr al)) (cons (car al) (alist-replace k v (cdr al))))) -(define (alist-remove k al) (cond ((null? al) '()) ((jolt= (caar al) k) (cdr al)) (else (cons (car al) (alist-remove k (cdr al)))))) - -;; split two leaves that collided at `shift` into a subtree (or hcoll if the -;; full hashes are equal / the hash is exhausted). -(define (split-leaf shift ek ev h k v) - (let ((eh (key-hash ek))) - (if (or (fx>? shift max-shift) (fx=? eh h)) - (make-hcoll h (list (cons ek ev) (cons k v))) - (let ((ei (chunk eh shift)) (ni (chunk h shift))) - (if (fx=? ei ni) - (make-hnode (fxsll 1 ei) (vector (split-leaf (fx+ shift 5) ek ev h k v))) - (let ((eb (fxsll 1 ei)) (nb (fxsll 1 ni))) - (if (fx= 16 in the reference). Clojure 1.13 -;; raised the limit to 64 for maps whose keys are ALL keywords (the common -;; keyword-map case); mixed-key maps still cap at 8. -(define array-map-limit 8) -(define array-map-limit-kw 64) -(define (all-keywords? ks) - (or (null? ks) (and (keyword? (car ks)) (all-keywords? (cdr ks))))) -;; Should a map of `cnt` entries with insertion order `ord` stay in array mode -;; when key `k` is added? Under 8 always; a keyword-only map (existing keys + the -;; new key all keywords) grows to 64; otherwise it caps at 8. -(define (pmap-array-keep? cnt ord k) - (cond ((fx=? cnt array-map-limit-kw) #f) - ((and (keyword? k) (all-keywords? ord)) #t) - (else #f))) -(define (append-key ord k) (append ord (list k))) -(define (remove-key ord k) (let loop ((o ord)) (cond ((null? o) '()) ((jolt= (car o) k) (cdr o)) (else (cons (car o) (loop (cdr o))))))) - -;; growth rule (PersistentArrayMap.assoc): a new key appends to the order while in -;; array mode under the limit; otherwise the result is hash-ordered. Replacing an -;; existing key (or assoc onto an already-hash map) keeps the current order. -(define (pmap-assoc m k v) - (let* ((added (box #f)) (r (node-assoc (pmap-root m) 0 (key-hash k) k v added)) - (cnt (pmap-cnt m)) (ord (pmap-order m))) - (if (unbox added) - (if (and ord (pmap-array-keep? cnt ord k)) - (make-pmap r (fx+ cnt 1) (append-key ord k)) - (make-pmap r (fx+ cnt 1) #f)) - (make-pmap r cnt ord)))) -;; force-ordered / force-hash inserts for rebuilding a map whose final mode is -;; already decided (array-map ctor, transient persistent!). -(define (pmap-put-ordered m k v) - (let* ((added (box #f)) (r (node-assoc (pmap-root m) 0 (key-hash k) k v added))) - (if (unbox added) - (make-pmap r (fx+ (pmap-cnt m) 1) (append-key (or (pmap-order m) '()) k)) - (make-pmap r (pmap-cnt m) (pmap-order m))))) -(define (pmap-put-hash m k v) - (let* ((added (box #f)) (r (node-assoc (pmap-root m) 0 (key-hash k) k v added))) - (make-pmap r (if (unbox added) (fx+ (pmap-cnt m) 1) (pmap-cnt m)) #f))) -(define (pmap->hash m) (if (pmap-order m) (make-pmap (pmap-root m) (pmap-cnt m) #f) m)) -(define (pmap-dissoc m k) - (let* ((removed (box #f)) (r (node-dissoc (pmap-root m) 0 (key-hash k) k removed)) - (ord (pmap-order m))) - (if (unbox removed) - (make-pmap r (fx- (pmap-cnt m) 1) (if ord (remove-key ord k) #f)) - m))) -(define (pmap-get m k default) (node-get (pmap-root m) 0 (key-hash k) k default)) -(define (pmap-contains? m k) (not (eq? pmap-absent (node-get (pmap-root m) 0 (key-hash k) k pmap-absent)))) -;; The universal fold idiom across the runtime is `(pmap-fold m (lambda (k v a) -;; (cons ... a)) '())`, which accumulates in REVERSE visitation order. So that this -;; reconstructs the map's INSERTION order, pmap-fold visits an array-mode map's keys -;; in reverse insertion order; a hash-mode map visits HAMT order (its iteration -;; order is unspecified, so reverse-of-HAMT is equivalent and matches prior -;; behaviour). Use pmap-fold-fwd when building a value directly in iteration order. -(define (pmap-fold m proc acc) - (let ((ord (pmap-order m))) - (if ord - (fold-right (lambda (k a) (proc k (pmap-get m k jolt-nil) a)) acc ord) ; visits last->first - (node-fold (pmap-root m) proc acc)))) -;; visit entries in iteration (insertion) order — for code that builds a new map / -;; ordered value directly rather than via cons-accumulation. -(define (pmap-fold-fwd m proc acc) - (let ((ord (pmap-order m))) - (if ord - (let loop ((ks ord) (a acc)) - (if (null? ks) a (loop (cdr ks) (proc (car ks) (pmap-get m (car ks) jolt-nil) a)))) - (node-fold (pmap-root m) proc acc)))) -;; map LITERAL ({...}): array map up to 8 entries (64 if keyword-only, per 1.13), -;; hash map beyond (RT.map). -(define (jolt-hash-map . kvs) - (let loop ((m empty-pmap) (kvs kvs)) - (cond ((null? kvs) - (let ((cnt (pmap-cnt m)) (ord (pmap-order m))) - (if (fx>? cnt (if (all-keywords? ord) array-map-limit-kw array-map-limit)) - (pmap->hash m) m))) - ((null? (cdr kvs)) (error 'hash-map "odd number of map literal entries")) - (else (loop (pmap-put-ordered m (car kvs) (cadr kvs)) (cddr kvs)))))) -;; array-map ctor: insertion-ordered regardless of size (createAsIfByAssoc). -(define (jolt-array-map-build kvs) - (let loop ((m empty-pmap) (kvs kvs)) - (cond ((null? kvs) m) - ((null? (cdr kvs)) (error 'array-map "odd number of map entries")) - (else (loop (pmap-put-ordered m (car kvs) (cadr kvs)) (cddr kvs)))))) -;; hash-map ctor: hash order (PersistentHashMap). -(define (jolt-hash-map-build kvs) - (let loop ((m empty-pmap-hash) (kvs kvs)) - (cond ((null? kvs) m) - ((null? (cdr kvs)) (error 'hash-map "odd number of map entries")) - (else (loop (pmap-put-hash m (car kvs) (cadr kvs)) (cddr kvs)))))) - -(define-record-type pset (fields m) (nongenerative chez-pset-v1)) -(define empty-pset (make-pset empty-pmap-hash)) ; sets are hash-ordered -(define (pset-conj s e) (if (pmap-contains? (pset-m s) e) s (make-pset (pmap-assoc (pset-m s) e e)))) -(define (pset-disj s e) (make-pset (pmap-dissoc (pset-m s) e))) -(define (pset-contains? s e) (pmap-contains? (pset-m s) e)) -(define (pset-count s) (pmap-cnt (pset-m s))) -(define (pset-fold s proc acc) (pmap-fold (pset-m s) (lambda (k v a) (proc k a)) acc)) -(define (jolt-hash-set . xs) (let loop ((s empty-pset) (xs xs)) (if (null? xs) s (loop (pset-conj s (car xs)) (cdr xs))))) - -;; ============================================================================ -;; leaf ops the emitter lowers core/clojure fns to (mirrors native-ops) -;; ============================================================================ -(define (jolt-conj1 coll x) - (cond ((pvec? coll) (pvec-conj coll x)) ; nil is a valid vector/set element - ((pset? coll) (pset-conj coll x)) - ;; a list/seq conjs by PREPENDING (seq.ss: cseq / empty-list). conj onto a - ;; list stays a list, conj onto a lazy/realized seq yields a seq cell (a - ;; Cons) — list?-preserving. - ((cseq? coll) (if (cseq-list? coll) (cseq-list x coll) (cseq-realized x coll))) - ((empty-list-t? coll) (cseq-list x jolt-nil)) - ((pmap? coll) - (cond ((jolt-nil? x) coll) ; (conj m nil) = m - ((pmap? x) (pmap-fold-fwd x (lambda (k v m) (pmap-assoc m k v)) coll)) ; merge in x's order - ((and (pvec? x) (fx=? 2 (pvec-count x))) - (pmap-assoc coll (pvec-nth-d x 0 jolt-nil) (pvec-nth-d x 1 jolt-nil))) - (else (error 'conj "conj on a map expects a [k v] pair or a map")))) - ((rec-coll-method coll "cons") => (lambda (m) (jolt-invoke m coll x))) - (else (error 'conj "unsupported collection")))) -;; (conj) -> []; (conj nil a b ...) builds a list (conj prepending -> (b a)). -(define (jolt-conj . args) - (if (null? args) - (jolt-vector) - (let ((coll (car args)) (xs (cdr args))) - (cond - ;; 1-arity returns the coll untouched — (conj nil) is nil - ((null? xs) coll) - ((jolt-nil? coll) (fold-left jolt-conj1 jolt-empty-list xs)) - (else (meta-carry coll (fold-left jolt-conj1 coll xs))))))) - -;; A host shim registers a type's get via register-get-arm! (handler: (coll k d) -> -;; value) instead of set!-wrapping jolt-get — disjoint coll types, checked before the -;; base map/set/vec/string cases (cf. register-hash-arm!). -(define jolt-get-arms '()) -(define (register-get-arm! pred handler) - (set! jolt-get-arms (cons (cons pred handler) jolt-get-arms))) -(define (jolt-get-base coll k d) - (cond ((pmap? coll) (pmap-get coll k d)) - ((pset? coll) (if (pset-contains? coll k) k d)) - ((pvec? coll) (pvec-nth-d coll k d)) - ((string? coll) (let ((i (->idx k))) - (if (and (fixnum? i) (fx>=? i 0) (fxidx i))) - (cond ((jolt-nil? coll) jolt-nil) ; RT.nth(nil, i) is nil at any index - ((pvec? coll) (let ((v (pvec-v coll))) - (if (and (fx>=? i 0) (fx=? i 0) (fx (lambda (m) (jolt-invoke m coll i))) - (else (error 'nth "unsupported collection"))))) - ((coll i d) - (jolt-nth-nil-idx! i) - (let ((i (->idx i))) - (cond ((jolt-nil? coll) d) ; RT.nth(nil, i, notFound) is notFound - ((pvec? coll) (pvec-nth-d coll i d)) - ((string? coll) (if (and (fx>=? i 0) (fx (lambda (m) (jolt-invoke m coll i d))) - (else d)))))) - -;; a count is an exact integer (JVM parity: count returns a long). jolt= is -;; exactness-aware, so this must be exact to match an exact integer literal: -;; (= 2 (count m)) -> 2 vs exact 2 -> true. -(define (jolt-count coll) - (begin - (cond ((pvec? coll) (pvec-count coll)) - ((pmap? coll) (pmap-cnt coll)) - ((pset? coll) (pset-count coll)) - ((string? coll) (string-length coll)) - ((jolt-nil? coll) 0) - ((empty-list-t? coll) 0) - ((cseq? coll) (let loop ((s coll) (n 0)) ; walk (forces a finite seq) - (if (jolt-nil? s) n (loop (jolt-seq (seq-more s)) (fx+ n 1))))) - ((rec-coll-method coll "count") => (lambda (m) (jolt-invoke m coll))) - (else (error 'count "uncountable"))))) - -(define (jolt-assoc1 coll k v) - (cond ((pmap? coll) (pmap-assoc coll k v)) - ((pvec? coll) (pvec-assoc coll k v)) - ((jolt-nil? coll) (pmap-assoc empty-pmap k v)) - ((rec-coll-method coll "assoc") => (lambda (m) (jolt-invoke m coll k v))) - (else (error 'assoc "unsupported collection")))) -(define (jolt-assoc coll . kvs) - (meta-carry coll - (let loop ((coll coll) (kvs kvs)) - (cond ((null? kvs) coll) - ((null? (cdr kvs)) (error 'assoc "assoc expects an even number of key/vals")) - (else (loop (jolt-assoc1 coll (car kvs) (cadr kvs)) (cddr kvs))))))) - -(define (jolt-dissoc coll . ks) - (cond ((jolt-nil? coll) jolt-nil) - ((pmap? coll) (meta-carry coll (fold-left pmap-dissoc coll ks))) - (else (error 'dissoc "unsupported collection")))) - -(define (jolt-contains? coll k) - (cond ((pmap? coll) (pmap-contains? coll k)) - ((pset? coll) (pset-contains? coll k)) - ((pvec? coll) (let ((k (->idx k))) (and (fixnum? k) (fx>=? k 0) (fx= k 0) (< k (string-length coll))) - (jolt-throw (jolt-host-throwable - "java.lang.IllegalArgumentException" - "contains? not supported on type: java.lang.String")))) - ((or (cseq? coll) (empty-list-t? coll) (number? coll) (boolean? coll) - (keyword? coll) (jolt-symbol? coll) (char? coll)) - (jolt-throw (jolt-host-throwable - "java.lang.IllegalArgumentException" - (string-append "contains? not supported on type: " - (guard (e (#t "?")) (jolt-class-name coll)))))) - (else #f))) - -(define (jolt-empty? coll) - (cond ((jolt-nil? coll) #t) - ((pvec? coll) (fx=? 0 (pvec-count coll))) - ((pmap? coll) (fx=? 0 (pmap-cnt coll))) - ((pset? coll) (fx=? 0 (pset-count coll))) - ((string? coll) (fx=? 0 (string-length coll))) - ((empty-list-t? coll) #t) - ((cseq? coll) #f) ; a cseq is non-empty by construction - (else (error 'empty? "unsupported collection")))) - -(define (jolt-stack-throw coll) - (jolt-throw (jolt-host-throwable - "java.lang.ClassCastException" - (string-append "class " (guard (e (#t "?")) (jolt-class-name coll)) - " cannot be cast to class clojure.lang.IPersistentStack")))) -(define (jolt-peek coll) - (cond ((pvec? coll) (pvec-peek coll)) - ;; list peek = first; a non-list seq (range, a rest chain) is not an - ;; IPersistentStack on the JVM - ((and (cseq? coll) (cseq-list? coll)) (jolt-first coll)) - ((empty-list-t? coll) (jolt-first coll)) - ((jolt-nil? coll) jolt-nil) - (else (jolt-stack-throw coll)))) -(define (jolt-pop coll) - (cond ((jolt-nil? coll) jolt-nil) ; RT.pop(nil) is nil - ((pvec? coll) (meta-carry coll (pvec-pop coll))) - ((and (cseq? coll) (cseq-list? coll)) (meta-carry coll (jolt-rest coll))) - ((empty-list-t? coll) (error 'pop "can't pop empty list")) - (else (jolt-stack-throw coll)))) - -;; ============================================================================ -;; equality / hash hooks called from values.ss (jolt=2 / jolt-hash) -;; ============================================================================ -(define (jolt-coll? x) (or (pvec? x) (pmap? x) (pset? x))) -(define (jolt-coll=? a b) - (cond - ((and (pvec? a) (pvec? b)) - (let ((va (pvec-v a)) (vb (pvec-v b))) - (and (fx=? (vector-length va) (vector-length vb)) - (let loop ((i 0)) - (or (fx=? i (vector-length va)) - (and (jolt= (vector-ref va i) (vector-ref vb i)) (loop (fx+ i 1)))))))) - ((and (pmap? a) (pmap? b)) - (and (fx=? (pmap-cnt a) (pmap-cnt b)) - (pmap-fold a (lambda (k v ok) (and ok (jolt= (pmap-get b k pmap-absent) v))) #t))) - ((and (pset? a) (pset? b)) - (and (fx=? (pset-count a) (pset-count b)) - (pset-fold a (lambda (e ok) (and ok (pset-contains? b e))) #t))) - (else #f))) -(define (jolt-coll-hash x) - (cond - ((pvec? x) - (let ((v (pvec-v x))) - (let loop ((i 0) (h 1)) - (if (fx=? i (vector-length v)) (bitwise-and h hmask) - (loop (fx+ i 1) (bitwise-and (+ (* 31 h) (key-hash (vector-ref v i))) hmask)))))) - ;; maps/sets hash order-independently (sum), consistent with unordered = - ((pmap? x) (bitwise-and (pmap-fold x (lambda (k v a) (+ a (fxxor (key-hash k) (key-hash v)))) 0) hmask)) - ((pset? x) (bitwise-and (pset-fold x (lambda (e a) (+ a (key-hash e))) 0) hmask)))) diff --git a/host/chez/compile-eval.ss b/host/chez/compile-eval.ss deleted file mode 100644 index 4c2da62..0000000 --- a/host/chez/compile-eval.ss +++ /dev/null @@ -1,297 +0,0 @@ -;; compile-eval.ss — the compile spine. -;; -;; Ties together the cross-compiled compiler image (jolt.ir + jolt.analyzer + -;; jolt.backend-scheme, loaded as def-var! forms) and the host contract -;; (host-contract.ss) into a runtime entry: a Clojure source string is read by the -;; Chez data reader, analyzed by the analyzer to IR, emitted to Scheme by the -;; emitter, and eval'd. This is the spine the stage2==stage3 bootstrap fixpoint -;; closes over. -;; -;; Loaded after host-contract.ss + the compiler image. - -(define jolt-ce-analyze (var-deref "jolt.analyzer" "analyze")) -(define jolt-ce-emit (var-deref "jolt.backend-scheme" "emit")) -;; jolt.passes/run-passes: const-fold every analyzed form, plus inline + type -;; inference when the unit opted into direct-linking (jolt build --opt). Off that -;; path it is a pure const-fold. Loaded from the compiler image (jolt.passes). -(define jolt-ce-run-passes (var-deref "jolt.passes" "run-passes")) -;; The compiler reads source as FORMS (set literals stay {:jolt/type :jolt/set}, -;; which the analyzer lowers) — the raw reader, not clojure.core/read-string, -;; whose data conversion would turn those into real sets. -(define jolt-ce-read jolt-read-form-raw) - -;; --- current source location ------------------------------------------------ -;; The position of the top-level form currently compiling/evaluating, so an -;; uncaught error can report where it came from (cli.ss jolt-report-uncaught). -;; Thread-local: a future/agent worker tracks its own form. Holds #f or a -;; {:line :column :file?} position map (jolt.host/form-position's shape). -;; Top-level granularity — one set per top-level form, nothing per call. -(define jolt-current-source (make-thread-parameter #f)) - -;; clojure.lang.Compiler/LINE and /COLUMN — derefable cells (Vars on the JVM) -;; holding the line/column of the form being compiled. Macros read @Compiler/LINE -;; as a fallback when &form carries no position (jolt's reader stamps :line on list -;; forms, so this is rarely hit). Updated per top-level form, like *current-source*. -(define compiler-line-cell (jolt-atom-new 0)) -(define compiler-column-cell (jolt-atom-new 0)) -;; clojure.lang.Compiler/specials — the JVM's special-form table (sym -> parser). -;; tools.macro reads (keys Compiler/specials) to know which heads NOT to expand. -;; Only the keys matter here; values are #t. The set matches Clojure 1.2/1.3. -(define compiler-specials - (let ((unq '("def" "loop*" "recur" "if" "case*" "let*" "letfn*" "do" "fn*" - "quote" "var" "." "set!" "try" "monitor-enter" "monitor-exit" - "throw" "new" "&" "catch" "finally" "reify*" "deftype*"))) - (fold-left (lambda (m s) (jolt-assoc1 m (jolt-symbol #f s) #t)) - (jolt-assoc1 (jolt-hash-map) (jolt-symbol "clojure.core" "import*") #t) - unq))) -;; clojure.lang.Compiler/demunge — reverse the name munging Clojure applies to -;; build JVM class/method names, so "clojure.core$odd_QMARK_" -> clojure.core/odd?. -;; clojure.spec.alpha's fn-sym uses it to recover a symbol from a fn's class name. -;; Longest tokens first; a standalone _ is a hyphen; $ separates ns from name. -(define demunge-token-map - '(("_DOUBLEQUOTE_" . "\"") ("_SINGLEQUOTE_" . "'") ("_AMPERSAND_" . "&") ("_PERCENT_" . "%") - ("_LBRACE_" . "{") ("_RBRACE_" . "}") ("_LBRACK_" . "[") ("_RBRACK_" . "]") - ("_BSLASH_" . "\\") ("_TILDE_" . "~") ("_CIRCA_" . "@") ("_SHARP_" . "#") ("_BANG_" . "!") - ("_CARET_" . "^") ("_COLON_" . ":") ("_QMARK_" . "?") ("_SLASH_" . "/") ("_PLUS_" . "+") - ("_STAR_" . "*") ("_BAR_" . "|") ("_GT_" . ">") ("_LT_" . "<") ("_EQ_" . "=") ("_DOT_" . "."))) -(define (compiler-demunge s) - (let* ((s (if (string? s) s (jolt-str-render-one s))) - (n (string-length s)) - (out (open-output-string))) - (let loop ((i 0)) - (if (>= i n) (get-output-string out) - (let ((tok (let scan ((ts demunge-token-map)) - (cond ((null? ts) #f) - ((let ((t (caar ts))) - (and (<= (+ i (string-length t)) n) - (string=? (substring s i (+ i (string-length t))) t))) - (car ts)) - (else (scan (cdr ts))))))) - (cond - (tok (display (cdr tok) out) (loop (+ i (string-length (car tok))))) - ((char=? (string-ref s i) #\_) (write-char #\- out) (loop (+ i 1))) - ((char=? (string-ref s i) #\$) (write-char #\/ out) (loop (+ i 1))) - (else (write-char (string-ref s i) out) (loop (+ i 1))))))))) -(let ((members (list (cons "LINE" compiler-line-cell) (cons "COLUMN" compiler-column-cell) - (cons "specials" compiler-specials) - (cons "demunge" compiler-demunge)))) - (register-class-statics! "Compiler" members) - (register-class-statics! "clojure.lang.Compiler" members)) - -(define (jolt-enter-form! form) - (let ((p (hc-form-position form))) - (when (pmap? p) - (jolt-current-source p) - (let ((line (jolt-get p hc-kw-line jolt-nil)) (col (jolt-get p hc-kw-column jolt-nil))) - (jolt-atom-val-set! compiler-line-cell (if (jolt-nil? line) 0 line)) - (jolt-atom-val-set! compiler-column-cell (if (jolt-nil? col) 0 col)))))) - -;; "file:line:col" / "line:col" for the current form, or #f when none is set. -(define (jolt-current-source-string) - (let ((p (jolt-current-source))) - (and (pmap? p) - (let ((line (jolt-get p hc-kw-line jolt-nil)) - (col (jolt-get p hc-kw-column jolt-nil)) - (file (jolt-get p hc-kw-file jolt-nil))) - (string-append - (if (jolt-nil? file) "" (string-append file ":")) - (if (jolt-nil? line) "?" (number->string line)) ":" - (if (jolt-nil? col) "?" (number->string col))))))) - -;; The spine ALWAYS runs with the full clojure.core prelude loaded, so a clojure.* -;; ref must lower to var-deref (resolved from the prelude), not trip the emitter's -;; "unsupported stdlib fn (no core on Chez yet)" out-of-subset guard — that guard -;; is only for the bare -e subset with no prelude. Turn prelude mode on once, here, -;; so every analyze->emit on this spine sees the full core. -((var-deref "jolt.backend-scheme" "set-prelude-mode!") #t) -;; Cache resolved var cells per reference site in runtime-compiled code (the big -;; win for libraries / REPL code). emit-image.ss turns this back off so the seed -;; mint and AOT build stay byte-deterministic. Guarded: the flag is absent in an -;; older seed during the first re-mint pass. -(let ((scv (var-deref "jolt.backend-scheme" "set-var-cache!"))) - (when (procedure? scv) (scv #t))) -;; JOLT_TRACE is a falsey value (case-insensitive) — the single predicate both the -;; dev-mode enable and the whole-run enable consult, so "off" never accidentally -;; means "on". An empty / unset value is NOT falsey here — it carries no signal, so -;; dev mode still traces and a whole run still doesn't. -(define (jolt-trace-env-off? e) - (and (string? e) - (let ((s (string-downcase e))) - (or (string=? s "0") (string=? s "false") (string=? s "no") - (string=? s "off") (string=? s "n"))))) -;; Tail-frame history. Turning it on makes the emitter add a per-fn history push to -;; every fn compiled AFTERWARD, and allocates this thread's ring. Suppressed when -;; JOLT_TRACE is a falsey value, so JOLT_TRACE=0 / off / no disables it in dev mode. -(define (jolt-enable-trace!) - (unless (jolt-trace-env-off? (getenv "JOLT_TRACE")) - (let ((stf (var-deref "jolt.backend-scheme" "set-trace-frames!"))) - (when (procedure? stf) (stf #t))) - (jolt-trace-enable!))) -;; Exposed so the REPL / nREPL entrypoints (jolt.main, jolt.nrepl) can turn tracing -;; on for REPL-driven development without the user setting JOLT_TRACE. Because the -;; push is baked in at compile time, only code compiled after this call is traced — -;; which is exactly the code you eval / reload in a live session. -(def-var! "jolt.host" "enable-trace!" jolt-enable-trace!) -;; Explicit opt-in for a whole run (JOLT_TRACE=1): turn tracing on BEFORE any app -;; namespace is compiled, so a plain `-M:run` traces the app's own code too. Called -;; from the runtime entrypoints (cli.ss, and the built joltc launcher) — NOT at load -;; time: a built joltc runs top-level forms at heap-build time, where JOLT_TRACE is -;; always unset, so a load-time check would never see the user's runtime env. Only an -;; affirmative value (set, non-empty, not falsey) forces it on. -(define (jolt-trace-init-from-env!) - (let ((e (getenv "JOLT_TRACE"))) - (when (and e (fx>? (string-length e) 0) (not (jolt-trace-env-off? e))) - (jolt-enable-trace!)))) - -;; (with-meta sym m) -> sym, else x — an (ns ^:no-doc name …) yields the name with -;; reader metadata as a with-meta form; strip it to read the bare ns symbol. -(define (ce-unwrap-meta x) - (if (and (cseq? x) (cseq-list? x)) - (let ((items (seq->list x))) - (if (and (pair? items) (symbol-t? (car items)) - (string=? (symbol-t-name (car items)) "with-meta") (pair? (cdr items))) - (cadr items) x)) - x)) - -;; (quote X) -> X, else x — unwraps a quoted require spec. -(define (ce-unquote x) - (if (and (cseq? x) (cseq-list? x)) - (let ((items (seq->list x))) - (if (and (pair? items) (symbol-t? (car items)) - (string=? (symbol-t-name (car items)) "quote") (pair? (cdr items))) - (cadr items) x)) - x)) - -;; Pre-register any (require ...)/(use ...) :as aliases under `ns` BEFORE analysis, -;; so a qualified s/foo resolves while compiling (analysis precedes the runtime -;; require). Walks the whole form (a require may be nested in a do/let). -(define (ce-clause-require? cl) ; (:require ...) / (:use ...) ns clause - (and (pair? cl) (keyword? (car cl)) - (let ((kn (keyword-t-name (car cl)))) (or (string=? kn "require") (string=? kn "use"))))) -(define (ce-scan-requires! form ns) - (when (and (cseq? form) (cseq-list? form)) - (let ((items (seq->list form))) - (when (pair? items) - (let* ((h (car items)) (hn (and (symbol-t? h) (symbol-t-name h)))) - (cond - ;; (require spec...) / (use spec...) — specs are quoted - ((and hn (or (string=? hn "require") (string=? hn "use"))) - (for-each (lambda (a) (chez-register-spec! ns (ce-unquote a))) (cdr items))) - ;; (ns name (:require [a :as x]) ...) — clause specs are literal. Register - ;; the aliases under NAME (the ns being defined), not the passed `ns`: - ;; when a file is loaded its ns form compiles while (chez-current-ns) is - ;; still the requiring ns, so using `ns` would leak the loaded ns's - ;; aliases into its requirer and clobber a same-named alias there - ;; (rewrite-clj.zip.base's [node.protocols :as node] over the caller's node). - ((and hn (string=? hn "ns")) - (let ((ns-name (if (and (pair? (cdr items)) (symbol-t? (ce-unwrap-meta (cadr items)))) - (symbol-t-name (ce-unwrap-meta (cadr items))) - ns))) - (for-each (lambda (clause) - (when (and (cseq? clause) (cseq-list? clause)) - (let ((cl (seq->list clause))) - (when (ce-clause-require? cl) - (for-each (lambda (spec) (chez-register-spec! ns-name spec)) (cdr cl)))))) - (if (pair? (cdr items)) (cddr items) '())))) - (else (for-each (lambda (x) (ce-scan-requires! x ns)) items)))))))) - -;; Already-read FORM -> Scheme source string (analyze -> emit on Chez). -;; `ns` is the compile namespace unqualified symbols resolve against. -(define (jolt-analyze-emit-form form ns) - (ce-scan-requires! form ns) - (let* ((ctx (make-analyze-ctx ns)) - (ir (jolt-ce-run-passes (jolt-ce-analyze ctx form) ctx))) - (jolt-ce-emit ir))) - -;; --- runtime defmacro ------------------------------------------------------- -;; Shared with emit-image.ss (loaded after this). A defmacro lowers to a def of -;; its expander fn + a macro flag, exactly as the prelude emits build-time macros. - -;; Is `f` a (defmacro ...) / (definline ...) form? -(define (ce-macro-form? f) - (and (cseq? f) (cseq-list? f) - (let ((items (seq->list f))) - (and (pair? items) (symbol-t? (car items)) - (let ((h (symbol-t-name (car items)))) - (or (string=? h "defmacro") (string=? h "definline"))))))) - -;; (defmacro NAME [docstring] [attr-map] params body...) -> (values "NAME" (fn ...)). -;; Strips a leading docstring (native string) + attr-map (a non-symbol pmap), then -;; re-heads the rest with `fn` so a destructured macro arglist desugars. Emits the -;; BARE fn (the caller wraps it in def-var! + mark-macro!), never a (def NAME ...) — -;; interning NAME would make require skip the real macro. -(define (ce-defmacro->fn f) - (let* ((items (seq->list f)) - (name-sym (cadr items)) - (after-name (cddr items)) - (a1 (if (and (pair? after-name) (string? (car after-name))) - (cdr after-name) after-name)) - (after-meta (if (and (pair? a1) (pmap? (car a1))) - (cdr a1) a1)) - (fn-sym (jolt-symbol #f "fn"))) - (values (symbol-t-name name-sym) - (apply jolt-list (cons fn-sym after-meta))))) - -;; A bare top-level (do ...) form — head is the unqualified `do` symbol. -(define (ce-top-do? form) - (and (cseq? form) (cseq-list? form) - (let ((h (seq-first form))) - (and (symbol-t? h) (jolt-nil? (hc-sym-ns h)) - (string=? (symbol-t-name h) "do"))))) - -;; Compile + eval ONE already-read form in compile ns `ns`; returns the value. -;; A top-level (do ...) is UNROLLED — each subform compiled+eval'd in turn, like -;; Clojure's top-level do — so a runtime defmacro/def in an earlier subform is -;; visible (macro flag set, var interned) before a later subform is analyzed. -;; a non-form VALUE (a function object, a BigDecimal, a reference type) -;; self-evaluates, like eval on the JVM. -(define (jolt-compile-eval-form form ns) - (if (or (procedure? form) (jbigdec? form) (jolt-atom? form) (jolt-multifn? form)) - form - (jolt-compile-eval-form* form ns))) -(define (jolt-compile-eval-form* form ns) - (cond - ;; thread the current ns: an earlier subform may switch it (ns/in-ns call - ;; set-chez-ns!), and the next subform must be ANALYZED in that ns so its defs - ;; land there and its refs resolve (cross-ns def/require in one program). - ((ce-top-do? form) - (let loop ((fs (cdr (seq->list form))) (result jolt-nil) (cur ns)) - (if (null? fs) - result - (let ((r (jolt-compile-eval-form (car fs) cur))) - (loop (cdr fs) r (chez-current-ns)))))) - ;; defmacro is compiled like any other form — the analyzer lowers it to a def - ;; of the expander fn + (mark-macro! …) so subsequent forms expand it. One - ;; macro-expansion path (no separate spine interception). - (else - ;; record this form's source location first, so a compile- or run-time error - ;; in it reports the right place. - (jolt-enter-form! form) - ;; drop tail-frame history from earlier top-level forms, so an error's trace - ;; shows only this form's own call history (a no-op unless JOLT_TRACE is on). - (jolt-trace-reset!) - (eval (read (open-input-string (jolt-analyze-emit-form form ns))) - (interaction-environment))))) - -;; Source string -> value (read one form, compile + eval on Chez, in the -;; top-level environment where rt.ss's runtime procedures live). -(define (jolt-compile-eval src ns) - (jolt-compile-eval-form (jolt-ce-read src) ns)) - -;; clojure.core/load-string: read every form from the source string and compile+ -;; eval each in the current ns, returning the last value (nil for blank input). -(define (jolt-load-string s) - (let loop ((src s) (result jolt-nil)) - (let ((pn (jolt-parse-next src))) - (if (jolt-nil? pn) - result - (loop (jolt-nth pn 1) - (jolt-compile-eval-form (jolt-nth pn 0) (chez-current-ns))))))) - -;; eval / load-string are FUNCTIONS on the spine (the compiler image is resident -;; at runtime). eval takes an already-read FORM (e.g. from quote / list); it and -;; load-string compile+eval in the current ns. eval is removed from the analyzer's -;; special-symbol lists (host-contract.ss) so it resolves as an ordinary core var. -(def-var! "clojure.core" "eval" - (lambda (form) (jolt-compile-eval-form form (chez-current-ns)))) -(def-var! "clojure.core" "load-string" jolt-load-string) diff --git a/host/chez/converters.ss b/host/chez/converters.ss deleted file mode 100644 index afef684..0000000 --- a/host/chez/converters.ss +++ /dev/null @@ -1,288 +0,0 @@ -;; converters + string ops — host-coupled natives def-var!'d into clojure.core, -;; resolved in prelude mode. Loaded last (after jolt-pr-str), since `str` reuses -;; the printer. int/long truncate toward zero to an exact integer; compare returns -;; an exact -1/0/1; double yields a flonum. - -;; str rendering for the value types not handled by the fast arms below. A host -;; shim loaded later (records, host-table, inst-time, …) registers an arm with -;; register-str-render! instead of set!-wrapping jolt-str-render-one — the arms -;; are type-disjoint, so the full behavior is the base arms here plus the -;; registry, gathered in one place rather than scattered across a set! chain. -;; Newest registration is checked first (matches the old outermost-wins order). -(define str-render-registry '()) ; list of (pred . render), checked front-to-back -(define (register-str-render! pred render) - (set! str-render-registry (cons (cons pred render) str-render-registry))) - -;; str: nil -> "", string raw, char bare (not \c), regex -> raw source, a -;; registered host type via its arm, else the printer (which renders collections -;; with readable elements). -(define (jolt-str-render-one v) - (cond - ((jolt-nil? v) "") - ((string? v) v) - ((char? v) (string v)) - ((regex-t? v) (regex-t-source v)) - ;; str/print render the infinities and NaN long-form (Clojure .toString), - ;; unlike the -e printer's inf/-inf/nan. - ((and (flonum? v) (fl= v +inf.0)) "Infinity") - ((and (flonum? v) (fl= v -inf.0)) "-Infinity") - ((and (flonum? v) (not (fl= v v))) "NaN") - ;; a symbol stringifies to its name (JVM Symbol.toString returns the interned - ;; name), so (str sym) of a no-ns symbol is the SAME string object the symbol - ;; holds — code that compares those by identity (core.logic's non-unique lvar - ;; equality) depends on it. - ((symbol-t? v) - (let ((ns (symbol-t-ns v))) - (if (or (not ns) (jolt-nil? ns)) - (symbol-t-name v) - (string-append ns "/" (symbol-t-name v))))) - (else - (let loop ((rs str-render-registry)) - (cond - ((null? rs) (jolt-pr-str v)) - (((caar rs) v) ((cdar rs) v)) - (else (loop (cdr rs)))))))) -;; print/println render non-readably: a nested string is raw. jolt-str-render-one -;; is exactly that (collections fall through to jolt-pr-str). The print family -;; uses this seam, NOT the str fn — which renders readably (below). A top-level nil -;; prints "nil" (str renders it ""), so the seam special-cases it. -(define (jolt-print-one v) (if (jolt-nil? v) "nil" (jolt-str-render-one v))) -(def-var! "clojure.core" "__print1" jolt-print-one) - -;; str: a top-level string/scalar renders as jolt-str-render-one (raw string, -;; "Infinity"…), but a COLLECTION renders as its readable form — nested strings -;; are QUOTED ((str ["x"]) => "[\"x\"]"), matching the JVM (a collection's -;; toString is readable). jolt-pr-readable resolves at call time. -(define (jolt-str-one v) - (if (or (pvec? v) (pmap? v) (pset? v) (cseq? v) (empty-list-t? v) (jolt-lazyseq? v)) - (jolt-pr-readable v) - (jolt-str-render-one v))) -(define (jolt-str . xs) - (cond - ((null? xs) "") - ;; single arg returns its rendering directly (no string-append copy), so - ;; (str sym) hands back the symbol's own name string — JVM (str x) is - ;; x.toString(), and core.logic's non-unique lvar equality compares those by - ;; identity. - ((null? (cdr xs)) (jolt-str-one (car xs))) - (else (let loop ((xs xs) (acc '())) - (if (null? xs) - (apply string-append (reverse acc)) - (loop (cdr xs) (cons (jolt-str-one (car xs)) acc))))))) - -;; jolt indices are flonums; substring etc. need exact ints. -(define (jolt->idx n) (exact (truncate n))) - -(define (jolt-subs s start . end) - (substring s (jolt->idx start) - (if (null? end) (string-length s) (jolt->idx (car end))))) - -;; vec: a pvec from any seqable (already-pvec returns itself). -(define (jolt-vec coll) - (cond - ((jolt-nil? coll) (jolt-vector)) - ((pvec? coll) coll) - ((string? coll) (apply jolt-vector (string->list coll))) - (else (apply jolt-vector (seq->list coll))))) - -(define (jolt-keyword . args) - (cond - ((= (length args) 1) - (let ((a (car args))) - (cond - ((jolt-nil? a) jolt-nil) - ((keyword? a) a) - ;; a 1-arg string splits on the FIRST "/" into ns/name: - ;; (keyword "x/y") => :x/y with ns "x" — destructure's {:keys [x/y]} builds - ;; the key this way, so without the split the namespaced key never matches. - ((string? a) - (let ((si (let loop ((i 0)) - (cond ((>= i (string-length a)) #f) - ((char=? (string-ref a i) #\/) i) - (else (loop (+ i 1))))))) - (if (and si (> si 0) (< si (- (string-length a) 1))) - (keyword (substring a 0 si) (substring a (+ si 1) (string-length a))) - (keyword #f a)))) - ((jolt-symbol? a) - (let ((ns (symbol-t-ns a))) - (keyword (if (or (jolt-nil? ns) (not ns) (eq? ns '())) #f ns) (symbol-t-name a)))) - (else (error #f "keyword: requires string/symbol/keyword" a))))) - ((= (length args) 2) - (keyword (let ((ns (car args))) (if (jolt-nil? ns) #f ns)) (cadr args))) - (else (error #f "keyword: wrong arity")))) - -(define (jolt-symbol-new . args) - (cond - ((= (length args) 1) - (let ((a (car args))) - (cond - ((jolt-symbol? a) a) - ;; (symbol "ns/name") splits the namespace at the FIRST "/" (JVM - ;; Symbol.intern), so (namespace (symbol "foo/bar/baz")) => "foo" with - ;; name "bar/baz". A lone "/" or a leading slash has no namespace. The - ;; no-ns sentinel is #f — matches emit's quoted-symbol lowering - ;; (jolt-symbol #f "x"), so (= 'x (symbol "x")) holds (jolt= compares - ;; ns with strict equal?). - ((string? a) - (let ((slen (string-length a))) - (if (string=? a "/") - (jolt-symbol #f "/") - (let loop ((i 1)) - (cond ((>= i slen) (jolt-symbol #f a)) - ((char=? (string-ref a i) #\/) - (jolt-symbol (substring a 0 i) (substring a (+ i 1) slen))) - (else (loop (+ i 1)))))))) - ((keyword? a) (jolt-symbol (keyword-t-ns a) (keyword-t-name a))) - ;; (symbol a-var) -> the var's qualified symbol (clojure.spec.alpha/->sym). - ((var-cell? a) (jolt-symbol (var-cell-ns a) (var-cell-name a))) - (else (error #f "symbol: requires string/symbol" a))))) - ;; (symbol ns name): a nil namespace is the no-ns sentinel #f (NOT jolt-nil), - ;; so (symbol nil "x") equals (symbol "x") and the reader literal 'x — jolt= - ;; compares ns with strict equal?, so a jolt-nil ns would differ from #f. - ((= (length args) 2) - (let ((ns (car args))) - (jolt-symbol (if (jolt-nil? ns) #f ns) (cadr args)))) - (else (error #f "symbol: wrong arity")))) - -;; gensym: per-process counter. -(define jolt-gensym-counter 0) -(define (jolt-gensym . prefix) - (let ((p (if (null? prefix) "G__" (car prefix)))) - (set! jolt-gensym-counter (+ jolt-gensym-counter 1)) - (jolt-symbol #f - (string-append (if (string? p) p (jolt-str-render-one p)) - (number->string jolt-gensym-counter))))) - -;; int/long: truncate toward zero to an EXACT integer (= JVM long). char -> code -;; point (exact). double: always a flonum (= JVM double). -(define (jolt-int x) (if (char? x) (char->integer x) (exact (truncate x)))) -;; a numeric type outside Chez's tower converts through this hook (bigdec). -(define (jolt-double-slow x) (jolt-num-cast-throw x)) -(define (jolt-double x) - (cond ((char? x) (exact->inexact (char->integer x))) - ((number? x) (exact->inexact x)) - (else (jolt-double-slow x)))) - -;; compare: 3-way, returns an EXACT integer (= JVM compare -> int). -(define (jolt-cmp3 x y) (cond ((< x y) -1) ((> x y) 1) (else 0))) -(define (jolt-strcmp a b) (cond ((string? a b) 1) (else 0))) -(define (jolt-kw->string k) - (let ((ns (keyword-t-ns k))) (if ns (string-append ns "/" (keyword-t-name k)) (keyword-t-name k)))) -(define (jolt-sym-ns-string s) - (let ((n (symbol-t-ns s))) (if (or (jolt-nil? n) (not n) (eq? n '())) "" n))) -;; compare returns an EXACT integer -1/0/1 (= JVM compare -> int). -(define (jolt-compare a b) - (cond - ((and (jolt-nil? a) (jolt-nil? b)) 0) - ((jolt-nil? a) -1) - ((jolt-nil? b) 1) - ((and (number? a) (number? b)) (jolt-cmp3 a b)) - ((and (string? a) (string? b)) (jolt-strcmp a b)) - ;; keywords order like symbols: a nil namespace sorts before any namespace, - ;; then by namespace, then by name (Keyword.compareTo -> Symbol.compareTo) - ((and (keyword? a) (keyword? b)) - (let ((r (jolt-strcmp (or (keyword-t-ns a) "") (or (keyword-t-ns b) "")))) - (if (= r 0) (jolt-strcmp (keyword-t-name a) (keyword-t-name b)) r))) - ((and (jolt-symbol? a) (jolt-symbol? b)) - (let ((r (jolt-strcmp (jolt-sym-ns-string a) (jolt-sym-ns-string b)))) - (if (= r 0) (jolt-strcmp (symbol-t-name a) (symbol-t-name b)) r))) - ((and (boolean? a) (boolean? b)) (cond ((eq? a b) 0) ((eq? a #f) -1) (else 1))) - ((and (char? a) (char? b)) (jolt-cmp3 (char->integer a) (char->integer b))) - ((and (pvec? a) (pvec? b)) - (let ((la (pvec-count a)) (lb (pvec-count b))) - (if (not (= la lb)) - (jolt-cmp3 la lb) - (let loop ((i 0)) - (if (>= i la) - 0 - (let ((r (jolt-compare (pvec-nth-d a i jolt-nil) (pvec-nth-d b i jolt-nil)))) - (if (= r 0) (loop (+ i 1)) r))))))) - (else (error #f "compare: cannot compare these types" a b)))) - -(def-var! "clojure.core" "str" jolt-str) -(def-var! "clojure.core" "subs" jolt-subs) -(def-var! "clojure.core" "vec" jolt-vec) -(def-var! "clojure.core" "keyword" jolt-keyword) -(def-var! "clojure.core" "symbol" jolt-symbol-new) -(def-var! "clojure.core" "gensym" jolt-gensym) -;; --- checked narrow casts (RT.byteCast/shortCast/intCast/longCast/charCast) -- -;; One helper carries the JVM ranges: truncate toward zero, then range-check. -;; NaN casts to 0 (Java (long)NaN); an out-of-range value (including a float -;; infinity) is IllegalArgumentException "Value out of range for : x". -;; A non-numeric operand is the usual ClassCastException. Numeric types outside -;; Chez's tower truncate through a hook the shim extends (BigDecimal). -(define (jolt-cast-range-throw name x) - (jolt-throw (jolt-host-throwable - "java.lang.IllegalArgumentException" - (string-append "Value out of range for " name ": " (jolt-str x))))) -(define (jolt-cast-truncate-slow x) (jolt-num-cast-throw x)) -(define (jolt-checked-cast name lo hi x) - (let ((n (cond ((char? x) (char->integer x)) - ((and (number? x) (exact? x)) (truncate x)) - ;; a double range-checks ITSELF (before truncation): (byte - ;; 127.000001) throws, (byte 1.1) is 1; NaN casts to 0; an - ;; infinity always fails the compare. - ((flonum? x) (cond ((nan? x) 0) - ((or (< x lo) (> x hi)) (+ hi 1)) - (else (exact (truncate x))))) - (else (jolt-cast-truncate-slow x))))) - (if (and (>= n lo) (<= n hi)) n (jolt-cast-range-throw name x)))) -(define (jolt-byte-cast x) (jolt-checked-cast "byte" -128 127 x)) -(define (jolt-short-cast x) (jolt-checked-cast "short" -32768 32767 x)) -(define (jolt-int-cast x) (jolt-checked-cast "int" -2147483648 2147483647 x)) -(define (jolt-long-cast x) (jolt-checked-cast "long" -9223372036854775808 9223372036854775807 x)) -(def-var! "clojure.core" "int" jolt-int-cast) -(def-var! "clojure.core" "long" jolt-long-cast) -(def-var! "clojure.core" "byte" jolt-byte-cast) -(def-var! "clojure.core" "short" jolt-short-cast) -;; char: pass a char through; a code point must be in [0, 0xFFFF] (charCast). -(define (jolt-char x) - (if (char? x) x (integer->char (jolt-checked-cast "char" 0 65535 x)))) -(def-var! "clojure.core" "char" jolt-char) -;; unchecked-long: truncate + wrap to 64 bits (RT.uncheckedLongCast — a float -;; infinity saturates, NaN is 0). unchecked-int wraps and sign-folds to 32. -(define (jolt-cast-saturate n lo hi) (cond ((< n lo) lo) ((> n hi) hi) (else n))) -(define (jolt-unchecked-long x) - (cond ((char? x) (char->integer x)) - ;; an exact integer wraps (long narrowing); a double SATURATES (Java's - ;; double->long conversion clamps at the bounds, NaN is 0). - ((and (number? x) (exact? x)) (jolt-wrap64 (truncate x))) - ((flonum? x) (if (nan? x) 0 - (jolt-cast-saturate (if (infinite? x) (if (> x 0.0) unc-2^63 (- unc-2^63)) (exact (truncate x))) - -9223372036854775808 9223372036854775807))) - (else (jolt-wrap64 (jolt-cast-truncate-slow x))))) -(define (jolt-unchecked-int x) - (if (flonum? x) - ;; double->int clamps like Java - (if (nan? x) 0 - (jolt-cast-saturate (if (infinite? x) (if (> x 0.0) #x80000000 (- #x80000000)) (exact (truncate x))) - -2147483648 2147483647)) - (let ((i (bitwise-and (jolt-unchecked-long x) #xffffffff))) - (if (>= i #x80000000) (- i #x100000000) i)))) -(def-var! "clojure.core" "unchecked-long" jolt-unchecked-long) -(def-var! "clojure.core" "unchecked-int" jolt-unchecked-int) -(def-var! "clojure.core" "double" jolt-double) -;; float: Chez has no single-float type, so the value stays a flonum — but the -;; cast range-checks against Float/MAX_VALUE like RT.floatCast (an infinity is -;; out of range; NaN passes). -(define fl-float-max 3.4028234663852886e38) -(define (jolt-float x) - (let ((d (jolt-double x))) - (if (and (flonum? d) (not (nan? d)) - (or (< d (- fl-float-max)) (> d fl-float-max))) - (jolt-cast-range-throw "float" x) - d))) -(def-var! "clojure.core" "float" jolt-float) -;; numerator/denominator: jolt ratios are Chez exact rationals; a non-ratio is -;; the JVM's Ratio cast failure. -(define (jolt-ratio-part name f) - (lambda (x) - (if (and (number? x) (exact? x) (rational? x) (not (integer? x))) - (f x) - (jolt-throw (jolt-host-throwable - "java.lang.ClassCastException" - (string-append "class " (guard (e (#t "?")) (jolt-class-name x)) - " cannot be cast to class clojure.lang.Ratio")))))) -(def-var! "clojure.core" "numerator" (jolt-ratio-part "numerator" numerator)) -(def-var! "clojure.core" "denominator" (jolt-ratio-part "denominator" denominator)) -(def-var! "clojure.core" "compare" jolt-compare) diff --git a/host/chez/cts.sh b/host/chez/cts.sh deleted file mode 100755 index 0c2f1cb..0000000 --- a/host/chez/cts.sh +++ /dev/null @@ -1,120 +0,0 @@ -#!/bin/bash -# clojure-test-suite gate: run the vendored jank-lang/clojure-test-suite -# (vendor/clojure-test-suite) against joltc, one process per test namespace (a -# hang or crash is contained), and compare per-namespace fail/error counts -# against the checked-in baseline test/chez/cts-known-failures.txt. -# -# The comparison is exact, like certify's allowlist: a namespace doing WORSE -# than the baseline fails the gate (regression), and one doing BETTER also -# fails (stale baseline — update the file in the same change that improved it). -# -# JOLT_CTS_JOBS=N parallel workers (default 4) -# JOLT_CTS_TIMEOUT=SECS per-namespace timeout (default 120) -# JOLT_CTS_WRITE_BASELINE=1 regenerate the baseline file instead of gating -# JOLT_CTS_NS=ns1,ns2 run only these namespaces, verbose, no gating -set -u -root="$(CDPATH= cd -- "$(dirname -- "$0")/../.." && pwd)" -cd "$root" - -suite="vendor/clojure-test-suite/test" -baseline="test/chez/cts-known-failures.txt" -app="$root/test/chez/cts-app" -jobs="${JOLT_CTS_JOBS:-4}" -tmo="${JOLT_CTS_TIMEOUT:-120}" - -if [ ! -d "$suite/clojure" ]; then - echo "cts: skipped (git submodule update --init vendor/clojure-test-suite)" - exit 0 -fi - -work="$(mktemp -d)" -trap 'rm -rf "$work"' EXIT - -# test namespaces from the .cljc files (portability is a helper, not a test ns) -find "$suite" -name '*.cljc' | sed "s|^$suite/||;s|\.cljc$||;s|/|.|g;s|_|-|g" \ - | grep -v '\.portability$' | sort > "$work/nses" -if [ -n "${JOLT_CTS_NS:-}" ]; then - echo "${JOLT_CTS_NS}" | tr ',' '\n' > "$work/nses" -fi - -# round-robin the namespaces over N sequential workers; each worker appends -# "ns pass fail error" lines (HUNG/CRASH in the pass column) to its own file. -awk -v j="$jobs" '{print > ("'"$work"'/chunk." (NR % j))}' "$work/nses" -run_chunk() { - chunk="$1"; out="$2" - while IFS= read -r ns; do - res=$(JOLT_PWD="$app" perl -e "alarm $tmo; exec @ARGV" -- "$root/bin/joltc" -M:cts "$ns" 2>&1 > "$out" - if [ -n "${JOLT_CTS_NS:-}" ]; then - echo "$res" | grep -E 'FAIL:|ERROR:|LOAD:' | sed 's/^/ /' >> "$out" - fi - elif [ $rc -ge 128 ]; then - echo "$ns HUNG 0 0" >> "$out" - else - echo "$ns CRASH 0 0" >> "$out" - fi - done < "$chunk" -} -for c in "$work"/chunk.*; do - run_chunk "$c" "$c.res" & -done -wait -cat "$work"/chunk.*.res 2>/dev/null | sort > "$work/results" - -if [ -n "${JOLT_CTS_NS:-}" ]; then - cat "$work/results" - exit 0 -fi - -summary=$(awk '$2!="HUNG" && $2!="CRASH" {p+=$2; f+=$3; e+=$4; c++} - $2=="HUNG" {h++} $2=="CRASH" {x++} - END {printf "%d namespaces: pass %d, fail %d, error %d, hung %d, crash %d", - c+h+x, p, f, e, h, x}' "$work/results") - -if [ "${JOLT_CTS_WRITE_BASELINE:-0}" = "1" ]; then - { - echo "# clojure-test-suite known failures: " - echo "# The gate fails on any per-namespace change, worse OR better; regenerate" - echo "# with: JOLT_CTS_WRITE_BASELINE=1 host/chez/cts.sh" - awk '$2=="HUNG" || $2=="CRASH" {print $1, $2, $2; next} - $3 != 0 || $4 != 0 {print $1, $3, $4}' "$work/results" - } > "$baseline" - echo "cts: $summary" - echo "cts: baseline written to $baseline ($(grep -cv '^#' "$baseline") namespaces)" - exit 0 -fi - -if [ ! -f "$baseline" ]; then - echo "cts: FAIL — no baseline; run JOLT_CTS_WRITE_BASELINE=1 host/chez/cts.sh" - exit 1 -fi - -status=0 -while read -r ns p f e; do - case "$p" in HUNG|CRASH) f="$p"; e="$p" ;; esac - bl=$(grep -v '^#' "$baseline" | awk -v n="$ns" '$1==n {print $2, $3; exit}') - if [ -n "$bl" ]; then bf="${bl%% *}"; be="${bl##* }"; else bf=0; be=0; fi - if [ "$f" = "$bf" ] && [ "$e" = "$be" ]; then - continue - elif [ "$f" = "HUNG" ] || [ "$f" = "CRASH" ] \ - || { [ "$bf" != "HUNG" ] && [ "$bf" != "CRASH" ] \ - && { [ "$f" -gt "$bf" ] || [ "$e" -gt "$be" ]; }; }; then - echo "cts: NEW regression in $ns — fail $f error $e (baseline $bf $be)" - status=1 - else - echo "cts: STALE baseline for $ns — now fail $f error $e (baseline $bf $be); update $baseline" - status=1 - fi -done < "$work/results" - -# a baseline entry whose namespace no longer reports is stale too -while read -r ns bf be; do - grep -q "^$ns " "$work/results" || { echo "cts: STALE baseline entry $ns (namespace gone)"; status=1; } -done < <(grep -v '^#' "$baseline") - -echo "cts: $summary" -if [ $status -eq 0 ]; then echo "cts: passed (matches baseline)"; else echo "cts: FAILED"; fi -exit $status diff --git a/host/chez/dce.ss b/host/chez/dce.ss deleted file mode 100644 index b7d9d06..0000000 --- a/host/chez/dce.ss +++ /dev/null @@ -1,186 +0,0 @@ -;; dce.ss — tree-shaking (jolt build --tree-shake): whole-program reachability DCE. -;; -;; Build one call graph over the re-emitted app + libraries AND the clojure.core -;; prelude, keep -main + every side-effecting top-level form + everything reachable -;; from those, drop the rest. Bails (keeps everything) if reachable code resolves a -;; var by name at runtime (eval/resolve/...), which a static graph can't follow. Per -;; Stalin's rule, ANY reference — a call OR a value/#'x — keeps its target live, so a -;; fn passed to map or referenced as #'x is never dropped. -;; -;; Loaded by build.ss after the compiler image (needs jolt.ir/reduce-ir-children). -;; The records it consumes come from ei-emit-ns-records (app/libs) + dce-blob-records -;; (the prelude); both build the (dce-rec …) shape below. - -;; --- the DCE record --------------------------------------------------------- -;; keep?: #t = a non-def form (side effect / registration) — always emitted, and its -;; refs are reachability roots. #f = a prunable def emitted only if fqn is reached. -;; fqn: "ns/name" of a prunable def, else #f. refs: "ns/name" strings it references. -;; str: the Scheme source to emit. -(define (dce-rec keep? fqn refs str) (vector keep? fqn refs str)) -(define (dce-rec-keep? r) (vector-ref r 0)) -(define (dce-rec-fqn r) (vector-ref r 1)) -(define (dce-rec-refs r) (vector-ref r 2)) -(define (dce-rec-str r) (vector-ref r 3)) - -;; --- reference extraction from IR ------------------------------------------- -(define dce-kw-op (keyword #f "op")) -(define dce-kw-var (keyword #f "var")) -(define dce-kw-the-var (keyword #f "the-var")) -(define dce-kw-def (keyword #f "def")) -(define dce-kw-ns (keyword #f "ns")) -(define dce-kw-name (keyword #f "name")) -(define dce-reduce-children (var-deref "jolt.ir" "reduce-ir-children")) - -;; "ns/name" of every var reference anywhere in an IR node, prepended to acc. Counts -;; a :var (call head or value) and a :the-var (#'x). Arg order (acc node) matches -;; reduce-ir-children's fold fn so it nests directly. -(define (dce-collect-refs acc node) - (let ((op (jolt-get node dce-kw-op))) - (if (or (eq? op dce-kw-var) (eq? op dce-kw-the-var)) - (cons (string-append (jolt-get node dce-kw-ns) "/" (jolt-get node dce-kw-name)) acc) - (dce-reduce-children dce-collect-refs acc node)))) - -;; The fqn of a bare top-level def (the only prunable IR form), else #f. -(define (dce-def-fqn node) - (and (eq? (jolt-get node dce-kw-op) dce-kw-def) - (string-append (jolt-get node dce-kw-ns) "/" (jolt-get node dce-kw-name)))) - -;; --- reference sets that gate the analysis ---------------------------------- -;; A reference whose presence in reachable code forces keep-everything (the static -;; graph can't follow runtime name resolution). -(define dce-bail-refs - '("clojure.core/eval" "clojure.core/resolve" "clojure.core/ns-resolve" - "clojure.core/requiring-resolve" "clojure.core/find-var" "clojure.core/intern" - "clojure.core/load-string" "clojure.core/load-file" "clojure.core/load-reader" - "clojure.core/load")) - -;; A reference that needs the analyzer/back end at runtime (compile-from-source). If -;; reachable code uses none of these, the compiler image is dropped from the binary — -;; an AOT app is fully compiled. (resolve/require don't need it: resolve is a -;; var-table lookup; a require of a baked ns no-ops.) -(define dce-compile-refs - '("clojure.core/eval" "clojure.core/load-string" "clojure.core/load-file" - "clojure.core/load-reader" "clojure.core/load")) - -;; clojure.core fns the runtime .ss shims reference by name (via var-deref) — they -;; aren't visible in the IR call graph, so seed them as roots. (Found by grepping the -;; runtime shims; the smoke harness catches a miss as a diff/crash.) -(define dce-runtime-core-roots - '("clojure.core/identity" "clojure.core/isa?" "clojure.core/line-seq" - "clojure.core/make-hierarchy" "clojure.core/read" "clojure.core/read-string" - "clojure.core/read+string" "clojure.core/realized?" "clojure.core/reset!")) - -;; --- reading a minted blob (prelude.ss) into records ------------------------ -;; The prelude is a flat list of (guard CLAUSE (def-var! "ns" "name" V)) forms (+ the -;; occasional side-effecting init). Read each with Chez `read` so it joins the graph -;; instead of being baked wholesale: a def-var! is a prunable node whose core->core -;; edges are the (var-deref/jolt-var "ns" "name") calls in V; any other form is -;; non-prunable (kept, refs are roots). -(define (dce-unwrap form) - (if (and (pair? form) (eq? (car form) 'guard) (pair? (cddr form))) (caddr form) form)) - -(define (dce-sexp-refs form acc) - (cond - ((and (pair? form) (memq (car form) '(var-deref jolt-var)) - (pair? (cdr form)) (string? (cadr form)) (pair? (cddr form)) (string? (caddr form))) - (cons (string-append (cadr form) "/" (caddr form)) acc)) - ((pair? form) (dce-sexp-refs (cdr form) (dce-sexp-refs (car form) acc))) - (else acc))) - -;; str re-serializes the read form (compiled identically; comments/whitespace are -;; irrelevant). -(define (dce-blob-records path) - ;; bld-source-string (build.ss) reads the embedded copy when running from a - ;; self-contained joltc, else the file on disk — so tree-shake works with no - ;; jolt checkout present. Forward ref: build.ss loads after this file. - (call-with-port (open-input-string (bld-source-string path)) - (lambda (p) - (let loop ((acc '())) - (let ((form (read p))) - (if (eof-object? form) - (reverse acc) - (let ((b (dce-unwrap form)) - (str (with-output-to-string (lambda () (write form)))) - (refs (dce-sexp-refs form '()))) - (loop (cons - (if (and (pair? b) (eq? (car b) 'def-var!) (pair? (cdr b)) (string? (cadr b)) - (pair? (cddr b)) (string? (caddr b))) - (dce-rec #f (string-append (cadr b) "/" (caddr b)) refs str) - (dce-rec #t #f refs str)) - acc))))))))) - -;; --- the shake: graph -> reachable -> bail check -> partition ---------------- -;; edges: fqn -> refs (prunable defs only). roots: -main + the runtime-core roots + -;; every non-def form's refs. -(define (dce-build-graph records entry-main) - (let ((edges (make-hashtable string-hash string=?)) - (roots (cons entry-main dce-runtime-core-roots))) - (for-each (lambda (r) - (if (dce-rec-keep? r) - (set! roots (append (dce-rec-refs r) roots)) - (hashtable-set! edges (dce-rec-fqn r) (dce-rec-refs r)))) - records) - (values edges roots))) - -;; Closure of roots over edges -> a reached set (hashtable fqn -> #t). -(define (dce-reachable edges roots) - (let ((reached (make-hashtable string-hash string=?))) - (let bfs ((work roots)) - (unless (null? work) - (let ((fq (car work))) - (if (hashtable-ref reached fq #f) - (bfs (cdr work)) - (begin (hashtable-set! reached fq #t) - (bfs (append (or (hashtable-ref edges fq #f) '()) (cdr work)))))))) - reached)) - -(define (dce-rec-reached? r reached) - (or (dce-rec-keep? r) (hashtable-ref reached (dce-rec-fqn r) #f))) - -;; Scan the KEPT records: does any resolve a var at runtime (bail), and does any need -;; the compiler? Returns (values bail? bail-why needs-compiler?). bail-why is up to 6 -;; (def . bail-ref) pairs for the diagnostic. -(define (dce-bail-scan records reached) - (let ((bail #f) (why '()) (needs-compiler #f)) - (for-each - (lambda (r) - (when (dce-rec-reached? r reached) - (for-each (lambda (b) - (when (member b (dce-rec-refs r)) - (set! bail #t) - (when (< (length why) 6) - (set! why (cons (cons (or (dce-rec-fqn r) "
") b) why))))) - dce-bail-refs) - (when (ormap (lambda (c) (and (member c (dce-rec-refs r)) #t)) dce-compile-refs) - (set! needs-compiler #t)))) - records) - (values bail (reverse why) needs-compiler))) - -;; Kept records -> (values kept-strings n-defs n-kept-defs). -(define (dce-partition records reached) - (let loop ((rs records) (acc '()) (n 0) (k 0)) - (if (null? rs) - (values (reverse acc) n k) - (let* ((r (car rs)) (isdef (and (dce-rec-fqn r) #t))) - (if (dce-rec-reached? r reached) - (loop (cdr rs) (cons (dce-rec-str r) acc) (if isdef (+ n 1) n) (if isdef (+ k 1) k)) - (loop (cdr rs) acc (if isdef (+ n 1) n) k)))))) - -;; Returns (values core-strs app-strs drop-compiler?). core-strs is #f on a bail, -;; signalling "inline prelude.ss unshaken" + keep the compiler. -(define (dce-shake core-records app-records entry-main) - (let-values (((edges roots) (dce-build-graph (append core-records app-records) entry-main))) - (let* ((reached (dce-reachable edges roots))) - (let-values (((bail why needs-compiler) (dce-bail-scan (append core-records app-records) reached))) - (let ((drop-compiler? (and (not bail) (not needs-compiler)))) - (if bail - (begin - (display "jolt build: tree-shake skipped (reachable code resolves vars at runtime):\n") - (for-each (lambda (w) (display (string-append " " (car w) " -> " (cdr w) "\n"))) why) - (values #f (map dce-rec-str app-records) drop-compiler?)) - (let-values (((core-strs cn ck) (dce-partition core-records reached)) - ((app-strs an ak) (dce-partition app-records reached))) - (display (string-append "jolt build: tree-shake kept " (number->string (+ ck ak)) - " of " (number->string (+ cn an)) " defs (core " - (number->string ck) "/" (number->string cn) ")\n")) - (values core-strs app-strs drop-compiler?)))))))) diff --git a/host/chez/dyn-binding.ss b/host/chez/dyn-binding.ss deleted file mode 100644 index dd2742d..0000000 --- a/host/chez/dyn-binding.ss +++ /dev/null @@ -1,167 +0,0 @@ -;; dynamic var binding — binding / with-bindings* / var-set / thread-bound? / -;; with-local-vars / with-redefs / bound-fn* / get-thread-bindings. -;; -;; A per-thread dynamic-binding stack: a list of frames, innermost (most recently -;; pushed) at the HEAD. Each frame is an alist of (var-cell . value) MUTABLE pairs -;; — so var-set can update the innermost binding in place (set-cdr!), matching -;; Clojure where var-set targets the current binding, not the root. -;; -;; The binding macro builds a frame as a jolt map (array-map of (var x) -> value); -;; push-thread-bindings folds it into the alist. Lookups walk frames by cell -;; IDENTITY (eq?) — vars are interned, so (var x) always yields the same cell, and -;; this sidesteps a persistent-hash-map-can't-find-a-var-key quirk. -;; -;; var reads (var-deref in compiled code, jolt-var-get / deref on a cell) consult -;; the stack before falling back to the cell root. Loaded LAST (after vars.ss and -;; ns.ss) so it chains the fully-extended jolt-var-get and overrides rt.ss var-deref. - -;; THREAD-LOCAL: a Chez thread parameter, so each OS thread (a future / go block) -;; has its own binding stack. Chez initializes a new thread's parameter -;; to the spawning thread's value at fork time, giving Clojure binding conveyance -;; for free (the future shim also installs an explicit snapshot, belt-and-suspenders). -(define dyn-binding-stack (make-thread-parameter '())) - -;; find the innermost (cell . value) pair binding CELL, or #f. -(define (dyn-find-binding cell) - (let loop ((frames (dyn-binding-stack))) - (and (pair? frames) - (or (assq cell (car frames)) - (loop (cdr frames)))))) - -;; a unique sentinel: distinguishes "no thread binding" from a binding whose -;; value happens to be jolt-nil. -(define dyn-no-binding (list 'no-binding)) -(define (dyn-binding-value cell) - (if (pair? (dyn-binding-stack)) - (let ((p (dyn-find-binding cell))) - (if p - (let ((val (cdr p))) - (if (var-cell? val) (jolt-var-get val) val)) ; nested var deref (Clojure) - dyn-no-binding)) - dyn-no-binding)) - -;; push-thread-bindings: frame is a jolt map of var-cell -> value. Fold it into an -;; identity-keyed alist of mutable pairs and push. -(define (jolt-push-thread-bindings frame) - (dyn-binding-stack - (cons (pmap-fold frame (lambda (k v acc) (cons (cons k v) acc)) '()) - (dyn-binding-stack))) - jolt-nil) - -(define (jolt-pop-thread-bindings) - (when (pair? (dyn-binding-stack)) - (dyn-binding-stack (cdr (dyn-binding-stack)))) - jolt-nil) - -;; get-thread-bindings: a jolt map of every currently-bound cell -> value, -;; innermost wins. Merge oldest-frame-first (the stack head is innermost). The -;; result can be re-pushed by with-bindings* / bound-fn*. -(define (jolt-get-thread-bindings) - (let loop ((frames (reverse (dyn-binding-stack))) (m (jolt-hash-map))) - (if (null? frames) - m - (loop (cdr frames) - (let frame-loop ((alist (car frames)) (m m)) - (if (null? alist) - m - (frame-loop (cdr alist) - (pmap-assoc m (caar alist) (cdar alist))))))))) - -;; __thread-bound? — single var; true iff it has a thread binding. -(define (jolt-thread-bound? v) - (and (var-cell? v) (dyn-find-binding v) #t)) - -;; var-set: update the innermost frame that binds v (in place); else set the root. -(define (jolt-var-set v val) - (if (var-cell? v) - (let ((p (dyn-find-binding v))) - (if p - (begin (set-cdr! p val) val) - ;; a ROOT change is Var.bindRoot: validate, set, notify watches - ;; (a thread-binding set does not notify, like the JVM). - (let ((old (var-cell-root v))) - (iref-validate v val) - (var-cell-root-set! v val) (var-cell-defined?-set! v #t) - (iref-notify v old val) - val))) - (error #f "var-set: not a var" v))) - -;; alter-var-root: atomically apply f to the current root plus args. -(define (jolt-alter-var-root v f . args) - (let* ((old (var-cell-root v)) - (new (apply jolt-invoke f old args))) - (iref-validate v new) - (var-cell-root-set! v new) - (var-cell-defined?-set! v #t) - (iref-notify v old new) - new)) - -;; __local-var: a fresh free-standing var cell (not interned). with-local-vars -;; binds these as lexical locals; var-get/var-set read/write the root. Each gets a -;; unique name so two locals never compare/hash equal as map keys. -(define local-var-counter 0) -(define (jolt-local-var . args) - (set! local-var-counter (fx+ local-var-counter 1)) - (make-var-cell "" (string-append "local-" (number->string local-var-counter)) - (if (pair? args) (car args) jolt-nil) - #t)) - -;; --- chain the var-read paths onto the binding stack ------------------------- - -;; var-deref (rt.ss): the compiled-code read path for every clojure.core var -;; reference. Consult the stack first; fall straight back to the root (NOT through -;; jolt-var-get's unbound-error path) so undefined-var reads keep prior behaviour. -;; The *ns* var cell — its reads are thread-local: with no thread-binding they -;; derive from chez-current-ns (a thread-parameter), so *ns* tracks in-ns per -;; thread and a (binding [*ns* ..]) drives resolution. Captured now that *ns* is -;; defined (ns.ss loaded earlier); chez-current-ns consults it too. -(set! star-ns-cell (jolt-var "clojure.core" "*ns*")) - -(define %dyn-rt-var-deref var-deref) -(set! var-deref - (lambda (ns name) - (let ((cell (jolt-var ns name))) - (let ((bv (dyn-binding-value cell))) - (cond ((not (eq? bv dyn-no-binding)) bv) - ((eq? cell star-ns-cell) (intern-ns! (chez-current-ns))) - (else (var-cell-root cell))))))) - -;; var-deref's read on an ALREADY-RESOLVED cell — what compiled code emits when it -;; caches the cell at a reference site. Binding stack first, then *ns* thread-local, -;; else the raw root. Lenient on an unbound root (returns the sentinel), matching -;; var-deref — NOT the strict jolt-var-get, which throws "Unbound var". -(define (var-cell-deref cell) - (let ((bv (dyn-binding-value cell))) - (cond ((not (eq? bv dyn-no-binding)) bv) - ((eq? cell star-ns-cell) (intern-ns! (chez-current-ns))) - (else (var-cell-root cell))))) - -;; jolt-var-get (vars.ss): the var-get fn + deref/@ on a cell. Stack first, then -;; the original (which errors on an unbound root, matching Clojure). -(define %dyn-var-get jolt-var-get) -(set! jolt-var-get - (lambda (v) - (if (var-cell? v) - (let ((bv (dyn-binding-value v))) - (cond ((not (eq? bv dyn-no-binding)) bv) - ((eq? v star-ns-cell) (intern-ns! (chez-current-ns))) - (else (%dyn-var-get v)))) - (%dyn-var-get v)))) - -;; var-cell keys hash/compare by ns/name (jolt=2 in vars.ss already compares -;; ns/name) — stable under root mutation, so a var works as a map key (with-redefs -;; builds (hash-map (var f) v); get-thread-bindings returns a var-keyed map). -(register-hash-arm! var-cell? (lambda (x) (equal-hash (cons (var-cell-ns x) (var-cell-name x))))) - -;; --- bind the host seams the overlay references ----------------------------- -(def-var! "clojure.core" "push-thread-bindings" jolt-push-thread-bindings) -(def-var! "clojure.core" "pop-thread-bindings" jolt-pop-thread-bindings) -(def-var! "clojure.core" "get-thread-bindings" jolt-get-thread-bindings) -(def-var! "clojure.core" "__thread-bound?" jolt-thread-bound?) -(def-var! "clojure.core" "var-set" jolt-var-set) -(def-var! "clojure.core" "alter-var-root" jolt-alter-var-root) -(def-var! "clojure.core" "__local-var" jolt-local-var) -;; re-assert var-get / deref to the new (stack-aware) closures (vars.ss captured -;; the pre-chain values). -(def-var! "clojure.core" "var-get" jolt-var-get) -(def-var! "clojure.core" "deref" jolt-deref) diff --git a/host/chez/dynamic-var-defaults.ss b/host/chez/dynamic-var-defaults.ss deleted file mode 100644 index 9520dfa..0000000 --- a/host/chez/dynamic-var-defaults.ss +++ /dev/null @@ -1,70 +0,0 @@ -;; dynamic-var-defaults.ss — default values for the handful of clojure.core dynamic -;; vars that aren't emitted into the prelude (*clojure-version*, *assert*, …). Plain -;; constant def-var!s; *ns* (a namespace object) needs a value type with -;; get-see-through and map?=false and is tracked separately. The binding-stack -;; machinery (binding / var-set / thread-bound?) lives in dyn-binding.ss. Loaded -;; from rt.ss after the value model + def-var!. - -;; *clojure-version* — a map {:major 1 :minor 11 :incremental 0 :qualifier nil}. -(def-var! "clojure.core" "*clojure-version*" - (jolt-hash-map (keyword #f "major") 1 - (keyword #f "minor") 11 - (keyword #f "incremental") 0 - (keyword #f "qualifier") jolt-nil)) - -;; *unchecked-math* — jolt does no unchecked-math elision; the var reads false. -(def-var! "clojure.core" "*unchecked-math*" #f) - -;; *warn-on-reflection* — jolt has no reflection, so the var reads false; (set! -;; *warn-on-reflection* …) resolves and updates it (a no-op effect). -(def-var! "clojure.core" "*warn-on-reflection*" #f) - -;; *assert* — gates `assert`; settable/bindable (malli.assert toggles it). Default -;; true, like the JVM. -(def-var! "clojure.core" "*assert*" #t) - -;; *print-readably* — bound by pr-family / with-out-str-style code; default true. -(def-var! "clojure.core" "*print-readably*" #t) - -;; *print-meta* — when true, pr prints metadata with a ^ prefix; default false. -(def-var! "clojure.core" "*print-meta*" #f) - -;; *print-length* / *print-level* — collection print limits, honored by both -;; printers (rt.ss jolt-pr-str + printing.ss jolt-pr-readable). nil = unlimited -;; (the default); a number truncates elements / collapses depth to "#". -;; *print-length* limits a lazy/infinite seq before realizing it. -(def-var! "clojure.core" "*print-length*" jolt-nil) -(def-var! "clojure.core" "*print-level*" jolt-nil) -;; *default-data-reader-fn* — a (fn [tag value]) the reader consults for an -;; unregistered #tag before raising; nil = no default handler. -(def-var! "clojure.core" "*default-data-reader-fn*" jolt-nil) - -;; Portable clojure.core dynamic vars whose DEFAULT already matches jolt's -;; behaviour, so exposing them is sound (resolve/binding work, reads return the -;; right value) — not a silent divergence. -;; -;; *read-eval* — gates #=() read-eval. jolt's reader has no #=, so it reads true -;; (no eval-on-read happens regardless); a lib can (binding [*read-eval* false] …). -(def-var! "clojure.core" "*read-eval*" #t) -;; *print-dup* — gates print-dup (a multimethod that exists); default false. -(def-var! "clojure.core" "*print-dup*" #f) -;; *print-namespace-maps* — jolt never prints the #:ns{…} map shorthand, so the -;; var reads false (accurate); settable for code that toggles it. -(def-var! "clojure.core" "*print-namespace-maps*" #f) -;; *flush-on-newline* — jolt flushes line output; default true. -(def-var! "clojure.core" "*flush-on-newline*" #t) -;; *compile-files* — jolt has no separate compile phase that emits .class files. -(def-var! "clojure.core" "*compile-files*" #f) -;; *math-context* — BigDecimal rounding context; nil = unlimited, jolt's default. -(def-var! "clojure.core" "*math-context*" jolt-nil) -;; *command-line-args* — the args after the script/-main; nil outside a -m run. -(def-var! "clojure.core" "*command-line-args*" jolt-nil) -;; *file* — the source file being loaded; "NO_SOURCE_PATH" when none, like the JVM. -(def-var! "clojure.core" "*file*" "NO_SOURCE_PATH") - -;; REPL result/exception history. Bound by the REPL after each evaluation; nil -;; outside a REPL, which is what reading them returns here. -(def-var! "clojure.core" "*1" jolt-nil) -(def-var! "clojure.core" "*2" jolt-nil) -(def-var! "clojure.core" "*3" jolt-nil) -(def-var! "clojure.core" "*e" jolt-nil) diff --git a/host/chez/emit-image.ss b/host/chez/emit-image.ss deleted file mode 100644 index a2489cc..0000000 --- a/host/chez/emit-image.ss +++ /dev/null @@ -1,191 +0,0 @@ -;; emit-image.ss — the on-Chez compiler-image emitter. -;; -;; This is the stage2/stage3 half of the self-hosting fixpoint. The -;; analyze->emit runs ON CHEZ (jolt-ce-analyze / jolt-ce-emit, loaded from a -;; previously-built image): feed it stage1's image and it produces stage2; feed it -;; stage2 and it produces stage3. stage2 == stage3 byte-for-byte proves the -;; on-Chez compiler reproduces itself (self-hosting-bootstrap-research §4). -;; -;; Loaded after compile-eval.ss (needs jolt-ce-analyze/jolt-ce-emit/ce-scan-requires!, -;; make-analyze-ctx) and rt.ss (read-file-string, the reader's rdr-read-form). - -;; Read every top-level form from a source string (a Chez read-all). -;; Uses the same reader the spine reads single forms with. -(define (ei-read-all src) - (let ((end (string-length src))) - (let loop ((i 0) (acc '())) - (let-values (((form j) (rdr-read-form src i end))) - (if (rdr-eof? form) - (reverse acc) - (loop j (cons form acc))))))) - -;; Is `f` an (ns ...) form? (Its only role in the image is alias registration; we -;; never emit it — the def-var!s carry explicit ns names.) -(define (ei-ns-form? f) - (and (cseq? f) (cseq-list? f) - (let ((items (seq->list f))) - (and (pair? items) (symbol-t? (car items)) - (string=? (symbol-t-name (car items)) "ns"))))) - -;; ei-macro-form? / ei-defmacro->fn moved to compile-eval.ss (ce-macro-form? / -;; ce-defmacro->fn, loaded before this) — shared with the runtime defmacro spine. - -;; Cross-compile one namespace's source to a list of guard-wrapped Scheme strings. -;; Each form is analyzed with a fresh ctx — resolution is via the runtime var-table -;; + alias tables, not ctx-accumulated state, so this matches the spine's per-form -;; analyze. A defmacro emits its expander fn as (def-var! ns name ) + -;; (mark-macro! ns name) so the on-Chez analyzer can expand it. -;; Analyze -> (optionally run passes) -> emit one form. optimize? runs -;; jolt.passes/run-passes (build optimizes; the seed minter stays un-optimized so -;; the self-host fixpoint is independent of the passes). emit-top-form is the -;; top-level entry: in direct-link mode it binds jv$ for a top-level def; off -;; that mode (the minter, runtime eval) it is exactly emit, so output is unchanged. -(define jolt-ce-emit-top (var-deref "jolt.backend-scheme" "emit-top-form")) -;; Seed mint and AOT build must stay byte-deterministic, so emit the image with var -;; cell-caching OFF (compile-eval.ss turned it on for runtime eval; this file loads -;; after it). Guarded for the first re-mint pass off an older seed. -(let ((scv (var-deref "jolt.backend-scheme" "set-var-cache!"))) - (when (procedure? scv) (scv #f))) -;; Tail-frame tracing off for the mint + `jolt build`: the seed must stay a -;; byte-fixpoint, and a built app should carry no per-call trace overhead. -(let ((stf (var-deref "jolt.backend-scheme" "set-trace-frames!"))) - (when (procedure? stf) (stf #f))) -(define (ei-compile-form ctx f optimize?) - (let ((ir (jolt-ce-analyze ctx f))) - (jolt-ce-emit-top (if optimize? (jolt-ce-run-passes ir ctx) ir)))) - -;; The emitted `(def-var! …)(mark-macro! …)` pair for a defmacro, guard-wrapped -;; (tolerant) or bare (strict) to match guard?. -(define (ei-macro-string ns-name nm scm guard?) - (if guard? - (string-append "(guard (e (#t #f))\n (def-var! " (ei-str-lit ns-name) " " (ei-str-lit nm) - "\n " scm ")\n (mark-macro! " (ei-str-lit ns-name) " " (ei-str-lit nm) "))") - (string-append "(def-var! " (ei-str-lit ns-name) " " (ei-str-lit nm) "\n " scm - ")\n(mark-macro! " (ei-str-lit ns-name) " " (ei-str-lit nm) ")"))) - -;; Cross-compile one namespace's source to a list of Scheme strings — shared by -;; the seed minter (ei-emit-ns: optimize? #f, guard? #t — tolerant, skips a form -;; that fails to emit) and `jolt build` (bld-emit-ns: optimize? #t, guard? #f — -;; strict, a failing form errors the build). -;; A per-form transform applied to each read form before emit — the build sets it -;; to the data-reader rewrite (loader.ss ldr-apply-readers) so a registered #tag -;; literal compiles in a `jolt build` the same as it does in an interpreted load. -;; #f (the default, and during the seed mint where loader.ss isn't loaded) is no -;; transform, so emit-image.ss carries no loader dependency. -(define ei-emit-form-hook (make-parameter #f)) - -(define (ei-emit-ns* ns-name src optimize? guard?) - ;; set the ns before reading so ::kw auto-resolves against this ns (the runtime - ;; loader reads form-by-form after the ns form sets it; the cross-compile reads - ;; all forms up front, so set it here). - (set-chez-ns! ns-name) - (let ((hook (ei-emit-form-hook))) - (let loop ((forms (ei-read-all src)) (acc '())) - (if (null? forms) - (reverse acc) - (let ((f (let ((f0 (car forms))) (if hook (hook f0) f0)))) - (ce-scan-requires! f ns-name) - (cond - ((ei-ns-form? f) (loop (cdr forms) acc)) - ((ce-macro-form? f) - (let-values (((nm fn-form) (ce-defmacro->fn f))) - (let ((scm (if guard? - (guard (e (#t #f)) (ei-compile-form (make-analyze-ctx ns-name) fn-form optimize?)) - (ei-compile-form (make-analyze-ctx ns-name) fn-form optimize?)))) - (loop (cdr forms) - (if (and guard? (not scm)) acc - (cons (ei-macro-string ns-name nm scm guard?) acc)))))) - (else - (let ((scm (if guard? - (guard (e (#t #f)) (ei-compile-form (make-analyze-ctx ns-name) f optimize?)) - (ei-compile-form (make-analyze-ctx ns-name) f optimize?)))) - (loop (cdr forms) - (if (and guard? (not scm)) acc - (cons (if guard? (string-append "(guard (e (#t #f))\n " scm ")") scm) acc))))))))))) - -(define (ei-emit-ns ns-name src) (ei-emit-ns* ns-name src #f #t)) - -;; --- DCE record producer ---------------------------------------------------- -;; Cross-compile a namespace's source to tree-shaking records — the app/library -;; counterpart to dce-blob-records (the prelude). The shake itself and all dce-* -;; helpers live in dce.ss; this stays here because it drives the ei-* compiler. A -;; top-level def becomes a prunable record; any other form a kept (side-effecting) -;; record whose refs are roots. A macro is prunable — its expander isn't called at -;; runtime in an AOT build. -(define (ei-emit-ns-records ns-name src) - (set-chez-ns! ns-name) ; ::kw resolves against this ns (see ei-emit-ns*) - (let loop ((forms (ei-read-all src)) (acc '())) - (if (null? forms) - (reverse acc) - (let ((f (car forms))) - (ce-scan-requires! f ns-name) - (cond - ((ei-ns-form? f) (loop (cdr forms) acc)) - ((ce-macro-form? f) - (let-values (((nm fn-form) (ce-defmacro->fn f))) - (let* ((ctx (make-analyze-ctx ns-name)) - (ir (jolt-ce-run-passes (jolt-ce-analyze ctx fn-form) ctx)) - (str (ei-macro-string ns-name nm (jolt-ce-emit-top ir) #f)) - (refs (dce-collect-refs '() ir))) - (loop (cdr forms) (cons (dce-rec #f (string-append ns-name "/" nm) refs str) acc))))) - (else - (let* ((ctx (make-analyze-ctx ns-name)) - (ir (jolt-ce-run-passes (jolt-ce-analyze ctx f) ctx)) - (str (jolt-ce-emit-top ir)) - (fqn (dce-def-fqn ir)) - (refs (dce-collect-refs '() ir))) - (loop (cdr forms) - (cons (if fqn (dce-rec #f fqn refs str) (dce-rec #t #f refs str)) acc))))))))) - -;; Scheme string literal for a ns/name — uses the runtime's own writer -;; (printable ASCII identifiers only here). -(define (ei-str-lit s) (with-output-to-string (lambda () (write s)))) - -;; The compiler namespaces, in load order. The passes (fold/inline/types + the -;; jolt.passes façade) load after ir so run-passes is available to the back end; -;; fold/inline/types come before the façade that :refers them. -(define ei-compiler-ns-files - (list (cons "jolt.ir" "jolt-core/jolt/ir.clj") - (cons "jolt.analyzer" "jolt-core/jolt/analyzer.clj") - (cons "jolt.backend-scheme" "jolt-core/jolt/backend_scheme.clj") - (cons "jolt.passes.fold" "jolt-core/jolt/passes/fold.clj") - (cons "jolt.passes.numeric" "jolt-core/jolt/passes/numeric.clj") - (cons "jolt.passes.inline" "jolt-core/jolt/passes/inline.clj") - (cons "jolt.passes.types.lattice" "jolt-core/jolt/passes/types/lattice.clj") - (cons "jolt.passes.types.check" "jolt-core/jolt/passes/types/check.clj") - (cons "jolt.passes.types" "jolt-core/jolt/passes/types.clj") - (cons "jolt.passes" "jolt-core/jolt/passes.clj"))) - -;; The clojure.core tiers + stdlib namespaces, in load order. -;; Re-emitting these on Chez is the -;; prelude half of the fixpoint (the whole emitted system reproducing itself). -(define ei-prelude-ns-files - (append - (map (lambda (tf) (cons "clojure.core" (string-append "jolt-core/clojure/core/" tf ".clj"))) - '("00-syntax" "00-kernel" "10-seq" "20-coll" "21-coll" "22-coll" "25-sorted" "30-macros" "40-lazy" "50-io")) - (list (cons "clojure.string" "stdlib/clojure/string.clj") - (cons "clojure.walk" "stdlib/clojure/walk.clj") - (cons "clojure.template" "stdlib/clojure/template.clj") - (cons "clojure.edn" "stdlib/clojure/edn.clj") - (cons "clojure.set" "stdlib/clojure/set.clj") - (cons "clojure.pprint" "stdlib/clojure/pprint.clj")))) - -;; Join a list of form strings with "\n", no trailing newline. -(define (ei-join forms) - (let join ((fs forms) (out "")) - (cond - ((null? fs) out) - ((string=? out "") (join (cdr fs) (car fs))) - (else (join (cdr fs) (string-append out "\n" (car fs))))))) - -;; Re-emit the whole list of (ns . file) pairs ON CHEZ as one Scheme string. -(define (ei-emit-ns-files nfs) - (ei-join (apply append - (map (lambda (nf) (ei-emit-ns (car nf) (read-file-string (cdr nf)))) nfs)))) - -;; Emit the compiler image (jolt.ir + jolt.analyzer + jolt.backend-scheme) on Chez. -(define (jolt-emit-image) (ei-emit-ns-files ei-compiler-ns-files)) - -;; Emit the clojure.core prelude (all tiers + stdlib) on Chez — the prelude half of -;; the self-hosting fixpoint. -(define (jolt-emit-prelude) (ei-emit-ns-files ei-prelude-ns-files)) diff --git a/host/chez/host-contract.ss b/host/chez/host-contract.ss deleted file mode 100644 index 9593a0e..0000000 --- a/host/chez/host-contract.ss +++ /dev/null @@ -1,528 +0,0 @@ -;; host-contract.ss — the jolt.host contract on Chez. -;; -;; The portable seam between jolt-core (analyzer/IR/emitter, cross-compiled to -;; Scheme) and the host. Every -;; contract fn is def-var!'d into the "jolt.host" namespace so the cross-compiled -;; jolt.analyzer / jolt.backend-scheme — whose unqualified form-*/resolve-global/ -;; ... refs lower to (var-deref "jolt.host" ...) — resolve here at runtime. -;; -;; This is what puts analyze->IR->emit ON CHEZ. It runs -;; over the Chez data reader's forms (reader.ss): symbols are symbol-t, lists are -;; cseq (list?), () is empty-list-t, vectors/maps are pvec/pmap, sets and #tag/ -;; regex/inst/uuid are pmaps tagged :jolt/type, chars are NATIVE Chez chars. -;; -;; Loaded after rt.ss + reader.ss + the core prelude; before the compiler image. - -;; --- the analyze ctx -------------------------------------------------------- -;; ctx is opaque to the analyzer (only ever threaded to these contract fns); we -;; make it a box carrying the compile namespace. The var/ns registry it consults -;; is the global var-table (rt.ss). -(define-record-type chez-actx (fields (mutable cns)) (nongenerative chez-actx-v1)) -(define (make-analyze-ctx ns) (make-chez-actx ns)) - -;; Interned keywords reused for form tags + resolve-global's result map. -(define hc-kw-jolt-type (keyword "jolt" "type")) -(define hc-kw-jolt-set (keyword "jolt" "set")) -(define hc-kw-jolt-tagged (keyword "jolt" "tagged")) -(define hc-kw-value (keyword #f "value")) -(define hc-kw-tag (keyword #f "tag")) -(define hc-kw-form (keyword #f "form")) -(define hc-kw-kind (keyword #f "kind")) -(define hc-kw-ns (keyword #f "ns")) -(define hc-kw-name (keyword #f "name")) -(define hc-kw-var (keyword #f "var")) -(define hc-kw-unresolved (keyword #f "unresolved")) -(define hc-kw-class (keyword #f "class")) -(define hc-kw-num-ret (keyword #f "num-ret")) -(define hc-kw-double (keyword #f "double")) -(define hc-kw-long (keyword #f "long")) -(define hc-kw-regex (keyword #f "regex")) -(define hc-kw-inst (keyword #f "#inst")) -(define hc-kw-uuid (keyword #f "#uuid")) -(define hc-kw-bigdec (keyword #f "bigdec")) - -;; --- form predicates -------------------------------------------------------- -(define (hc-sym? x) (symbol-t? x)) -;; ANY non-empty seq is a list form for analysis (a macro/eval form built via -;; concat/map/cons is a lazy cseq with list?=#f, but evaluating it still means -;; calling its head) — not just reader-built lists. -;; a lazy seq is a list form too: a macro that builds its expansion with map/for -;; (now a LazySeq, not an eager cseq) and splices it must still analyze. -(define (hc-list? x) (or (empty-list-t? x) (cseq? x) (jolt-lazyseq? x))) -(define (hc-vec? x) (pvec? x)) -(define (hc-map? x) (and (pmap? x) (jolt-nil? (jolt-get x hc-kw-jolt-type)))) -;; A set form is the reader's tagged map {:jolt/type :jolt/set :value } OR a -;; real pset value — a macro template's #{...} expansion (syntax-quote.ss jolt-sqset) -;; produces a pset, which the analyzer must still read as a set literal. -(define (hc-set? x) - (or (pset? x) - (and (pmap? x) (eq? (jolt-get x hc-kw-jolt-type) hc-kw-jolt-set)))) -(define (hc-char? x) (char? x)) -(define (hc-keyword? x) (keyword? x)) -(define (hc-literal? x) - (or (jolt-nil? x) (boolean? x) (number? x) (string? x) (keyword-t? x) (char? x))) - -(define (hc-tagged-of x tag) - (and (pmap? x) - (eq? (jolt-get x hc-kw-jolt-type) hc-kw-jolt-tagged) - (eq? (jolt-get x hc-kw-tag) tag))) -(define (hc-regex? x) (regex-t? x)) ; #"..." reads as a regex VALUE now -(define (hc-inst? x) (hc-tagged-of x hc-kw-inst)) -(define (hc-uuid? x) (hc-tagged-of x hc-kw-uuid)) -(define (hc-bigdec? x) (hc-tagged-of x hc-kw-bigdec)) -(define (hc-bigdec-source x) (jolt-get x hc-kw-form)) -;; A live namespace value spliced into a form (e.g. `(str ~*ns*) in a macro): -;; the analyzer can't carry an opaque runtime value, so recognize a jns and -;; reconstruct it by name at the call site. -(define (hc-ns-value? x) (jns? x)) -(define (hc-ns-value-name x) (jns-name x)) -;; a live Var value spliced into a form (a macro that does `(~v …)` with v a -;; resolved var) — the analyzer turns it into a :the-var reference by ns+name. -(define (hc-var-value? x) (var-cell? x)) -(define (hc-var-value-ns x) (var-cell-ns x)) -(define (hc-var-value-name x) (var-cell-name x)) - -;; *unchecked-math* read at compile time: when truthy (a file's (set! -;; *unchecked-math* …)), the analyzer rewrites +/-/*/inc/dec to their wrapping -;; unchecked-* forms for the rest of that file, like the JVM. -(define (hc-unchecked-math?) - (jolt-truthy? (guard (e (#t #f)) (var-deref "clojure.core" "*unchecked-math*")))) - -;; --- form accessors --------------------------------------------------------- -(define (hc-char-code x) (char->integer x)) ; native Chez char -> codepoint -(define (hc-sym-name x) (symbol-t-name x)) -;; The reader stores an unqualified symbol's ns inconsistently (#f, '(), or -;; jolt-nil — see converters.ss). The contract is jolt-nil for unqualified (the -;; analyzer tests (nil? ns)), so normalize; a real ns string passes through. -(define (hc-sym-ns x) - (let ((ns (symbol-t-ns x))) - (if (and ns (not (jolt-nil? ns)) (not (null? ns))) ns jolt-nil))) -(define (hc-sym-meta x) - (let ((m (symbol-t-meta x))) - (if (and m (not (jolt-nil? m)) (not (null? m))) m jolt-nil))) -;; Metadata the reader attached to a collection literal (vec/map/set/list), or -;; jolt-nil. The analyzer re-emits a runtime (with-meta ..) for a meta-carrying -;; vector/map/set so the value keeps its metadata. -(define (hc-coll-meta x) (jolt-meta x)) - -;; list items -> jolt vector (pvec); the analyzer mapv's over the result. -(define (hc-elements x) - (cond ((empty-list-t? x) empty-pvec) - ((or (cseq? x) (jolt-lazyseq? x)) (make-pvec (list->vector (seq->list x)))) - (else empty-pvec))) -(define (hc-vec-items x) x) ; already a pvec -(define (hc-set-items x) - (if (pset? x) - (apply jolt-vector (pset-fold x cons '())) - (jolt-get x hc-kw-value))) -(define (hc-map-pairs x) - (let ((kv (hashtable-ref rdr-map-order x #f))) - (if kv - ;; reader-built map literal: emit pairs in SOURCE order (kv = k1 v1 k2 v2 …) - ;; so the analyzer evaluates the values left-to-right. - (let loop ((kv kv) (acc '())) - (if (null? kv) (apply jolt-vector (reverse acc)) - (loop (cddr kv) (cons (jolt-vector (car kv) (cadr kv)) acc)))) - ;; a runtime/non-reader map: pmap iteration order - (let loop ((ks (if (jolt-nil? (jolt-seq (jolt-keys x))) '() - (seq->list (jolt-seq (jolt-keys x))))) (acc '())) - (if (null? ks) (apply jolt-vector (reverse acc)) - (loop (cdr ks) (cons (jolt-vector (car ks) (jolt-get x (car ks))) acc))))))) -(define (hc-regex-source x) (regex-t-source x)) -(define (hc-inst-source x) (jolt-get x hc-kw-form)) -(define (hc-uuid-source x) (jolt-get x hc-kw-form)) - -;; Source position for a list form: the reader stamps :line/:column (+ :file when -;; compiling a file) into the form's metadata. Return a clean {:line :column -;; :file?} map, or nil for a synthetic/macro-built form that carries none. -(define hc-kw-line (keyword #f "line")) -(define hc-kw-column (keyword #f "column")) -(define hc-kw-file (keyword #f "file")) -(define (hc-form-position x) - (let ((m (jolt-meta x))) - (if (and (pmap? m) (not (jolt-nil? (jolt-get m hc-kw-line)))) - (let ((line (jolt-get m hc-kw-line)) - (col (jolt-get m hc-kw-column)) - (file (jolt-get m hc-kw-file))) - (if (jolt-nil? file) - (jolt-hash-map hc-kw-line line hc-kw-column col) - (jolt-hash-map hc-kw-line line hc-kw-column col hc-kw-file file))) - jolt-nil))) - -;; --- special forms ---------------------------------------------------------- -;; Mirrors host_iface special-names + interop-head? — forms the analyzer marks -;; uncompilable (the handled specials are dispatched in analyze-list BEFORE this). -;; `eval` is NOT here: it is a clojure.core FUNCTION on the spine (compile-eval.ss -;; def-var!s it), so it must resolve as an ordinary var, not punt. -;; `defmacro` stays special — the spine intercepts it before analysis. -(define hc-special-names - '("quote" "syntax-quote" "unquote" "unquote-splicing" "do" "if" "def" - "defmacro" "fn*" "let*" "loop*" "recur" "throw" "try" "set!" "new" - "." "gen-class" "monitor-enter" "monitor-exit" "letfn")) -(define (hc-interop-head? name) - (let ((n (string-length name))) - (and (> n 1) - (not (string=? name "..")) ; the .. threading macro, not an interop form - (or (char=? (string-ref name 0) #\.) - (char=? (string-ref name (- n 1)) #\.))))) -(define (hc-special? name) - (if (or (member name hc-special-names) (hc-interop-head? name)) #t #f)) - -;; --- compile-time environment ----------------------------------------------- -(define (hc-current-ns ctx) (chez-actx-cns ctx)) -(define (hc-late-bind? ctx) #t) ; Chez has no interpreter to punt to - -;; Resolve a global symbol to its var cell against the compile ns then clojure.core -;; (a qualified ns wins). Shared by resolve-global / form-macro? / form-expand-1. -;; Normalizes the reader's unqualified-ns sentinel (#f / '() / jolt-nil) like -;; hc-sym-ns, so an unqualified symbol never looks up a bogus "#f" namespace. -(define (hc-resolve-cell ctx sym) - (let* ((nm (symbol-t-name sym)) - (sns (symbol-t-ns sym)) - (qualified (and sns (not (jolt-nil? sns)) (not (null? sns)) sns))) - (if qualified - ;; a qualified ns may be a require :as alias (s/split -> clojure.string/split) - (let ((target (or (chez-resolve-alias (chez-actx-cns ctx) qualified) qualified))) - (var-cell-lookup target nm)) - (or (let ((c (var-cell-lookup (chez-actx-cns ctx) nm))) - ;; an undefined forward-intern must not shadow a real referred - ;; or clojure.core var — e.g. the compiler ns referencing `set`, - ;; which late-binds (interns `jolt.backend-scheme/set` undefined) - ;; and would otherwise hide clojure.core/set on the mint fixpoint. - (and c (var-cell-defined? c) c)) - ;; a :refer'd name resolves to its source ns - (let ((ref (chez-resolve-refer (chez-actx-cns ctx) nm))) - (and ref (var-cell-lookup ref nm))) - (var-cell-lookup "clojure.core" nm))))) - -;; Runtime macros: a defmacro is emitted into the prelude as a -;; def-var! of its cross-compiled expander fn plus (mark-macro! ns name), so the -;; var cell is flagged a macro (rt.ss var-macro-table). form-macro? checks the -;; flag; form-expand-1 applies the expander to the unevaluated arg forms (the rest -;; of the list), and the analyzer re-analyzes the returned form. -(define (hc-macro? ctx sym) - (macro-var? (hc-resolve-cell ctx sym))) -;; Clojure parity: a macro expansion inherits the call form's source position, so -;; errors/traces in macro-generated code point at the macro call site. Carry it -;; onto the top of a LIST expansion (code) that has none of its own — merged under -;; any meta the macro set, leaving collection literals (runtime data) alone. The -;; recursion through analyze re-expands inner macros, so each level's top form -;; picks up the position the same way (as the reference compiler does). -(define (hc-propagate-pos src dst) - (if (and (cseq? dst) (cseq-list? dst)) - (let ((sp (hc-form-position src)) - (dm (jolt-meta dst))) - (if (and (pmap? sp) - (or (jolt-nil? dm) (jolt-nil? (jolt-get dm hc-kw-line)))) - (jolt-with-meta dst - (if (pmap? dm) - (pmap-fold-fwd sp (lambda (k v acc) (jolt-assoc1 acc k v)) dm) - sp)) - dst)) - dst)) - -;; A set literal reads as the tagged set-form {:jolt/type :jolt/set :value [...]} -;; for the analyzer, but a macro must see a real set value (Clojure parity, so -;; (set? arg) / seq / conj work — hiccup's compiler does this). Convert a set-form -;; argument to a set; elements stay as read (a deeply-nested set literal inside -;; another form is rarer and left for the analyzer). -(define (hc-macro-arg x) - (if (rdr-set-form? x) - (let ((items (jolt-get x rdr-kw-value))) - (let loop ((i 0) (s empty-pset)) - (if (fx>=? i (pvec-count items)) s - (loop (fx+ i 1) (pset-conj s (pvec-nth-d items i jolt-nil)))))) - x)) -;; &form and &env are bound (as dynamic vars) around the expander call, so a -;; macro body can read the call form / lexical env without changing the calling -;; convention. The analyzer passes amp-env (the in-scope locals); macroexpand-1 -;; has none, so it defaults to {}. -(define hc-amp-form-cell (declare-var! "clojure.core" "&form")) -(define hc-amp-env-cell (declare-var! "clojure.core" "&env")) -(define (hc-expand-1 ctx form . maybe-env) - (let* ((items (seq->list form)) - (head (car items)) - (args (map hc-macro-arg (cdr items))) - (expander (var-cell-root (hc-resolve-cell ctx head))) - (amp-env (if (pair? maybe-env) (car maybe-env) (jolt-hash-map)))) - (dynamic-wind - (lambda () (jolt-push-thread-bindings - (jolt-hash-map hc-amp-form-cell form hc-amp-env-cell amp-env))) - (lambda () (hc-propagate-pos form (apply jolt-invoke expander args))) - (lambda () (jolt-pop-thread-bindings))))) - -;; Classify a global (non-local) symbol reference against the var registry: -;; {:kind :var :ns NS :name NAME} — a defined var (compile ns / clojure.core) -;; {:kind :unresolved :name NAME} — not found (late-bind -> var-ref @ compile ns; -;; a qualified one -> host-static in the analyzer) -;; No :host branch: there is no separate native-op env — the hot -;; clojure.core primitives (+,-,map,...) are declared in clojure.core below so -;; they classify as :var and the emitter's native-op path lowers them. -;; A var's declared numeric return (^double/^long on its name) -> :double/:long, -;; read from its meta. Lets jolt.passes.numeric type a call to it. -(define (hc-cell-num-ret cell) - (let ((m (and cell (hashtable-ref var-meta-table cell #f)))) - (and m (let* ((t (jolt-get m hc-kw-tag)) ; ^double/^long is a symbol; ^"double" a string - (s (cond ((symbol-t? t) (symbol-t-name t)) ((string? t) t) (else #f)))) - (cond ((equal? s "double") hc-kw-double) - ((equal? s "long") hc-kw-long) - (else #f)))))) - -;; A slash-free dotted symbol whose final segment is Capitalized is a class -;; reference (java.util.Map, clojure.lang.Named) — Clojure has no such vars. With -;; no JVM classes, jolt models a class as its name string, so the symbol -;; self-evaluates to that string (the analyzer emits a :const). This lets a lib -;; extend a protocol to / instance?-check a host class jolt has no shim for. -(define (hc-fq-class-name? nm) - (let ((n (string-length nm))) - (let loop ((i (fx- n 1))) - (cond ((fx? (string-length nm) 0) (char-upper-case? (string-ref nm 0)) - (hashtable-ref class-statics-tbl nm #f)) - (jolt-hash-map hc-kw-kind hc-kw-class hc-kw-name nm)) - (else (jolt-hash-map hc-kw-kind hc-kw-unresolved hc-kw-name nm)))))) - -(define (hc-intern! ctx ns-name nm) (declare-var! ns-name nm) jolt-nil) - -;; --- syntax-quote lowering --------------------------------------------------- -;; Lowers a `form -;; to CONSTRUCTION CODE — Chez reader forms calling __sqcat/__sqvec/__sqmap/ -;; __sqset/__sq1 + quote — that the analyzer re-analyzes, so a backtick compiles -;; with zero runtime cost (read -> macroexpand -> compile). Symbols resolve to -;; clojure.core / the compile ns; a foo# auto-gensym is stable within one `. -(define hc-special-symbols - '("quote" "syntax-quote" "unquote" "unquote-splicing" "do" "if" "def" - "defmacro" "fn*" "let*" "loop*" "recur" "throw" "try" "set!" "var" - "new" ".")) -(define (hc-special-symbol? nm) (and (member nm hc-special-symbols) #t)) - -(define hc-sq-gensym-counter 0) -(define (hc-sq-gensym base) - (set! hc-sq-gensym-counter (+ hc-sq-gensym-counter 1)) - (jolt-symbol #f (string-append base "__" (number->string hc-sq-gensym-counter) "__auto"))) - -(define (hc-sym nm) (jolt-symbol #f nm)) -;; is `x` a non-empty list FORM whose head is the unqualified symbol `nm`? -;; Detect a (unquote …) / (unquote-splicing …) form in a syntax-quote template. -;; Any seq counts, not just a proper list: a macro that builds the template with -;; map/for (e.g. deftype's rewrite-set) yields a LAZY seq, and its ~unquotes must -;; still be recognized. -;; head symbol matches name nm, bare or clojure.core-qualified — the reader -;; produces clojure.core/unquote(-splicing) for ~/~@ (JVM parity), and this is -;; only used to spot those heads in syntax-quote templates. -(define (hc-head-is? x nm) - (and (cseq? x) - (let ((h (seq-first x))) - (and (symbol-t? h) (string=? (symbol-t-name h) nm) - (let ((ns (hc-sym-ns h))) - (or (jolt-nil? ns) (and (string? ns) (string=? ns "clojure.core")))))))) -(define (hc-second x) (seq-first (jolt-seq (seq-more x)))) - -(define (hc-sq-symbol ctx form gsmap) - (let ((sns (hc-sym-ns form)) (nm (symbol-t-name form))) - (if (jolt-nil? sns) - (cond - ;; foo# -> a stable per-` auto-gensym - ((and (> (string-length nm) 0) - (char=? (string-ref nm (- (string-length nm) 1)) #\#)) - (or (hashtable-ref gsmap nm #f) - (let ((g (hc-sq-gensym (substring nm 0 (- (string-length nm) 1))))) - (hashtable-set! gsmap nm g) g))) - ((hc-special-symbol? nm) form) ; special form: leave bare - ((hc-interop-head? nm) form) ; interop (.method / Class. / .-field): bare - ;; a fully-qualified class name (java.util.Map, clojure.lang.ILookup) is - ;; a class token, not a var to namespace-qualify — leave it bare, as - ;; Clojure's syntax-quote resolves it to the class. - ((hc-fq-class-name? nm) form) - ;; the compile ns's OWN def shadows clojure.core — a name the ns - ;; excluded and redefined (e.g. core.logic's `==` after - ;; (:refer-clojure :exclude [==])), or any ns-local redefinition. - ;; Referred names live in a separate table, so this only hits a real - ;; local intern, matching how the analyzer resolves the bare symbol. - ((var-cell-lookup (chez-actx-cns ctx) nm) (jolt-symbol (chez-actx-cns ctx) nm)) - ;; a name the compile ns excluded from clojure.core (:refer-clojure - ;; :exclude) is not clojure.core/nm even before the ns defines its own — - ;; qualify to the compile ns, like Clojure (core.logic.fd's `==`). - ((chez-core-excluded? (chez-actx-cns ctx) nm) (jolt-symbol (chez-actx-cns ctx) nm)) - ((var-cell-lookup "clojure.core" nm) (jolt-symbol "clojure.core" nm)) - ;; a name referred into the compile ns (:require :refer / :use :only) - ;; qualifies to its SOURCE ns, not the compile ns — so a macro that - ;; syntax-quotes a referred var (e.g. clojure.tools.logging/spy using - ;; clojure.pprint's pprint) expands to the real var. - ((chez-resolve-refer (chez-actx-cns ctx) nm) - => (lambda (target) (jolt-symbol target nm))) - (else (jolt-symbol (chez-actx-cns ctx) nm))) ; else: qualify to compile ns - ;; qualified: if the ns part is an :as alias in the compile ns, resolve it - ;; to the target namespace — Clojure resolves the alias part of a qualified - ;; symbol in syntax-quote, so a macro's `impl/foo` expands to its real - ;; (clojure.tools.logging.impl/foo) name and stays unambiguous even when - ;; another loaded ns shares the alias's short name. Otherwise - ;; leave it as written (a real ns or an interop class token). - (let ((target (chez-resolve-alias (chez-actx-cns ctx) sns))) - (if target (jolt-symbol target nm) form))))) - -(define (hc-sq-lower ctx form gsmap) - (cond - ((hc-head-is? form "unquote") (hc-second form)) - ((hc-head-is? form "unquote-splicing") - (jolt-throw (jolt-ex-info "~@ used outside of a list or vector in syntax-quote" - (jolt-hash-map)))) - ((hc-literal? form) form) - ((symbol-t? form) (jolt-list (hc-sym "quote") (hc-sq-symbol ctx form gsmap))) - ((hc-list? form) - (apply jolt-list (hc-sym "__sqcat") - (map (lambda (it) (hc-sq-lower-part ctx it gsmap)) (seq->list form)))) - ((hc-vec? form) - (apply jolt-list (hc-sym "__sqvec") - (map (lambda (it) (hc-sq-lower-part ctx it gsmap)) (seq->list form)))) - ((hc-set? form) - (apply jolt-list (hc-sym "__sqset") - (map (lambda (it) (hc-sq-lower-part ctx it gsmap)) (seq->list (hc-set-items form))))) - ((hc-map? form) - (apply jolt-list (hc-sym "__sqmap") - (let loop ((pairs (seq->list (hc-map-pairs form))) (acc '())) - (if (null? pairs) (reverse acc) - (let ((p (seq->list (car pairs)))) - (loop (cdr pairs) - (cons (hc-sq-lower ctx (cadr p) gsmap) - (cons (hc-sq-lower ctx (car p) gsmap) acc)))))))) - (else (jolt-list (hc-sym "quote") form)))) ; tagged (char/regex/...) etc. - -;; a list/vector/set element: a ~@ splice passes through (its seq is spliced by -;; __sqcat), any other item is wrapped (__sq1 ) so __sqcat flattens it. -(define (hc-sq-lower-part ctx item gsmap) - (if (hc-head-is? item "unquote-splicing") - (hc-second item) - (jolt-list (hc-sym "__sq1") (hc-sq-lower ctx item gsmap)))) - -(define (hc-syntax-quote-lower ctx inner) - (hc-sq-lower ctx inner (make-hashtable string-hash string=?))) -;; a ^Type param hint: name is the tag (a symbol, sometimes a string). Resolve it -;; against the record registry (records.ss) so the inference seeds the param as -;; that record — the open-world / cross-ns path where no caller type is inferred. -(define (hc-record-tag-name name) - (cond ((symbol-t? name) (symbol-t-name name)) - ((string? name) name) - (else #f))) -(define (hc-record-type? ctx name) - (let ((nm (hc-record-tag-name name))) - (if (and nm (chez-find-ctor-key nm (chez-current-ns))) #t #f))) -(define (hc-record-ctor-key ctx name) - (let ((nm (hc-record-tag-name name))) - (or (and nm (chez-find-ctor-key nm (chez-current-ns))) jolt-nil))) -;; The fully-qualified deftype tag ("ns.Name") IFF `class` names a deftype DEFINED -;; in the ctx's compile ns — the analyzer qualifies a bare (Name. …) to it, so a -;; deftype doesn't shadow a same-named built-in host class in an unrelated ns -;; (rewrite-clj imports java.io.PushbackReader; tools.reader defines its own). Strict: -;; only this ns's own def (the preferred shape key) counts, not the global -;; simple-name fallback, so a ns that merely uses the built-in resolves nil. -(define (hc-deftype-ctor-class ctx class) - (let* ((nm (jolt-str-render-one class)) - (cns (hc-current-ns ctx)) - (key (string-append cns "/->" nm))) - (if (hashtable-ref chez-record-shapes-tbl key #f) - (string-append cns "." nm) - jolt-nil))) -;; record + protocol-method shapes for the inference, from the runtime registries -;; (records.ss) populated as deftype/defprotocol forms load. -(define (hc-record-shapes ctx) (chez-record-shapes-map)) -(define (hc-protocol-methods ctx) (chez-protocol-methods-map)) -;; Optimization gate. Off for ordinary runs (open world, redefinition); `jolt -;; build` flips it on during app emission for release/optimized modes (closed -;; world), turning on the inference + flatten + scalar-replace passes. -(define hc-optimize? #f) -(define (set-optimize! on) (set! hc-optimize? on)) -(define (hc-inline-enabled? ctx) hc-optimize?) -;; Inline-body registry: jolt.passes stashes an inline-eligible defn's -;; {:params :body :nhints :ret} here (keyed ns/name) as its form is optimized; -;; jolt.passes.inline fetches it to splice the body at a call site. The stash is an -;; opaque jolt value to the host — IR maps round-tripping through the table. -(define inline-stash-table (make-hashtable string-hash string=?)) -(define (hc-stash-inline! ctx ns-name nm m) - (hashtable-set! inline-stash-table (string-append ns-name "/" nm) m) jolt-nil) -(define (hc-inline-ir ctx ns-name nm) - (or (hashtable-ref inline-stash-table (string-append ns-name "/" nm) #f) jolt-nil)) - -;; --- declare the hot clojure.core primitives so resolve-global sees them ------ -;; (mirrors backend_scheme.clj native-ops keys — the emitter lowers these inline, -;; so the declared cell's unbound root is never deref'd.) -(for-each (lambda (nm) (declare-var! "clojure.core" nm)) - '("+" "-" "*" "/" "<" ">" "<=" ">=" "=" "inc" "dec" "not" "min" "max" - "mod" "rem" "quot" "vector" "hash-map" "hash-set" "conj" "get" "nth" "count" - "assoc" "dissoc" "contains?" "empty?" "peek" "pop" "first" "rest" "next" "seq" - "cons" "list" "reverse" "last" "map" "filter" "remove" "reduce" "into" "concat" - "apply" "range" "take" "drop" "keys" "vals" "even?" "odd?" "pos?" "neg?" - "zero?" "identity" "ex-info")) - -;; --- install: bind the contract into the jolt.host namespace ----------------- -(define (hc-install!) - (def-var! "jolt.host" "form-sym?" hc-sym?) - (def-var! "jolt.host" "form-sym-name" hc-sym-name) - (def-var! "jolt.host" "form-sym-ns" hc-sym-ns) - (def-var! "jolt.host" "form-sym-meta" hc-sym-meta) - (def-var! "jolt.host" "form-coll-meta" hc-coll-meta) - (def-var! "jolt.host" "form-list?" hc-list?) - (def-var! "jolt.host" "form-vec?" hc-vec?) - (def-var! "jolt.host" "form-map?" hc-map?) - (def-var! "jolt.host" "form-set?" hc-set?) - (def-var! "jolt.host" "form-char?" hc-char?) - (def-var! "jolt.host" "form-char-code" hc-char-code) - (def-var! "jolt.host" "form-literal?" hc-literal?) - (def-var! "jolt.host" "form-keyword?" hc-keyword?) - (def-var! "jolt.host" "form-regex?" hc-regex?) - (def-var! "jolt.host" "form-inst?" hc-inst?) - (def-var! "jolt.host" "form-uuid?" hc-uuid?) - (def-var! "jolt.host" "form-ns-value?" hc-ns-value?) - (def-var! "jolt.host" "form-ns-value-name" hc-ns-value-name) - (def-var! "jolt.host" "form-var-value?" hc-var-value?) - (def-var! "jolt.host" "form-var-value-ns" hc-var-value-ns) - (def-var! "jolt.host" "form-var-value-name" hc-var-value-name) - (def-var! "jolt.host" "unchecked-math?" hc-unchecked-math?) - (def-var! "jolt.host" "form-bigdec?" hc-bigdec?) - (def-var! "jolt.host" "form-bigdec-source" hc-bigdec-source) - (def-var! "jolt.host" "form-elements" hc-elements) - (def-var! "jolt.host" "form-vec-items" hc-vec-items) - (def-var! "jolt.host" "form-set-items" hc-set-items) - (def-var! "jolt.host" "form-map-pairs" hc-map-pairs) - (def-var! "jolt.host" "form-regex-source" hc-regex-source) - (def-var! "jolt.host" "form-inst-source" hc-inst-source) - (def-var! "jolt.host" "form-uuid-source" hc-uuid-source) - (def-var! "jolt.host" "form-position" hc-form-position) - (def-var! "jolt.host" "form-special?" hc-special?) - (def-var! "jolt.host" "compile-ns" hc-current-ns) - (def-var! "jolt.host" "late-bind?" hc-late-bind?) - (def-var! "jolt.host" "form-macro?" hc-macro?) - (def-var! "jolt.host" "form-expand-1" hc-expand-1) - (def-var! "jolt.host" "resolve-global" hc-resolve-global) - (def-var! "jolt.host" "host-intern!" hc-intern!) - (def-var! "jolt.host" "form-syntax-quote-lower" hc-syntax-quote-lower) - (def-var! "jolt.host" "record-type?" hc-record-type?) - (def-var! "jolt.host" "record-ctor-key" hc-record-ctor-key) - (def-var! "jolt.host" "deftype-ctor-class" hc-deftype-ctor-class) - (def-var! "jolt.host" "record-shapes" hc-record-shapes) - (def-var! "jolt.host" "protocol-methods" hc-protocol-methods) - (def-var! "jolt.host" "inline-enabled?" hc-inline-enabled?) - (def-var! "jolt.host" "inline-ir" hc-inline-ir) - (def-var! "jolt.host" "stash-inline!" hc-stash-inline!)) - -(hc-install!) diff --git a/host/chez/host-table.ss b/host/chez/host-table.ss deleted file mode 100644 index cda2330..0000000 --- a/host/chez/host-table.ss +++ /dev/null @@ -1,178 +0,0 @@ -;; host tables + sorted collections — the jolt.host value primitives and the -;; 25-sorted tier's runtime. -;; -;; jolt.host/tagged-table + ref-put! + ref-get back the whole sorted tier -;; (sorted-map/sorted-set/subseq/rsubseq) AND every overlay fn that calls -;; (sorted? x) — empty, ifn?, reversible?, map?, set?, coll?. This provides: -;; 1. tagged-table / ref-put! / ref-get over a Chez mutable tagged-table type -;; (a string-keyed hashtable wrapped in an `htable` record), def-var!'d into -;; the jolt.host ns. The sorted tier (25-sorted.clj) mints its wrapper with -;; these — a red-black tree + :ops table travel inside the htable. -;; 2. a sorted-coll arm on the collection dispatchers, set!-extended the same -;; way records.ss extends them for jrec: each op routes through the value's -;; own :ops table (the dispatch pattern). first/rest/ -;; next/last fall out free once jolt-seq has a sorted arm (they seq first). -;; -;; Loaded LAST (after records.ss / transients.ss / natives-meta.ss): it wraps the -;; jrec-extended dispatchers + value-host-tags, delegating to the captured prior. - -;; --- jolt.host primitives ---------------------------------------------------- -;; A tagged-table: a string-keyed hashtable (keyword field -> value). Keyword -;; keys collapse to their ns/name string so interning isn't relied on. -(define-record-type htable (fields (immutable h)) (nongenerative chez-htable-v1)) -(define (kw->key k) - (let ((ns (keyword-t-ns k))) - (if (and ns (not (jolt-nil? ns))) (string-append ns "/" (keyword-t-name k)) (keyword-t-name k)))) -(define (jolt-tagged-table tag) - (let ((h (make-hashtable string-hash string=?))) - (hashtable-set! h "jolt/type" tag) - (make-htable h))) -;; ref-put! threads the table back; a nil value REMOVES the key. Errors on a -;; non-htable so the atom-watch / volatile uses (which pass a different ref type -;; and have no table yet) stay a crash rather than silently diverging. -(define (jolt-ref-put! t k v) - (unless (htable? t) (error #f "ref-put!: not a host table" t)) - (if (jolt-nil? v) - (hashtable-delete! (htable-h t) (kw->key k)) - (hashtable-set! (htable-h t) (kw->key k) v)) - t) -(define (jolt-ref-get t k) - (if (htable? t) (hashtable-ref (htable-h t) (kw->key k) jolt-nil) jolt-nil)) - -(def-var! "jolt.host" "tagged-table" jolt-tagged-table) -(def-var! "jolt.host" "ref-put!" jolt-ref-put!) -(def-var! "jolt.host" "ref-get" jolt-ref-get) -;; map-entry constructor: a 2-elem entry-flagged pvec (map-entry? true, vector? -;; false), so sorted-map seq/first produce real map entries that key/val accept. -(def-var! "jolt.host" "map-entry" make-map-entry) - -;; --- sorted-coll recognition + ops access ------------------------------------ -(define kw-jtype (keyword "jolt" "type")) -(define kw-sorted-map (keyword "jolt" "sorted-map")) -(define kw-sorted-set (keyword "jolt" "sorted-set")) -(define kw-ops (keyword #f "ops")) -(define kw-op-count (keyword #f "count")) -(define kw-op-seq (keyword #f "seq")) -(define kw-op-get (keyword #f "get")) -(define kw-op-contains (keyword #f "contains")) -(define kw-op-assoc (keyword #f "assoc")) -(define kw-op-dissoc (keyword #f "dissoc")) -(define kw-op-conj (keyword #f "conj")) -(define kw-op-disj (keyword #f "disj")) - -(define (htable-sorted-map? x) (and (htable? x) (jolt=2 (jolt-ref-get x kw-jtype) kw-sorted-map))) -(define (htable-sorted-set? x) (and (htable? x) (jolt=2 (jolt-ref-get x kw-jtype) kw-sorted-set))) -(define (htable-sorted? x) (or (htable-sorted-map? x) (htable-sorted-set? x))) -;; the op fn for `op-kw` from the value's attached :ops map, then invoke it on sc. -(define (sc-op sc op-kw) (jolt-get (jolt-ref-get sc kw-ops) op-kw jolt-nil)) -(define (sc-call sc op-kw . args) (apply jolt-invoke (sc-op sc op-kw) sc args)) - -;; --- extend the collection dispatchers with a sorted arm --------------------- -(define %h-seq jolt-seq) -(set! jolt-seq (lambda (x) (if (htable-sorted? x) (sc-call x kw-op-seq) (%h-seq x)))) -(define %h-count jolt-count) -(set! jolt-count (lambda (coll) (if (htable-sorted? coll) (sc-call coll kw-op-count) (%h-count coll)))) -(register-get-arm! htable-sorted? (lambda (coll k d) (sc-call coll kw-op-get k d))) -(define %h-contains? jolt-contains?) -(set! jolt-contains? (lambda (coll k) - (if (htable-sorted? coll) (if (jolt-truthy? (sc-call coll kw-op-contains k)) #t #f) (%h-contains? coll k)))) -(define %h-assoc1 jolt-assoc1) -(set! jolt-assoc1 (lambda (coll k v) - (if (htable-sorted-map? coll) (sc-call coll kw-op-assoc (jolt-vector k v)) (%h-assoc1 coll k v)))) -(define %h-dissoc jolt-dissoc) -(set! jolt-dissoc (lambda (coll . ks) - (if (htable-sorted-map? coll) (sc-call coll kw-op-dissoc (apply jolt-vector ks)) (apply %h-dissoc coll ks)))) -(define %h-conj1 jolt-conj1) -(set! jolt-conj1 (lambda (coll x) - (if (htable-sorted? coll) (sc-call coll kw-op-conj (jolt-vector x)) (%h-conj1 coll x)))) -(define %h-disj jolt-disj) -(set! jolt-disj (lambda (s . xs) - (if (htable-sorted-set? s) (sc-call s kw-op-disj (apply jolt-vector xs)) (apply %h-disj s xs)))) -(def-var! "clojure.core" "disj" jolt-disj) -(define %h-empty? jolt-empty?) -(set! jolt-empty? (lambda (coll) (if (htable-sorted? coll) (zero? (sc-call coll kw-op-count)) (%h-empty? coll)))) -(define %h-keys jolt-keys) -(set! jolt-keys (lambda (m) - (if (htable-sorted-map? m) - (list->cseq (map (lambda (e) (jolt-nth e 0)) (seq->list (sc-call m kw-op-seq)))) - (%h-keys m)))) -(define %h-vals jolt-vals) -(set! jolt-vals (lambda (m) - (if (htable-sorted-map? m) - (list->cseq (map (lambda (e) (jolt-nth e 1)) (seq->list (sc-call m kw-op-seq)))) - (%h-vals m)))) -;; sorted colls are collections (callable as fns via jolt-invoke, conj-able). -(define %h-coll? jolt-coll?) -(set! jolt-coll? (lambda (x) (or (htable-sorted? x) (%h-coll? x)))) - -;; public predicates: a sorted-map is map?, a sorted-set is set?, both coll?. -;; predicates.ss/records.ss def-var!'d a snapshot, so re-def-var! after set!. -(define %h-map? jolt-map?) -(set! jolt-map? (lambda (x) (or (htable-sorted-map? x) (%h-map? x)))) -(def-var! "clojure.core" "map?" jolt-map?) -(define %h-set? jolt-set?) -(set! jolt-set? (lambda (x) (or (htable-sorted-set? x) (%h-set? x)))) -(def-var! "clojure.core" "set?" jolt-set?) -(def-var! "clojure.core" "coll?" (lambda (x) (or (htable-sorted? x) (jrec-collection? x) (jolt-coll-pred? x)))) - -;; --- equality / hash --------------------------------------------------------- -;; A sorted coll canonicalizes like its unordered counterpart: -;; a sorted-map equals ANY map (hash or sorted) with the same entries, a -;; sorted-set ANY set with the same elements — the comparator is irrelevant to =. -;; Convert to the plain persistent coll and delegate to the prior jolt=2 / hash. -;; (htable-sorted? short-circuits on a non-htable BEFORE any jolt=2, so extending -;; jolt=2 here doesn't recurse: the inner tag compare gets two keywords.) -(define (sorted-map->pmap sc) - (fold-left (lambda (m e) (pmap-assoc m (jolt-nth e 0) (jolt-nth e 1))) - empty-pmap (seq->list (sc-call sc kw-op-seq)))) -(define (sorted-set->pset sc) - (fold-left (lambda (s x) (pset-conj s x)) empty-pset (seq->list (sc-call sc kw-op-seq)))) -(define (sorted->plain x) (if (htable-sorted-map? x) (sorted-map->pmap x) (sorted-set->pset x))) -;; a sorted coll compares as its plain equivalent: normalize and re-dispatch (the -;; normalized values aren't sorted, so this arm won't re-match — the base compares). -(register-eq-arm! (lambda (a b) (or (htable-sorted? a) (htable-sorted? b))) - (lambda (a b) (jolt=2 (if (htable-sorted? a) (sorted->plain a) a) - (if (htable-sorted? b) (sorted->plain b) b)))) -;; a sorted coll hashes as its plain equivalent (jolt-hash recurses through the base). -(register-hash-arm! htable-sorted? (lambda (x) (jolt-hash (sorted->plain x)))) - -;; --- printing ---------------------------------------------------------------- -;; sorted colls render in SORTED order (the value's :seq), not HAMT order — and -;; a sorted-map prints "{k v, k v}" (", " between pairs), -;; NOT the space-only form the unordered pmap arm uses. -(define (sorted-map-render sc render) - (string-append "{" - (let loop ((es (seq->list (sc-call sc kw-op-seq))) (first #t) (acc "")) - (if (null? es) acc - (loop (cdr es) #f - (string-append acc (if first "" ", ") - (render (jolt-nth (car es) 0)) " " (render (jolt-nth (car es) 1)))))) - "}")) -(define (sorted-set-render sc render) - (string-append "#{" (jolt-str-join (map render (seq->list (sc-call sc kw-op-seq)))) "}")) -(define (sorted-render x render) - (if (htable-sorted-map? x) (sorted-map-render x render) (sorted-set-render x render))) - -;; sorted colls render in :seq order via the calling printer (str vs readable). -(register-pr-readable-arm! htable-sorted? (lambda (x) (sorted-render x jolt-pr-readable))) -(register-pr-str-arm! htable-sorted? (lambda (x) (sorted-render x jolt-pr-str))) -(register-str-render! htable-sorted? (lambda (x) (sorted-render x jolt-str-render-one))) - -;; --- protocol dispatch over builtins (extend-protocol Map/Set on sorted) ------ -;; value-host-tags (records.ss) drives extend-protocol on host values; a -;; sorted-map must answer to "Map", a sorted-set to "Set"/"Collection". -(define %h-value-host-tags value-host-tags) -(set! value-host-tags (lambda (obj) - (cond - ((htable-sorted-map? obj) '("PersistentTreeMap" "Sorted" "IPersistentMap" "Associative" - "Map" "java.util.Map" "IPersistentCollection" "Object")) - ((htable-sorted-set? obj) '("PersistentTreeSet" "Sorted" "IPersistentSet" - "Set" "java.util.Set" "Collection" "IPersistentCollection" "Object")) - (else (%h-value-host-tags obj))))) - -;; (class e) on a throwable tagged-table (a library's ex-info envelope carrying a -;; JVM :class, e.g. jolt-lang/http-client's UnknownHostException) reads that -;; class name, so clojure.test's (thrown? Class …) / (= Class (class e)) match. -;; an htable carrying a string "class" entry reports it (a host-object class mirror). -(register-class-arm! (lambda (x) (and (htable? x) (string? (hashtable-ref (htable-h x) "class" #f)))) - (lambda (x) (hashtable-ref (htable-h x) "class" #f))) diff --git a/host/chez/java/async.ss b/host/chez/java/async.ss deleted file mode 100644 index 98a4a11..0000000 --- a/host/chez/java/async.ss +++ /dev/null @@ -1,315 +0,0 @@ -;; async.ss — clojure.core.async channel primitives on real OS threads. -;; -;; A `go` block is an OS thread and a channel is a Chez mutex+condition blocking -;; queue: ! are the blocking !! (they "park" by blocking the thread), -;; and work ANYWHERE — no CPS transform, no go-only restriction. Real parallelism, -;; shared heap. This is a superset of the JVM model: it has no fixed go-block -;; thread pool, no MAX-QUEUE-SIZE on pending ops, and parking ops are legal outside -;; a go block. One OS thread per go block (fine for typical use). -;; -;; Channel: an unbuffered channel is a rendezvous (the putter blocks until its -;; value is taken); a buffered (chan n) put blocks only when full; dropping/sliding -;; buffers never block the putter. A transducer is applied on the put side; an -;; optional ex-handler catches a throw from the transducer step. -;; -;; This file provides the primitives; the higher-level dataflow API (mult, mix, -;; pub/sub, pipeline, map, merge, reduce, …) is a Clojure overlay over them. -;; go/go-loop/thread are macros (mark-macro!) expanding to go-spawn. Loaded after -;; concurrency.ss (reuses ms->duration). Requires a threaded Chez build. - -;; --- buffers ---------------------------------------------------------------- -(define-record-type async-buffer (fields n kind) (nongenerative async-buffer-v1)) -(define (jolt-async-buffer n) (make-async-buffer n 'fixed)) -(define (jolt-async-dropping-buffer n) (make-async-buffer n 'dropping)) -(define (jolt-async-sliding-buffer n) (make-async-buffer n 'sliding)) -(define (jolt-async-unblocking-buffer? b) - (if (and (async-buffer? b) (memq (async-buffer-kind b) '(dropping sliding promise))) #t #f)) - -;; --- channels --------------------------------------------------------------- -;; items: an amortized-O(1) FIFO held as a mutable #(out in len) — `out` is the -;; front (pop from its head), `in` holds pushed entries reversed onto it, `len` is -;; the count (an append-to-a-list FIFO is O(n) per push and O(n) to measure). -;; Each entry is (value . box); box is #f for a buffered value or a 1-slot vector -;; for an unbuffered rendezvous put (set #t when taken, waking the putter). -;; cap 0 + kind 'unbuffered = rendezvous; cap>0 with kind fixed/dropping/sliding. -;; takew counts threads parked in a blocking take (so a non-blocking offer! to an -;; unbuffered channel can tell a taker is waiting). xrf is the transducer reducing -;; fn (or #f); exh the ex-handler (or #f). -(define-record-type async-chan - (fields mu cv (mutable items) cap kind (mutable closed?) (mutable xrf) (mutable takew) exh) - (nongenerative async-chan-v2)) - -(define (ac-qnew) (vector '() '() 0)) -(define (ac-qlen ch) (vector-ref (async-chan-items ch) 2)) -(define (ac-qempty? ch) (fx=? 0 (vector-ref (async-chan-items ch) 2))) -(define (ac-qpush! ch entry) - (let ((q (async-chan-items ch))) - (vector-set! q 1 (cons entry (vector-ref q 1))) - (vector-set! q 2 (fx+ 1 (vector-ref q 2))))) -(define (ac-qfront! q) ; ensure `out` is non-empty: out := reverse in - (when (null? (vector-ref q 0)) - (vector-set! q 0 (reverse (vector-ref q 1))) - (vector-set! q 1 '()))) -(define (ac-qpop! ch) - (let ((q (async-chan-items ch))) - (ac-qfront! q) - (let ((out (vector-ref q 0))) - (vector-set! q 0 (cdr out)) - (vector-set! q 2 (fx- (vector-ref q 2) 1)) - (car out)))) -(define (ac-qdrop-oldest! ch) - (let ((q (async-chan-items ch))) - (ac-qfront! q) - (vector-set! q 0 (cdr (vector-ref q 0))) - (vector-set! q 2 (fx- (vector-ref q 2) 1)))) - -;; enqueue honoring the buffer kind (used by the transducer step + buffered puts). -(define (ac-buf-give! ch v) - (case (async-chan-kind ch) - ((dropping) (when (< (ac-qlen ch) (async-chan-cap ch)) (ac-qpush! ch (cons v #f)))) - ((sliding) (when (>= (ac-qlen ch) (async-chan-cap ch)) (ac-qdrop-oldest! ch)) - (ac-qpush! ch (cons v #f))) - (else (ac-qpush! ch (cons v #f)))) ; fixed: caller ensured room - (condition-broadcast (async-chan-cv ch))) - -;; A transducer is a jolt fn (xform); (xform add-rf) yields the channel's reducing -;; fn. add-rf: 0-arg init, 1-arg completion, 2-arg step (enqueue the output). A -;; `reduced` step result closes the channel. -(define (ac-make-add-rf ch) - (lambda args - (cond ((null? args) ch) ; init - ((null? (cdr args)) (car args)) ; completion - (else (ac-buf-give! ch (cadr args)) (car args))))) ; step - -;; run the transducer step (or completion) guarded by the channel's ex-handler: -;; if the xform throws and exh returns non-nil, that value is added to the buffer. -(define (ac-xrf-apply ch . v) - (let ((xrf (async-chan-xrf ch)) (exh (async-chan-exh ch))) - (guard (e (#t (if exh - (let ((else (jolt-invoke exh e))) - (unless (jolt-nil? else) (ac-buf-give! ch else)) - (async-chan-xrf ch)) ; treat as non-reduced - (raise e)))) - (apply jolt-invoke xrf ch v)))) - -(define (ac-make cap kind xrf) (make-async-chan (make-mutex) (make-condition) (ac-qnew) cap kind #f xrf 0 #f)) -(define (ac-make/exh cap kind exh) (make-async-chan (make-mutex) (make-condition) (ac-qnew) cap kind #f #f 0 exh)) - -;; (chan) | (chan n) | (chan buf) | (chan n|buf xform) | (chan n|buf xform exh) -(define (jolt-async-chan . args) - (let ((buf (if (pair? args) (car args) jolt-nil)) - (xform (if (and (pair? args) (pair? (cdr args))) (cadr args) jolt-nil)) - (exh (if (and (pair? args) (pair? (cdr args)) (pair? (cddr args))) (caddr args) jolt-nil))) - (let-values (((cap kind) - (cond ((async-buffer? buf) (values (async-buffer-n buf) (async-buffer-kind buf))) - ((and (number? buf) (> buf 0)) (values buf 'fixed)) - (else (values 0 'unbuffered))))) - (let ((ch (ac-make/exh cap kind (if (jolt-nil? exh) #f exh)))) - (unless (jolt-nil? xform) - (async-chan-xrf-set! ch (jolt-invoke xform (ac-make-add-rf ch)))) - ch)))) - -;; close! (idempotent): mark closed, flush a stateful transducer's completion, and -;; wake everyone. ac-close! assumes the lock is held; the public form takes it. -(define (ac-close! ch) - (unless (async-chan-closed? ch) - (async-chan-closed?-set! ch #t) - (when (async-chan-xrf ch) (guard (e (#t #f)) (ac-xrf-apply ch))) - (condition-broadcast (async-chan-cv ch))) - jolt-nil) -(define (jolt-async-close! ch) (with-mutex (async-chan-mu ch) (ac-close! ch))) - -;; >! / >!! — put, blocking. false if closed; nil may not be put. With a -;; transducer the value is run through it (one put -> zero or more channel values); -;; a `reduced` result closes the channel. -(define (jolt-async-give ch v) - (when (jolt-nil? v) (jolt-throw (jolt-host-throwable "java.lang.IllegalArgumentException" "Can't put nil on a channel"))) - (with-mutex (async-chan-mu ch) - (cond - ((async-chan-closed? ch) #f) - ((async-chan-xrf ch) - (let ((r (ac-xrf-apply ch v))) - (when (jolt-reduced? r) (ac-close! ch)) - #t)) - (else - (case (async-chan-kind ch) - ((dropping sliding) (ac-buf-give! ch v) #t) - ;; a promise channel takes ONE value, delivered to every taker; further - ;; puts are dropped. Never blocks. - ((promise) (when (ac-qempty? ch) - (ac-qpush! ch (cons v #f)) (condition-broadcast (async-chan-cv ch))) - #t) - (else - (if (> (async-chan-cap ch) 0) - (let loop () ; buffered fixed: wait for room - (cond ((async-chan-closed? ch) #f) - ((< (ac-qlen ch) (async-chan-cap ch)) - (ac-qpush! ch (cons v #f)) (condition-broadcast (async-chan-cv ch)) #t) - (else (condition-wait (async-chan-cv ch) (async-chan-mu ch)) (loop)))) - (let ((box (vector #f))) ; unbuffered: rendezvous - (ac-qpush! ch (cons v box)) - (condition-broadcast (async-chan-cv ch)) - (let loop () - (cond ((vector-ref box 0) #t) - ((async-chan-closed? ch) #f) - (else (condition-wait (async-chan-cv ch) (async-chan-mu ch)) (loop)))))))))))) - -;; remove + return the head value, waking a parked rendezvous putter. -(define (ac-take-head! ch) - (let* ((entry (ac-qpop! ch)) (v (car entry)) (box (cdr entry))) - (when box (vector-set! box 0 #t)) - (condition-broadcast (async-chan-cv ch)) - v)) - -;; peek the front value without removing it (promise channels keep their value). -(define (ac-peek ch) - (let ((q (async-chan-items ch))) - (ac-qfront! q) - (car (car (vector-ref q 0))))) - -;; (async-chan-cap ch) 0) - (if (< (ac-qlen ch) (async-chan-cap ch)) - (begin (ac-qpush! ch (cons v #f)) (condition-broadcast (async-chan-cv ch)) 'ok) - 'full)) - ;; unbuffered: only immediate if a taker is parked to receive it. - ((> (async-chan-takew ch) 0) - (let ((box (vector #f))) - (ac-qpush! ch (cons v box)) - (condition-broadcast (async-chan-cv ch)) - 'ok)) - (else 'full)))))))) - -;; offer! / poll! — never block. offer! returns #t/#f(closed) on completion, nil if -;; it would block; poll! returns a value, nil (closed+empty), or the ::none sentinel. -(define cca-none (keyword "clojure.core.async" "none")) -(define (jolt-async-offer! ch v) - (case (ac-try-give! ch v) ((ok) #t) ((closed) #f) (else jolt-nil))) -(define (jolt-async-poll! ch) - (let ((r (ac-poll! ch))) (if (eq? r ac-poll-empty) cca-none r))) - -;; (timeout ms) — a channel that closes after ms milliseconds. -(define (jolt-async-timeout ms) - (let ((w (ac-make 0 'unbuffered #f))) - (fork-thread (lambda () (sleep (ms->duration ms)) (jolt-async-close! w))) - w)) - -;; (put! ch v [cb [on-caller?]]) — async put, optional completion callback. If the -;; put completes immediately and on-caller? (default #t), the callback runs on the -;; calling thread; otherwise on another thread. Returns true unless already closed. -(define (jolt-async-put! ch v . rest) - (let* ((cb (if (pair? rest) (car rest) jolt-nil)) - (on-caller? (if (and (pair? rest) (pair? (cdr rest))) (jolt-truthy? (cadr rest)) #t)) - (call-cb (lambda (ok) (unless (jolt-nil? cb) (jolt-invoke cb ok))))) - (case (ac-try-give! ch v) - ((ok) (if on-caller? (call-cb #t) (fork-thread (lambda () (call-cb #t)))) #t) - ((closed) (if on-caller? (call-cb #f) (fork-thread (lambda () (call-cb #f)))) #f) - (else (fork-thread (lambda () (call-cb (jolt-async-give ch v)))) #t)))) - -;; (take! ch cb [on-caller?]) — async take. Same on-caller? rule as put!. -(define (jolt-async-take! ch cb . rest) - (let* ((on-caller? (if (pair? rest) (jolt-truthy? (car rest)) #t)) - (call-cb (lambda (v) (unless (jolt-nil? cb) (jolt-invoke cb v)))) - (r (ac-poll! ch))) - (cond - ((eq? r ac-poll-empty) (fork-thread (lambda () (call-cb (jolt-async-take ch))))) - (on-caller? (call-cb r)) - (else (fork-thread (lambda () (call-cb r))))) - jolt-nil)) - -;; (go-spawn thunk) — run thunk on a thread; return a buffered(1) channel that -;; conveys its value once then closes (a nil result just closes). Dynamic bindings -;; are conveyed (Chez inherits the thread-parameter at fork; we install explicitly). -(define (async-go-spawn thunk) - (let ((w (ac-make 1 'fixed #f)) (snap (dyn-binding-stack))) - (fork-thread - (lambda () - (dyn-binding-stack snap) - (let ((r (guard (e (#t (cons #f e))) (cons #t (jolt-invoke thunk))))) - (when (and (car r) (not (jolt-nil? (cdr r)))) (jolt-async-give w (cdr r))) - (jolt-async-close! w)))) - w)) - -;; --- macros (expander fns over the reader forms) ---------------------------- -(define cca-go-spawn-sym (jolt-symbol "clojure.core.async" "go-spawn")) -(define cca-go-sym (jolt-symbol "clojure.core.async" "go")) -(define cca-fn*-sym (jolt-symbol #f "fn*")) -(define cca-loop-sym (jolt-symbol #f "loop")) - -;; (go body...) -> (clojure.core.async/go-spawn (fn* [] body...)) -(define (cca-go-macro . body) - (jolt-list cca-go-spawn-sym (apply jolt-list cca-fn*-sym empty-pvec body))) -;; (go-loop bindings body...) -> (go (loop bindings body...)) -(define (cca-go-loop-macro bindings . body) - (jolt-list cca-go-sym (apply jolt-list cca-loop-sym bindings body))) -;; (thread body...) — a real OS thread (same shape as go here). -(define (cca-thread-macro . body) - (jolt-list cca-go-spawn-sym (apply jolt-list cca-fn*-sym empty-pvec body))) - -;; --- install clojure.core.async --------------------------------------------- -(define (cca-def! name v) (def-var! "clojure.core.async" name v)) -(cca-def! "chan" jolt-async-chan) -(cca-def! "promise-chan" (lambda args (ac-make 1 'promise #f))) -(cca-def! "chan?" async-chan?) -(cca-def! "buffer" jolt-async-buffer) -(cca-def! "dropping-buffer" jolt-async-dropping-buffer) -(cca-def! "sliding-buffer" jolt-async-sliding-buffer) -(cca-def! "__promise-buffer" (lambda () (make-async-buffer 1 'promise))) -(cca-def! "unblocking-buffer?" jolt-async-unblocking-buffer?) -(cca-def! "close!" jolt-async-close!) -(cca-def! "!" jolt-async-give) (cca-def! ">!!" jolt-async-give) -(cca-def! "timeout" jolt-async-timeout) -(cca-def! "put!" jolt-async-put!) -(cca-def! "take!" jolt-async-take!) -(cca-def! "offer!" jolt-async-offer!) -(cca-def! "go-spawn" async-go-spawn) -;; non-blocking primitives the Clojure overlay's do-alts polls over. -(cca-def! "__poll!" jolt-async-poll!) -(cca-def! "__offer!" jolt-async-offer!) -(cca-def! "go" cca-go-macro) (mark-macro! "clojure.core.async" "go") -(cca-def! "go-loop" cca-go-loop-macro) (mark-macro! "clojure.core.async" "go-loop") -(cca-def! "thread" cca-thread-macro) (mark-macro! "clojure.core.async" "thread") diff --git a/host/chez/java/bigdec.ss b/host/chez/java/bigdec.ss deleted file mode 100644 index f8e202b..0000000 --- a/host/chez/java/bigdec.ss +++ /dev/null @@ -1,402 +0,0 @@ -;; BigDecimal. A jbigdec is {unscaled, scale} over Chez arbitrary-precision exact -;; integers; its value is unscaled * 10^-scale (1.5M = {15,1}, 1.00M = {100,2}, -;; 3M = {3,0}). M-suffix literals read to a :bigdec form that the back end lowers -;; to jolt-bigdec-from-string; bigdec coerces a number/string. Equality is by -;; value (1.0M = 1.00M), str drops the M, pr keeps it, class is -;; java.math.BigDecimal. -;; -;; Arithmetic follows java.math.BigDecimal's scale rules: add/sub align to the -;; larger scale; multiply adds scales; divide gives the exact quotient at minimal -;; scale or throws ArithmeticException on a non-terminating expansion (a bound -;; *math-context* rounds instead). Clojure contagion: a bigdec mixed with an -;; integer or ratio stays a bigdec; a flonum operand wins (the result is a -;; double). jbd-add/-sub/-mul/-div, jbd-min/-max, the jbd-lt?/…/zero? helpers, -;; and jbd-quot/-rem are the shared engine. Two paths reach it, both leaving the -;; inlined fast path untouched: -;; - the seq.ss binary dispatch: every generic op (any position — (+ (bigdec x) -;; 1), (reduce + bigs), (quot 10.0 3M)) whose operand is outside Chez's tower -;; falls to the jolt-*-slow hooks extended below. -;; - static call position ((+ 1.5M 2.5M), (< a b), (zero? b)): jolt.passes.numeric -;; tags the invoke :num-kind :bigdec when every operand is statically a bigdec -;; (M literal or a let-bound copy, integer literals allowed), and the back end -;; lowers it directly to the jbd op. - -(define-record-type jbigdec (fields unscaled scale) (nongenerative chez-jbigdec-v1)) - -(define (bd-index-char s ch) - (let loop ((i 0)) - (cond ((>= i (string-length s)) #f) - ((char=? (string-ref s i) ch) i) - (else (loop (+ i 1)))))) - -;; "1.50" -> {150,2}; "3" -> {3,0}; "-0.0" -> {0,1}; ".5" -> {5,1}. -(define (jolt-bigdec-from-string s) - (let* ((neg (and (> (string-length s) 0) (char=? (string-ref s 0) #\-))) - (sgn (and (> (string-length s) 0) (or neg (char=? (string-ref s 0) #\+)))) - (s1 (if sgn (substring s 1 (string-length s)) s)) - (sign (if neg -1 1)) - (dot (bd-index-char s1 #\.))) - (if dot - (let* ((intp (substring s1 0 dot)) - (fracp (substring s1 (+ dot 1) (string-length s1))) - (digs (string-append intp fracp)) - (unscaled (if (= 0 (string-length digs)) 0 (string->number digs)))) - (make-jbigdec (* sign unscaled) (string-length fracp))) - (make-jbigdec (* sign (string->number s1)) 0)))) - -;; bigdec coercion: a bigdec is itself; an exact integer keeps scale 0; a string -;; or any other number routes through its decimal text. -(define (jolt-bigdec x) - (cond - ((jbigdec? x) x) - ((and (number? x) (exact? x) (integer? x)) (make-jbigdec x 0)) - ((string? x) (jolt-bigdec-from-string x)) - ((number? x) (jolt-bigdec-from-string (jolt-num->string x))) - (else (error #f "bigdec: cannot coerce" x)))) - -;; value equality: unscaled_a * 10^scale_b == unscaled_b * 10^scale_a. -(define (jbigdec=? a b) - (= (* (jbigdec-unscaled a) (expt 10 (jbigdec-scale b))) - (* (jbigdec-unscaled b) (expt 10 (jbigdec-scale a))))) - -;; render the decimal text (no M): insert the point `scale` digits from the right. -(define (jbigdec->string bd) - (let* ((u (jbigdec-unscaled bd)) (sc (jbigdec-scale bd)) - (neg (< u 0)) (digs (number->string (abs u)))) - (string-append - (if neg "-" "") - (if (<= sc 0) - digs - (let* ((padded (if (<= (string-length digs) sc) - (string-append (make-string (- (+ sc 1) (string-length digs)) #\0) digs) - digs)) - (pl (string-length padded))) - (string-append (substring padded 0 (- pl sc)) "." (substring padded (- pl sc) pl))))))) - -;; value as a Chez flonum (for double contagion: a flonum operand wins). -(define (jbigdec->flonum b) - (exact->inexact (/ (jbigdec-unscaled b) (expt 10 (jbigdec-scale b))))) - -;; coerce an exact operand to a bigdec; pass a bigdec through. Used on the -;; non-flonum mixed path (bigdec + long -> bigdec). A Ratio converts like -;; Numbers.toBigDecimal — exact decimal expansion or throw on non-terminating. -(define (jbd-coerce x) - (cond ((jbigdec? x) x) - ((and (number? x) (exact? x) (integer? x)) (make-jbigdec x 0)) - ((and (number? x) (exact? x) (rational? x)) (jbd-rational->bigdec x)) - (else (error #f "bigdec arithmetic: cannot coerce operand" x)))) - -;; --- core arithmetic on the {unscaled, scale} pair -------------------------- -;; align two bigdecs to a common scale, returning (unscaled-a unscaled-b scale). -(define (jbd-align a b) - (let ((sa (jbigdec-scale a)) (sb (jbigdec-scale b))) - (cond - ((= sa sb) (values (jbigdec-unscaled a) (jbigdec-unscaled b) sa)) - ((> sa sb) (values (jbigdec-unscaled a) - (* (jbigdec-unscaled b) (expt 10 (- sa sb))) sa)) - (else (values (* (jbigdec-unscaled a) (expt 10 (- sb sa))) - (jbigdec-unscaled b) sb))))) - -(define (jbd2+ a b) (let-values (((ua ub s) (jbd-align a b))) (make-jbigdec (+ ua ub) s))) -(define (jbd2- a b) (let-values (((ua ub s) (jbd-align a b))) (make-jbigdec (- ua ub) s))) -(define (jbd2* a b) (make-jbigdec (* (jbigdec-unscaled a) (jbigdec-unscaled b)) - (+ (jbigdec-scale a) (jbigdec-scale b)))) -(define (jbd-negate a) (make-jbigdec (- (jbigdec-unscaled a)) (jbigdec-scale a))) - -;; exact rational -> bigdec at minimal scale, or throw if non-terminating. den must -;; factor into 2s and 5s; scale = max(count2, count5). -(define (jbd-rational->bigdec r) - (let ((p (numerator r)) (q (denominator r))) - (let loop ((d q) (c2 0) (c5 0)) - (cond - ((= d 1) (let ((sc (max c2 c5))) - (make-jbigdec (* p (quotient (expt 10 sc) q)) sc))) - ((= 0 (modulo d 2)) (loop (quotient d 2) (+ c2 1) c5)) - ((= 0 (modulo d 5)) (loop (quotient d 5) c2 (+ c5 1))) - (else (jolt-throw (jolt-host-throwable - "java.lang.ArithmeticException" - "Non-terminating decimal expansion; no exact representable decimal result."))))))) - -;; floor(log10 |r|) for a nonzero exact rational. -(define (jbd-exp10 r) - (let ((n (abs (numerator r))) (d (denominator r))) - (if (>= n d) - (- (jbd-digits (quotient n d)) 1) - (let loop ((x (* n 10)) (e -1)) - (if (>= x d) e (loop (* x 10) (- e 1))))))) -;; round an exact rational to `prec` significant digits (the MathContext divide). -(define (jbd-rational-prec r prec mode) - (if (= r 0) - (make-jbigdec 0 0) - (let* ((neg (< r 0)) (ar (abs r)) - (s (- prec 1 (jbd-exp10 ar))) - (scaled (* ar (expt 10 s))) - (q (floor scaled)) (frac (- scaled q)) - (q2 (if (jbd-round-inc? q frac 1 mode neg) (+ q 1) q)) - (res (make-jbigdec (if neg (- q2) q2) s))) - ;; a carry can add a digit (9.99 -> 10.0); re-normalizing drops an exact - ;; trailing zero, never re-rounds. - (if (> (jbd-digits q2) prec) (jbd-round-prec res prec mode) res)))) - -(define (jbd2-div a b) - (when (= 0 (jbigdec-unscaled b)) - (jolt-throw (jolt-host-throwable "java.lang.ArithmeticException" "Divide by zero"))) - ;; a/b = (ua * 10^sb) / (ub * 10^sa) as an exact rational. Unlimited context: - ;; exact result at minimal scale or throw on a non-terminating expansion. A - ;; bound *math-context* instead rounds to its precision. - (let ((r (/ (* (jbigdec-unscaled a) (expt 10 (jbigdec-scale b))) - (* (jbigdec-unscaled b) (expt 10 (jbigdec-scale a))))) - (mc (jbd-math-context))) - (if mc - (jbd-rational-prec r (jbd-mc-precision mc) (jbd-mc-mode mc)) - (jbd-rational->bigdec r)))) - -;; integer-division semantics (quot/rem): truncate toward zero, scale 0. -(define (jbd-int-quot a b) - (when (= 0 (jbigdec-unscaled b)) - (jolt-throw (jolt-host-throwable "java.lang.ArithmeticException" "Divide by zero"))) - (let-values (((ua ub s) (jbd-align a b))) (make-jbigdec (quotient ua ub) 0))) -(define (jbd-int-rem a b) - (when (= 0 (jbigdec-unscaled b)) - (jolt-throw (jolt-host-throwable "java.lang.ArithmeticException" "Divide by zero"))) - (let-values (((ua ub s) (jbd-align a b))) - (make-jbigdec (remainder ua ub) (max (jbigdec-scale a) (jbigdec-scale b))))) - -;; scale-independent ordering: compare unscaled values aligned to a common scale. -(define (jbd-compare2 a b) - (let-values (((ua ub s) (jbd-align a b))) (cond ((< ua ub) -1) ((> ua ub) 1) (else 0)))) - -;; --- *math-context* (with-precision) ----------------------------------------- -;; with-precision binds clojure.core/*math-context* to {:precision N :rounding -;; MODE}; every exact bigdec result rounds through it (java.math.MathContext). -(define jbd-kw-precision (keyword #f "precision")) -(define jbd-kw-rounding (keyword #f "rounding")) -(define (jbd-math-context) - (let ((mc (var-deref "clojure.core" "*math-context*"))) - (if (jolt-nil? mc) #f mc))) -(define (jbd-mc-precision mc) (jolt-get mc jbd-kw-precision)) -(define (jbd-mc-mode mc) - (let ((r (jolt-get mc jbd-kw-rounding))) - (cond ((symbol-t? r) (symbol-t-name r)) - ((string? r) r) - (else "HALF_UP")))) - -;; should |value| = q + r/div (0 <= r < div) round up in magnitude? neg is the -;; value's sign; r/div may be exact rationals (the division path). -(define (jbd-round-inc? q r div mode neg) - (cond ((= r 0) #f) - ((string=? mode "UP") #t) - ((string=? mode "DOWN") #f) - ((string=? mode "CEILING") (not neg)) - ((string=? mode "FLOOR") neg) - ((string=? mode "HALF_DOWN") (> (* 2 r) div)) - ((string=? mode "HALF_EVEN") - (let ((c (- (* 2 r) div))) - (cond ((> c 0) #t) ((< c 0) #f) (else (odd? q))))) - ((string=? mode "UNNECESSARY") - (jolt-throw (jolt-host-throwable "java.lang.ArithmeticException" "Rounding necessary"))) - (else (>= (* 2 r) div)))) ; HALF_UP, the MathContext default - -(define (jbd-digits n) (string-length (number->string (abs n)))) -;; round a bigdec to `prec` significant digits with `mode` (a RoundingMode name). -(define (jbd-round-prec bd prec mode) - (let ((u (jbigdec-unscaled bd)) (s (jbigdec-scale bd))) - (if (= u 0) - bd - (let ((digs (jbd-digits u))) - (if (<= digs prec) - bd - (let* ((drop (- digs prec)) (div (expt 10 drop)) - (neg (< u 0)) (au (abs u)) - (q (quotient au div)) (r (remainder au div)) - (q2 (if (jbd-round-inc? q r div mode neg) (+ q 1) q)) - (res (make-jbigdec (if neg (- q2) q2) (- s drop)))) - ;; a carry can add a digit back (99 -> 100 at precision 2) - (if (> (jbd-digits q2) prec) (jbd-round-prec res prec mode) res))))))) -(define (jbd-mc-round x) - (let ((mc (and (jbigdec? x) (jbd-math-context)))) - (if mc (jbd-round-prec x (jbd-mc-precision mc) (jbd-mc-mode mc)) x))) - -;; A binary op over operands that may mix bigdec / integer / flonum. flonum-op is -;; the native fallback for the double-contagion path; bd-op is the exact bigdec op -;; (its result rounds through a bound *math-context*). -(define (jbd-binop flonum-op bd-op a b) - (if (or (flonum? a) (flonum? b)) - (flonum-op (if (jbigdec? a) (jbigdec->flonum a) a) - (if (jbigdec? b) (jbigdec->flonum b) b)) - (jbd-mc-round (bd-op (jbd-coerce a) (jbd-coerce b))))) - -;; --- variadic engine ops (Phase-2 emit targets + value-position folds) ------- -(define (jbd-fold flonum-op bd-op init xs) - (let loop ((acc init) (rest xs)) - (if (null? rest) acc (loop (jbd-binop flonum-op bd-op acc (car rest)) (cdr rest))))) - -(define (jbd-add . xs) - (cond ((null? xs) (make-jbigdec 0 0)) - ((null? (cdr xs)) (car xs)) - (else (jbd-fold + jbd2+ (car xs) (cdr xs))))) -(define (jbd-sub . xs) - (cond ((null? xs) (error #f "- needs at least 1 arg")) - ((null? (cdr xs)) (if (jbigdec? (car xs)) (jbd-negate (car xs)) (- (car xs)))) - (else (jbd-fold - jbd2- (car xs) (cdr xs))))) -(define (jbd-mul . xs) - (cond ((null? xs) (make-jbigdec 1 0)) - ((null? (cdr xs)) (car xs)) - (else (jbd-fold * jbd2* (car xs) (cdr xs))))) -(define (jbd-div . xs) - (cond ((null? xs) (error #f "/ needs at least 1 arg")) - ((null? (cdr xs)) (jbd-binop / jbd2-div (make-jbigdec 1 0) (car xs))) - (else (jbd-fold / jbd2-div (car xs) (cdr xs))))) - -;; comparison / predicate helpers (Phase-2 emit targets). A flonum operand demotes -;; to the native comparison on the flonum values. -(define (jbd-cmp-num op flop a b) - (if (or (flonum? a) (flonum? b)) - (flop (if (jbigdec? a) (jbigdec->flonum a) a) (if (jbigdec? b) (jbigdec->flonum b) b)) - (op (jbd-compare2 (jbd-coerce a) (jbd-coerce b)) 0))) -(define (jbd-lt? a b) (jbd-cmp-num < < a b)) -(define (jbd-gt? a b) (jbd-cmp-num > > a b)) -(define (jbd-le? a b) (jbd-cmp-num <= <= a b)) -(define (jbd-ge? a b) (jbd-cmp-num >= >= a b)) -(define (jbd-zero? a) (= 0 (jbigdec-unscaled a))) -(define (jbd-pos? a) (> (jbigdec-unscaled a) 0)) -(define (jbd-neg? a) (< (jbigdec-unscaled a) 0)) -(define (jbd-quot a b) (jbd-int-quot (jbd-coerce a) (jbd-coerce b))) -(define (jbd-rem a b) (jbd-int-rem (jbd-coerce a) (jbd-coerce b))) - -;; min/max compare by value but return the ORIGINAL operand (its type and scale -;; unchanged), matching java/Clojure: (min 1M 2.0) -> 1M, (max 1M 2.0) -> 2.0, -;; (min 1.50M 2M) -> 1.50M. Comparison handles a bigdec mixed with an int / flonum. -(define (jbd-value-compare a b) - (if (or (flonum? a) (flonum? b)) - (let ((fa (if (jbigdec? a) (jbigdec->flonum a) a)) (fb (if (jbigdec? b) (jbigdec->flonum b) b))) - (cond ((< fa fb) -1) ((> fa fb) 1) (else 0))) - (jbd-compare2 (jbd-coerce a) (jbd-coerce b)))) -;; strict comparison so a tie keeps the second operand, like Clojure's -;; (if (< x y) x y) / (if (> x y) x y): (max 1.5M 1.50M) -> 1.50M. -(define (jbd-min2 a b) (if (< (jbd-value-compare a b) 0) a b)) -(define (jbd-max2 a b) (if (> (jbd-value-compare a b) 0) a b)) -(define (jbd-min x . xs) (fold-left jbd-min2 x xs)) -(define (jbd-max x . xs) (fold-left jbd-max2 x xs)) - -;; --- wire into the value model ---------------------------------------------- -(def-var! "clojure.core" "bigdec" jolt-bigdec) - -;; The seq.ss binary numeric dispatch (jolt-add2/… and the jolt-n* macros) routes -;; any op whose operand is outside Chez's tower to the *-slow hooks; extend each -;; with a bigdec arm. Every arithmetic position (call, value, higher-order) -;; funnels through these, so contagion and *math-context* rounding apply -;; uniformly. min/max need no arm: the generic jolt-min2 compares through -;; jolt-num-cmp-slow and returns the original operand. -(set! jolt-num-slow? - (let ((prev jolt-num-slow?)) (lambda (x) (or (jbigdec? x) (prev x))))) -(define (jbd-extend-hook prev bd-op) - (lambda (a b) - (if (or (jbigdec? a) (jbigdec? b)) (bd-op a b) (prev a b)))) -(set! jolt-add-slow (jbd-extend-hook jolt-add-slow (lambda (a b) (jbd-binop + jbd2+ a b)))) -(set! jolt-sub-slow (jbd-extend-hook jolt-sub-slow (lambda (a b) (jbd-binop - jbd2- a b)))) -(set! jolt-mul-slow (jbd-extend-hook jolt-mul-slow (lambda (a b) (jbd-binop * jbd2* a b)))) -(set! jolt-div-slow (jbd-extend-hook jolt-div-slow (lambda (a b) (jbd-binop / jbd2-div a b)))) -(set! jolt-num-cmp-slow - (let ((prev jolt-num-cmp-slow)) - (lambda (a b) - (if (and (or (jbigdec? a) (jbigdec? b)) (jbd-numberish? a) (jbd-numberish? b)) - (jbd-value-compare a b) - (prev a b))))) -;; quot/rem/mod: a double operand demotes to the double path; exact operands use -;; the integer-division bigdec ops (mod = rem, floor-adjusted to the divisor's sign). -(define (jbd->num x) (if (jbigdec? x) (jbigdec->flonum x) x)) -(set! jolt-quot-slow - (jbd-extend-hook jolt-quot-slow - (lambda (a b) (if (or (flonum? a) (flonum? b)) - (jolt-quot (jbd->num a) (jbd->num b)) - (jbd-int-quot (jbd-coerce a) (jbd-coerce b)))))) -(set! jolt-rem-slow - (jbd-extend-hook jolt-rem-slow - (lambda (a b) (if (or (flonum? a) (flonum? b)) - (jolt-rem (jbd->num a) (jbd->num b)) - (jbd-int-rem (jbd-coerce a) (jbd-coerce b)))))) -(set! jolt-mod-slow - (jbd-extend-hook jolt-mod-slow - (lambda (a b) - (if (or (flonum? a) (flonum? b)) - (jolt-mod (jbd->num a) (jbd->num b)) - (let* ((bb (jbd-coerce b)) - (m (jbd-int-rem (jbd-coerce a) bb))) - (if (or (jbd-zero? m) (eq? (jbd-neg? m) (jbd-neg? bb))) m (jbd2+ m bb))))))) -;; unary shims: inc/dec and the sign predicates take a bigdec arm. set! updates -;; call-position references; the re-def-var! updates the var cell AND claims the -;; wrapped proc's class name before the prelude's inc'/dec' aliases are defined -;; ((type inc) stays clojure.core$inc — first def wins in the class registry). -(define jbd-one (make-jbigdec 1 0)) -(set! jolt-inc (let ((prev jolt-inc)) (lambda (x) (if (jbigdec? x) (jbd-mc-round (jbd2+ x jbd-one)) (prev x))))) -(set! jolt-dec (let ((prev jolt-dec)) (lambda (x) (if (jbigdec? x) (jbd-mc-round (jbd2- x jbd-one)) (prev x))))) -(set! jolt-zero? (let ((prev jolt-zero?)) (lambda (x) (if (jbigdec? x) (jbd-zero? x) (prev x))))) -(set! jolt-pos? (let ((prev jolt-pos?)) (lambda (x) (if (jbigdec? x) (jbd-pos? x) (prev x))))) -(set! jolt-neg? (let ((prev jolt-neg?)) (lambda (x) (if (jbigdec? x) (jbd-neg? x) (prev x))))) -;; a BigDecimal IS a number (java.lang.Number): extend the number? native so the -;; predicate — and everything defined over it (num, =='s guard) — accepts it. -;; The compiled fast paths test Chez number? directly and are unaffected. -(set! jolt-number? (let ((prev jolt-number?)) (lambda (x) (if (jbigdec? x) #t (prev x))))) -(def-var! "clojure.core" "number?" jolt-number?) -(def-var! "clojure.core" "inc" jolt-inc) -(def-var! "clojure.core" "dec" jolt-dec) -(def-var! "clojure.core" "zero?" jolt-zero?) -(def-var! "clojure.core" "pos?" jolt-pos?) -(def-var! "clojure.core" "neg?" jolt-neg?) - -;; rationalize: reference Clojure goes through BigDecimal.valueOf(double) — the -;; SHORTEST decimal print of the double, not its exact binary value — so -;; (rationalize 1.1) is 11/10. A bigdec is exact already; other exacts pass through. -(define (jolt-rationalize x) - (cond ((jbigdec? x) (/ (jbigdec-unscaled x) (expt 10 (jbigdec-scale x)))) - ((flonum? x) - (if (or (nan? x) (infinite? x)) - (jolt-throw (jolt-host-throwable "java.lang.NumberFormatException" - (string-append "Invalid input: " (number->string x)))) - (let ((bd (jolt-bigdec-from-string (jolt-num->string x)))) - (/ (jbigdec-unscaled bd) (expt 10 (jbigdec-scale bd)))))) - ((number? x) x) - (else (jolt-num-cast-throw x)))) -(def-var! "clojure.core" "rationalize" jolt-rationalize) - -;; double/float of a bigdec is its flonum value. -(set! jolt-double-slow - (let ((prev jolt-double-slow)) - (lambda (x) (if (jbigdec? x) (jbigdec->flonum x) (prev x))))) - -;; narrow casts truncate a bigdec like Number.longValue. -(set! jolt-cast-truncate-slow - (let ((prev jolt-cast-truncate-slow)) - (lambda (x) - (if (jbigdec? x) - (truncate (/ (jbigdec-unscaled x) (expt 10 (jbigdec-scale x)))) - (prev x))))) - -;; compare: add a bigdec arm (enables compare / sort / sorted collections). A -;; bigdec vs a plain number compares by value; bigdec vs bigdec is scale-independent. -(define jbd-prev-compare jolt-compare) -(define (jbd-numberish? x) (or (jbigdec? x) (number? x))) -(set! jolt-compare - (lambda (a b) - (if (and (or (jbigdec? a) (jbigdec? b)) (jbd-numberish? a) (jbd-numberish? b)) - (if (or (flonum? a) (flonum? b)) - (let ((fa (if (jbigdec? a) (jbigdec->flonum a) a)) - (fb (if (jbigdec? b) (jbigdec->flonum b) b))) - (cond ((< fa fb) -1) ((> fa fb) 1) (else 0))) - (jbd-compare2 (jbd-coerce a) (jbd-coerce b))) - (jbd-prev-compare a b)))) -(def-var! "clojure.core" "compare" jolt-compare) - -;; equality: a bigdec equals only another bigdec, by value (matching (= 3M 3) = false). -(register-eq-arm! (lambda (a b) (or (jbigdec? a) (jbigdec? b))) - (lambda (a b) (and (jbigdec? a) (jbigdec? b) (jbigdec=? a b)))) - -;; str drops the M; pr/pr-str keep it. -(register-str-render! jbigdec? jbigdec->string) -(register-pr-arm! jbigdec? (lambda (x) (string-append (jbigdec->string x) "M"))) - -;; class / decimal? -(register-class-arm! jbigdec? (lambda (x) "java.math.BigDecimal")) -(set! jolt-decimal? (lambda (x) (jbigdec? x))) -(def-var! "clojure.core" "decimal?" jolt-decimal?) diff --git a/host/chez/java/byte-buffer.ss b/host/chez/java/byte-buffer.ss deleted file mode 100644 index e2a7f62..0000000 --- a/host/chez/java/byte-buffer.ss +++ /dev/null @@ -1,85 +0,0 @@ -;; byte-buffer.ss — java.nio.ByteBuffer over a jolt byte-array. A buffer is a -;; jhost tagged "byte-buffer" with mutable #(backing-array position limit); the -;; backing is a jolt byte-array (vector of 0..255). Covers the slice of the API -;; portable code reaches for — wrap / get(byte[]) / array / remaining / position / -;; limit / duplicate / flip / rewind — e.g. cognitect aws-api wrapping blob bytes. - -(define (make-byte-buffer backing pos limit) (make-jhost "byte-buffer" (vector backing pos limit))) -(define (bb? x) (and (jhost? x) (string=? (jhost-tag x) "byte-buffer"))) -(define (bb-backing b) (vector-ref (jhost-state b) 0)) -(define (bb-pos b) (vector-ref (jhost-state b) 1)) -(define (bb-limit b) (vector-ref (jhost-state b) 2)) -(define (bb-pos! b n) (vector-set! (jhost-state b) 1 n)) -(define (bb-limit! b n) (vector-set! (jhost-state b) 2 n)) -(define (bb-capacity b) (vector-length (jolt-array-vec (bb-backing b)))) - -;; (ByteBuffer/wrap ba) | (ByteBuffer/wrap ba off len) | (ByteBuffer/allocate n) -(register-class-statics! "ByteBuffer" - (list - (cons "wrap" (lambda (ba . rest) - (let ((cap (vector-length (jolt-array-vec ba)))) - (if (pair? rest) - (let ((off (jnum->exact (car rest))) (len (jnum->exact (cadr rest)))) - (make-byte-buffer ba off (+ off len))) - (make-byte-buffer ba 0 cap))))) - (cons "allocate" (lambda (n) - (let ((cap (jnum->exact n))) - (make-byte-buffer (make-jolt-array (make-vector cap 0) 'byte) 0 cap)))) - ;; jolt has one heap; a direct buffer is just a buffer here. - (cons "allocateDirect" (lambda (n) - (let ((cap (jnum->exact n))) - (make-byte-buffer (make-jolt-array (make-vector cap 0) 'byte) 0 cap)))))) - -(register-host-methods! "byte-buffer" - (list - (cons "remaining" (lambda (self) (->num (- (bb-limit self) (bb-pos self))))) - (cons "hasRemaining" (lambda (self) (> (bb-limit self) (bb-pos self)))) - ;; position / limit are getters with no arg, setters (returning the buffer) with one - (cons "position" (lambda (self . a) - (if (pair? a) (begin (bb-pos! self (jnum->exact (car a))) self) (->num (bb-pos self))))) - (cons "limit" (lambda (self . a) - (if (pair? a) (begin (bb-limit! self (jnum->exact (car a))) self) (->num (bb-limit self))))) - (cons "capacity" (lambda (self) (->num (bb-capacity self)))) - (cons "hasArray" (lambda (self) #t)) - (cons "array" (lambda (self) (bb-backing self))) - (cons "duplicate" (lambda (self) (make-byte-buffer (bb-backing self) (bb-pos self) (bb-limit self)))) - (cons "rewind" (lambda (self) (bb-pos! self 0) self)) - (cons "flip" (lambda (self) (bb-limit! self (bb-pos self)) (bb-pos! self 0) self)) - (cons "clear" (lambda (self) (bb-pos! self 0) (bb-limit! self (bb-capacity self)) self)) - ;; (.get dst) | (.get dst off len): bulk copy from position into a byte-array, - ;; advancing position. Returns the buffer like the JVM. - ;; (.put src): copy bytes into the buffer at position, advancing it. src is - ;; another ByteBuffer (its remaining bytes), a byte-array, or a single byte. - (cons "put" (lambda (self src . rest) - (let ((dv (jolt-array-vec (bb-backing self))) (dp (bb-pos self))) - (cond - ((bb? src) - (let* ((sv (jolt-array-vec (bb-backing src))) (sp (bb-pos src)) - (n (- (bb-limit src) sp))) - (do ((i 0 (fx+ i 1))) ((fx=? i n)) - (vector-set! dv (+ dp i) (vector-ref sv (+ sp i)))) - (bb-pos! src (bb-limit src)) (bb-pos! self (+ dp n)))) - ((jolt-array? src) - (let* ((sv (jolt-array-vec src)) (n (vector-length sv))) - (do ((i 0 (fx+ i 1))) ((fx=? i n)) - (vector-set! dv (+ dp i) (vector-ref sv i))) - (bb-pos! self (+ dp n)))) - (else (vector-set! dv dp (jnum->exact src)) (bb-pos! self (+ dp 1)))) - self))) - (cons "get" (lambda (self dst . rest) - (let* ((src (jolt-array-vec (bb-backing self))) - (dv (jolt-array-vec dst)) - (off (if (pair? rest) (jnum->exact (car rest)) 0)) - (len (if (and (pair? rest) (pair? (cdr rest))) (jnum->exact (cadr rest)) (vector-length dv))) - (p (bb-pos self))) - (do ((i 0 (+ i 1))) ((= i len)) - (vector-set! dv (+ off i) (vector-ref src (+ p i)))) - (bb-pos! self (+ p len)) - self))))) - -(register-class-arm! bb? (lambda (x) "java.nio.ByteBuffer")) -(register-instance-check-arm! - (lambda (type-sym val) - (if (and (symbol-t? type-sym) (bb? val) - (member (last-dot (symbol-t-name type-sym)) '("ByteBuffer"))) - #t 'pass))) diff --git a/host/chez/java/class-hierarchy.ss b/host/chez/java/class-hierarchy.ss deleted file mode 100644 index 484a908..0000000 --- a/host/chez/java/class-hierarchy.ss +++ /dev/null @@ -1,261 +0,0 @@ -;; class-hierarchy.ss — one JVM class/interface graph, the single source of truth -;; for every "what classes does this satisfy" question. value-host-tags (protocol -;; dispatch), instance?, isa?/supers/ancestors, and the exception hierarchy all -;; derive from the ONE table here instead of maintaining parallel hand-kept lists -;; that drift apart. -;; -;; The graph is keyed by canonical (FQN) class name -> its DIRECT super -;; interfaces/classes (also FQN). Transitivity is computed (jch-closure), so a row -;; lists only what a class directly extends/implements, matching the JVM source. -;; -;; It is OPEN: a library registers a class and its supers with -;; jolt.host/register-class-supers! (plus a class-arm in host-class.ss to map its -;; values to that class name), and every derived view picks the class up with no -;; core change. Loaded before records.ss so value-host-tags can derive from it. - -;; canonical-name -> list of direct super canonical-names. Mutable + extensible. -(define jvm-class-parents (make-hashtable string-hash string=?)) -;; closure cache, invalidated whenever the graph is extended. -(define jch-closure-cache (make-hashtable string-hash string=?)) -(define jch-tags-cache (make-hashtable string-hash string=?)) - -;; Merge direct supers for a class (union with any already registered). Public so -;; libraries can graft their own classes onto the modeled hierarchy. -(define (jch-register-supers! name supers) - (let ((cur (hashtable-ref jvm-class-parents name '()))) - (hashtable-set! jvm-class-parents name - (let add ((ss supers) (acc cur)) - (cond ((null? ss) acc) - ((member (car ss) acc) (add (cdr ss) acc)) - (else (add (cdr ss) (append acc (list (car ss))))))))) - (hashtable-clear! jch-closure-cache) - (hashtable-clear! jch-tags-cache)) - -(define (jch-direct-supers name) (hashtable-ref jvm-class-parents name '())) - -;; Replace a class's direct supers outright (defrecord re-declares the row its -;; deftype half registered). Same cache invalidation as a register. -(define (jch-set-supers! name supers) - (hashtable-set! jvm-class-parents name supers) - (hashtable-clear! jch-closure-cache) - (hashtable-clear! jch-tags-cache) - (set! jch-known-cache #f) - (set! jch-simple->fqn-cache #f)) - -;; transitive supers of NAME (canonical), excluding NAME and Object; Object is the -;; universal root supplied by callers. Breadth-first, deduped, stable order. -(define (jch-closure name) - (or (hashtable-ref jch-closure-cache name #f) - (let ((result - (let loop ((pending (jch-direct-supers name)) (seen '())) - (cond ((null? pending) (reverse seen)) - ((member (car pending) seen) (loop (cdr pending) seen)) - (else (loop (append (jch-direct-supers (car pending)) (cdr pending)) - (cons (car pending) seen))))))) - (hashtable-set! jch-closure-cache name result) - result))) - -;; ns segment munging for a JVM-spelled class name: dashes become underscores -;; (clojure.core-test.x -> clojure.core_test.x). -(define (jch-munge-segments s) - (list->string (map (lambda (c) (if (char=? c #\-) #\_ c)) (string->list s)))) - -(define (jch-last-segment s) - (let loop ((i (- (string-length s) 1))) - (cond ((< i 0) s) - ((char=? (string-ref s i) #\.) (substring s (+ i 1) (string-length s))) - ((char=? (string-ref s i) #\$) (substring s (+ i 1) (string-length s))) - (else (loop (- i 1)))))) - -;; The protocol-dispatch / instance? tag list for a value of class NAME: the class -;; and its whole ancestry, each in BOTH canonical and simple spelling (extend-protocol -;; and instance? accept either "Associative" or "clojure.lang.Associative"), plus -;; "Object". Memoized — this is on the hot protocol-dispatch path. -(define (jch-tags name) - (or (hashtable-ref jch-tags-cache name #f) - (let* ((chain (cons name (jch-closure name))) - (result - (let build ((cs chain) (acc '())) - (if (null? cs) - (reverse (cons "Object" acc)) - (let* ((fqn (car cs)) - (simple (jch-last-segment fqn)) - (acc1 (if (member fqn acc) acc (cons fqn acc))) - (acc2 (if (or (string=? simple fqn) (member simple acc1)) - acc1 (cons simple acc1)))) - (build (cdr cs) acc2)))))) - (hashtable-set! jch-tags-cache name result) - result))) - -;; Is WANTED (canonical or simple) the class CHILD (canonical) or one of its -;; ancestors? Object is every class's root. Matched by full name or last segment so -;; "IOException" and "java.io.IOException" both hit. -(define (jch-isa? child wanted) - (let ((wseg (jch-last-segment wanted))) - (or (string=? wanted "java.lang.Object") (string=? wanted "Object") - (let loop ((names (cons child (jch-closure child)))) - (cond ((null? names) #f) - ((or (string=? wanted (car names)) - (string=? wseg (jch-last-segment (car names)))) #t) - (else (loop (cdr names)))))))) - -;; Does the graph model WANTED at all (as a class or as any class's ancestor)? Used -;; by instance? to decide between a definitive #f and 'pass (defer to other arms). -(define jch-known-cache #f) -(define (jch-known? wanted) - (when (not jch-known-cache) - (set! jch-known-cache (make-hashtable string-hash string=?)) - (let-values (((keys vals) (hashtable-entries jvm-class-parents))) - (vector-for-each - (lambda (k supers) - (hashtable-set! jch-known-cache k #t) - (hashtable-set! jch-known-cache (jch-last-segment k) #t) - (for-each (lambda (s) - (hashtable-set! jch-known-cache s #t) - (hashtable-set! jch-known-cache (jch-last-segment s) #t)) - supers)) - keys vals))) - (or (hashtable-ref jch-known-cache wanted #f) - (hashtable-ref jch-known-cache (jch-last-segment wanted) #f))) - -;; simple last-segment -> canonical FQN for a modeled class (first registered -;; wins). Lets a simple exception name (from chez-condition-exc-class) resolve to -;; its graph key so the exception hierarchy answers through the one graph. -(define jch-simple->fqn-cache #f) -(define (jch-fqn-of-simple name) - (when (not jch-simple->fqn-cache) - (set! jch-simple->fqn-cache (make-hashtable string-hash string=?)) - (let-values (((keys vals) (hashtable-entries jvm-class-parents))) - (vector-for-each - (lambda (k supers) - (for-each (lambda (n) - (let ((seg (jch-last-segment n))) - (when (not (hashtable-ref jch-simple->fqn-cache seg #f)) - (hashtable-set! jch-simple->fqn-cache seg n)))) - (cons k supers))) - keys vals))) - (or (hashtable-ref jch-simple->fqn-cache name #f) name)) - -;; A register also invalidates the derived caches. -(define jch-register-supers!-inner jch-register-supers!) -(set! jch-register-supers! - (lambda (name supers) - (set! jch-known-cache #f) - (set! jch-simple->fqn-cache #f) - (jch-register-supers!-inner name supers))) - -;; ---- interface marking --------------------------------------------------------- -;; The JVM distinguishes a concrete class (whose bases/supers chain roots at -;; Object) from an interface (whose don't). The graph marks the modeled -;; interfaces; anything unmarked is treated as a concrete class. -(define jch-interface-set (make-hashtable string-hash string=?)) -(define (jch-mark-interface! name) (hashtable-set! jch-interface-set name #t)) -(define (jch-interface? name) (hashtable-ref jch-interface-set name #f)) -(for-each jch-mark-interface! - '("clojure.lang.Seqable" "clojure.lang.Sequential" "clojure.lang.Sorted" - "clojure.lang.Reversible" "clojure.lang.Indexed" "clojure.lang.Counted" - "clojure.lang.Named" "clojure.lang.Fn" "clojure.lang.IFn" - "clojure.lang.IPersistentCollection" "clojure.lang.ISeq" - "clojure.lang.Associative" "clojure.lang.ILookup" - "clojure.lang.IPersistentStack" "clojure.lang.IPersistentVector" - "clojure.lang.IPersistentMap" "clojure.lang.IPersistentSet" - "clojure.lang.IPersistentList" "clojure.lang.IObj" "clojure.lang.IMeta" - "clojure.lang.IDeref" "clojure.lang.IRecord" "clojure.lang.IType" - "clojure.lang.IHashEq" "clojure.lang.IEditableCollection" - "clojure.lang.IExceptionInfo" "clojure.lang.IReduceInit" - "java.util.List" "java.util.Set" "java.util.Collection" "java.util.Map" - "java.util.Iterator" "java.lang.Iterable" "java.lang.CharSequence" - "java.lang.Comparable" "java.lang.Runnable" - "java.util.concurrent.Callable" "java.io.Serializable")) - -;; ---- seed the built-in graph: direct supers only, faithful to the JVM --------- -;; core clojure.lang interfaces -(jch-register-supers! "clojure.lang.IPersistentCollection" '("clojure.lang.Seqable")) -(jch-register-supers! "clojure.lang.ISeq" '("clojure.lang.IPersistentCollection")) -(jch-register-supers! "clojure.lang.Associative" '("clojure.lang.IPersistentCollection" "clojure.lang.ILookup")) -(jch-register-supers! "clojure.lang.IPersistentStack" '("clojure.lang.IPersistentCollection")) -(jch-register-supers! "clojure.lang.IPersistentVector" '("clojure.lang.Associative" "clojure.lang.Sequential" - "clojure.lang.IPersistentStack" "clojure.lang.Reversible" - "clojure.lang.Indexed")) -(jch-register-supers! "clojure.lang.IPersistentMap" '("java.lang.Iterable" "clojure.lang.Associative" "clojure.lang.Counted")) -(jch-register-supers! "clojure.lang.IPersistentSet" '("clojure.lang.IPersistentCollection" "clojure.lang.Counted")) -(jch-register-supers! "clojure.lang.IPersistentList" '("clojure.lang.Sequential" "clojure.lang.IPersistentStack")) -(jch-register-supers! "clojure.lang.IObj" '("clojure.lang.IMeta")) -(jch-register-supers! "clojure.lang.IFn" '("java.lang.Runnable" "java.util.concurrent.Callable")) -(jch-register-supers! "clojure.lang.Fn" '("clojure.lang.IFn")) -(jch-register-supers! "clojure.lang.AFn" '("clojure.lang.IFn")) -(jch-register-supers! "clojure.lang.AFunction" '("clojure.lang.AFn" "clojure.lang.Fn")) -;; java.util collection interfaces -(jch-register-supers! "java.util.List" '("java.util.Collection")) -(jch-register-supers! "java.util.Set" '("java.util.Collection")) -(jch-register-supers! "java.util.Collection" '("java.lang.Iterable")) -;; concrete collection classes -(jch-register-supers! "clojure.lang.APersistentVector" '("clojure.lang.IPersistentVector" "java.util.List")) -(jch-register-supers! "clojure.lang.PersistentVector" '("clojure.lang.APersistentVector" "clojure.lang.IObj" - "java.util.List" "java.lang.Comparable")) -(jch-register-supers! "clojure.lang.APersistentMap" '("clojure.lang.IPersistentMap" "java.util.Map")) -(jch-register-supers! "clojure.lang.PersistentArrayMap" '("clojure.lang.APersistentMap" "clojure.lang.IObj")) -(jch-register-supers! "clojure.lang.PersistentHashMap" '("clojure.lang.APersistentMap" "clojure.lang.IObj")) -(jch-register-supers! "clojure.lang.PersistentTreeMap" '("clojure.lang.APersistentMap" "clojure.lang.IObj" "clojure.lang.Sorted" "clojure.lang.Reversible")) -(jch-register-supers! "clojure.lang.APersistentSet" '("clojure.lang.IPersistentSet" "java.util.Set")) -(jch-register-supers! "clojure.lang.PersistentHashSet" '("clojure.lang.APersistentSet" "clojure.lang.IObj")) -(jch-register-supers! "clojure.lang.PersistentTreeSet" '("clojure.lang.APersistentSet" "clojure.lang.IObj" "clojure.lang.Sorted" "clojure.lang.Reversible")) -(jch-register-supers! "clojure.lang.ASeq" '("clojure.lang.ISeq" "clojure.lang.Sequential" "java.util.List")) -(jch-register-supers! "clojure.lang.PersistentList" '("clojure.lang.ASeq" "clojure.lang.IPersistentList" "clojure.lang.Counted")) -(jch-register-supers! "clojure.lang.PersistentList$EmptyList" '("clojure.lang.PersistentList")) -(jch-register-supers! "clojure.lang.LazySeq" '("clojure.lang.ISeq" "clojure.lang.Sequential" "java.util.List" "clojure.lang.IObj")) -(jch-register-supers! "clojure.lang.Cons" '("clojure.lang.ASeq")) -(jch-register-supers! "clojure.lang.PersistentQueue" '("clojure.lang.IPersistentList" "clojure.lang.IPersistentCollection" "java.util.Collection")) -;; scalars / named / callable -(jch-register-supers! "clojure.lang.Keyword" '("clojure.lang.IFn" "clojure.lang.Named" "java.lang.Comparable")) -(jch-register-supers! "clojure.lang.Symbol" '("clojure.lang.IObj" "clojure.lang.IFn" "clojure.lang.Named" "java.lang.Comparable")) -(jch-register-supers! "clojure.lang.Var" '("clojure.lang.IDeref" "clojure.lang.IFn")) -(jch-register-supers! "clojure.lang.Atom" '("clojure.lang.IDeref")) -(jch-register-supers! "clojure.lang.Ratio" '("java.lang.Number" "java.lang.Comparable")) -(jch-register-supers! "clojure.lang.BigInt" '("java.lang.Number")) -(jch-register-supers! "java.lang.String" '("java.lang.CharSequence" "java.lang.Comparable")) -(jch-register-supers! "java.lang.Long" '("java.lang.Number" "java.lang.Comparable")) -(jch-register-supers! "java.lang.Integer" '("java.lang.Number" "java.lang.Comparable")) -(jch-register-supers! "java.lang.Double" '("java.lang.Number" "java.lang.Comparable")) -(jch-register-supers! "java.lang.Float" '("java.lang.Number" "java.lang.Comparable")) -(jch-register-supers! "java.math.BigDecimal" '("java.lang.Number" "java.lang.Comparable")) -(jch-register-supers! "java.math.BigInteger" '("java.lang.Number" "java.lang.Comparable")) -(jch-register-supers! "java.lang.Boolean" '("java.lang.Comparable")) -(jch-register-supers! "java.lang.Character" '("java.lang.Comparable")) -(jch-register-supers! "java.util.UUID" '("java.lang.Comparable")) -;; exception hierarchy (folds in the former exception-parent table) -(jch-register-supers! "java.lang.Exception" '("java.lang.Throwable")) -(jch-register-supers! "java.lang.RuntimeException" '("java.lang.Exception")) -(jch-register-supers! "clojure.lang.ExceptionInfo" '("java.lang.RuntimeException" "clojure.lang.IExceptionInfo")) -(jch-register-supers! "java.lang.IllegalArgumentException" '("java.lang.RuntimeException")) -(jch-register-supers! "clojure.lang.ArityException" '("java.lang.IllegalArgumentException")) -(jch-register-supers! "java.lang.NumberFormatException" '("java.lang.IllegalArgumentException")) -(jch-register-supers! "java.lang.IllegalStateException" '("java.lang.RuntimeException")) -(jch-register-supers! "java.lang.UnsupportedOperationException" '("java.lang.RuntimeException")) -(jch-register-supers! "java.lang.ArithmeticException" '("java.lang.RuntimeException")) -(jch-register-supers! "java.lang.NullPointerException" '("java.lang.RuntimeException")) -(jch-register-supers! "java.lang.ClassCastException" '("java.lang.RuntimeException")) -(jch-register-supers! "java.lang.IndexOutOfBoundsException" '("java.lang.RuntimeException")) -(jch-register-supers! "java.util.ConcurrentModificationException" '("java.lang.RuntimeException")) -(jch-register-supers! "java.util.NoSuchElementException" '("java.lang.RuntimeException")) -(jch-register-supers! "java.io.UncheckedIOException" '("java.lang.RuntimeException")) -(jch-register-supers! "java.time.DateTimeException" '("java.lang.RuntimeException")) -(jch-register-supers! "java.time.format.DateTimeParseException" '("java.time.DateTimeException")) -(jch-register-supers! "java.lang.InterruptedException" '("java.lang.Exception")) -(jch-register-supers! "java.io.IOException" '("java.lang.Exception")) -(jch-register-supers! "java.io.InterruptedIOException" '("java.io.IOException")) -(jch-register-supers! "java.io.FileNotFoundException" '("java.io.IOException")) -(jch-register-supers! "java.io.UnsupportedEncodingException" '("java.io.IOException")) -(jch-register-supers! "java.net.UnknownHostException" '("java.io.IOException")) -(jch-register-supers! "java.net.SocketException" '("java.io.IOException")) -(jch-register-supers! "java.net.ConnectException" '("java.net.SocketException")) -(jch-register-supers! "java.net.SocketTimeoutException" '("java.io.InterruptedIOException")) -(jch-register-supers! "java.net.MalformedURLException" '("java.io.IOException")) -(jch-register-supers! "javax.net.ssl.SSLException" '("java.io.IOException")) -(jch-register-supers! "java.lang.Error" '("java.lang.Throwable")) -(jch-register-supers! "java.lang.AssertionError" '("java.lang.Error")) -;; Throwable's only super is Object (universal), so no row needed for it. - -;; Public seam: libraries extend the modeled hierarchy. -(def-var! "jolt.host" "register-class-supers!" - (lambda (name supers) (jch-register-supers! name (seq->list supers)) jolt-nil)) diff --git a/host/chez/java/concurrency.ss b/host/chez/java/concurrency.ss deleted file mode 100644 index f0ed225..0000000 --- a/host/chez/java/concurrency.ss +++ /dev/null @@ -1,611 +0,0 @@ -;; concurrency.ss — real OS-thread futures + promises for the Chez host. -;; -;; SHARED-HEAP semantics, like JVM Clojure: a future body runs on a native thread -;; (fork-thread) over the SAME heap, so a captured atom is shared and the body's -;; mutations are visible to the parent. deref blocks on a mutex+condition latch. -;; -;; future / future-call / future-cancel / future? / future-done? / future-cancelled? -;; promise / deliver, and the deref extension for both, are bound here (some -;; re-asserted in post-prelude.ss over the overlay's versions). -;; -;; pmap / pcalls / pvalues live in the clojure.core overlay (40-lazy) expressed -;; over `future`, so they light up for free once future-call exists. -;; -;; Loaded near the end of rt.ss — after atoms.ss (jolt-deref, the atom lock) and -;; dyn-binding.ss (the thread-local binding stack we convey into the worker). -;; Requires a threaded Chez build (fork-thread / make-mutex / make-condition). - -;; --- time helpers ----------------------------------------------------------- -;; A relative duration / absolute deadline from a millisecond count (a jolt number). -(define (ms->duration ms) - (let* ((ms* (exact (floor ms))) - (secs (quotient ms* 1000)) - (nanos (* (remainder ms* 1000) 1000000))) - (make-time 'time-duration nanos secs))) -(define (ms->deadline ms) (add-duration (current-time 'time-utc) (ms->duration ms))) - -;; --- futures ---------------------------------------------------------------- -;; A future is a mutable cell guarded by `mu`; workers/derefs coordinate on `cv`. -;; done? — result (or cancellation) is final; derefs may proceed -;; cancelled? — future-cancel won before the body finished -;; ok? — payload is a value (else payload is a raised condition/value) -;; payload — the result value, or the captured throw -(define-record-type jolt-future - (fields (mutable done?) (mutable cancelled?) (mutable ok?) (mutable payload) mu cv) - (nongenerative jolt-future-v1)) - -;; (future-call thunk): spawn a thread running (thunk). The dynamic bindings in -;; effect now are conveyed into the worker (Chez inherits thread-parameters at -;; fork; we also install an explicit snapshot for certainty). The result — value -;; or thrown condition — is latched and broadcast; a cancel that already finalized -;; the future makes the late result a no-op. -(define (jolt-future-call thunk) - (let ((f (make-jolt-future #f #f #f jolt-nil (make-mutex) (make-condition))) - (snap (dyn-binding-stack))) - (fork-thread - (lambda () - (dyn-binding-stack snap) - (let ((r (guard (e (#t (cons #f e))) (cons #t (jolt-invoke thunk))))) - (with-mutex (jolt-future-mu f) - (unless (jolt-future-done? f) ; not already cancelled - (jolt-future-ok?-set! f (car r)) - (jolt-future-payload-set! f (cdr r)) - (jolt-future-done?-set! f #t)) - (condition-broadcast (jolt-future-cv f)))))) - f)) - -;; Final value of a settled future (called OUTSIDE the lock): re-raise a captured -;; throw, signal a cancellation, else the value. -(define (jolt-future-finish f) - (cond - ((jolt-future-cancelled? f) - (jolt-throw (jolt-ex-info "Future cancelled" (jolt-hash-map)))) - ((jolt-future-ok? f) (jolt-future-payload f)) - (else (raise (jolt-future-payload f))))) - -(define (jolt-future-deref f) - (with-mutex (jolt-future-mu f) - (let loop () - (unless (jolt-future-done? f) - (condition-wait (jolt-future-cv f) (jolt-future-mu f)) - (loop)))) - (jolt-future-finish f)) - -;; (deref f timeout-ms timeout-val): wait up to timeout-ms; return timeout-val if -;; it has not settled by the absolute deadline. -(define (jolt-future-deref-timed f ms timeout-val) - (let* ((deadline (ms->deadline ms)) - (settled (with-mutex (jolt-future-mu f) - (let loop () - (cond ((jolt-future-done? f) #t) - ((condition-wait (jolt-future-cv f) (jolt-future-mu f) deadline) - (loop)) ; woken — recheck - (else (jolt-future-done? f))))))) ; timed out: final check - (if settled (jolt-future-finish f) timeout-val))) - -;; future-cancel: the running thread can't be interrupted, but the future object -;; reflects the cancellation — if not already settled, mark it cancelled+done so -;; derefs raise and the predicates flip. Returns true iff this call cancelled it. -(define (jolt-future-cancel f) - (let ((cancelled (with-mutex (jolt-future-mu f) - (if (jolt-future-done? f) - #f - (begin (jolt-future-cancelled?-set! f #t) - (jolt-future-done?-set! f #t) - (condition-broadcast (jolt-future-cv f)) - #t))))) - cancelled)) - -(define (jolt-native-future-done? x) - (if (jolt-future? x) (jolt-future-done? x) - (jolt-throw (jolt-ex-info "future-done? requires a future" (jolt-hash-map))))) -(define (jolt-native-future-cancelled? x) - (and (jolt-future? x) (jolt-future-cancelled? x))) - -;; --- promises --------------------------------------------------------------- -;; A blocking promise (like the JVM): deref parks until deliver, then caches the -;; value. deliver wins once; later delivers return nil. -(define-record-type jolt-promise - (fields (mutable delivered?) (mutable value) mu cv) - (nongenerative jolt-promise-v1)) - -(define (jolt-promise-new) (make-jolt-promise #f jolt-nil (make-mutex) (make-condition))) - -(define (jolt-deliver p v) - (if (jolt-promise? p) - (let ((won (with-mutex (jolt-promise-mu p) - (if (jolt-promise-delivered? p) - #f - (begin (jolt-promise-value-set! p v) - (jolt-promise-delivered?-set! p #t) - (condition-broadcast (jolt-promise-cv p)) - #t))))) - (if won p jolt-nil)) - (jolt-throw (jolt-ex-info "deliver requires a promise" (jolt-hash-map))))) - -(define (jolt-promise-deref p) - (with-mutex (jolt-promise-mu p) - (let loop () - (unless (jolt-promise-delivered? p) - (condition-wait (jolt-promise-cv p) (jolt-promise-mu p)) - (loop)))) - (jolt-promise-value p)) - -(define (jolt-promise-deref-timed p ms timeout-val) - (let* ((deadline (ms->deadline ms)) - (got (with-mutex (jolt-promise-mu p) - (let loop () - (cond ((jolt-promise-delivered? p) #t) - ((condition-wait (jolt-promise-cv p) (jolt-promise-mu p) deadline) - (loop)) - (else (jolt-promise-delivered? p))))))) - (if got (jolt-promise-value p) timeout-val))) - -;; --- agents (async, per-agent serialized dispatch) -------------------------- -;; JVM semantics: send/send-off enqueue an action and a single worker thread -;; applies them to the state IN ORDER; deref reads the -;; (possibly not-yet-updated) state without blocking; await blocks until the queue -;; drains. An action error is captured (agent-error) and stops the queue. -(define-record-type jolt-agent - (fields (mutable state) (mutable err) (mutable validator) - (mutable queue) (mutable running?) mu cv) - (nongenerative jolt-agent-v1)) - -;; (agent state :meta m :validator f :error-mode e): the ARef ctor contract like -;; atom's — the validator runs against the initial state, :meta must be a map. -;; :error-mode is accepted/ignored (jolt agents are always :fail). -(define (jolt-agent-new state . opts) - (let loop ((o opts) (validator jolt-nil) (m #f)) - (cond - ((or (null? o) (null? (cdr o))) - (let ((a (make-jolt-agent state jolt-nil validator (vector '() '()) #f (make-mutex) (make-condition)))) - (when (and (not (jolt-nil? validator)) (jolt-not (jolt-invoke validator state))) - (jolt-iref-state-throw)) - (when (and m (not (jolt-nil? m))) - (unless (jolt-map? m) - (jolt-throw (jolt-host-throwable - "java.lang.ClassCastException" - (string-append "class " (jolt-class-name m) - " cannot be cast to class clojure.lang.IPersistentMap")))) - (hashtable-set! meta-table a m)) - a)) - ((and (keyword-t? (car o)) (string=? (keyword-t-name (car o)) "validator")) - (loop (cddr o) (cadr o) m)) - ((and (keyword-t? (car o)) (string=? (keyword-t-name (car o)) "meta")) - (loop (cddr o) validator (cadr o))) - (else (loop (cddr o) validator m))))) -;; agents are watchable IRefs; the worker notifies on each state change. -(register-iref-arm! jolt-agent?) - -;; The action queue is an amortized-O(1) FIFO held as a mutable #(out in): `out` is -;; the front, `in` holds sends reversed onto it (an append-to-a-list send was O(n)). -;; All three helpers run under the agent mutex. -(define (jagent-q-empty? a) - (let ((q (jolt-agent-queue a))) (and (null? (vector-ref q 0)) (null? (vector-ref q 1))))) -(define (jagent-q-push! a entry) - (let ((q (jolt-agent-queue a))) (vector-set! q 1 (cons entry (vector-ref q 1))))) -(define (jagent-q-pop! a) - (let ((q (jolt-agent-queue a))) - (when (null? (vector-ref q 0)) - (vector-set! q 0 (reverse (vector-ref q 1))) (vector-set! q 1 '())) - (let ((out (vector-ref q 0))) (vector-set! q 0 (cdr out)) (car out)))) - -;; Drain the queue, applying each action (f state arg*) outside the lock (an action -;; may send/deref the same agent). A validator rejection or a thrown action puts the -;; agent in an error state and halts the queue (JVM :fail mode). -(define (jolt-agent-worker a) - (let loop () - (let ((act (with-mutex (jolt-agent-mu a) - (if (or (not (jolt-nil? (jolt-agent-err a))) (jagent-q-empty? a)) - (begin (jolt-agent-running?-set! a #f) - (condition-broadcast (jolt-agent-cv a)) #f) - (jagent-q-pop! a))))) - (when act - (guard (e (#t (with-mutex (jolt-agent-mu a) - (jolt-agent-err-set! a e) - (condition-broadcast (jolt-agent-cv a))))) - (let* ((old (jolt-agent-state a)) - (nv (apply jolt-invoke (car act) old (cdr act)))) - (let ((vf (jolt-agent-validator a))) - (when (and (not (jolt-nil? vf)) (jolt-not (jolt-invoke vf nv))) - (jolt-iref-state-throw))) - (jolt-agent-state-set! a nv) - (iref-notify a old nv))) - (loop))))) - -;; send / send-off: enqueue the action, start the worker if idle. (jolt treats them -;; identically — one serialized worker per agent — which is observably a superset of -;; the JVM's fixed/cached pool split.) -(define (jolt-agent-send a f . args) - (with-mutex (jolt-agent-mu a) - (jagent-q-push! a (cons f args)) - (unless (jolt-agent-running? a) - (jolt-agent-running?-set! a #t) - (fork-thread (lambda () (jolt-agent-worker a))))) - a) - -;; (await & agents): block until each agent's queue has drained. -(define (jolt-agent-await . agents) - (for-each - (lambda (a) - (with-mutex (jolt-agent-mu a) - (let loop () - (when (or (jolt-agent-running? a) (not (jagent-q-empty? a))) - (condition-wait (jolt-agent-cv a) (jolt-agent-mu a)) (loop))))) - agents) - jolt-nil) - -(define (jolt-agent-error a) (jolt-agent-err a)) -(define (jolt-agent-restart a new-state . _opts) - (jolt-agent-err-set! a jolt-nil) - (jolt-agent-state-set! a new-state) - a) - -;; --- delay (lazy once-forced computation) ----------------------------------- -;; (delay body) -> (make-delay (fn [] body)) (overlay macro); force/deref run the -;; thunk once under a lock and cache the value (JVM delays are thread-safe). force -;; (overlay) is (if (delay? x) (deref x) x), so it works once delay?/deref do. -(define-record-type jolt-delay (fields thunk (mutable realized?) (mutable value) (mutable exn) mu) - (nongenerative jolt-delay-v1)) -(define (jolt-make-delay thunk) (make-jolt-delay thunk #f jolt-nil #f (make-mutex))) -;; run the thunk once, like Clojure's Delay: if it throws, cache the exception -;; (the delay IS realized) and re-throw it on every deref — do NOT re-run the -;; body (so value-fns memoize and there is no cache-stampede / retried side -;; effect). Store the exception inside the lock, re-raise outside it so the mutex -;; is always released. -(define (jolt-delay-force d) - (with-mutex (jolt-delay-mu d) - (unless (jolt-delay-realized? d) - (guard (e (#t (jolt-delay-exn-set! d e) (jolt-delay-realized?-set! d #t))) - (jolt-delay-value-set! d (jolt-invoke (jolt-delay-thunk d))) - (jolt-delay-realized?-set! d #t)))) - (if (jolt-delay-exn d) (raise (jolt-delay-exn d)) (jolt-delay-value d))) - -;; --- deref extension -------------------------------------------------------- -;; Chain the fully-built jolt-deref (atoms/vars/volatiles/reduced) with futures, -;; promises, agents, and delays; accept the timed (deref ref ms val) arity for the -;; blocking ref types. -(define %pre-conc-deref jolt-deref) -(set! jolt-deref - (lambda (x . opts) - (cond - ((jolt-future? x) - (if (null? opts) (jolt-future-deref x) - (jolt-future-deref-timed x (car opts) (cadr opts)))) - ((jolt-promise? x) - (if (null? opts) (jolt-promise-deref x) - (jolt-promise-deref-timed x (car opts) (cadr opts)))) - ((jolt-agent? x) (jolt-agent-state x)) - ((jolt-delay? x) (jolt-delay-force x)) - ;; a record/reify implementing clojure.lang.IDeref: @x calls its `deref` - ;; method with the value itself as the leading `this`. - ((and (jrec? x) (find-method-any-protocol (jrec-tag x) "deref")) - => (lambda (m) (jolt-invoke m x))) - ((and (reified-methods x) (hashtable-ref (reified-methods x) "deref" #f)) - => (lambda (m) (jolt-invoke m x))) - (else (apply %pre-conc-deref x opts))))) - -;; realized? for a future/promise/delay. Wrapped over the overlay version in -;; post-prelude.ss. -(define (jolt-conc-realized? x) - (cond ((jolt-future? x) (jolt-future-done? x)) - ((jolt-promise? x) (jolt-promise-delivered? x)) - ((jolt-delay? x) (jolt-delay-realized? x)) - (else #f))) - -;; --- bind into clojure.core ------------------------------------------------- -(def-var! "clojure.core" "future-call" jolt-future-call) -(def-var! "clojure.core" "future-cancel" jolt-future-cancel) -(def-var! "clojure.core" "future?" jolt-future?) -(def-var! "clojure.core" "future-done?" jolt-native-future-done?) -(def-var! "clojure.core" "future-cancelled?" jolt-native-future-cancelled?) -(def-var! "clojure.core" "promise" jolt-promise-new) -(def-var! "clojure.core" "deliver" jolt-deliver) -;; a promise is an IFn on the JVM: (p val) delivers. Registered as a cold -;; invoke arm; callable-host? feeds the ifn? overlay (multimethods included). -(register-invoke-arm! jolt-promise? - (lambda (p args) - (if (and (pair? args) (null? (cdr args))) - (jolt-deliver p (car args)) - (jolt-throw (jolt-host-throwable "clojure.lang.ArityException" - "Wrong number of args passed to a promise"))))) -(def-var! "jolt.host" "callable-host?" - (lambda (x) (if (or (jolt-multifn? x) (jolt-promise? x)) #t jolt-nil))) -(def-var! "clojure.core" "agent" jolt-agent-new) -(def-var! "clojure.core" "agent?" jolt-agent?) -(def-var! "clojure.core" "send" jolt-agent-send) -(def-var! "clojure.core" "send-off" jolt-agent-send) -(def-var! "clojure.core" "await" jolt-agent-await) -(def-var! "clojure.core" "agent-error" jolt-agent-error) -(def-var! "clojure.core" "restart-agent" jolt-agent-restart) -(def-var! "clojure.core" "make-delay" jolt-make-delay) -(def-var! "clojure.core" "delay?" jolt-delay?) -(def-var! "clojure.core" "deref" jolt-deref) - -;; --- object monitors (locking) ---------------------------------------------- -;; (locking obj body…) takes obj's monitor for the body — a real per-object lock -;; now that futures/agents/threads share one heap. Each object gets a recursive -;; Chez mutex (a thread may re-enter a monitor it already holds, like the JVM), -;; held in an identity-keyed weak table so monitors are reclaimed with their -;; objects. dynamic-wind releases on normal, exceptional, and continuation exit. -(define monitor-table (make-weak-eq-hashtable)) -(define monitor-table-lock (make-mutex)) -(define (object-monitor obj) - (with-mutex monitor-table-lock - (or (hashtable-ref monitor-table obj #f) - (let ((m (make-mutex))) (hashtable-set! monitor-table obj m) m)))) -(define (jolt-with-monitor obj thunk) - (let ((m (object-monitor obj))) - (dynamic-wind - (lambda () (mutex-acquire m)) - thunk - (lambda () (mutex-release m))))) -(def-var! "jolt.host" "with-monitor" jolt-with-monitor) - -;; --- cooperative thread interrupt ------------------------------------------- -;; Chez has no force-kill, but its engine timer (set-timer + timer-interrupt- -;; handler, thread-local) is polled at procedure-call / loop back-edges — so a -;; running computation, even a tight Scheme loop, can be aborted from another -;; thread. An interrupt TOKEN is a shared box; run-interruptible arms a periodic -;; timer in the eval thread whose handler escapes (via call/cc) when the token is -;; set; interrupt! sets the token from any thread. The aborted eval throws a jolt -;; ex-info {:jolt/interrupted true}, so the thread is REUSED, not abandoned. -;; -;; Caveat: a thread blocked in a __collect_safe foreign call (socket recv/accept, -;; sleep) only sees the interrupt when it returns to Scheme — like the JVM not -;; killing native code. -(define interrupt-check-ticks 100000) ; ~poll interval; responsive + low overhead -(define interrupt-sentinel (cons 'jolt 'interrupted)) -(define jolt-kw-interrupted (keyword "jolt" "interrupted")) -(define (jolt-make-interrupt) (box #f)) -(define (jolt-interrupt! token) (when (box? token) (set-box! token #t)) jolt-nil) -(define (jolt-interrupted? token) (and (box? token) (unbox token) #t)) -(define (jolt-run-interruptible token thunk) - (let ((prev-handler (timer-interrupt-handler))) - (let ((r (call/cc - (lambda (k) - (timer-interrupt-handler - (lambda () - (if (and (box? token) (unbox token)) - (k interrupt-sentinel) - (begin (set-timer interrupt-check-ticks) (void))))) - (set-timer interrupt-check-ticks) - (let ((v (thunk))) (set-timer 0) v))))) - ;; restore the prior timer state regardless of outcome. - (set-timer 0) - (timer-interrupt-handler prev-handler) - (if (eq? r interrupt-sentinel) - (jolt-throw (jolt-ex-info "Evaluation interrupted" (jolt-hash-map jolt-kw-interrupted #t))) - r)))) -(def-var! "jolt.host" "make-interrupt" jolt-make-interrupt) -(def-var! "jolt.host" "interrupt!" jolt-interrupt!) -(def-var! "jolt.host" "interrupted?" jolt-interrupted?) -(def-var! "jolt.host" "run-interruptible" jolt-run-interruptible) - -;; --- java.lang.Thread / java.util.concurrent.CountDownLatch ----------------- -;; Real OS threads over Chez fork-thread (shared heap — a captured atom/var is -;; shared). A Thread runs its Runnable thunk; start forks, join waits on a -;; condition latched at completion. CountDownLatch is a counting barrier. -(define (make-jthread thunk) (make-jhost "user-thread" (vector thunk #f (make-mutex) (make-condition)))) -(for-each (lambda (nm) (register-class-ctor! nm (lambda (thunk . _) (make-jthread thunk)))) - '("Thread" "java.lang.Thread")) -(register-host-methods! "user-thread" - (list (cons "start" (lambda (self) - (let ((st (jhost-state self)) (snap (dyn-binding-stack))) - (fork-thread (lambda () - (dyn-binding-stack snap) - (guard (e (#t #f)) (jolt-invoke (vector-ref st 0))) - (with-mutex (vector-ref st 2) - (vector-set! st 1 #t) - (condition-broadcast (vector-ref st 3))))) - jolt-nil))) - (cons "run" (lambda (self) (jolt-invoke (vector-ref (jhost-state self) 0)) jolt-nil)) - (cons "join" (lambda (self . _) - (let ((st (jhost-state self))) - (with-mutex (vector-ref st 2) - (let loop () (unless (vector-ref st 1) (condition-wait (vector-ref st 3) (vector-ref st 2)) (loop))))) - jolt-nil)) - (cons "isAlive" (lambda (self) (not (vector-ref (jhost-state self) 1)))) - (cons "interrupt" (lambda (self . _) jolt-nil)) - (cons "setDaemon" (lambda (self . _) jolt-nil)))) - -(define (make-jlatch n) (make-jhost "count-down-latch" (vector n (make-mutex) (make-condition)))) -(for-each (lambda (nm) (register-class-ctor! nm (lambda (n . _) (make-jlatch (jnum->exact n))))) - '("CountDownLatch" "java.util.concurrent.CountDownLatch")) -(register-host-methods! "count-down-latch" - (list (cons "countDown" (lambda (self) - (let ((st (jhost-state self))) - (with-mutex (vector-ref st 1) - (when (> (vector-ref st 0) 0) (vector-set! st 0 (- (vector-ref st 0) 1))) - (when (= (vector-ref st 0) 0) (condition-broadcast (vector-ref st 2))))) - jolt-nil)) - (cons "await" (lambda (self . _) - (let ((st (jhost-state self))) - (with-mutex (vector-ref st 1) - (let loop () (when (> (vector-ref st 0) 0) (condition-wait (vector-ref st 2) (vector-ref st 1)) (loop))))) - jolt-nil)) - (cons "getCount" (lambda (self) (vector-ref (jhost-state self) 0))))) - -;; --- main-thread executor --------------------------------------------------- -;; Lets a worker thread (e.g. an nREPL eval future) run a thunk on the thread -;; that owns the GUI main loop. On macOS GTK quartz, g_application_run must run -;; on the process main thread or AppKit aborts (setMainMenu off-main → SIGABRT). -;; Under `joltc nrepl` the accept loop is backgrounded in a future and the -;; primordial thread enters jolt-run-main-pump; glimmer's run marshals its -;; startup through jolt-call-on-main-thread. -;; -;; - With no pump running (`joltc -M:run` calls run directly on the main thread), -;; call-on-main-thread runs the thunk INLINE — unchanged behaviour. -;; - A call from a thunk already executing on the pump runs inline too, so the -;; pump can't deadlock on itself. -;; - Otherwise the thunk is enqueued; the caller blocks until the pump runs it, -;; then receives the value, or the thrown condition is re-raised. -;; -;; stop-main-pump is the graceful-shutdown / external API: it tells the pump to -;; drain whatever is queued and return. The pump-active flag is flipped to #f -;; under jolt-main-queue-mu in the same critical section that decides to exit, and -;; call-on-main-thread reads that flag and enqueues under the SAME mutex, so a job -;; can never slip in after the pump has decided to leave — a call that loses the -;; race simply runs inline instead of blocking forever on a pump that is gone. - -(define jolt-main-queue-mu (make-mutex)) -(define jolt-main-queue-cv (make-condition)) -(define jolt-main-queue '()) ; FIFO of jolt-main-job, guarded by mu -(define jolt-main-pump-active (box #f)) ; #t while run-main-pump owns this thread -(define jolt-main-pump-stop (box #f)) ; set by stop-main-pump to drain + exit -;; thread-local: this thread is the pump, mid-thunk → nested calls run inline. -(define jolt-in-main-pump? (make-thread-parameter #f)) - -(define-record-type jolt-main-job - (fields thunk (mutable done?) (mutable ok?) (mutable val) mu cv) - (nongenerative jolt-main-job-v1)) - -(define (jolt-call-on-main-thread thunk) - (if (jolt-in-main-pump?) ; reentrant — already on the pump - (jolt-invoke thunk) - ;; Decide-and-enqueue atomically: read pump-active and (if active) push the - ;; job under jolt-main-queue-mu, the same lock the pump holds when it flips - ;; active to #f on exit. So we either get queued before the pump leaves, or - ;; we see #f and fall through to inline — never enqueue onto a dead pump. - (let ((job (with-mutex jolt-main-queue-mu - (and (unbox jolt-main-pump-active) - (let ((j (make-jolt-main-job thunk #f #f jolt-nil - (make-mutex) (make-condition)))) - (set! jolt-main-queue (append jolt-main-queue (list j))) - (condition-signal jolt-main-queue-cv) - j))))) - (if (not job) - (jolt-invoke thunk) ; no pump (or stopped) — inline, like -M:run - (begin - (with-mutex (jolt-main-job-mu job) - (let wait () - (unless (jolt-main-job-done? job) - (condition-wait (jolt-main-job-cv job) (jolt-main-job-mu job)) - (wait)))) - (if (jolt-main-job-ok? job) - (jolt-main-job-val job) - (raise (jolt-main-job-val job)))))))) - -(define jolt-pump-kih - (lambda () - (for-each (lambda (th) (guard (e (#t #f)) (th))) - (reverse (unbox jolt-shutdown-hooks))) - (exit 0))) - -;; Park the calling thread until a keyboard interrupt (^C), then run the shutdown -;; hooks and exit. Unlike run-main-pump (whose tight recursive condition-wait -;; loop elides Chez's interrupt poll points, so the handler never fires), this -;; uses a single condition-wait — the form Chez reliably interrupts. The nREPL -;; server parks here; SIGINT is unblocked in this thread first (it was masked by -;; jolt-block-sigint so the accept loop inherited a blocked mask and couldn't -;; absorb ^C in its foreign accept() call). -(define jolt-park-mu (make-mutex)) -(define jolt-park-cv (make-condition)) -(define (jolt-park-until-interrupt) - (keyboard-interrupt-handler jolt-pump-kih) - (jolt-set-sigint-blocked #f) - (with-mutex jolt-park-mu (condition-wait jolt-park-cv jolt-park-mu)) - jolt-nil) - -(define (jolt-run-main-pump) - (with-mutex jolt-main-queue-mu - (set-box! jolt-main-pump-stop #f) - (set-box! jolt-main-pump-active #t)) - ;; dynamic-wind guarantees active is cleared even if the pump escapes abnormally, - ;; so a later run-main-pump starts clean and call-on-main-thread never sees a - ;; stale #t. The clean-exit path below also clears it under the mutex (the flip - ;; that races call-on-main-thread); this is the belt-and-suspenders for escapes. - (dynamic-wind - (lambda () #f) - (lambda () - (let loop () - (let ((job (with-mutex jolt-main-queue-mu - (let wait () - (cond - ((not (null? jolt-main-queue)) - (let ((j (car jolt-main-queue))) - (set! jolt-main-queue (cdr jolt-main-queue)) - j)) - ((unbox jolt-main-pump-stop) - ;; drain done, told to exit — clear active in the same - ;; critical section so no job can be enqueued after. - (set-box! jolt-main-pump-active #f) - #f) - (else (condition-wait jolt-main-queue-cv jolt-main-queue-mu) - (wait))))))) - (when job - (let ((r (dynamic-wind - (lambda () (jolt-in-main-pump? #t)) - (lambda () - (guard (e (#t (cons #f e))) - (cons #t (jolt-invoke (jolt-main-job-thunk job))))) - (lambda () (jolt-in-main-pump? #f))))) - (with-mutex (jolt-main-job-mu job) - (jolt-main-job-ok?-set! job (car r)) - (jolt-main-job-val-set! job (cdr r)) - (jolt-main-job-done?-set! job #t) - (condition-broadcast (jolt-main-job-cv job)))) - (loop))))) - (lambda () - (with-mutex jolt-main-queue-mu (set-box! jolt-main-pump-active #f)))) - jolt-nil) - -(define (jolt-stop-main-pump) - (with-mutex jolt-main-queue-mu - (set-box! jolt-main-pump-stop #t) - (condition-broadcast jolt-main-queue-cv)) - jolt-nil) - -;; Shutdown hooks run by jolt-pump-kih (the keyboard-interrupt-handler installed by -;; park-until-interrupt) before (exit 0), so a foreground server (nREPL) can close -;; its socket and drop .nrepl-port on ^C instead of Chez's default mutex-corrupting -;; abort. Newest-first; each hook is isolated so one failing hook can't block the exit. -(define jolt-shutdown-hooks (box '())) -(define (jolt-add-shutdown-hook thunk) - (set-box! jolt-shutdown-hooks (cons thunk (unbox jolt-shutdown-hooks))) - jolt-nil) - -;; Per-thread SIGINT mask. A worker thread parked in a foreign call (the nREPL -;; accept loop in c-accept, or a conn handler) can't run Chez's keyboard-interrupt -;; handler on ^C, so if SIGINT is delivered there the process hangs. Block SIGINT -;; in the primordial thread BEFORE forking such workers (they inherit the mask), -;; then park-until-interrupt unblocks it in the primordial once its handler is -;; installed, so ^C is always delivered to the parked thread. pthread_sigmask/ -;; sigaddset are libc/libpthread symbols, resolvable once the process object is -;; loaded (as the socket fns already are). 128 bytes covers Linux's 1024-bit -;; sigset_t and is larger than macOS's 4-byte one. -;; foreign-procedure resolves its symbol eagerly, and these POSIX signal fns don't -;; exist on Windows — resolving them unguarded aborted startup ("no entry for -;; pthread_sigmask"). Guard so a non-POSIX host yields #f; jolt-set-sigint-blocked -;; then no-ops (Windows delivers ^C through the console, not a per-thread mask). -(define c-pthread-sigmask - (jolt-foreign-proc-safe "pthread_sigmask" '(int u8* u8*) 'int)) -(define c-sigemptyset (jolt-foreign-proc-safe "sigemptyset" '(u8*) 'int)) -(define c-sigaddset (jolt-foreign-proc-safe "sigaddset" '(u8* int) 'int)) -;; POSIX SIG_BLOCK/SIG_UNBLOCK numerics differ by platform: Linux/glibc 0/1, -;; Darwin/macOS 1/2 (SIG_UNBLOCK is SIG_BLOCK+1 on both). Resolve SIG_BLOCK for -;; this host from the machine-type symbol — macOS builds contain "osx". -(define jolt-sig-block-how - (let* ((s (symbol->string (machine-type))) - (n (string-length s))) - (let loop ((i 0)) - (cond - ((> (+ i 3) n) 0) ; default: Linux/glibc - ((string=? (substring s i (+ i 3)) "osx") 1) ; Darwin/macOS - (else (loop (+ i 1))))))) -(define (jolt-set-sigint-blocked block?) - (when (and c-pthread-sigmask c-sigemptyset c-sigaddset) - (let ((set (make-bytevector 128 0)) - (old (make-bytevector 128 0))) - (c-sigemptyset set) - (c-sigaddset set 2) ; SIGINT = 2 - (c-pthread-sigmask (if block? jolt-sig-block-how (+ jolt-sig-block-how 1)) set old))) - jolt-nil) - -(def-var! "jolt.host" "call-on-main-thread" jolt-call-on-main-thread) -(def-var! "jolt.host" "run-main-pump" jolt-run-main-pump) -(def-var! "jolt.host" "stop-main-pump" jolt-stop-main-pump) -(def-var! "jolt.host" "add-shutdown-hook" jolt-add-shutdown-hook) -(def-var! "jolt.host" "block-sigint" (lambda () (jolt-set-sigint-blocked #t))) -(def-var! "jolt.host" "park-until-interrupt" jolt-park-until-interrupt) -(def-var! "jolt.host" "delete-file" delete-file) diff --git a/host/chez/java/dot-forms.ss b/host/chez/java/dot-forms.ss deleted file mode 100644 index 8d7206b..0000000 --- a/host/chez/java/dot-forms.ss +++ /dev/null @@ -1,149 +0,0 @@ -;; dot-forms.ss — generic dispatch for the `.` special-form / `.-field` desugar. -;; The analyzer lowers (. target member arg*) and (.-field target) -;; to a :host-call; the Chez emit routes a non-shimmed :host-call through -;; record-method-dispatch. This file extends that dispatcher with the collection -;; arms the interpreter's dispatch-member covers but the record/string base does -;; not, with this precedence: -;; -;; * collection interop wins first — count/seq/nth/get/valAt/containsKey on a -;; vector/map/set/seq/record (so (. {:count 9} count) is the entry count, 1, -;; NOT the :count field). -;; * field access — a "-name" member reads the field (records and maps). -;; * map member — a stored fn is a method (called with self + args); any -;; other value is returned as a field. -;; -;; Anything not recognized falls through to the previous dispatcher (jhost / -;; number / regex / jrec protocol / string). Loaded LAST (after host-static.ss). -;; A record (jrec) is jolt-map? here (records.ss makes it so) and a collection, -;; so its protocol method (no dash, not a coll method) lands in the base. - -;; Vectors / maps / sets only (records are jolt-map? here). Raw seqs are excluded: -;; coll-interop accepts some seq representations and not others (a -;; plain (seq v) returns nil from .count, a lazy-seq returns the count), an -;; inconsistency Chez's normalized cseq can't mirror — so a raw seq target falls -;; through to the base dispatcher rather than risk a divergence the corpus would -;; never exercise but a future case might. -(define (dot-coll? obj) - (or (jolt-vector? obj) (jolt-map? obj) (pset? obj))) - -;; Mirror coll-interop: return a one-element list boxing the result (so a jolt-nil -;; result is still distinguishable from "not a collection method"), or #f. -(define (dot-coll-method obj name args) - (cond - ((string=? name "count") (list (jolt-count obj))) - ((string=? name "seq") (list (jolt-seq obj))) - ((string=? name "nth") (list (apply jolt-nth obj args))) - ((or (string=? name "get") (string=? name "valAt")) - (list (apply jolt-get obj args))) - ((string=? name "containsKey") (list (jolt-contains? obj (car args)))) - ;; java.util.Collection.contains(o): VALUE membership (a set is O(1) via - ;; contains?; a list/vector/seq is a linear scan — contains? on a vector tests - ;; an index, so it is wrong here). - ((string=? name "contains") - (list (if (pset? obj) - (jolt-contains? obj (car args)) - (let ((x (car args))) - (let loop ((s (jolt-seq obj))) - (cond ((jolt-nil? s) #f) - ((jolt=2 (seq-first s) x) #t) - (else (loop (jolt-seq (seq-more s)))))))))) - ((string=? name "size") (list (jolt-count obj))) - ((string=? name "isEmpty") (list (jolt-empty? obj))) - ;; java.util.Map views: keySet (a Set), values (a Collection), entrySet. - ((and (jolt-map? obj) (string=? name "keySet")) - (list (apply jolt-hash-set (seq->list (jolt-keys obj))))) - ((and (jolt-map? obj) (string=? name "values")) - (list (apply jolt-vector (seq->list (jolt-vals obj))))) - ((and (jolt-map? obj) (string=? name "entrySet")) (list (jolt-seq obj))) - ;; (.iterator coll): a java.util.Iterator over the seq — for a map this is the - ;; entry iterator. Without this a map's .iterator falls into the map-as-object - ;; branch and is mis-read as a missing :iterator key (nil). Some libraries - ;; (e.g. malli's -vmap) iterate a map this way. - ((string=? name "iterator") (list (make-jiterator (jolt-seq obj)))) - ;; (.reduce coll f) / (.reduce coll f init): clojure.lang.IReduce — every - ;; persistent collection reduces itself on the JVM. - ((string=? name "reduce") - (list (if (pair? (cdr args)) - (jolt-reduce (car args) (cadr args) obj) - (jolt-reduce (car args) obj)))) - (else #f))) - -;; Universal object-methods: on a -;; non-record map these win OVER a field lookup, like dispatch-member. getMessage -;; on an ex-info reads its :message (the one the corpus exercises); getCause reads -;; :cause; toString/hashCode/equals round out the set. Returns a boxed result or -;; #f. Strings/numbers/records/jhost keep the base dispatcher (it shims them). -(define (dot-object-method obj name args) - (cond - ((string=? name "getMessage") - (list (if (jolt=2 (jolt-get obj jolt-kw-ex-type jolt-nil) jolt-kw-ex-info) - (jolt-get obj jolt-kw-message jolt-nil) - (jolt-str-render-one obj)))) - ((string=? name "getCause") (list (jolt-get obj jolt-kw-cause jolt-nil))) - ;; java.sql.SQLException chaining — ex-info / host throwables don't chain. - ((string=? name "getNextException") (list jolt-nil)) - ((string=? name "getStackTrace") (list (jolt-vector))) - ((string=? name "toString") (list (jolt-str-render-one obj))) - ((string=? name "hashCode") (list (jolt-hash obj))) - ((string=? name "equals") (list (if (jolt= obj (car args)) #t #f))) - (else #f))) - -(register-method-arm! 30 - (lambda (obj method-name rest-args) - (let* ((rest (if (jolt-nil? rest-args) '() (seq->list rest-args))) - (field? (and (> (string-length method-name) 0) - (char=? (string-ref method-name 0) #\-))) - (mname (if field? - (substring method-name 1 (string-length method-name)) - method-name))) - (cond - ;; clojure.lang.MultiFn .dispatchFn / .getMethod — clojure.spec.alpha's - ;; multi-spec walks a multimethod through these. - ((jolt-multifn? obj) - (cond - ((string=? mname "dispatchFn") (jolt-multifn-dispatch-fn obj)) - ((string=? mname "getMethod") - (let ((methods (jolt-multifn-methods obj)) (dv (car rest))) - (or (hashtable-ref methods dv #f) - (mm-find-isa obj dv) - (hashtable-ref methods (jolt-multifn-default obj) #f) - jolt-nil))) - (else 'pass))) - ;; (.applyTo f args): apply a fn to a seq of args (clojure.spec instrument). - ((and (procedure? obj) (string=? mname "applyTo")) - (apply jolt-invoke obj (seq->list (jolt-seq (car rest))))) - ;; a transient (ITransientCollection/Set/Map): .contains / .valAt / .count — - ;; test.check's distinct-collection gen uses (.contains transient-set k). - ((jolt-transient? obj) - (cond - ((string=? mname "contains") (if (jolt-truthy? (t-contains? obj (car rest))) #t #f)) - ((or (string=? mname "valAt") (string=? mname "get")) - (t-get obj (car rest) (if (null? (cdr rest)) jolt-nil (cadr rest)))) - ((string=? mname "count") (t-count obj)) - (else 'pass))) - ;; a deftype/record's OWN declared method (matched by name AND arity) wins - ;; over the generic collection interop below — e.g. data.priority-map - ;; declares both seq[this] (Seqable) and seq[this ascending] (Sorted), and - ;; (.seq pm false) must reach the 2-arg one, not dot-coll's plain seq. - ((and (not field?) (jrec? obj) - (find-method-any-protocol-arity (jrec-tag obj) mname (+ 1 (length rest)))) - => (lambda (f) (apply jolt-invoke f obj rest))) - ;; collection interop first (entry count / seq / nth / get / containsKey). - ((and (dot-coll? obj) (dot-coll-method obj mname rest)) - => (lambda (box) (car box))) - ;; clojure.lang.Sorted (comparator / entryKey / seqFrom) on a sorted - ;; map/set, before the map arm below reads the method name as a key. - ;; data.priority-map's subseq/rsubseq reach for these. - ((and (not field?) (htable-sorted? obj) (sorted-iface-method? mname)) - (sorted-iface-dispatch obj mname rest)) - ;; (.-field obj) / (. obj -field): field read on a record or map. - (field? (jolt-get obj (keyword #f mname) jolt-nil)) - ;; non-record map: a universal object-method (getMessage/...) wins first, - ;; then a stored procedure is a method (call with self), else the field. - ((and (jolt-map? obj) (not (jrec? obj))) - (cond - ((dot-object-method obj mname rest) => car) - (else - (let ((v (jolt-get obj (keyword #f mname) jolt-nil))) - (if (procedure? v) (apply jolt-invoke v obj rest) v))))) - (else 'pass))))) diff --git a/host/chez/java/ffi.ss b/host/chez/java/ffi.ss deleted file mode 100644 index ca665e5..0000000 --- a/host/chez/java/ffi.ss +++ /dev/null @@ -1,167 +0,0 @@ -;; ffi.ss — the runtime side of jolt's foreign-function interface (jolt.ffi). -;; -;; A jolt LIBRARY binds native code itself: it loads a shared object and declares -;; typed foreign functions, then exposes a Clojure API. The TYPED CALL is lowered -;; at compile time to a Chez `foreign-procedure` by the backend (the -;; `jolt.ffi/foreign-fn` special form) — this file provides everything that does -;; NOT need compile-time types: loading libraries, allocating/reading/writing -;; foreign memory, and string/pointer marshaling. All exposed under `jolt.ffi`. -;; -;; A foreign pointer is a Chez machine address (an exact integer / uptr), the same -;; representation `void*` arguments and results use, so pointers flow between -;; foreign-fn calls and these helpers transparently. - -;; --- loading shared objects -------------------------------------------------- -;; (jolt.ffi/load-library name) loads a .so/.dylib by name (resolved by the OS -;; loader against the standard search paths). A library typically calls this once -;; at load with a platform-specific name. (load-library) with no name (or #f) -;; loads the running process's own symbols (libc, sockets). -(define (ffi-load-library . args) - (if (or (null? args) (jolt-nil? (car args))) - (begin (load-shared-object #f) jolt-nil) - (begin (load-shared-object (jolt-str-render-one (car args))) jolt-nil))) - -(define (ffi-loaded? name) - (guard (e (#t #f)) (load-shared-object (jolt-str-render-one name)) #t)) - -;; --- foreign type keywords --------------------------------------------------- -;; The keyword type names jolt.ffi accepts (in foreign-fn signatures and the -;; memory accessors) map to Chez foreign types. Kept in one place so the backend -;; (compile-time, for foreign-procedure) and these accessors (runtime, for -;; foreign-ref/set!) agree. -(define (ffi-type->chez kw) - (let ((n (if (keyword-t? kw) (keyword-t-name kw) (jolt-str-render-one kw)))) - (cond - ((string=? n "int") 'int) - ((string=? n "uint") 'unsigned-int) - ((string=? n "long") 'long) - ((string=? n "ulong") 'unsigned-long) - ((string=? n "int64") 'integer-64) - ((string=? n "uint64") 'unsigned-64) - ((string=? n "size_t") 'size_t) - ((string=? n "ssize_t") 'ssize_t) - ((string=? n "iptr") 'iptr) - ((string=? n "uptr") 'uptr) - ((string=? n "double") 'double) - ((string=? n "float") 'float) - ((or (string=? n "pointer") (string=? n "void*")) 'void*) - ((string=? n "string") 'string) - ((string=? n "void") 'void) - ((or (string=? n "uint8") (string=? n "u8") (string=? n "byte")) 'unsigned-8) - ((string=? n "char") 'char) - (else (error #f (string-append "jolt.ffi: unknown foreign type :" n)))))) - -;; --- foreign memory ---------------------------------------------------------- -;; alloc returns a pointer (integer address). The caller frees it. read/write take -;; a type keyword and an optional byte offset. -(define (ffi-alloc nbytes) (foreign-alloc (jnum->exact nbytes))) -(define (ffi-free ptr) (foreign-free (jnum->exact ptr)) jolt-nil) -(define (ffi-read ptr ty . off) - (foreign-ref (ffi-type->chez ty) (jnum->exact ptr) (if (pair? off) (jnum->exact (car off)) 0))) -(define (ffi-write ptr ty off val) - (foreign-set! (ffi-type->chez ty) (jnum->exact ptr) (jnum->exact off) val) jolt-nil) -;; sizeof a foreign type (for laying out structs / arrays). -(define (ffi-sizeof ty) (foreign-sizeof (ffi-type->chez ty))) -(define (ffi-null? ptr) (and (number? ptr) (= (jnum->exact ptr) 0))) -(define ffi-null 0) - -;; --- buffer I/O (known length) ---------------------------------------------- -;; read n bytes at ptr as a string (UTF-8, falling back to latin1 for invalid -;; sequences) — for a socket recv buffer and similar fixed-length reads. -(define (ffi-read-bytes ptr n) - (let* ((n (jnum->exact n)) (p (jnum->exact ptr)) (bv (make-bytevector n))) - (do ((i 0 (+ i 1))) ((= i n)) (bytevector-u8-set! bv i (foreign-ref 'unsigned-8 p i))) - (guard (e (#t (list->string (map integer->char (bytevector->u8-list bv))))) (utf8->string bv)))) -;; write a string's UTF-8 bytes into ptr (no NUL terminator); return the count. -(define (ffi-write-bytes ptr s) - (let* ((bv (string->utf8 (jolt-str-render-one s))) (n (bytevector-length bv)) (p (jnum->exact ptr))) - (do ((i 0 (+ i 1))) ((= i n)) (foreign-set! 'unsigned-8 p i (bytevector-u8-ref bv i))) - n)) -(def-var! "jolt.ffi" "read-bytes" ffi-read-bytes) -(def-var! "jolt.ffi" "write-bytes" ffi-write-bytes) - -;; --- byte-array buffer I/O (binary-faithful) -------------------------------- -;; Move raw bytes between a jolt byte-array (jolt-array kind 'byte) and foreign -;; memory, byte-exact (no UTF-8 / latin1 decode) — for socket recv/send and the -;; zlib / OpenSSL buffers an HTTP client passes through. read-array returns a -;; fresh byte-array of n bytes; write-array copies a byte-array's bytes into ptr -;; and returns the count. -(define (ffi-read-array ptr n) - (let* ((n (jnum->exact n)) (p (jnum->exact ptr)) (v (make-vector n 0))) - (do ((i 0 (+ i 1))) ((= i n)) (vector-set! v i (foreign-ref 'unsigned-8 p i))) - (make-jolt-array v 'byte))) -(define (ffi-write-array ptr arr) - (let* ((v (jolt-array-vec arr)) (n (vector-length v)) (p (jnum->exact ptr))) - (do ((i 0 (+ i 1))) ((= i n)) (foreign-set! 'unsigned-8 p i (bitwise-and (exact (vector-ref v i)) #xff))) - n)) -(def-var! "jolt.ffi" "read-array" ffi-read-array) -(def-var! "jolt.ffi" "write-array" ffi-write-array) - -;; --- string / bytevector marshaling ------------------------------------------ -;; A C string result already comes back as a jolt string (the `string` foreign -;; type). For a `void*` that points at a NUL-terminated C string, read it here. -(define (ffi-ptr->string ptr) - (if (ffi-null? ptr) jolt-nil - (let ((p (jnum->exact ptr))) - (let loop ((i 0) (acc '())) - (let ((b (foreign-ref 'unsigned-8 p i))) - (if (= b 0) (utf8->string (u8-list->bytevector (reverse acc))) - (loop (+ i 1) (cons b acc)))))))) -;; Copy a jolt string's UTF-8 bytes into a freshly alloc'd NUL-terminated buffer; -;; the caller frees it. Returns the pointer. -(define (ffi-string->ptr s) - (let* ((bv (string->utf8 (jolt-str-render-one s))) (n (bytevector-length bv)) - (p (foreign-alloc (+ n 1)))) - (do ((i 0 (+ i 1))) ((= i n)) (foreign-set! 'unsigned-8 p i (bytevector-u8-ref bv i))) - (foreign-set! 'unsigned-8 p n 0) - p)) - -;; --- callbacks: receive calls FROM C ---------------------------------------- -;; jolt.ffi/foreign-callable lowers to (jolt-ffi-register-callable! (foreign-callable …)). -;; A foreign-callable code object must be LOCKED (so the collector neither moves -;; nor reclaims it) and RETAINED while C may still call through its entry point. -;; Register it keyed by that entry-point address (a jolt pointer integer) — which -;; is what the caller hands to C; free-callable unlocks and drops it. A callback -;; left registered lives for the process (the GTK-signal-handler common case). -(define ffi-callable-table (make-eqv-hashtable)) ; entry-point addr -> code object -(define (jolt-ffi-register-callable! co) - (lock-object co) - (let ((addr (foreign-callable-entry-point co))) - (hashtable-set! ffi-callable-table addr co) - addr)) -(define (ffi-free-callable addr) - (let* ((a (jnum->exact addr)) (co (hashtable-ref ffi-callable-table a #f))) - (when co (unlock-object co) (hashtable-delete! ffi-callable-table a)) - jolt-nil)) - -;; --- native libraries for a standalone binary ------------------------------- -;; `jolt build` bakes a project's deps.edn :jolt/native declarations into the -;; launcher, which loads them at startup (load-shared-object isn't part of the -;; saved heap, so it must run in the built process, not at heap build). process? -;; loads the running binary's own symbols (libc sockets); otherwise try each -;; platform candidate in turn and fail unless the spec is optional. -(define (jolt-build-load-native cands optional? process?) - (if process? - (begin (load-shared-object #f) #t) - (let loop ((cs cands)) - (cond - ((null? cs) - (unless optional? - (error 'jolt-build "required native library not found" cands)) - #f) - ((guard (e (#t #f)) (load-shared-object (car cs)) #t) #t) - (else (loop (cdr cs))))))) - -;; --- expose under jolt.ffi --------------------------------------------------- -(def-var! "jolt.ffi" "free-callable" ffi-free-callable) -(def-var! "jolt.ffi" "load-library" ffi-load-library) -(def-var! "jolt.ffi" "loaded?" (lambda (n) (if (ffi-loaded? n) #t #f))) -(def-var! "jolt.ffi" "alloc" ffi-alloc) -(def-var! "jolt.ffi" "free" ffi-free) -(def-var! "jolt.ffi" "read" ffi-read) -(def-var! "jolt.ffi" "write" ffi-write) -(def-var! "jolt.ffi" "sizeof" ffi-sizeof) -(def-var! "jolt.ffi" "null?" (lambda (p) (if (ffi-null? p) #t #f))) -(def-var! "jolt.ffi" "null" ffi-null) -(def-var! "jolt.ffi" "ptr->string" ffi-ptr->string) -(def-var! "jolt.ffi" "string->ptr" ffi-string->ptr) diff --git a/host/chez/java/host-class.ss b/host/chez/java/host-class.ss deleted file mode 100644 index 10d8940..0000000 --- a/host/chez/java/host-class.ss +++ /dev/null @@ -1,205 +0,0 @@ -;; host class tokens — a bare class name (String, Keyword, File...) -;; evaluates to its JVM canonical-name STRING, the same value (class instance) -;; returns, so (= String (class "x")) holds and a (defmethod m String ...) keys -;; against a (class …) dispatch (ring.util.request does this). -;; The analyzer resolves these names to clojure.core vars, so the back end emits -;; (var-deref "clojure.core" "String") — def-var!'ing the canonical strings here is -;; all that's needed at runtime. -;; -;; Loaded after natives-meta.ss (jolt-type) + the printer (jolt-str-render-one). - -;; (class x) — Clojure's class of a value. Scalars map to their JVM class name, -;; matching core-class. Collections/seqs have no JVM class on this host; -;; (str (type x)) is the clean host taxonomy and -;; is never compared against a class token in the corpus. Records yield their -;; ns-qualified class name (= (str (type x))). Total — never crashes. -;; A host shim (bigdec, queue, host-table) registers its type's class name via -;; register-class-arm! instead of set!-wrapping jolt-class (cf. register-hash-arm!). -;; The entry is stable, so the var cell bound below stays current as arms register. -(define jolt-class-arms '()) -(define (register-class-arm! pred handler) - (set! jolt-class-arms (cons (cons pred handler) jolt-class-arms))) -(define (jolt-class-base x) - (cond - ((jolt-nil? x) jolt-nil) - ((boolean? x) "java.lang.Boolean") - ;; per-type number classes, like the JVM: integer -> Long, flonum -> Double, - ;; exact non-integer -> Ratio. - ((and (number? x) (flonum? x)) "java.lang.Double") - ((and (number? x) (exact? x) (integer? x)) "java.lang.Long") - ((and (number? x) (exact? x) (rational? x)) "clojure.lang.Ratio") - ((number? x) "java.lang.Number") - ((string? x) "java.lang.String") - ((keyword? x) "clojure.lang.Keyword") - ((symbol-t? x) "clojure.lang.Symbol") - ((jolt-atom? x) "clojure.lang.Atom") - ((char? x) "java.lang.Character") - ((regex-t? x) "java.util.regex.Pattern") - ;; an anonymous / unregistered fn — like the JVM, where (class #(..)) is a - ;; concrete ns$fn__N subclass. The $fn marker lets clojure.spec.alpha's fn-sym - ;; recognize it as anonymous and return ::s/unknown. A named fn is registered - ;; (proc-name-tbl) and handled by a class-arm with its real ns$name. - ((procedure? x) "clojure.lang.AFunction$fn") - ;; an exception value (ex-info / host-constructed throwable) reports its JVM - ;; class, so (= clojure.lang.ExceptionInfo (class e)) and clojure.test's - ;; (thrown? Class …) match (records.ss ex-info-map?/ex-info-class). - ((ex-info-map? x) (ex-info-class x)) - ;; persistent collections + namespace report their JVM class names (not jolt's - ;; internal :vector/:set/… type keyword), so class-based dispatch — e.g. a - ;; defmulti on [(class a) (class b)] — sees a real clojure.lang.* class. - ((jns? x) "clojure.lang.Namespace") - ((pvec? x) "clojure.lang.PersistentVector") - ((pset? x) "clojure.lang.PersistentHashSet") - ((pmap? x) "clojure.lang.PersistentArrayMap") - ((jolt-lazyseq? x) "clojure.lang.LazySeq") - ((empty-list-t? x) "clojure.lang.PersistentList$EmptyList") - ((cseq? x) "clojure.lang.PersistentList") - (else (jolt-str-render-one (jolt-type x))))) -;; the class NAME of x (string), or nil for nil. (class x) wraps it in a Class -;; value (make-class-obj, host-static-classes.ss) so it renders like a JVM Class -;; while staying = its name string. -;; a raw Chez condition Clojure raises a specific class for (records-interop.ss -;; chez-condition-exc-class) reports that JVM class, so (class e) and a -;; (thrown? ArityException …) test match — not the opaque :object fallback. -(register-class-arm! - (lambda (x) (and (chez-condition-exc-class x) #t)) - (lambda (x) (let ((p (assoc (chez-condition-exc-class x) class-token-alist))) - (if p (cdr p) "java.lang.IllegalArgumentException")))) -;; A fn def'd into a var reports a JVM-style class name "ns$munged-name" (the -;; forward CHAR_MAP), so clojure.spec.alpha's fn-sym (which splits on $ and -;; demunges) recovers the predicate's symbol. Anonymous / unregistered fns stay -;; clojure.lang.IFn (fn-sym yields :unknown, as on the JVM). -(define class-munge-map - '((#\? . "_QMARK_") (#\! . "_BANG_") (#\* . "_STAR_") (#\+ . "_PLUS_") - (#\> . "_GT_") (#\< . "_LT_") (#\= . "_EQ_") (#\/ . "_SLASH_") (#\- . "_") - (#\& . "_AMPERSAND_") (#\% . "_PERCENT_") (#\~ . "_TILDE_") (#\^ . "_CARET_") - (#\| . "_BAR_") (#\: . "_COLON_"))) -(define (class-munge-name s) - (let ((out (open-output-string))) - (string-for-each - (lambda (c) (let ((t (assv c class-munge-map))) (if t (display (cdr t) out) (write-char c out)))) - s) - (get-output-string out))) -(register-class-arm! - (lambda (x) (and (procedure? x) (hashtable-ref proc-name-tbl x #f))) - (lambda (x) (let ((p (hashtable-ref proc-name-tbl x #f))) - (string-append (car p) "$" (class-munge-name (cdr p)))))) - -(define (jolt-class-name x) - (let loop ((as jolt-class-arms)) - (cond ((null? as) (jolt-class-base x)) - (((caar as) x) ((cdar as) x)) - (else (loop (cdr as)))))) -(define (jolt-class x) - (let ((n (jolt-class-name x))) - (if (jolt-nil? n) jolt-nil (make-class-obj n)))) - -(def-var! "clojure.core" "class" jolt-class) - -;; The PUBLIC clojure.core/type — Clojure's (or (:type meta) (class x)). This is the -;; java host layer's job: the core taxonomy (natives-meta.ss jolt-type, kept under -;; __type-tag for print-method) is JVM-free, and the JVM class mapping lives HERE, -;; next to (class …). The inst/array/byte-buffer host files extend `class` (a -;; class-arm or jolt-type fallthrough) and re-point `type` at this same fn, so the -;; remap of every value — :jolt/inst -> java.util.Date etc. — happens in one place. -(define ty-meta-key (keyword #f "type")) -(define (jolt-type-pub x) - (let* ((m (jolt-meta x)) - (override (if (jolt-nil? m) jolt-nil (jolt-get m ty-meta-key jolt-nil)))) - (if (not (jolt-nil? override)) override (jolt-class x)))) -(def-var! "clojure.core" "type" jolt-type-pub) - -;; bare class-name tokens -> canonical JVM class-name strings. -(define class-token-alist - '(("String" . "java.lang.String") ("Number" . "java.lang.Number") - ("Boolean" . "java.lang.Boolean") ("Long" . "java.lang.Long") - ("Integer" . "java.lang.Integer") ("Double" . "java.lang.Double") - ("Float" . "java.lang.Float") ("Byte" . "java.lang.Byte") ("Short" . "java.lang.Short") - ("Object" . "java.lang.Object") ("Character" . "java.lang.Character") - ("InputStream" . "java.io.InputStream") ("OutputStream" . "java.io.OutputStream") - ("File" . "java.io.File") ("Reader" . "java.io.Reader") ("Writer" . "java.io.Writer") - ("ISeq" . "clojure.lang.ISeq") ("Keyword" . "clojure.lang.Keyword") - ("Symbol" . "clojure.lang.Symbol") ("MapEntry" . "clojure.lang.MapEntry") - ("StringReader" . "java.io.StringReader") ("StringWriter" . "java.io.StringWriter") - ("StringBuilder" . "java.lang.StringBuilder") - ("StringTokenizer" . "java.util.StringTokenizer") - ("Charset" . "java.nio.charset.Charset") ("Base64" . "java.util.Base64") - ("Exception" . "java.lang.Exception") - ("IllegalArgumentException" . "java.lang.IllegalArgumentException") - ("ArityException" . "clojure.lang.ArityException") - ("IllegalStateException" . "java.lang.IllegalStateException") - ("RuntimeException" . "java.lang.RuntimeException") - ("UnsupportedOperationException" . "java.lang.UnsupportedOperationException") - ("InterruptedException" . "java.lang.InterruptedException") - ("IOException" . "java.io.IOException") - ("UnknownHostException" . "java.net.UnknownHostException") - ("ConnectException" . "java.net.ConnectException") - ("SocketTimeoutException" . "java.net.SocketTimeoutException") - ("MalformedURLException" . "java.net.MalformedURLException") - ("SSLException" . "javax.net.ssl.SSLException") - ("ExceptionInfo" . "clojure.lang.ExceptionInfo") - ("IExceptionInfo" . "clojure.lang.IExceptionInfo") - ("Pattern" . "java.util.regex.Pattern") - ("URI" . "java.net.URI") ("UUID" . "java.util.UUID") - ("ArrayList" . "java.util.ArrayList") ("PersistentQueue" . "clojure.lang.PersistentQueue") - ("NumberFormatException" . "java.lang.NumberFormatException") - ("ArithmeticException" . "java.lang.ArithmeticException") - ("NullPointerException" . "java.lang.NullPointerException") - ("ClassCastException" . "java.lang.ClassCastException") - ("IndexOutOfBoundsException" . "java.lang.IndexOutOfBoundsException") - ("UnsupportedEncodingException" . "java.io.UnsupportedEncodingException") - ("FileNotFoundException" . "java.io.FileNotFoundException") - ("Throwable" . "java.lang.Throwable") - ;; clojure.lang / java.util types that class-based multimethods dispatch on. - ("Fn" . "clojure.lang.Fn") ("IFn" . "clojure.lang.IFn") - ("Namespace" . "clojure.lang.Namespace") ("Named" . "clojure.lang.Named") - ("Set" . "java.util.Set") ("List" . "java.util.List") ("Map" . "java.util.Map") - ("Collection" . "java.util.Collection") ("Iterable" . "java.lang.Iterable") - ("CharSequence" . "java.lang.CharSequence") ("Comparable" . "java.lang.Comparable") - ("Runnable" . "java.lang.Runnable") ("Callable" . "java.util.concurrent.Callable") - ("IPersistentSet" . "clojure.lang.IPersistentSet") - ("IPersistentVector" . "clojure.lang.IPersistentVector") - ("IPersistentMap" . "clojure.lang.IPersistentMap") - ("IPersistentCollection" . "clojure.lang.IPersistentCollection") - ("Sequential" . "clojure.lang.Sequential") ("Seqable" . "clojure.lang.Seqable") - ("Associative" . "clojure.lang.Associative"))) -(for-each - (lambda (pair) (def-var! "clojure.core" (car pair) (cdr pair))) - class-token-alist) - -;; resolve a ^Type hint symbol-name to its canonical class name at def time: -;; "String" -> "java.lang.String", matching the JVM compiler. An -;; already-canonical name maps to itself; an unknown name yields #f (left as-is). -(define class-hint-table (make-hashtable string-hash string=?)) -(for-each (lambda (p) (hashtable-set! class-hint-table (car p) (cdr p))) class-token-alist) -(for-each (lambda (p) (hashtable-set! class-hint-table (cdr p) (cdr p))) class-token-alist) -(define (resolve-class-hint name) (hashtable-ref class-hint-table name #f)) -(def-var! "jolt.host" "resolve-class-hint" resolve-class-hint) - -;; fully-qualified canonical class names self-evaluate to their own name string, -;; so (= (class 1) java.lang.Long) and (instance? clojure.lang.Atom x) resolve the -;; class token (= what jolt-class / instance-check key on). -;; Value classes only — NOT the collection interfaces (ISeq/IPersistentMap/...), -;; which downstream code (e.g. SCI) references as protocols/interfaces. -(for-each - (lambda (nm) (def-var! "clojure.core" nm nm)) - '("java.lang.Long" "java.lang.Integer" "java.lang.Double" "java.lang.Float" - "java.lang.Byte" "java.lang.Short" - "java.lang.Number" "java.lang.String" "java.lang.Boolean" "java.lang.Character" - "java.lang.Object" - ;; exception classes compared against (class e): (= java.net.SocketTimeoutException (class e)) - "java.lang.Exception" "java.lang.Throwable" "java.lang.RuntimeException" - "java.lang.IllegalArgumentException" "java.lang.IllegalStateException" - "java.lang.UnsupportedOperationException" "java.io.IOException" - "java.net.UnknownHostException" "java.net.ConnectException" - "java.net.SocketTimeoutException" "java.net.MalformedURLException" - "javax.net.ssl.SSLException" - "java.lang.NumberFormatException" "java.lang.ArithmeticException" - "java.lang.NullPointerException" "java.lang.ClassCastException" - "java.lang.IndexOutOfBoundsException" "java.io.FileNotFoundException" - "java.io.UnsupportedEncodingException" - ;; clojure.lang.ExceptionInfo / IExceptionInfo compared against (class e) - "clojure.lang.ExceptionInfo" "clojure.lang.IExceptionInfo" "clojure.lang.ArityException" - "java.util.regex.Pattern" "java.net.URI" "java.util.UUID" - "clojure.lang.PersistentQueue" - "clojure.lang.Keyword" "clojure.lang.Symbol" "clojure.lang.Ratio" "clojure.lang.Atom")) diff --git a/host/chez/java/host-static-classes.ss b/host/chez/java/host-static-classes.ss deleted file mode 100644 index a5730d5..0000000 --- a/host/chez/java/host-static-classes.ss +++ /dev/null @@ -1,1113 +0,0 @@ -;; host-static-classes.ss — instantiable host object classes: ArrayList, HashMap, -;; the String/Reader/Writer/Tokenizer shims, BigInteger/MapEntry ctors, and URL -;; codecs. Holds the tagged-table method dispatch (the (.method ...) arm on a jhost) -;; and the pluggable instance? hook. Loaded after host-static-methods.ss; the -;; `Class/member` static methods live there, the registry core in host-static.ss. - -;; ---- java.util.ArrayList ---------------------------------------------------- -;; A mutable list backed by a growable Scheme vector. State is #(backing count); -;; .add amortizes O(1) and .get is O(1) (a list backing made both O(n)). medley's -;; stateful transducers (window / partition-between) build one with .add / .size / -;; .toArray / .clear / .remove. (ArrayList.) | (ArrayList. n) | (ArrayList. coll). -(define al-min-cap 8) -(define (al-vec self) (vector-ref (jhost-state self) 0)) -(define (al-cnt self) (vector-ref (jhost-state self) 1)) -(define (al-cnt! self n) (vector-set! (jhost-state self) 1 n)) -(define (make-arraylist xs) ; xs: a Scheme list of initial elements - (let* ((n (length xs)) (cap (fxmax al-min-cap n)) (v (make-vector cap jolt-nil))) - (let loop ((i 0) (xs xs)) (when (pair? xs) (vector-set! v i (car xs)) (loop (fx+ i 1) (cdr xs)))) - (make-jhost "arraylist" (vector v n)))) -(define (al-ensure! self need) ; grow the backing vector (doubling) to fit `need` - (let ((v (al-vec self))) - (when (fx>? need (vector-length v)) - (let grow ((cap (fxmax al-min-cap (vector-length v)))) - (if (fx? j i) (vector-set! v j (vector-ref v (fx- j 1))) (shift (fx- j 1)))) - (vector-set! v i x) (al-cnt! self (fx+ n 1))))) -(define (al-remove-at! self i) - (let ((n (al-cnt self)) (v (al-vec self))) - (let shift ((j i)) (when (fxlist self) ; first `count` elements as a Scheme list - (let ((v (al-vec self))) - (let loop ((i (fx- (al-cnt self) 1)) (acc '())) (if (fxlist (jolt-seq (car args)))))))) -(register-class-ctor! "java.util.ArrayList" - (lambda args - (cond ((null? args) (make-arraylist '())) - ((number? (car args)) (make-arraylist '())) - (else (make-arraylist (seq->list (jolt-seq (car args)))))))) -(define arraylist-methods - (list - (cons "add" (lambda (self . a) - ;; (.add x) -> append+true; (.add i x) -> insert at i, returns nil. - (if (= 1 (length a)) - (begin (al-push! self (car a)) #t) - (begin (al-insert-at! self (jnum->exact (car a)) (cadr a)) jolt-nil)))) - (cons "add!" (lambda (self x) (al-push! self x) #t)) - (cons "addAll" (lambda (self . a) - ;; (.addAll coll) appends; (.addAll i coll) inserts at i. - (let* ((at-i (= 2 (length a))) - (i (if at-i (jnum->exact (car a)) (al-cnt self))) - (coll (if at-i (cadr a) (car a)))) - (let loop ((xs (seq->list (jolt-seq coll))) (k i)) - (if (null? xs) (pair? (seq->list (jolt-seq coll))) - (begin (al-insert-at! self k (car xs)) (loop (cdr xs) (fx+ k 1)))))))) - (cons "get" (lambda (self i) (vector-ref (al-vec self) (jnum->exact i)))) - (cons "set" (lambda (self i x) - (let* ((idx (jnum->exact i)) (old (vector-ref (al-vec self) idx))) - (vector-set! (al-vec self) idx x) old))) - (cons "size" (lambda (self) (->num (al-cnt self)))) - (cons "isEmpty" (lambda (self) (fx=? 0 (al-cnt self)))) - (cons "remove" (lambda (self i) - (let* ((idx (jnum->exact i)) (old (vector-ref (al-vec self) idx))) - (al-remove-at! self idx) old))) - (cons "clear" (lambda (self) (vector-set! (jhost-state self) 0 (make-vector al-min-cap jolt-nil)) (al-cnt! self 0) jolt-nil)) - (cons "contains" (lambda (self x) (and (memp (lambda (e) (jolt=2 e x)) (al->list self)) #t))) - (cons "toArray" (lambda (self . _) (apply jolt-vector (al->list self)))) - (cons "iterator" (lambda (self) (make-jiterator (list->cseq (al->list self))))) - (cons "toString" (lambda (self) (jolt-pr-str (list->cseq (al->list self))))))) -(register-host-methods! "arraylist" arraylist-methods) - -;; java.util.LinkedList: the ArrayList backing plus the Deque surface -;; (addFirst/addLast/removeFirst/removeLast/getFirst/getLast/peek/push/pop). -;; tools.reader holds pending splice forms in one and (seq)s / .remove(0)s it. -(define (al-first self) (vector-ref (al-vec self) 0)) -(define (al-last self) (vector-ref (al-vec self) (fx- (al-cnt self) 1))) -(define linkedlist-methods - (append arraylist-methods - (list - (cons "addFirst" (lambda (self x) (al-insert-at! self 0 x) jolt-nil)) - (cons "addLast" (lambda (self x) (al-push! self x) jolt-nil)) - (cons "offer" (lambda (self x) (al-push! self x) #t)) - (cons "removeFirst" (lambda (self) (let ((o (al-first self))) (al-remove-at! self 0) o))) - (cons "removeLast" (lambda (self) (let ((o (al-last self))) (al-remove-at! self (fx- (al-cnt self) 1)) o))) - (cons "getFirst" al-first) (cons "getLast" al-last) - (cons "peek" (lambda (self) (if (fx=? 0 (al-cnt self)) jolt-nil (al-first self)))) - (cons "poll" (lambda (self) (if (fx=? 0 (al-cnt self)) jolt-nil (let ((o (al-first self))) (al-remove-at! self 0) o)))) - (cons "push" (lambda (self x) (al-insert-at! self 0 x) jolt-nil)) - (cons "pop" (lambda (self) (let ((o (al-first self))) (al-remove-at! self 0) o)))))) -(define (make-linkedlist xs) - (let ((al (make-arraylist xs))) (make-jhost "linkedlist" (jhost-state al)))) -(register-host-methods! "linkedlist" linkedlist-methods) -(let ((ctor (lambda args - (cond ((null? args) (make-linkedlist '())) - (else (make-linkedlist (seq->list (jolt-seq (car args))))))))) - (register-class-ctor! "LinkedList" ctor) - (register-class-ctor! "java.util.LinkedList" ctor)) - -;; ArrayList / LinkedList are Iterable: (seq al) walks the elements (nil if empty), -;; so (seq pending-forms) and reduce/into over one work like the JVM. -(define %al-seq jolt-seq) -(set! jolt-seq - (lambda (x) - (if (and (jhost? x) (or (string=? (jhost-tag x) "arraylist") (string=? (jhost-tag x) "linkedlist"))) - (list->cseq (al->list x)) - (%al-seq x)))) - -;; Appendable.append text: append(x) renders x; append(csq,start,end) appends the -;; subsequence csq[start,end) (data.json's writer appends string runs this way). -(define (append-text x rest) - (if (null? rest) - (render-piece x) - (substring (render-piece x) (jnum->exact (car rest)) (jnum->exact (cadr rest))))) - -(register-class-ctor! "StringBuilder" - (lambda args (make-jhost "string-builder" - ;; a numeric first arg is a CAPACITY hint, not content. - (vector (if (and (pair? args) (not (number? (car args)))) (render-piece (car args)) ""))))) -(register-host-methods! "string-builder" - (list (cons "append" (lambda (self x . rest) (sb-set! self (string-append (sb-str self) (append-text x rest))) self)) - (cons "toString" (lambda (self) (sb-str self))) - (cons "length" (lambda (self) (->num (string-length (sb-str self))))) - (cons "charAt" (lambda (self i) (string-ref (sb-str self) (jnum->exact i)))) - (cons "setLength" (lambda (self n) - (let ((cur (sb-str self)) (n (jnum->exact n))) - (sb-set! self (if (< n (string-length cur)) - (substring cur 0 n) - (string-append cur (make-string (- n (string-length cur)) #\nul))))) - jolt-nil)))) -;; (str sb) / print a StringBuilder -> its accumulated content, like the JVM -;; (str calls toString). Without this str renders the opaque host object. -(register-str-render! (lambda (x) (and (jhost? x) (string=? (jhost-tag x) "string-builder"))) sb-str) - -;; ---- StringWriter ----------------------------------------------------------- -;; Writer.write(int) writes the CHAR for that code; append(char) appends the char. -(define (writer-piece x) (if (number? x) (string (integer->char (jnum->exact x))) (render-piece x))) -(register-class-ctor! "StringWriter" (lambda args (make-jhost "writer" (vector "")))) -(register-host-methods! "writer" - (list (cons "write" (lambda (self x) (sb-set! self (string-append (sb-str self) (writer-piece x))) jolt-nil)) - (cons "append" (lambda (self x . rest) (sb-set! self (string-append (sb-str self) (append-text x rest))) self)) - (cons "flush" (lambda (self) jolt-nil)) - (cons "close" (lambda (self) jolt-nil)) - (cons "toString" (lambda (self) (sb-str self))))) -;; (str sw) / print a StringWriter -> its accumulated content, like the JVM -;; (str calls toString) — data.csv writes CSV to a StringWriter and reads it back. -(register-str-render! (lambda (x) (and (jhost? x) (string=? (jhost-tag x) "writer"))) sb-str) - -;; a file-backed writer (clojure.java.io/writer of a File/path): accumulates like -;; StringWriter, then persists to the path on flush/close, so -;; (with-open [w (io/writer "f")] (.write w …)) writes the file. State #(path buf). -(define (fw-path self) (vector-ref (jhost-state self) 0)) -(define (fw-buf self) (vector-ref (jhost-state self) 1)) -(define (fw-append! self s) (vector-set! (jhost-state self) 1 (string-append (fw-buf self) s))) -(define (fw-flush! self) (jolt-spit (fw-path self) (fw-buf self))) ; jolt-spit: io.ss -(register-host-methods! "file-writer" - (list (cons "write" (lambda (self x) (fw-append! self (writer-piece x)) jolt-nil)) - (cons "append" (lambda (self x . rest) (fw-append! self (append-text x rest)) self)) - (cons "flush" (lambda (self) (fw-flush! self) jolt-nil)) - (cons "close" (lambda (self) (fw-flush! self) jolt-nil)) - (cons "toString" (lambda (self) (fw-buf self))))) - -;; a writer over a real Chez port — the values *out* / *err* hold. write/append -;; push to the port (so (.write *out* s) and (binding [*out* *err*] …) work); -;; it isn't a buffer, so toString is empty. Lets libraries that touch *out*/*err* -;; (tools.logging, selmer) compile and run. -;; *out*/*err* resolve their port LIVE — 'out -> (current-output-port), 'err -> -;; (current-error-port) — so a (.write *out* …) / (.flush *out*) follows a -;; with-out-str redirect (with-output-to-string rebinds current-output-port) the -;; same way print/__write do. Storing the startup port instead pinned *out* to the -;; real stdout, so rewrite-clj's (z/print) — which writes via *out* — escaped the -;; capture. A stored port object (should any other code make a port-writer) is used -;; as-is. -(define (port-writer-port self) - (let ((p (vector-ref (jhost-state self) 0))) - (cond ((eq? p 'out) (current-output-port)) - ((eq? p 'err) (current-error-port)) - (else p)))) -(register-host-methods! "port-writer" - (list (cons "write" (lambda (self x) (display (writer-piece x) (port-writer-port self)) jolt-nil)) - (cons "append" (lambda (self x . rest) (display (append-text x rest) (port-writer-port self)) self)) - (cons "flush" (lambda (self) (flush-output-port (port-writer-port self)) jolt-nil)) - (cons "close" (lambda (self) jolt-nil)) - (cons "toString" (lambda (self) "")))) -(def-var! "clojure.core" "*out*" (make-jhost "port-writer" (vector 'out))) -(def-var! "clojure.core" "*err*" (make-jhost "port-writer" (vector 'err))) - -;; PrintWriter — a thin wrapper over a target writer. write/append/print forward -;; the rendered text to the target. clojure.data.json's pretty printer builds -;; (PrintWriter. *out*) where *out* is bound to clojure.pprint's pretty-writer (a -;; jolt record), so forwarding routes column-aware through clojure.pprint/-write; -;; for a host writer target it falls back to that writer's own write. -(define (pw-forward target s) - (cond - ((and (jhost? target) (string=? (jhost-tag target) "port-writer")) - (display s (vector-ref (jhost-state target) 0))) - ((and (jhost? target) (memv #t (list (string=? (jhost-tag target) "writer") - (string=? (jhost-tag target) "string-builder")))) - (sb-set! target (string-append (sb-str target) s))) - (else - (jolt-invoke (var-deref "clojure.pprint" "-write") target s)))) -(register-class-ctor! "PrintWriter" - (lambda args (make-jhost "print-writer" (vector (if (pair? args) (car args) jolt-nil))))) -(register-class-ctor! "java.io.PrintWriter" - (lambda args (make-jhost "print-writer" (vector (if (pair? args) (car args) jolt-nil))))) -(register-host-methods! "print-writer" - (list (cons "write" (lambda (self x . rest) (pw-forward (vector-ref (jhost-state self) 0) (append-text x rest)) jolt-nil)) - (cons "print" (lambda (self x) (pw-forward (vector-ref (jhost-state self) 0) (render-piece x)) jolt-nil)) - (cons "append" (lambda (self x . rest) (pw-forward (vector-ref (jhost-state self) 0) (append-text x rest)) self)) - (cons "flush" (lambda (self) jolt-nil)) - (cons "close" (lambda (self) jolt-nil)) - (cons "toString" (lambda (self) "")))) - -;; ---- java.util.HashMap ------------------------------------------------------ -;; A mutable map keyed by jolt values (jolt-hash / jolt=2). State #(chez-hashtable). -;; Constructors: () | (capacity) | (capacity load-factor) [sizing args ignored] | -;; (Map m) [copy]. Enough of the Map surface for libraries that build a fast lookup -;; (malli's fast-registry: (doto (HashMap. 1024 0.25) (.putAll m)) then .get). -(define (hm-hash k) (let ((h (jolt-hash k))) - (bitwise-and (if (and (integer? h) (exact? h)) (abs h) 0) #x3FFFFFFF))) -(define (hm-tbl self) (vector-ref (jhost-state self) 0)) -(define (hm-hashmap? x) (and (jhost? x) (string=? (jhost-tag x) "hashmap"))) -(define (hm-copy-into! ht src) ; src: a jolt map or another hashmap - (if (hm-hashmap? src) - (vector-for-each (lambda (k) (hashtable-set! ht k (hashtable-ref (hm-tbl src) k jolt-nil))) - (hashtable-keys (hm-tbl src))) - (for-each (lambda (e) (hashtable-set! ht (jolt-nth e 0) (jolt-nth e 1))) - (seq->list (jolt-seq src))))) -(register-class-ctor! "HashMap" - (lambda args - (let ((ht (make-hashtable hm-hash jolt=2))) - (when (and (pair? args) (or (pmap? (car args)) (hm-hashmap? (car args)))) - (hm-copy-into! ht (car args))) - (make-jhost "hashmap" (vector ht))))) -(define (hm->pmap self) - (let ((m (jolt-hash-map))) - (vector-for-each (lambda (k) (set! m (jolt-assoc m k (hashtable-ref (hm-tbl self) k jolt-nil)))) - (hashtable-keys (hm-tbl self))) - m)) -(register-host-methods! "hashmap" - (list (cons "put" (lambda (self k v) (let ((old (hashtable-ref (hm-tbl self) k jolt-nil))) - (hashtable-set! (hm-tbl self) k v) old))) - (cons "get" (lambda (self k) (hashtable-ref (hm-tbl self) k jolt-nil))) - (cons "getOrDefault" (lambda (self k d) (hashtable-ref (hm-tbl self) k d))) - (cons "containsKey" (lambda (self k) (if (hashtable-contains? (hm-tbl self) k) #t #f))) - (cons "containsValue" (lambda (self v) - (let ((found #f)) - (vector-for-each (lambda (k) (when (jolt=2 v (hashtable-ref (hm-tbl self) k jolt-nil)) (set! found #t))) - (hashtable-keys (hm-tbl self))) found))) - (cons "size" (lambda (self) (hashtable-size (hm-tbl self)))) - (cons "isEmpty" (lambda (self) (= 0 (hashtable-size (hm-tbl self))))) - (cons "remove" (lambda (self k) (let ((old (hashtable-ref (hm-tbl self) k jolt-nil))) - (hashtable-delete! (hm-tbl self) k) old))) - (cons "clear" (lambda (self) (hashtable-clear! (hm-tbl self)) jolt-nil)) - (cons "putAll" (lambda (self m) (hm-copy-into! (hm-tbl self) m) jolt-nil)) - (cons "keySet" (lambda (self) (apply jolt-hash-set (vector->list (hashtable-keys (hm-tbl self)))))) - (cons "values" (lambda (self) (apply jolt-vector - (map (lambda (k) (hashtable-ref (hm-tbl self) k jolt-nil)) - (vector->list (hashtable-keys (hm-tbl self))))))) - (cons "entrySet" (lambda (self) (jolt-seq (hm->pmap self)))) - (cons "toString" (lambda (self) (jolt-pr-str (hm->pmap self)))))) -;; java.util.concurrent.ConcurrentHashMap — one shared heap, so the mutable -;; HashMap shim serves. (get a-hashmap k) reads the map (clojure.core/get). -(define (make-hashmap-jhost . args) - (let ((ht (make-hashtable hm-hash jolt=2))) - (when (and (pair? args) (or (pmap? (car args)) (hm-hashmap? (car args)))) (hm-copy-into! ht (car args))) - (make-jhost "hashmap" (vector ht)))) -(register-class-ctor! "ConcurrentHashMap" make-hashmap-jhost) -(register-class-ctor! "java.util.concurrent.ConcurrentHashMap" make-hashmap-jhost) -(register-get-arm! (lambda (x) (and (jhost? x) (string=? (jhost-tag x) "hashmap"))) - (lambda (coll k d) (hashtable-ref (hm-tbl coll) k d))) -;; count / contains? over the mutable map shim (clojure.core/count + contains?, -;; which core.cache's SoftCache uses on its backing ConcurrentHashMap). -(define (jhost-hashmap? x) (and (jhost? x) (string=? (jhost-tag x) "hashmap"))) -(let ((prev-count jolt-count) (prev-contains jolt-contains?)) - (set! jolt-count (lambda (c) (if (jhost-hashmap? c) (hashtable-size (hm-tbl c)) (prev-count c)))) - (set! jolt-contains? (lambda (c k) (if (jhost-hashmap? c) - (if (hashtable-contains? (hm-tbl c) k) #t #f) - (prev-contains c k))))) - -;; ---- java.lang.ref.Soft/WeakReference + ReferenceQueue ---------------------- -;; Real GC reclamation via Chez's generational collector: the referent is held -;; through a weak pair (collected once otherwise unreachable, leaving the bwp -;; object), and a guardian registered on the referent makes the reference itself -;; available the moment its referent is reclaimed — which the ReferenceQueue -;; surfaces as enqueued, exactly like the JVM. (Chez has no softer-than-weak -;; reference, so a SoftReference clears on unreachability rather than under memory -;; pressure — its SoftCache evicts more eagerly than the JVM's, but it is genuine -;; GC eviction, not an unbounded strong cache. Immediates like fixnums/keywords -;; are never collected.) -;; ref-queue state: #(guardian pending-list); reference state: #(weak-pair queue enqueued?). -(define (rq-guardian-of q) (vector-ref (jhost-state q) 0)) -(define (rq-add! q ref) - (let ((st (jhost-state q))) (vector-set! st 1 (append (vector-ref st 1) (list ref))))) -(define (rq-pump! q) ; drain GC-reclaimed refs onto the list - (let loop () - (let ((rep ((rq-guardian-of q)))) (when rep (rq-add! q rep) (loop))))) -(define (rq-poll q) - (rq-pump! q) - (let* ((st (jhost-state q)) (l (vector-ref st 1))) - (if (null? l) jolt-nil (begin (vector-set! st 1 (cdr l)) (car l))))) -(define (a-ref-queue? x) (and (jhost? x) (string=? (jhost-tag x) "ref-queue"))) -(define (make-reference v rest) - (let* ((rq (if (pair? rest) (car rest) jolt-nil)) - (ref (make-jhost "weak-ref" (vector (weak-cons v #f) rq #f)))) - (when (a-ref-queue? rq) ((rq-guardian-of rq) v ref)) ; fire on the referent's collection - ref)) -(for-each (lambda (nm) (register-class-ctor! nm (lambda (v . rest) (make-reference v rest)))) - '("SoftReference" "java.lang.ref.SoftReference" "WeakReference" "java.lang.ref.WeakReference")) -(register-host-methods! "weak-ref" - (list (cons "get" (lambda (self) (let ((r (car (vector-ref (jhost-state self) 0)))) - (if (bwp-object? r) jolt-nil r)))) - (cons "clear" (lambda (self) (set-car! (vector-ref (jhost-state self) 0) jolt-nil) jolt-nil)) - (cons "isEnqueued" (lambda (self) (vector-ref (jhost-state self) 2))) - (cons "enqueue" (lambda (self) - (let* ((st (jhost-state self)) (rq (vector-ref st 1))) - (if (vector-ref st 2) #f - (begin (vector-set! st 2 #t) (when (a-ref-queue? rq) (rq-add! rq self)) #t))))))) -(for-each (lambda (nm) (register-class-ctor! nm (lambda _ (make-jhost "ref-queue" (vector (make-guardian) '()))))) - '("ReferenceQueue" "java.lang.ref.ReferenceQueue")) -(register-host-methods! "ref-queue" - (list (cons "poll" (lambda (self . _) (rq-poll self))) - (cons "remove" (lambda (self . _) (rq-poll self))))) - -;; ---- StringReader ----------------------------------------------------------- -;; state: a vector #(string pos marked). -(register-class-ctor! "StringReader" - ;; src is a String or a char[] ((StringReader. (char-array s)) — selmer's parser - ;; reads templates this way); a char-array becomes the string of its chars. - (lambda (src . _) - (make-jhost "string-reader" - (vector (cond ((string? src) src) - ((jolt-array? src) (apply string-append (map jolt-str-render-one (seq->list (jolt-seq src))))) - (else (jolt-str-render-one src))) - 0 0)))) -(define (sr-s self) (vector-ref (jhost-state self) 0)) -(define (sr-pos self) (vector-ref (jhost-state self) 1)) -(define (sr-pos! self p) (vector-set! (jhost-state self) 1 p)) -(register-host-methods! "string-reader" - (list (cons "read" (lambda (self . rest) - (let ((s (sr-s self)) (p (sr-pos self))) - (cond - ;; .read() -> one char code, -1 at EOF - ((null? rest) - (if (>= p (string-length s)) -1 - (begin (sr-pos! self (+ p 1)) (->num (char->integer (string-ref s p)))))) - ;; .read(cbuf, off, len) -> fill cbuf, return count or -1 at EOF - (else - (let ((slen (string-length s))) - (if (>= p slen) -1 - (let ((cbuf (car rest)) (off (jnum->exact (cadr rest))) (len (jnum->exact (caddr rest)))) - (let ((n (min len (- slen p))) (dv (jolt-array-vec cbuf))) - (let loop ((i 0)) (when (< i n) (vector-set! dv (+ off i) (string-ref s (+ p i))) (loop (+ i 1)))) - (sr-pos! self (+ p n)) (->num n)))))))))) - (cons "mark" (lambda (self . _) (vector-set! (jhost-state self) 2 (sr-pos self)) jolt-nil)) - (cons "reset" (lambda (self) (sr-pos! self (vector-ref (jhost-state self) 2)) jolt-nil)) - (cons "skip" (lambda (self n) (let ((n (jnum->exact n))) - (sr-pos! self (min (string-length (sr-s self)) (+ (sr-pos self) n))) (->num n)))) - ;; readLine: the next line without its terminator (\n or \r\n), nil at EOF — - ;; what line-seq drives over a BufferedReader. - (cons "readLine" - (lambda (self) - (let ((s (sr-s self)) (p (sr-pos self)) (len (string-length (sr-s self)))) - (if (>= p len) jolt-nil - (let scan ((i p)) - (cond - ((>= i len) (sr-pos! self len) (substring s p len)) - ((char=? (string-ref s i) #\newline) - (sr-pos! self (+ i 1)) - (substring s p (if (and (> i p) (char=? (string-ref s (- i 1)) #\return)) (- i 1) i))) - (else (scan (+ i 1))))))))) - (cons "close" (lambda (self) jolt-nil)))) - -;; ---- PushbackReader --------------------------------------------------------- -;; state: a vector #(wrapped-reader pushed-list) -(register-class-ctor! "PushbackReader" - (lambda (rdr . _) (make-jhost "pushback-reader" (vector rdr '())))) -;; Fully-qualified aliases so (java.io.PushbackReader. …) / (java.io.StringReader. …) -;; resolve to these built-ins even when a library defines a deftype of the same -;; simple name (tools.reader), which would otherwise take the bare-name slot. -(register-class-ctor! "java.io.PushbackReader" (lookup-class class-ctors-tbl "PushbackReader")) -(register-class-ctor! "java.io.StringReader" (lookup-class class-ctors-tbl "StringReader")) -;; LineNumberingPushbackReader: a pushback-reader (jolt doesn't track line -;; numbers; getLineNumber is a stub for error-reporting paths that read it). -(register-class-ctor! "LineNumberingPushbackReader" - (lambda (rdr . _) (make-jhost "pushback-reader" (vector rdr '())))) -(register-class-ctor! "clojure.lang.LineNumberingPushbackReader" - (lambda (rdr . _) (make-jhost "pushback-reader" (vector rdr '())))) -(define (read-unit r) ; read one code unit (flonum) from any reader, -1 at EOF - (record-method-dispatch r "read" jolt-nil)) -(register-host-methods! "pushback-reader" - (list (cons "read" - (lambda (self . rest) - (define (read1) - (let ((pushed (vector-ref (jhost-state self) 1))) - (if (pair? pushed) - (begin (vector-set! (jhost-state self) 1 (cdr pushed)) (car pushed)) - (read-unit (vector-ref (jhost-state self) 0))))) - (if (null? rest) - (read1) - ;; .read(cbuf, off, len) -> read one code unit at a time into cbuf, - ;; return count or -1 at immediate EOF. - (let ((off (jnum->exact (cadr rest))) (len (jnum->exact (caddr rest))) (dv (jolt-array-vec (car rest)))) - (let loop ((i 0)) - (if (>= i len) (->num i) - (let ((c (jnum->exact (read1)))) - (if (= c -1) (if (= i 0) -1 (->num i)) - (begin (vector-set! dv (+ off i) (integer->char c)) (loop (+ i 1))))))))))) - (cons "unread" - (lambda (self ch . rest) - (if (null? rest) - ;; unread(int|char) — push one code unit back - (vector-set! (jhost-state self) 1 - (cons (if (char? ch) (->num (char->integer ch)) ch) (vector-ref (jhost-state self) 1))) - ;; unread(char[] cbuf, off, len) — push cbuf[off,off+len) so cbuf[off] - ;; reads back first (the list head). - (let ((dv (jolt-array-vec ch)) (off (jnum->exact (car rest))) (len (jnum->exact (cadr rest)))) - (let loop ((i (- (+ off len) 1)) (acc (vector-ref (jhost-state self) 1))) - (if (< i off) - (vector-set! (jhost-state self) 1 acc) - (loop (- i 1) (cons (->num (char->integer (vector-ref dv i))) acc)))))) - jolt-nil)) - (cons "close" (lambda (self) jolt-nil)) - (cons "getLineNumber" (lambda (self) 0)))) - -;; ---- StringTokenizer -------------------------------------------------------- -;; state: a vector #(tokens-list pos) -(define (tokenize s delims) - (let ((dset (string->list delims))) - (let loop ((chars (string->list s)) (cur '()) (toks '())) - (cond ((null? chars) (reverse (if (null? cur) toks (cons (list->string (reverse cur)) toks)))) - ((memv (car chars) dset) - (loop (cdr chars) '() (if (null? cur) toks (cons (list->string (reverse cur)) toks)))) - (else (loop (cdr chars) (cons (car chars) cur) toks)))))) -(register-class-ctor! "StringTokenizer" - (lambda (s . delims) (make-jhost "string-tokenizer" - (vector (tokenize (if (string? s) s (jolt-str-render-one s)) - (if (null? delims) " \t\n\r\f" (car delims))) 0)))) -(register-host-methods! "string-tokenizer" - (list (cons "hasMoreTokens" (lambda (self) (< (vector-ref (jhost-state self) 1) (length (vector-ref (jhost-state self) 0))))) - (cons "countTokens" (lambda (self) (->num (- (length (vector-ref (jhost-state self) 0)) (vector-ref (jhost-state self) 1))))) - (cons "nextToken" (lambda (self) - (let ((toks (vector-ref (jhost-state self) 0)) (p (vector-ref (jhost-state self) 1))) - (if (< p (length toks)) - (begin (vector-set! (jhost-state self) 1 (+ p 1)) (list-ref toks p)) - (jolt-throw (jolt-host-throwable "java.util.NoSuchElementException" "no more tokens")))))) - ;; StringTokenizer implements java.util.Enumeration — enumeration-seq drives - ;; it through these, so alias them onto the token methods. - (cons "hasMoreElements" (lambda (self) (< (vector-ref (jhost-state self) 1) (length (vector-ref (jhost-state self) 0))))) - (cons "nextElement" (lambda (self) - (let ((toks (vector-ref (jhost-state self) 0)) (p (vector-ref (jhost-state self) 1))) - (if (< p (length toks)) - (begin (vector-set! (jhost-state self) 1 (+ p 1)) (list-ref toks p)) - (jolt-throw (jolt-host-throwable "java.util.NoSuchElementException" "no more tokens")))))))) - -;; ---- String / BigInteger / MapEntry constructors ---------------------------- -;; (String. bytes [charset]) decodes bytes (a bytevector OR a jolt byte-array) -;; with the named charset (UTF-8 default; ISO-8859-1/latin1/ascii = one byte per -;; char); else stringify. clj-http-lite's body coercion is (String. ^[B body cs). -(define (string-charset-name rest) - (if (pair? rest) - (let ((c (car rest))) - (cond ((string? c) c) - ((and (jhost? c) (string=? (jhost-tag c) "charset")) - (let ((p (assq 'name (jhost-state c)))) (if p (jolt-str-render-one (cdr p)) "UTF-8"))) - (else "UTF-8"))) - "UTF-8")) -(define (decode-bytevector bv rest) - (let ((cs (ascii-string-down (string-charset-name rest)))) - (cond - ((or (string=? cs "utf-8") (string=? cs "utf8")) (utf8->string bv)) - ((or (string=? cs "iso-8859-1") (string=? cs "latin1") (string=? cs "iso8859-1") - (string=? cs "us-ascii") (string=? cs "ascii")) - (list->string (map integer->char (bytevector->u8-list bv)))) - ((or (string=? cs "utf-16") (string=? cs "utf16") (string=? cs "utf-16be") (string=? cs "unicode")) - (utf16->string bv (endianness big))) ; respects a leading BOM - ((string=? cs "utf-16le") (utf16->string bv (endianness little))) - ((or (string=? cs "utf-32") (string=? cs "utf32") (string=? cs "utf-32be")) - (utf32->string bv (endianness big))) - ((string=? cs "utf-32le") (utf32->string bv (endianness little))) - (else (guard (e (#t (list->string (map integer->char (bytevector->u8-list bv))))) (utf8->string bv)))))) -(register-class-ctor! "String" - (lambda (x . rest) - (cond ((bytevector? x) (decode-bytevector x rest)) - ((and (jolt-array? x) (eq? (jolt-array-kind x) 'byte)) (decode-bytevector (na-bytearray->bv x) rest)) - ;; (String. char[] [offset count]) — the whole array or a slice. Buffered - ;; readers (data.json) build a string from a fill buffer this way. - ((and (jolt-array? x) (eq? (jolt-array-kind x) 'char)) - (let ((v (jolt-array-vec x))) - (if (pair? rest) - (let* ((off (jnum->exact (car rest))) (cnt (jnum->exact (cadr rest))) (out (make-string cnt))) - (let loop ((i 0)) (when (fxstring (vector->list v))))) - ((string? x) x) - (else (jolt-str-render-one x))))) -;; (BigInteger. s) | (BigInteger. s radix) — parse a string in the given radix -;; (default 10). tools.reader's integer parser builds (BigInteger. digits radix). -(register-class-ctor! "BigInteger" - (lambda (v . r) (parse-int-or-throw v (if (null? r) 10 (jnum->exact (car r))) "BigInteger"))) -(register-class-ctor! "java.math.BigInteger" - (lambda (v . r) (parse-int-or-throw v (if (null? r) 10 (jnum->exact (car r))) "BigInteger"))) -(register-class-ctor! "MapEntry" (lambda (k v) (make-map-entry k v))) -;; JVM exception ctors -> a typed host throwable carrying the canonical :jolt/class -;; (so class / instance? / getMessage / ex-message reflect the real type) and the -;; message. Supports (E. msg), (E. msg cause), (E. cause), and (E.). -(for-each - (lambda (nm) - (let ((canonical (or (resolve-class-hint nm) nm))) - (register-class-ctor! nm - (lambda args - (let* ((a0 (if (pair? args) (car args) jolt-nil)) - (rest (if (pair? args) (cdr args) '())) - (cause (if (pair? rest) (car rest) jolt-nil))) - (cond - ((string? a0) (jolt-host-throwable canonical a0 cause)) - ((jolt-nil? a0) (jolt-host-throwable canonical jolt-nil)) - ;; (E. cause): a lone throwable arg is the cause, message nil. - ((and (null? rest) (ex-info-map? a0)) (jolt-host-throwable canonical jolt-nil a0)) - (else (jolt-host-throwable canonical (jolt-str-render-one a0) cause)))))))) - '("Throwable" "Exception" "RuntimeException" "IllegalArgumentException" "IllegalStateException" - "InterruptedException" "UnsupportedOperationException" "IOException" "NumberFormatException" - "ArithmeticException" "NullPointerException" "ClassCastException" "IndexOutOfBoundsException" - "FileNotFoundException" "UnsupportedEncodingException" "EOFException" "java.io.EOFException" - "Error" "AssertionError")) - -;; ---- URLEncoder / URLDecoder (www-form-urlencoded) -------------------------- -(define (url-unreserved? b) - (or (and (>= b 48) (<= b 57)) (and (>= b 65) (<= b 90)) (and (>= b 97) (<= b 122)) - (= b 46) (= b 42) (= b 95) (= b 45))) -(define hex-digits "0123456789ABCDEF") -(define (url-encode s . _) - (let ((bs (string->utf8 (if (string? s) s (jolt-str-render-one s)))) (out '())) - (let loop ((i 0)) - (if (= i (bytevector-length bs)) (list->string (reverse out)) - (let ((b (bytevector-u8-ref bs i))) - (cond ((url-unreserved? b) (set! out (cons (integer->char b) out))) - ((= b 32) (set! out (cons #\+ out))) - (else (set! out (cons (string-ref hex-digits (bitwise-and b 15)) - (cons (string-ref hex-digits (bitwise-arithmetic-shift-right b 4)) - (cons #\% out)))))) - (loop (+ i 1))))))) -(define (hexv c) - (cond ((and (char<=? #\0 c) (char<=? c #\9)) (- (char->integer c) 48)) - ((and (char<=? #\A c) (char<=? c #\F)) (- (char->integer c) 55)) - ((and (char<=? #\a c) (char<=? c #\f)) (- (char->integer c) 87)) - (else (error #f "URLDecoder: malformed escape")))) -(define (url-decode s . _) - (let* ((str (if (string? s) s (jolt-str-render-one s))) (n (string-length str)) (out '())) - (let loop ((i 0)) - (if (>= i n) (utf8->string (u8-list->bytevector (reverse out))) - (let ((c (string-ref str i))) - (cond ((char=? c #\+) (set! out (cons 32 out)) (loop (+ i 1))) - ((char=? c #\%) - (set! out (cons (+ (* 16 (hexv (string-ref str (+ i 1)))) (hexv (string-ref str (+ i 2)))) out)) - (loop (+ i 3))) - (else (set! out (cons (char->integer c) out)) (loop (+ i 1))))))))) -(define (u8-list->bytevector lst) - (let ((bv (make-bytevector (length lst)))) - (let loop ((l lst) (i 0)) (if (null? l) bv (begin (bytevector-u8-set! bv i (car l)) (loop (cdr l) (+ i 1))))))) -(register-class-statics! "URLEncoder" (list (cons "encode" url-encode))) -(register-class-statics! "URLDecoder" (list (cons "decode" url-decode))) -;; Charset/forName yields the canonical name STRING (not an opaque object) so it -;; threads straight into (.getBytes s cs) / (String. bytes cs), which take a name. -(register-class-statics! "Charset" (list (cons "forName" (lambda (nm) (jolt-str-render-one nm))))) - -;; ---- Base64 (RFC 4648) ------------------------------------------------------ -(define b64-alphabet "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/") -(define (->bytevector x) - (cond ((bytevector? x) x) - ((and (jolt-array? x) (eq? (jolt-array-kind x) 'byte)) (na-bytearray->bv x)) - ((string? x) (string->utf8 x)) - (else (string->utf8 (jolt-str-render-one x))))) -(define (b64-encode x) - (let* ((bs (->bytevector x)) (n (bytevector-length bs)) (out '())) - (let loop ((i 0)) - (if (>= i n) (list->string (reverse out)) - (let* ((b0 (bytevector-u8-ref bs i)) - (b1 (if (< (+ i 1) n) (bytevector-u8-ref bs (+ i 1)) #f)) - (b2 (if (< (+ i 2) n) (bytevector-u8-ref bs (+ i 2)) #f))) - (set! out (cons (string-ref b64-alphabet (bitwise-arithmetic-shift-right b0 2)) out)) - (set! out (cons (string-ref b64-alphabet (bitwise-ior (bitwise-arithmetic-shift-left (bitwise-and b0 3) 4) - (bitwise-arithmetic-shift-right (or b1 0) 4))) out)) - (set! out (cons (if b1 (string-ref b64-alphabet (bitwise-ior (bitwise-arithmetic-shift-left (bitwise-and b1 15) 2) - (bitwise-arithmetic-shift-right (or b2 0) 6))) #\=) out)) - (set! out (cons (if b2 (string-ref b64-alphabet (bitwise-and b2 63)) #\=) out)) - (loop (+ i 3))))))) -(define (b64-char-val c) - (let loop ((i 0)) (cond ((= i 64) (error #f "Base64: illegal character")) ((char=? (string-ref b64-alphabet i) c) i) (else (loop (+ i 1)))))) -(define (b64-decode x) - (let* ((str (let ((s (if (string? x) x (utf8->string (->bytevector x))))) - (list->string (filter (lambda (c) (not (char=? c #\=))) (string->list s))))) - (out '()) (acc 0) (bits 0)) - (for-each (lambda (c) - (set! acc (bitwise-ior (bitwise-arithmetic-shift-left acc 6) (b64-char-val c))) - (set! bits (+ bits 6)) - (when (>= bits 8) - (set! bits (- bits 8)) - (set! out (cons (bitwise-and (bitwise-arithmetic-shift-right acc bits) 255) out)))) - (string->list str)) - (u8-list->bytevector (reverse out)))) -(register-host-methods! "b64-encoder" - (list (cons "encode" (lambda (self bs) (string->utf8 (b64-encode bs)))) - (cons "encodeToString" (lambda (self bs) (b64-encode bs))))) -(register-host-methods! "b64-decoder" - (list (cons "decode" (lambda (self s) (b64-decode s))))) -(register-class-statics! "Base64" - (list (cons "getEncoder" (lambda () (make-jhost "b64-encoder" '()))) - (cons "getDecoder" (lambda () (make-jhost "b64-decoder" '()))))) - -;; ---- java.util.regex.Pattern ------------------------------------------------ -;; Pattern/compile returns a jolt-regex value (regex-t), so str/replace, re-find, -;; .split etc. accept it transparently. -(define pattern-multiline 8.0) -(define (pattern-quote s) - (let ((meta "\\.[]{}()*+-?^$|&") (s (if (string? s) s (jolt-str-render-one s))) (out '())) - (let loop ((i 0)) - (if (= i (string-length s)) (list->string (reverse out)) - (let ((c (string-ref s i))) - (when (memv c (string->list meta)) (set! out (cons #\\ out))) - (set! out (cons c out)) - (loop (+ i 1))))))) -(register-class-statics! "Pattern" - (list (cons "compile" (lambda (s . flags) - (if (and (pair? flags) (= (bitwise-and (jnum->exact (car flags)) 8) 8)) - (jolt-regex (string-append "(?m)" s)) - (jolt-regex s)))) - (cons "quote" (lambda (s) (pattern-quote s))) - (cons "MULTILINE" pattern-multiline))) -;; record-method-dispatch already routes string? -> jolt-string-method. Add a -;; regex-t arm (Pattern .split / .matcher-less surface used by corpus) by wrapping -;; once more — a regex-t isn't a jhost. -(register-method-arm! 42 - (lambda (obj method-name rest-args) - (let ((rest (if (jolt-nil? rest-args) '() (seq->list rest-args)))) - (cond - ((regex-t? obj) - (cond ((string=? method-name "split") - ;; .split returns a String[] — a seq (prints - ;; (a b c), not a vector). re-split with no limit; drop trailing - ;; empties (JVM default). - (let ((parts (re-split (regex-t-irx obj) (car rest) #f))) - (list->cseq (str-split-drop-trailing parts)))) - ((string=? method-name "pattern") (regex-t-source obj)) - ((or (string=? method-name "toString")) (regex-t-source obj)) - ;; (.matcher pattern s) -> a Matcher (matcher-t) for stepping matches. - ((string=? method-name "matcher") (jolt-re-matcher obj (car rest))) - (else (error #f (string-append "No method " method-name " on Pattern"))))) - ;; java.util.regex.Matcher: .matches (anchored whole-region), .find - ;; (next match), .group [n], .groupCount. - ((jolt-matcher? obj) - (cond ((string=? method-name "matches") (jolt-matcher-matches obj)) - ((string=? method-name "find") (not (jolt-nil? (jolt-re-find obj)))) - ((string=? method-name "group") (apply jolt-matcher-group obj rest)) - ((string=? method-name "groupCount") (jolt-matcher-group-count obj)) - (else (error #f (string-append "No method " method-name " on Matcher"))))) - (else 'pass))))) - -;; ---- def-var! the registry entry points so emit can also reach them --------- -(def-var! "clojure.core" "host-static-ref" host-static-ref) -(def-var! "clojure.core" "host-static-call" (lambda (c m . a) (apply host-static-call c m a))) -(def-var! "clojure.core" "host-new" (lambda (c . a) (apply host-new c a))) - -;; Clojure-visible class-registration hooks. A host shim (e.g. reitit.trie-jolt, -;; which mirrors the reitit.Trie Java class) registers a constructor proc or a -;; map of static members against a class token so (Class. args) / (Class/member -;; args) resolve to it. The statics argument is a jolt map {member-name -> val}. -(define (jmap->static-alist m) - (let loop ((s (jolt-seq m)) (acc '())) - (if (jolt-nil? s) acc - (let ((e (jolt-first s))) - (loop (jolt-seq (jolt-rest s)) (cons (cons (jolt-nth e 0) (jolt-nth e 1)) acc)))))) -(def-var! "clojure.core" "__register-class-ctor!" - (lambda (name proc) (register-class-ctor! name proc) jolt-nil)) -(def-var! "clojure.core" "__register-class-statics!" - (lambda (name members) (register-class-statics! name (jmap->static-alist members)) jolt-nil)) - -;; ---- tagged-table method dispatch + pluggable instance? -------------------- -;; A jolt library can build stateful host objects with (jolt.host/tagged-table -;; tag) and dispatch (.method obj ...) to handlers registered here, keyed by the -;; table's "jolt/type" tag — the htable analogue of the jhost method registry -;; above. jolt-lang/http-client uses this to emulate java.net URL / -;; HttpURLConnection / java.io byte streams so clj-http-lite runs unchanged. -(define tagged-methods-tbl (make-hashtable string-hash string=?)) ; tag-key -> (method-ht) -(define (tag->method-key tag) - (if (keyword-t? tag) - (let ((ns (keyword-t-ns tag))) - (if (and ns (not (jolt-nil? ns))) (string-append ns "/" (keyword-t-name tag)) (keyword-t-name tag))) - (jolt-str-render-one tag))) -(define (register-tagged-methods! tag members) - (let* ((key (tag->method-key tag)) - (h (or (hashtable-ref tagged-methods-tbl key #f) - (let ((nh (make-hashtable string-hash string=?))) - (hashtable-set! tagged-methods-tbl key nh) nh)))) - (for-each (lambda (p) (hashtable-set! h (car p) (cdr p))) members))) - -;; htable arm: dispatch (.method obj a*) through the table's tag method registry; -;; an unregistered method falls through (sorted colls are htables too). -(register-method-arm! 43 - (lambda (obj method-name rest-args) - (let ((tag (and (htable? obj) (hashtable-ref (htable-h obj) "jolt/type" #f)))) - (let* ((mh (and tag (hashtable-ref tagged-methods-tbl (tag->method-key tag) #f))) - (f (and mh (hashtable-ref mh method-name #f)))) - (if f - (apply f obj (if (jolt-nil? rest-args) '() (seq->list rest-args))) - 'pass))))) - -(def-var! "clojure.core" "__register-class-methods!" - (lambda (tag members) (register-tagged-methods! tag (jmap->static-alist members)) jolt-nil)) - -;; java.lang.ThreadLocal via a Chez thread-parameter: real per-thread storage with -;; a lazy initialValue (the proxy macro lowers (proxy [ThreadLocal] …) to this). -;; .get returns the thread's value, computing initialValue once; .set / .remove. -(define tl-unset (list 'tl-unset)) -(define (jolt-make-thread-local init-thunk) - (make-jhost "threadlocal" (vector (make-thread-parameter tl-unset) init-thunk))) -(register-host-methods! "threadlocal" - (list (cons "get" (lambda (self) - (let* ((st (jhost-state self)) (tp (vector-ref st 0)) (v (tp))) - (if (eq? v tl-unset) - (let ((nv (jolt-invoke (vector-ref st 1)))) (tp nv) nv) - v)))) - (cons "set" (lambda (self v) ((vector-ref (jhost-state self) 0) v) jolt-nil)) - (cons "remove" (lambda (self) ((vector-ref (jhost-state self) 0) tl-unset) jolt-nil)))) -(def-var! "jolt.host" "make-thread-local" jolt-make-thread-local) - -;; Pluggable instance? — a library registers (fn [class-name-string val] -> true -;; | false | nil); nil means "not my class, fall through". First non-nil wins. -(define user-instance-checks '()) -(register-instance-check-arm! - (lambda (type-sym val) - (let ((tname (symbol-t-name type-sym))) - (let loop ((fs user-instance-checks)) - (if (null? fs) - 'pass - (let ((r ((car fs) tname val))) - (if (jolt-nil? r) (loop (cdr fs)) (if (jolt-truthy? r) #t #f)))))))) -(def-var! "clojure.core" "__register-instance-check!" - (lambda (f) (set! user-instance-checks (append user-instance-checks (list f))) jolt-nil)) - -;; (instance? clojure.lang.IFoo x) for the core clojure.lang interfaces libraries -;; branch on — jolt's value model satisfies them, so report it. Matched by the -;; interface's last dotted segment, so "clojure.lang.IObj" and "IObj" both hit. -(define (hsc-last-segment s) - (let loop ((i (- (string-length s) 1))) - (cond ((< i 0) s) - ((char=? (string-ref s i) #\.) (substring s (+ i 1) (string-length s))) - (else (loop (- i 1)))))) -;; values that carry metadata (mirrors jolt-with-meta's set in natives-meta.ss). -(define (hsc-imeta? x) - (or (pvec? x) (pmap? x) (pset? x) (cseq? x) (empty-list-t? x) - (jolt-lazyseq? x) (jrec? x) (jreify? x) (procedure? x) (symbol-t? x))) -(register-instance-check-arm! - (lambda (type-sym val) - (let ((iface (hsc-last-segment (symbol-t-name type-sym)))) - ;; the value's own class-graph tags (value-host-tags) are authoritative — the - ;; SAME source protocol dispatch reads, so instance? and extend-protocol can't - ;; disagree about the interfaces a builtin implements. - (if (let ((tags (value-host-tags val))) - (or (member (symbol-t-name type-sym) tags) (member iface tags))) - #t - (let ((hit (cond - ((or (string=? iface "IObj") (string=? iface "IMeta")) (hsc-imeta? val)) - ((or (string=? iface "IMapEntry") (string=? iface "MapEntry")) (jolt-map-entry? val)) - ((string=? iface "IRecord") (jrec? val)) - ((string=? iface "IPersistentMap") (or (pmap? val) (htable-sorted-map? val))) - ((string=? iface "IPersistentVector") (and (pvec? val) (not (jolt-map-entry? val)))) - ((string=? iface "IPersistentSet") (or (pset? val) (htable-sorted-set? val))) - ((string=? iface "ISeq") - (or (cseq? val) (empty-list-t? val) (jolt-lazyseq? val))) - ((string=? iface "LazySeq") (jolt-lazyseq? val)) - ;; Seqable is anything (seq x) works on — every persistent - ;; collection, not just seqs (a vector IS Seqable, not an ISeq). - ((string=? iface "Seqable") - (or (cseq? val) (empty-list-t? val) (jolt-lazyseq? val) - (pvec? val) (pmap? val) (pset? val) - (htable-sorted-map? val) (htable-sorted-set? val))) - ((string=? iface "Sequential") - (or (pvec? val) (cseq? val) (empty-list-t? val) (jolt-lazyseq? val))) - ((string=? iface "IFn") - (or (procedure? val) (keyword? val) (symbol-t? val) - (pmap? val) (pset? val) (pvec? val))) - ;; host-class interfaces libraries branch on (data.json, etc.). - ;; Matched by last segment, so java.util.Map and Map both hit. - ((string=? iface "Named") (or (keyword? val) (symbol-t? val))) - ((string=? iface "CharSequence") (string? val)) - ((string=? iface "Number") (number? val)) - ((string=? iface "Map") (or (pmap? val) (htable-sorted-map? val))) - ((string=? iface "Set") (or (pset? val) (htable-sorted-set? val))) - ;; a Java List is a vector or a seq/list — not a set or map. - ((string=? iface "List") - (or (and (pvec? val) (not (jolt-map-entry? val))) - (cseq? val) (empty-list-t? val) (jolt-lazyseq? val))) - ;; a Java Collection is any of those plus a set — but NOT a map. - ((string=? iface "Collection") - (or (pvec? val) (pset? val) (cseq? val) (empty-list-t? val) - (jolt-lazyseq? val) (htable-sorted-set? val))) - ((string=? iface "Associative") - (or (pmap? val) (htable-sorted-map? val) - (and (pvec? val) (not (jolt-map-entry? val))))) - ;; ILookup (valAt): maps and vectors; Indexed (nth): vectors; - ;; Counted: the counted collections. A deftype that declares one - ;; is matched by type-satisfies? in instance-check-base. - ((string=? iface "ILookup") - (or (pmap? val) (htable-sorted-map? val) - (and (pvec? val) (not (jolt-map-entry? val))))) - ((string=? iface "Indexed") - (and (pvec? val) (not (jolt-map-entry? val)))) - ((string=? iface "Counted") - (or (pmap? val) (pset? val) (pvec? val) - (htable-sorted-map? val) (htable-sorted-set? val))) - ;; reader jhosts — data.json re-wraps a reader in a new - ;; PushbackReader unless (instance? PushbackReader r), so this - ;; must hold for repeated reads from one reader to work. - ((string=? iface "PushbackReader") - (and (jhost? val) (string=? (jhost-tag val) "pushback-reader"))) - ((string=? iface "StringReader") - (and (jhost? val) (string=? (jhost-tag val) "string-reader"))) - ((or (string=? iface "Reader") (string=? iface "BufferedReader")) - (reader-jhost? val)) - (else 'none)))) - (if (eq? hit 'none) 'pass (if hit #t #f))))))) - -;; java.lang.Class value: (class x) / (.getClass x) return one. It renders like -;; the JVM — str/.toString -> "class ", pr -> "", .getName -> "" -;; — but stays = and hash equal to its name STRING, so (= (class x) String), -;; class-keyed maps/sets, multimethod dispatch on class, and instance? all keep -;; working against the bare class-name tokens. -(define (make-class-obj name) (make-jhost "class" (vector name))) -(define (jclass? x) (and (jhost? x) (string=? (jhost-tag x) "class"))) -(define (jclass-name x) (vector-ref (jhost-state x) 0)) -(define (class-key x) - (cond ((jclass? x) (jclass-name x)) - ((string? x) x) - ;; a deftype/defrecord NAME var holds its ctor; treat it as the class - ((procedure? x) (hashtable-ref chez-deftype-ctor-tag x #f)) - (else #f))) -(register-eq-arm! (lambda (a b) (or (jclass? a) (jclass? b))) - (lambda (a b) (let ((ka (class-key a)) (kb (class-key b))) - (and ka kb (string=? ka kb) #t)))) -(register-hash-arm! jclass? (lambda (x) (jolt-hash (jclass-name x)))) -(register-str-render! jclass? (lambda (x) (string-append "class " (jclass-name x)))) -(register-pr-arm! jclass? (lambda (x) (jclass-name x))) -(register-host-methods! "class" - (list (cons "getName" (lambda (self) (jclass-name self))) - (cons "getCanonicalName" (lambda (self) (jclass-name self))) - (cons "getSimpleName" (lambda (self) (hsc-last-segment (jclass-name self)))) - (cons "toString" (lambda (self) (string-append "class " (jclass-name self)))) - (cons "isArray" (lambda (self) (let ((n (jclass-name self))) - (and (fx>? (string-length n) 0) (char=? (string-ref n 0) #\[))))) - ;; Class.isInstance(o) == (instance? class o); core.logic's deftype .equals - ;; uses (.. this getClass (isInstance o)). - (cons "isInstance" (lambda (self o) (if (instance-check self o) #t #f))) - (cons "getClass" (lambda (self) (make-class-obj "java.lang.Class"))))) - -;; (jolt.host/table? x) — is x a host tagged-table? -(def-var! "jolt.host" "table?" (lambda (x) (if (htable? x) #t #f))) - -;; --- java.util.Arrays ------------------------------------------------------- -(let ((arrays-statics - (list - (cons "equals" (lambda (a b) - (cond ((and (jolt-nil? a) (jolt-nil? b)) #t) - ((or (jolt-nil? a) (jolt-nil? b)) #f) - (else (equal? (jolt-array-vec a) (jolt-array-vec b)))))) - (cons "fill" (lambda (a v) (vector-fill! (jolt-array-vec a) v) jolt-nil)) - (cons "copyOf" (lambda (a n) - (let* ((src (jolt-array-vec a)) (len (jnum->exact n)) - (out (make-vector len 0))) - (do ((i 0 (fx+ i 1))) ((fx=? i (min len (vector-length src)))) - (vector-set! out i (vector-ref src i))) - (make-jolt-array out (jolt-array-kind a))))) - (cons "copyOfRange" (lambda (a from to) - (let* ((src (jolt-array-vec a)) (f (jnum->exact from)) (tt (jnum->exact to)) - (len (- tt f)) (out (make-vector len 0))) - (do ((i 0 (fx+ i 1))) ((fx=? i len)) - (vector-set! out i (vector-ref src (+ f i)))) - (make-jolt-array out (jolt-array-kind a))))) - (cons "toString" (lambda (a) (jolt-pr-str (apply jolt-vector (vector->list (jolt-array-vec a))))))))) - (register-class-statics! "Arrays" arrays-statics) - (register-class-statics! "java.util.Arrays" arrays-statics)) - -;; --- java.util.Random ------------------------------------------------------- -;; A non-cryptographic PRNG over Chez's `random`. A seed argument is accepted but -;; not honored for reproducibility (jolt has no seedable Random state); callers -;; that need determinism use SecureRandom or their own generator. -(for-each - (lambda (nm) (register-class-ctor! nm (lambda args (make-jhost "random" (vector))))) - '("Random" "java.util.Random")) -(register-host-methods! "random" - (list - (cons "nextBytes" (lambda (self ba) - (let ((v (jolt-array-vec ba))) - (do ((i 0 (fx+ i 1))) ((fx=? i (vector-length v))) - (vector-set! v i (random 256)))) - jolt-nil)) - (cons "nextInt" (lambda (self . a) - (->num (if (pair? a) (random (jnum->exact (car a))) (- (random 4294967296) 2147483648))))) - (cons "nextLong" (lambda (self) (->num (- (random 18446744073709551616) 9223372036854775808)))) - (cons "nextDouble" (lambda (self) (random 1.0))) - (cons "nextFloat" (lambda (self) (random 1.0))) - (cons "nextBoolean" (lambda (self) (fx=? 0 (random 2)))))) - -;; --- java.util.Optional ----------------------------------------------------- -;; Returned by getters across java.time / java.net.http (e.g. HttpRequest.timeout, -;; HttpClient.connectTimeout). Value-equal so (= (Optional/of x) (Optional/of x)). -(define (jt-optional present? value) (make-jhost "optional" (vector present? value))) -(define jt-optional-empty (jt-optional #f jolt-nil)) -(define (opt? x) (and (jhost? x) (string=? (jhost-tag x) "optional"))) -(define (opt-present? o) (vector-ref (jhost-state o) 0)) -(define (opt-value o) (vector-ref (jhost-state o) 1)) -(let ((statics (list (cons "of" (lambda (v) (if (jolt-nil? v) (error #f "Optional.of(null)") (jt-optional #t v)))) - (cons "ofNullable" (lambda (v) (if (jolt-nil? v) jt-optional-empty (jt-optional #t v)))) - (cons "empty" (lambda _ jt-optional-empty))))) - (register-class-statics! "Optional" statics) - (register-class-statics! "java.util.Optional" statics)) -(register-host-methods! "optional" - (list (cons "isPresent" (lambda (o) (opt-present? o))) - (cons "isEmpty" (lambda (o) (not (opt-present? o)))) - (cons "get" (lambda (o) (if (opt-present? o) (opt-value o) (error #f "Optional.get() on empty Optional")))) - (cons "orElse" (lambda (o d) (if (opt-present? o) (opt-value o) d))) - (cons "orElseGet" (lambda (o f) (if (opt-present? o) (opt-value o) (jolt-invoke f)))) - (cons "ifPresent" (lambda (o f) (when (opt-present? o) (jolt-invoke f (opt-value o))) jolt-nil)) - (cons "toString" (lambda (o) (if (opt-present? o) - (string-append "Optional[" (jolt-str-render-one (opt-value o)) "]") - "Optional.empty"))))) -(register-eq-arm! (lambda (a b) (or (opt? a) (opt? b))) - (lambda (a b) (and (opt? a) (opt? b) (eq? (opt-present? a) (opt-present? b)) - (or (not (opt-present? a)) (jolt=2 (opt-value a) (opt-value b)))))) - -;; --- minimal JVM class/interface ancestry ----------------------------------- -;; A handful of libraries reflect over the class hierarchy — e.g. core.memoize -;; validates its first argument with (some #{IFn AFn Runnable Callable} -;; (ancestors (class f))). jolt models a class as its name string and has no -;; reflection, so supers/ancestors return nothing on their own. This table gives -;; the common interfaces the direct supers the JVM reports, and the overlay's -;; supers/ancestors fold it in. Keyed by canonical class name; value = direct -;; supers. Extend as more interfaces are exercised. -(define class-supers-tbl (make-hashtable string-hash string=?)) -(define (reg-class-supers! name supers) (hashtable-set! class-supers-tbl name supers)) -(reg-class-supers! "clojure.lang.IFn" '("java.lang.Runnable" "java.util.concurrent.Callable")) -(reg-class-supers! "clojure.lang.AFn" '("clojure.lang.IFn" "java.lang.Runnable" "java.util.concurrent.Callable")) -(reg-class-supers! "clojure.lang.AFunction" '("clojure.lang.AFn" "clojure.lang.IFn" "clojure.lang.Fn" - "java.lang.Runnable" "java.util.concurrent.Callable")) -;; common exception hierarchy, so (instance? IOException e) / (catch IOException e) -;; match a more specific throwable a library threw (e.g. http-client's -;; UnknownHostException, caught by clj-http-lite's :ignore-unknown-host?). -(reg-class-supers! "java.lang.Throwable" '("java.lang.Object")) -(reg-class-supers! "java.lang.Exception" '("java.lang.Throwable" "java.lang.Object")) -(reg-class-supers! "java.lang.RuntimeException" '("java.lang.Exception" "java.lang.Throwable" "java.lang.Object")) -(reg-class-supers! "java.io.IOException" '("java.lang.Exception" "java.lang.Throwable" "java.lang.Object")) -(reg-class-supers! "java.io.InterruptedIOException" '("java.io.IOException" "java.lang.Exception" "java.lang.Throwable" "java.lang.Object")) -(reg-class-supers! "java.net.SocketException" '("java.io.IOException" "java.lang.Exception" "java.lang.Throwable" "java.lang.Object")) -(reg-class-supers! "java.net.UnknownHostException" '("java.io.IOException" "java.lang.Exception" "java.lang.Throwable" "java.lang.Object")) -(reg-class-supers! "java.net.ConnectException" '("java.net.SocketException" "java.io.IOException" "java.lang.Exception" "java.lang.Throwable" "java.lang.Object")) -(reg-class-supers! "java.net.SocketTimeoutException" '("java.io.InterruptedIOException" "java.io.IOException" "java.lang.Exception" "java.lang.Throwable" "java.lang.Object")) -;; clojure.lang / java.util ancestry for the builtins (class) reports, so a -;; class-keyed multimethod / (isa? (class x) SomeClass) dispatches like the JVM. -;; (Object is supplied universally by class-isa?, so it need not be listed.) -(reg-class-supers! "clojure.lang.IFn" '("clojure.lang.Fn" "java.lang.Runnable" "java.util.concurrent.Callable")) -;; Keyword and Symbol implement IFn (they are callable: (:k m) / ('s m)), so a -;; (class x)-dispatched multimethod with an IFn method matches them, like the JVM. -(reg-class-supers! "clojure.lang.Keyword" '("clojure.lang.Named" "java.lang.Comparable" - "clojure.lang.IFn" "clojure.lang.Fn" - "java.lang.Runnable" "java.util.concurrent.Callable")) -(reg-class-supers! "clojure.lang.Symbol" '("clojure.lang.Named" "java.lang.Comparable" - "clojure.lang.IFn" "clojure.lang.Fn" - "java.lang.Runnable" "java.util.concurrent.Callable")) -(reg-class-supers! "java.lang.String" '("java.lang.CharSequence" "java.lang.Comparable")) -(reg-class-supers! "clojure.lang.PersistentHashSet" '("clojure.lang.APersistentSet" "clojure.lang.IPersistentSet" "clojure.lang.IPersistentCollection" "java.util.Set" "java.util.Collection" "java.lang.Iterable")) -(reg-class-supers! "clojure.lang.PersistentTreeSet" '("clojure.lang.APersistentSet" "clojure.lang.IPersistentSet" "clojure.lang.IPersistentCollection" "java.util.Set" "java.util.Collection" "java.lang.Iterable")) -(reg-class-supers! "clojure.lang.PersistentVector" '("clojure.lang.APersistentVector" "clojure.lang.IPersistentVector" "clojure.lang.IPersistentCollection" "clojure.lang.Sequential" "clojure.lang.Associative" "java.util.List" "java.util.Collection" "java.lang.Iterable")) -(reg-class-supers! "clojure.lang.PersistentArrayMap" '("clojure.lang.APersistentMap" "clojure.lang.IPersistentMap" "clojure.lang.IPersistentCollection" "clojure.lang.Associative" "java.util.Map" "java.lang.Iterable")) -(reg-class-supers! "clojure.lang.PersistentHashMap" '("clojure.lang.APersistentMap" "clojure.lang.IPersistentMap" "clojure.lang.IPersistentCollection" "clojure.lang.Associative" "java.util.Map" "java.lang.Iterable")) -(reg-class-supers! "clojure.lang.PersistentList" '("clojure.lang.ASeq" "clojure.lang.ISeq" "clojure.lang.IPersistentCollection" "clojure.lang.Sequential" "clojure.lang.Seqable" "java.util.List" "java.util.Collection" "java.lang.Iterable")) -(reg-class-supers! "clojure.lang.LazySeq" '("clojure.lang.ISeq" "clojure.lang.IPersistentCollection" "clojure.lang.Sequential" "clojure.lang.Seqable" "java.lang.Iterable")) -(reg-class-supers! "clojure.lang.Cons" '("clojure.lang.ASeq" "clojure.lang.ISeq" "clojure.lang.Sequential" "clojure.lang.Seqable" "java.lang.Iterable")) - -;; A munged fn class name "ns$name" (jolt-class for a def'd fn) isn't in the table; -;; like the JVM (a fn extends clojure.lang.AFunction) its super is AFunction, whose -;; registered supers give AFn / IFn / Fn / Runnable / Callable transitively. -(define (str-has-dollar? s) - (let loop ((i 0)) (and (< i (string-length s)) (or (char=? (string-ref s i) #\$) (loop (+ i 1)))))) -(define (class-direct-supers name) - ;; union the modeled class graph (jch, direct edges) with any legacy table entry, - ;; so isa?/supers/ancestors see the single hierarchy source plus anything not yet - ;; migrated. The closure below traverses these to the full transitive set. - (let ((jch (jch-direct-supers name)) - (old (hashtable-ref class-supers-tbl name #f))) - (cond ((and (pair? jch) old) - (let merge ((ss old) (acc jch)) - (cond ((null? ss) acc) - ((member (car ss) acc) (merge (cdr ss) acc)) - (else (merge (cdr ss) (append acc (list (car ss)))))))) - ((pair? jch) jch) - (old old) - ((str-has-dollar? name) '("clojure.lang.AFunction")) - (else '())))) -;; transitive closure of direct supers (set semantics via an accumulator list) -(define (class-ancestors-list name) - (let loop ((pending (class-direct-supers name)) (seen '())) - (cond ((null? pending) (reverse seen)) - ((member (car pending) seen) (loop (cdr pending) seen)) - (else (loop (append (class-direct-supers (car pending)) (cdr pending)) - (cons (car pending) seen)))))) - -;; (instance? Class e) on a throwable tagged-table carrying a JVM :class matches the -;; carried class or any of its ancestors (full name or last segment), so a library's -;; (catch UnknownHostException e …) / (catch IOException e …) matches the ex-info -;; envelope it threw. Mirrors the (class e) arm (host-table.ss) for catch dispatch, -;; which lowers to (instance? C e). Non-match returns 'pass so other arms still run. -(register-instance-check-arm! - (lambda (type-sym val) - (if (and (htable? val) (string? (hashtable-ref (htable-h val) "class" #f))) - (let* ((cls (hashtable-ref (htable-h val) "class" #f)) - (want (symbol-t-name type-sym)) - (want-seg (hsc-last-segment want))) - (let loop ((names (cons cls (class-ancestors-list cls)))) - (cond ((null? names) 'pass) - ((or (string=? want (car names)) - (string=? want-seg (hsc-last-segment (car names)))) #t) - (else (loop (cdr names)))))) - 'pass))) - -;; JVM class assignability for isa? (20-coll): true when child and parent are both -;; class values and parent is child, java.lang.Object (every class's root), or a -;; modeled ancestor of child (full name or last segment). nil for non-class args, so -;; isa? falls through to its hierarchy/vector logic. -(def-var! "jolt.host" "class-isa?" - (lambda (child parent) - (let ((cc (class-key child)) (pp (class-key parent))) - (if (and cc pp) - (let ((pseg (hsc-last-segment pp))) - (if (let loop ((names (cons cc (class-ancestors-list cc)))) - (cond ((string=? pp "java.lang.Object") #t) - ((null? names) #f) - ((or (string=? pp (car names)) - (string=? pseg (hsc-last-segment (car names)))) #t) - (else (loop (cdr names))))) - #t jolt-nil)) - jolt-nil)))) - -;; is NAME a class the host models (registered in the class graph, a legacy -;; supers-table entry, or a fn class)? Object itself is modeled. -(define (hsc-class-known? name) - (or (string=? name "java.lang.Object") - (jch-known? name) - (and (hashtable-ref class-supers-tbl name #f) #t) - (str-has-dollar? name))) - -;; transitive ancestry, rooted at Object for a concrete class like (supers c); -;; an interface's chain has no Object (its getSuperclass is null). '() for -;; Object itself and for a name the host doesn't model. -(define (class-ancestors-rooted name) - (if (or (string=? name "java.lang.Object") (jch-interface? name)) - (class-ancestors-list name) - (let ((as (class-ancestors-list name))) - (cond ((member "java.lang.Object" as) as) - ((null? as) (if (hsc-class-known? name) '("java.lang.Object") '())) - (else (append as '("java.lang.Object"))))))) - -;; (jolt.host/class-supers name) / (jolt.host/class-ancestors name) — a jolt seq of -;; super / ancestor class-name strings (transitive, Object-rooted), or nil when -;; jolt models no hierarchy for it. class-bases is the DIRECT supers (clojure.core -;; `bases` / the class arm of `parents`). -(def-var! "jolt.host" "class-supers" - (lambda (x) - (let ((name (class-key x))) - (if name - (let ((as (class-ancestors-rooted name))) - (if (null? as) jolt-nil (list->cseq as))) - jolt-nil)))) -(def-var! "jolt.host" "class-ancestors" - (lambda (x) - (let ((name (class-key x))) - (if name - (let ((as (class-ancestors-rooted name))) - (if (null? as) jolt-nil (list->cseq as))) - jolt-nil)))) -(def-var! "jolt.host" "class-bases" - (lambda (x) - (let ((name (class-key x))) - (if name - (let* ((ds (class-direct-supers name)) - ;; a concrete class's bases include its superclass — Object when - ;; nothing more specific is modeled (interfaces have none). - (ds (if (or (string=? name "java.lang.Object") - (jch-interface? name) - (member "java.lang.Object" ds)) - ds - (append ds '("java.lang.Object"))))) - (if (null? ds) jolt-nil (list->cseq ds))) - jolt-nil)))) -;; is X a class value — a jclass, a deftype ctor, or a name string the host -;; graph models? -(def-var! "jolt.host" "class-value?" - (lambda (x) - (if (jclass? x) - #t - (let ((n (class-key x))) - (if (and n (hsc-class-known? n)) #t jolt-nil))))) diff --git a/host/chez/java/host-static-methods.ss b/host/chez/java/host-static-methods.ss deleted file mode 100644 index ea8981f..0000000 --- a/host/chez/java/host-static-methods.ss +++ /dev/null @@ -1,443 +0,0 @@ -;; host-static-methods.ss — the `Class/member` static surface: java.lang.Math, -;; System (properties/env), Thread, the Long/Integer/Double/Character/String static -;; methods, java.text.NumberFormat, and the Class registry. Registers into -;; host-static.ss's class-statics table (loaded just before this); instantiable host -;; object classes (ArrayList, StringBuilder, …) live in host-static-classes.ss. - -;; ---- java.lang statics ------------------------------------------------------ -;; java.lang.Math: sqrt/pow/floor/ceil/trig/log/exp always return a DOUBLE on the -;; JVM (Chez's sqrt/expt return EXACT for exact args, e.g. (sqrt 9) -> 3), so coerce -;; to flonum. round -> long (exact); abs/max/min preserve the argument's type. -(define (->dbl x) (exact->inexact x)) -(register-class-statics! "Math" - (list (cons "sqrt" (lambda (x) (->dbl (sqrt x)))) - (cons "pow" (lambda (a b) (->dbl (expt a b)))) - (cons "floor" (lambda (x) (->dbl (floor x)))) - (cons "ceil" (lambda (x) (->dbl (ceiling x)))) - (cons "round" (lambda (x) (exact (floor (+ x 1/2))))) ; JVM round-half-up -> long - (cons "abs" (lambda (x) (abs x))) - (cons "sin" (lambda (x) (->dbl (sin x)))) (cons "cos" (lambda (x) (->dbl (cos x)))) - (cons "tan" (lambda (x) (->dbl (tan x)))) (cons "asin" (lambda (x) (->dbl (asin x)))) - (cons "acos" (lambda (x) (->dbl (acos x)))) (cons "atan" (lambda (x) (->dbl (atan x)))) - (cons "log" (lambda (x) (->dbl (log x)))) (cons "log10" (lambda (x) (->dbl (/ (log x) (log 10))))) - (cons "exp" (lambda (x) (->dbl (exp x)))) - ;; getExponent: the unbiased binary exponent of a double (floor(log2|x|)); - ;; scalb: x * 2^n. test.check's double generator uses both. - (cons "getExponent" (lambda (x) (if (= x 0.0) -1023 - (exact (floor (/ (log (abs (exact->inexact x))) (log 2.0))))))) - (cons "scalb" (lambda (x n) (->dbl (* (exact->inexact x) (expt 2.0 (jnum->exact n)))))) - (cons "max" (lambda (a b) (if (> a b) a b))) (cons "min" (lambda (a b) (if (< a b) a b))) - (cons "signum" (lambda (x) (cond ((< x 0) -1.0) ((> x 0) 1.0) (else 0.0)))) - (cons "PI" (->dbl (* 4 (atan 1)))) (cons "E" (->dbl (exp 1))) - (cons "random" (lambda args (random 1.0))))) - -;; Thread: real OS threads back futures/promises. -;; - sleep parks the calling thread for `ms` ms (a worker sleeping doesn't block -;; the parent). -;; - yield hands the CPU to another runnable thread (libc sched_yield). -;; - each thread carries an interrupt flag; interrupted (static) reads AND clears -;; the current thread's flag, matching the JVM. currentThread / .interrupt / -;; .isInterrupted are wired in io.ss, where the thread handle is built. - -;; Per-thread interrupt flag, lazily allocated so each OS thread gets its own box. -;; A thread handle (from currentThread) captures this box, so .interrupt from -;; another thread sets the target thread's flag. -(define thread-interrupt-box (make-thread-parameter #f)) -(define (current-interrupt-box) - (or (thread-interrupt-box) - (let ((b (box #f))) (thread-interrupt-box b) b))) -(define (clear-thread-interrupt!) (set-box! (current-interrupt-box) #f)) - -;; libc sched_yield, resolved once; fall back to a zero-length park if the symbol -;; isn't available. -(define thread-yield! - (let ((fp #f) (tried? #f)) - (lambda () - (unless tried? - (set! tried? #t) - (set! fp (jolt-foreign-proc-safe "sched_yield" '() 'int))) - (if fp (fp) (sleep (make-time 'time-duration 0 0))) - jolt-nil))) - -(define thread-statics - (list (cons "sleep" (lambda (ms . _) - (let* ((ms* (exact (floor ms))) - (secs (quotient ms* 1000)) - (nanos (* (remainder ms* 1000) 1000000))) - (sleep (make-time 'time-duration nanos secs))) - jolt-nil)) - (cons "yield" (lambda _ (thread-yield!))) - (cons "interrupted" (lambda _ (let* ((b (current-interrupt-box)) (v (unbox b))) - (set-box! b #f) (and v #t)))))) -(register-class-statics! "Thread" thread-statics) -(register-class-statics! "java.lang.Thread" thread-statics) - -;; clojure.lang.LockingTransaction: jolt has no STM (no refs/dosync), so a -;; transaction is never running. isRunning -> false. -(register-class-statics! "LockingTransaction" (list (cons "isRunning" (lambda () #f)))) -(register-class-statics! "clojure.lang.LockingTransaction" (list (cons "isRunning" (lambda () #f)))) - -;; clojure.lang.LazilyPersistentVector/createOwning: build a vector from an array -;; (malli's -vmap fills an object-array then hands it over). jolt has no array -;; ownership transfer, so copy the array's elements into a persistent vector. -(define (lpv-create-owning arr) (apply jolt-vector (seq->list (jolt-seq arr)))) -(register-class-statics! "LazilyPersistentVector" (list (cons "createOwning" lpv-create-owning))) -(register-class-statics! "clojure.lang.LazilyPersistentVector" (list (cons "createOwning" lpv-create-owning))) - -;; clojure.lang.PersistentArrayMap/createWithCheck: build a map from a [k v k v…] -;; array, throwing on a duplicate key. malli's eager entry parser relies on the -;; throw to report ::duplicate-keys, so a missing class would mis-fire on every -;; map. Build the map and signal if a key collapsed (count*2 < array length). -(define (pam-create-with-check arr) - (let ((items (seq->list (jolt-seq arr)))) - (let loop ((xs items) (m (jolt-hash-map))) - (if (null? xs) m - (if (null? (cdr xs)) (error #f "PersistentArrayMap: odd key/value count") - (let ((k (car xs))) - (if (jolt-contains? m k) (error #f "Duplicate key") - (loop (cddr xs) (jolt-assoc m k (cadr xs)))))))))) -(register-class-statics! "PersistentArrayMap" (list (cons "createWithCheck" pam-create-with-check))) -(register-class-statics! "clojure.lang.PersistentArrayMap" (list (cons "createWithCheck" pam-create-with-check))) - -;; clojure.lang.RT/map: build a map from a [k v k v…] array/seq (RT.map). Small -;; maps keep insertion order (PersistentArrayMap). tools.reader builds map and -;; namespaced-map literals this way. -(define (rt-map arr) - (let loop ((xs (if (jolt-nil? arr) '() (seq->list (jolt-seq arr)))) (m (jolt-hash-map))) - (cond ((null? xs) m) - ((null? (cdr xs)) (error #f "RT/map: odd key/value count")) - (else (loop (cddr xs) (jolt-assoc m (car xs) (cadr xs))))))) -(register-class-statics! "RT" (list (cons "map" rt-map))) -(register-class-statics! "clojure.lang.RT" (list (cons "map" rt-map))) - -;; clojure.lang.PersistentList/create: a list (in order) from a seq; empty -> (). -(define (plist-create x) - (let ((items (seq->list (jolt-seq x)))) - (if (null? items) jolt-empty-list (list->cseq items)))) -(register-class-statics! "PersistentList" (list (cons "create" plist-create))) -(register-class-statics! "clojure.lang.PersistentList" (list (cons "create" plist-create))) - -;; clojure.lang.PersistentHashSet/createWithCheck: a set from a seq, throwing on a -;; duplicate element (tools.reader's #{…} reader reports the dup). -(define (phs-create-with-check x) - (let loop ((xs (seq->list (jolt-seq x))) (s (jolt-hash-set))) - (if (null? xs) s - (let ((e (car xs))) - (if (jolt-truthy? (jolt-contains? s e)) - (jolt-throw (jolt-ex-info (string-append "Duplicate key: " (jolt-str-render-one e)) (jolt-hash-map))) - (loop (cdr xs) (jolt-conj1 s e))))))) -(register-class-statics! "PersistentHashSet" (list (cons "createWithCheck" phs-create-with-check))) -(register-class-statics! "clojure.lang.PersistentHashSet" (list (cons "createWithCheck" phs-create-with-check))) - -;; java.lang.Character statics. digit(ch, radix) -> the digit value or -1; ch may -;; be a char or an int codepoint (tools.reader passes (int c)). isDigit/ -;; isWhitespace take a char; valueOf boxes a char (identity on jolt). -(define (char->cp x) (if (char? x) (char->integer x) (jnum->exact x))) -(define (char-digit-value cp radix) - (let ((d (cond ((and (fx>=? cp 48) (fx<=? cp 57)) (fx- cp 48)) ; 0-9 - ((and (fx>=? cp 97) (fx<=? cp 122)) (fx+ 10 (fx- cp 97))) ; a-z - ((and (fx>=? cp 65) (fx<=? cp 90)) (fx+ 10 (fx- cp 65))) ; A-Z - (else 99)))) - (if (fxnum (char-digit-value (char->cp ch) (jnum->exact radix))))) - (cons "isDigit" (lambda (ch) (let ((cp (char->cp ch))) (and (fx>=? cp 48) (fx<=? cp 57))))) - (cons "isWhitespace" (lambda (ch) (char-whitespace? (integer->char (char->cp ch))))) - (cons "valueOf" (lambda (ch) (if (char? ch) ch (integer->char (char->cp ch))))))) -(register-class-statics! "Character" character-statics) -(register-class-statics! "java.lang.Character" character-statics) - -;; java.util.regex.Pattern/compile: a regex value from a string pattern. -(define pattern-statics (list (cons "compile" (lambda (s) (jolt-regex (jolt-str-render-one s)))))) -(register-class-statics! "Pattern" pattern-statics) -(register-class-statics! "java.util.regex.Pattern" pattern-statics) - -;; clojure.lang.BigInt / clojure.lang.Numbers: jolt has one exact-integer type -;; (Chez bignums auto-reduce), so BigInt.fromBigInteger and Numbers.reduceBigInt -;; are identity. tools.reader's number parser threads integers through these. -(define identity-num-statics (list (cons "fromBigInteger" (lambda (x) x)))) -(register-class-statics! "BigInt" identity-num-statics) -(register-class-statics! "clojure.lang.BigInt" identity-num-statics) -(register-class-statics! "Numbers" - (list (cons "reduceBigInt" (lambda (x) x)) (cons "toRatio" (lambda (x) x)))) -(register-class-statics! "clojure.lang.Numbers" - (list (cons "reduceBigInt" (lambda (x) x)) (cons "toRatio" (lambda (x) x)))) - -(define (now-millis) - (let ((t (current-time 'time-utc))) - (+ (* 1000 (time-second t)) (quotient (time-nanosecond t) 1000000)))) - -;; clojure.core/current-time-ms — epoch milliseconds; backs the `time` macro. -(def-var! "clojure.core" "current-time-ms" (lambda () (->num (now-millis)))) -(register-class-statics! "System" - (list (cons "currentTimeMillis" (lambda () (->num (now-millis)))) - (cons "nanoTime" (lambda () (->num (* 1000000 (now-millis))))) - (cons "exit" (lambda args (exit (if (null? args) 0 (jnum->exact (car args)))))) - ;; System/gc -> a full Chez collection (so weak references clear and their - ;; guardians fire); Runtime.gc() routes here too. - (cons "gc" (lambda _ (collect (collect-maximum-generation)) jolt-nil)) - ;; wrapped in lambdas: the helpers are defined below, resolved at call time. - (cons "getProperty" (lambda (k . d) (apply sys-get-property k d))) - (cons "setProperty" (lambda (k v) (sys-set-property k v))) - (cons "clearProperty" (lambda (k) (sys-clear-property k))) - (cons "getProperties" (lambda () (sys-properties-map))) - (cons "getenv" (lambda k (apply sys-getenv k))))) - -;; java.lang.Long.bitCount: the population count of the value's 64-bit two's- -;; complement (mask to 64 bits so a negative long counts like the JVM, e.g. -;; bitCount(-1) = 64). test.check's splittable PRNG uses it. -(define long-mask64 #xFFFFFFFFFFFFFFFF) -(define long-2^63 (expt 2 63)) -(define long-2^64 (expt 2 64)) -;; interpret a 64-bit value as a signed long (top bit = sign), like the JVM. -(define (as-signed64 v) (if (>= v long-2^63) (- v long-2^64) v)) -(define (long-nlz n) (- 64 (integer-length (bitwise-and (jnum->exact n) long-mask64)))) -(define (long-reverse n) - (let ((v (bitwise-and (jnum->exact n) long-mask64))) - (let loop ((i 0) (r 0)) - (if (fx=? i 64) (as-signed64 r) - (loop (fx+ i 1) - (bitwise-ior (bitwise-arithmetic-shift-left r 1) - (bitwise-and (bitwise-arithmetic-shift-right v i) 1))))))) -(register-class-statics! "Long" - (list (cons "TYPE" "long") - (cons "MAX_VALUE" (->num 9223372036854775807)) - (cons "MIN_VALUE" (->num -9223372036854775808)) - (cons "bitCount" (lambda (n) (->num (bitwise-bit-count (bitwise-and (jnum->exact n) long-mask64))))) - (cons "numberOfLeadingZeros" (lambda (n) (->num (long-nlz n)))) - (cons "reverse" (lambda (n) (->num (long-reverse n)))) - (cons "parseLong" (lambda (s . r) (parse-int-or-throw s (if (null? r) 10 (jnum->exact (car r))) "parseLong"))) - (cons "valueOf" (lambda (s . r) (parse-int-or-throw s (if (null? r) 10 (jnum->exact (car r))) "valueOf"))))) - -;; JVM Integer.toHexString/etc. treat the int as 32-bit unsigned. -(define (int->u32 n) (if (< n 0) (+ n 4294967296) n)) -(register-class-statics! "Integer" - (list (cons "MAX_VALUE" (->num 2147483647)) (cons "MIN_VALUE" (->num -2147483648)) - ;; the primitive class token (int.class); jolt models a class as its name - (cons "TYPE" "int") - (cons "valueOf" (lambda (x . r) - (if (number? x) (->num x) - (parse-int-or-throw x (if (null? r) 10 (jnum->exact (car r))) "valueOf")))) - (cons "parseInt" (lambda (x . r) (parse-int-or-throw x (if (null? r) 10 (jnum->exact (car r))) "parseInt"))) - ;; lowercase, like the JVM; a negative int is the 32-bit unsigned form. - (cons "toHexString" (lambda (x) (string-downcase (number->string (int->u32 (jnum->exact x)) 16)))) - (cons "toOctalString" (lambda (x) (number->string (int->u32 (jnum->exact x)) 8))) - (cons "toBinaryString" (lambda (x) (number->string (int->u32 (jnum->exact x)) 2))) - (cons "toString" (lambda (x . r) (number->string (jnum->exact x) (if (null? r) 10 (jnum->exact (car r)))))))) - -;; Byte / Short bounds (their values are plain integers on jolt; the statics let -;; libraries reference the JVM ranges — clojure.test.check generates over them). -(register-class-statics! "Byte" - (list (cons "TYPE" "byte") - (cons "MAX_VALUE" (->num 127)) (cons "MIN_VALUE" (->num -128)) - (cons "valueOf" (lambda (x . r) (->num (if (number? x) x (parse-int-or-throw x 10 "valueOf"))))) - (cons "parseByte" (lambda (x . r) (parse-int-or-throw x (if (null? r) 10 (jnum->exact (car r))) "parseByte"))) - (cons "toString" (lambda (x . r) (number->string (jnum->exact x)))))) -(register-class-statics! "Short" - (list (cons "TYPE" "short") - (cons "MAX_VALUE" (->num 32767)) (cons "MIN_VALUE" (->num -32768)) - (cons "valueOf" (lambda (x . r) (->num (if (number? x) x (parse-int-or-throw x 10 "valueOf"))))) - (cons "parseShort" (lambda (x . r) (parse-int-or-throw x (if (null? r) 10 (jnum->exact (car r))) "parseShort"))) - (cons "toString" (lambda (x . r) (number->string (jnum->exact x)))))) - -;; java.util.Locale — jolt's case ops are codepoint-based (locale-independent), so -;; the default locale is a no-op token. Libraries set/restore it around formatting -;; to prove output is locale-stable (honeysql's Turkish-İ regression guard). -(register-class-statics! "Locale" - (list (cons "getDefault" (lambda () "und")) - (cons "setDefault" (lambda (x) jolt-nil)) - (cons "forLanguageTag" (lambda (tag) (if (string? tag) tag (jolt-str-render-one tag)))) - (cons "ROOT" "und") (cons "US" "en-US") (cons "ENGLISH" "en"))) - -(register-class-statics! "Boolean" - (list (cons "TYPE" "boolean") - (cons "parseBoolean" (lambda (s) (string=? "true" (ascii-string-down (if (string? s) s (jolt-str-render-one s)))))) - (cons "TRUE" #t) (cons "FALSE" #f))) - -(register-class-ctor! "Double" ->double) -(register-class-ctor! "Float" ->double) -(register-class-statics! "Double" - (list (cons "TYPE" "double") - (cons "parseDouble" parse-double-or-throw) - (cons "valueOf" ->double) - (cons "toString" (lambda (x) (jolt-str-render-one (->double x)))) - (cons "isNaN" (lambda (x) (and (flonum? x) (nan? x)))) - (cons "isInfinite" (lambda (x) (and (flonum? x) (infinite? x)))) - (cons "MAX_VALUE" 1.7976931348623157e308) (cons "MIN_VALUE" 4.9e-324) - (cons "POSITIVE_INFINITY" +inf.0) (cons "NEGATIVE_INFINITY" -inf.0) (cons "NaN" +nan.0))) -(register-class-statics! "Float" - (list (cons "TYPE" "float") - (cons "parseFloat" parse-double-or-throw) (cons "valueOf" ->double))) - -;; Character: ASCII predicates (the engine is byte/ASCII oriented). -(register-class-statics! "Character" - (list (cons "TYPE" "char") - (cons "isUpperCase" (lambda (c) (let ((n (char-code c))) (and (>= n 65) (<= n 90))))) - (cons "isLowerCase" (lambda (c) (let ((n (char-code c))) (and (>= n 97) (<= n 122))))) - (cons "isDigit" (lambda (c) (let ((n (char-code c))) (and (>= n 48) (<= n 57))))) - ;; JVM Character.isWhitespace: Unicode whitespace (so U+2028 line separator - ;; counts, like the JVM) MINUS the no-break spaces the JVM excludes - ;; (U+00A0/U+2007/U+202F). char<=?space missed everything above ASCII. - (cons "isWhitespace" (lambda (c) (let ((cp (char-code c))) - (and (char-whitespace? (integer->char cp)) - (not (fx=? cp #xA0)) (not (fx=? cp #x2007)) (not (fx=? cp #x202F)))))))) - -;; String/valueOf(Object): "null" for nil, else jolt's str semantics. -;; String/format(fmt args…) / (locale fmt args…) -> the clojure.core format engine. -(register-class-statics! "String" - (list (cons "valueOf" (lambda (x . _) (if (jolt-nil? x) "null" (jolt-str-render-one x)))) - (cons "format" (lambda (a . rest) - (if (and (jhost? a) (string=? (jhost-tag a) "locale")) - (apply jolt-format (car rest) (cdr rest)) - (apply jolt-format a rest)))))) - -;; ---- java.text.NumberFormat ------------------------------------------------- -;; A grouping decimal formatter (selmer number-format / cuerdas). state: -;; #(grouping? min-frac max-frac). .format groups the integer part with commas. -(define (nf-make grouping? minf maxf) (make-jhost "numberformat" (vector grouping? minf maxf))) -(define (group-int-str s) ; "1234567" -> "1,234,567" - (let* ((neg (and (> (string-length s) 0) (char=? (string-ref s 0) #\-))) - (digs (if neg (substring s 1 (string-length s)) s)) - (n (string-length digs)) (out '())) - (let loop ((i 0)) - (when (< i n) - (when (and (> i 0) (= 0 (modulo (- n i) 3))) (set! out (cons #\, out))) - (set! out (cons (string-ref digs i) out)) (loop (+ i 1)))) - (string-append (if neg "-" "") (list->string (reverse out))))) -(define (nf-format self x) - (let* ((grouping? (vector-ref (jhost-state self) 0)) - (minf (vector-ref (jhost-state self) 1)) (maxf (vector-ref (jhost-state self) 2)) - (neg (< x 0)) (ax (abs (exact->inexact x))) - (scale (expt 10 maxf)) - (scaled (exact (round (* ax scale)))) - (ipart (quotient scaled scale)) (fpart (remainder scaled scale)) - (istr (number->string ipart)) - (fstr0 (if (> maxf 0) (let ((s (number->string fpart))) - (string-append (make-string (max 0 (- maxf (string-length s))) #\0) s)) "")) - ;; trim trailing zeros down to minf - (fstr (let loop ((s fstr0)) (if (and (> (string-length s) minf) - (char=? (string-ref s (- (string-length s) 1)) #\0)) - (loop (substring s 0 (- (string-length s) 1))) s)))) - (string-append (if neg "-" "") (if grouping? (group-int-str istr) istr) - (if (> (string-length fstr) 0) (string-append "." fstr) "")))) -(register-host-methods! "numberformat" - (list (cons "format" (lambda (self n) (nf-format self n))) - (cons "setMaximumFractionDigits" (lambda (self d) (vector-set! (jhost-state self) 2 (jnum->exact d)) jolt-nil)) - (cons "setMinimumFractionDigits" (lambda (self d) (vector-set! (jhost-state self) 1 (jnum->exact d)) jolt-nil)) - (cons "setGroupingUsed" (lambda (self b) (vector-set! (jhost-state self) 0 (jolt-truthy? b)) jolt-nil)))) -(let ((nf-statics (list (cons "getInstance" (lambda _ (nf-make #t 0 3))) - (cons "getNumberInstance" (lambda _ (nf-make #t 0 3))) - (cons "getIntegerInstance" (lambda _ (nf-make #t 0 0)))))) - (register-class-statics! "NumberFormat" nf-statics) - (register-class-statics! "java.text.NumberFormat" nf-statics)) - -;; Class.forName: an array descriptor ("[C") is its own class token; a class Jolt -;; can back (registered statics/ctor, or a java.*/clojure.* core class) yields a -;; class object; anything else throws a catchable ClassNotFoundException, like the -;; JVM — so the common `(try (Class/forName "optional.Dep") (catch …))` probe a -;; library uses to detect an absent dependency works (e.g. ring's joda-time check). -;; java.* / clojure.* packages jolt does NOT back, even though the broad prefix -;; below would otherwise claim them — optional backends a library feature-probes -;; with (Class/forName …) (e.g. tools.logging's java.util.logging / log4j). Listing -;; them here keeps class-found? honest so the probe sees them absent and skips the -;; backend (jolt has its own logging) instead of trying to use it and crashing. -(define forname-absent-prefixes - '("java.util.logging." "javax.management." "java.lang.management.")) -(define (forname-known? nm) - ;; exact lookups only — lookup-class would fall back to the short class name, so - ;; any "x.y.Class" would spuriously match the registered java.lang.Class. - (or (hashtable-ref class-statics-tbl nm #f) - (hashtable-ref class-ctors-tbl nm #f) - (let ((pre? (lambda (p) (and (>= (string-length nm) (string-length p)) - (string=? (substring nm 0 (string-length p)) p))))) - (and (or (pre? "java.") (pre? "clojure.") (pre? "jolt.")) - (not (exists pre? forname-absent-prefixes)))))) -(register-class-statics! "Class" - (list (cons "forName" - (lambda (nm . _) - (cond - ((and (> (string-length nm) 0) (char=? (string-ref nm 0) #\[)) nm) - ((forname-known? nm) (make-class-obj nm)) - (else (jolt-throw (jolt-host-throwable "java.lang.ClassNotFoundException" nm)))))))) - -;; ---- System helpers (defined before use above via top-level order) ---------- -;; os.name reflects the actual platform (Chez's machine-type names it): a *osx -;; machine is macOS, otherwise Linux. Code that branches on the OS (socket struct -;; layout, path handling) needs the truth, not a fixed value. -(define (substring-index needle hay) - (let ((nl (string-length needle)) (hl (string-length hay))) - (let loop ((i 0)) (cond ((> (+ i nl) hl) #f) - ((string=? (substring hay i (+ i nl)) needle) i) - (else (loop (+ i 1))))))) -(define sys-os-name - (let ((m (symbol->string (machine-type)))) - (cond ((or (substring-index "osx" m) (substring-index "macos" m)) "Mac OS X") - ((or (substring-index "nt" m) (substring-index "windows" m)) "Windows") - (else "Linux")))) -;; runtime-settable system properties (System/setProperty). A set value wins over -;; the built-in defaults below; clearProperty removes it. -(define sys-prop-table (make-hashtable string-hash string=?)) -(define (sys-set-property k v) - (let ((prev (hashtable-ref sys-prop-table k jolt-nil))) - (hashtable-set! sys-prop-table k (if (string? v) v (jolt-str-render-one v))) - prev)) -(define (sys-clear-property k) - (let ((prev (hashtable-ref sys-prop-table k jolt-nil))) - (hashtable-delete! sys-prop-table k) prev)) -(define (sys-get-property k . dflt) - (let ((set-val (hashtable-ref sys-prop-table k #f))) - (cond (set-val set-val) - ((string=? k "os.name") sys-os-name) - ((string=? k "line.separator") "\n") - ((string=? k "file.separator") "/") - ((string=? k "path.separator") ":") - ((string=? k "user.dir") (or (getenv "PWD") ".")) - ((string=? k "user.home") (or (getenv "HOME") "")) - ((string=? k "java.io.tmpdir") (or (getenv "TMPDIR") "/tmp")) - ((pair? dflt) (car dflt)) - (else jolt-nil)))) -(define (sys-properties-map) - (jolt-hash-map "os.name" sys-os-name "line.separator" "\n" "file.separator" "/" - "user.dir" (or (getenv "PWD") ".") "user.home" (or (getenv "HOME") "") - "java.io.tmpdir" (or (getenv "TMPDIR") "/tmp"))) - -;; full environment as an alist of (name . value), via spawning `env`. -(define (all-env-pairs) - (call-with-values - (lambda () (open-process-ports "env" (buffer-mode block) (native-transcoder))) - (lambda (stdin stdout stderr pid) - (let loop ((acc '())) - (let ((l (get-line stdout))) - (if (eof-object? l) (reverse acc) - (let ((eq (let scan ((i 0)) (cond ((= i (string-length l)) #f) - ((char=? (string-ref l i) #\=) i) - (else (scan (+ i 1))))))) - (loop (if eq (cons (cons (substring l 0 eq) (substring l (+ eq 1) (string-length l))) acc) acc))))))))) -;; JOLT_BAKE_ENV_ALLOWLIST: when set, only the listed comma-separated -;; names are served; unset (the normal case) reads are live and unfiltered. -(define (env-allowlist) - (let ((a (getenv "JOLT_BAKE_ENV_ALLOWLIST"))) - (and a (map str-trim (str-literal-split a ","))))) -(define (sys-getenv . k) - (let ((allow (env-allowlist))) - (if (null? k) - (apply jolt-hash-map - (let loop ((ps (all-env-pairs)) (acc '())) - (cond ((null? ps) (reverse acc)) - ((and allow (not (member (caar ps) allow))) (loop (cdr ps) acc)) - (else (loop (cdr ps) (cons (cdar ps) (cons (caar ps) acc))))))) - (let ((name (car k))) - (if (and allow (not (member name allow))) jolt-nil - (let ((v (getenv name))) (if v v jolt-nil))))))) - -;; ---- StringBuilder ---------------------------------------------------------- -;; state: a box (1-vector) holding the accumulated string. -(define (sb-str self) (vector-ref (jhost-state self) 0)) -(define (sb-set! self s) (vector-set! (jhost-state self) 0 s)) -(define (render-piece x) - (cond ((jolt-nil? x) "null") ((char? x) (string x)) ((string? x) x) - (else (jolt-str-render-one x)))) -;; (Object.) — a fresh value with distinct identity (libraries use it as a lock -;; or a unique sentinel). Each call returns a new jhost so identical?/= separate. -(register-class-ctor! "Object" (lambda _ (make-jhost "object" (vector)))) - diff --git a/host/chez/java/host-static.ss b/host/chez/java/host-static.ss deleted file mode 100644 index a579803..0000000 --- a/host/chez/java/host-static.ss +++ /dev/null @@ -1,217 +0,0 @@ -;; host-static.ss — the host-interop registry core: the class-statics / class-ctors -;; / tagged-methods tables, the jhost record, and the coercion helpers. The actual -;; entries are registered by host-static-methods.ss (Class/member statics) and -;; host-static-classes.ss (instantiable object classes), loaded after this. -;; -;; The analyzer lowers `Class/member` to a :host-static node and `(Class. ...)` / -;; `(new Class ...)` to a :host-new node (jolt-core/jolt/analyzer.clj); the Chez -;; emit lowers a value ref to (host-static-ref "Class" "member"), a -;; call head to (host-static-call "Class" "member" args...), and a constructor to -;; (host-new "Class" args...). This file is the runtime registry those three -;; resolve against — the class-statics / class-ctors / -;; tagged-methods registries, -;; restricted to the java.lang/util/net/io surface portable cljc code calls. -;; (java.time formatting is a separate increment.) -;; -;; Constructed host objects are `jhost` records (a tag + mutable state); their -;; (.method ...) calls reach record-method-dispatch (records.ss), extended below -;; with a jhost arm that dispatches through host-tagged-methods. -;; -;; Loaded from rt.ss LAST (after natives-str.ss / records.ss): it extends -;; record-method-dispatch and reuses jolt-str-render-one / jolt-re-pattern. - -;; ---- registries ------------------------------------------------------------- -(define class-statics-tbl (make-hashtable string-hash string=?)) ; "Class" -> (member-ht) -(define class-ctors-tbl (make-hashtable string-hash string=?)) ; "Class" -> ctor proc -(define host-methods-tbl (make-hashtable string-hash string=?)) ; tag -> (method-ht) - -;; A class token may arrive fully qualified (java.io.StringReader) or short -;; (StringReader). Register both; resolve by exact then by last dotted segment. -(define (short-class-name s) - (let loop ((i (- (string-length s) 1))) - (cond ((< i 0) s) - ((char=? (string-ref s i) #\.) (substring s (+ i 1) (string-length s))) - (else (loop (- i 1)))))) - -(define (register-class-statics! name members) ; members: list of (str . val/proc) - (let ((h (or (hashtable-ref class-statics-tbl name #f) - (let ((h (make-hashtable string-hash string=?))) - (hashtable-set! class-statics-tbl name h) h)))) - (for-each (lambda (p) (hashtable-set! h (car p) (cdr p))) members))) - -(define (register-class-ctor! name proc) (hashtable-set! class-ctors-tbl name proc)) - -(define (register-host-methods! tag members) - (let ((h (or (hashtable-ref host-methods-tbl tag #f) - (let ((h (make-hashtable string-hash string=?))) - (hashtable-set! host-methods-tbl tag h) h)))) - (for-each (lambda (p) (hashtable-set! h (car p) (cdr p))) members))) - -(define (lookup-class h-tbl name) - (or (hashtable-ref h-tbl name #f) - (hashtable-ref h-tbl (short-class-name name) #f))) - -;; ---- host object ------------------------------------------------------------ -(define-record-type jhost (fields tag (mutable state)) (nongenerative chez-jhost-v1)) - -;; record-method-dispatch (records.ss) gets a jhost arm: dispatch (.method obj a*) -;; through the tag's method table. -;; clojure.lang.Sorted on jolt's sorted-map / sorted-set: comparator / entryKey / -;; seqFrom / seq. data.priority-map's subseq/rsubseq reach for these (its -;; PersistentPriorityMap delegates .comparator to the backing sorted-map). The -;; comparator is returned as a small Comparator object whose .compare runs the -;; map's 3-way fn, since (.. sc comparator (compare a b)) is the calling form. -(define sorted-cmp-kw (keyword #f "cmp")) -(register-host-methods! "jolt-comparator" - (list (cons "compare" (lambda (self a b) (jolt-invoke (jhost-state self) a b))))) -(define (sorted-comparator-of sc) - (let ((c (jolt-ref-get sc sorted-cmp-kw))) - (make-jhost "jolt-comparator" (if (jolt-nil? c) jolt-compare c)))) -(define (sorted-iface-method? m) - (or (string=? m "comparator") (string=? m "entryKey") - (string=? m "seqFrom") (string=? m "seq"))) -(define (sorted-iface-dispatch obj method rest) - (cond - ((string=? method "comparator") (sorted-comparator-of obj)) - ((string=? method "entryKey") (jolt-first (car rest))) ; map entry -> its key - ((string=? method "seq") ; (.seq sc) or (.seq sc ascending?) - (if (or (null? rest) (jolt-truthy? (car rest))) (jolt-seq obj) (jolt-rseq obj))) - ;; (.seqFrom sc k ascending?) — the entries from k onward, in order. Done with a - ;; comparator filter over the seq (jolt has no tree cursor), like subseq. - ((string=? method "seqFrom") - (let* ((k (car rest)) (asc (jolt-truthy? (cadr rest))) - (cmp (jolt-ref-get obj sorted-cmp-kw)) - (cmpf (if (jolt-nil? cmp) jolt-compare cmp)) - (es (seq->list (jolt-seq obj))) - (keep (filter (lambda (e) - (let ((c (jnum->exact (jolt-invoke cmpf (jolt-first e) k)))) - (if asc (>= c 0) (<= c 0)))) - es))) - (list->cseq (if asc keep (reverse keep))))) - (else (error #f (string-append "No method " method " on sorted collection"))))) - -(register-method-arm! 44 - (lambda (obj method-name rest-args) - (cond - ((jhost? obj) - (let ((mh (hashtable-ref host-methods-tbl (jhost-tag obj) #f))) - (let ((f (and mh (hashtable-ref mh method-name #f)))) - (if f - (apply f obj (if (jolt-nil? rest-args) '() (seq->list rest-args))) - (error #f (string-append "No method " method-name " on host " (jhost-tag obj))))))) - ((number? obj) (apply number-method method-name obj (if (jolt-nil? rest-args) '() (seq->list rest-args)))) - (else 'pass)))) - -;; java.lang.Number method surface (the boxed-number methods cljc code calls). The -;; integer projections wrap modulo their width (ring-codec relies on byteValue -;; overflow: (.byteValue 255) => -1); the float projections are identity flonums. -(define (number-method method n . args) - (cond - ((string=? method "byteValue") (let ((b (modulo (jnum->exact n) 256))) (->num (if (>= b 128) (- b 256) b)))) - ((string=? method "shortValue") (let ((b (modulo (jnum->exact n) 65536))) (->num (if (>= b 32768) (- b 65536) b)))) - ((string=? method "intValue") (->num (jnum->exact n))) - ((string=? method "longValue") (->num (jnum->exact n))) - ((string=? method "doubleValue") (->num n)) - ((string=? method "floatValue") (->num n)) - ;; .toString(radix) — BigInteger/Integer render in a base, lowercase like the - ;; JVM (rewrite-clj's integer node reconstructs 0xff / 0377 / 2r1001 this way). - ((string=? method "toString") - (if (pair? args) - (string-downcase (number->string (jnum->exact n) (jnum->exact (car args)))) - (jolt-num->string n))) - ((string=? method "hashCode") (->num (jnum->exact n))) - ;; Double/Float .isNaN / .isInfinite (a non-flonum is neither). - ((string=? method "isNaN") (and (flonum? n) (not (= n n)))) - ((string=? method "isInfinite") (and (flonum? n) (infinite? n))) - ;; BigInteger interop: .negate / .bitLength / .signum / .abs. A jolt integer is - ;; a Chez exact integer, so these are native (integer-length = JVM bitLength, - ;; matching for negative values too). tools.reader's number parser uses them. - ((string=? method "negate") (->num (- (jnum->exact n)))) - ((string=? method "abs") (->num (abs (jnum->exact n)))) - ((string=? method "bitLength") (->num (integer-length (jnum->exact n)))) - ((string=? method "signum") (->num (let ((e (jnum->exact n))) (cond ((> e 0) 1) ((< e 0) -1) (else 0))))) - ;; BigInteger.shiftLeft/shiftRight (test.check's size-bounded-bigint): arbitrary - ;; precision, so an arithmetic shift by the (positive) amount. - ((string=? method "shiftLeft") (->num (bitwise-arithmetic-shift-left (jnum->exact n) (jnum->exact (car args))))) - ((string=? method "shiftRight") (->num (bitwise-arithmetic-shift-right (jnum->exact n) (jnum->exact (car args))))) - (else (error #f (string-append "No method " method " for number"))))) - -;; Mutable static fields: "Class" -> (member -> 1-vector cell). A library that -;; writes a static field — clojure.spec.alpha's (set! (. clojure.lang.RT -;; checkSpecAsserts) flag) — lands here; the analyzer lowers the set! to a -;; set-static-field! call and a plain Class/member read consults the cell first. -(define mutable-statics-tbl (make-hashtable string-hash string=?)) -(define (mutable-static-cell class member create?) - (let ((h (or (hashtable-ref mutable-statics-tbl class #f) - (and create? (let ((nh (make-hashtable string-hash string=?))) - (hashtable-set! mutable-statics-tbl class nh) nh))))) - (and h (or (hashtable-ref h member #f) - (and create? (let ((c (vector jolt-nil))) (hashtable-set! h member c) c)))))) -(def-var! "jolt.host" "set-static-field!" - (lambda (class member val) - (vector-set! (mutable-static-cell class member #t) 0 val) - val)) -;; clojure.lang.RT.checkSpecAsserts — a JVM-internal flag clojure.spec.alpha reads -;; and writes; default false. Pre-seed the cell so a read before any write works. -(vector-set! (mutable-static-cell "clojure.lang.RT" "checkSpecAsserts" #t) 0 #f) - -;; ---- emit entry points ------------------------------------------------------ -(define (host-static-ref class member) - (let ((cell (mutable-static-cell class member #f))) - (if cell - (vector-ref cell 0) - (let ((h (lookup-class class-statics-tbl class))) - (if h - (let ((v (hashtable-ref h member #f))) - (if v v (error #f (string-append "No static " class "/" member)))) - (error #f (string-append "Unknown class " class))))))) - -(define (host-static-call class member . args) - (apply (host-static-ref class member) args)) - -(define (host-new class . args) - (let ((ctor (lookup-class class-ctors-tbl class))) - (cond - (ctor (apply ctor args)) - ;; deftype/defrecord: the type name is bound as a VAR (the - ;; make-deftype-ctor closure) in its defining ns, not a registered host class. - ;; Resolve it in the current ns / clojure.core and invoke it — so (P. args) - ;; works the same as the ->P factory. - (else - (let ((cell (or (var-cell-lookup (chez-current-ns) class) - (var-cell-lookup "clojure.core" class)))) - (if (and cell (var-cell-defined? cell) (procedure? (var-cell-root cell))) - (apply (var-cell-root cell) args) - (error #f (string-append "No constructor for class " class)))))))) - -;; ---- coercion helpers ------------------------------------------------------- -;; numeric tower: currentTimeMillis/nanoTime are exact longs (JVM). -(define (->num x) x) -(define (jnum->exact n) (exact (truncate n))) -;; parse an integer string in radix; #f on failure -(define (parse-int-str s radix) - (let ((n (string->number (str-trim (if (string? s) s (jolt-str-render-one s))) radix))) - (and n (integer? n) (->num n)))) -(define (parse-int-or-throw s radix what) - (or (parse-int-str s radix) - (jolt-throw (jolt-host-throwable "java.lang.NumberFormatException" - (string-append "For input string: \"" - (if (string? s) s (jolt-str-render-one s)) "\""))))) -(define (char-code c) (if (char? c) (char->integer c) (jnum->exact c))) - -;; parse a double string (Double/parseDouble, (Double. s)); JVM accepts NaN / -;; Infinity / decimal / scientific. #f on failure. -(define (parse-double-str s) - (let ((t (str-trim (if (string? s) s (jolt-str-render-one s))))) - (cond - ((or (string=? t "NaN") (string=? t "+NaN") (string=? t "-NaN")) +nan.0) - ((or (string=? t "Infinity") (string=? t "+Infinity")) +inf.0) - ((string=? t "-Infinity") -inf.0) - (else (let ((n (string->number t))) (and n (real? n) (exact->inexact n))))))) -(define (parse-double-or-throw s) - (or (parse-double-str s) - (jolt-throw (jolt-host-throwable "java.lang.NumberFormatException" - (string-append "For input string: \"" - (if (string? s) s (jolt-str-render-one s)) "\""))))) -(define (->double x) (if (number? x) (exact->inexact x) (parse-double-or-throw x))) - diff --git a/host/chez/java/inst-time.ss b/host/chez/java/inst-time.ss deleted file mode 100644 index 4b2937f..0000000 --- a/host/chez/java/inst-time.ss +++ /dev/null @@ -1,596 +0,0 @@ -;; #inst values + a java.time formatting shim. -;; -;; A #inst literal lowers (analyzer :inst node -> emit) to (jolt-inst-from-string -;; "…"); this file parses the RFC3339 string to epoch-ms and models the value as a -;; `jinst` record (one flonum field, ms). Equality / map-key hashing are by the -;; INSTANT (offset-normalized). The overlay inst?/inst-ms read (get x :jolt/type)/(get x :ms), -;; so jolt-get answers those off a jinst — the overlay fns then work unchanged. -;; -;; The java.time surface (DateTimeFormatter/Instant/ZoneId/LocalDateTime/ -;; FormatStyle/Locale + the .format/.atZone/.toInstant/… methods) is -;; registered through host-static.ss's class-statics / host- -;; methods registries — so this loads LAST in rt.ss, after host-static.ss and io.ss. - -;; --- civil <-> days since the Unix epoch (Howard Hinnant's algorithms) ------- -;; No portable UTC mktime on Chez, so compute epoch days directly from y/m/d. -(define (days-from-civil y m d) - (let* ((y2 (if (<= m 2) (- y 1) y)) - (era (quotient (if (>= y2 0) y2 (- y2 399)) 400)) - (yoe (- y2 (* era 400))) - (doy (+ (quotient (+ (* 153 (+ m (if (> m 2) -3 9))) 2) 5) (- d 1))) - (doe (+ (* yoe 365) (quotient yoe 4) (- (quotient yoe 100)) doy))) - (+ (* era 146097) doe -719468))) - -(define (civil-from-days z) ; -> (values year month day) - (let* ((z2 (+ z 719468)) - (era (quotient (if (>= z2 0) z2 (- z2 146096)) 146097)) - (doe (- z2 (* era 146097))) - (yoe (quotient (+ doe (- (quotient doe 1460)) (quotient doe 36524) (- (quotient doe 146096))) 365)) - (y (+ yoe (* era 400))) - (doy (- doe (+ (* 365 yoe) (quotient yoe 4) (- (quotient yoe 100))))) - (mp (quotient (+ (* 5 doy) 2) 153)) - (d (+ (- doy (quotient (+ (* 153 mp) 2) 5)) 1)) - (m (+ mp (if (< mp 10) 3 -9)))) - (values (if (<= m 2) (+ y 1) y) m d))) - -;; --- RFC3339 parse: yyyy[-MM[-dd[Thh[:mm[:ss[.fff]]]]]][Z|±hh:mm] -> ms ------- -(define-record-type jinst (fields ms) (nongenerative chez-jinst-v1)) - -(define (digit? c) (and (char>=? c #\0) (char<=? c #\9))) -(define (digits-at s i n) ; n digits from i -> integer, or #f - (and (<= (+ i n) (string-length s)) - (let loop ((j i) (acc 0)) - (if (= j (+ i n)) - acc - (and (digit? (string-ref s j)) - (loop (+ j 1) (+ (* acc 10) (- (char->integer (string-ref s j)) 48)))))))) - -(define (jolt-inst-from-string ts0) - ;; a leading '-' marks a negative (proleptic) year; the rest of the field may be - ;; more than 4 digits (java.time prints -999999999-…). Read the year up to the - ;; first '-' that separates it from the month. - (define neg-year (and (> (string-length ts0) 0) (char=? (string-ref ts0 0) #\-))) - (define ts (if neg-year (substring ts0 1 (string-length ts0)) ts0)) - (define len (string-length ts)) - (define (fail) (error #f (string-append "Unrecognized #inst timestamp: " ts0))) - (define (read-year) - ;; >=4 digits up to a non-digit; java.time uses min-4 but allows more. - (let loop ((j 0) (acc 0) (n 0)) - (if (and (< j len) (digit? (string-ref ts j))) - (loop (+ j 1) (+ (* acc 10) (- (char->integer (string-ref ts j)) 48)) (+ n 1)) - (if (>= n 4) (cons acc j) #f)))) - (let* ((yr (or (read-year) (fail))) - (year (if neg-year (- (car yr)) (car yr))) - (i (cdr yr)) (month 1) (day 1) (hh 0) (mm 0) (ss 0) (frac-ms 0) (off-s 0)) - ;; -MM - (when (and (< i len) (char=? (string-ref ts i) #\-) (digits-at ts (+ i 1) 2)) - (set! month (digits-at ts (+ i 1) 2)) (set! i (+ i 3))) - ;; -dd - (when (and (< i len) (char=? (string-ref ts i) #\-) (digits-at ts (+ i 1) 2)) - (set! day (digits-at ts (+ i 1) 2)) (set! i (+ i 3))) - ;; Thh - (when (and (< i len) (or (char=? (string-ref ts i) #\T) (char=? (string-ref ts i) #\t)) - (digits-at ts (+ i 1) 2)) - (set! hh (digits-at ts (+ i 1) 2)) (set! i (+ i 3)) - ;; :mm - (when (and (< i len) (char=? (string-ref ts i) #\:) (digits-at ts (+ i 1) 2)) - (set! mm (digits-at ts (+ i 1) 2)) (set! i (+ i 3)) - ;; :ss - (when (and (< i len) (char=? (string-ref ts i) #\:) (digits-at ts (+ i 1) 2)) - (set! ss (digits-at ts (+ i 1) 2)) (set! i (+ i 3)) - ;; .fff (truncate beyond 3) - (when (and (< i len) (char=? (string-ref ts i) #\.)) - (let loop ((j (+ i 1)) (k 0) (acc 0)) - (if (and (< j len) (digit? (string-ref ts j))) - (loop (+ j 1) (+ k 1) (if (< k 3) (+ (* acc 10) (- (char->integer (string-ref ts j)) 48)) acc)) - (begin - (set! frac-ms (* acc (expt 10 (max 0 (- 3 k))))) - (set! i j)))))))) - ;; offset Z | ±hh:mm - (when (< i len) - (let ((c (string-ref ts i))) - (cond - ((or (char=? c #\Z) (char=? c #\z)) (set! i (+ i 1))) - ((or (char=? c #\+) (char=? c #\-)) - (let ((oh (digits-at ts (+ i 1) 2)) (om (digits-at ts (+ i 4) 2))) - (unless (and oh om (char=? (string-ref ts (+ i 3)) #\:)) (fail)) - (set! off-s (* (if (char=? c #\-) -1 1) (+ (* oh 3600) (* om 60)))) - (set! i (+ i 6)))) - (else (fail))))) - (unless (= i len) (fail)) - (let ((base-s (+ (* (days-from-civil year month day) 86400) (* hh 3600) (* mm 60) ss))) - (make-jinst (- (+ (* base-s 1000) frac-ms) (* off-s 1000)))))) - -;; --- canonical print form: yyyy-MM-ddThh:mm:ss.fff-00:00 (UTC) --------------- -(define (pad2 n) (if (< n 10) (string-append "0" (number->string n)) (number->string n))) -(define (pad4 n) (let ((s (number->string n))) (string-append (make-string (max 0 (- 4 (string-length s))) #\0) s))) -(define (pad3 n) (let ((s (number->string n))) (string-append (make-string (max 0 (- 3 (string-length s))) #\0) s))) -(define (inst-floor-div a b) (let ((q (quotient a b)) (r (remainder a b))) (if (and (not (= r 0)) (< (* a b) 0)) (- q 1) q))) -(define (inst-floor-mod a b) (- a (* (inst-floor-div a b) b))) - -(define (inst-fields ms) ; -> list (y mo d hh mm ss frac dow) - (let* ((total-s (inst-floor-div (exact (truncate ms)) 1000)) - (frac (- (exact (truncate ms)) (* total-s 1000))) - (days (inst-floor-div total-s 86400)) - (sod (inst-floor-mod total-s 86400)) - (hh (quotient sod 3600)) (mm (quotient (remainder sod 3600) 60)) (ss (remainder sod 60)) - (dow (inst-floor-mod (+ days 4) 7))) ; 1970-01-01 = Thursday; 0=Sunday - (call-with-values (lambda () (civil-from-days days)) - (lambda (y mo d) (list y mo d hh mm ss frac dow))))) - -(define (inst-rfc3339 inst) - (let ((f (inst-fields (jinst-ms inst)))) - (string-append (pad4 (list-ref f 0)) "-" (pad2 (list-ref f 1)) "-" (pad2 (list-ref f 2)) - "T" (pad2 (list-ref f 3)) ":" (pad2 (list-ref f 4)) ":" (pad2 (list-ref f 5)) - "." (pad3 (list-ref f 6)) "-00:00"))) - -;; --- DateTimeFormatter pattern engine ----- -(define month-names (vector "January" "February" "March" "April" "May" "June" "July" - "August" "September" "October" "November" "December")) -(define day-names (vector "Sunday" "Monday" "Tuesday" "Wednesday" "Thursday" "Friday" "Saturday")) - -(define (format-ms pattern ms) - (let ((f (inst-fields ms)) (n (string-length pattern)) (out (open-output-string))) - (let ((y (list-ref f 0)) (mo (list-ref f 1)) (d (list-ref f 2)) - (hh (list-ref f 3)) (mi (list-ref f 4)) (se (list-ref f 5)) (dow (list-ref f 7))) - (define (run-len i c) (let loop ((j i)) (if (and (< j n) (char=? (string-ref pattern j) c)) (loop (+ j 1)) (- j i)))) - (let loop ((i 0)) - (when (< i n) - (let* ((c (string-ref pattern i)) (k (run-len i c))) - (cond - ((char=? c #\') - (if (and (< (+ i 1) n) (char=? (string-ref pattern (+ i 1)) #\')) - (begin (write-char #\' out) (loop (+ i 2))) - (let close ((j (+ i 1))) - (cond ((>= j n) (loop j)) - ((char=? (string-ref pattern j) #\') (loop (+ j 1))) - (else (write-char (string-ref pattern j) out) (close (+ j 1))))))) - ((char=? c #\y) (display (if (>= k 4) (number->string y) (pad2 (modulo y 100))) out) (loop (+ i k))) - ((char=? c #\M) - (display (cond ((= k 1) (number->string mo)) ((= k 2) (pad2 mo)) - ((= k 3) (substring (vector-ref month-names (- mo 1)) 0 3)) - (else (vector-ref month-names (- mo 1)))) out) - (loop (+ i k))) - ((char=? c #\d) (display (if (= k 1) (number->string d) (pad2 d)) out) (loop (+ i k))) - ((char=? c #\E) - (display (if (>= k 4) (vector-ref day-names dow) (substring (vector-ref day-names dow) 0 3)) out) - (loop (+ i k))) - ((char=? c #\H) (display (if (= k 1) (number->string hh) (pad2 hh)) out) (loop (+ i k))) - ((char=? c #\h) - (let ((h12 (let ((h (modulo hh 12))) (if (= h 0) 12 h)))) - (display (if (= k 1) (number->string h12) (pad2 h12)) out)) (loop (+ i k))) - ((char=? c #\m) (display (if (= k 1) (number->string mi) (pad2 mi)) out) (loop (+ i k))) - ((char=? c #\s) (display (if (= k 1) (number->string se) (pad2 se)) out) (loop (+ i k))) - ((char=? c #\a) (display (if (< hh 12) "AM" "PM") out) (loop (+ i k))) - ;; timezone — format-ms renders UTC, the HTTP zone is GMT: z/zzz -> GMT, - ;; Z (RFC822) -> +0000, X (ISO) -> Z. - ((char=? c #\z) (display "GMT" out) (loop (+ i k))) - ((char=? c #\Z) (display "+0000" out) (loop (+ i k))) - ((char=? c #\X) (display "Z" out) (loop (+ i k))) - (else (write-char c out) (loop (+ i 1))))))) - (get-output-string out)))) - -;; --- SimpleDateFormat .parse: pattern-driven parse to epoch-ms (UTC/GMT) ------ -(define (month-from-name s) - (let ((m3 (ascii-string-down (substring s 0 (min 3 (string-length s)))))) - (let loop ((i 0)) - (cond ((= i 12) #f) - ((string=? (ascii-string-down (substring (vector-ref month-names i) 0 3)) m3) (+ i 1)) - (else (loop (+ i 1))))))) -(define (parse-ms pattern input) - (let ((pn (string-length pattern)) (inn (string-length input)) - (y 1970) (mo 1) (d 1) (hh 0) (mi 0) (ss 0) (frac-ms 0) (pm 'none)) - ;; a parse failure is a java.time.format.DateTimeParseException (typed, so a - ;; (catch DateTimeParseException …) over a bad date matches), like the JVM. - (define (pfail) - (jolt-throw (jolt-host-throwable "java.time.format.DateTimeParseException" - (string-append "unparseable date \"" input "\"") jolt-nil))) - (define (run-len i c) (let loop ((j i)) (if (and (< j pn) (char=? (string-ref pattern j) c)) (loop (+ j 1)) (- j i)))) - ;; read up to `maxw` digits (#f = unbounded). A fixed-width field (k>=2, e.g. - ;; HHmm) caps the read at its run length so adjacent numeric fields split. - (define (read-digits-w ii maxw) ; -> (val . next), pfail if none - (let loop ((j ii) (acc 0) (n 0) (any #f)) - (if (and (< j inn) (digit? (string-ref input j)) (or (not maxw) (< n maxw))) - (loop (+ j 1) (+ (* acc 10) (- (char->integer (string-ref input j)) 48)) (+ n 1) #t) - (if any (cons acc j) (pfail))))) - (define (read-digits ii) (read-digits-w ii #f)) - (define (read-alpha ii) ; -> (str . next) - (let loop ((j ii)) (if (and (< j inn) (char-alphabetic? (string-ref input j))) (loop (+ j 1)) - (cons (substring input ii j) j)))) - (define (read-tz ii) ; consume GMT/UTC/Z or ±hhmm; -> next - (cond ((>= ii inn) ii) - ((char-alphabetic? (string-ref input ii)) (cdr (read-alpha ii))) - ((or (char=? (string-ref input ii) #\+) (char=? (string-ref input ii) #\-)) - (let loop ((j (+ ii 1))) (if (and (< j inn) (or (digit? (string-ref input j)) (char=? (string-ref input j) #\:))) (loop (+ j 1)) j))) - (else ii))) - (let loop ((pi 0) (ii 0)) - (if (>= pi pn) - (begin - (when (eq? pm 'pm) (when (< hh 12) (set! hh (+ hh 12)))) - (when (eq? pm 'am) (when (= hh 12) (set! hh 0))) - (make-jinst (+ (* 1000 (+ (* (days-from-civil y mo d) 86400) (* hh 3600) (* mi 60) ss)) frac-ms))) - (let ((c (string-ref pattern pi))) - (cond - ((char-alphabetic? c) - (let ((k (run-len pi c))) - (cond - ((char=? c #\y) (let ((r (read-digits-w ii (if (>= k 3) #f k)))) - ;; 2-digit year (value < 100): JVM sliding window — 00-68 -> 20xx, - ;; 69-99 -> 19xx (rfc1036 HTTP dates). A full year stays as-is. - (set! y (let ((v (car r))) (if (and (= k 2) (< v 100)) (if (< v 69) (+ 2000 v) (+ 1900 v)) v))) - (loop (+ pi k) (cdr r)))) - ((char=? c #\M) (if (>= k 3) - (let ((r (read-alpha ii))) (set! mo (or (month-from-name (car r)) (pfail))) (loop (+ pi k) (cdr r))) - (let ((r (read-digits-w ii (if (>= k 2) k #f)))) (set! mo (car r)) (loop (+ pi k) (cdr r))))) - ((char=? c #\d) (let ((r (read-digits-w ii (if (>= k 2) k #f)))) (set! d (car r)) (loop (+ pi k) (cdr r)))) - ((or (char=? c #\H) (char=? c #\h)) (let ((r (read-digits-w ii (if (>= k 2) k #f)))) (set! hh (car r)) (loop (+ pi k) (cdr r)))) - ((char=? c #\m) (let ((r (read-digits-w ii (if (>= k 2) k #f)))) (set! mi (car r)) (loop (+ pi k) (cdr r)))) - ((char=? c #\s) (let ((r (read-digits-w ii (if (>= k 2) k #f)))) - (set! ss (car r)) - ;; an ISO formatter (modeled here as an ss-pattern with no S - ;; field) still accepts an optional fractional second; consume - ;; .fff -> millis from the input. Skip when the pattern carries - ;; the fraction itself (a following '.'/S handles it). - (let ((j (cdr r)) (pnext (if (< (+ pi k) pn) (string-ref pattern (+ pi k)) #\nul))) - (if (and (not (char=? pnext #\.)) (not (char=? pnext #\S)) - (< j inn) (char=? (string-ref input j) #\.) - (< (+ j 1) inn) (digit? (string-ref input (+ j 1)))) - (let frac ((p (+ j 1)) (kk 0) (acc 0)) - (if (and (< p inn) (digit? (string-ref input p))) - (frac (+ p 1) (+ kk 1) (if (< kk 3) (+ (* acc 10) (- (char->integer (string-ref input p)) 48)) acc)) - (begin (set! frac-ms (* acc (expt 10 (max 0 (- 3 kk))))) (loop (+ pi k) p)))) - (loop (+ pi k) j))))) - ((char=? c #\S) (let frac ((p ii) (kk 0) (acc 0)) - (if (and (< p inn) (< kk k) (digit? (string-ref input p))) - (frac (+ p 1) (+ kk 1) (+ (* acc 10) (- (char->integer (string-ref input p)) 48))) - (begin (set! frac-ms (* acc (expt 10 (max 0 (- 3 kk))))) (loop (+ pi k) p))))) - ((char=? c #\E) (loop (+ pi k) (cdr (read-alpha ii)))) - ((char=? c #\a) (let ((r (read-alpha ii))) - (set! pm (if (string=? (ascii-string-down (car r)) "pm") 'pm 'am)) - (loop (+ pi k) (cdr r)))) - ((or (char=? c #\z) (char=? c #\Z) (char=? c #\X) (char=? c #\x) (char=? c #\V) (char=? c #\v)) (loop (+ pi k) (read-tz ii))) - (else (loop (+ pi k) ii))))) - ((char=? c #\') - (if (and (< (+ pi 1) pn) (char=? (string-ref pattern (+ pi 1)) #\')) - (loop (+ pi 2) (if (and (< ii inn) (char=? (string-ref input ii) #\')) (+ ii 1) ii)) - (let lit ((pj (+ pi 1)) (ij ii)) - (cond ((>= pj pn) (loop pj ij)) - ((char=? (string-ref pattern pj) #\') (loop (+ pj 1) ij)) - ((and (< ij inn) (char=? (string-ref input ij) (string-ref pattern pj))) (lit (+ pj 1) (+ ij 1))) - (else (pfail)))))) - ;; literal: match it; a pattern space tolerates missing/extra spaces. - ((char=? c #\space) - (let skip ((ij ii)) (if (and (< ij inn) (char=? (string-ref input ij) #\space)) (skip (+ ij 1)) (loop (+ pi 1) ij)))) - ((and (< ii inn) (char=? (string-ref input ii) c)) (loop (+ pi 1) (+ ii 1))) - (else (pfail)))))))) - -;; --- value integration: get / = / hash / pr / type / instance? -------------- -(define kw-jolt-type (keyword "jolt" "type")) -(define kw-ms (keyword #f "ms")) -(define inst-type-kw (keyword "jolt" "inst")) - -(register-get-arm! jinst? - (lambda (coll k d) - (cond ((jolt=2 k kw-jolt-type) inst-type-kw) - ((jolt=2 k kw-ms) (jinst-ms coll)) - (else d)))) - -(register-eq-arm! (lambda (a b) (or (jinst? a) (jinst? b))) - (lambda (a b) (and (jinst? a) (jinst? b) (= (jinst-ms a) (jinst-ms b))))) - -(register-hash-arm! jinst? (lambda (x) (jolt-hash (jinst-ms x)))) - -;; #inst is a java.util.Date — (class x) / (type x) report that, not the internal -;; :jolt/inst tag (which print-method still dispatches on via __type-tag). -(register-class-arm! jinst? (lambda (x) "java.util.Date")) - -;; java.time.Instant is nano-precise: two Instants are = when their epoch-nanos -;; match (so an Instant and one shifted by a single nanosecond differ). -(define (jt-instant-tag? x) (and (jhost? x) (string=? (jhost-tag x) "instant"))) -(register-eq-arm! (lambda (a b) (or (jt-instant-tag? a) (jt-instant-tag? b))) - (lambda (a b) (and (jt-instant-tag? a) (jt-instant-tag? b) - (= (inst-nanos a) (inst-nanos b))))) -(register-hash-arm! jt-instant-tag? (lambda (x) (jolt-hash (inst-nanos x)))) - -;; ZonedDateTime / java.sql.Date shim values (mk-zoned/mk-sql-date jhosts) are -;; equal when same kind + same epoch-ms. -(define (time-jhost? x) (and (jhost? x) (member (jhost-tag x) '("zoned-dt" "sql-date")) #t)) -(register-eq-arm! (lambda (a b) (or (time-jhost? a) (time-jhost? b))) - (lambda (a b) (and (time-jhost? a) (time-jhost? b) - (string=? (jhost-tag a) (jhost-tag b)) - (= (ms-of a) (ms-of b))))) -(register-hash-arm! time-jhost? (lambda (x) (jolt-hash (ms-of x)))) - -(define (inst-pr i) (string-append "#inst \"" (inst-rfc3339 i) "\"")) -(register-pr-arm! jinst? inst-pr) -(register-str-render! jinst? inst-rfc3339) - -(define %it-type jolt-type) -(set! jolt-type (lambda (x) (if (jinst? x) inst-type-kw (%it-type x)))) - -;; instance? java.util.Date -> a jinst; java.time.Instant/LocalDateTime -> the -;; matching jhost tag. The instance? macro passes the class-name symbol. -(define (class-short tn) (let loop ((i (- (string-length tn) 1))) - (cond ((< i 0) tn) ((char=? (string-ref tn i) #\.) (substring tn (+ i 1) (string-length tn))) (else (loop (- i 1)))))) -(register-instance-check-arm! - (lambda (type-sym val) - (let ((tn (class-short (symbol-t-name type-sym)))) - (cond - ;; a #inst / (Date.) is a java.util.Date; it is NOT a java.sql.Timestamp - ;; (on the JVM a Date is not a Timestamp), so answer Timestamp explicitly #f. - ((jinst? val) (cond ((string=? tn "Date") #t) - ((string=? tn "Timestamp") #f) - (else 'pass))) - ((and (jhost? val) (string=? (jhost-tag val) "instant")) (if (string=? tn "Instant") #t 'pass)) - ;; java.sql.Date is a java.util.Date subclass (but not a Timestamp). - ((and (jhost? val) (string=? (jhost-tag val) "sql-date")) - (cond ((or (string=? tn "Date")) #t) ((string=? tn "Timestamp") #f) (else 'pass))) - (else 'pass))))) - -;; inst-ms* is a seed native (the overlay inst-ms reads (get x :ms), now answered). -(def-var! "clojure.core" "inst-ms*" (lambda (i) (jinst-ms i))) - -;; --- java.time shim values (jhost objects over host-static.ss registries) ----- -;; "local-date" stores an epoch-day (java-time.ss owns the type); ms-of projects it -;; to UTC midnight so existing date math keeps working. "local-dt" stores epoch-day + -;; nano-of-day; the others store epoch-ms. -(define (ms-of d) - (cond ((number? d) d) - ((jinst? d) (jinst-ms d)) - ((and (jhost? d) (string=? (jhost-tag d) "local-date")) - (* (vector-ref (jhost-state d) 0) 86400000)) - ((and (jhost? d) (string=? (jhost-tag d) "local-date-time")) - (+ (* (vector-ref (jhost-state d) 0) 86400000) - (quotient (vector-ref (jhost-state d) 1) 1000000))) - ;; "instant" stores epoch-nanos; project to ms (floor) for ms-based callers. - ((and (jhost? d) (string=? (jhost-tag d) "instant")) - (inst-floor-div (vector-ref (jhost-state d) 0) 1000000)) - ((and (jhost? d) (member (jhost-tag d) '("zoned-dt" "calendar" "sql-date"))) - (vector-ref (jhost-state d) 0)) - (else (error #f "not a date value" d)))) -;; A java.time.Instant stores epoch-nanos (exact integer). mk-instant takes ms, -;; for the many ms-based call sites; mk-instant-nanos is the nano-precise ctor and -;; inst-nanos the nano accessor (java-time.ss owns the nano-aware arithmetic). -(define (mk-instant-nanos n) (make-jhost "instant" (vector (exact (truncate n))))) -(define (inst-nanos x) (vector-ref (jhost-state x) 0)) -(define (mk-instant ms) (mk-instant-nanos (* (ms->exact ms) 1000000))) -(define (mk-zoned ms) (make-jhost "zoned-dt" (vector ms))) -;; LocalDateTime from epoch-ms (UTC): the java-time.ss "local-date-time" jhost, -;; state [epoch-day nano-of-day]. -(define (mk-local ms) - (let* ((ems (exact (truncate ms))) - (ed (inst-floor-div ems 86400000)) - (mod (inst-floor-mod ems 86400000))) - (make-jhost "local-date-time" (vector ed (* mod 1000000))))) -;; local-date from epoch-ms: the epoch-day of the UTC day containing ms. -(define (mk-local-date ms) (make-jhost "local-date" (vector (inst-floor-div (exact (truncate ms)) 86400000)))) -;; start of the UTC day containing ms. -(define (start-of-utc-day ms) - (* (inst-floor-div (exact (truncate ms)) 86400000) 86400000)) -;; a formatter carries its pattern and a locale id (default "en"); the locale -;; selects month/day names in the java-time.ss format engine. -(define (mk-formatter pat . loc) (make-jhost "dt-formatter" (vector pat (if (null? loc) "en" (car loc))))) -(define (fmt-pat f) (vector-ref (jhost-state f) 0)) -(define (fmt-locale f) (let ((s (jhost-state f))) (if (> (vector-length s) 1) (vector-ref s 1) "en"))) -(define (locale-id l) (if (and (jhost? l) (string=? (jhost-tag l) "locale")) (vector-ref (jhost-state l) 0) "en")) -(define (now-ms) (now-millis)) ; exact ms (= JVM long); now-millis from host-static.ss -;; coerce a user-supplied ms (exact or flonum) to an exact integer for storage. -(define (ms->exact ms) (exact (round ms))) - -(register-host-methods! "instant" - (list (cons "atZone" (lambda (self zone) (mk-zoned (ms-of self)))) - (cons "toEpochMilli" (lambda (self) (ms-of self))) - (cons "toString" (lambda (self) (inst-rfc3339 (make-jinst (ms-of self))))))) -(register-host-methods! "zoned-dt" - (list (cons "toLocalDateTime" (lambda (self) (mk-local (ms-of self)))) - (cons "toInstant" (lambda (self) (mk-instant (ms-of self)))))) -;; LocalDate.atZone(zone): the UTC layer treats it as a zoned value at midnight. -;; (java-time.ss registers atStartOfDay and the rest of the local-date surface.) -(register-host-methods! "local-date" - (list (cons "atZone" (lambda (self zone) (mk-zoned (ms-of self)))))) -(register-host-methods! "dt-formatter" - (list (cons "withLocale" (lambda (self locale) (mk-formatter (fmt-pat self) (locale-id locale)))) - (cons "withZone" (lambda (self zone) (mk-formatter (fmt-pat self) (fmt-locale self)))) - (cons "format" (lambda (self d) (format-ms (fmt-pat self) (ms-of d)))) - ;; parse a string per the pattern -> an instant value; Instant/from / the - ;; LocalDateTime/parse static read its ms back out. - (cons "parse" (lambda (self s) (mk-instant (jinst-ms (parse-ms (fmt-pat self) (jolt-str-render-one s)))))))) - -;; FormatStyle approximations (no locale DB on this host). -(define style-patterns - '((date . ((short . "M/d/yy") (medium . "MMM d, yyyy") (long . "MMMM d, yyyy") (full . "EEEE, MMMM d, yyyy"))) - (time . ((short . "h:mm a") (medium . "h:mm:ss a") (long . "h:mm:ss a") (full . "h:mm:ss a"))) - (datetime . ((short . "M/d/yy, h:mm a") (medium . "MMM d, yyyy, h:mm:ss a") - (long . "MMMM d, yyyy, h:mm:ss a") (full . "EEEE, MMMM d, yyyy, h:mm:ss a"))))) -(define (style-of fs) (vector-ref (jhost-state fs) 0)) ; a symbol: short/medium/long/full -(define (style-fmt kind fs) - (mk-formatter (or (let ((row (assq kind style-patterns))) (and row (let ((e (assq (style-of fs) (cdr row)))) (and e (cdr e))))) - "yyyy-MM-dd HH:mm:ss"))) - -(register-class-statics! "FormatStyle" - (list (cons "SHORT" (make-jhost "format-style" (vector 'short))) - (cons "MEDIUM" (make-jhost "format-style" (vector 'medium))) - (cons "LONG" (make-jhost "format-style" (vector 'long))) - (cons "FULL" (make-jhost "format-style" (vector 'full))))) -(register-class-statics! "DateTimeFormatter" - (list (cons "ofPattern" (lambda (p . _) (mk-formatter p))) - (cons "ISO_LOCAL_DATE" (mk-formatter "yyyy-MM-dd")) - (cons "ISO_LOCAL_DATE_TIME" (mk-formatter "yyyy-MM-dd'T'HH:mm:ss")) - ;; ISO_INSTANT always renders in UTC with a trailing Z (format-ms is UTC; X -> "Z"). - (cons "ISO_INSTANT" (mk-formatter "yyyy-MM-dd'T'HH:mm:ssX")) - ;; ISO_ZONED_DATE_TIME: the UTC layer renders/parses it like ISO_INSTANT. - (cons "ISO_ZONED_DATE_TIME" (mk-formatter "yyyy-MM-dd'T'HH:mm:ssX")) - (cons "ofLocalizedDate" (lambda (fs) (style-fmt 'date fs))) - (cons "ofLocalizedTime" (lambda (fs) (style-fmt 'time fs))) - (cons "ofLocalizedDateTime" (lambda (fs) (style-fmt 'datetime fs))))) -(register-class-statics! "Instant" - (list (cons "ofEpochMilli" (lambda (ms) (mk-instant (ms->exact ms)))) - (cons "now" (lambda () (mk-instant (now-ms)))) - ;; Instant/parse an ISO-8601 instant ("…T…Z") -> an instant value. - (cons "parse" (lambda (s) (mk-instant (jinst-ms (jolt-inst-from-string - (if (string? s) s (jolt-str-render-one s))))))) - ;; Instant/from a temporal accessor -> an instant at the same epoch-ms. - (cons "from" (lambda (t) (mk-instant (ms-of t)))))) -(register-class-statics! "ZoneId" - (list (cons "systemDefault" (lambda () (make-jhost "zone-id" (vector "system")))) - (cons "of" (lambda (id) (make-jhost "zone-id" (vector id)))))) -(register-class-statics! "LocalDateTime" - (list (cons "ofInstant" (lambda (inst zone) (mk-local (ms-of inst)))) - (cons "now" (lambda () (mk-local (now-ms)))) - ;; LocalDateTime/parse text, or text + a formatter (the UTC layer ignores - ;; the parsed offset) -> a local-dt at the parsed instant. - (cons "parse" (lambda (s . fmt) - (let ((str (if (string? s) s (jolt-str-render-one s)))) - (mk-local (jinst-ms (if (null? fmt) - (jolt-inst-from-string str) - (parse-ms (fmt-pat (car fmt)) str))))))))) -(let ((locale-ctor (lambda (id . _) (make-jhost "locale" (vector (if (string? id) id (jolt-str-render-one id))))))) - (register-class-ctor! "Locale" locale-ctor) - (register-class-ctor! "java.util.Locale" locale-ctor)) -(register-class-statics! "Locale" - (list (cons "getDefault" (lambda () (make-jhost "locale" (vector "default")))) - (cons "ENGLISH" (make-jhost "locale" (vector "en"))) - (cons "US" (make-jhost "locale" (vector "en-US"))) - (cons "FRENCH" (make-jhost "locale" (vector "fr"))) - (cons "FRANCE" (make-jhost "locale" (vector "fr-FR"))) - (cons "GERMAN" (make-jhost "locale" (vector "de"))) - (cons "ROOT" (make-jhost "locale" (vector "root"))))) - -;; java.util.Date / java.sql.Timestamp: #inst's classes. (Date.) = now, (Date. ms) -;; or (Date. another-date) -> a jinst (ms-of accepts a number / jinst / instant), so -;; .getTime / inst? / instance? Date|Timestamp work. -(define (date-ctor . args) - (cond - ((null? args) (make-jinst (now-ms))) - ((null? (cdr args)) (make-jinst (ms->exact (ms-of (car args))))) - ;; deprecated (Date. year-1900 month0 date [hrs min sec]) — civil fields in UTC. - (else - (let* ((y (+ 1900 (jnum->exact (list-ref args 0)))) - (mo (+ 1 (jnum->exact (list-ref args 1)))) - (d (jnum->exact (list-ref args 2))) - (hh (if (> (length args) 3) (jnum->exact (list-ref args 3)) 0)) - (mm (if (> (length args) 4) (jnum->exact (list-ref args 4)) 0)) - (ss (if (> (length args) 5) (jnum->exact (list-ref args 5)) 0))) - (make-jinst (* 1000 (+ (* (days-from-civil y mo d) 86400) (* hh 3600) (* mm 60) ss))))))) -(register-class-ctor! "Date" date-ctor) -(register-class-ctor! "java.util.Date" date-ctor) -(register-class-ctor! "Timestamp" date-ctor) -(register-class-ctor! "java.sql.Timestamp" date-ctor) -;; Date/from(Instant) -> a java.util.Date at the instant's epoch-ms. -(let ((date-statics (list (cons "from" (lambda (inst) (make-jinst (ms->exact (ms-of inst)))))))) - (register-class-statics! "Date" date-statics) - (register-class-statics! "java.util.Date" date-statics)) -;; java.sql.Date: a distinct class from java.util.Date (a "sql-date" jhost over -;; epoch-ms) so a protocol extended to both routes a sql.Date to its own impl. -;; (Date. year-1900 month0 day) builds UTC midnight of that civil date; valueOf -;; parses "yyyy-MM-dd" to the same instant (so the two agree). -(define (mk-sql-date ms) (make-jhost "sql-date" (vector (ms->exact ms)))) -(define (sql-date-midnight y mo d) (mk-sql-date (* 1000 (* (days-from-civil y mo d) 86400)))) -(register-class-ctor! "java.sql.Date" - (case-lambda - ((ms) (mk-sql-date (ms-of ms))) ; (Date. epoch-ms) - ((y m d) (sql-date-midnight (+ 1900 (jnum->exact y)) (+ 1 (jnum->exact m)) (jnum->exact d))))) -(register-class-statics! "java.sql.Date" - (list (cons "valueOf" (lambda (s) (mk-sql-date (jinst-ms (parse-ms "yyyy-MM-dd" (if (string? s) s (jolt-str-render-one s))))))))) -(register-host-methods! "sql-date" - (list (cons "getTime" (lambda (self) (ms-of self))) - (cons "toInstant" (lambda (self) (mk-instant (ms-of self)))) - (cons "toLocalDate" (lambda (self) (mk-local-date (ms-of self)))) - (cons "toString" (lambda (self) (inst-rfc3339 (make-jinst (ms-of self))))))) - -;; java.util.Calendar: a mutable broken-down UTC time over an epoch-ms. setTime/ -;; getTime read/write it; set(field,value) recomputes ms from the field projection. -;; Field constants are Java's int values so .set/.get dispatch on the right field. -(define cal-YEAR 1) (define cal-MONTH 2) (define cal-DAY_OF_MONTH 5) -(define cal-HOUR_OF_DAY 11) (define cal-MINUTE 12) (define cal-SECOND 13) -(define cal-MILLISECOND 14) -(define (cal-ms->fields ms) ; -> vector [y mo0 d hh mi ss frac] (MONTH 0-based, JVM) - (let ((f (inst-fields ms))) - (vector (list-ref f 0) (- (list-ref f 1) 1) (list-ref f 2) - (list-ref f 3) (list-ref f 4) (list-ref f 5) (list-ref f 6)))) -(define (cal-fields->ms v) - (+ (* 1000 (+ (* (days-from-civil (vector-ref v 0) (+ 1 (vector-ref v 1)) (vector-ref v 2)) 86400) - (* (vector-ref v 3) 3600) (* (vector-ref v 4) 60) (vector-ref v 5))) - (vector-ref v 6))) -(define (cal-field-index fld) - (cond ((= fld cal-YEAR) 0) ((= fld cal-MONTH) 1) ((= fld cal-DAY_OF_MONTH) 2) - ((= fld cal-HOUR_OF_DAY) 3) ((= fld cal-MINUTE) 4) ((= fld cal-SECOND) 5) - ((= fld cal-MILLISECOND) 6) (else #f))) -(register-host-methods! "calendar" - (list (cons "setTime" (lambda (self d) (vector-set! (jhost-state self) 0 (ms->exact (ms-of d))) jolt-nil)) - (cons "getTime" (lambda (self) (make-jinst (vector-ref (jhost-state self) 0)))) - (cons "getTimeInMillis" (lambda (self) (vector-ref (jhost-state self) 0))) - (cons "setTimeInMillis" (lambda (self ms) (vector-set! (jhost-state self) 0 (ms->exact ms)) jolt-nil)) - (cons "set" (lambda (self field val) - (let ((v (cal-ms->fields (vector-ref (jhost-state self) 0))) - (idx (cal-field-index (jnum->exact field)))) - (when idx (vector-set! v idx (jnum->exact val)) - (vector-set! (jhost-state self) 0 (cal-fields->ms v))) - jolt-nil))) - (cons "get" (lambda (self field) - (let ((v (cal-ms->fields (vector-ref (jhost-state self) 0))) - (idx (cal-field-index (jnum->exact field)))) - (if idx (vector-ref v idx) 0)))))) -(define calendar-statics - (list (cons "getInstance" (lambda _ (make-jhost "calendar" (vector (now-ms))))) - (cons "YEAR" cal-YEAR) (cons "MONTH" cal-MONTH) (cons "DAY_OF_MONTH" cal-DAY_OF_MONTH) - (cons "HOUR_OF_DAY" cal-HOUR_OF_DAY) (cons "MINUTE" cal-MINUTE) - (cons "SECOND" cal-SECOND) (cons "MILLISECOND" cal-MILLISECOND))) -(register-class-statics! "Calendar" calendar-statics) -(register-class-statics! "java.util.Calendar" calendar-statics) - -;; java.util.TimeZone: an opaque id holder (format-ms is UTC, so a non-UTC zone is -;; not honored — only the UTC case the corpus uses is exercised). -(define (timezone-of id) (make-jhost "timezone" (vector (if (string? id) id (jolt-str-render-one id))))) -(define timezone-statics - (list (cons "getTimeZone" timezone-of) - (cons "getDefault" (lambda () (timezone-of "default"))))) -(register-class-statics! "TimeZone" timezone-statics) -(register-class-statics! "java.util.TimeZone" timezone-statics) - -;; java.text.SimpleDateFormat: holds a pattern; .setTimeZone is accepted (format-ms -;; is UTC); .format(date) renders the date per the pattern via the format-ms engine. -(define (sdf-ctor pat . _) (make-jhost "sdf" (vector (if (string? pat) pat (jolt-str-render-one pat))))) -(register-class-ctor! "SimpleDateFormat" sdf-ctor) -(register-class-ctor! "java.text.SimpleDateFormat" sdf-ctor) -(register-host-methods! "sdf" - (list (cons "setTimeZone" (lambda (self tz) jolt-nil)) - (cons "setLenient" (lambda (self b) jolt-nil)) - (cons "applyPattern" (lambda (self p) (vector-set! (jhost-state self) 0 (jolt-str-render-one p)) jolt-nil)) - (cons "toPattern" (lambda (self) (vector-ref (jhost-state self) 0))) - (cons "parse" (lambda (self s) (parse-ms (vector-ref (jhost-state self) 0) (jolt-str-render-one s)))) - (cons "format" (lambda (self d) (format-ms (vector-ref (jhost-state self) 0) (ms-of d)))))) - -;; a jinst's java.util.Date method surface (record-method-dispatch arm). -(register-method-arm! 40 - (lambda (obj method-name rest-args) - (cond - ((jinst? obj) - (cond ((string=? method-name "getTime") (jinst-ms obj)) - ;; deprecated java.util.Date accessors (UTC civil fields). - ((string=? method-name "getYear") (- (list-ref (inst-fields (jinst-ms obj)) 0) 1900)) - ((string=? method-name "getMonth") (- (list-ref (inst-fields (jinst-ms obj)) 1) 1)) - ((string=? method-name "getDate") (list-ref (inst-fields (jinst-ms obj)) 2)) - ((string=? method-name "getHours") (list-ref (inst-fields (jinst-ms obj)) 3)) - ((string=? method-name "getMinutes") (list-ref (inst-fields (jinst-ms obj)) 4)) - ((string=? method-name "getSeconds") (list-ref (inst-fields (jinst-ms obj)) 5)) - ((string=? method-name "getDay") (list-ref (inst-fields (jinst-ms obj)) 7)) - ((string=? method-name "toInstant") (mk-instant (jinst-ms obj))) - ((string=? method-name "toLocalDate") (mk-local-date (jinst-ms obj))) - ((string=? method-name "toLocalDateTime") (mk-local (jinst-ms obj))) - ((string=? method-name "toString") (inst-rfc3339 obj)) - ((string=? method-name "equals") (and (pair? (if (jolt-nil? rest-args) '() (seq->list rest-args))) - (jinst? (car (seq->list rest-args))) - (= (jinst-ms obj) (jinst-ms (car (seq->list rest-args)))))) - ((string=? method-name "before") (< (jinst-ms obj) (ms-of (car (seq->list rest-args))))) - ((string=? method-name "after") (> (jinst-ms obj) (ms-of (car (seq->list rest-args))))) - (else (error #f (string-append "No method " method-name " on Date"))))) - (else 'pass)))) - -;; Clojure's built-in data readers, so a library that merges default-data-readers -;; or binds *data-readers* (e.g. aero's reader opts) resolves #inst / #uuid. -;; Keyed by symbol, like Clojure. *data-readers* is the bindable user table. -(def-var! "clojure.core" "default-data-readers" - (jolt-hash-map (jolt-symbol #f "inst") jolt-inst-from-string - (jolt-symbol #f "uuid") jolt-uuid-from-string)) -(def-var! "clojure.core" "*data-readers*" empty-pmap) diff --git a/host/chez/java/io-streams.ss b/host/chez/java/io-streams.ss deleted file mode 100644 index 98849b2..0000000 --- a/host/chez/java/io-streams.ss +++ /dev/null @@ -1,333 +0,0 @@ -;; java.io byte/char streams over Chez ports. Each stream is a jhost wrapping a -;; Chez port, so buffering, EOF and binary<->char transcoding come from Chez -;; rather than a hand-rolled buffer. -;; -;; in-stream #(binary-input-port) FileInputStream / ByteArrayInputStream -;; out-stream #(binary-output-port extract acc) FileOutputStream / ByteArrayOutputStream -;; char-reader #(textual-input-port) FileReader / InputStreamReader -;; char-writer #(textual-output-port) FileWriter / OutputStreamWriter -;; -;; Buffered{Reader,Writer,Input,Output}Stream are buffering wrappers; Chez ports -;; are already buffered, so their constructors return the wrapped stream. -;; -;; Loaded after io.ss + natives-array.ss (uses make-jfile/slurp helpers + the -;; byte-array <-> bytevector bridge), and extends io.ss's reader-jhost? / slurp / -;; __close so the new readers/streams flow through slurp / line-seq / with-open. - -;; --- byte input stream ------------------------------------------------------ -(define (in-stream-port self) (vector-ref (jhost-state self) 0)) -(define (make-in-stream port) (make-jhost "in-stream" (vector port))) -(define (in-stream? x) (and (jhost? x) (string=? (jhost-tag x) "in-stream"))) -(register-host-methods! "in-stream" - (list - (cons "read" - (lambda (self . rest) - (let ((port (in-stream-port self))) - (if (null? rest) - (let ((b (get-u8 port))) (if (eof-object? b) -1 (->num b))) - (let* ((buf (car rest)) - (vec (jolt-array-vec buf)) - (off (if (>= (length rest) 3) (jnum->exact (cadr rest)) 0)) - (len (if (>= (length rest) 3) (jnum->exact (caddr rest)) (vector-length vec)))) - (let loop ((i 0)) - (if (>= i len) (->num i) - (let ((b (get-u8 port))) - (if (eof-object? b) - (if (= i 0) -1 (->num i)) - (begin (vector-set! vec (+ off i) b) (loop (+ i 1)))))))))))) - (cons "readAllBytes" (lambda (self) (let ((bv (get-bytevector-all (in-stream-port self)))) - (na-byte-array (if (eof-object? bv) (make-bytevector 0) bv))))) - (cons "skip" (lambda (self n) (let ((bv (get-bytevector-n (in-stream-port self) (jnum->exact n)))) - (->num (if (eof-object? bv) 0 (bytevector-length bv)))))) - (cons "available" (lambda (self) (->num 0))) - (cons "close" (lambda (self) (close-port (in-stream-port self)) jolt-nil)) - (cons "mark" (lambda (self . _) jolt-nil)) - (cons "reset" (lambda (self) (guard (e (#t jolt-nil)) (set-port-position! (in-stream-port self) 0) jolt-nil))) - (cons "markSupported" (lambda (self) #f)) - (cons "toString" (lambda (self) "#")))) - -;; --- byte output stream ----------------------------------------------------- -;; state #(port extract acc): extract/acc are #f for a file/passthrough stream; -;; a ByteArrayOutputStream carries the R6RS extraction proc + an accumulator -;; bytevector (Chez's extract resets the port, so snapshot on demand, not per write). -(define (out-stream-port self) (vector-ref (jhost-state self) 0)) -(define (out-stream? x) (and (jhost? x) (string=? (jhost-tag x) "out-stream"))) -(define (make-out-stream port) (make-jhost "out-stream" (vector port #f #f))) -(define (bv-concat a b) - (if (= 0 (bytevector-length b)) a - (let ((m (make-bytevector (+ (bytevector-length a) (bytevector-length b))))) - (bytevector-copy! a 0 m 0 (bytevector-length a)) - (bytevector-copy! b 0 m (bytevector-length a) (bytevector-length b)) - m))) -;; all bytes written to a ByteArrayOutputStream so far (folds the latest extract -;; into the accumulator). -(define (baos-bytes self) - (let* ((st (jhost-state self)) (port (vector-ref st 0)) (extract (vector-ref st 1)) (acc (vector-ref st 2))) - (flush-output-port port) - (let ((merged (bv-concat acc (extract)))) - (vector-set! st 2 merged) merged))) -(register-host-methods! "out-stream" - (list - (cons "write" - (lambda (self x . rest) - (let ((port (out-stream-port self))) - (cond - ((number? x) (put-u8 port (bitwise-and (jnum->exact x) #xff))) - ((and (jolt-array? x) (eq? (jolt-array-kind x) 'byte)) - (let ((bv (na-bytearray->bv x))) - (if (pair? rest) - (put-bytevector port bv (jnum->exact (car rest)) (jnum->exact (cadr rest))) - (put-bytevector port bv)))) - ((bytevector? x) (put-bytevector port x)) - (else (error #f "OutputStream/write: unsupported" x))) - jolt-nil))) - (cons "flush" (lambda (self) (flush-output-port (out-stream-port self)) jolt-nil)) - (cons "close" (lambda (self) (flush-output-port (out-stream-port self)) - ;; a ByteArrayOutputStream's close is a no-op (toByteArray stays valid); - ;; a file stream's port is closed. - (unless (vector-ref (jhost-state self) 1) (close-port (out-stream-port self))) jolt-nil)) - (cons "toByteArray" (lambda (self) (na-byte-array (bytevector-copy (baos-bytes self))))) - (cons "size" (lambda (self) (->num (bytevector-length (baos-bytes self))))) - (cons "reset" (lambda (self) (baos-bytes self) (vector-set! (jhost-state self) 2 (make-bytevector 0)) jolt-nil)) - (cons "toString" (lambda (self . cs) (decode-bytevector (baos-bytes self) - (if (pair? cs) (list (jolt-str-render-one (car cs))) '())))))) - -;; --- char input (Reader) ---------------------------------------------------- -(define (char-reader-port self) (vector-ref (jhost-state self) 0)) -(define (char-reader? x) (and (jhost? x) (string=? (jhost-tag x) "char-reader"))) -(define (make-char-reader port) (make-jhost "char-reader" (vector port))) -(register-host-methods! "char-reader" - (list - (cons "read" - (lambda (self . rest) - (let ((port (char-reader-port self))) - (if (null? rest) - (let ((c (get-char port))) (if (eof-object? c) -1 (->num (char->integer c)))) - (let* ((buf (car rest)) - (vec (jolt-array-vec buf)) - (off (if (>= (length rest) 3) (jnum->exact (cadr rest)) 0)) - (len (if (>= (length rest) 3) (jnum->exact (caddr rest)) (vector-length vec)))) - (let loop ((i 0)) - (if (>= i len) (->num i) - (let ((c (get-char port))) - (if (eof-object? c) - (if (= i 0) -1 (->num i)) - (begin (vector-set! vec (+ off i) c) (loop (+ i 1)))))))))))) - (cons "readLine" (lambda (self) (let ((l (get-line (char-reader-port self)))) (if (eof-object? l) jolt-nil l)))) - (cons "lines" (lambda (self) - (let loop ((acc '())) - (let ((l (get-line (char-reader-port self)))) - (if (eof-object? l) (list->cseq (reverse acc)) (loop (cons l acc))))))) - (cons "ready" (lambda (self) #t)) - (cons "skip" (lambda (self n) (let loop ((i 0) (k (jnum->exact n))) - (if (or (>= i k) (eof-object? (get-char (char-reader-port self)))) (->num i) - (loop (+ i 1) k))))) - (cons "close" (lambda (self) (close-port (char-reader-port self)) jolt-nil)) - (cons "mark" (lambda (self . _) jolt-nil)) - (cons "reset" (lambda (self) (guard (e (#t jolt-nil)) (set-port-position! (char-reader-port self) 0) jolt-nil))) - (cons "toString" (lambda (self) "#")))) - -;; --- char output (Writer) --------------------------------------------------- -(define (char-writer-port self) (vector-ref (jhost-state self) 0)) -(define (char-writer? x) (and (jhost? x) (string=? (jhost-tag x) "char-writer"))) -(define (make-char-writer port) (make-jhost "char-writer" (vector port))) -(define (cw-text x) (if (number? x) (string (integer->char (jnum->exact x))) (jolt-str-render-one x))) -(register-host-methods! "char-writer" - (list - (cons "write" (lambda (self x . rest) - ;; (write str) | (write int) | (write str off len) - (let ((s (cw-text x))) - (put-string (char-writer-port self) - (if (>= (length rest) 2) (substring s (jnum->exact (car rest)) - (+ (jnum->exact (car rest)) (jnum->exact (cadr rest)))) s))) - jolt-nil)) - (cons "append" (lambda (self x . rest) (put-string (char-writer-port self) (cw-text x)) self)) - (cons "newLine" (lambda (self) (put-char (char-writer-port self) #\newline) jolt-nil)) - (cons "flush" (lambda (self) (flush-output-port (char-writer-port self)) jolt-nil)) - (cons "close" (lambda (self) (close-port (char-writer-port self)) jolt-nil)) - (cons "toString" (lambda (self) "#")))) - -;; --- constructors ----------------------------------------------------------- -(define utf8-tx (make-transcoder (utf-8-codec))) -(define (path-of x) (project-relative (file-path-of x))) -(define (src-bytevector x) ; a byte[] or Chez bytevector -> bytevector - (cond ((bytevector? x) x) - ((and (jolt-array? x) (eq? (jolt-array-kind x) 'byte)) (na-bytearray->bv x)) - (else (error #f "expected a byte array" x)))) - -(define (reg-ctor! names ctor) (for-each (lambda (n) (register-class-ctor! n ctor)) names)) - -(reg-ctor! '("FileInputStream" "java.io.FileInputStream") - (lambda (src . _) (make-in-stream (open-file-input-port (path-of src) (file-options) (buffer-mode block))))) -(reg-ctor! '("FileOutputStream" "java.io.FileOutputStream") - (lambda (src . rest) - (let ((append? (and (pair? rest) (jolt-truthy? (car rest))))) - (make-out-stream (open-file-output-port (path-of src) - (if append? (file-options no-fail no-truncate append) (file-options no-fail)) - (buffer-mode block)))))) -(reg-ctor! '("ByteArrayInputStream" "java.io.ByteArrayInputStream") - (lambda (bytes . rest) - (let ((bv (src-bytevector bytes))) - (make-in-stream (open-bytevector-input-port - (if (>= (length rest) 2) - (let ((off (jnum->exact (car rest))) (len (jnum->exact (cadr rest)))) - (let ((sub (make-bytevector len))) (bytevector-copy! bv off sub 0 len) sub)) - bv)))))) -(reg-ctor! '("ByteArrayOutputStream" "java.io.ByteArrayOutputStream") - (lambda _ - (call-with-values open-bytevector-output-port - (lambda (port extract) (make-jhost "out-stream" (vector port extract (make-bytevector 0))))))) -(reg-ctor! '("FileReader" "java.io.FileReader") - (lambda (src . _) (make-char-reader (transcoded-port (open-file-input-port (path-of src) (file-options) (buffer-mode block)) utf8-tx)))) -(reg-ctor! '("FileWriter" "java.io.FileWriter") - (lambda (src . rest) - (let ((append? (and (pair? rest) (jolt-truthy? (car rest))))) - (make-char-writer (transcoded-port (open-file-output-port (path-of src) - (if append? (file-options no-fail no-truncate append) (file-options no-fail)) - (buffer-mode block)) utf8-tx))))) -;; InputStreamReader / OutputStreamWriter take ownership of the wrapped byte -;; stream's port and transcode it (UTF-8 default; an explicit charset is honored -;; only as UTF-8 here). -(reg-ctor! '("InputStreamReader" "java.io.InputStreamReader") - (lambda (in . _) (make-char-reader (transcoded-port (in-stream-port in) utf8-tx)))) -(reg-ctor! '("OutputStreamWriter" "java.io.OutputStreamWriter") - (lambda (out . _) (make-char-writer (transcoded-port (out-stream-port out) utf8-tx)))) -;; Buffered* — Chez ports are buffered already; the wrapper is the wrapped stream. -(for-each (lambda (n) (register-class-ctor! n (lambda (inner . _) inner))) - '("BufferedReader" "java.io.BufferedReader" - "BufferedWriter" "java.io.BufferedWriter" - "BufferedInputStream" "java.io.BufferedInputStream" - "BufferedOutputStream" "java.io.BufferedOutputStream")) - -;; --- integration: slurp / line-seq / with-open ------------------------------ -;; a char-reader joins the reader-jhost set (drain-reader / line-seq read it via -;; its .read method). -(let ((prev reader-jhost?)) - (set! reader-jhost? (lambda (x) (or (char-reader? x) (prev x))))) - -;; slurp a char-reader (drain chars) or a byte in-stream (drain bytes -> decode). -(let ((prev jolt-slurp)) - (set! jolt-slurp - (lambda (src . opts) - (cond - ((char-reader? src) (drain-reader src)) - ((in-stream? src) (decode-bytevector (let ((bv (get-bytevector-all (in-stream-port src)))) - (if (eof-object? bv) (make-bytevector 0) bv)) - (slurp-encoding opts))) - (else (apply prev src opts))))) - (def-var! "clojure.core" "slurp" jolt-slurp)) - -;; with-open closes the new stream jhosts via their .close method. -(let ((prev jolt-close)) - (set! jolt-close - (lambda (x) - (if (and (jhost? x) (member (jhost-tag x) '("in-stream" "out-stream" "char-reader" "char-writer"))) - (begin (record-method-dispatch x "close" jolt-nil) jolt-nil) - (prev x)))) - (def-var! "clojure.core" "__close" jolt-close)) - -;; --- clojure.java.io: byte streams + copy / make-parents / delete-file ------- -;; input-stream/output-stream now yield real byte streams (were char reader/writer). -(define (jio-input-stream x) - (cond ((in-stream? x) x) - ((jfile? x) (make-in-stream (open-file-input-port (jfile-fs x) (file-options) (buffer-mode block)))) - ((and (jolt-array? x) (eq? (jolt-array-kind x) 'byte)) (make-in-stream (open-bytevector-input-port (na-bytearray->bv x)))) - ((bytevector? x) (make-in-stream (open-bytevector-input-port x))) - ((and (jhost? x) (string=? (jhost-tag x) "url")) (make-in-stream (open-file-input-port (url-strip-scheme (url-spec x)) (file-options) (buffer-mode block)))) - ((string? x) (make-in-stream (open-file-input-port (project-relative x) (file-options) (buffer-mode block)))) - (else (error #f "io/input-stream: don't know how to open" x)))) -(define (jio-output-stream x . rest) - (cond ((out-stream? x) x) - ((or (jfile? x) (string? x)) - (let ((append? (let loop ((o rest)) (cond ((or (null? o) (null? (cdr o))) #f) - ((and (keyword-t? (car o)) (string=? (keyword-t-name (car o)) "append") (jolt-truthy? (cadr o))) #t) - (else (loop (cddr o))))))) - (make-out-stream (open-file-output-port (path-of x) - (if append? (file-options no-fail no-truncate append) (file-options no-fail)) - (buffer-mode block))))) - (else (error #f "io/output-stream: don't know how to open" x)))) -(def-var! "clojure.java.io" "input-stream" jio-input-stream) -(def-var! "clojure.java.io" "output-stream" jio-output-stream) - -;; io/make-parents: create the parent directories of the last path segment. -(define (jio-make-parents . args) - (let ((p (apply-make-file-path args))) - (let loop ((i (- (string-length p) 1))) - (cond ((<= i 0) #f) - ((char=? (string-ref p i) #\/) (mkdirs! (substring p 0 i))) - (else (loop (- i 1))))))) -(define (apply-make-file-path args) - (jfile-path (apply jolt-make-file args))) -(def-var! "clojure.java.io" "make-parents" jio-make-parents) - -;; io/delete-file: delete the file; raise unless :silently truthy. -(define (jio-delete-file f . opts) - (let ((p (file-path-of f))) - (if (delete-path! p) jolt-nil - (if (and (pair? opts) (jolt-truthy? (car opts))) jolt-nil - (error #f (string-append "Couldn't delete " p)))))) -(def-var! "clojure.java.io" "delete-file" jio-delete-file) - -;; io/copy: file/path/reader/stream/string/byte[] -> writer/stream/file/path. -;; A byte source copies byte-exact to a byte/file destination (no lossy text -;; round-trip); otherwise the content is read as text. UTF-8 bridges byte<->char. -(define (input-bytes input) ; bytevector for a byte source, else #f - (cond ((in-stream? input) (let ((bv (get-bytevector-all (in-stream-port input)))) (if (eof-object? bv) (make-bytevector 0) bv))) - ((bytevector? input) input) - ((and (jolt-array? input) (eq? (jolt-array-kind input) 'byte)) (na-bytearray->bv input)) - ;; a byte-input-stream shim (host tagged-table, :jolt/input-stream — e.g. - ;; http-client's ByteArrayInputStream): drain it byte-exact, like slurp. - ((and (htable? input) (jolt-truthy? (jolt-ref-get input (keyword "jolt" "input-stream")))) - (drain-byte-stream input)) - (else #f))) -(define (input-text input) - (cond ((string? input) input) - ((or (char-reader? input) (reader-jhost? input)) (drain-reader input)) - ((jfile? input) (jolt-slurp input)) - ((input-bytes input) => (lambda (bv) (decode-bytevector bv '()))) - (else (jolt-str-render-one input)))) -(define (jio-copy input output . opts) - (cond - ((out-stream? output) - (put-bytevector (out-stream-port output) - (or (input-bytes input) (string->utf8 (input-text input))))) - ((char-writer? output) (put-string (char-writer-port output) (input-text input))) - ((and (jhost? output) (member (jhost-tag output) '("writer" "file-writer" "port-writer" "print-writer"))) - (record-method-dispatch output "write" (list->cseq (list (input-text input))))) - ((or (jfile? output) (string? output)) - (let ((bv (and (not (string? input)) (not (jfile? input)) (input-bytes input)))) - (if bv - (let ((port (open-file-output-port (path-of output) (file-options no-fail) (buffer-mode block)))) - (put-bytevector port bv) (close-port port)) - (jolt-spit output (input-text input))))) - ;; a byte-output-stream shim (a host tagged-table with :jolt/output-stream, - ;; e.g. http-client's ByteArrayOutputStream): write through its .write method, - ;; byte-exact for a byte source. - ((and (htable? output) (jolt-truthy? (jolt-ref-get output (keyword "jolt" "output-stream")))) - (let ((bv (input-bytes input))) - (record-method-dispatch output "write" - (list->cseq (list (if bv (make-jolt-array (list->vector (bytevector->u8-list bv)) 'byte) - (input-text input))))))) - (else (error #f "io/copy: don't know how to write to" output))) - jolt-nil) -(def-var! "clojure.java.io" "copy" jio-copy) - -;; --- instance? for the java.io stream taxonomy ------------------------------ -(register-class-arm! in-stream? (lambda (x) "java.io.InputStream")) -(register-class-arm! out-stream? (lambda (x) "java.io.OutputStream")) -(register-class-arm! char-reader? (lambda (x) "java.io.Reader")) -(register-class-arm! char-writer? (lambda (x) "java.io.Writer")) -(register-instance-check-arm! - (lambda (type-sym val) - (if (not (symbol-t? type-sym)) 'pass - (let ((short (last-dot (symbol-t-name type-sym)))) - (cond - ((and (in-stream? val) (member short '("InputStream" "FileInputStream" "ByteArrayInputStream" - "BufferedInputStream" "FilterInputStream" "Closeable" "AutoCloseable"))) #t) - ((and (out-stream? val) (member short '("OutputStream" "FileOutputStream" "ByteArrayOutputStream" - "BufferedOutputStream" "FilterOutputStream" "Closeable" "AutoCloseable" "Flushable"))) #t) - ((and (char-reader? val) (member short '("Reader" "BufferedReader" "FileReader" "InputStreamReader" - "Closeable" "AutoCloseable" "Readable"))) #t) - ((and (char-writer? val) (member short '("Writer" "BufferedWriter" "FileWriter" "OutputStreamWriter" - "Closeable" "AutoCloseable" "Flushable" "Appendable"))) #t) - (else 'pass)))))) diff --git a/host/chez/java/io.ss b/host/chez/java/io.ss deleted file mode 100644 index d6ce4b7..0000000 --- a/host/chez/java/io.ss +++ /dev/null @@ -1,760 +0,0 @@ -;; java.io.File + host file I/O, implemented over Chez's filesystem -;; primitives. A File is a -;; path-backed jfile record: (instance? java.io.File f) is true, str/slurp coerce -;; it to its path, and the File method surface (getName/getPath/exists/ -;; isDirectory/isFile/listFiles) dispatches through record-method-dispatch. -;; -;; Provides make-file/file?/slurp/spit/flush/dir?/ -;; list-dir for the overlay file-seq (20-coll.clj), which calls __file?/__dir?/ -;; __list-dir + the .isDirectory/.listFiles/.isFile method surface. -;; -;; Loaded LAST in rt.ss, after -;; dot-forms.ss (so the jfile method arm wraps the fully-built dispatch) and -;; natives-meta.ss / records.ss / printing.ss (jolt-type / instance-check / -;; jolt-str-render-one, which it extends). - -(define-record-type jfile (fields path) (nongenerative jolt-jfile-v1)) -(define (jolt-file? x) (jfile? x)) - -;; path string of any value: a jfile -> its path, else its str rendering. -(define (file-path-of x) (if (jfile? x) (jfile-path x) (jolt-str-render-one x))) - -;; Resources baked into a standalone binary by `jolt build` (deps.edn -;; :jolt/build :embed). The build emits a register-embedded-resource! per file at -;; heap-build time, so the contents live in the boot image — io/resource serves -;; them with no file on disk. An embedded hit reads through slurp/reader exactly -;; like a jfile would. -(define embedded-resources (make-hashtable equal-hash equal?)) -(define (register-embedded-resource! name content) - (hashtable-set! embedded-resources name content)) -(define-record-type embedded-res (fields name content) (nongenerative jolt-embres-v1)) - -;; --- self-contained build artifacts (jolt-eaj) ------------------------------ -;; A toolchain-free `jolt build` (the distributed joltc) carries the Chez -;; petite/scheme boots and a prebuilt launcher stub baked into its own boot image. -;; They live in the same table as embedded-resources, but keyed under bytevector -;; values (register-embedded-bytes!) rather than strings; resolve-on-roots / -;; io/resource only ever ask for the string-keyed source entries, so the two -;; coexist. The build driver reads them at heap-build time from files that exist -;; only on the dev machine. -(define (register-embedded-bytes! name bv) (hashtable-set! embedded-resources name bv)) -(define (jolt-embedded-bytes name) - (let ((v (hashtable-ref embedded-resources name #f))) - (and (bytevector? v) v))) - -;; Read a whole file as a bytevector ("" -> empty). Used to slurp boot/stub files. -(define (read-file-bytes path) - (let ((p (open-file-input-port path))) - (let ((bv (get-bytevector-all p))) - (close-port p) - (if (eof-object? bv) (bytevector) bv)))) - -;; Write an embedded bytevector resource out to a path. make-boot-file needs the -;; petite/scheme boots as files, so they are spilled to scratch before the call. -(define (jolt-spill-embedded! name path) - (let ((bv (jolt-embedded-bytes name))) - (unless bv (error 'jolt-spill-embedded! "no embedded bytes for" name)) - (let ((p (open-file-output-port path (file-options no-fail) (buffer-mode block)))) - (put-bytevector p bv) - (close-port p)))) - -;; Frame an app boot onto a file that already holds the stub bytes. Layout: -;; [stub][boot][boot-length:le64]["JOLTBOOT"]. The stub (host/chez/stub/launcher.c) -;; reads the trailing 16 bytes — the 8-byte magic, then the preceding 8-byte LE -;; length — to locate and register the boot, so a boot that itself contains the -;; magic bytes can't be mistaken for the frame. -(define jolt-payload-magic (string->utf8 "JOLTBOOT")) -(define (jolt-append-payload! path boot-bv) - (let ((head (read-file-bytes path))) ; the stub bytes already written - (let ((p (open-file-output-port path (file-options no-fail) (buffer-mode block))) - (lb (make-bytevector 8 0))) - (bytevector-u64-set! lb 0 (bytevector-length boot-bv) (endianness little)) - (put-bytevector p head) - (put-bytevector p boot-bv) - (put-bytevector p lb) - (put-bytevector p jolt-payload-magic) - (close-port p)))) - -;; chmod 0755 via libc, so the produced binary is executable. load-shared-object -;; with #f pulls the running process's own symbols (chmod is in libc, linked into -;; every Chez binary) — no external toolchain. Falls back to /bin/sh chmod if the -;; symbol can't be resolved. -(define jolt-chmod-755 - (let ((c (jolt-foreign-proc-safe "chmod" '(string int) 'int))) - (lambda (path) - (cond - (c (c path #o755)) - ;; Windows has no chmod and needs none (execute is by extension) - ((let ((m (symbol->string (machine-type)))) - (let loop ((i 0)) - (cond ((> (+ i 2) (string-length m)) #f) - ((string=? (substring m i (+ i 2)) "nt") #t) - (else (loop (+ i 1)))))) - 0) - (else (system (string-append "chmod 755 '" path "'"))))))) - -;; A user-facing relative path resolves against JOLT_PWD — the user's cwd before -;; the launcher cd'd to the jolt repo root — matching the JVM, where io/file is -;; cwd-relative. (io/resource builds jfiles from the source roots directly, so it -;; isn't routed through here.) -(define (project-relative p) - (if (or (= (string-length p) 0) (char=? (string-ref p 0) #\/)) - p - (let ((pwd (getenv "JOLT_PWD"))) - (if (and pwd (> (string-length pwd) 0)) (string-append pwd "/" p) p)))) - -;; (io/file path) / (io/file parent child) — join children with "/". The File -;; keeps the path AS GIVEN (like the JVM: new File("rel").getPath() is "rel"); -;; a relative path resolves against JOLT_PWD only when the filesystem is touched -;; (jfile-fs / slurp / spit / the stream constructors). -(define (jolt-make-file path . rest) - (let loop ((p (file-path-of path)) (cs rest)) - (if (null? cs) (make-jfile p) - (loop (string-append p "/" (file-path-of (car cs))) (cdr cs))))) -;; the on-disk path of a value: a relative path resolves against JOLT_PWD. -(define (jfile-fs f) (project-relative (file-path-of f))) - -(define (path-last-segment p) - (let loop ((i (- (string-length p) 1))) - (cond ((< i 0) p) - ((char=? (string-ref p i) #\/) (substring p (+ i 1) (string-length p))) - (else (loop (- i 1)))))) - -;; directory children as full paths, sorted (the __list-dir seed primitive). -(define (jolt-list-dir path) - (let ((p (project-relative (file-path-of path)))) - (map (lambda (e) (string-append p "/" e)) - (sort string (string-length p) 0) (char=? (string-ref p 0) #\/)) p - (string-append (current-directory) "/" p))) - -;; --- file metadata over Chez filesystem ops --------------------------------- -;; byte size of a regular file (0 for a directory or a missing file). -(define (file-byte-size p) - (if (or (not (file-exists? p)) (file-directory? p)) 0 - (let ((port (open-file-input-port p))) (let ((n (file-length port))) (close-port port) n)))) -;; last-modified as epoch milliseconds (0 if the file is absent). -(define (file-mtime-millis p) - (if (file-exists? p) - (let ((t (file-modification-time p))) - (+ (* (time-second t) 1000) (div (time-nanosecond t) 1000000))) - 0)) -;; mkdir -p: create p and any missing parents. Returns #t if p ends up a dir. -(define (mkdirs! p) - (unless (or (= 0 (string-length p)) (file-exists? p)) - (let loop ((i (- (string-length p) 1))) - (cond ((<= i 0) #f) - ((char=? (string-ref p i) #\/) - (let ((parent (substring p 0 i))) (unless (file-exists? parent) (mkdirs! parent)))) - (else (loop (- i 1))))) - (guard (e (#t #f)) (mkdir p))) - (and (file-exists? p) (file-directory? p))) -;; delete a file or an (empty) directory; #t on success. -(define (delete-path! p) - (guard (e (#t #f)) - (cond ((not (file-exists? p)) #f) - ((file-directory? p) (delete-directory p) #t) - (else (delete-file p) #t)))) - -;; --- java.net.URL (a jhost "url", state #(spec)) ---------------------------- -;; A File.toURL value: .toString / .toExternalForm give the spec, .getPath / -;; .getFile strip the "file:" scheme. -(define (make-url spec) (make-jhost "url" (vector spec))) -(define (url-spec u) (vector-ref (jhost-state u) 0)) -(define (url-strip-scheme spec) - (if (and (>= (string-length spec) 5) (string=? (substring spec 0 5) "file:")) - (substring spec 5 (string-length spec)) spec)) -(define (url-protocol spec) - (let ((i (let loop ((j 0)) (cond ((>= j (string-length spec)) #f) - ((char=? (string-ref spec j) #\:) j) (else (loop (+ j 1))))))) - (if i (substring spec 0 i) ""))) -;; (java.net.URL. spec) — a basic file/http URL value (a library may register a -;; richer URL shim, which overrides this). -(register-class-ctor! "URL" (lambda (spec . _) (make-url (jolt-str-render-one spec)))) -(register-class-ctor! "java.net.URL" (lambda (spec . _) (make-url (jolt-str-render-one spec)))) -(register-host-methods! "url" - (list (cons "toString" (lambda (self) (url-spec self))) - (cons "toExternalForm" (lambda (self) (url-spec self))) - (cons "getProtocol" (lambda (self) (url-protocol (url-spec self)))) - (cons "getPath" (lambda (self) (url-strip-scheme (url-spec self)))) - (cons "getFile" (lambda (self) (url-strip-scheme (url-spec self)))))) - -;; --- File method surface (record-method-dispatch arm) ----------------------- -(define (jfile-method f name args) ; -> boxed result, or #f to fall through - (let ((p (jfile-path f)) ; the path as given (display methods) - (fp (jfile-fs f))) ; JOLT_PWD-resolved on-disk path (FS methods) - (cond - ((string=? name "getPath") (list p)) - ((string=? name "getName") (list (path-last-segment p))) - ((string=? name "toString") (list p)) - ((string=? name "getAbsolutePath")(list (jfile-abs fp))) - ((string=? name "getCanonicalPath")(list (jfile-abs fp))) - ((string=? name "toURI") (list (string-append "file:" (jfile-abs fp)))) - ((string=? name "toURL") (list (make-url (string-append "file:" (jfile-abs fp))))) - ;; io/resource returns a File where the JVM returns a file: URL; answer the - ;; two URL methods resource-serving middleware (ring) calls on the result, so - ;; it sees a "file" protocol and a path without changing the return type. - ((string=? name "getProtocol") (list "file")) - ((string=? name "getFile") (list (jfile-abs fp))) - ((string=? name "exists") (list (if (file-exists? fp) #t #f))) - ((string=? name "isDirectory") (list (if (file-directory? fp) #t #f))) - ((string=? name "isFile") (list (if (and (file-exists? fp) (not (file-directory? fp))) #t #f))) - ((string=? name "isAbsolute") (list (if (and (> (string-length p) 0) (char=? (string-ref p 0) #\/)) #t #f))) - ((string=? name "listFiles") (list (list->cseq (map make-jfile (jolt-list-dir fp))))) - ;; .list -> the child NAMES (a String[]), nil if not a directory. - ((string=? name "list") - (list (if (file-directory? fp) - (apply jolt-vector (sort stringnum (file-byte-size fp)))) - ((string=? name "lastModified") (list (->num (file-mtime-millis fp)))) - ((string=? name "canRead") (list (if (file-exists? fp) #t #f))) - ((string=? name "canWrite") (list (if (file-exists? fp) #t #f))) - ((string=? name "canExecute") (list (if (file-exists? fp) #t #f))) - ((string=? name "isHidden") (list (let ((nm (path-last-segment p))) - (if (and (> (string-length nm) 0) (char=? (string-ref nm 0) #\.)) #t #f)))) - ((string=? name "mkdir") (list (guard (e (#t #f)) (and (not (file-exists? fp)) (begin (mkdir fp) #t))))) - ((string=? name "mkdirs") (list (if (mkdirs! fp) #t #f))) - ((string=? name "delete") (list (if (delete-path! fp) #t #f))) - ((string=? name "deleteOnExit") (list jolt-nil)) - ((string=? name "setLastModified")(list #t)) - ((string=? name "createNewFile") - (list (if (file-exists? fp) #f - (guard (e (#t #f)) (close-port (open-output-file fp 'truncate)) #t)))) - ((string=? name "renameTo") - (list (let ((dst (jfile-fs (car args)))) (guard (e (#t #f)) (rename-file fp dst) #t)))) - ((string=? name "getParentFile") - (let loop ((i (- (string-length p) 1))) - (cond ((< i 0) (list jolt-nil)) - ((char=? (string-ref p i) #\/) (list (make-jfile (if (= i 0) "/" (substring p 0 i))))) - (else (loop (- i 1)))))) - ((string=? name "getAbsoluteFile") (list (make-jfile (jfile-abs p)))) - ((string=? name "getCanonicalFile") (list (make-jfile (jfile-abs p)))) - ((string=? name "compareTo") (list (->num (let ((o (file-path-of (car args)))) - (cond ((string? p o) 1) (else 0)))))) - ((string=? name "equals") (list (and (jfile? (car args)) (string=? p (jfile-path (car args)))))) - ((string=? name "hashCode") (list (->num (string-hash p)))) - ((string=? name "getParent") - (let loop ((i (- (string-length p) 1))) - (cond ((< i 0) (list jolt-nil)) - ((char=? (string-ref p i) #\/) (list (if (= i 0) "/" (substring p 0 i)))) - (else (loop (- i 1)))))) - (else #f)))) - -(register-method-arm! 41 - (lambda (obj method-name rest-args) - (if (jfile? obj) - (let* ((rest (if (jolt-nil? rest-args) '() (seq->list rest-args))) - (r (jfile-method obj method-name rest))) - (if r (car r) (error #f "no File method" method-name))) - 'pass))) - -;; .isDirectory / .listFiles emit to jolt-host-call (rt.ss), not record-method- -;; dispatch — the shims there assume a path STRING target. Make them jfile-aware -;; so file-seq's File branch works. -(define %io-host-call jolt-host-call) -(set! jolt-host-call - (lambda (method target . args) - (cond - ((and (jfile? target) (string=? method "isDirectory")) - (if (file-directory? (jfile-fs target)) #t #f)) - ((and (jfile? target) (string=? method "listFiles")) - (list->cseq (map make-jfile (jolt-list-dir target)))) - (else (apply %io-host-call method target args))))) - -;; --- slurp / spit / flush --------------------------------------------------- -(define (read-file-string path) - (let ((p (open-input-file path))) - (let ((s (get-string-all p))) (close-port p) (if (eof-object? s) "" s)))) - -;; Drain a jhost reader (StringReader / PushbackReader): read code units from the -;; current position to EOF (-1) and assemble the string. Used by slurp; advances -;; the reader, as on the JVM. -(define (drain-reader r) - (let loop ((acc '())) - (let ((u (record-method-dispatch r "read" jolt-nil))) - (if (or (jolt-nil? u) (and (number? u) (< u 0))) - (list->string (reverse acc)) - (loop (cons (integer->char (exact (truncate u))) acc)))))) - -(define (reader-jhost? x) - (and (jhost? x) (member (jhost-tag x) '("string-reader" "pushback-reader")))) - -;; Refill a host reader so subsequent read/slurp see `s` (the unconsumed tail). -(define (reader-refill! r s) - (cond - ((string=? (jhost-tag r) "string-reader") - (vector-set! (jhost-state r) 0 s) (vector-set! (jhost-state r) 1 0)) - ((string=? (jhost-tag r) "pushback-reader") - (vector-set! (jhost-state r) 0 (host-new "StringReader" s)) - (vector-set! (jhost-state r) 1 '())))) -;; Read ONE form from a host reader (StringReader/PushbackReader): drain the -;; remaining chars, parse one form, push the tail back. -> (values form found?). -;; (read r) over a java.io reader — cuerdas' interpolation reads this way. -(define (host-reader-read-form r) - (let* ((s (drain-reader r)) (pr (jolt-parse-next s))) - (if (jolt-nil? pr) - (begin (reader-refill! r "") (values jolt-nil #f)) - (begin (reader-refill! r (jolt-nth pr 1)) (values (jolt-nth pr 0) #t))))) - -;; clojure.edn/read over a reader: drain the jhost reader to a string and read the -;; first EDN form (read-string). Re-asserted over the prelude in post-prelude.ss. -(define (chez-edn-read reader) - (jolt-invoke (var-deref "clojure.core" "read-string") - (if (reader-jhost? reader) (drain-reader reader) (jolt-str-render-one reader)))) - -;; line-seq: an io/reader is a jhost StringReader. Drain it (or take a string) -;; and split on newline; a trailing newline does NOT yield a final empty line -;; (like readLine -> nil at EOF). Re-asserted in post-prelude.ss. -(define (chez-lines s) - (let loop ((cs (string->list s)) (cur '()) (acc '())) - (cond ((null? cs) (reverse (if (null? cur) acc (cons (list->string (reverse cur)) acc)))) - ((char=? (car cs) #\newline) (loop (cdr cs) '() (cons (list->string (reverse cur)) acc))) - (else (loop (cdr cs) (cons (car cs) cur) acc))))) -(define (chez-line-seq rdr) - (list->cseq (chez-lines (cond ((string? rdr) rdr) - ((reader-jhost? rdr) (drain-reader rdr)) - (else (jolt-str-render-one rdr)))))) - -;; (slurp src :encoding "...") — pull the charset from the trailing kwargs. -(define (slurp-encoding opts) - (let loop ((o opts)) - (cond ((or (null? o) (null? (cdr o))) '()) - ((and (keyword-t? (car o)) (string=? (keyword-t-name (car o)) "encoding")) - (list (jolt-str-render-one (cadr o)))) - (else (loop (cddr o)))))) -;; drain a byte input-stream shim (tagged-table) one byte at a time to a bytevector. -(define (drain-byte-stream src) - (let loop ((acc '())) - (let ((b (record-method-dispatch src "read" jolt-nil))) - (if (or (jolt-nil? b) (and (number? b) (< b 0))) - (u8-list->bytevector (reverse acc)) - (loop (cons (bitwise-and (jnum->exact b) #xff) acc)))))) -(define (jolt-slurp src . opts) - (cond - ((jfile? src) (read-file-string (jfile-fs src))) - ((embedded-res? src) (embedded-res-content src)) - ((reader-jhost? src) (drain-reader src)) - ;; bytes (a bytevector or a jolt byte-array): decode with :encoding (UTF-8 - ;; default). clj-http-lite slurps response-body byte arrays. - ((bytevector? src) (decode-bytevector src (slurp-encoding opts))) - ((and (jolt-array? src) (eq? (jolt-array-kind src) 'byte)) - (decode-bytevector (na-bytearray->bv src) (slurp-encoding opts))) - ;; a byte input-stream shim (e.g. clj-http-lite's :as :stream body): drain it. - ((and (htable? src) (jolt-truthy? (jolt-ref-get src (keyword "jolt" "input-stream")))) - (decode-bytevector (drain-byte-stream src) (slurp-encoding opts))) - ((string? src) (read-file-string (project-relative src))) - (else (error #f "slurp: unsupported source" src)))) - -(define (spit-append? opts) - (let loop ((o opts)) - (cond ((or (null? o) (null? (cdr o))) #f) - ((and (keyword-t? (car o)) (string=? (keyword-t-name (car o)) "append") - (jolt-truthy? (cadr o))) #t) - (else (loop (cddr o)))))) - -(define (jolt-spit path content . opts) - (let* ((p (project-relative (file-path-of path))) - (port (open-output-file p (if (spit-append? opts) 'append 'truncate)))) - (put-string port (jolt-str-render-one content)) - (close-port port) - jolt-nil)) - -(define (jolt-flush) (flush-output-port (current-output-port)) jolt-nil) - -;; --- str / type / instance? integration ------------------------------------ -;; str of a jfile is its path (Clojure's File.toString). -(register-str-render! jfile? jfile-path) - -;; stdin line seam: the clojure.core *in* reader (50-io.clj) drives read-line / -;; read / read+string through __stdin-read-line. Return the next line (newline -;; stripped) or nil at EOF. Without this, (read-line) and the REPL call nil. -(def-var! "clojure.core" "__stdin-read-line" - (lambda () (let ((l (get-line (current-input-port)))) (if (eof-object? l) jolt-nil l)))) - -;; (type f) -> :jolt/file (the tagged-file :jolt/type). Re-def-var! -;; "type": natives-meta.ss already bound the var to the old jolt-type value, so the -;; set! alone (which updates the symbol for internal callers) wouldn't reach it. -(define io-kw-file (keyword "jolt" "file")) -(define %io-type jolt-type) -(set! jolt-type (lambda (x) (if (jfile? x) io-kw-file (%io-type x)))) - -;; (instance? java.io.File f): the instance? macro passes the class-name symbol; -;; match "File" / "java.io.File" (and any *.File) against a jfile. -(register-instance-check-arm! - (lambda (type-sym val) - (let ((tname (symbol-t-name type-sym))) - (if (and (jfile? val) - (or (string=? tname "File") (string=? tname "java.io.File") - (string=? (path-last-segment tname) "File"))) - #t - 'pass)))) - -;; --- def-var! the native names the overlay file-seq + str/slurp use ---- -(def-var! "clojure.core" "__make-file" jolt-make-file) -(def-var! "clojure.core" "__file?" jolt-file?) -(def-var! "clojure.core" "__dir?" jolt-dir?) -(def-var! "clojure.core" "__list-dir" (lambda (p) (list->cseq (jolt-list-dir p)))) -(def-var! "clojure.core" "slurp" jolt-slurp) -(def-var! "clojure.core" "spit" jolt-spit) -(def-var! "clojure.core" "flush" jolt-flush) - -;; --- with-open's close seam (__close): a map-like value closes via its :close -;; fn; a jhost reader/writer/file via its .close method (a no-op here); anything -;; else is an error. -(define (jolt-close x) - (cond - ((jolt-nil? x) jolt-nil) - ((and (jhost? x) (member (jhost-tag x) '("string-reader" "pushback-reader" "writer" - "file-writer" "port-writer" "print-writer"))) - (record-method-dispatch x "close" jolt-nil) jolt-nil) - ;; a library's stream shim (tagged-table) closes via its registered .close - ;; method (a no-op for in-memory streams); absent method -> no-op. - ((htable? x) (guard (e (#t jolt-nil)) (record-method-dispatch x "close" jolt-nil)) jolt-nil) - ((jfile? x) jolt-nil) - ;; a deftype/defrecord that implements a `close` method (java.io.Closeable / - ;; AutoCloseable, e.g. tools.reader's reader types) closes through it — the - ;; same method (.close x) would dispatch to. - ((and (jrec? x) (jrec-cl x "close")) - (record-method-dispatch x "close" jolt-nil) jolt-nil) - (else - (let ((closef (jolt-get x (keyword #f "close") jolt-nil))) - (if (and (not (jolt-nil? closef)) (procedure? closef)) - (begin (jolt-invoke closef) jolt-nil) - (error #f "with-open: don't know how to close" x)))))) -(def-var! "clojure.core" "__close" jolt-close) - -;; --- clojure.java.io/reader: an in-memory java.io.Reader over the source. An -;; existing reader passes through; a File / path / URL is slurped; a char[] (or -;; any seq) becomes a reader over (apply str …). Mirrors io.clj's reader. Returns -;; a StringReader (host-static.ss jhost) so .read/.mark/.reset and slurp work. -(define (seq-source->string x) - (apply string-append (map jolt-str-render-one (seq->list x)))) -;; io/reader returns an in-memory StringReader (the full Reader contract incl. -;; (read), mark/reset and pushback). The streaming java.io.FileReader / -;; BufferedReader classes (io-streams.ss) read a Chez port directly when a caller -;; wants to avoid loading the whole source. -(define (jolt-io-reader x) - (cond - ((reader-jhost? x) x) - ((jfile? x) (host-new "StringReader" (read-file-string (jfile-fs x)))) - ((embedded-res? x) (host-new "StringReader" (embedded-res-content x))) - ((and (jhost? x) (string=? (jhost-tag x) "url")) - (host-new "StringReader" (read-file-string (url-strip-scheme (url-spec x))))) - ((string? x) (host-new "StringReader" (read-file-string (project-relative x)))) - ((or (cseq? x) (empty-list-t? x) (pvec? x)) - (host-new "StringReader" (seq-source->string x))) - (else (host-new "StringReader" (jolt-str-render-one x))))) - -;; --- clojure.java.io/writer: an existing writer passes through; a File / path -;; gets a file-backed writer (host-static.ss "file-writer") that persists on -;; flush/close. Mirrors io.clj's writer over the host's StringWriter/file ports. -(define (jolt-io-writer x) - (cond - ((and (jhost? x) (string=? (jhost-tag x) "writer")) x) - ((and (jhost? x) (string=? (jhost-tag x) "file-writer")) x) - ((jfile? x) (make-jhost "file-writer" (vector (jfile-path x) ""))) - ((string? x) (make-jhost "file-writer" (vector x ""))) - (else (error #f "io/writer: don't know how to create a writer from" x)))) - -;; --- clojure.java.io ns ----------------------------------------------------- -(def-var! "clojure.java.io" "file" jolt-make-file) -(def-var! "clojure.java.io" "as-file" (lambda (x) (if (jfile? x) x (make-jfile (file-path-of x))))) -;; "reader" is bound by natives-array.ss (loaded later) so a char[] argument is -;; handled; that binding delegates here via jolt-io-reader for everything else. -(def-var! "clojure.java.io" "writer" jolt-io-writer) -(def-var! "clojure.java.io" "input-stream" jolt-io-reader) -(def-var! "clojure.java.io" "output-stream" jolt-io-writer) -;; resource: jolt has no classpath, so a named resource is resolved against the -;; loader's source roots (a project's :paths, e.g. "resources"). Returns a File -;; (slurp/reader-able) for the first match, else nil. get-source-roots is the -;; loader's accessor (loader.ss), resolved at call time — the runtime CLI loads it. -(define (jolt-io-resource name) - (let* ((nm (jolt-str-render-one name)) - (emb (hashtable-ref embedded-resources nm #f))) - (if emb (make-embedded-res nm emb) - (let loop ((roots (get-source-roots))) - (cond ((null? roots) jolt-nil) - ((file-exists? (string-append (car roots) "/" nm)) (make-jfile (string-append (car roots) "/" nm))) - (else (loop (cdr roots)))))))) -(def-var! "clojure.java.io" "resource" jolt-io-resource) -;; as-url honors a library-registered URL class (e.g. jolt-lang/http-client's full -;; java.net.URL shim) so io/as-url and (URL. spec) agree; else the file-only jhost. -(def-var! "clojure.java.io" "as-url" - (lambda (x) - (cond ((and (jhost? x) (string=? (jhost-tag x) "url")) x) - ((htable? x) x) - (else (let ((ctor (lookup-class class-ctors-tbl "URL"))) - (if ctor (ctor (jolt-str-render-one x)) (make-url (jolt-str-render-one x)))))))) - -;; --- java.lang.ClassLoader -------------------------------------------------- -;; jolt has no classpath; a "classloader" resolves a named resource against the -;; loader's source roots (the same model as clojure.java.io/resource), returning a -;; file: URL or nil. getSystemClassLoader / a thread's contextClassLoader both hand -;; back this loader. Libraries that probe the classpath (e.g. migratus's migration- -;; dir discovery) then fall back to the filesystem when a resource isn't a root. -(define the-classloader (make-jhost "classloader" (vector))) -(define (cl-get-resource self name) - (let ((nm (jolt-str-render-one name))) - (let loop ((roots (get-source-roots))) - (cond ((null? roots) jolt-nil) - ((file-exists? (string-append (car roots) "/" nm)) - (make-url (string-append "file:" (car roots) "/" nm))) - (else (loop (cdr roots))))))) -;; getResources: every source root that holds the named resource, as file: URLs -;; (enumeration-seq just calls seq, so a list serves). ring's static-resource -;; symlink check enumerates these to confirm a served file sits under a root. -(define (cl-get-resources self name) - (let ((nm (jolt-str-render-one name))) - (let loop ((roots (get-source-roots)) (acc '())) - (cond ((null? roots) (list->cseq (reverse acc))) - ((file-exists? (string-append (car roots) "/" nm)) - (loop (cdr roots) (cons (make-url (string-append "file:" (car roots) "/" nm)) acc))) - (else (loop (cdr roots) acc)))))) -(register-host-methods! "classloader" - (list (cons "getResource" cl-get-resource) - (cons "getResources" cl-get-resources) - (cons "getResourceAsStream" - (lambda (self name) - (let ((u (cl-get-resource self name))) - (if (jolt-nil? u) jolt-nil (host-new "StringReader" (jolt-slurp (url-strip-scheme (url-spec u)))))))))) -(register-class-statics! "ClassLoader" (list (cons "getSystemClassLoader" (lambda () the-classloader)))) -(register-class-statics! "java.lang.ClassLoader" (list (cons "getSystemClassLoader" (lambda () the-classloader)))) -;; clojure.lang.RT/baseLoader — the resource-resolving class loader (RT/baseLoader -;; is how libraries reach Clojure's base loader, e.g. aws-api's resources ns). -(register-class-statics! "RT" (list (cons "baseLoader" (lambda () the-classloader)))) -(register-class-statics! "clojure.lang.RT" (list (cons "baseLoader" (lambda () the-classloader)))) -;; clojure.lang.RT/nextID — process-unique increasing id (AtomicInteger(1) -;; getAndIncrement), used by id generators such as core.logic's lvar. -(define rt-next-id-counter 1) -(define (rt-next-id) - (let ((v rt-next-id-counter)) - (set! rt-next-id-counter (+ rt-next-id-counter 1)) - v)) -(register-class-statics! "RT" (list (cons "nextID" rt-next-id))) -(register-class-statics! "clojure.lang.RT" (list (cons "nextID" rt-next-id))) -;; clojure.lang.Util — hash/equality helpers libraries call directly (core.logic's -;; LCons.hashCode uses Util/hash). hash = Java hashCode (0 for nil); hasheq = the -;; value hash jolt's = uses; equiv = value equality; identical = reference identity. -(let ((util-statics - (list (cons "hash" (lambda (x) (if (jolt-nil? x) 0 (record-method-dispatch x "hashCode" jolt-nil)))) - (cons "hasheq" (lambda (x) (jolt-hash x))) - (cons "equiv" (lambda (a b) (if (jolt= a b) #t #f))) - (cons "identical" (lambda (a b) (if (eq? a b) #t #f)))))) - (register-class-statics! "Util" util-statics) - (register-class-statics! "clojure.lang.Util" util-statics)) -;; Thread/currentThread -> a fresh thread jhost wrapping THIS thread's interrupt -;; flag (the box from current-interrupt-box, host-static.ss), so .interrupt from -;; any thread sets the target thread's flag and .isInterrupted reads it without -;; clearing (instance semantics; the static Thread/interrupted reads-and-clears). -;; getContextClassLoader hands back the loader. -(register-host-methods! "thread" - (list (cons "getContextClassLoader" (lambda (self) the-classloader)) - (cons "getName" (lambda (self) "main")) - ;; no reified call stack (jolt does TCO, so caller frames are erased) — an - ;; empty StackTraceElement[]. clojure.spec.test.alpha's instrument reads it - ;; to name the caller var; it degrades to no ::caller, the conform error - ;; (the ExceptionInfo) is still thrown. - (cons "getStackTrace" (lambda (self) (jolt-vector))) - (cons "interrupt" (lambda (self) - (when (box? (jhost-state self)) (set-box! (jhost-state self) #t)) - jolt-nil)) - (cons "isInterrupted" (lambda (self) - (and (box? (jhost-state self)) (unbox (jhost-state self)) #t))))) -(define (current-thread-handle) (make-jhost "thread" (current-interrupt-box))) -(register-class-statics! "Thread" (list (cons "currentThread" current-thread-handle))) -(register-class-statics! "java.lang.Thread" (list (cons "currentThread" current-thread-handle))) - -;; --- java.io.File / java.util.UUID constructors ----------------------------- -;; (java.io.File. parent child) joins with "/"; (File. path) wraps the path. -(register-class-ctor! "File" - (lambda (a . rest) - (if (pair? rest) - (jolt-make-file (string-append (file-path-of a) "/" (file-path-of (car rest)))) - (jolt-make-file a)))) -;; File statics: the platform separators plus createTempFile / listRoots. -(define temp-file-counter 0) -(define (file-create-temp prefix suffix . dir) - (let* ((d (cond ((pair? dir) (file-path-of (car dir))) - ((getenv "TMPDIR") => (lambda (t) t)) - (else "/tmp"))) - (sfx (if (or (null? (list suffix)) (jolt-nil? suffix)) ".tmp" (jolt-str-render-one suffix)))) - (set! temp-file-counter (+ temp-file-counter 1)) - (let loop ((n temp-file-counter)) - (let ((p (string-append d "/" (jolt-str-render-one prefix) - (number->string (now-millis)) "-" (number->string n) sfx))) - (if (file-exists? p) (loop (+ n 1)) - (begin (close-port (open-output-file p 'truncate)) (make-jfile p))))))) -(let ((statics (list (cons "separator" "/") - (cons "separatorChar" #\/) - (cons "pathSeparator" ":") - (cons "pathSeparatorChar" #\:) - (cons "createTempFile" file-create-temp) - (cons "listRoots" (lambda () (jolt-vector (make-jfile "/"))))))) - (register-class-statics! "File" statics) - (register-class-statics! "java.io.File" statics)) -(register-class-ctor! "java.io.File" - (lambda (a . rest) - (if (pair? rest) - (jolt-make-file (string-append (file-path-of a) "/" (file-path-of (car rest)))) - (jolt-make-file a)))) -;; UUID: randomUUID / fromString statics + a (UUID. s) string ctor. -(register-class-statics! "UUID" - (list (cons "randomUUID" (lambda () (jolt-random-uuid))) - (cons "fromString" (lambda (s) (jolt-parse-uuid (jolt-str-render-one s)))))) -(register-class-statics! "java.util.UUID" - (list (cons "randomUUID" (lambda () (jolt-random-uuid))) - (cons "fromString" (lambda (s) (jolt-parse-uuid (jolt-str-render-one s)))))) -;; (UUID. msb lsb): build from the most/least-significant 64-bit halves (the JVM's -;; 2-long ctor), the form test.check's uuid generator uses. (UUID. s) parses a -;; string. The 128 bits format as the canonical 8-4-4-4-12 lowercase hex string. -(define (uuid-long->hex16 n) - (let* ((u (bitwise-and (jnum->exact n) #xFFFFFFFFFFFFFFFF)) - (s (string-downcase (number->string u 16)))) ; JVM UUIDs are lowercase - (string-append (make-string (- 16 (string-length s)) #\0) s))) -(define (uuid-from-halves msb lsb) - (let ((h (uuid-long->hex16 msb)) (l (uuid-long->hex16 lsb))) - (make-juuid (string-append (substring h 0 8) "-" (substring h 8 12) "-" (substring h 12 16) - "-" (substring l 0 4) "-" (substring l 4 16))))) -(define (uuid-ctor . args) - (if (= (length args) 2) - (uuid-from-halves (car args) (cadr args)) - (jolt-parse-uuid (jolt-str-render-one (car args))))) -(register-class-ctor! "UUID" uuid-ctor) -(register-class-ctor! "java.util.UUID" uuid-ctor) -;; (Long. n) / (Long. "n"): a Long is just jolt's integer; return it (parse a string). -(register-class-ctor! "Long" (lambda (x) (if (string? x) (parse-int-or-throw x 10 "Long") (->num (jnum->exact x))))) -(register-class-ctor! "java.lang.Long" (lambda (x) (if (string? x) (parse-int-or-throw x 10 "Long") (->num (jnum->exact x))))) -;; (Integer. n) / (Integer. "n"): jolt's integer, range-checked like intCast. -(define (integer-ctor x) - (jolt-int-cast (if (string? x) (parse-int-or-throw x 10 "Integer") x))) -(register-class-ctor! "Integer" integer-ctor) -(register-class-ctor! "java.lang.Integer" integer-ctor) -;; (Double. x) / (Double. "x"): jolt's double. -(define (double-ctor x) - (if (string? x) - (let ((n (string->number x))) - (if n (exact->inexact n) - (jolt-throw (jolt-host-throwable "java.lang.NumberFormatException" - (string-append "For input string: \"" x "\""))))) - (jolt-double x))) -(register-class-ctor! "Double" double-ctor) -(register-class-ctor! "java.lang.Double" double-ctor) - -;; (Boolean. "true") / (Boolean. b): true for the string "true" (case-insensitive, -;; anything else false) or the boolean itself — Boolean.valueOf semantics; the -;; box is jolt's plain boolean. -(define (boolean-ctor x) - (cond ((string? x) (string-ci=? x "true")) - ((boolean? x) x) - (else #f))) -(register-class-ctor! "Boolean" boolean-ctor) -(register-class-ctor! "java.lang.Boolean" boolean-ctor) - -;; --- java.net.URI ----------------------------------------------------------- -;; A minimal RFC-3986 split into scheme/authority/host/port/path/query/fragment, -;; kept in a jhost "uri" carrying the original string. (str u)/(.toString u) give -;; the original; getHost is nil for a relative URI (hiccup.util/to-str branches on -;; it). instance? java.net.URI + extend-protocol dispatch work via value-host-tags. -(define (uri-index-of s ch from) - (let ((n (string-length s))) - (let loop ((i from)) (cond ((>= i n) #f) ((char=? (string-ref s i) ch) i) (else (loop (+ i 1))))))) -(define (uri-scheme-end s) - ;; index of ':' that ends a scheme (letter then alnum/+-. before any /?#), or #f. - (let ((n (string-length s))) - (and (> n 0) (char-alphabetic? (string-ref s 0)) - (let loop ((i 1)) - (cond ((>= i n) #f) - ((char=? (string-ref s i) #\:) i) - ((let ((c (string-ref s i))) - (or (char-alphabetic? c) (char-numeric? c) (char=? c #\+) (char=? c #\-) (char=? c #\.))) - (loop (+ i 1))) - (else #f)))))) -(define (uri-parse s) - (let* ((n (string-length s)) - (se (uri-scheme-end s)) - (scheme (and se (substring s 0 se))) - (rest-start (if se (+ se 1) 0)) - ;; fragment - (hash (uri-index-of s #\# rest-start)) - (frag (and hash (substring s (+ hash 1) n))) - (pre-frag-end (or hash n)) - ;; query - (qm (uri-index-of s #\? rest-start)) - (query (and qm (< qm pre-frag-end) (substring s (+ qm 1) pre-frag-end))) - (hp-end (cond ((and qm (< qm pre-frag-end)) qm) (else pre-frag-end))) - ;; authority (after "//") - (has-auth (and (<= (+ rest-start 2) n) - (char=? (string-ref s rest-start) #\/) - (char=? (string-ref s (+ rest-start 1)) #\/))) - (auth-start (and has-auth (+ rest-start 2))) - (auth-end (and has-auth - (let loop ((i auth-start)) - (cond ((>= i hp-end) hp-end) - ((char=? (string-ref s i) #\/) i) - (else (loop (+ i 1))))))) - (authority (and has-auth (substring s auth-start auth-end))) - (path-start (if has-auth auth-end rest-start)) - (path (substring s path-start hp-end))) - ;; host:port from authority (strip userinfo@) - (let* ((at (and authority (uri-index-of authority #\@ 0))) - (hostport (if at (substring authority (+ at 1) (string-length authority)) authority)) - (colon (and hostport (uri-index-of hostport #\: 0))) - (host (cond ((not hostport) jolt-nil) - (colon (substring hostport 0 colon)) - (else hostport))) - (port (if (and colon (< (+ colon 1) (string-length hostport))) - (or (string->number (substring hostport (+ colon 1) (string-length hostport))) -1) - -1))) - (make-jhost "uri" - (list (cons 'string s) - (cons 'scheme (or scheme jolt-nil)) - (cons 'authority (or authority jolt-nil)) - (cons 'host (if (and host (string? host) (= 0 (string-length host))) jolt-nil host)) - (cons 'port (->num port)) - (cons 'path (if (= 0 (string-length path)) (if has-auth "" jolt-nil) path)) - (cons 'query (or query jolt-nil)) - (cons 'fragment (or frag jolt-nil))))))) -(define (uri-field u k) (let ((p (assq k (jhost-state u)))) (if p (cdr p) jolt-nil))) -(register-class-ctor! "URI" (lambda (s) (uri-parse (jolt-str-render-one s)))) -(register-class-ctor! "java.net.URI" (lambda (s) (uri-parse (jolt-str-render-one s)))) -;; URI/create — the static factory, same as the (URI. s) constructor. -(register-class-statics! "URI" (list (cons "create" (lambda (s) (uri-parse (jolt-str-render-one s)))))) -(register-class-statics! "java.net.URI" (list (cons "create" (lambda (s) (uri-parse (jolt-str-render-one s)))))) -(register-host-methods! "uri" - (list (cons "toString" (lambda (u) (uri-field u 'string))) - (cons "toASCIIString" (lambda (u) (uri-field u 'string))) - (cons "getScheme" (lambda (u) (uri-field u 'scheme))) - (cons "getAuthority" (lambda (u) (uri-field u 'authority))) - (cons "getHost" (lambda (u) (uri-field u 'host))) - (cons "getPort" (lambda (u) (uri-field u 'port))) - (cons "getPath" (lambda (u) (uri-field u 'path))) - (cons "getRawPath" (lambda (u) (uri-field u 'path))) - (cons "getQuery" (lambda (u) (uri-field u 'query))) - (cons "getRawQuery" (lambda (u) (uri-field u 'query))) - (cons "getFragment" (lambda (u) (uri-field u 'fragment))) - (cons "isAbsolute" (lambda (u) (not (jolt-nil? (uri-field u 'scheme))))) - (cons "hashCode" (lambda (u) (string-hash (uri-field u 'string)))) - (cons "equals" (lambda (u o) (and (jhost? o) (string=? (jhost-tag o) "uri") - (string=? (uri-field u 'string) (uri-field o 'string))))))) -;; (= u1 u2) is value equality by string form (the .equals method above only -;; serves explicit (.equals …)); hash matches so a URI works as a map key / set -;; member (ring/hiccup compare (URI. "/") values). -(define (uri-jhost? x) (and (jhost? x) (string=? (jhost-tag x) "uri"))) -(register-eq-arm! (lambda (a b) (or (uri-jhost? a) (uri-jhost? b))) - (lambda (a b) (and (uri-jhost? a) (uri-jhost? b) - (string=? (uri-field a 'string) (uri-field b 'string))))) -(register-hash-arm! uri-jhost? (lambda (x) (string-hash (uri-field x 'string)))) -;; str / pr-str of a uri -> its string form. -(register-str-render! (lambda (x) (and (jhost? x) (string=? (jhost-tag x) "uri"))) - (lambda (x) (uri-field x 'string))) -(register-pr-readable-arm! (lambda (x) (and (jhost? x) (string=? (jhost-tag x) "uri"))) - (lambda (x) (string-append "#object[java.net.URI \"" (uri-field x 'string) "\"]"))) -;; class of the host value types defined by now (uri/uuid/file). -(register-class-arm! (lambda (x) (and (jhost? x) (string=? (jhost-tag x) "uri"))) (lambda (x) "java.net.URI")) -(register-class-arm! juuid? (lambda (x) "java.util.UUID")) -(register-class-arm! jfile? (lambda (x) "java.io.File")) diff --git a/host/chez/java/java-time.ss b/host/chez/java/java-time.ss deleted file mode 100644 index 836dc15..0000000 --- a/host/chez/java/java-time.ss +++ /dev/null @@ -1,2307 +0,0 @@ -;; java.time core value types: LocalDate, LocalTime, LocalDateTime, Instant. -;; -;; Each is a tz-free jhost over an integer state: -;; local-date (vector epoch-day) day number from 1970-01-01 -;; local-time (vector nano-of-day) [0, 86_400_000_000_000) -;; local-dt (vector epoch-day nano-of-day) -;; instant (vector epoch-ms) reused from inst-time.ss -;; -;; The cljc.java-time wrappers are thin interop over these — static factories -;; (LocalDate/of …) reach register-class-statics!, instance methods reach the -;; per-tag method tables. Equality / hash / compare / print / instance? / protocol -;; dispatch are wired through the host registries. -;; -;; Precision: Instant is millisecond-granular (it carries epoch-ms only). get-nano -;; reports (ms-sub-second * 1e6); plus-nanos / plus-millis round to the millisecond. -;; LocalTime / LocalDateTime carry full nanosecond precision. - -;; --- shared helpers ---------------------------------------------------------- -(define nanos-per-day 86400000000000) -(define nanos-per-sec 1000000000) - -(define (jt-floor-div a b) (let ((q (quotient a b)) (r (remainder a b))) - (if (and (not (= r 0)) (< (* a b) 0)) (- q 1) q))) -(define (jt-floor-mod a b) (- a (* (jt-floor-div a b) b))) -(define (jt->exact n) (cond ((and (number? n) (exact? n) (integer? n)) n) - ((number? n) (exact (truncate n))) - (else (error #f "java.time: not an integer" n)))) - -(define (jt-leap? y) (and (= 0 (modulo y 4)) (or (not (= 0 (modulo y 100))) (= 0 (modulo y 400))))) -(define (jt-len-of-month y m) - (cond ((= m 2) (if (jt-leap? y) 29 28)) - ((memv m '(4 6 9 11)) 30) - (else 31))) - -;; constructors -(define (jt-local-date ed) (make-jhost "local-date" (vector ed))) -(define (jt-local-time nod) (make-jhost "local-time" (vector nod))) -(define (jt-local-dt ed nod) (make-jhost "local-date-time" (vector ed nod))) - -;; state accessors -(define (ld-epoch-day d) (vector-ref (jhost-state d) 0)) -(define (lt-nano-of-day t) (vector-ref (jhost-state t) 0)) -;; the LocalDateTime jhost uses tag "local-date-time" with [epoch-day nano-of-day]. -;; inst-time.ss's ms-based "local-dt" tag stays for the #inst formatting shim. -(define (ldt-epoch-day x) (vector-ref (jhost-state x) 0)) -(define (ldt-nano-of-day x) (vector-ref (jhost-state x) 1)) - -;; civil <-> epoch-day (inst-time.ss owns days-from-civil / civil-from-days) -(define (ymd->epoch-day y m d) (days-from-civil y m d)) -(define (epoch-day->ymd ed) (civil-from-days ed)) ; -> (values y m d) - -;; build a LocalDate, normalizing month/day overflow the way java.time does: -;; the year/month roll, then the day is clamped to the month length. -(define (jt-date-of y m d) - (let* ((ym (+ (* y 12) (- m 1))) - (y2 (jt-floor-div ym 12)) - (m2 (+ 1 (jt-floor-mod ym 12))) - (dom (min d (jt-len-of-month y2 m2)))) - (jt-local-date (ymd->epoch-day y2 m2 dom)))) - -;; day-of-week: 1970-01-01 is Thursday; java.time DayOfWeek is 1=Mon..7=Sun. -(define (ld-dow ed) (+ 1 (jt-floor-mod (+ ed 3) 7))) -(define jt-day-names (vector "MONDAY" "TUESDAY" "WEDNESDAY" "THURSDAY" "FRIDAY" "SATURDAY" "SUNDAY")) -(define jt-month-names (vector "JANUARY" "FEBRUARY" "MARCH" "APRIL" "MAY" "JUNE" "JULY" - "AUGUST" "SEPTEMBER" "OCTOBER" "NOVEMBER" "DECEMBER")) - -(define (ld-day-of-year ed) - (call-with-values (lambda () (epoch-day->ymd ed)) - (lambda (y m d) (+ 1 (- ed (ymd->epoch-day y 1 1)))))) - -;; nano-of-day <-> (h m s nano) -(define (hmsn->nano h m s nano) (+ (* (+ (* h 3600) (* m 60) s) nanos-per-sec) nano)) -(define (lt-hour t) (quotient (lt-nano-of-day t) (* 3600 nanos-per-sec))) -(define (lt-minute t) (modulo (quotient (lt-nano-of-day t) (* 60 nanos-per-sec)) 60)) -(define (lt-second t) (modulo (quotient (lt-nano-of-day t) nanos-per-sec) 60)) -(define (lt-nano t) (modulo (lt-nano-of-day t) nanos-per-sec)) - -;; --- ISO-8601 rendering ------------------------------------------------------ -(define (iso-date-str ed) - (call-with-values (lambda () (epoch-day->ymd ed)) - (lambda (y m d) (string-append (pad4 y) "-" (pad2 m) "-" (pad2 d))))) - -;; LocalTime: "HH:mm", "HH:mm:ss", or with a fractional second (3/6/9 digits). -(define (frac-digits nano) - (cond ((= 0 (modulo nano 1000000)) (let ((s (number->string (quotient nano 1000000)))) - (string-append (make-string (max 0 (- 3 (string-length s))) #\0) s))) - ((= 0 (modulo nano 1000)) (let ((s (number->string (quotient nano 1000)))) - (string-append (make-string (max 0 (- 6 (string-length s))) #\0) s))) - (else (let ((s (number->string nano))) - (string-append (make-string (max 0 (- 9 (string-length s))) #\0) s))))) -(define (iso-time-str nod) - (let ((h (quotient nod (* 3600 nanos-per-sec))) - (mi (modulo (quotient nod (* 60 nanos-per-sec)) 60)) - (s (modulo (quotient nod nanos-per-sec) 60)) - (nano (modulo nod nanos-per-sec))) - (string-append (pad2 h) ":" (pad2 mi) - (if (and (= s 0) (= nano 0)) "" - (string-append ":" (pad2 s) (if (= nano 0) "" (string-append "." (frac-digits nano)))))))) -(define (iso-datetime-str ed nod) - (string-append (iso-date-str ed) "T" (iso-time-str nod))) -;; Instant: always UTC with a trailing Z; seconds always shown, millis only when nonzero. -(define (iso-instant-str ms) - (let* ((ems (exact (truncate ms))) - (secs (jt-floor-div ems 1000)) - (frac (- ems (* secs 1000))) - (ed (jt-floor-div secs 86400)) - (sod (jt-floor-mod secs 86400)) - (nod (* (+ (* (quotient sod 3600) 3600) (* (quotient (modulo sod 3600) 60) 60) (modulo sod 60)) - nanos-per-sec))) - (string-append (iso-date-str ed) "T" - (pad2 (quotient sod 3600)) ":" (pad2 (modulo (quotient sod 60) 60)) ":" (pad2 (modulo sod 60)) - (if (= frac 0) "" (string-append "." (frac-digits (* frac 1000000)))) - "Z"))) -;; nano-precise ISO instant. The fraction is shown in groups of 3 digits (millis, -;; micros, or nanos), matching DateTimeFormatter.ISO_INSTANT. -(define (iso-instant-str-nanos en) - (let* ((secs (jt-floor-div en nanos-per-sec)) - (nano (jt-floor-mod en nanos-per-sec)) - (ed (jt-floor-div secs 86400)) - (sod (jt-floor-mod secs 86400))) - (string-append (iso-date-str ed) "T" - (pad2 (quotient sod 3600)) ":" (pad2 (modulo (quotient sod 60) 60)) ":" (pad2 (modulo sod 60)) - (cond ((= nano 0) "") - ((= 0 (modulo nano 1000000)) (string-append "." (frac-fixed nano 3))) - ((= 0 (modulo nano 1000)) (string-append "." (frac-fixed nano 6))) - (else (string-append "." (frac-fixed nano 9)))) - "Z"))) -;; nano (0..1e9) -> the leading `digits` of its 9-digit zero-padded form. -(define (frac-fixed nano digits) - (let ((s9 (let ((s (number->string nano))) (string-append (make-string (max 0 (- 9 (string-length s))) #\0) s)))) - (substring s9 0 digits))) - -;; --- ISO parsing ------------------------------------------------------------- -(define (jt-str x) (if (string? x) x (jolt-str-render-one x))) -;; "yyyy-MM-dd" -> epoch-day -(define (parse-iso-date s) - (let ((y (digits-at s 0 4)) (m (digits-at s 5 2)) (d (digits-at s 8 2))) - (if (and y m d (char=? (string-ref s 4) #\-) (char=? (string-ref s 7) #\-)) - (ymd->epoch-day y m d) - (error #f (string-append "could not parse LocalDate: " s))))) -;; "HH:mm[:ss[.fff…]]" -> nano-of-day -(define (parse-iso-time s) - (let ((len (string-length s))) - (let ((h (digits-at s 0 2)) (mi (digits-at s 3 2))) - (unless (and h mi (char=? (string-ref s 2) #\:)) - (error #f (string-append "could not parse LocalTime: " s))) - (let ((s2 (and (> len 5) (char=? (string-ref s 5) #\:) (digits-at s 6 2)))) - (if (not s2) - (hmsn->nano h mi 0 0) - (let loop ((i 8) (nano 0)) ; optional .fraction - (if (and (< i len) (char=? (string-ref s 8) #\.)) - (let frac ((j 9) (k 0) (acc 0)) - (if (and (< j len) (digit? (string-ref s j))) - (frac (+ j 1) (+ k 1) (+ (* acc 10) (- (char->integer (string-ref s j)) 48))) - (hmsn->nano h mi s2 (* acc (expt 10 (max 0 (- 9 k))))))) - (hmsn->nano h mi s2 0)))))))) -;; "yyyy-MM-ddTHH:mm[:ss[.fff]]" -> (values epoch-day nano-of-day) -(define (parse-iso-datetime s) - (let ((ti (let loop ((i 0)) (cond ((>= i (string-length s)) #f) - ((or (char=? (string-ref s i) #\T) (char=? (string-ref s i) #\t)) i) - (else (loop (+ i 1))))))) - (unless ti (error #f (string-append "could not parse LocalDateTime: " s))) - (values (parse-iso-date (substring s 0 ti)) - (parse-iso-time (substring s (+ ti 1) (string-length s)))))) - -;; the offset/zone suffix start in an ISO instant/offset string: the first -;; Z/z/+/- after the 'T', or #f if local-only. (parse-zone-offset / the [zone] -;; bracket handle the suffix itself.) -(define (iso-offset-pos s) - (let ((tpos (let loop ((i 0)) (cond ((>= i (string-length s)) 0) - ((memv (string-ref s i) '(#\T #\t)) i) - (else (loop (+ i 1))))))) - (let loop ((i (+ tpos 1))) - (cond ((>= i (string-length s)) #f) - ((memv (string-ref s i) '(#\Z #\z #\+ #\-)) i) - (else (loop (+ i 1))))))) -;; parse an ISO-8601 instant ("…T…[.fffffffff](Z|±HH:mm)") -> UTC epoch-nanos, -;; preserving full fractional-second precision. -(define (parse-iso-instant-nanos s) - (let* ((opos (iso-offset-pos s)) - (local (if opos (substring s 0 opos) s)) - (osuf (if opos (substring s opos (string-length s)) "Z")) - (off (if (or (string=? osuf "Z") (string=? osuf "z")) 0 (parse-zone-offset osuf)))) - (call-with-values (lambda () (parse-iso-datetime local)) - (lambda (ed nod) (- (+ (* ed nanos-per-day) nod) (* off nanos-per-sec)))))) - -;; --- LocalDate --------------------------------------------------------------- -(define ld-min (jt-local-date (ymd->epoch-day -999999999 1 1))) -(define ld-max (jt-local-date (ymd->epoch-day 999999999 12 31))) - -(register-class-statics! "LocalDate" - (list (cons "of" (lambda (y m d) (jt-date-of (jt->exact y) (jt->exact m) (jt->exact d)))) - (cons "ofEpochDay" (lambda (n) (jt-local-date (jt->exact n)))) - (cons "ofYearDay" (lambda (y doy) (jt-local-date (+ (ymd->epoch-day (jt->exact y) 1 1) (- (jt->exact doy) 1))))) - (cons "parse" (lambda (s . _) (jt-local-date (parse-iso-date (jt-str s))))) - (cons "now" (lambda _ (mk-local-date (now-ms)))) - (cons "from" (lambda (t) (cond ((and (jhost? t) (string=? (jhost-tag t) "local-date")) t) - ((and (jhost? t) (string=? (jhost-tag t) "local-date-time")) (jt-local-date (ldt-epoch-day t))) - (else (mk-local-date (ms-of t)))))) - (cons "MIN" ld-min) - (cons "MAX" ld-max))) - -(define (ld-plus-months d n) - (call-with-values (lambda () (epoch-day->ymd (ld-epoch-day d))) - (lambda (y m dom) - (let* ((ym (+ (* y 12) (- m 1) n)) - (y2 (jt-floor-div ym 12)) (m2 (+ 1 (jt-floor-mod ym 12)))) - (jt-local-date (ymd->epoch-day y2 m2 (min dom (jt-len-of-month y2 m2)))))))) -(define (ld-plus-years d n) - (call-with-values (lambda () (epoch-day->ymd (ld-epoch-day d))) - (lambda (y m dom) (jt-local-date (ymd->epoch-day (+ y n) m (min dom (jt-len-of-month (+ y n) m))))))) - -(define (ld-with-field d which v) - (call-with-values (lambda () (epoch-day->ymd (ld-epoch-day d))) - (lambda (y m dom) - (case which - ((year) (jt-local-date (ymd->epoch-day v m (min dom (jt-len-of-month v m))))) - ((month) (jt-local-date (ymd->epoch-day y v (min dom (jt-len-of-month y v))))) - ((day) (jt-local-date (ymd->epoch-day y m v))) - ((day-of-year) (jt-local-date (+ (ymd->epoch-day y 1 1) (- v 1)))))))) - -(register-host-methods! "local-date" - (list (cons "getYear" (lambda (d) (call-with-values (lambda () (epoch-day->ymd (ld-epoch-day d))) (lambda (y m dd) y)))) - (cons "getMonthValue" (lambda (d) (call-with-values (lambda () (epoch-day->ymd (ld-epoch-day d))) (lambda (y m dd) m)))) - (cons "getDayOfMonth" (lambda (d) (call-with-values (lambda () (epoch-day->ymd (ld-epoch-day d))) (lambda (y m dd) dd)))) - (cons "getMonth" (lambda (d) (call-with-values (lambda () (epoch-day->ymd (ld-epoch-day d))) - (lambda (y m dd) (make-jhost "month-enum" (vector m)))))) - (cons "getDayOfWeek" (lambda (d) (make-jhost "dow-enum" (vector (ld-dow (ld-epoch-day d)))))) - (cons "getDayOfYear" (lambda (d) (ld-day-of-year (ld-epoch-day d)))) - (cons "toEpochDay" (lambda (d) (ld-epoch-day d))) - (cons "lengthOfMonth" (lambda (d) (call-with-values (lambda () (epoch-day->ymd (ld-epoch-day d))) - (lambda (y m dd) (jt-len-of-month y m))))) - (cons "lengthOfYear" (lambda (d) (call-with-values (lambda () (epoch-day->ymd (ld-epoch-day d))) - (lambda (y m dd) (if (jt-leap? y) 366 365))))) - (cons "isLeapYear" (lambda (d) (call-with-values (lambda () (epoch-day->ymd (ld-epoch-day d))) - (lambda (y m dd) (jt-leap? y))))) - (cons "plusDays" (lambda (d n) (jt-local-date (+ (ld-epoch-day d) (jt->exact n))))) - (cons "minusDays" (lambda (d n) (jt-local-date (- (ld-epoch-day d) (jt->exact n))))) - (cons "plusWeeks" (lambda (d n) (jt-local-date (+ (ld-epoch-day d) (* 7 (jt->exact n)))))) - (cons "minusWeeks" (lambda (d n) (jt-local-date (- (ld-epoch-day d) (* 7 (jt->exact n)))))) - (cons "plusMonths" (lambda (d n) (ld-plus-months d (jt->exact n)))) - (cons "minusMonths" (lambda (d n) (ld-plus-months d (- (jt->exact n))))) - (cons "plusYears" (lambda (d n) (ld-plus-years d (jt->exact n)))) - (cons "minusYears" (lambda (d n) (ld-plus-years d (- (jt->exact n))))) - (cons "withYear" (lambda (d v) (ld-with-field d 'year (jt->exact v)))) - (cons "withMonth" (lambda (d v) (ld-with-field d 'month (jt->exact v)))) - (cons "withDayOfMonth" (lambda (d v) (ld-with-field d 'day (jt->exact v)))) - (cons "withDayOfYear" (lambda (d v) (ld-with-field d 'day-of-year (jt->exact v)))) - (cons "isBefore" (lambda (d o) (< (ld-epoch-day d) (ld-epoch-day o)))) - (cons "isAfter" (lambda (d o) (> (ld-epoch-day d) (ld-epoch-day o)))) - (cons "isEqual" (lambda (d o) (= (ld-epoch-day d) (ld-epoch-day o)))) - (cons "compareTo" (lambda (d o) (let ((a (ld-epoch-day d)) (b (ld-epoch-day o))) - (cond ((< a b) -1) ((> a b) 1) (else 0))))) - (cons "equals" (lambda (d o) (and (jhost? o) (string=? (jhost-tag o) "local-date") (= (ld-epoch-day d) (ld-epoch-day o))))) - (cons "hashCode" (lambda (d) (ld-epoch-day d))) - (cons "atStartOfDay" (lambda (d . _) (jt-local-dt (ld-epoch-day d) 0))) - (cons "atTime" (case-lambda - ((d t) (if (and (jhost? t) (string=? (jhost-tag t) "local-time")) - (jt-local-dt (ld-epoch-day d) (lt-nano-of-day t)) - (error #f "atTime: expected LocalTime"))) - ((d h m) (jt-local-dt (ld-epoch-day d) (hmsn->nano (jt->exact h) (jt->exact m) 0 0))) - ((d h m s) (jt-local-dt (ld-epoch-day d) (hmsn->nano (jt->exact h) (jt->exact m) (jt->exact s) 0))) - ((d h m s nano) (jt-local-dt (ld-epoch-day d) (hmsn->nano (jt->exact h) (jt->exact m) (jt->exact s) (jt->exact nano)))))) - (cons "toString" (lambda (d) (iso-date-str (ld-epoch-day d)))))) - -;; --- LocalTime --------------------------------------------------------------- -(define lt-min (jt-local-time 0)) -(define lt-max (jt-local-time (- nanos-per-day 1))) - -(register-class-statics! "LocalTime" - (list (cons "of" (case-lambda - ((h m) (jt-local-time (hmsn->nano (jt->exact h) (jt->exact m) 0 0))) - ((h m s) (jt-local-time (hmsn->nano (jt->exact h) (jt->exact m) (jt->exact s) 0))) - ((h m s nano) (jt-local-time (hmsn->nano (jt->exact h) (jt->exact m) (jt->exact s) (jt->exact nano)))))) - (cons "ofNanoOfDay" (lambda (n) (jt-local-time (jt->exact n)))) - (cons "ofSecondOfDay" (lambda (n) (jt-local-time (* (jt->exact n) nanos-per-sec)))) - (cons "parse" (lambda (s . _) (jt-local-time (parse-iso-time (jt-str s))))) - (cons "now" (lambda _ (jt-local-time (let ((ms (now-ms))) (* (jt-floor-mod (exact (truncate ms)) 86400000) 1000000))))) - (cons "from" (lambda (t) (cond ((and (jhost? t) (string=? (jhost-tag t) "local-time")) t) - ((and (jhost? t) (string=? (jhost-tag t) "local-date-time")) (jt-local-time (ldt-nano-of-day t))) - (else (error #f "LocalTime/from: unsupported"))))) - (cons "MIN" lt-min) - (cons "MAX" lt-max) - (cons "MIDNIGHT" (jt-local-time 0)) - (cons "NOON" (jt-local-time (* 12 3600 nanos-per-sec))))) - -(define (lt-plus t nanos) (jt-local-time (jt-floor-mod (+ (lt-nano-of-day t) nanos) nanos-per-day))) -(define (lt-with t which v) - (let ((h (lt-hour t)) (mi (lt-minute t)) (s (lt-second t)) (nano (lt-nano t))) - (case which - ((hour) (jt-local-time (hmsn->nano v mi s nano))) - ((minute) (jt-local-time (hmsn->nano h v s nano))) - ((second) (jt-local-time (hmsn->nano h mi v nano))) - ((nano) (jt-local-time (hmsn->nano h mi s v)))))) - -(register-host-methods! "local-time" - (list (cons "getHour" (lambda (t) (lt-hour t))) - (cons "getMinute" (lambda (t) (lt-minute t))) - (cons "getSecond" (lambda (t) (lt-second t))) - (cons "getNano" (lambda (t) (lt-nano t))) - (cons "toNanoOfDay" (lambda (t) (lt-nano-of-day t))) - (cons "toSecondOfDay" (lambda (t) (quotient (lt-nano-of-day t) nanos-per-sec))) - (cons "plusHours" (lambda (t n) (lt-plus t (* (jt->exact n) 3600 nanos-per-sec)))) - (cons "minusHours" (lambda (t n) (lt-plus t (- (* (jt->exact n) 3600 nanos-per-sec))))) - (cons "plusMinutes" (lambda (t n) (lt-plus t (* (jt->exact n) 60 nanos-per-sec)))) - (cons "minusMinutes" (lambda (t n) (lt-plus t (- (* (jt->exact n) 60 nanos-per-sec))))) - (cons "plusSeconds" (lambda (t n) (lt-plus t (* (jt->exact n) nanos-per-sec)))) - (cons "minusSeconds" (lambda (t n) (lt-plus t (- (* (jt->exact n) nanos-per-sec))))) - (cons "plusNanos" (lambda (t n) (lt-plus t (jt->exact n)))) - (cons "minusNanos" (lambda (t n) (lt-plus t (- (jt->exact n))))) - (cons "withHour" (lambda (t v) (lt-with t 'hour (jt->exact v)))) - (cons "withMinute" (lambda (t v) (lt-with t 'minute (jt->exact v)))) - (cons "withSecond" (lambda (t v) (lt-with t 'second (jt->exact v)))) - (cons "withNano" (lambda (t v) (lt-with t 'nano (jt->exact v)))) - (cons "truncatedTo" (lambda (t u) (lt-truncate t u))) - (cons "isBefore" (lambda (t o) (< (lt-nano-of-day t) (lt-nano-of-day o)))) - (cons "isAfter" (lambda (t o) (> (lt-nano-of-day t) (lt-nano-of-day o)))) - (cons "compareTo" (lambda (t o) (let ((a (lt-nano-of-day t)) (b (lt-nano-of-day o))) - (cond ((< a b) -1) ((> a b) 1) (else 0))))) - (cons "equals" (lambda (t o) (and (jhost? o) (string=? (jhost-tag o) "local-time") (= (lt-nano-of-day t) (lt-nano-of-day o))))) - (cons "hashCode" (lambda (t) (lt-nano-of-day t))) - (cons "atDate" (lambda (t d) (jt-local-dt (ld-epoch-day d) (lt-nano-of-day t)))) - (cons "toString" (lambda (t) (iso-time-str (lt-nano-of-day t)))))) - -;; truncatedTo a ChronoUnit: zero out below the unit. The unit arrives as a -;; chrono-unit jhost (name) or a keyword/string; common units only. -(define (chrono-unit-name u) - (cond ((and (jhost? u) (string=? (jhost-tag u) "chrono-unit")) (vector-ref (jhost-state u) 0)) - ((string? u) u) - ((keyword? u) (keyword-t-name u)) - (else #f))) -(define (lt-truncate t u) - (let* ((nod (lt-nano-of-day t)) - (unit (chrono-unit-name u)) - (div (cond ((not unit) 1) - ((string-ci=? unit "NANOS") 1) - ((string-ci=? unit "MICROS") 1000) - ((string-ci=? unit "MILLIS") 1000000) - ((string-ci=? unit "SECONDS") nanos-per-sec) - ((string-ci=? unit "MINUTES") (* 60 nanos-per-sec)) - ((string-ci=? unit "HOURS") (* 3600 nanos-per-sec)) - ((string-ci=? unit "DAYS") nanos-per-day) - (else 1)))) - (jt-local-time (* (quotient nod div) div)))) - -;; --- LocalDateTime ----------------------------------------------------------- -(define ldt-min (jt-local-dt (ymd->epoch-day -999999999 1 1) 0)) -(define ldt-max (jt-local-dt (ymd->epoch-day 999999999 12 31) (- nanos-per-day 1))) - -;; epoch-seconds at a zero offset (the tz-free layer treats LocalDateTime as UTC). -(define (ldt->epoch-second x) (+ (* (ldt-epoch-day x) 86400) (quotient (ldt-nano-of-day x) nanos-per-sec))) -(define (ldt->ms x) (+ (* (ldt-epoch-day x) 86400000) (quotient (ldt-nano-of-day x) 1000000))) - -(register-class-statics! "LocalDateTime" - (list (cons "of" (case-lambda - ((d t) (jt-local-dt (ld-epoch-day d) (lt-nano-of-day t))) ; (LocalDate LocalTime) - ((y mo d h mi) (jt-local-dt (ymd->epoch-day (jt->exact y) (jt->exact mo) (jt->exact d)) - (hmsn->nano (jt->exact h) (jt->exact mi) 0 0))) - ((y mo d h mi s) (jt-local-dt (ymd->epoch-day (jt->exact y) (jt->exact mo) (jt->exact d)) - (hmsn->nano (jt->exact h) (jt->exact mi) (jt->exact s) 0))) - ((y mo d h mi s nano) (jt-local-dt (ymd->epoch-day (jt->exact y) (jt->exact mo) (jt->exact d)) - (hmsn->nano (jt->exact h) (jt->exact mi) (jt->exact s) (jt->exact nano)))))) - (cons "ofEpochSecond" (lambda (secs nano off) - (let ((es (jt->exact secs))) - (jt-local-dt (jt-floor-div es 86400) - (+ (* (jt-floor-mod es 86400) nanos-per-sec) (jt->exact nano)))))) - (cons "ofInstant" (lambda (inst . _) (let ((ms (ms-of inst))) - (jt-local-dt (jt-floor-div (exact (truncate ms)) 86400000) - (* (jt-floor-mod (exact (truncate ms)) 86400000) 1000000))))) - (cons "parse" (lambda (s . _) (call-with-values (lambda () (parse-iso-datetime (jt-str s))) - (lambda (ed nod) (jt-local-dt ed nod))))) - (cons "now" (lambda _ (let ((ms (exact (truncate (now-ms))))) - (jt-local-dt (jt-floor-div ms 86400000) (* (jt-floor-mod ms 86400000) 1000000))))) - (cons "from" (lambda (t) (cond ((and (jhost? t) (string=? (jhost-tag t) "local-date-time")) t) - (else (let ((ms (ms-of t))) - (jt-local-dt (jt-floor-div (exact (truncate ms)) 86400000) - (* (jt-floor-mod (exact (truncate ms)) 86400000) 1000000))))))) - (cons "MIN" ldt-min) - (cons "MAX" ldt-max))) - -;; date / time arithmetic on a LocalDateTime: round-trip through the components. -(define (ldt-date x) (jt-local-date (ldt-epoch-day x))) -(define (ldt-time x) (jt-local-time (ldt-nano-of-day x))) -(define (ldt-combine d t) (jt-local-dt (ld-epoch-day d) (lt-nano-of-day t))) -;; add nanos to a LocalDateTime, carrying whole days into the date. -(define (ldt-plus-nanos x nanos) - (let* ((total (+ (ldt-nano-of-day x) nanos)) - (carry (jt-floor-div total nanos-per-day)) - (nod (jt-floor-mod total nanos-per-day))) - (jt-local-dt (+ (ldt-epoch-day x) carry) nod))) - -(register-host-methods! "local-date-time" - (list (cons "getYear" (lambda (x) (call-with-values (lambda () (epoch-day->ymd (ldt-epoch-day x))) (lambda (y m d) y)))) - (cons "getMonthValue" (lambda (x) (call-with-values (lambda () (epoch-day->ymd (ldt-epoch-day x))) (lambda (y m d) m)))) - (cons "getMonth" (lambda (x) (call-with-values (lambda () (epoch-day->ymd (ldt-epoch-day x))) (lambda (y m d) (make-jhost "month-enum" (vector m)))))) - (cons "getDayOfMonth" (lambda (x) (call-with-values (lambda () (epoch-day->ymd (ldt-epoch-day x))) (lambda (y m d) d)))) - (cons "getDayOfWeek" (lambda (x) (make-jhost "dow-enum" (vector (ld-dow (ldt-epoch-day x)))))) - (cons "getDayOfYear" (lambda (x) (ld-day-of-year (ldt-epoch-day x)))) - (cons "getHour" (lambda (x) (lt-hour (ldt-time x)))) - (cons "getMinute" (lambda (x) (lt-minute (ldt-time x)))) - (cons "getSecond" (lambda (x) (lt-second (ldt-time x)))) - (cons "getNano" (lambda (x) (lt-nano (ldt-time x)))) - (cons "toLocalDate" (lambda (x) (ldt-date x))) - (cons "toLocalTime" (lambda (x) (ldt-time x))) - (cons "toEpochSecond" (lambda (x . _) (ldt->epoch-second x))) - (cons "plusDays" (lambda (x n) (jt-local-dt (+ (ldt-epoch-day x) (jt->exact n)) (ldt-nano-of-day x)))) - (cons "minusDays" (lambda (x n) (jt-local-dt (- (ldt-epoch-day x) (jt->exact n)) (ldt-nano-of-day x)))) - (cons "plusWeeks" (lambda (x n) (jt-local-dt (+ (ldt-epoch-day x) (* 7 (jt->exact n))) (ldt-nano-of-day x)))) - (cons "minusWeeks" (lambda (x n) (jt-local-dt (- (ldt-epoch-day x) (* 7 (jt->exact n))) (ldt-nano-of-day x)))) - (cons "plusMonths" (lambda (x n) (ldt-combine (ld-plus-months (ldt-date x) (jt->exact n)) (ldt-time x)))) - (cons "minusMonths" (lambda (x n) (ldt-combine (ld-plus-months (ldt-date x) (- (jt->exact n))) (ldt-time x)))) - (cons "plusYears" (lambda (x n) (ldt-combine (ld-plus-years (ldt-date x) (jt->exact n)) (ldt-time x)))) - (cons "minusYears" (lambda (x n) (ldt-combine (ld-plus-years (ldt-date x) (- (jt->exact n))) (ldt-time x)))) - (cons "plusHours" (lambda (x n) (ldt-plus-nanos x (* (jt->exact n) 3600 nanos-per-sec)))) - (cons "minusHours" (lambda (x n) (ldt-plus-nanos x (- (* (jt->exact n) 3600 nanos-per-sec))))) - (cons "plusMinutes" (lambda (x n) (ldt-plus-nanos x (* (jt->exact n) 60 nanos-per-sec)))) - (cons "minusMinutes" (lambda (x n) (ldt-plus-nanos x (- (* (jt->exact n) 60 nanos-per-sec))))) - (cons "plusSeconds" (lambda (x n) (ldt-plus-nanos x (* (jt->exact n) nanos-per-sec)))) - (cons "minusSeconds" (lambda (x n) (ldt-plus-nanos x (- (* (jt->exact n) nanos-per-sec))))) - (cons "plusNanos" (lambda (x n) (ldt-plus-nanos x (jt->exact n)))) - (cons "minusNanos" (lambda (x n) (ldt-plus-nanos x (- (jt->exact n))))) - (cons "withYear" (lambda (x v) (ldt-combine (ld-with-field (ldt-date x) 'year (jt->exact v)) (ldt-time x)))) - (cons "withMonth" (lambda (x v) (ldt-combine (ld-with-field (ldt-date x) 'month (jt->exact v)) (ldt-time x)))) - (cons "withDayOfMonth" (lambda (x v) (ldt-combine (ld-with-field (ldt-date x) 'day (jt->exact v)) (ldt-time x)))) - (cons "withDayOfYear" (lambda (x v) (ldt-combine (ld-with-field (ldt-date x) 'day-of-year (jt->exact v)) (ldt-time x)))) - (cons "withHour" (lambda (x v) (ldt-combine (ldt-date x) (lt-with (ldt-time x) 'hour (jt->exact v))))) - (cons "withMinute" (lambda (x v) (ldt-combine (ldt-date x) (lt-with (ldt-time x) 'minute (jt->exact v))))) - (cons "withSecond" (lambda (x v) (ldt-combine (ldt-date x) (lt-with (ldt-time x) 'second (jt->exact v))))) - (cons "withNano" (lambda (x v) (ldt-combine (ldt-date x) (lt-with (ldt-time x) 'nano (jt->exact v))))) - (cons "truncatedTo" (lambda (x u) (ldt-combine (ldt-date x) (lt-truncate (ldt-time x) u)))) - (cons "isBefore" (lambda (x o) (ldtms x)))) - (cons "toString" (lambda (x) (iso-datetime-str (ldt-epoch-day x) (ldt-nano-of-day x)))))) - -(define (ldt-cmp x o) - (cond ((< (ldt-epoch-day x) (ldt-epoch-day o)) -1) - ((> (ldt-epoch-day x) (ldt-epoch-day o)) 1) - ((< (ldt-nano-of-day x) (ldt-nano-of-day o)) -1) - ((> (ldt-nano-of-day x) (ldt-nano-of-day o)) 1) - (else 0))) -(define (ldt nanos, or #f for an unsupported unit (no-op). -(define (instant-unit-nanos u) - (let ((unit (chrono-unit-name u))) - (cond ((and unit (string-ci=? unit "DAYS")) (* 86400 nanos-per-sec)) - ((and unit (string-ci=? unit "HALF_DAYS")) (* 43200 nanos-per-sec)) - ((and unit (string-ci=? unit "HOURS")) (* 3600 nanos-per-sec)) - ((and unit (string-ci=? unit "MINUTES")) (* 60 nanos-per-sec)) - ((and unit (string-ci=? unit "SECONDS")) nanos-per-sec) - ((and unit (string-ci=? unit "MILLIS")) 1000000) - ((and unit (string-ci=? unit "MICROS")) 1000) - (else 1)))) -(register-class-statics! "Instant" - (list (cons "ofEpochSecond" (case-lambda - ((s) (mk-instant-nanos (* (jt->exact s) nanos-per-sec))) - ((s nano) (mk-instant-nanos (+ (* (jt->exact s) nanos-per-sec) (jt->exact nano)))))) - (cons "EPOCH" (mk-instant-nanos 0)) - (cons "MIN" (mk-instant-nanos (* (ymd->epoch-day -999999999 1 1) 86400 nanos-per-sec))) - (cons "MAX" (mk-instant-nanos (+ (* (ymd->epoch-day 999999999 12 31) 86400 nanos-per-sec) - (* 86399 nanos-per-sec) 999999999))) - ;; nano-precise ISO parse, overriding the ms-granular inst-time.ss parse. - ;; Falls back to the ms parser for extended-year (±999999999) MIN/MAX strings - ;; the fixed-width date parser can't read. - (cons "parse" (lambda (s . _) - (let ((str (if (string? s) s (jolt-str-render-one s)))) - (guard (e (#t (mk-instant (jinst-ms (jolt-inst-from-string str))))) - (mk-instant-nanos (parse-iso-instant-nanos str)))))))) - -(register-host-methods! "instant" - (list (cons "getEpochSecond" (lambda (x) (jt-floor-div (inst-nanos x) nanos-per-sec))) - (cons "getNano" (lambda (x) (jt-floor-mod (inst-nanos x) nanos-per-sec))) - (cons "toEpochMilli" (lambda (x) (jt-floor-div (inst-nanos x) 1000000))) - (cons "plusMillis" (lambda (x n) (mk-instant-nanos (+ (inst-nanos x) (* (jt->exact n) 1000000))))) - (cons "minusMillis" (lambda (x n) (mk-instant-nanos (- (inst-nanos x) (* (jt->exact n) 1000000))))) - (cons "plusSeconds" (lambda (x n) (mk-instant-nanos (+ (inst-nanos x) (* (jt->exact n) nanos-per-sec))))) - (cons "minusSeconds" (lambda (x n) (mk-instant-nanos (- (inst-nanos x) (* (jt->exact n) nanos-per-sec))))) - (cons "plusNanos" (lambda (x n) (mk-instant-nanos (+ (inst-nanos x) (jt->exact n))))) - (cons "minusNanos" (lambda (x n) (mk-instant-nanos (- (inst-nanos x) (jt->exact n))))) - (cons "isBefore" (lambda (x o) (< (inst-nanos x) (inst-nanos o)))) - (cons "isAfter" (lambda (x o) (> (inst-nanos x) (inst-nanos o)))) - (cons "compareTo" (lambda (x o) (let ((a (inst-nanos x)) (b (inst-nanos o))) - (cond ((< a b) -1) ((> a b) 1) (else 0))))) - (cons "equals" (lambda (x o) (and (jhost? o) (string=? (jhost-tag o) "instant") (= (inst-nanos x) (inst-nanos o))))) - (cons "hashCode" (lambda (x) (inst-nanos x))) - (cons "truncatedTo" (lambda (x u) (let ((d (instant-unit-nanos u))) - (mk-instant-nanos (* (jt-floor-div (inst-nanos x) d) d))))) - (cons "atOffset" (lambda (x off) (offset-of-instant-nanos (inst-nanos x) off))) - (cons "atZone" (lambda (x zone) (zoned-of-instant-nanos (inst-nanos x) zone))) - (cons "toString" (lambda (x) (iso-instant-str-nanos (inst-nanos x)))))) - -;; --- Month / DayOfWeek enums (returned by getMonth / getDayOfWeek) ----------- -(define (jt-month n) (make-jhost "month-enum" (vector n))) -(define (jt-dow n) (make-jhost "dow-enum" (vector n))) -(define (month-val e) (vector-ref (jhost-state e) 0)) -(define (dow-val e) (vector-ref (jhost-state e) 0)) -(define (month-name n) (vector-ref jt-month-names (- n 1))) -(define (dow-name n) (vector-ref jt-day-names (- n 1))) -;; quarter starts: Jan/Apr/Jul/Oct. -(define (month-quarter-start m) (+ 1 (* 3 (quotient (- m 1) 3)))) -;; day-of-year of the first day of month m (non-leap base; +1 from March on a leap year). -(define (month-first-day-of-year m leap) - (let ((cum (vector 0 0 31 59 90 120 151 181 212 243 273 304 334))) - (+ 1 (vector-ref cum m) (if (and leap (> m 2)) 1 0)))) - -(register-host-methods! "month-enum" - (list (cons "getValue" (lambda (e) (month-val e))) - (cons "ordinal" (lambda (e) (- (month-val e) 1))) - (cons "name" (lambda (e) (month-name (month-val e)))) - (cons "toString" (lambda (e) (month-name (month-val e)))) - (cons "getDisplayName" (lambda (e . _) (month-name (month-val e)))) - (cons "plus" (lambda (e n) (jt-month (+ 1 (jt-floor-mod (+ (- (month-val e) 1) (jt->exact n)) 12))))) - (cons "minus" (lambda (e n) (jt-month (+ 1 (jt-floor-mod (- (- (month-val e) 1) (jt->exact n)) 12))))) - (cons "length" (lambda (e leap) (jt-len-of-month (if (jolt-truthy? leap) 4 1) (month-val e)))) - (cons "minLength" (lambda (e) (if (= (month-val e) 2) 28 (jt-len-of-month 1 (month-val e))))) - (cons "maxLength" (lambda (e) (if (= (month-val e) 2) 29 (jt-len-of-month 1 (month-val e))))) - (cons "firstMonthOfQuarter" (lambda (e) (jt-month (month-quarter-start (month-val e))))) - (cons "firstDayOfYear" (lambda (e leap) (month-first-day-of-year (month-val e) (jolt-truthy? leap)))) - (cons "compareTo" (lambda (e o) (- (month-val e) (month-val o)))) - (cons "equals" (lambda (e o) (and (jhost? o) (string=? (jhost-tag o) "month-enum") (= (month-val e) (month-val o))))) - (cons "hashCode" (lambda (e) (month-val e))))) -(register-host-methods! "dow-enum" - (list (cons "getValue" (lambda (e) (dow-val e))) - (cons "ordinal" (lambda (e) (- (dow-val e) 1))) - (cons "name" (lambda (e) (dow-name (dow-val e)))) - (cons "toString" (lambda (e) (dow-name (dow-val e)))) - (cons "getDisplayName" (lambda (e . _) (dow-name (dow-val e)))) - (cons "plus" (lambda (e n) (jt-dow (+ 1 (jt-floor-mod (+ (- (dow-val e) 1) (jt->exact n)) 7))))) - (cons "minus" (lambda (e n) (jt-dow (+ 1 (jt-floor-mod (- (- (dow-val e) 1) (jt->exact n)) 7))))) - (cons "compareTo" (lambda (e o) (- (dow-val e) (dow-val o)))) - (cons "equals" (lambda (e o) (and (jhost? o) (string=? (jhost-tag o) "dow-enum") (= (dow-val e) (dow-val o))))) - (cons "hashCode" (lambda (e) (dow-val e))))) - -(define (month-from-temporal t) - (cond ((and (jhost? t) (string=? (jhost-tag t) "month-enum")) t) - ((jt-date? t) (jt-month (call-with-values (lambda () (epoch-day->ymd (ld-epoch-day t))) (lambda (y m d) m)))) - ((jt-dt? t) (jt-month (call-with-values (lambda () (epoch-day->ymd (ldt-epoch-day t))) (lambda (y m d) m)))) - (else (error #f "Month/from: unsupported")))) -(register-class-statics! "Month" - (append - (list (cons "of" (lambda (n) (jt-month (jt->exact n)))) - (cons "valueOf" (lambda (s) (let ((nm (jt-str s))) - (let loop ((i 0)) (cond ((= i 12) (error #f (string-append "No enum constant Month." nm))) - ((string=? (vector-ref jt-month-names i) nm) (jt-month (+ i 1))) - (else (loop (+ i 1)))))))) - (cons "from" (lambda (t) (month-from-temporal t))) - (cons "values" (lambda () (make-pvec (list->vector (map jt-month '(1 2 3 4 5 6 7 8 9 10 11 12))))))) - (map (lambda (i) (cons (vector-ref jt-month-names (- i 1)) (jt-month i))) '(1 2 3 4 5 6 7 8 9 10 11 12)))) -(define (dow-from-temporal t) - (cond ((and (jhost? t) (string=? (jhost-tag t) "dow-enum")) t) - ((jt-date? t) (jt-dow (ld-dow (ld-epoch-day t)))) - ((jt-dt? t) (jt-dow (ld-dow (ldt-epoch-day t)))) - (else (error #f "DayOfWeek/from: unsupported")))) -(register-class-statics! "DayOfWeek" - (append - (list (cons "of" (lambda (n) (jt-dow (jt->exact n)))) - (cons "valueOf" (lambda (s) (let ((nm (jt-str s))) - (let loop ((i 0)) (cond ((= i 7) (error #f (string-append "No enum constant DayOfWeek." nm))) - ((string=? (vector-ref jt-day-names i) nm) (jt-dow (+ i 1))) - (else (loop (+ i 1)))))))) - (cons "from" (lambda (t) (dow-from-temporal t))) - (cons "values" (lambda () (make-pvec (list->vector (map jt-dow '(1 2 3 4 5 6 7))))))) - (map (lambda (i) (cons (vector-ref jt-day-names (- i 1)) (jt-dow i))) '(1 2 3 4 5 6 7)))) - -;; --- Duration: (vector seconds nanos), nanos in [0, 1e9) ---------------------- -(define (dur-normalize secs nanos) - (let* ((carry (jt-floor-div nanos nanos-per-sec)) - (n (jt-floor-mod nanos nanos-per-sec))) - (make-jhost "duration" (vector (+ secs carry) n)))) -(define (dur-secs d) (vector-ref (jhost-state d) 0)) -(define (dur-nanos d) (vector-ref (jhost-state d) 1)) -(define (dur-total-nanos d) (+ (* (dur-secs d) nanos-per-sec) (dur-nanos d))) -(define (dur-of-total-nanos tn) (dur-normalize (jt-floor-div tn nanos-per-sec) (jt-floor-mod tn nanos-per-sec))) -(define dur-zero (make-jhost "duration" (vector 0 0))) - -;; ISO-8601: PTnHnMnS. Components come from the normalized (secs,nanos>=0) state; -;; each H/M/S field carries its own sign (java.time prints them per-component). The -;; seconds field folds in the fractional nanos: a negative second with nanos shows -;; e.g. "-0.5" (rem-sec -1 + nanos 5e8 -> -0.5). -(define (dur->string d) - (let ((secs (dur-secs d)) (nanos (dur-nanos d))) - (if (and (= secs 0) (= nanos 0)) "PT0S" - (let* ((hours (quotient secs 3600)) - (mins (quotient (remainder secs 3600) 60)) - (rem-secs (remainder secs 60)) - (out (open-output-string))) - (display "PT" out) - (unless (= hours 0) (display (number->string hours) out) (write-char #\H out)) - (unless (= mins 0) (display (number->string mins) out) (write-char #\M out)) - (when (or (not (= rem-secs 0)) (not (= nanos 0)) (and (= hours 0) (= mins 0))) - (if (= nanos 0) - (display (number->string rem-secs) out) - ;; whole second + fraction; a negative rem-sec with positive nanos - ;; rolls toward zero (rem+1) and shows fraction as 1e9-nanos. - (let* ((neg (< rem-secs 0)) - (whole (if neg (+ rem-secs 1) rem-secs)) - (frac (if neg (- nanos-per-sec nanos) nanos))) - (when (and neg (= whole 0)) (write-char #\- out)) - (display (number->string whole) out) - (write-char #\. out) - (display (dur-frac-digits frac) out))) - (write-char #\S out)) - (get-output-string out))))) -;; nanos -> a 9-digit fraction with all trailing zeros stripped (Duration shows the -;; minimal fraction, e.g. .5, unlike LocalTime which pads to 3/6/9). -(define (dur-frac-digits nano) - (let ((s9 (let ((s (number->string nano))) (string-append (make-string (max 0 (- 9 (string-length s))) #\0) s)))) - (let loop ((i 9)) (cond ((<= i 1) (substring s9 0 1)) - ((char=? (string-ref s9 (- i 1)) #\0) (loop (- i 1))) - (else (substring s9 0 i)))))) - -(define (dur-temporal-nanos t) ; instant/ldt/lt/zoned/offset -> a nanos count - (cond ((jt-instant? t) (inst-nanos t)) - ((jt-dt? t) (+ (* (ldt-epoch-day t) nanos-per-day) (ldt-nano-of-day t))) - ((jt-time? t) (lt-nano-of-day t)) - ((jt-date? t) (* (ld-epoch-day t) nanos-per-day)) - ;; zoned/offset date-times measure on the instant timeline (UTC nanos). - ((jt-zoned-dt? t) (zdt->nanos t)) - ((jt-offset-dt? t) (odt->nanos t)) - (else (error #f "Duration/between: unsupported temporal")))) -(register-class-statics! "Duration" - (list (cons "ZERO" dur-zero) - (cons "of" (lambda (n unit) (dur-of-total-nanos (* (jt->exact n) (chrono-unit-nanos unit))))) - (cons "ofDays" (lambda (n) (dur-normalize (* (jt->exact n) 86400) 0))) - (cons "ofHours" (lambda (n) (dur-normalize (* (jt->exact n) 3600) 0))) - (cons "ofMinutes" (lambda (n) (dur-normalize (* (jt->exact n) 60) 0))) - (cons "ofSeconds" (case-lambda - ((s) (dur-normalize (jt->exact s) 0)) - ((s na) (dur-normalize (jt->exact s) (jt->exact na))))) - (cons "ofMillis" (lambda (n) (dur-of-total-nanos (* (jt->exact n) 1000000)))) - (cons "ofNanos" (lambda (n) (dur-of-total-nanos (jt->exact n)))) - (cons "between" (lambda (a b) (dur-of-total-nanos (- (dur-temporal-nanos b) (dur-temporal-nanos a))))) - (cons "from" (lambda (t) (if (and (jhost? t) (string=? (jhost-tag t) "duration")) t (error #f "Duration/from")))) - (cons "parse" (lambda (s) (parse-iso-duration (jt-str s)))))) - -(define (dur-plus a b) (dur-of-total-nanos (+ (dur-total-nanos a) (dur-total-nanos b)))) -(register-host-methods! "duration" - (list (cons "getSeconds" (lambda (d) (dur-secs d))) - (cons "getNano" (lambda (d) (dur-nanos d))) - (cons "toDays" (lambda (d) (quotient (dur-secs d) 86400))) - (cons "toHours" (lambda (d) (quotient (dur-secs d) 3600))) - (cons "toMinutes" (lambda (d) (quotient (dur-secs d) 60))) - ;; toMillis/toSeconds truncate the TOTAL toward zero (JVM rounds the whole - ;; value, not per-field): -1001 micros -> -1 ms, not -2. - (cons "toMillis" (lambda (d) (quotient (dur-total-nanos d) 1000000))) - (cons "toNanos" (lambda (d) (dur-total-nanos d))) - (cons "plus" (lambda (d o) (cond ((and (jhost? o) (string=? (jhost-tag o) "duration")) (dur-plus d o)) - (else (error #f "Duration.plus: expected Duration"))))) - (cons "minus" (lambda (d o) (dur-of-total-nanos (- (dur-total-nanos d) (dur-total-nanos o))))) - (cons "plusDays" (lambda (d n) (dur-of-total-nanos (+ (dur-total-nanos d) (* (jt->exact n) 86400 nanos-per-sec))))) - (cons "plusHours" (lambda (d n) (dur-of-total-nanos (+ (dur-total-nanos d) (* (jt->exact n) 3600 nanos-per-sec))))) - (cons "plusMinutes" (lambda (d n) (dur-of-total-nanos (+ (dur-total-nanos d) (* (jt->exact n) 60 nanos-per-sec))))) - (cons "plusSeconds" (lambda (d n) (dur-of-total-nanos (+ (dur-total-nanos d) (* (jt->exact n) nanos-per-sec))))) - (cons "plusMillis" (lambda (d n) (dur-of-total-nanos (+ (dur-total-nanos d) (* (jt->exact n) 1000000))))) - (cons "plusNanos" (lambda (d n) (dur-of-total-nanos (+ (dur-total-nanos d) (jt->exact n))))) - (cons "minusDays" (lambda (d n) (dur-of-total-nanos (- (dur-total-nanos d) (* (jt->exact n) 86400 nanos-per-sec))))) - (cons "minusHours" (lambda (d n) (dur-of-total-nanos (- (dur-total-nanos d) (* (jt->exact n) 3600 nanos-per-sec))))) - (cons "minusMinutes" (lambda (d n) (dur-of-total-nanos (- (dur-total-nanos d) (* (jt->exact n) 60 nanos-per-sec))))) - (cons "minusSeconds" (lambda (d n) (dur-of-total-nanos (- (dur-total-nanos d) (* (jt->exact n) nanos-per-sec))))) - (cons "minusMillis" (lambda (d n) (dur-of-total-nanos (- (dur-total-nanos d) (* (jt->exact n) 1000000))))) - (cons "minusNanos" (lambda (d n) (dur-of-total-nanos (- (dur-total-nanos d) (jt->exact n))))) - (cons "multipliedBy" (lambda (d n) (dur-of-total-nanos (* (dur-total-nanos d) (jt->exact n))))) - (cons "dividedBy" (lambda (d n) (dur-of-total-nanos (quotient (dur-total-nanos d) (jt->exact n))))) - (cons "negated" (lambda (d) (dur-of-total-nanos (- (dur-total-nanos d))))) - (cons "abs" (lambda (d) (dur-of-total-nanos (abs (dur-total-nanos d))))) - (cons "withSeconds" (lambda (d s) (dur-normalize (jt->exact s) (dur-nanos d)))) - (cons "withNanos" (lambda (d na) (dur-normalize (dur-secs d) (jt->exact na)))) - (cons "isZero" (lambda (d) (and (= (dur-secs d) 0) (= (dur-nanos d) 0)))) - (cons "isNegative" (lambda (d) (< (dur-total-nanos d) 0))) - (cons "compareTo" (lambda (d o) (let ((a (dur-total-nanos d)) (b (dur-total-nanos o))) - (cond ((< a b) -1) ((> a b) 1) (else 0))))) - (cons "equals" (lambda (d o) (and (jhost? o) (string=? (jhost-tag o) "duration") (= (dur-total-nanos d) (dur-total-nanos o))))) - (cons "hashCode" (lambda (d) (jolt-hash (dur-total-nanos d)))) - ;; TemporalAmount: addTo/subtractFrom apply this duration to a temporal. - (cons "addTo" (lambda (d t) (temporal-plus-nanos t (dur-total-nanos d)))) - (cons "subtractFrom" (lambda (d t) (temporal-plus-nanos t (- (dur-total-nanos d))))) - ;; TemporalAmount: a Duration is measured in SECONDS + NANOS. - (cons "getUnits" (lambda (d) (make-pvec (vector (jt-chrono-unit "SECONDS") (jt-chrono-unit "NANOS"))))) - (cons "get" (lambda (d u) (let ((nm (string-upcase (arg-unit-name u)))) - (cond ((string=? nm "SECONDS") (dur-secs d)) - ((string=? nm "NANOS") (dur-nanos d)) - (else (error #f (string-append "Duration has no unit " nm))))))) - (cons "toString" (lambda (d) (dur->string d))))) - -;; "PT…" parse: PnDTnHnMn.nS (we accept the time part; days fold into hours). -(define (parse-iso-duration s) - (let ((len (string-length s)) (neg #f) (i 0) (total 0)) - (define (sign-at j) (cond ((>= j len) (values 1 j)) - ((char=? (string-ref s j) #\-) (values -1 (+ j 1))) - ((char=? (string-ref s j) #\+) (values 1 (+ j 1))) - (else (values 1 j)))) - (when (and (< i len) (char=? (string-ref s i) #\-)) (set! neg #t) (set! i (+ i 1))) - (unless (and (< i len) (or (char=? (string-ref s i) #\P) (char=? (string-ref s i) #\p))) - (error #f (string-append "could not parse Duration: " s))) - (set! i (+ i 1)) - (let loop ((in-time #f)) - (when (< i len) - (let ((c (string-ref s i))) - (cond - ((or (char=? c #\T) (char=? c #\t)) (set! i (+ i 1)) (loop #t)) - (else - (call-with-values (lambda () (sign-at i)) - (lambda (sg j) - ;; read number (with optional fraction) - (let num ((k j) (acc 0) (frac 0) (fdigits 0) (in-frac #f) (any #f)) - (cond - ((and (< k len) (digit? (string-ref s k))) - (if in-frac - (num (+ k 1) acc (+ (* frac 10) (- (char->integer (string-ref s k)) 48)) (+ fdigits 1) #t #t) - (num (+ k 1) (+ (* acc 10) (- (char->integer (string-ref s k)) 48)) frac fdigits #f #t))) - ((and (< k len) (char=? (string-ref s k) #\.)) (num (+ k 1) acc frac fdigits #t any)) - ((and any (< k len)) - (let* ((unit (char-upcase (string-ref s k))) - (nanos (* (+ (* acc nanos-per-sec) (* frac (expt 10 (max 0 (- 9 fdigits))))) sg)) - (mult (cond ((char=? unit #\D) 86400) ((char=? unit #\H) 3600) - ((char=? unit #\M) (if in-time 60 (error #f "Duration months unsupported"))) - ((char=? unit #\S) 1) - (else (error #f (string-append "bad Duration unit: " s)))))) - (set! total (+ total (* nanos mult))) - (set! i (+ k 1)) - (loop in-time))) - (else (error #f (string-append "could not parse Duration: " s)))))))))))) - (dur-of-total-nanos (if neg (- total) total)))) - -;; --- Period: (vector years months days) -------------------------------------- -(define (jt-period y m d) (make-jhost "period" (vector y m d))) -(define (per-years p) (vector-ref (jhost-state p) 0)) -(define (per-months p) (vector-ref (jhost-state p) 1)) -(define (per-days p) (vector-ref (jhost-state p) 2)) -(define per-zero (jt-period 0 0 0)) -(define (per->string p) - (let ((y (per-years p)) (m (per-months p)) (d (per-days p))) - (if (and (= y 0) (= m 0) (= d 0)) "P0D" - (let ((out (open-output-string))) - (write-char #\P out) - (unless (= y 0) (display (number->string y) out) (write-char #\Y out)) - (unless (= m 0) (display (number->string m) out) (write-char #\M out)) - (unless (= d 0) (display (number->string d) out) (write-char #\D out)) - (get-output-string out))))) -;; Period/between counts whole years/months/days from a to b (java.time semantics). -(define (per-between a b) - (call-with-values (lambda () (epoch-day->ymd (ld-epoch-day a))) - (lambda (y1 m1 d1) - (call-with-values (lambda () (epoch-day->ymd (ld-epoch-day b))) - (lambda (y2 m2 d2) - (let* ((total-months (- (+ (* y2 12) m2) (+ (* y1 12) m1))) - (days (- d2 d1))) - ;; if days go negative, borrow a month (using the prior month length of b) - (let-values (((tm dd) - (if (and (> total-months 0) (< days 0)) - (let* ((tm (- total-months 1)) - (bm (+ (* y1 12) (- m1 1) tm)) - (by (jt-floor-div bm 12)) (bmo (+ 1 (jt-floor-mod bm 12))) - (len (jt-len-of-month by bmo))) - (values tm (+ days len))) - (if (and (< total-months 0) (> days 0)) - (values (+ total-months 1) (- days (jt-len-of-month y2 m2))) - (values total-months days))))) - (jt-period (jt-floor-div tm 12) (jt-floor-mod tm 12) dd)))))))) -(define (per-normalize p) - (let ((tm (+ (* (per-years p) 12) (per-months p)))) - (jt-period (jt-floor-div tm 12) (jt-floor-mod tm 12) (per-days p)))) -(register-class-statics! "Period" - (list (cons "ZERO" per-zero) - (cons "of" (lambda (y m d) (jt-period (jt->exact y) (jt->exact m) (jt->exact d)))) - (cons "ofYears" (lambda (y) (jt-period (jt->exact y) 0 0))) - (cons "ofMonths" (lambda (m) (jt-period 0 (jt->exact m) 0))) - (cons "ofWeeks" (lambda (w) (jt-period 0 0 (* 7 (jt->exact w))))) - (cons "ofDays" (lambda (d) (jt-period 0 0 (jt->exact d)))) - (cons "between" (lambda (a b) (per-between a b))) - (cons "from" (lambda (t) (if (and (jhost? t) (string=? (jhost-tag t) "period")) t (error #f "Period/from")))) - (cons "parse" (lambda (s) (parse-iso-period (jt-str s)))))) -(register-host-methods! "period" - (list (cons "getYears" (lambda (p) (per-years p))) - (cons "getMonths" (lambda (p) (per-months p))) - (cons "getDays" (lambda (p) (per-days p))) - (cons "toTotalMonths" (lambda (p) (+ (* (per-years p) 12) (per-months p)))) - (cons "plusYears" (lambda (p n) (jt-period (+ (per-years p) (jt->exact n)) (per-months p) (per-days p)))) - (cons "plusMonths" (lambda (p n) (jt-period (per-years p) (+ (per-months p) (jt->exact n)) (per-days p)))) - (cons "plusDays" (lambda (p n) (jt-period (per-years p) (per-months p) (+ (per-days p) (jt->exact n))))) - (cons "minusYears" (lambda (p n) (jt-period (- (per-years p) (jt->exact n)) (per-months p) (per-days p)))) - (cons "minusMonths" (lambda (p n) (jt-period (per-years p) (- (per-months p) (jt->exact n)) (per-days p)))) - (cons "minusDays" (lambda (p n) (jt-period (per-years p) (per-months p) (- (per-days p) (jt->exact n))))) - (cons "withYears" (lambda (p n) (jt-period (jt->exact n) (per-months p) (per-days p)))) - (cons "withMonths" (lambda (p n) (jt-period (per-years p) (jt->exact n) (per-days p)))) - (cons "withDays" (lambda (p n) (jt-period (per-years p) (per-months p) (jt->exact n)))) - (cons "plus" (lambda (p o) (jt-period (+ (per-years p) (per-years o)) (+ (per-months p) (per-months o)) (+ (per-days p) (per-days o))))) - (cons "minus" (lambda (p o) (jt-period (- (per-years p) (per-years o)) (- (per-months p) (per-months o)) (- (per-days p) (per-days o))))) - (cons "multipliedBy" (lambda (p n) (jt-period (* (per-years p) (jt->exact n)) (* (per-months p) (jt->exact n)) (* (per-days p) (jt->exact n))))) - (cons "negated" (lambda (p) (jt-period (- (per-years p)) (- (per-months p)) (- (per-days p))))) - (cons "normalized" (lambda (p) (per-normalize p))) - (cons "isZero" (lambda (p) (and (= (per-years p) 0) (= (per-months p) 0) (= (per-days p) 0)))) - (cons "isNegative" (lambda (p) (or (< (per-years p) 0) (< (per-months p) 0) (< (per-days p) 0)))) - (cons "equals" (lambda (p o) (and (jhost? o) (string=? (jhost-tag o) "period") - (= (per-years p) (per-years o)) (= (per-months p) (per-months o)) (= (per-days p) (per-days o))))) - (cons "hashCode" (lambda (p) (+ (per-years p) (bitwise-arithmetic-shift-left (per-months p) 8) (bitwise-arithmetic-shift-left (per-days p) 16)))) - ;; TemporalAmount: a Period adds its y/m/d to a date-bearing temporal. - (cons "addTo" (lambda (p t) (temporal-plus-period t p 1))) - (cons "subtractFrom" (lambda (p t) (temporal-plus-period t p -1))) - ;; TemporalAmount: a Period is measured in YEARS + MONTHS + DAYS. - (cons "getUnits" (lambda (p) (make-pvec (vector (jt-chrono-unit "YEARS") (jt-chrono-unit "MONTHS") (jt-chrono-unit "DAYS"))))) - (cons "get" (lambda (p u) (let ((nm (string-upcase (arg-unit-name u)))) - (cond ((string=? nm "YEARS") (per-years p)) - ((string=? nm "MONTHS") (per-months p)) - ((string=? nm "DAYS") (per-days p)) - (else (error #f (string-append "Period has no unit " nm))))))) - (cons "toString" (lambda (p) (per->string p))))) -;; "PnYnMnWnD" -> a Period (weeks fold into days). -(define (parse-iso-period s) - (let ((len (string-length s)) (sign 1) (i 0) (y 0) (m 0) (d 0)) - (when (and (< i len) (char=? (string-ref s i) #\-)) (set! sign -1) (set! i (+ i 1))) - (unless (and (< i len) (or (char=? (string-ref s i) #\P) (char=? (string-ref s i) #\p))) - (error #f (string-append "could not parse Period: " s))) - (set! i (+ i 1)) - (let loop () - (when (< i len) - (let ((vsign (cond ((char=? (string-ref s i) #\-) (set! i (+ i 1)) -1) - ((char=? (string-ref s i) #\+) (set! i (+ i 1)) 1) - (else 1)))) - (let num ((k i) (acc 0) (any #f)) - (cond - ((and (< k len) (digit? (string-ref s k))) (num (+ k 1) (+ (* acc 10) (- (char->integer (string-ref s k)) 48)) #t)) - ((and any (< k len)) - (let ((u (char-upcase (string-ref s k))) (val (* vsign acc))) - (cond ((char=? u #\Y) (set! y val)) ((char=? u #\M) (set! m val)) - ((char=? u #\W) (set! d (+ d (* 7 val)))) ((char=? u #\D) (set! d (+ d val))) - (else (error #f (string-append "bad Period unit: " s)))) - (set! i (+ k 1)) (loop))) - (else (error #f (string-append "could not parse Period: " s)))))))) - (jt-period (* sign y) (* sign m) (* sign d)))) - -;; --- Year -------------------------------------------------------------------- -(define (jt-year y) (make-jhost "year" (vector y))) -(define (year-val y) (vector-ref (jhost-state y) 0)) -(define (year-from-temporal t) - (cond ((and (jhost? t) (string=? (jhost-tag t) "year")) t) - ((jt-date? t) (jt-year (call-with-values (lambda () (epoch-day->ymd (ld-epoch-day t))) (lambda (y m d) y)))) - ((jt-dt? t) (jt-year (call-with-values (lambda () (epoch-day->ymd (ldt-epoch-day t))) (lambda (y m d) y)))) - ((and (jhost? t) (string=? (jhost-tag t) "year-month")) (jt-year (ym-year t))) - (else (error #f "Year/from: unsupported")))) -(register-class-statics! "Year" - (list (cons "of" (lambda (y) (jt-year (jt->exact y)))) - (cons "now" (lambda _ (jt-year (call-with-values (lambda () (epoch-day->ymd (jt-floor-div (exact (truncate (now-ms))) 86400000))) (lambda (y m d) y))))) - (cons "isLeap" (lambda (y) (jt-leap? (jt->exact y)))) - (cons "parse" (lambda (s . _) (jt-year (or (string->number (jt-str s)) (error #f "could not parse Year"))))) - (cons "from" (lambda (t) (year-from-temporal t))) - (cons "MIN_VALUE" -999999999) - (cons "MAX_VALUE" 999999999))) -(register-host-methods! "year" - (list (cons "getValue" (lambda (y) (year-val y))) - (cons "isLeap" (lambda (y) (jt-leap? (year-val y)))) - (cons "length" (lambda (y) (if (jt-leap? (year-val y)) 366 365))) - (cons "plusYears" (lambda (y n) (jt-year (+ (year-val y) (jt->exact n))))) - (cons "minusYears" (lambda (y n) (jt-year (- (year-val y) (jt->exact n))))) - (cons "atMonth" (lambda (y m) (jt-year-month (year-val y) (jt->exact m)))) - (cons "atDay" (lambda (y doy) (jt-local-date (+ (ymd->epoch-day (year-val y) 1 1) (- (jt->exact doy) 1))))) - (cons "atMonthDay" (lambda (y md) (error #f "Year.atMonthDay: MonthDay unsupported"))) - (cons "isBefore" (lambda (y o) (< (year-val y) (year-val o)))) - (cons "isAfter" (lambda (y o) (> (year-val y) (year-val o)))) - (cons "isValidMonthDay" (lambda (y md) #f)) - (cons "compareTo" (lambda (y o) (let ((a (year-val y)) (b (year-val o))) (cond ((< a b) -1) ((> a b) 1) (else 0))))) - (cons "equals" (lambda (y o) (and (jhost? o) (string=? (jhost-tag o) "year") (= (year-val y) (year-val o))))) - (cons "hashCode" (lambda (y) (year-val y))) - (cons "toString" (lambda (y) (number->string (year-val y)))))) - -;; --- YearMonth: (vector year month) ------------------------------------------ -(define (jt-year-month y m) - (let* ((ym (+ (* y 12) (- m 1))) (y2 (jt-floor-div ym 12)) (m2 (+ 1 (jt-floor-mod ym 12)))) - (make-jhost "year-month" (vector y2 m2)))) -(define (ym-year x) (vector-ref (jhost-state x) 0)) -(define (ym-month x) (vector-ref (jhost-state x) 1)) -(define (ym-plus-months x n) - (let ((tm (+ (* (ym-year x) 12) (- (ym-month x) 1) n))) - (make-jhost "year-month" (vector (jt-floor-div tm 12) (+ 1 (jt-floor-mod tm 12)))))) -(define (ym->string x) (string-append (pad4 (ym-year x)) "-" (pad2 (ym-month x)))) -(define (ym-from-temporal t) - (cond ((and (jhost? t) (string=? (jhost-tag t) "year-month")) t) - ((jt-date? t) (call-with-values (lambda () (epoch-day->ymd (ld-epoch-day t))) (lambda (y m d) (jt-year-month y m)))) - ((jt-dt? t) (call-with-values (lambda () (epoch-day->ymd (ldt-epoch-day t))) (lambda (y m d) (jt-year-month y m)))) - (else (error #f "YearMonth/from: unsupported")))) -(register-class-statics! "YearMonth" - (list (cons "of" (lambda (y m) (jt-year-month (jt->exact y) (jt->exact m)))) - (cons "now" (lambda _ (call-with-values (lambda () (epoch-day->ymd (jt-floor-div (exact (truncate (now-ms))) 86400000))) - (lambda (y m d) (jt-year-month y m))))) - (cons "parse" (lambda (s . fmt) - (if (null? fmt) - (let ((str (jt-str s))) - (jt-year-month (or (digits-at str 0 4) (error #f "could not parse YearMonth")) - (or (digits-at str 5 2) (error #f "could not parse YearMonth")))) - (call-with-values (lambda () (formatter-parse-fields (car fmt) s)) - (lambda (ed nod) (call-with-values (lambda () (epoch-day->ymd ed)) (lambda (y m d) (jt-year-month y m)))))))) - (cons "from" (lambda (t) (ym-from-temporal t))))) -(register-host-methods! "year-month" - (list (cons "getYear" (lambda (x) (ym-year x))) - (cons "getMonthValue" (lambda (x) (ym-month x))) - (cons "getMonth" (lambda (x) (jt-month (ym-month x)))) - (cons "lengthOfMonth" (lambda (x) (jt-len-of-month (ym-year x) (ym-month x)))) - (cons "lengthOfYear" (lambda (x) (if (jt-leap? (ym-year x)) 366 365))) - (cons "isLeapYear" (lambda (x) (jt-leap? (ym-year x)))) - (cons "plusMonths" (lambda (x n) (ym-plus-months x (jt->exact n)))) - (cons "minusMonths" (lambda (x n) (ym-plus-months x (- (jt->exact n))))) - (cons "plusYears" (lambda (x n) (jt-year-month (+ (ym-year x) (jt->exact n)) (ym-month x)))) - (cons "minusYears" (lambda (x n) (jt-year-month (- (ym-year x) (jt->exact n)) (ym-month x)))) - (cons "withYear" (lambda (x v) (jt-year-month (jt->exact v) (ym-month x)))) - (cons "withMonth" (lambda (x v) (jt-year-month (ym-year x) (jt->exact v)))) - (cons "atDay" (lambda (x d) (jt-local-date (ymd->epoch-day (ym-year x) (ym-month x) (jt->exact d))))) - (cons "atEndOfMonth" (lambda (x) (jt-local-date (ymd->epoch-day (ym-year x) (ym-month x) (jt-len-of-month (ym-year x) (ym-month x)))))) - (cons "isValidDay" (lambda (x d) (let ((dd (jt->exact d))) (and (>= dd 1) (<= dd (jt-len-of-month (ym-year x) (ym-month x))))))) - (cons "isBefore" (lambda (x o) (< (ym-cmp x o) 0))) - (cons "isAfter" (lambda (x o) (> (ym-cmp x o) 0))) - (cons "compareTo" (lambda (x o) (ym-cmp x o))) - (cons "equals" (lambda (x o) (and (jhost? o) (string=? (jhost-tag o) "year-month") (= (ym-cmp x o) 0)))) - (cons "hashCode" (lambda (x) (+ (* (ym-year x) 13) (ym-month x)))) - (cons "toString" (lambda (x) (ym->string x))))) -(define (ym-cmp x o) - (cond ((< (ym-year x) (ym-year o)) -1) ((> (ym-year x) (ym-year o)) 1) - ((< (ym-month x) (ym-month o)) -1) ((> (ym-month x) (ym-month o)) 1) (else 0))) - -;; --- ChronoUnit / ChronoField ------------------------------------------------ -;; Each ChronoUnit is a jhost (vector name nanos-or-#f) — nanos is the fixed -;; duration in nanoseconds for time-based units, or an estimate for date-based ones. -;; The conversion lets Duration/of and unit-based between/plus/until work. -(define seconds-per-year (* (/ 146097 400) 86400)) ; 365.2425 days -(define chrono-unit-table - ;; (name . nanos-per-unit) month/year use the average-length estimate java.time uses. - (list (cons "NANOS" 1) - (cons "MICROS" 1000) - (cons "MILLIS" 1000000) - (cons "SECONDS" nanos-per-sec) - (cons "MINUTES" (* 60 nanos-per-sec)) - (cons "HOURS" (* 3600 nanos-per-sec)) - (cons "HALF_DAYS" (* 43200 nanos-per-sec)) - (cons "DAYS" (* 86400 nanos-per-sec)) - (cons "WEEKS" (* 7 86400 nanos-per-sec)) - (cons "MONTHS" (exact (round (* (/ seconds-per-year 12) nanos-per-sec)))) - (cons "YEARS" (exact (round (* seconds-per-year nanos-per-sec)))) - (cons "DECADES" (exact (round (* 10 seconds-per-year nanos-per-sec)))) - (cons "CENTURIES" (exact (round (* 100 seconds-per-year nanos-per-sec)))) - (cons "MILLENNIA" (exact (round (* 1000 seconds-per-year nanos-per-sec)))) - (cons "ERAS" (exact (round (* 1000000000 seconds-per-year nanos-per-sec)))) - (cons "FOREVER" #f))) -(define (jt-chrono-unit name) (make-jhost "chrono-unit" (vector name))) -(define (cu-name u) (vector-ref (jhost-state u) 0)) -(define (chrono-unit-nanos u) - (let* ((nm (chrono-unit-name u)) (row (and nm (assoc (string-upcase nm) chrono-unit-table)))) - (if (and row (cdr row)) (cdr row) (error #f (string-append "no fixed duration for unit " (or nm "?")))))) -;; register the 16 unit constants under ChronoUnit statics. -(register-class-statics! "ChronoUnit" - (append - (map (lambda (row) (cons (car row) (jt-chrono-unit (car row)))) chrono-unit-table) - (list (cons "valueOf" (lambda (s) (jt-chrono-unit (jt-str s)))) - (cons "values" (lambda () (make-pvec (list->vector (map (lambda (r) (jt-chrono-unit (car r))) chrono-unit-table)))))))) -(register-host-methods! "chrono-unit" - (list (cons "name" (lambda (u) (cu-name u))) - (cons "toString" (lambda (u) (cu-name u))) - (cons "ordinal" (lambda (u) (let loop ((t chrono-unit-table) (i 0)) - (cond ((null? t) -1) ((string=? (caar t) (cu-name u)) i) (else (loop (cdr t) (+ i 1))))))) - (cons "getDuration" (lambda (u) (dur-of-total-nanos (chrono-unit-nanos u)))) - (cons "isDateBased" (lambda (u) (and (member (cu-name u) '("DAYS" "WEEKS" "MONTHS" "YEARS" "DECADES" "CENTURIES" "MILLENNIA" "ERAS")) #t))) - (cons "isTimeBased" (lambda (u) (and (member (cu-name u) '("NANOS" "MICROS" "MILLIS" "SECONDS" "MINUTES" "HOURS" "HALF_DAYS")) #t))) - (cons "isDurationEstimated" (lambda (u) (and (member (cu-name u) '("DAYS" "WEEKS" "MONTHS" "YEARS" "DECADES" "CENTURIES" "MILLENNIA" "ERAS" "FOREVER")) #t))) - (cons "between" (lambda (u a b) (unit-between (cu-name u) a b))) - (cons "addTo" (lambda (u t n) (temporal-plus-unit t (jt->exact n) (cu-name u)))) - (cons "equals" (lambda (u o) (and (jhost? o) (string=? (jhost-tag o) "chrono-unit") (string=? (cu-name u) (cu-name o))))) - (cons "hashCode" (lambda (u) (string-hash (cu-name u)))))) - -;; ChronoField: a jhost (vector name). get/getLong/with project the field onto a -;; temporal via the field-projection table below. -;; the full ChronoField enum (the cljc wrapper defs every constant at load). Only -;; the common ones are projected by temporal-get-field; the rest exist as tokens. -(define chrono-field-names - '("NANO_OF_SECOND" "NANO_OF_DAY" "MICRO_OF_SECOND" "MICRO_OF_DAY" "MILLI_OF_SECOND" "MILLI_OF_DAY" - "SECOND_OF_MINUTE" "SECOND_OF_DAY" "MINUTE_OF_HOUR" "MINUTE_OF_DAY" - "HOUR_OF_AMPM" "CLOCK_HOUR_OF_AMPM" "HOUR_OF_DAY" "CLOCK_HOUR_OF_DAY" "AMPM_OF_DAY" - "DAY_OF_WEEK" "ALIGNED_DAY_OF_WEEK_IN_MONTH" "ALIGNED_DAY_OF_WEEK_IN_YEAR" - "DAY_OF_MONTH" "DAY_OF_YEAR" "EPOCH_DAY" - "ALIGNED_WEEK_OF_MONTH" "ALIGNED_WEEK_OF_YEAR" - "MONTH_OF_YEAR" "PROLEPTIC_MONTH" "YEAR_OF_ERA" "YEAR" "ERA" - "INSTANT_SECONDS" "OFFSET_SECONDS")) -(define (jt-chrono-field name) (make-jhost "chrono-field" (vector name))) -(define (cf-name f) (vector-ref (jhost-state f) 0)) -(register-class-statics! "ChronoField" - (append - (map (lambda (n) (cons n (jt-chrono-field n))) chrono-field-names) - (list (cons "valueOf" (lambda (s) (jt-chrono-field (jt-str s)))) - (cons "values" (lambda () (make-pvec (list->vector (map jt-chrono-field chrono-field-names)))))))) -(register-host-methods! "chrono-field" - (list (cons "name" (lambda (f) (cf-name f))) - (cons "toString" (lambda (f) (cf-name f))) - (cons "getDisplayName" (lambda (f . _) (cf-name f))) - (cons "isDateBased" (lambda (f) (and (member (cf-name f) '("DAY_OF_WEEK" "DAY_OF_MONTH" "DAY_OF_YEAR" "EPOCH_DAY" "MONTH_OF_YEAR" "PROLEPTIC_MONTH" "YEAR_OF_ERA" "YEAR" "ERA")) #t))) - (cons "isTimeBased" (lambda (f) (not (member (cf-name f) '("DAY_OF_WEEK" "DAY_OF_MONTH" "DAY_OF_YEAR" "EPOCH_DAY" "MONTH_OF_YEAR" "PROLEPTIC_MONTH" "YEAR_OF_ERA" "YEAR" "ERA" "INSTANT_SECONDS" "OFFSET_SECONDS"))))) - (cons "getFrom" (lambda (f t) (temporal-get-field t (cf-name f)))) - (cons "equals" (lambda (f o) (and (jhost? o) (string=? (jhost-tag o) "chrono-field") (string=? (cf-name f) (cf-name o))))) - (cons "hashCode" (lambda (f) (string-hash (cf-name f)))))) - -;; --- ValueRange (minimal min/max holder) ------------------------------------- -(define (jt-value-range smin lmin smax lmax) (make-jhost "value-range" (vector smin lmin smax lmax))) -(register-host-methods! "value-range" - (list (cons "getMinimum" (lambda (r) (vector-ref (jhost-state r) 1))) - (cons "getLargestMinimum" (lambda (r) (vector-ref (jhost-state r) 1))) - (cons "getSmallestMaximum" (lambda (r) (vector-ref (jhost-state r) 2))) - (cons "getMaximum" (lambda (r) (vector-ref (jhost-state r) 3))) - (cons "isFixed" (lambda (r) (and (= (vector-ref (jhost-state r) 0) (vector-ref (jhost-state r) 1)) - (= (vector-ref (jhost-state r) 2) (vector-ref (jhost-state r) 3))))) - (cons "isValidValue" (lambda (r v) (let ((x (jt->exact v))) (and (>= x (vector-ref (jhost-state r) 1)) (<= x (vector-ref (jhost-state r) 3)))))) - (cons "toString" (lambda (r) (string-append (number->string (vector-ref (jhost-state r) 1)) " - " (number->string (vector-ref (jhost-state r) 3))))))) - -;; --- temporal field/unit machinery: plus/minus/until/get/with on core types -- -;; These power the generic cljc.java-time.temporal dispatchers, which forward to -;; the receiver's plus/minus/until/get/getLong/with/range/isSupported. - -;; add n of `unit` to a temporal (local-date / local-time / local-date-time / instant). -(define (temporal-plus-unit t n unit) - (let ((u (string-upcase unit))) - (cond - ((jt-date? t) - (cond ((string=? u "DAYS") (jt-local-date (+ (ld-epoch-day t) n))) - ((string=? u "WEEKS") (jt-local-date (+ (ld-epoch-day t) (* 7 n)))) - ((string=? u "MONTHS") (ld-plus-months t n)) - ((string=? u "YEARS") (ld-plus-years t n)) - ((string=? u "DECADES") (ld-plus-years t (* 10 n))) - ((string=? u "CENTURIES") (ld-plus-years t (* 100 n))) - ((string=? u "MILLENNIA") (ld-plus-years t (* 1000 n))) - (else (error #f (string-append "LocalDate plus unsupported unit " u))))) - ((jt-time? t) (lt-plus t (* n (chrono-unit-nanos (jt-chrono-unit u))))) - ((jt-dt? t) - (cond ((string=? u "DAYS") (jt-local-dt (+ (ldt-epoch-day t) n) (ldt-nano-of-day t))) - ((string=? u "WEEKS") (jt-local-dt (+ (ldt-epoch-day t) (* 7 n)) (ldt-nano-of-day t))) - ((string=? u "MONTHS") (ldt-combine (ld-plus-months (ldt-date t) n) (ldt-time t))) - ((string=? u "YEARS") (ldt-combine (ld-plus-years (ldt-date t) n) (ldt-time t))) - ((string=? u "DECADES") (ldt-combine (ld-plus-years (ldt-date t) (* 10 n)) (ldt-time t))) - ((string=? u "CENTURIES") (ldt-combine (ld-plus-years (ldt-date t) (* 100 n)) (ldt-time t))) - ((string=? u "MILLENNIA") (ldt-combine (ld-plus-years (ldt-date t) (* 1000 n)) (ldt-time t))) - (else (ldt-plus-nanos t (* n (chrono-unit-nanos (jt-chrono-unit u))))))) - ((jt-instant? t) - (cond ((string=? u "DAYS") (mk-instant-nanos (+ (inst-nanos t) (* n 86400 nanos-per-sec)))) - (else (mk-instant-nanos (+ (inst-nanos t) (* n (chrono-unit-nanos (jt-chrono-unit u)))))))) - (else (error #f "plus: unsupported temporal"))))) - -;; add raw nanos (for Duration.addTo). -(define (temporal-plus-nanos t nanos) - (cond ((jt-time? t) (lt-plus t nanos)) - ((jt-dt? t) (ldt-plus-nanos t nanos)) - ((jt-instant? t) (mk-instant-nanos (+ (inst-nanos t) nanos))) - ((jt-date? t) (jt-local-date (+ (ld-epoch-day t) (quotient nanos (* 86400 nanos-per-sec))))) - (else (error #f "plus(Duration): unsupported temporal")))) - -;; add a Period (scaled by sign) to a date-bearing temporal. -(define (temporal-plus-period t p sign) - (let ((y (* sign (per-years p))) (m (* sign (per-months p))) (d (* sign (per-days p)))) - (cond ((jt-date? t) (jt-local-date (+ (ld-epoch-day (ld-plus-months (ld-plus-years t y) m)) d))) - ((jt-dt? t) (let ((nd (ld-plus-months (ld-plus-years (ldt-date t) y) m))) - (jt-local-dt (+ (ld-epoch-day nd) d) (ldt-nano-of-day t)))) - (else (error #f "plus(Period): unsupported temporal"))))) - -;; count whole `unit`s from a to b. -(define (unit-between unit a b) - (let ((u (string-upcase unit))) - (cond - ((and (jt-date? a) (jt-date? b)) - (let ((da (ld-epoch-day a)) (db (ld-epoch-day b))) - (cond ((string=? u "DAYS") (- db da)) - ((string=? u "WEEKS") (quotient (- db da) 7)) - ((string=? u "MONTHS") (date-months-between da db)) - ((string=? u "YEARS") (quotient (date-months-between da db) 12)) - ((string=? u "DECADES") (quotient (date-months-between da db) 120)) - ((string=? u "CENTURIES") (quotient (date-months-between da db) 1200)) - (else (error #f (string-append "between unsupported unit " u)))))) - ((and (jt-time? a) (jt-time? b)) (quotient (- (lt-nano-of-day b) (lt-nano-of-day a)) (chrono-unit-nanos (jt-chrono-unit u)))) - ((and (jt-dt? a) (jt-dt? b)) - (cond ((member u '("YEARS" "MONTHS" "DECADES" "CENTURIES" "MILLENNIA")) - (unit-between u (ldt-date a) (ldt-date b))) ; date-based: ignore time-of-day below months on LDT? use date months adjusted - (else (quotient (- (+ (* (ldt-epoch-day b) nanos-per-day) (ldt-nano-of-day b)) - (+ (* (ldt-epoch-day a) nanos-per-day) (ldt-nano-of-day a))) - (chrono-unit-nanos (jt-chrono-unit u)))))) - ((and (jt-instant? a) (jt-instant? b)) - (quotient (- (inst-nanos b) (inst-nanos a)) (chrono-unit-nanos (jt-chrono-unit u)))) - (else (error #f "between: unsupported temporals"))))) -;; whole months between two epoch-days (java.time: months, then -1 if day-of-month -;; of b hasn't reached a's). -(define (date-months-between da db) - (call-with-values (lambda () (epoch-day->ymd da)) - (lambda (y1 m1 d1) - (call-with-values (lambda () (epoch-day->ymd db)) - (lambda (y2 m2 d2) - (let ((months (- (+ (* y2 12) m2) (+ (* y1 12) m1)))) - (cond ((and (> months 0) (< d2 d1)) (- months 1)) - ((and (< months 0) (> d2 d1)) (+ months 1)) - (else months)))))))) - -;; field get: project a ChronoField onto a temporal. -(define (temporal-get-field t field) - (let ((f (string-upcase field))) - (cond - ((jt-date? t) - (call-with-values (lambda () (epoch-day->ymd (ld-epoch-day t))) - (lambda (y m d) - (cond ((string=? f "YEAR") y) ((string=? f "MONTH_OF_YEAR") m) ((string=? f "DAY_OF_MONTH") d) - ((string=? f "DAY_OF_WEEK") (ld-dow (ld-epoch-day t))) - ((string=? f "DAY_OF_YEAR") (ld-day-of-year (ld-epoch-day t))) - ((string=? f "EPOCH_DAY") (ld-epoch-day t)) - ((string=? f "PROLEPTIC_MONTH") (+ (* y 12) (- m 1))) - ((string=? f "YEAR_OF_ERA") (if (>= y 1) y (- 1 y))) - ((string=? f "ERA") (if (>= y 1) 1 0)) - ;; aligned-* group the day-of-month/year into 7-day blocks from the - ;; 1st (java.time): the within-block weekday is ((n-1) mod 7)+1, the - ;; block number is ((n-1) quotient 7)+1. - ((string=? f "ALIGNED_DAY_OF_WEEK_IN_MONTH") (+ (modulo (- d 1) 7) 1)) - ((string=? f "ALIGNED_WEEK_OF_MONTH") (+ (quotient (- d 1) 7) 1)) - ((string=? f "ALIGNED_DAY_OF_WEEK_IN_YEAR") - (+ (modulo (- (ld-day-of-year (ld-epoch-day t)) 1) 7) 1)) - ((string=? f "ALIGNED_WEEK_OF_YEAR") - (+ (quotient (- (ld-day-of-year (ld-epoch-day t)) 1) 7) 1)) - (else (error #f (string-append "LocalDate has no field " f))))))) - ((jt-time? t) - (cond ((string=? f "HOUR_OF_DAY") (lt-hour t)) ((string=? f "MINUTE_OF_HOUR") (lt-minute t)) - ((string=? f "SECOND_OF_MINUTE") (lt-second t)) ((string=? f "NANO_OF_SECOND") (lt-nano t)) - ((string=? f "NANO_OF_DAY") (lt-nano-of-day t)) - ((string=? f "MILLI_OF_DAY") (quotient (lt-nano-of-day t) 1000000)) - ((string=? f "MICRO_OF_DAY") (quotient (lt-nano-of-day t) 1000)) - ((string=? f "SECOND_OF_DAY") (quotient (lt-nano-of-day t) nanos-per-sec)) - ((string=? f "MINUTE_OF_DAY") (quotient (lt-nano-of-day t) (* 60 nanos-per-sec))) - ((string=? f "MILLI_OF_SECOND") (quotient (lt-nano t) 1000000)) - ((string=? f "MICRO_OF_SECOND") (quotient (lt-nano t) 1000)) - ;; CLOCK_HOUR_OF_DAY is 1..24 (midnight is 24), HOUR_OF_AMPM 0..11, - ;; CLOCK_HOUR_OF_AMPM 1..12, AMPM_OF_DAY 0 (AM) / 1 (PM). - ((string=? f "CLOCK_HOUR_OF_DAY") (let ((h (lt-hour t))) (if (= h 0) 24 h))) - ((string=? f "HOUR_OF_AMPM") (modulo (lt-hour t) 12)) - ((string=? f "CLOCK_HOUR_OF_AMPM") (let ((h (modulo (lt-hour t) 12))) (if (= h 0) 12 h))) - ((string=? f "AMPM_OF_DAY") (quotient (lt-hour t) 12)) - (else (error #f (string-append "LocalTime has no field " f))))) - ((jt-dt? t) - ;; route a field to whichever part supports it (date fields incl. the - ;; aligned-* group to the date, the rest to the time). - (if (temporal-supports-field? (ldt-date t) f) - (temporal-get-field (ldt-date t) f) - (temporal-get-field (ldt-time t) f))) - ((jt-instant? t) - (cond ((string=? f "INSTANT_SECONDS") (jt-floor-div (inst-nanos t) nanos-per-sec)) - ((string=? f "NANO_OF_SECOND") (jt-floor-mod (inst-nanos t) nanos-per-sec)) - ((string=? f "MILLI_OF_SECOND") (jt-floor-div (jt-floor-mod (inst-nanos t) nanos-per-sec) 1000000)) - ((string=? f "MICRO_OF_SECOND") (jt-floor-div (jt-floor-mod (inst-nanos t) nanos-per-sec) 1000)) - (else (error #f (string-append "Instant has no field " f))))) - ((and (jhost? t) (string=? (jhost-tag t) "year")) - (let ((y (year-val t))) - (cond ((string=? f "YEAR") y) ((string=? f "YEAR_OF_ERA") (if (>= y 1) y (- 1 y))) - ((string=? f "ERA") (if (>= y 1) 1 0)) - (else (error #f (string-append "Year has no field " f)))))) - ((and (jhost? t) (string=? (jhost-tag t) "year-month")) - (let ((y (ym-year t)) (m (ym-month t))) - (cond ((string=? f "YEAR") y) ((string=? f "MONTH_OF_YEAR") m) - ((string=? f "PROLEPTIC_MONTH") (+ (* y 12) (- m 1))) - ((string=? f "YEAR_OF_ERA") (if (>= y 1) y (- 1 y))) ((string=? f "ERA") (if (>= y 1) 1 0)) - (else (error #f (string-append "YearMonth has no field " f)))))) - (else (error #f "get(field): unsupported temporal"))))) - -;; field set: (with temporal ChronoField value) -> a new temporal. -(define (temporal-with-field t field v) - (let ((f (string-upcase field))) - (cond - ((jt-date? t) - (cond ((string=? f "YEAR") (ld-with-field t 'year v)) ((string=? f "MONTH_OF_YEAR") (ld-with-field t 'month v)) - ((string=? f "DAY_OF_MONTH") (ld-with-field t 'day v)) ((string=? f "DAY_OF_YEAR") (ld-with-field t 'day-of-year v)) - ((string=? f "EPOCH_DAY") (jt-local-date v)) - (else (error #f (string-append "LocalDate.with unsupported field " f))))) - ((jt-time? t) - (cond ((string=? f "HOUR_OF_DAY") (lt-with t 'hour v)) ((string=? f "MINUTE_OF_HOUR") (lt-with t 'minute v)) - ((string=? f "SECOND_OF_MINUTE") (lt-with t 'second v)) ((string=? f "NANO_OF_SECOND") (lt-with t 'nano v)) - ((string=? f "NANO_OF_DAY") (jt-local-time v)) - (else (error #f (string-append "LocalTime.with unsupported field " f))))) - ((jt-dt? t) - (if (member f '("YEAR" "MONTH_OF_YEAR" "DAY_OF_MONTH" "DAY_OF_YEAR" "EPOCH_DAY")) - (ldt-combine (temporal-with-field (ldt-date t) f v) (ldt-time t)) - (ldt-combine (ldt-date t) (temporal-with-field (ldt-time t) f v)))) - (else (error #f "with(field): unsupported temporal"))))) - -(define (temporal-supports-unit? t unit) - (let ((u (string-upcase unit))) - (cond ((jt-date? t) (and (member u '("DAYS" "WEEKS" "MONTHS" "YEARS" "DECADES" "CENTURIES" "MILLENNIA" "ERAS")) #t)) - ((jt-time? t) (and (member u '("NANOS" "MICROS" "MILLIS" "SECONDS" "MINUTES" "HOURS" "HALF_DAYS")) #t)) - ((or (jt-dt? t) (jt-instant? t)) (not (member u '("FOREVER")))) - (else #f)))) -(define (temporal-supports-field? t field) - (let ((f (string-upcase field))) - (cond ((jt-date? t) (and (member f '("YEAR" "MONTH_OF_YEAR" "DAY_OF_MONTH" "DAY_OF_WEEK" "DAY_OF_YEAR" "EPOCH_DAY" "PROLEPTIC_MONTH" "YEAR_OF_ERA" "ERA" - "ALIGNED_DAY_OF_WEEK_IN_MONTH" "ALIGNED_DAY_OF_WEEK_IN_YEAR" "ALIGNED_WEEK_OF_MONTH" "ALIGNED_WEEK_OF_YEAR")) #t)) - ((jt-time? t) (and (member f '("HOUR_OF_DAY" "CLOCK_HOUR_OF_DAY" "HOUR_OF_AMPM" "CLOCK_HOUR_OF_AMPM" "AMPM_OF_DAY" - "MINUTE_OF_HOUR" "MINUTE_OF_DAY" "SECOND_OF_MINUTE" "SECOND_OF_DAY" - "MILLI_OF_SECOND" "MILLI_OF_DAY" "MICRO_OF_SECOND" "MICRO_OF_DAY" - "NANO_OF_SECOND" "NANO_OF_DAY")) #t)) - ((jt-dt? t) (or (temporal-supports-field? (ldt-date t) field) (temporal-supports-field? (ldt-time t) field))) - ((jt-instant? t) (and (member f '("INSTANT_SECONDS" "NANO_OF_SECOND" "MILLI_OF_SECOND" "MICRO_OF_SECOND")) #t)) - ((and (jhost? t) (string=? (jhost-tag t) "year")) (and (member f '("YEAR" "YEAR_OF_ERA" "ERA")) #t)) - ((and (jhost? t) (string=? (jhost-tag t) "year-month")) - (and (member f '("YEAR" "MONTH_OF_YEAR" "PROLEPTIC_MONTH" "YEAR_OF_ERA" "ERA")) #t)) - (else #f)))) - -;; isSupported / get / getLong / with / range / plus / minus / until accept a -;; chrono-unit OR chrono-field jhost (or a string). These method names extend the -;; existing per-tag tables. -(define (unit-or-field-arg x) x) -(define (arg-is-unit? x) (and (jhost? x) (string=? (jhost-tag x) "chrono-unit"))) -(define (arg-is-field? x) (and (jhost? x) (string=? (jhost-tag x) "chrono-field"))) -(define (arg-is-amount? x) (and (jhost? x) (member (jhost-tag x) '("duration" "period")))) -(define (arg-unit-name x) (cond ((arg-is-unit? x) (cu-name x)) ((string? x) x) ((keyword? x) (keyword-t-name x)) (else #f))) -(define (arg-field-name x) (cond ((arg-is-field? x) (cf-name x)) ((string? x) x) ((keyword? x) (keyword-t-name x)) (else #f))) - -;; the generic plus/minus/until/get/getLong/with/range/isSupported, shared by all -;; four core tags. plus/minus accept (n unit) or (amount); with accepts (field val). -(define (mk-temporal-methods) - (list - (cons "plus" (case-lambda - ((t a) (cond ((arg-is-amount? a) (if (string=? (jhost-tag a) "duration") - (temporal-plus-nanos t (dur-total-nanos a)) - (temporal-plus-period t a 1))) - (else (error #f "plus: bad amount")))) - ((t n u) (temporal-plus-unit t (jt->exact n) (arg-unit-name u))))) - (cons "minus" (case-lambda - ((t a) (cond ((arg-is-amount? a) (if (string=? (jhost-tag a) "duration") - (temporal-plus-nanos t (- (dur-total-nanos a))) - (temporal-plus-period t a -1))) - (else (error #f "minus: bad amount")))) - ((t n u) (temporal-plus-unit t (- (jt->exact n)) (arg-unit-name u))))) - (cons "until" (lambda (t o u) (unit-between (arg-unit-name u) t o))) - (cons "get" (lambda (t f) (temporal-get-field t (arg-field-name f)))) - (cons "getLong" (lambda (t f) (temporal-get-field t (arg-field-name f)))) - (cons "with" (case-lambda - ((t adj) (apply-adjuster t adj)) ; (.with t adjuster) - ((t f v) (temporal-with-field t (arg-field-name f) (jt->exact v))))) - (cons "isSupported" (lambda (t x) (cond ((arg-is-unit? x) (temporal-supports-unit? t (cu-name x))) - ((arg-is-field? x) (temporal-supports-field? t (cf-name x))) - (else #f)))) - (cons "range" (lambda (t f) (temporal-range t (arg-field-name f)))))) -(register-host-methods! "local-date" (mk-temporal-methods)) -(register-host-methods! "local-time" (mk-temporal-methods)) -(register-host-methods! "local-date-time" (mk-temporal-methods)) -;; Year/YearMonth answer the field accessors too (a fields-over-all-temporals walk -;; queries them); their own plus/minus/with stay the specific methods above. -(let ((field-methods - (list (cons "isSupported" (lambda (t x) (cond ((arg-is-unit? x) (temporal-supports-unit? t (cu-name x))) - ((arg-is-field? x) (temporal-supports-field? t (cf-name x))) - (else #f)))) - (cons "get" (lambda (t f) (temporal-get-field t (arg-field-name f)))) - (cons "getLong" (lambda (t f) (temporal-get-field t (arg-field-name f))))))) - (register-host-methods! "year" field-methods) - (register-host-methods! "year-month" field-methods)) -(register-host-methods! "instant" (mk-temporal-methods)) - -;; --- TemporalAdjuster: a date->date transform applied via (.with t adjuster) -- -;; Stored as a jhost over a procedure that takes/returns a LocalDate; for a -;; LocalDateTime the date part is adjusted and the time kept. -(define (jt-adjuster proc) (make-jhost "temporal-adjuster" (vector proc))) -(define (adjuster-proc a) (vector-ref (jhost-state a) 0)) -(define (apply-adjuster t adj) - (let ((proc (cond ((and (jhost? adj) (string=? (jhost-tag adj) "temporal-adjuster")) (adjuster-proc adj)) - ((procedure? adj) adj) - (else (error #f "with: expected a TemporalAdjuster"))))) - (cond ((jt-date? t) (proc t)) - ((jt-dt? t) (ldt-combine (proc (ldt-date t)) (ldt-time t))) - (else (proc t))))) -;; the next/previous day-of-week adjusters (dow target 1=Mon..7=Sun). -(define (adj-next-dow d target same?) - (let* ((cur (ld-dow (ld-epoch-day d))) - (delta (jt-floor-mod (- target cur) 7)) - (step (if (and same? (= delta 0)) 0 (if (= delta 0) 7 delta)))) - (jt-local-date (+ (ld-epoch-day d) step)))) -(define (adj-prev-dow d target same?) - (let* ((cur (ld-dow (ld-epoch-day d))) - (delta (jt-floor-mod (- cur target) 7)) - (step (if (and same? (= delta 0)) 0 (if (= delta 0) 7 delta)))) - (jt-local-date (- (ld-epoch-day d) step)))) -(define (dow-target dow) (cond ((and (jhost? dow) (string=? (jhost-tag dow) "dow-enum")) (dow-val dow)) - (else (jt->exact dow)))) -(define (adj-first-day-of-month d) - (call-with-values (lambda () (epoch-day->ymd (ld-epoch-day d))) (lambda (y m dd) (jt-local-date (ymd->epoch-day y m 1))))) -(define (adj-last-day-of-month d) - (call-with-values (lambda () (epoch-day->ymd (ld-epoch-day d))) (lambda (y m dd) (jt-local-date (ymd->epoch-day y m (jt-len-of-month y m)))))) -(define (adj-day-of-week-in-month d ordinal target) - ;; the ordinal-th (1-based) `target` weekday in d's month (negative counts from end). - (call-with-values (lambda () (epoch-day->ymd (ld-epoch-day d))) - (lambda (y m dd) - (if (>= ordinal 0) - (let* ((first (jt-local-date (ymd->epoch-day y m 1))) - (first-match (adj-next-dow first target #t))) - (jt-local-date (+ (ld-epoch-day first-match) (* 7 (- (max 1 ordinal) 1))))) - (let* ((last (adj-last-day-of-month d)) - (last-match (adj-prev-dow last target #t))) - (jt-local-date (- (ld-epoch-day last-match) (* 7 (- (- ordinal) 1))))))))) -(register-class-statics! "TemporalAdjusters" - (list (cons "firstDayOfMonth" (lambda () (jt-adjuster adj-first-day-of-month))) - (cons "lastDayOfMonth" (lambda () (jt-adjuster adj-last-day-of-month))) - (cons "firstDayOfNextMonth" (lambda () (jt-adjuster (lambda (d) (jt-local-date (+ (ld-epoch-day (adj-last-day-of-month d)) 1)))))) - (cons "firstDayOfYear" (lambda () (jt-adjuster (lambda (d) (call-with-values (lambda () (epoch-day->ymd (ld-epoch-day d))) (lambda (y m dd) (jt-local-date (ymd->epoch-day y 1 1)))))))) - (cons "lastDayOfYear" (lambda () (jt-adjuster (lambda (d) (call-with-values (lambda () (epoch-day->ymd (ld-epoch-day d))) (lambda (y m dd) (jt-local-date (ymd->epoch-day y 12 31)))))))) - (cons "firstDayOfNextYear" (lambda () (jt-adjuster (lambda (d) (call-with-values (lambda () (epoch-day->ymd (ld-epoch-day d))) (lambda (y m dd) (jt-local-date (ymd->epoch-day (+ y 1) 1 1)))))))) - (cons "dayOfWeekInMonth" (lambda (ordinal dow) (jt-adjuster (lambda (d) (adj-day-of-week-in-month d (jt->exact ordinal) (dow-target dow)))))) - (cons "firstInMonth" (lambda (dow) (jt-adjuster (lambda (d) (adj-day-of-week-in-month d 1 (dow-target dow)))))) - (cons "lastInMonth" (lambda (dow) (jt-adjuster (lambda (d) (adj-day-of-week-in-month d -1 (dow-target dow)))))) - (cons "next" (lambda (dow) (jt-adjuster (lambda (d) (adj-next-dow d (dow-target dow) #f))))) - (cons "nextOrSame" (lambda (dow) (jt-adjuster (lambda (d) (adj-next-dow d (dow-target dow) #t))))) - (cons "previous" (lambda (dow) (jt-adjuster (lambda (d) (adj-prev-dow d (dow-target dow) #f))))) - (cons "previousOrSame" (lambda (dow) (jt-adjuster (lambda (d) (adj-prev-dow d (dow-target dow) #t))))) - (cons "ofDateAdjuster" (lambda (f) (jt-adjuster (lambda (d) (jolt-invoke f d))))))) -(register-host-methods! "temporal-adjuster" - (list (cons "adjustInto" (lambda (a t) (apply-adjuster t a))))) - -;; range(field): a ValueRange. A small set of common fields; others fall back to a -;; generous range so callers that only read min/max don't crash. -(define (temporal-range t field) - (let ((f (string-upcase field))) - (cond - ((and (jt-date? t) (string=? f "DAY_OF_MONTH")) - (jt-value-range 1 1 28 (call-with-values (lambda () (epoch-day->ymd (ld-epoch-day t))) (lambda (y m d) (jt-len-of-month y m))))) - ((string=? f "MONTH_OF_YEAR") (jt-value-range 1 1 12 12)) - ((string=? f "DAY_OF_WEEK") (jt-value-range 1 1 7 7)) - ((string=? f "HOUR_OF_DAY") (jt-value-range 0 0 23 23)) - ((string=? f "MINUTE_OF_HOUR") (jt-value-range 0 0 59 59)) - ((string=? f "SECOND_OF_MINUTE") (jt-value-range 0 0 59 59)) - ((string=? f "NANO_OF_SECOND") (jt-value-range 0 0 999999999 999999999)) - (else (jt-value-range 0 0 999999999999 999999999999))))) - -;; --- equality / hash / compare / print / instance? -------------------------- -(define (jt-date? x) (and (jhost? x) (string=? (jhost-tag x) "local-date"))) -(define (jt-time? x) (and (jhost? x) (string=? (jhost-tag x) "local-time"))) -(define (jt-dt? x) (and (jhost? x) (string=? (jhost-tag x) "local-date-time"))) - -(register-eq-arm! (lambda (a b) (or (jt-date? a) (jt-date? b))) - (lambda (a b) (and (jt-date? a) (jt-date? b) (= (ld-epoch-day a) (ld-epoch-day b))))) -(register-hash-arm! jt-date? (lambda (x) (jolt-hash (ld-epoch-day x)))) -(register-eq-arm! (lambda (a b) (or (jt-time? a) (jt-time? b))) - (lambda (a b) (and (jt-time? a) (jt-time? b) (= (lt-nano-of-day a) (lt-nano-of-day b))))) -(register-hash-arm! jt-time? (lambda (x) (jolt-hash (lt-nano-of-day x)))) -(register-eq-arm! (lambda (a b) (or (jt-dt? a) (jt-dt? b))) - (lambda (a b) (and (jt-dt? a) (jt-dt? b) (ldt=? a b)))) -(register-hash-arm! jt-dt? (lambda (x) (jolt-hash (+ (* (ldt-epoch-day x) 31) (ldt-nano-of-day x))))) - -(register-str-render! jt-date? (lambda (x) (iso-date-str (ld-epoch-day x)))) -(register-pr-arm! jt-date? (lambda (x) (iso-date-str (ld-epoch-day x)))) -(register-str-render! jt-time? (lambda (x) (iso-time-str (lt-nano-of-day x)))) -(register-pr-arm! jt-time? (lambda (x) (iso-time-str (lt-nano-of-day x)))) -(register-str-render! jt-dt? (lambda (x) (iso-datetime-str (ldt-epoch-day x) (ldt-nano-of-day x)))) -(register-pr-arm! jt-dt? (lambda (x) (iso-datetime-str (ldt-epoch-day x) (ldt-nano-of-day x)))) - -;; the "instant" jhost prints as a java.time ISO instant (…Z), not the bare record. -(define (jt-instant? x) (and (jhost? x) (string=? (jhost-tag x) "instant"))) -(register-str-render! jt-instant? (lambda (x) (iso-instant-str-nanos (inst-nanos x)))) -(register-pr-arm! jt-instant? (lambda (x) (iso-instant-str-nanos (inst-nanos x)))) - -;; Phase-2 value types: amounts, enums, and the chrono-unit/field tokens. Each -;; prints as its java.time toString and is = / hashed on its canonical state. -(define (jt-tagged? tag) (lambda (x) (and (jhost? x) (string=? (jhost-tag x) tag)))) -(define (register-jt-value! tag str-fn hash-fn) - (let ((pred (jt-tagged? tag))) - (register-str-render! pred str-fn) - (register-pr-arm! pred str-fn) - (register-eq-arm! (lambda (a b) (or (pred a) (pred b))) - (lambda (a b) (and (pred a) (pred b) (equal? (jhost-state a) (jhost-state b))))) - (register-hash-arm! pred hash-fn))) -(register-jt-value! "duration" dur->string (lambda (x) (jolt-hash (dur-total-nanos x)))) -(register-jt-value! "period" per->string (lambda (x) (jolt-hash (+ (per-years x) (per-months x) (per-days x))))) -(register-jt-value! "month-enum" (lambda (x) (month-name (month-val x))) (lambda (x) (jolt-hash (month-val x)))) -(register-jt-value! "dow-enum" (lambda (x) (dow-name (dow-val x))) (lambda (x) (jolt-hash (dow-val x)))) -(register-jt-value! "year" (lambda (x) (number->string (year-val x))) (lambda (x) (jolt-hash (year-val x)))) -(register-jt-value! "year-month" ym->string (lambda (x) (jolt-hash (+ (* (ym-year x) 13) (ym-month x))))) -(register-jt-value! "chrono-unit" cu-name (lambda (x) (jolt-hash (cu-name x)))) -(register-jt-value! "chrono-field" cf-name (lambda (x) (jolt-hash (cf-name x)))) - -;; compare: same-type java.time values compare on their canonical state. -(define %jt-prev-compare jolt-compare) -(set! jolt-compare - (lambda (a b) - (cond - ((and (jt-date? a) (jt-date? b)) (cond ((< (ld-epoch-day a) (ld-epoch-day b)) -1) ((> (ld-epoch-day a) (ld-epoch-day b)) 1) (else 0))) - ((and (jt-time? a) (jt-time? b)) (cond ((< (lt-nano-of-day a) (lt-nano-of-day b)) -1) ((> (lt-nano-of-day a) (lt-nano-of-day b)) 1) (else 0))) - ((and (jt-dt? a) (jt-dt? b)) (ldt-cmp a b)) - ((and (jt-instant? a) (jt-instant? b)) (cond ((< (inst-nanos a) (inst-nanos b)) -1) ((> (inst-nanos a) (inst-nanos b)) 1) (else 0))) - ((and (jt-tagged-as? a "duration") (jt-tagged-as? b "duration")) - (let ((x (dur-total-nanos a)) (y (dur-total-nanos b))) (cond ((< x y) -1) ((> x y) 1) (else 0)))) - ((and (jt-tagged-as? a "month-enum") (jt-tagged-as? b "month-enum")) (- (month-val a) (month-val b))) - ((and (jt-tagged-as? a "dow-enum") (jt-tagged-as? b "dow-enum")) (- (dow-val a) (dow-val b))) - ((and (jt-tagged-as? a "year") (jt-tagged-as? b "year")) - (let ((x (year-val a)) (y (year-val b))) (cond ((< x y) -1) ((> x y) 1) (else 0)))) - ((and (jt-tagged-as? a "year-month") (jt-tagged-as? b "year-month")) (ym-cmp a b)) - (else (%jt-prev-compare a b))))) -(define (jt-tagged-as? x tag) (and (jhost? x) (string=? (jhost-tag x) tag))) -(def-var! "clojure.core" "compare" jolt-compare) - -;; instance? for the three new tags (inst-time.ss already answers "instant"). -(register-instance-check-arm! - (lambda (type-sym val) - (let ((tn (short-class-name (symbol-t-name type-sym)))) - (cond - ((jt-date? val) (if (string=? tn "LocalDate") #t 'pass)) - ((jt-time? val) (if (string=? tn "LocalTime") #t 'pass)) - ((jt-dt? val) (if (string=? tn "LocalDateTime") #t 'pass)) - ((jt-tagged-as? val "duration") (if (member tn '("Duration" "TemporalAmount")) #t 'pass)) - ((jt-tagged-as? val "period") (if (member tn '("Period" "TemporalAmount")) #t 'pass)) - ((jt-tagged-as? val "month-enum") (if (string=? tn "Month") #t 'pass)) - ((jt-tagged-as? val "dow-enum") (if (string=? tn "DayOfWeek") #t 'pass)) - ((jt-tagged-as? val "year") (if (string=? tn "Year") #t 'pass)) - ((jt-tagged-as? val "year-month") (if (string=? tn "YearMonth") #t 'pass)) - ((jt-tagged-as? val "chrono-unit") (if (member tn '("ChronoUnit" "TemporalUnit")) #t 'pass)) - ((jt-tagged-as? val "chrono-field") (if (member tn '("ChronoField" "TemporalField")) #t 'pass)) - (else 'pass))))) - -;; ==================================================================== -;; Phase 3: zones, offset/zoned date-times, clocks, formatter integration. -;; ==================================================================== -;; -;; Chez exposes local + UTC + fixed offsets, not an IANA tz database. Fixed-offset -;; and UTC zones are exact. A named zone (America/New_York) maps to a representative -;; fixed offset from a small table; arbitrary-instant DST transitions are NOT modeled. -;; -;; zone-offset (vector total-seconds) -;; zone-id (vector id offset-seconds) offset-seconds: resolved fixed offset -;; offset-time (vector nano-of-day offset-seconds) -;; offset-date-time (vector epoch-day nano-of-day offset-seconds) -;; zoned-date-time (vector epoch-day nano-of-day offset-seconds zone-id) -;; clock (vector kind fixed-ms zone-id [base-clock]) kind: 'system | 'fixed | 'offset | 'tick - -;; --- ZoneOffset -------------------------------------------------------------- -(define (jt-zone-offset secs) (make-jhost "zone-offset" (vector secs))) -(define (zo-secs z) (vector-ref (jhost-state z) 0)) -(define (jt-zone-offset? x) (and (jhost? x) (string=? (jhost-tag x) "zone-offset"))) -;; ZoneOffset id: "Z" for 0, else ±HH:mm[:ss] with the seconds field elided at :00. -(define (zo-id secs) - (if (= secs 0) "Z" - (let* ((neg (< secs 0)) (a (abs secs)) - (h (quotient a 3600)) (m (quotient (modulo a 3600) 60)) (s (modulo a 60))) - (string-append (if neg "-" "+") (pad2 h) ":" (pad2 m) - (if (= s 0) "" (string-append ":" (pad2 s))))))) -;; parse a ZoneOffset id: "Z"/"+00:00" -> 0, "+HH:mm[:ss]" / "+HHmm" / "+HH". -(define (parse-zone-offset s) - (let ((str (jt-str s))) - (cond - ((or (string=? str "Z") (string=? str "z") (string=? str "UTC") (string=? str "GMT") (string=? str "+00:00")) 0) - (else - (let* ((sign (cond ((char=? (string-ref str 0) #\-) -1) (else 1))) - (body (if (memv (string-ref str 0) '(#\+ #\-)) (substring str 1 (string-length str)) str)) - (parts (let loop ((i 0) (cur '()) (acc '())) - (cond ((>= i (string-length body)) - (reverse (cons (list->string (reverse cur)) acc))) - ((char=? (string-ref body i) #\:) (loop (+ i 1) '() (cons (list->string (reverse cur)) acc))) - (else (loop (+ i 1) (cons (string-ref body i) cur) acc)))))) - (if (and (= (length parts) 1) (> (string-length (car parts)) 2)) - ;; "+HHmm" / "+HHmmss" compact form - (let ((b (car parts))) - (* sign (+ (* (or (string->number (substring b 0 2)) 0) 3600) - (* (if (>= (string-length b) 4) (or (string->number (substring b 2 4)) 0) 0) 60) - (if (>= (string-length b) 6) (or (string->number (substring b 4 6)) 0) 0)))) - (* sign (+ (* (or (string->number (list-ref parts 0)) 0) 3600) - (* (if (> (length parts) 1) (or (string->number (list-ref parts 1)) 0) 0) 60) - (if (> (length parts) 2) (or (string->number (list-ref parts 2)) 0) 0))))))))) - -(register-class-statics! "ZoneOffset" - (list (cons "of" (lambda (s) (jt-zone-offset (parse-zone-offset s)))) - (cons "ofTotalSeconds" (lambda (n) (jt-zone-offset (jt->exact n)))) - (cons "ofHours" (lambda (h) (jt-zone-offset (* (jt->exact h) 3600)))) - ;; java.time requires h/m/s to share a sign; the total is the plain sum. - (cons "ofHoursMinutes" (lambda (h m) (jt-zone-offset (+ (* (jt->exact h) 3600) (* (jt->exact m) 60))))) - (cons "ofHoursMinutesSeconds" (lambda (h m s) (jt-zone-offset (+ (* (jt->exact h) 3600) (* (jt->exact m) 60) (jt->exact s))))) - (cons "from" (lambda (t) (cond ((jt-zone-offset? t) t) - ((jt-offset-dt? t) (jt-zone-offset (odt-offset t))) - ((jt-zoned-dt? t) (jt-zone-offset (zdt-offset t))) - (else (error #f "ZoneOffset/from: unsupported"))))) - (cons "UTC" (jt-zone-offset 0)) - (cons "MIN" (jt-zone-offset (* -18 3600))) - (cons "MAX" (jt-zone-offset (* 18 3600))))) -(register-host-methods! "zone-offset" - (list (cons "getId" (lambda (z) (zo-id (zo-secs z)))) - (cons "getTotalSeconds" (lambda (z) (zo-secs z))) - (cons "getRules" (lambda (z) (make-jhost "zone-rules" (vector (zo-secs z))))) - (cons "normalized" (lambda (z) z)) - (cons "compareTo" (lambda (z o) (let ((a (zo-secs z)) (b (zo-secs o))) (cond ((< a b) -1) ((> a b) 1) (else 0))))) - (cons "equals" (lambda (z o) (and (jt-zone-offset? o) (= (zo-secs z) (zo-secs o))))) - (cons "hashCode" (lambda (z) (zo-secs z))) - (cons "toString" (lambda (z) (zo-id (zo-secs z)))))) - -;; --- ZoneId ------------------------------------------------------------------ -;; Named-zone offsets the corpus/tick set the JVM tz to. A fixed best-effort offset; -;; arbitrary-instant DST is not modeled. -(define zone-offset-table - '(("UTC" . 0) ("GMT" . 0) ("Z" . 0) ("Etc/UTC" . 0) ("Etc/GMT" . 0) - ("America/New_York" . -18000) ("America/Chicago" . -21600) ("America/Denver" . -25200) - ("America/Los_Angeles" . -28800) ("America/Toronto" . -18000) ("America/Sao_Paulo" . -10800) - ("Europe/London" . 0) ("Europe/Paris" . 3600) ("Europe/Berlin" . 3600) ("Europe/Madrid" . 3600) - ("Europe/Moscow" . 10800) ("Asia/Tokyo" . 32400) ("Asia/Shanghai" . 28800) - ("Asia/Kolkata" . 19800) ("Australia/Sydney" . 36000) ("Pacific/Auckland" . 43200))) -;; java.time ZoneId.SHORT_IDS: 3-letter ids -> region/offset ids. -(define short-ids-pairs - '(("ACT" . "Australia/Darwin") ("AET" . "Australia/Sydney") ("AGT" . "America/Argentina/Buenos_Aires") - ("ART" . "Africa/Cairo") ("AST" . "America/Anchorage") ("BET" . "America/Sao_Paulo") - ("BST" . "Asia/Dhaka") ("CAT" . "Africa/Harare") ("CNT" . "America/St_Johns") - ("CST" . "America/Chicago") ("CTT" . "Asia/Shanghai") ("EAT" . "Africa/Addis_Ababa") - ("ECT" . "Europe/Paris") ("IET" . "America/Indiana/Indianapolis") ("IST" . "Asia/Kolkata") - ("JST" . "Asia/Tokyo") ("MIT" . "Pacific/Apia") ("NET" . "Asia/Yerevan") - ("NST" . "Pacific/Auckland") ("PLT" . "Asia/Karachi") ("PNT" . "America/Phoenix") - ("PRT" . "America/Puerto_Rico") ("PST" . "America/Los_Angeles") ("SST" . "Pacific/Guadalcanal") - ("VST" . "Asia/Ho_Chi_Minh") ("EST" . "-05:00") ("MST" . "-07:00") ("HST" . "-10:00"))) -(define (jt-zone-id id off) (make-jhost "zone-id" (vector id off))) -(define (zid-id z) (vector-ref (jhost-state z) 0)) -(define (zid-off z) (vector-ref (jhost-state z) 1)) -(define (jt-zone-id? x) (and (jhost? x) (string=? (jhost-tag x) "zone-id"))) -;; system zone offset. The inst/SimpleDateFormat layer is UTC-centric (tz-free, -;; machine-independent by design), so systemDefault resolves to UTC: a LocalDateTime -;; round-tripped through atZone/toInstant stays aligned with the UTC #inst model. -;; (Chez's real machine offset is available via date-zone-offset, but using it would -;; make results machine-tz-dependent and break that round-trip.) -(define (system-zone-offset-secs) 0) -;; --- DST rules --------------------------------------------------------------- -;; A DST-observing named zone has a standard offset plus a rule family (US/Canada -;; or EU) that puts the clock one hour ahead for part of the year. The rule yields -;; the two transition points; outside the table a zone keeps a fixed offset. -;; Southern-hemisphere zones (Sydney/Auckland) stay fixed — their reversed DST -;; isn't exercised and a fixed offset preserves existing behavior. -(define dst-saving 3600) -;; day-of-week of an epoch-day, 0=Sunday (1970-01-01 is a Thursday). -(define (epoch-day-dow ed) (modulo (+ ed 4) 7)) -;; epoch-day of the nth (1-based) weekday `dow` in (year, month); n<0 counts from the end. -(define (nth-dow-epoch-day year month dow n) - (if (> n 0) - (let* ((first-ed (ymd->epoch-day year month 1)) - (shift (modulo (- dow (epoch-day-dow first-ed)) 7))) - (+ first-ed shift (* 7 (- n 1)))) - (let* ((last-ed (ymd->epoch-day year month (jt-len-of-month year month))) - (shift (modulo (- (epoch-day-dow last-ed) dow) 7))) - (- last-ed shift)))) -;; year of a UTC/local epoch-seconds value. -(define (secs->year s) - (call-with-values (lambda () (civil-from-days (jt-floor-div s 86400))) - (lambda (y m d) y))) -;; zone-id -> (standard-offset-secs . rule-symbol: us | eu). -(define dst-zone-table - '(("America/New_York" -18000 . us) ("America/Toronto" -18000 . us) - ("America/Chicago" -21600 . us) ("America/Denver" -25200 . us) - ("America/Los_Angeles" -28800 . us) - ("Europe/London" 0 . eu) ("Europe/Paris" 3600 . eu) - ("Europe/Berlin" 3600 . eu) ("Europe/Madrid" 3600 . eu))) -(define (dst-entry id) (assoc id dst-zone-table)) -;; offset for a DST zone at a UTC instant (epoch-seconds). -(define (dst-offset-at-instant id std rule secs) - (let ((year (secs->year secs))) - (case rule - ;; US: spring 2nd Sun Mar 02:00 local std; fall 1st Sun Nov 02:00 local DST. - ((us) - (let ((spring (- (+ (* (nth-dow-epoch-day year 3 0 2) 86400) (* 2 3600)) std)) - (fall (- (+ (* (nth-dow-epoch-day year 11 0 1) 86400) (* 2 3600)) (+ std dst-saving)))) - (if (and (<= spring secs) (< secs fall)) (+ std dst-saving) std))) - ;; EU: spring last Sun Mar 01:00 UTC; fall last Sun Oct 01:00 UTC. - ((eu) - (let ((spring (+ (* (nth-dow-epoch-day year 3 0 -1) 86400) 3600)) - (fall (+ (* (nth-dow-epoch-day year 10 0 -1) 86400) 3600))) - (if (and (<= spring secs) (< secs fall)) (+ std dst-saving) std))) - (else std)))) -;; offset for a DST zone given a local wall-time (epoch-seconds in local time). -;; Boundary hours (the spring gap / fall overlap) resolve to the simple window test. -(define (dst-offset-at-local id std rule lsecs) - (let ((year (secs->year lsecs))) - (case rule - ((us) - (let ((spring (+ (* (nth-dow-epoch-day year 3 0 2) 86400) (* 2 3600))) - (fall (+ (* (nth-dow-epoch-day year 11 0 1) 86400) (* 2 3600)))) - (if (and (<= spring lsecs) (< lsecs fall)) (+ std dst-saving) std))) - ((eu) - (let ((spring (+ (* (nth-dow-epoch-day year 3 0 -1) 86400) 3600 std)) - (fall (+ (* (nth-dow-epoch-day year 10 0 -1) 86400) 7200 std))) - (if (and (<= spring lsecs) (< lsecs fall)) (+ std dst-saving) std))) - (else std)))) -;; DST-aware offset for a resolved (id . std-off) at a UTC instant / local wall-time. -;; Falls back to the resolved fixed offset for non-DST zones. -(define (zone-offset-at-instant id std secs) - (let ((e (dst-entry id))) (if e (dst-offset-at-instant id (cadr e) (cddr e) secs) std))) -(define (zone-offset-at-local id std lsecs) - (let ((e (dst-entry id))) (if e (dst-offset-at-local id (cadr e) (cddr e) lsecs) std))) - -;; resolve any zone designator (string / ZoneId / ZoneOffset) to a (id . offset). -(define (resolve-zone z) - (cond - ((jt-zone-offset? z) (cons (zo-id (zo-secs z)) (zo-secs z))) - ((jt-zone-id? z) (cons (zid-id z) (zid-off z))) - (else - (let ((id (jt-str z))) - (cond - ((string=? id "system") (cons (zo-id (system-zone-offset-secs)) (system-zone-offset-secs))) - ((or (string=? id "Z") (string=? id "UTC") (string=? id "GMT")) (cons "Z" 0)) - ((and (> (string-length id) 0) (memv (string-ref id 0) '(#\+ #\-))) - (let ((s (parse-zone-offset id))) (cons (zo-id s) s))) - ((assoc id zone-offset-table) (cons id (cdr (assoc id zone-offset-table)))) - (else (cons id 0))))))) ; unknown named zone: treat as UTC, id preserved -(define (zone-id-of z) - (let ((r (resolve-zone z))) (jt-zone-id (car r) (cdr r)))) - -(register-class-statics! "ZoneId" - (list (cons "of" (lambda (id . _) (zone-id-of id))) - (cons "systemDefault" (lambda () (let ((s (system-zone-offset-secs))) (jt-zone-id (zo-id s) s)))) - (cons "getAvailableZoneIds" (lambda () (fold-left pset-conj empty-pset (map car zone-offset-table)))) - (cons "SHORT_IDS" (apply jolt-hash-map (apply append (map (lambda (p) (list (car p) (cdr p))) short-ids-pairs)))) - (cons "from" (lambda (t) (cond ((jt-zone-id? t) t) ((jt-zone-offset? t) (jt-zone-id (zo-id (zo-secs t)) (zo-secs t))) - ((jt-zoned-dt? t) (zdt-zone t)) (else (error #f "ZoneId/from: unsupported"))))))) -(register-host-methods! "zone-id" - (list (cons "getId" (lambda (z) (zid-id z))) - (cons "getRules" (lambda (z) (make-jhost "zone-rules" (vector (zid-id z) (zid-off z))))) - (cons "normalized" (lambda (z) (if (and (> (string-length (zid-id z)) 0) (memv (string-ref (zid-id z) 0) '(#\+ #\- #\Z))) - (jt-zone-offset (zid-off z)) z))) - (cons "getDisplayName" (lambda (z . _) (zid-id z))) - (cons "equals" (lambda (z o) (and (jt-zone-id? o) (string=? (zid-id z) (zid-id o))))) - (cons "hashCode" (lambda (z) (string-hash (zid-id z)))) - (cons "toString" (lambda (z) (zid-id z))))) -;; ZoneRules carries the zone id + standard offset. getOffset is DST-aware: given -;; an Instant it resolves the offset at that instant, given a LocalDateTime at that -;; local wall time; with no argument it yields the standard offset. -(define (zr-id r) (vector-ref (jhost-state r) 0)) -(define (zr-std r) (vector-ref (jhost-state r) 1)) -(register-host-methods! "zone-rules" - (list (cons "getOffset" - (lambda (r . args) - (if (null? args) - (jt-zone-offset (zr-std r)) - (let ((a (car args))) - (cond - ((jt-instant-tag? a) - (jt-zone-offset (zone-offset-at-instant (zr-id r) (zr-std r) (jt-floor-div (inst-nanos a) nanos-per-sec)))) - ((jinst? a) - (jt-zone-offset (zone-offset-at-instant (zr-id r) (zr-std r) (jt-floor-div (exact (truncate (jinst-ms a))) 1000)))) - ((and (jhost? a) (string=? (jhost-tag a) "local-date-time")) - (jt-zone-offset (zone-offset-at-local (zr-id r) (zr-std r) - (+ (* (ldt-epoch-day a) 86400) (jt-floor-div (ldt-nano-of-day a) nanos-per-sec))))) - (else (jt-zone-offset (zr-std r)))))))) - (cons "isFixedOffset" (lambda (r) (not (dst-entry (zr-id r))))) - (cons "getStandardOffset" (lambda (r . _) (jt-zone-offset (zr-std r)))) - (cons "toString" (lambda (r) (if (dst-entry (zr-id r)) "ZoneRules" "ZoneRules[fixed]"))))) - -;; --- OffsetTime -------------------------------------------------------------- -(define (jt-offset-time nod off) (make-jhost "offset-time" (vector nod off))) -(define (ot-nod x) (vector-ref (jhost-state x) 0)) -(define (ot-offset x) (vector-ref (jhost-state x) 1)) -(define (jt-offset-time? x) (and (jhost? x) (string=? (jhost-tag x) "offset-time"))) -(define (ot->string x) (string-append (iso-time-str (ot-nod x)) (offset-suffix (ot-offset x)))) -;; the offset suffix used in ISO offset/zoned rendering: "Z" for 0 else ±HH:mm[:ss]. -(define (offset-suffix secs) (zo-id secs)) - -;; --- OffsetDateTime ---------------------------------------------------------- -(define (jt-offset-dt ed nod off) (make-jhost "offset-date-time" (vector ed nod off))) -(define (odt-epoch-day x) (vector-ref (jhost-state x) 0)) -(define (odt-nano-of-day x) (vector-ref (jhost-state x) 1)) -(define (odt-offset x) (vector-ref (jhost-state x) 2)) -(define (jt-offset-dt? x) (and (jhost? x) (string=? (jhost-tag x) "offset-date-time"))) -(define (odt-ldt x) (jt-local-dt (odt-epoch-day x) (odt-nano-of-day x))) -;; epoch-ms of the instant this offset-dt denotes (subtract the offset to reach UTC). -(define (odt->ms x) (- (ldt->ms (odt-ldt x)) (* (odt-offset x) 1000))) -(define (odt->nanos x) (- (+ (* (odt-epoch-day x) nanos-per-day) (odt-nano-of-day x)) (* (odt-offset x) nanos-per-sec))) -(define (odt->string x) (string-append (iso-datetime-str (odt-epoch-day x) (odt-nano-of-day x)) (offset-suffix (odt-offset x)))) - -;; --- ZonedDateTime ----------------------------------------------------------- -(define (jt-zoned-dt ed nod off zone) (make-jhost "zoned-date-time" (vector ed nod off zone))) -(define (zdt-epoch-day x) (vector-ref (jhost-state x) 0)) -(define (zdt-nano-of-day x) (vector-ref (jhost-state x) 1)) -(define (zdt-offset x) (vector-ref (jhost-state x) 2)) -(define (zdt-zone x) (vector-ref (jhost-state x) 3)) -(define (jt-zoned-dt? x) (and (jhost? x) (string=? (jhost-tag x) "zoned-date-time"))) -(define (zdt-ldt x) (jt-local-dt (zdt-epoch-day x) (zdt-nano-of-day x))) -(define (zdt->ms x) (- (ldt->ms (zdt-ldt x)) (* (zdt-offset x) 1000))) -(define (zdt->nanos x) (- (+ (* (zdt-epoch-day x) nanos-per-day) (zdt-nano-of-day x)) (* (zdt-offset x) nanos-per-sec))) -;; ISO zoned: local + offset, then [zone-id] unless the zone IS the offset. -(define (zdt->string x) - (let* ((zid (zdt-zone x)) (id (zid-id zid))) - (string-append (iso-datetime-str (zdt-epoch-day x) (zdt-nano-of-day x)) (offset-suffix (zdt-offset x)) - (if (or (string=? id (offset-suffix (zdt-offset x))) - (and (> (string-length id) 0) (memv (string-ref id 0) '(#\+ #\- #\Z)))) - "" (string-append "[" id "]"))))) - -;; build a ZonedDateTime/OffsetDateTime from a LocalDateTime + zone designator. The -;; offset is the zone's fixed offset (no DST resolution). -(define (zoned-of-ldt ldt zone) - (let* ((r (resolve-zone zone)) - (lsecs (+ (* (ldt-epoch-day ldt) 86400) (jt-floor-div (ldt-nano-of-day ldt) 1000000000))) - (off (zone-offset-at-local (car r) (cdr r) lsecs))) - (jt-zoned-dt (ldt-epoch-day ldt) (ldt-nano-of-day ldt) off (jt-zone-id (car r) (cdr r))))) -(define (offset-of-ldt ldt off) - (let ((secs (cond ((jt-zone-offset? off) (zo-secs off)) ((jt-zone-id? off) (zid-off off)) (else (parse-zone-offset off))))) - (jt-offset-dt (ldt-epoch-day ldt) (ldt-nano-of-day ldt) secs))) -;; from an epoch-ms instant + zone: apply the zone offset to get the local fields. -(define (zoned-of-instant-ms ms zone) - (let* ((r (resolve-zone zone)) - (off (zone-offset-at-instant (car r) (cdr r) (jt-floor-div (exact (truncate ms)) 1000))) - (local-ms (+ (exact (truncate ms)) (* off 1000))) - (ed (jt-floor-div local-ms 86400000)) (nod (* (jt-floor-mod local-ms 86400000) 1000000))) - (jt-zoned-dt ed nod off (jt-zone-id (car r) (cdr r))))) -(define (offset-of-instant-ms ms off-or-zone) - (let* ((secs (cond ((jt-zone-offset? off-or-zone) (zo-secs off-or-zone)) - ((jt-zone-id? off-or-zone) (zid-off off-or-zone)) - (else (let ((r (resolve-zone off-or-zone))) - (zone-offset-at-instant (car r) (cdr r) (jt-floor-div (exact (truncate ms)) 1000)))))) - (local-ms (+ (exact (truncate ms)) (* secs 1000))) - (ed (jt-floor-div local-ms 86400000)) (nod (* (jt-floor-mod local-ms 86400000) 1000000))) - (jt-offset-dt ed nod secs))) -;; nano-precise instant -> zoned/offset (Instant carries epoch-nanos; ms versions -;; above stay for the ms-based Date/Calendar callers). -(define (zoned-of-instant-nanos nanos zone) - (let* ((r (resolve-zone zone)) - (off (zone-offset-at-instant (car r) (cdr r) (jt-floor-div nanos nanos-per-sec))) - (local-nanos (+ nanos (* off nanos-per-sec))) - (ed (jt-floor-div local-nanos nanos-per-day)) (nod (jt-floor-mod local-nanos nanos-per-day))) - (jt-zoned-dt ed nod off (jt-zone-id (car r) (cdr r))))) -(define (offset-of-instant-nanos nanos off-or-zone) - (let* ((off (cond ((jt-zone-offset? off-or-zone) (zo-secs off-or-zone)) - ((jt-zone-id? off-or-zone) (zid-off off-or-zone)) - (else (let ((r (resolve-zone off-or-zone))) - (zone-offset-at-instant (car r) (cdr r) (jt-floor-div nanos nanos-per-sec)))))) - (local-nanos (+ nanos (* off nanos-per-sec))) - (ed (jt-floor-div local-nanos nanos-per-day)) (nod (jt-floor-mod local-nanos nanos-per-day))) - (jt-offset-dt ed nod off))) - -;; redefine mk-zoned (used by Phase-1/2 atZone/atOffset) to yield a real -;; ZonedDateTime at UTC. Older inst-time.ss "zoned-dt" callers route through here. -(set! mk-zoned (lambda (ms) (zoned-of-instant-ms ms (jt-zone-id "Z" 0)))) - -;; --- now / Clock-aware statics ----------------------------------------------- -;; A Clock yields an instant (epoch-ms) and a zone. now-from-clock reads ms. -(define (clock-now-ms clk) - (cond ((not (jhost? clk)) (now-ms)) - ((string=? (jhost-tag clk) "clock") (clk-millis clk)) - (else (now-ms)))) -(define (clock-zone clk) - (if (and (jhost? clk) (string=? (jhost-tag clk) "clock")) (vector-ref (jhost-state clk) 2) - (jt-zone-id "Z" 0))) -;; now-ms-arg: an optional first arg may be a Clock or a ZoneId; pick the ms. -(define (now-ms* args) - (if (and (pair? args) (jhost? (car args)) (string=? (jhost-tag (car args)) "clock")) - (clock-now-ms (car args)) - (now-ms))) - -;; rewire the Phase-1/2 now statics to accept an optional Clock/ZoneId argument. -(register-class-statics! "Instant" - (list (cons "now" (lambda args (mk-instant (now-ms* args)))))) -(register-class-statics! "LocalDate" - (list (cons "now" (lambda args (mk-local-date (now-ms* args)))))) -(register-class-statics! "LocalTime" - (list (cons "now" (lambda args (jt-local-time (* (jt-floor-mod (exact (truncate (now-ms* args))) 86400000) 1000000)))))) -(register-class-statics! "LocalDateTime" - (list (cons "now" (lambda args (mk-local (now-ms* args)))))) - -;; --- Clock ------------------------------------------------------------------- -;; (vector kind fixed-ms zone [base]) kind 'system | 'fixed | 'offset | 'tick -(define (jt-clock kind ms zone . base) (make-jhost "clock" (vector kind ms zone (and (pair? base) (car base))))) -(define (clk-millis clk) - (let ((kind (vector-ref (jhost-state clk) 0))) - (case kind - ((fixed) (vector-ref (jhost-state clk) 1)) - ((offset) (+ (clk-millis (vector-ref (jhost-state clk) 3)) (vector-ref (jhost-state clk) 1))) - ((tick) (let* ((base (vector-ref (jhost-state clk) 3)) (dur-ms (vector-ref (jhost-state clk) 1)) - (m (clk-millis base))) - (if (> dur-ms 0) (* (jt-floor-div m dur-ms) dur-ms) m))) - (else (now-ms))))) -(register-class-statics! "Clock" - (list (cons "systemUTC" (lambda () (jt-clock 'system 0 (jt-zone-id "Z" 0)))) - (cons "systemDefaultZone" (lambda () (let ((s (system-zone-offset-secs))) (jt-clock 'system 0 (jt-zone-id (zo-id s) s))))) - (cons "system" (lambda (zone) (jt-clock 'system 0 (zone-id-of zone)))) - (cons "fixed" (lambda (inst zone) (jt-clock 'fixed (exact (truncate (ms-of inst))) (zone-id-of zone)))) - (cons "offset" (lambda (clk dur) (jt-clock 'offset (quotient (dur-total-nanos dur) 1000000) (clock-zone clk) clk))) - (cons "tick" (lambda (clk dur) (jt-clock 'tick (quotient (dur-total-nanos dur) 1000000) (clock-zone clk) clk))) - (cons "tickMinutes" (lambda (zone) (jt-clock 'tick 60000 (zone-id-of zone) (jt-clock 'system 0 (zone-id-of zone))))) - (cons "tickSeconds" (lambda (zone) (jt-clock 'tick 1000 (zone-id-of zone) (jt-clock 'system 0 (zone-id-of zone))))))) -(register-host-methods! "clock" - (list (cons "instant" (lambda (clk) (mk-instant (clk-millis clk)))) - (cons "millis" (lambda (clk) (clk-millis clk))) - (cons "getZone" (lambda (clk) (vector-ref (jhost-state clk) 2))) - (cons "withZone" (lambda (clk zone) (make-jhost "clock" (vector (vector-ref (jhost-state clk) 0) - (vector-ref (jhost-state clk) 1) - (zone-id-of zone) - (vector-ref (jhost-state clk) 3))))) - (cons "equals" (lambda (clk o) (and (jhost? o) (string=? (jhost-tag o) "clock") (equal? (jhost-state clk) (jhost-state o))))) - (cons "toString" (lambda (clk) "Clock")))) - -;; --- ZonedDateTime statics + methods ----------------------------------------- -(register-class-statics! "ZonedDateTime" - (list (cons "of" (case-lambda - ((ldt zone) (zoned-of-ldt ldt zone)) - ((d t zone) (zoned-of-ldt (jt-local-dt (ld-epoch-day d) (lt-nano-of-day t)) zone)) - ((y mo d h mi s nano zone) - (zoned-of-ldt (jt-local-dt (ymd->epoch-day (jt->exact y) (jt->exact mo) (jt->exact d)) - (hmsn->nano (jt->exact h) (jt->exact mi) (jt->exact s) (jt->exact nano))) zone)))) - (cons "ofInstant" (case-lambda - ((inst zone) (zoned-of-instant-ms (ms-of inst) zone)) - ((ldt off zone) (zoned-of-ldt ldt zone)))) - (cons "ofLocal" (lambda (ldt zone . _) (zoned-of-ldt ldt zone))) - (cons "now" (lambda args (let ((ms (now-ms* args))) - (zoned-of-instant-ms ms (if (and (pair? args) (jhost? (car args)) (string=? (jhost-tag (car args)) "clock")) - (clock-zone (car args)) (jt-zone-id "Z" 0)))))) - (cons "parse" (lambda (s . fmt) - (if (null? fmt) (parse-zoned-date-time (jt-str s)) - (call-with-values (lambda () (formatter-parse-fields (car fmt) s)) - (lambda (ed nod) (jt-zoned-dt ed nod 0 (jt-zone-id "Z" 0))))))) - (cons "from" (lambda (t) (cond ((jt-zoned-dt? t) t) - ((jt-offset-dt? t) (jt-zoned-dt (odt-epoch-day t) (odt-nano-of-day t) (odt-offset t) (jt-zone-id (zo-id (odt-offset t)) (odt-offset t)))) - (else (zoned-of-instant-ms (ms-of t) (jt-zone-id "Z" 0)))))))) - -;; apply nano arithmetic to a zoned/offset value, keeping its offset & zone. -(define (zdt-plus-nanos x nanos) - (let ((nldt (ldt-plus-nanos (zdt-ldt x) nanos))) - (jt-zoned-dt (ldt-epoch-day nldt) (ldt-nano-of-day nldt) (zdt-offset x) (zdt-zone x)))) -(define (zdt-with-ldt x ldt) (jt-zoned-dt (ldt-epoch-day ldt) (ldt-nano-of-day ldt) (zdt-offset x) (zdt-zone x))) - -(register-host-methods! "zoned-date-time" - (list (cons "getYear" (lambda (x) (call-with-values (lambda () (epoch-day->ymd (zdt-epoch-day x))) (lambda (y m d) y)))) - (cons "getMonthValue" (lambda (x) (call-with-values (lambda () (epoch-day->ymd (zdt-epoch-day x))) (lambda (y m d) m)))) - (cons "getMonth" (lambda (x) (call-with-values (lambda () (epoch-day->ymd (zdt-epoch-day x))) (lambda (y m d) (jt-month m))))) - (cons "getDayOfMonth" (lambda (x) (call-with-values (lambda () (epoch-day->ymd (zdt-epoch-day x))) (lambda (y m d) d)))) - (cons "getDayOfWeek" (lambda (x) (jt-dow (ld-dow (zdt-epoch-day x))))) - (cons "getDayOfYear" (lambda (x) (ld-day-of-year (zdt-epoch-day x)))) - (cons "getHour" (lambda (x) (lt-hour (zdt-ldt x)))) - (cons "getMinute" (lambda (x) (lt-minute (zdt-ldt x)))) - (cons "getSecond" (lambda (x) (lt-second (zdt-ldt x)))) - (cons "getNano" (lambda (x) (lt-nano (zdt-ldt x)))) - (cons "getOffset" (lambda (x) (jt-zone-offset (zdt-offset x)))) - (cons "getZone" (lambda (x) (zdt-zone x))) - (cons "toInstant" (lambda (x) (mk-instant-nanos (zdt->nanos x)))) - (cons "toLocalDate" (lambda (x) (jt-local-date (zdt-epoch-day x)))) - (cons "toLocalTime" (lambda (x) (jt-local-time (zdt-nano-of-day x)))) - (cons "toLocalDateTime" (lambda (x) (zdt-ldt x))) - (cons "toOffsetDateTime" (lambda (x) (jt-offset-dt (zdt-epoch-day x) (zdt-nano-of-day x) (zdt-offset x)))) - (cons "toEpochSecond" (lambda (x) (jt-floor-div (zdt->ms x) 1000))) - (cons "plusDays" (lambda (x n) (zdt-with-ldt x (jt-local-dt (+ (zdt-epoch-day x) (jt->exact n)) (zdt-nano-of-day x))))) - (cons "minusDays" (lambda (x n) (zdt-with-ldt x (jt-local-dt (- (zdt-epoch-day x) (jt->exact n)) (zdt-nano-of-day x))))) - (cons "plusWeeks" (lambda (x n) (zdt-with-ldt x (jt-local-dt (+ (zdt-epoch-day x) (* 7 (jt->exact n))) (zdt-nano-of-day x))))) - (cons "minusWeeks" (lambda (x n) (zdt-with-ldt x (jt-local-dt (- (zdt-epoch-day x) (* 7 (jt->exact n))) (zdt-nano-of-day x))))) - (cons "plusMonths" (lambda (x n) (zdt-with-ldt x (ldt-combine (ld-plus-months (ldt-date (zdt-ldt x)) (jt->exact n)) (ldt-time (zdt-ldt x)))))) - (cons "minusMonths" (lambda (x n) (zdt-with-ldt x (ldt-combine (ld-plus-months (ldt-date (zdt-ldt x)) (- (jt->exact n))) (ldt-time (zdt-ldt x)))))) - (cons "plusYears" (lambda (x n) (zdt-with-ldt x (ldt-combine (ld-plus-years (ldt-date (zdt-ldt x)) (jt->exact n)) (ldt-time (zdt-ldt x)))))) - (cons "minusYears" (lambda (x n) (zdt-with-ldt x (ldt-combine (ld-plus-years (ldt-date (zdt-ldt x)) (- (jt->exact n))) (ldt-time (zdt-ldt x)))))) - (cons "plusHours" (lambda (x n) (zdt-plus-nanos x (* (jt->exact n) 3600 nanos-per-sec)))) - (cons "minusHours" (lambda (x n) (zdt-plus-nanos x (- (* (jt->exact n) 3600 nanos-per-sec))))) - (cons "plusMinutes" (lambda (x n) (zdt-plus-nanos x (* (jt->exact n) 60 nanos-per-sec)))) - (cons "minusMinutes" (lambda (x n) (zdt-plus-nanos x (- (* (jt->exact n) 60 nanos-per-sec))))) - (cons "plusSeconds" (lambda (x n) (zdt-plus-nanos x (* (jt->exact n) nanos-per-sec)))) - (cons "minusSeconds" (lambda (x n) (zdt-plus-nanos x (- (* (jt->exact n) nanos-per-sec))))) - (cons "plusNanos" (lambda (x n) (zdt-plus-nanos x (jt->exact n)))) - (cons "minusNanos" (lambda (x n) (zdt-plus-nanos x (- (jt->exact n))))) - (cons "withYear" (lambda (x v) (zdt-with-ldt x (ldt-combine (ld-with-field (ldt-date (zdt-ldt x)) 'year (jt->exact v)) (ldt-time (zdt-ldt x)))))) - (cons "withMonth" (lambda (x v) (zdt-with-ldt x (ldt-combine (ld-with-field (ldt-date (zdt-ldt x)) 'month (jt->exact v)) (ldt-time (zdt-ldt x)))))) - (cons "withDayOfMonth" (lambda (x v) (zdt-with-ldt x (ldt-combine (ld-with-field (ldt-date (zdt-ldt x)) 'day (jt->exact v)) (ldt-time (zdt-ldt x)))))) - (cons "withDayOfYear" (lambda (x v) (zdt-with-ldt x (ldt-combine (ld-with-field (ldt-date (zdt-ldt x)) 'day-of-year (jt->exact v)) (ldt-time (zdt-ldt x)))))) - (cons "withHour" (lambda (x v) (zdt-with-ldt x (ldt-combine (ldt-date (zdt-ldt x)) (lt-with (ldt-time (zdt-ldt x)) 'hour (jt->exact v)))))) - (cons "withMinute" (lambda (x v) (zdt-with-ldt x (ldt-combine (ldt-date (zdt-ldt x)) (lt-with (ldt-time (zdt-ldt x)) 'minute (jt->exact v)))))) - (cons "withSecond" (lambda (x v) (zdt-with-ldt x (ldt-combine (ldt-date (zdt-ldt x)) (lt-with (ldt-time (zdt-ldt x)) 'second (jt->exact v)))))) - (cons "withNano" (lambda (x v) (zdt-with-ldt x (ldt-combine (ldt-date (zdt-ldt x)) (lt-with (ldt-time (zdt-ldt x)) 'nano (jt->exact v)))))) - (cons "truncatedTo" (lambda (x u) (zdt-with-ldt x (ldt-combine (ldt-date (zdt-ldt x)) (lt-truncate (ldt-time (zdt-ldt x)) u))))) - (cons "withZoneSameInstant" (lambda (x zone) (zoned-of-instant-nanos (zdt->nanos x) zone))) - (cons "withZoneSameLocal" (lambda (x zone) (zoned-of-ldt (zdt-ldt x) zone))) - (cons "withFixedOffsetZone" (lambda (x) (jt-zoned-dt (zdt-epoch-day x) (zdt-nano-of-day x) (zdt-offset x) (jt-zone-id (zo-id (zdt-offset x)) (zdt-offset x))))) - (cons "plus" (case-lambda ((x a) (zdt-plus-amount x a 1)) ((x n u) (zdt-with-ldt x (temporal-plus-unit (zdt-ldt x) (jt->exact n) (arg-unit-name u)))))) - (cons "minus" (case-lambda ((x a) (zdt-plus-amount x a -1)) ((x n u) (zdt-with-ldt x (temporal-plus-unit (zdt-ldt x) (- (jt->exact n)) (arg-unit-name u)))))) - (cons "until" (lambda (x o u) (unit-between (arg-unit-name u) (zdt-ldt x) (zdt-ldt o)))) - (cons "get" (lambda (x f) (zdt-get-field x (arg-field-name f)))) - (cons "getLong" (lambda (x f) (zdt-get-field x (arg-field-name f)))) - (cons "with" (case-lambda ((x adj) (zdt-with-ldt x (apply-adjuster (zdt-ldt x) adj))) - ((x f v) (zdt-with-ldt x (temporal-with-field (zdt-ldt x) (arg-field-name f) (jt->exact v)))))) - (cons "isSupported" (lambda (x a) (cond ((arg-is-unit? a) (not (string-ci=? (cu-name a) "FOREVER"))) - ((arg-is-field? a) #t) (else #f)))) - (cons "range" (lambda (x f) (temporal-range (zdt-ldt x) (arg-field-name f)))) - (cons "isBefore" (lambda (x o) (< (zdt->ms x) (time-ms o)))) - (cons "isAfter" (lambda (x o) (> (zdt->ms x) (time-ms o)))) - (cons "isEqual" (lambda (x o) (= (zdt->ms x) (time-ms o)))) - (cons "compareTo" (lambda (x o) (let ((a (zdt->ms x)) (b (zdt->ms o))) (cond ((< a b) -1) ((> a b) 1) (else 0))))) - (cons "equals" (lambda (x o) (and (jt-zoned-dt? o) (equal? (jhost-state x) (jhost-state o))))) - (cons "hashCode" (lambda (x) (jolt-hash (zdt->ms x)))) - (cons "format" (lambda (x fmt) (fmt-format fmt x))) - (cons "toString" (lambda (x) (zdt->string x))))) -(define (zdt-plus-amount x a sign) - (cond ((arg-is-amount? a) (if (string=? (jhost-tag a) "duration") - (zdt-plus-nanos x (* sign (dur-total-nanos a))) - (zdt-with-ldt x (temporal-plus-period (zdt-ldt x) a sign)))) - (else (error #f "ZonedDateTime.plus: bad amount")))) -(define (zdt-get-field x field) - (let ((f (string-upcase field))) - (cond ((string=? f "OFFSET_SECONDS") (zdt-offset x)) - ((string=? f "INSTANT_SECONDS") (jt-floor-div (zdt->ms x) 1000)) - (else (temporal-get-field (zdt-ldt x) f))))) -;; epoch-ms of any time-bearing value (for cross-type before/after). -(define (time-ms o) - (cond ((jt-zoned-dt? o) (zdt->ms o)) ((jt-offset-dt? o) (odt->ms o)) ((jt-instant? o) (inst-ms o)) - ((jt-dt? o) (ldt->ms o)) (else (ms-of o)))) - -;; --- OffsetDateTime statics + methods ---------------------------------------- -(register-class-statics! "OffsetDateTime" - (list (cons "of" (case-lambda - ((ldt off) (offset-of-ldt ldt off)) - ((d t off) (offset-of-ldt (jt-local-dt (ld-epoch-day d) (lt-nano-of-day t)) off)) - ((y mo d h mi s nano off) - (offset-of-ldt (jt-local-dt (ymd->epoch-day (jt->exact y) (jt->exact mo) (jt->exact d)) - (hmsn->nano (jt->exact h) (jt->exact mi) (jt->exact s) (jt->exact nano))) off)))) - (cons "ofInstant" (lambda (inst zone) (offset-of-instant-ms (ms-of inst) zone))) - (cons "now" (lambda args (offset-of-instant-ms (now-ms* args) (jt-zone-offset 0)))) - (cons "parse" (lambda (s . fmt) - (if (null? fmt) (parse-offset-date-time (jt-str s)) - (call-with-values (lambda () (formatter-parse-fields (car fmt) s)) - (lambda (ed nod) (jt-offset-dt ed nod 0)))))) - (cons "from" (lambda (t) (cond ((jt-offset-dt? t) t) - ((jt-zoned-dt? t) (jt-offset-dt (zdt-epoch-day t) (zdt-nano-of-day t) (zdt-offset t))) - (else (offset-of-instant-ms (ms-of t) (jt-zone-offset 0)))))) - (cons "MIN" (jt-offset-dt (ymd->epoch-day -999999999 1 1) 0 (* 18 3600))) - (cons "MAX" (jt-offset-dt (ymd->epoch-day 999999999 12 31) (- nanos-per-day 1) (* -18 3600))))) -(define (odt-with-ldt x ldt) (jt-offset-dt (ldt-epoch-day ldt) (ldt-nano-of-day ldt) (odt-offset x))) -(define (odt-plus-nanos x nanos) (odt-with-ldt x (ldt-plus-nanos (odt-ldt x) nanos))) -(register-host-methods! "offset-date-time" - (list (cons "getYear" (lambda (x) (call-with-values (lambda () (epoch-day->ymd (odt-epoch-day x))) (lambda (y m d) y)))) - (cons "getMonthValue" (lambda (x) (call-with-values (lambda () (epoch-day->ymd (odt-epoch-day x))) (lambda (y m d) m)))) - (cons "getMonth" (lambda (x) (call-with-values (lambda () (epoch-day->ymd (odt-epoch-day x))) (lambda (y m d) (jt-month m))))) - (cons "getDayOfMonth" (lambda (x) (call-with-values (lambda () (epoch-day->ymd (odt-epoch-day x))) (lambda (y m d) d)))) - (cons "getDayOfWeek" (lambda (x) (jt-dow (ld-dow (odt-epoch-day x))))) - (cons "getDayOfYear" (lambda (x) (ld-day-of-year (odt-epoch-day x)))) - (cons "getHour" (lambda (x) (lt-hour (odt-ldt x)))) - (cons "getMinute" (lambda (x) (lt-minute (odt-ldt x)))) - (cons "getSecond" (lambda (x) (lt-second (odt-ldt x)))) - (cons "getNano" (lambda (x) (lt-nano (odt-ldt x)))) - (cons "getOffset" (lambda (x) (jt-zone-offset (odt-offset x)))) - (cons "toInstant" (lambda (x) (mk-instant-nanos (odt->nanos x)))) - (cons "toLocalDate" (lambda (x) (jt-local-date (odt-epoch-day x)))) - (cons "toLocalTime" (lambda (x) (jt-local-time (odt-nano-of-day x)))) - (cons "toLocalDateTime" (lambda (x) (odt-ldt x))) - (cons "toOffsetTime" (lambda (x) (jt-offset-time (odt-nano-of-day x) (odt-offset x)))) - (cons "toZonedDateTime" (lambda (x) (jt-zoned-dt (odt-epoch-day x) (odt-nano-of-day x) (odt-offset x) (jt-zone-id (zo-id (odt-offset x)) (odt-offset x))))) - (cons "toEpochSecond" (lambda (x) (jt-floor-div (odt->ms x) 1000))) - (cons "atZoneSameInstant" (lambda (x zone) (zoned-of-instant-nanos (odt->nanos x) zone))) - (cons "atZoneSimilarLocal" (lambda (x zone) (zoned-of-ldt (odt-ldt x) zone))) - (cons "withOffsetSameInstant" (lambda (x off) (offset-of-instant-ms (odt->ms x) off))) - (cons "withOffsetSameLocal" (lambda (x off) (offset-of-ldt (odt-ldt x) off))) - (cons "plusDays" (lambda (x n) (odt-with-ldt x (jt-local-dt (+ (odt-epoch-day x) (jt->exact n)) (odt-nano-of-day x))))) - (cons "minusDays" (lambda (x n) (odt-with-ldt x (jt-local-dt (- (odt-epoch-day x) (jt->exact n)) (odt-nano-of-day x))))) - (cons "plusWeeks" (lambda (x n) (odt-with-ldt x (jt-local-dt (+ (odt-epoch-day x) (* 7 (jt->exact n))) (odt-nano-of-day x))))) - (cons "minusWeeks" (lambda (x n) (odt-with-ldt x (jt-local-dt (- (odt-epoch-day x) (* 7 (jt->exact n))) (odt-nano-of-day x))))) - (cons "plusMonths" (lambda (x n) (odt-with-ldt x (ldt-combine (ld-plus-months (ldt-date (odt-ldt x)) (jt->exact n)) (ldt-time (odt-ldt x)))))) - (cons "minusMonths" (lambda (x n) (odt-with-ldt x (ldt-combine (ld-plus-months (ldt-date (odt-ldt x)) (- (jt->exact n))) (ldt-time (odt-ldt x)))))) - (cons "plusYears" (lambda (x n) (odt-with-ldt x (ldt-combine (ld-plus-years (ldt-date (odt-ldt x)) (jt->exact n)) (ldt-time (odt-ldt x)))))) - (cons "minusYears" (lambda (x n) (odt-with-ldt x (ldt-combine (ld-plus-years (ldt-date (odt-ldt x)) (- (jt->exact n))) (ldt-time (odt-ldt x)))))) - (cons "plusHours" (lambda (x n) (odt-plus-nanos x (* (jt->exact n) 3600 nanos-per-sec)))) - (cons "minusHours" (lambda (x n) (odt-plus-nanos x (- (* (jt->exact n) 3600 nanos-per-sec))))) - (cons "plusMinutes" (lambda (x n) (odt-plus-nanos x (* (jt->exact n) 60 nanos-per-sec)))) - (cons "minusMinutes" (lambda (x n) (odt-plus-nanos x (- (* (jt->exact n) 60 nanos-per-sec))))) - (cons "plusSeconds" (lambda (x n) (odt-plus-nanos x (* (jt->exact n) nanos-per-sec)))) - (cons "minusSeconds" (lambda (x n) (odt-plus-nanos x (- (* (jt->exact n) nanos-per-sec))))) - (cons "plusNanos" (lambda (x n) (odt-plus-nanos x (jt->exact n)))) - (cons "minusNanos" (lambda (x n) (odt-plus-nanos x (- (jt->exact n))))) - (cons "withYear" (lambda (x v) (odt-with-ldt x (ldt-combine (ld-with-field (ldt-date (odt-ldt x)) 'year (jt->exact v)) (ldt-time (odt-ldt x)))))) - (cons "withMonth" (lambda (x v) (odt-with-ldt x (ldt-combine (ld-with-field (ldt-date (odt-ldt x)) 'month (jt->exact v)) (ldt-time (odt-ldt x)))))) - (cons "withDayOfMonth" (lambda (x v) (odt-with-ldt x (ldt-combine (ld-with-field (ldt-date (odt-ldt x)) 'day (jt->exact v)) (ldt-time (odt-ldt x)))))) - (cons "withDayOfYear" (lambda (x v) (odt-with-ldt x (ldt-combine (ld-with-field (ldt-date (odt-ldt x)) 'day-of-year (jt->exact v)) (ldt-time (odt-ldt x)))))) - (cons "withHour" (lambda (x v) (odt-with-ldt x (ldt-combine (ldt-date (odt-ldt x)) (lt-with (ldt-time (odt-ldt x)) 'hour (jt->exact v)))))) - (cons "withMinute" (lambda (x v) (odt-with-ldt x (ldt-combine (ldt-date (odt-ldt x)) (lt-with (ldt-time (odt-ldt x)) 'minute (jt->exact v)))))) - (cons "withSecond" (lambda (x v) (odt-with-ldt x (ldt-combine (ldt-date (odt-ldt x)) (lt-with (ldt-time (odt-ldt x)) 'second (jt->exact v)))))) - (cons "withNano" (lambda (x v) (odt-with-ldt x (ldt-combine (ldt-date (odt-ldt x)) (lt-with (ldt-time (odt-ldt x)) 'nano (jt->exact v)))))) - (cons "truncatedTo" (lambda (x u) (odt-with-ldt x (ldt-combine (ldt-date (odt-ldt x)) (lt-truncate (ldt-time (odt-ldt x)) u))))) - (cons "plus" (case-lambda ((x a) (odt-plus-amount x a 1)) ((x n u) (odt-with-ldt x (temporal-plus-unit (odt-ldt x) (jt->exact n) (arg-unit-name u)))))) - (cons "minus" (case-lambda ((x a) (odt-plus-amount x a -1)) ((x n u) (odt-with-ldt x (temporal-plus-unit (odt-ldt x) (- (jt->exact n)) (arg-unit-name u)))))) - (cons "until" (lambda (x o u) (unit-between (arg-unit-name u) (odt-ldt x) (odt-ldt o)))) - (cons "get" (lambda (x f) (odt-get-field x (arg-field-name f)))) - (cons "getLong" (lambda (x f) (odt-get-field x (arg-field-name f)))) - (cons "with" (case-lambda ((x adj) (odt-with-ldt x (apply-adjuster (odt-ldt x) adj))) - ((x f v) (odt-with-ldt x (temporal-with-field (odt-ldt x) (arg-field-name f) (jt->exact v)))))) - (cons "isSupported" (lambda (x a) (cond ((arg-is-unit? a) (not (string-ci=? (cu-name a) "FOREVER"))) ((arg-is-field? a) #t) (else #f)))) - (cons "range" (lambda (x f) (temporal-range (odt-ldt x) (arg-field-name f)))) - (cons "isBefore" (lambda (x o) (< (odt->ms x) (time-ms o)))) - (cons "isAfter" (lambda (x o) (> (odt->ms x) (time-ms o)))) - (cons "isEqual" (lambda (x o) (= (odt->ms x) (time-ms o)))) - (cons "compareTo" (lambda (x o) (let ((a (odt->ms x)) (b (odt->ms o))) (cond ((< a b) -1) ((> a b) 1) (else 0))))) - (cons "equals" (lambda (x o) (and (jt-offset-dt? o) (equal? (jhost-state x) (jhost-state o))))) - (cons "hashCode" (lambda (x) (jolt-hash (odt->ms x)))) - (cons "format" (lambda (x fmt) (fmt-format fmt x))) - (cons "toString" (lambda (x) (odt->string x))))) -(define (odt-plus-amount x a sign) - (cond ((arg-is-amount? a) (if (string=? (jhost-tag a) "duration") - (odt-plus-nanos x (* sign (dur-total-nanos a))) - (odt-with-ldt x (temporal-plus-period (odt-ldt x) a sign)))) - (else (error #f "OffsetDateTime.plus: bad amount")))) -(define (odt-get-field x field) - (let ((f (string-upcase field))) - (cond ((string=? f "OFFSET_SECONDS") (odt-offset x)) - ((string=? f "INSTANT_SECONDS") (jt-floor-div (odt->ms x) 1000)) - (else (temporal-get-field (odt-ldt x) f))))) - -;; --- OffsetTime statics + methods -------------------------------------------- -(register-class-statics! "OffsetTime" - (list (cons "of" (case-lambda - ((t off) (jt-offset-time (lt-nano-of-day t) (zo-secs* off))) - ((h m s nano off) (jt-offset-time (hmsn->nano (jt->exact h) (jt->exact m) (jt->exact s) (jt->exact nano)) (zo-secs* off))))) - (cons "ofInstant" (lambda (inst zone) (let ((od (offset-of-instant-ms (ms-of inst) zone))) - (jt-offset-time (odt-nano-of-day od) (odt-offset od))))) - (cons "now" (lambda args (jt-offset-time (* (jt-floor-mod (exact (truncate (now-ms* args))) 86400000) 1000000) 0))) - (cons "parse" (lambda (s . _) (parse-offset-time (jt-str s)))) - (cons "from" (lambda (t) (cond ((jt-offset-time? t) t) - ((jt-offset-dt? t) (jt-offset-time (odt-nano-of-day t) (odt-offset t))) - (else (error #f "OffsetTime/from: unsupported"))))) - (cons "MIN" (jt-offset-time 0 (* 18 3600))) - (cons "MAX" (jt-offset-time (- nanos-per-day 1) (* -18 3600))))) -(define (zo-secs* off) (cond ((jt-zone-offset? off) (zo-secs off)) ((jt-zone-id? off) (zid-off off)) (else (parse-zone-offset off)))) -(define (ot-with x nod) (jt-offset-time nod (ot-offset x))) -(register-host-methods! "offset-time" - (list (cons "getHour" (lambda (x) (lt-hour (jt-local-time (ot-nod x))))) - (cons "getMinute" (lambda (x) (lt-minute (jt-local-time (ot-nod x))))) - (cons "getSecond" (lambda (x) (lt-second (jt-local-time (ot-nod x))))) - (cons "getNano" (lambda (x) (lt-nano (jt-local-time (ot-nod x))))) - (cons "getOffset" (lambda (x) (jt-zone-offset (ot-offset x)))) - (cons "toLocalTime" (lambda (x) (jt-local-time (ot-nod x)))) - (cons "atDate" (lambda (x d) (jt-offset-dt (ld-epoch-day d) (ot-nod x) (ot-offset x)))) - (cons "plusHours" (lambda (x n) (ot-with x (jt-floor-mod (+ (ot-nod x) (* (jt->exact n) 3600 nanos-per-sec)) nanos-per-day)))) - (cons "minusHours" (lambda (x n) (ot-with x (jt-floor-mod (- (ot-nod x) (* (jt->exact n) 3600 nanos-per-sec)) nanos-per-day)))) - (cons "plusMinutes" (lambda (x n) (ot-with x (jt-floor-mod (+ (ot-nod x) (* (jt->exact n) 60 nanos-per-sec)) nanos-per-day)))) - (cons "minusMinutes" (lambda (x n) (ot-with x (jt-floor-mod (- (ot-nod x) (* (jt->exact n) 60 nanos-per-sec)) nanos-per-day)))) - (cons "plusSeconds" (lambda (x n) (ot-with x (jt-floor-mod (+ (ot-nod x) (* (jt->exact n) nanos-per-sec)) nanos-per-day)))) - (cons "minusSeconds" (lambda (x n) (ot-with x (jt-floor-mod (- (ot-nod x) (* (jt->exact n) nanos-per-sec)) nanos-per-day)))) - (cons "plusNanos" (lambda (x n) (ot-with x (jt-floor-mod (+ (ot-nod x) (jt->exact n)) nanos-per-day)))) - (cons "minusNanos" (lambda (x n) (ot-with x (jt-floor-mod (- (ot-nod x) (jt->exact n)) nanos-per-day)))) - (cons "withHour" (lambda (x v) (ot-with x (lt-nano-of-day (lt-with (jt-local-time (ot-nod x)) 'hour (jt->exact v)))))) - (cons "withMinute" (lambda (x v) (ot-with x (lt-nano-of-day (lt-with (jt-local-time (ot-nod x)) 'minute (jt->exact v)))))) - (cons "withSecond" (lambda (x v) (ot-with x (lt-nano-of-day (lt-with (jt-local-time (ot-nod x)) 'second (jt->exact v)))))) - (cons "withNano" (lambda (x v) (ot-with x (lt-nano-of-day (lt-with (jt-local-time (ot-nod x)) 'nano (jt->exact v)))))) - (cons "truncatedTo" (lambda (x u) (ot-with x (lt-nano-of-day (lt-truncate (jt-local-time (ot-nod x)) u))))) - (cons "withOffsetSameLocal" (lambda (x off) (jt-offset-time (ot-nod x) (zo-secs* off)))) - (cons "isBefore" (lambda (x o) (< (- (ot-nod x) (* (ot-offset x) nanos-per-sec)) (- (ot-nod o) (* (ot-offset o) nanos-per-sec))))) - (cons "isAfter" (lambda (x o) (> (- (ot-nod x) (* (ot-offset x) nanos-per-sec)) (- (ot-nod o) (* (ot-offset o) nanos-per-sec))))) - (cons "isEqual" (lambda (x o) (= (- (ot-nod x) (* (ot-offset x) nanos-per-sec)) (- (ot-nod o) (* (ot-offset o) nanos-per-sec))))) - (cons "compareTo" (lambda (x o) (let ((a (- (ot-nod x) (* (ot-offset x) nanos-per-sec))) (b (- (ot-nod o) (* (ot-offset o) nanos-per-sec)))) - (cond ((< a b) -1) ((> a b) 1) (else 0))))) - (cons "equals" (lambda (x o) (and (jt-offset-time? o) (equal? (jhost-state x) (jhost-state o))))) - (cons "hashCode" (lambda (x) (jolt-hash (ot-nod x)))) - (cons "format" (lambda (x fmt) (fmt-format fmt x))) - (cons "toString" (lambda (x) (ot->string x))))) - -;; --- ISO parse for the offset/zoned types ------------------------------------ -;; split off an offset/zone suffix at the end of an ISO datetime string; -> (values -;; local-part offset-secs zone-id-or-#f). offset starts at the first +/-/Z after T. -(define (split-offset-zone s) - (let ((len (string-length s)) - (ti (let loop ((i 0)) (cond ((>= i (string-length s)) #f) - ((or (char=? (string-ref s i) #\T) (char=? (string-ref s i) #\t)) i) - (else (loop (+ i 1))))))) - ;; bracket zone "[Region/City]" at the very end - (let* ((zone-id (and (> len 0) (char=? (string-ref s (- len 1)) #\]) - (let loop ((i (- len 2))) (cond ((< i 0) #f) - ((char=? (string-ref s i) #\[) (substring s (+ i 1) (- len 1))) - (else (loop (- i 1))))))) - (s2 (if zone-id (let loop ((i (- len 1))) (if (char=? (string-ref s i) #\[) (substring s 0 i) (loop (- i 1)))) s)) - (len2 (string-length s2)) - ;; find the offset start (after the T) - (oi (let loop ((i (if ti (+ ti 1) 0))) - (cond ((>= i len2) #f) - ((or (char=? (string-ref s2 i) #\Z) (char=? (string-ref s2 i) #\z)) i) - ((and (> i (if ti (+ ti 1) 0)) (or (char=? (string-ref s2 i) #\+) (char=? (string-ref s2 i) #\-))) i) - (else (loop (+ i 1))))))) - (if oi - (values (substring s2 0 oi) (parse-zone-offset (substring s2 oi len2)) zone-id) - (values s2 0 zone-id))))) -(define (parse-zoned-date-time s) - (call-with-values (lambda () (split-offset-zone s)) - (lambda (local off zone-id) - (call-with-values (lambda () (parse-iso-datetime local)) - (lambda (ed nod) - (let ((zid (if zone-id (zone-id-of zone-id) (jt-zone-id (zo-id off) off)))) - (jt-zoned-dt ed nod off zid))))))) -(define (parse-offset-date-time s) - (call-with-values (lambda () (split-offset-zone s)) - (lambda (local off zone-id) - (call-with-values (lambda () (parse-iso-datetime local)) (lambda (ed nod) (jt-offset-dt ed nod off)))))) -(define (parse-offset-time s) - ;; "HH:mm[:ss]±HH:mm" / "...Z" - (let ((oi (let loop ((i 0)) (cond ((>= i (string-length s)) #f) - ((or (char=? (string-ref s i) #\Z) (char=? (string-ref s i) #\z)) i) - ((and (> i 0) (or (char=? (string-ref s i) #\+) (char=? (string-ref s i) #\-))) i) - (else (loop (+ i 1))))))) - (if oi (jt-offset-time (parse-iso-time (substring s 0 oi)) (parse-zone-offset (substring s oi (string-length s)))) - (jt-offset-time (parse-iso-time s) 0)))) - -;; --- formatter integration --------------------------------------------------- -;; format any java.time value through a dt-formatter pattern. Builds the broken-down -;; fields from the value's local representation; X/Z/x render its offset, z its zone. -(define (jt-value-format-parts v) ; -> (vector y mo d hh mi se nano dow offset-secs zone-id) - (define (from-ed-nod ed nod off zid) - (call-with-values (lambda () (epoch-day->ymd ed)) - (lambda (y m d) - (let ((t (jt-local-time nod))) - (vector y m d (lt-hour t) (lt-minute t) (lt-second t) (lt-nano t) (jt-floor-mod (+ ed 4) 7) off zid))))) - (cond - ((jt-date? v) (call-with-values (lambda () (epoch-day->ymd (ld-epoch-day v))) - (lambda (y m d) (vector y m d 0 0 0 0 (jt-floor-mod (+ (ld-epoch-day v) 4) 7) 0 #f)))) - ((jt-time? v) (let ((t v)) (vector 1970 1 1 (lt-hour t) (lt-minute t) (lt-second t) (lt-nano t) 4 0 #f))) - ((jt-dt? v) (from-ed-nod (ldt-epoch-day v) (ldt-nano-of-day v) 0 #f)) - ((jt-zoned-dt? v) (from-ed-nod (zdt-epoch-day v) (zdt-nano-of-day v) (zdt-offset v) (zid-id (zdt-zone v)))) - ((jt-offset-dt? v) (from-ed-nod (odt-epoch-day v) (odt-nano-of-day v) (odt-offset v) #f)) - ((jt-offset-time? v) (let ((t (jt-local-time (ot-nod v)))) (vector 1970 1 1 (lt-hour t) (lt-minute t) (lt-second t) (lt-nano t) 4 (ot-offset v) #f))) - ((jt-instant? v) #f) ; instants render via format-ms (UTC) - (else #f))) -;; Locale month/day names. Only the locales tick exercises (en, fr) are tabled; -;; an unknown locale falls back to English. French abbreviations follow CLDR/ -;; java.time (most carry a trailing period; "mars"/"mai"/"juin"/"août" don't). -(define fr-month-full - (vector "janvier" "février" "mars" "avril" "mai" "juin" - "juillet" "août" "septembre" "octobre" "novembre" "décembre")) -(define fr-month-abbr - (vector "janv." "févr." "mars" "avr." "mai" "juin" - "juil." "août" "sept." "oct." "nov." "déc.")) -(define fr-day-full ; indexed by day-of-week 0=Sunday - (vector "dimanche" "lundi" "mardi" "mercredi" "jeudi" "vendredi" "samedi")) -(define fr-day-abbr - (vector "dim." "lun." "mar." "mer." "jeu." "ven." "sam.")) -(define (locale-fr? loc) (and (>= (string-length loc) 2) (string=? (substring loc 0 2) "fr"))) -;; month display name for a 1-based month under a locale; full? picks MMMM over MMM. -(define (locale-month-name loc mo full?) - (if (locale-fr? loc) - (vector-ref (if full? fr-month-full fr-month-abbr) (- mo 1)) - (if full? (vector-ref month-names (- mo 1)) (substring (vector-ref month-names (- mo 1)) 0 3)))) -(define (locale-day-name loc dow full?) - (if (locale-fr? loc) - (vector-ref (if full? fr-day-full fr-day-abbr) dow) - (if full? (vector-ref day-names dow) (substring (vector-ref day-names dow) 0 3)))) - -;; the pattern engine for java.time values (extends inst-time.ss's format-ms letters -;; with fractional S and real X/x/Z/z from the value's own offset/zone). -(define (jt-format-pattern pattern v . loc) - (define locale (if (null? loc) "en" (car loc))) - (let ((parts (jt-value-format-parts v))) - (if (not parts) - (format-ms pattern (ms-of v)) ; instant: UTC engine - (let ((y (vector-ref parts 0)) (mo (vector-ref parts 1)) (d (vector-ref parts 2)) - (hh (vector-ref parts 3)) (mi (vector-ref parts 4)) (se (vector-ref parts 5)) - (nano (vector-ref parts 6)) (dow (vector-ref parts 7)) - (off (vector-ref parts 8)) (zid (vector-ref parts 9)) - (n (string-length pattern)) (out (open-output-string))) - (define (run-len i c) (let loop ((j i)) (if (and (< j n) (char=? (string-ref pattern j) c)) (loop (+ j 1)) (- j i)))) - (define (off-iso secs colon allow-z) - (if (and allow-z (= secs 0)) "Z" - (let* ((neg (< secs 0)) (a (abs secs)) (h (quotient a 3600)) (m (quotient (modulo a 3600) 60)) (s (modulo a 60))) - (string-append (if neg "-" "+") (pad2 h) (if colon ":" "") (pad2 m) - (if (= s 0) "" (string-append (if colon ":" "") (pad2 s))))))) - (let loop ((i 0)) - (when (< i n) - (let* ((c (string-ref pattern i)) (k (run-len i c))) - (cond - ((char=? c #\') - (if (and (< (+ i 1) n) (char=? (string-ref pattern (+ i 1)) #\')) - (begin (write-char #\' out) (loop (+ i 2))) - (let close ((j (+ i 1))) - (cond ((>= j n) (loop j)) - ((char=? (string-ref pattern j) #\') (loop (+ j 1))) - (else (write-char (string-ref pattern j) out) (close (+ j 1))))))) - ;; y = year-of-era, Y = week-based-year; for whole dates they agree, - ;; so render Y like y (no ISO-week calendar here). - ((or (char=? c #\y) (char=? c #\Y)) (display (if (>= k 4) (pad4 y) (pad2 (modulo y 100))) out) (loop (+ i k))) - ((char=? c #\M) - (display (cond ((= k 1) (number->string mo)) ((= k 2) (pad2 mo)) - ((= k 3) (locale-month-name locale mo #f)) - (else (locale-month-name locale mo #t))) out) (loop (+ i k))) - ((char=? c #\d) (display (if (= k 1) (number->string d) (pad2 d)) out) (loop (+ i k))) - ((char=? c #\E) (display (locale-day-name locale dow (>= k 4)) out) (loop (+ i k))) - ((char=? c #\H) (display (if (= k 1) (number->string hh) (pad2 hh)) out) (loop (+ i k))) - ((char=? c #\h) (let ((h12 (let ((h (modulo hh 12))) (if (= h 0) 12 h)))) (display (if (= k 1) (number->string h12) (pad2 h12)) out)) (loop (+ i k))) - ((char=? c #\m) (display (if (= k 1) (number->string mi) (pad2 mi)) out) (loop (+ i k))) - ((char=? c #\s) (display (if (= k 1) (number->string se) (pad2 se)) out) (loop (+ i k))) - ((char=? c #\S) (let ((str (let ((p (number->string (quotient nano (expt 10 (max 0 (- 9 k))))))) p))) - (display (string-append (make-string (max 0 (- k (string-length str))) #\0) str) out)) (loop (+ i k))) - ((char=? c #\a) (display (if (< hh 12) "AM" "PM") out) (loop (+ i k))) - ((char=? c #\X) (display (off-iso off (>= k 3) #t) out) (loop (+ i k))) - ((char=? c #\x) (display (off-iso off (>= k 3) #f) out) (loop (+ i k))) - ((char=? c #\Z) (display (if (>= k 3) (off-iso off #t #f) (off-iso off #f #f)) out) (loop (+ i k))) - ((char=? c #\V) (display (or zid (off-iso off #t #t)) out) (loop (+ i k))) - ((char=? c #\z) (display (or zid (off-iso off #t #t)) out) (loop (+ i k))) - (else (write-char c out) (loop (+ i 1))))))) - (get-output-string out))))) - -;; .format on a dt-formatter applied to a java.time value. The pattern comes from the -;; formatter; ISO_* constants carry a literal pattern that round-trips through here. -(define (fmt-format fmt v) - (cond ((and (jhost? fmt) (string=? (jhost-tag fmt) "dt-formatter")) (jt-format-pattern (fmt-pat fmt) v (fmt-locale fmt))) - ((string? fmt) (jt-format-pattern fmt v)) - (else (jt-value->iso v)))) -(define (jt-value->iso v) - (cond ((jt-date? v) (iso-date-str (ld-epoch-day v))) ((jt-time? v) (iso-time-str (lt-nano-of-day v))) - ((jt-dt? v) (iso-datetime-str (ldt-epoch-day v) (ldt-nano-of-day v))) - ((jt-zoned-dt? v) (zdt->string v)) ((jt-offset-dt? v) (odt->string v)) - ((jt-offset-time? v) (ot->string v)) ((jt-instant? v) (iso-instant-str-nanos (inst-nanos v))) - (else (jolt-str-render-one v)))) - -;; .format on the new value types reaches the per-tag method tables above. Add -;; .format to local-date/time/date-time too (they previously had none). -(register-host-methods! "local-date" (list (cons "format" (lambda (x fmt) (fmt-format fmt x))))) -(register-host-methods! "local-time" (list (cons "format" (lambda (x fmt) (fmt-format fmt x))))) -(register-host-methods! "local-date-time" (list (cons "format" (lambda (x fmt) (fmt-format fmt x))))) -(register-host-methods! "instant" (list (cons "format" (lambda (x fmt) (fmt-format fmt x))))) - -;; extend the dt-formatter method table: .format routes java.time values through the -;; richer engine; .parse picks the value type from the parsed fields. -(register-host-methods! "dt-formatter" - (list (cons "format" (lambda (self d) (jt-format-pattern (fmt-pat self) d (fmt-locale self)))) - (cons "getZone" (lambda (self) (jt-zone-id "Z" 0))) - (cons "getLocale" (lambda (self) (make-jhost "locale" (vector (fmt-locale self))))) - (cons "toString" (lambda (self) (fmt-pat self))))) - -;; DateTimeFormatter ISO constants (richer engine; the pattern strings drive parse + -;; format). Re-registers ofPattern so the format-aware Local*/parse statics see them. -(register-class-statics! "DateTimeFormatter" - (list (cons "ofPattern" (lambda (p . _) (mk-formatter (jt-str p)))) - (cons "ISO_LOCAL_DATE" (mk-formatter "yyyy-MM-dd")) - (cons "ISO_LOCAL_TIME" (mk-formatter "HH:mm:ss")) - (cons "ISO_LOCAL_DATE_TIME" (mk-formatter "yyyy-MM-dd'T'HH:mm:ss")) - (cons "ISO_DATE" (mk-formatter "yyyy-MM-dd")) - (cons "ISO_TIME" (mk-formatter "HH:mm:ss")) - (cons "ISO_DATE_TIME" (mk-formatter "yyyy-MM-dd'T'HH:mm:ss")) - (cons "ISO_INSTANT" (mk-formatter "yyyy-MM-dd'T'HH:mm:ssX")) - (cons "ISO_OFFSET_DATE_TIME" (mk-formatter "yyyy-MM-dd'T'HH:mm:ssXXX")) - (cons "ISO_OFFSET_TIME" (mk-formatter "HH:mm:ssXXX")) - (cons "ISO_OFFSET_DATE" (mk-formatter "yyyy-MM-ddXXX")) - (cons "ISO_ZONED_DATE_TIME" (mk-formatter "yyyy-MM-dd'T'HH:mm:ssXXX")) - (cons "ISO_ORDINAL_DATE" (mk-formatter "yyyy-DDD")) - (cons "ISO_WEEK_DATE" (mk-formatter "yyyy-'W'ww-e")) - (cons "BASIC_ISO_DATE" (mk-formatter "yyyyMMdd")) - (cons "RFC_1123_DATE_TIME" (mk-formatter "EEE, dd MMM yyyy HH:mm:ss Z")))) - -;; Local*/parse with a formatter: parse via the pattern, then build the right value. -;; The parse path reuses inst-time.ss parse-ms (UTC) and reads back the fields. -(define (formatter-parse-fields fmt s) - (let ((ms (jinst-ms (parse-ms (fmt-pat fmt) (jt-str s))))) - (let ((ed (jt-floor-div (exact (truncate ms)) 86400000)) (nod (* (jt-floor-mod (exact (truncate ms)) 86400000) 1000000))) - (values ed nod)))) -(register-class-statics! "LocalDate" - (list (cons "parse" (lambda (s . fmt) - (if (null? fmt) (jt-local-date (parse-iso-date (jt-str s))) - (call-with-values (lambda () (formatter-parse-fields (car fmt) s)) (lambda (ed nod) (jt-local-date ed)))))))) -(register-class-statics! "LocalTime" - (list (cons "parse" (lambda (s . fmt) - (if (null? fmt) (jt-local-time (parse-iso-time (jt-str s))) - (call-with-values (lambda () (formatter-parse-fields (car fmt) s)) (lambda (ed nod) (jt-local-time nod)))))))) -(register-class-statics! "LocalDateTime" - (list (cons "parse" (lambda (s . fmt) - (if (null? fmt) - (call-with-values (lambda () (parse-iso-datetime (jt-str s))) (lambda (ed nod) (jt-local-dt ed nod))) - (call-with-values (lambda () (formatter-parse-fields (car fmt) s)) (lambda (ed nod) (jt-local-dt ed nod)))))))) - -;; --- ms-of / equality / hash / compare / print / instance? for Phase-3 types -- -;; extend ms-of so ZonedDateTime/OffsetDateTime/OffsetTime route through to an epoch-ms. -(define %p3-ms-of ms-of) -(set! ms-of (lambda (d) - (cond ((jt-zoned-dt? d) (zdt->ms d)) - ((jt-offset-dt? d) (odt->ms d)) - (else (%p3-ms-of d))))) - -(register-jt-value! "zone-offset" (lambda (x) (zo-id (zo-secs x))) (lambda (x) (jolt-hash (zo-secs x)))) -(register-jt-value! "zone-id" (lambda (x) (zid-id x)) (lambda (x) (jolt-hash (string-hash (zid-id x))))) -(register-str-render! jt-zoned-dt? zdt->string) (register-pr-arm! jt-zoned-dt? zdt->string) -(register-str-render! jt-offset-dt? odt->string) (register-pr-arm! jt-offset-dt? odt->string) -(register-str-render! jt-offset-time? ot->string) (register-pr-arm! jt-offset-time? ot->string) -(register-hash-arm! jt-zoned-dt? (lambda (x) (jolt-hash (zdt->ms x)))) -(register-hash-arm! jt-offset-dt? (lambda (x) (jolt-hash (odt->ms x)))) -(register-hash-arm! jt-offset-time? (lambda (x) (jolt-hash (ot-nod x)))) -;; ZonedDateTime equality is local-date-time + offset + zone id (java.time -;; ZonedDateTime.equals). Compare fields, not the raw state: the state holds a -;; nested zone-id record that Chez equal? compares by identity, not contents. -(register-eq-arm! (lambda (a b) (or (jt-zoned-dt? a) (jt-zoned-dt? b))) - (lambda (a b) (and (jt-zoned-dt? a) (jt-zoned-dt? b) - (= (zdt-epoch-day a) (zdt-epoch-day b)) - (= (zdt-nano-of-day a) (zdt-nano-of-day b)) - (= (zdt-offset a) (zdt-offset b)) - (string=? (zid-id (zdt-zone a)) (zid-id (zdt-zone b)))))) -(register-eq-arm! (lambda (a b) (or (jt-offset-dt? a) (jt-offset-dt? b))) - (lambda (a b) (and (jt-offset-dt? a) (jt-offset-dt? b) (equal? (jhost-state a) (jhost-state b))))) -(register-eq-arm! (lambda (a b) (or (jt-offset-time? a) (jt-offset-time? b))) - (lambda (a b) (and (jt-offset-time? a) (jt-offset-time? b) (equal? (jhost-state a) (jhost-state b))))) - -;; compare for Phase-3 types (same-type only). -(define %p3-prev-compare jolt-compare) -(set! jolt-compare - (lambda (a b) - (cond - ((and (jt-zoned-dt? a) (jt-zoned-dt? b)) (let ((x (zdt->ms a)) (y (zdt->ms b))) (cond ((< x y) -1) ((> x y) 1) (else 0)))) - ((and (jt-offset-dt? a) (jt-offset-dt? b)) (let ((x (odt->ms a)) (y (odt->ms b))) (cond ((< x y) -1) ((> x y) 1) (else 0)))) - ((and (jt-zone-offset? a) (jt-zone-offset? b)) (let ((x (zo-secs a)) (y (zo-secs b))) (cond ((< x y) -1) ((> x y) 1) (else 0)))) - ;; #inst (java.util.Date) values compare by epoch-ms. - ((and (jinst? a) (jinst? b)) (let ((x (jinst-ms a)) (y (jinst-ms b))) (cond ((< x y) -1) ((> x y) 1) (else 0)))) - (else (%p3-prev-compare a b))))) -(def-var! "clojure.core" "compare" jolt-compare) - -;; instance? for the Phase-3 tags. -(register-instance-check-arm! - (lambda (type-sym val) - (let ((tn (short-class-name (symbol-t-name type-sym)))) - (cond - ((jt-zone-offset? val) (if (member tn '("ZoneOffset" "ZoneId")) #t 'pass)) - ((jt-zone-id? val) (if (string=? tn "ZoneId") #t 'pass)) - ((jt-zoned-dt? val) (if (string=? tn "ZonedDateTime") #t 'pass)) - ((jt-offset-dt? val) (if (string=? tn "OffsetDateTime") #t 'pass)) - ((jt-offset-time? val) (if (string=? tn "OffsetTime") #t 'pass)) - ((and (jhost? val) (string=? (jhost-tag val) "clock")) (if (string=? tn "Clock") #t 'pass)) - ((and (jhost? val) (string=? (jhost-tag val) "dt-formatter")) (if (string=? tn "DateTimeFormatter") #t 'pass)) - ((and (jhost? val) (string=? (jhost-tag val) "temporal-adjuster")) (if (member tn '("TemporalAdjuster")) #t 'pass)) - (else 'pass))))) diff --git a/host/chez/java/math.ss b/host/chez/java/math.ss deleted file mode 100644 index bc0ef21..0000000 --- a/host/chez/java/math.ss +++ /dev/null @@ -1,67 +0,0 @@ -;; clojure.math — host shim over native flonum math. -;; -;; clojure.math is registered as native bindings, NOT a .clj file — so there's no -;; source tier to emit. The def-var! shims here back each clojure.math fn over -;; Chez's native procedures. The analyzer knows the clojure.math ns exists, so a -;; ref like clojure.math/sqrt lowers to a var-deref; these cells back it at -;; runtime. -;; -;; jolt is all-flonum, so every result is a flonum (inputs arrive as flonums; Chez -;; sqrt/sin/expt/... return flonums for flonum args). Semantics match -;; Clojure 1.11 clojure.math: round = floor(x+0.5), rint = round-half-even, -;; floor/ceil/floor-div return doubles, to-degrees/to-radians via PI. - -(define jolt-math-pi (acos -1.0)) -(define jolt-math-e (exp 1.0)) - -(define (jolt-math-cbrt x) - ;; sign-aware so negative inputs stay real (expt of a negative flonum to a - ;; fractional power goes complex). - (if (< x 0.0) - (- (expt (- x) (/ 1.0 3.0))) - (expt x (/ 1.0 3.0)))) - -;; clojure.math/round returns a long (exact); floor/ceil/signum/rint return doubles. -(define (jolt-math-round x) (exact (floor (+ x 0.5)))) -(define (jolt-math-signum x) (cond ((< x 0.0) -1.0) ((> x 0.0) 1.0) (else 0.0))) -(define (jolt-math-to-degrees r) (/ (* r 180.0) jolt-math-pi)) -(define (jolt-math-to-radians d) (/ (* d jolt-math-pi) 180.0)) -(define (jolt-math-hypot a b) (sqrt (+ (* a a) (* b b)))) -(define (jolt-math-floor-div a b) (floor (/ a b))) -(define (jolt-math-floor-mod a b) (- a (* b (floor (/ a b))))) - -;; clojure.math fns always return a DOUBLE; Chez's sqrt/expt/sin/floor/... return -;; EXACT for exact args ((sqrt 9) -> 3, (sin 0) -> 0), so coerce. -(define (m1 f) (lambda (x) (exact->inexact (f x)))) -(define (m2 f) (lambda (a b) (exact->inexact (f a b)))) -(def-var! "clojure.math" "sqrt" (m1 sqrt)) -(def-var! "clojure.math" "cbrt" jolt-math-cbrt) -(def-var! "clojure.math" "pow" (m2 expt)) -(def-var! "clojure.math" "exp" (m1 exp)) -(def-var! "clojure.math" "expm1" (lambda (x) (- (exp x) 1.0))) -(def-var! "clojure.math" "log" (m1 log)) -(def-var! "clojure.math" "log10" (lambda (x) (exact->inexact (log x 10.0)))) -(def-var! "clojure.math" "log1p" (lambda (x) (log (+ 1.0 x)))) -(def-var! "clojure.math" "sin" (m1 sin)) -(def-var! "clojure.math" "cos" (m1 cos)) -(def-var! "clojure.math" "tan" (m1 tan)) -(def-var! "clojure.math" "asin" (m1 asin)) -(def-var! "clojure.math" "acos" (m1 acos)) -(def-var! "clojure.math" "atan" (m1 atan)) -;; clojure.math/atan2 is atan2(y, x); Chez's 2-arg atan is (atan y x). -(def-var! "clojure.math" "atan2" (lambda (y x) (exact->inexact (atan y x)))) -(def-var! "clojure.math" "sinh" (m1 sinh)) -(def-var! "clojure.math" "cosh" (m1 cosh)) -(def-var! "clojure.math" "tanh" (m1 tanh)) -(def-var! "clojure.math" "floor" (m1 floor)) -(def-var! "clojure.math" "ceil" (m1 ceiling)) -(def-var! "clojure.math" "rint" (m1 round)) -(def-var! "clojure.math" "round" jolt-math-round) -(def-var! "clojure.math" "signum" jolt-math-signum) -(def-var! "clojure.math" "to-degrees" jolt-math-to-degrees) -(def-var! "clojure.math" "to-radians" jolt-math-to-radians) -(def-var! "clojure.math" "hypot" jolt-math-hypot) -(def-var! "clojure.math" "floor-div" jolt-math-floor-div) -(def-var! "clojure.math" "floor-mod" jolt-math-floor-mod) -(def-var! "clojure.math" "E" jolt-math-e) -(def-var! "clojure.math" "PI" jolt-math-pi) diff --git a/host/chez/java/natives-array.ss b/host/chez/java/natives-array.ss deleted file mode 100644 index 6cbe13a..0000000 --- a/host/chez/java/natives-array.ss +++ /dev/null @@ -1,210 +0,0 @@ -;; natives-array.ss — Java-style mutable arrays for the Chez host. -;; -;; A jolt-array wraps a Chez mutable vector + a `kind` tag (for bytes?). The array -;; CONSTRUCTORS are native (they build the backing); the overlay's aget/aset/alength -;; are pure over count / nth / jolt.host/ref-put!, so we extend those dispatchers -;; to see a jolt-array (backed by a Chez vector). Loaded after host-table.ss (ref-put!), -;; transients.ss, seq.ss (the dispatchers it chains). - -(define-record-type jolt-array (fields (mutable vec) kind) (nongenerative jolt-array-v1)) - -;; JVM array class name per element kind ((class (int-array 3)) -> "[I", like the -;; JVM's Class.getName for arrays). Object arrays use the descriptor form. -(define (na-array-class-name arr) - (case (jolt-array-kind arr) - ((int) "[I") ((long) "[J") ((short) "[S") ((double) "[D") - ((float) "[F") ((boolean) "[Z") ((byte) "[B") ((char) "[C") - (else "[Ljava.lang.Object;"))) - -(define (na-idx i) (if (and (number? i) (not (exact? i))) (exact (floor i)) i)) -(define (na-from-seq x kind) (make-jolt-array (list->vector (seq->list (jolt-seq x))) kind)) -;; (T-array size) | (T-array size init) | (T-array seq) -(define (na-num-array a rest init kind) - (if (number? a) - (make-jolt-array (make-vector (exact (na-idx a)) (if (pair? rest) (car rest) init)) kind) - (na-from-seq a kind))) - -;; numeric tower: array element defaults / masked bytes / count are -;; EXACT integers (= JVM byte/short/int), matching exact integer literals. -(define (na-byte-of v) (bitwise-and (exact (floor v)) #xff)) - -;; --- constructors ----------------------------------------------------------- -(define (na-object-array a . rest) (na-num-array a rest jolt-nil 'object)) -;; integer kinds default to exact 0 (JVM int/long/short 0 -> "0", not "0.0"). -(define (na-int-array a . rest) (na-num-array a rest 0 'int)) -(define (na-long-array a . rest) (na-num-array a rest 0 'long)) -(define (na-short-array a . rest) (na-num-array a rest 0 'short)) -(define (na-double-array a . rest) (na-num-array a rest 0.0 'double)) -(define (na-float-array a . rest) (na-num-array a rest 0.0 'float)) -(define (na-boolean-array a . rest) (na-num-array a rest #f 'boolean)) -;; char-array is a real 'char array (instance? "[C"), seqing as chars via the -;; dispatchers below — io/reader (extended here) and str/slurp consume the seq. -(define (na-char-array a . rest) - (cond - ((string? a) (make-jolt-array (list->vector (string->list a)) 'char)) - ((number? a) (make-jolt-array (make-vector (exact (na-idx a)) #\nul) 'char)) - (else (make-jolt-array - (list->vector (map (lambda (c) (if (char? c) c (integer->char (exact (truncate c))))) - (seq->list (jolt-seq a)))) 'char)))) -;; (byte-array n [init]) | (byte-array coll). Also coerces the host's OTHER byte -;; carrier — a Chez bytevector (what String/.getBytes produce) — and a string's -;; UTF-8 bytes, so bytevector and byte-array interconvert across interop seams. -(define (na-byte-array a . rest) - (cond - ((number? a) (make-jolt-array (make-vector (exact (na-idx a)) (na-byte-of (if (pair? rest) (car rest) 0))) 'byte)) - ((bytevector? a) (make-jolt-array (list->vector (bytevector->u8-list a)) 'byte)) - ((string? a) (make-jolt-array (list->vector (bytevector->u8-list (string->utf8 a))) 'byte)) - (else (make-jolt-array (list->vector (map na-byte-of (seq->list (jolt-seq a)))) 'byte)))) -;; jolt byte-array -> Chez bytevector (for String decode / utf8->string). -(define (na-bytearray->bv arr) - (let* ((v (jolt-array-vec arr)) (n (vector-length v)) (bv (make-bytevector n))) - (do ((i 0 (+ i 1))) ((= i n)) (bytevector-u8-set! bv i (bitwise-and (exact (vector-ref v i)) #xff))) - bv)) -(define (na-make-array a . rest) ; (make-array len) | (make-array type len ...) - (make-jolt-array (make-vector (exact (na-idx (if (number? a) a (car rest)))) jolt-nil) 'object)) -(define (na-into-array a . rest) (na-from-seq (if (pair? rest) (car rest) a) 'object)) -(define (na-to-array coll) (na-from-seq coll 'object)) -(define (na-aclone arr) - (if (jolt-array? arr) - (make-jolt-array (vector-copy (jolt-array-vec arr)) (jolt-array-kind arr)) - (na-from-seq arr 'object))) - -;; --- typed aset (return the stored value) ----------------------------------- -(define (na-aset! arr i v) (vector-set! (jolt-array-vec arr) (exact (na-idx i)) v) v) -(define (na-aset-int arr i v) (na-aset! arr i v)) -(define (na-aset-long arr i v) (na-aset! arr i v)) -(define (na-aset-short arr i v) (na-aset! arr i v)) -(define (na-aset-double arr i v) (na-aset! arr i v)) -(define (na-aset-float arr i v) (na-aset! arr i v)) -(define (na-aset-char arr i v) (na-aset! arr i v)) -(define (na-aset-boolean arr i v) (na-aset! arr i v)) -(define (na-aset-byte arr i v) - (vector-set! (jolt-array-vec arr) (exact (na-idx i)) (na-byte-of v)) v) - -;; --- coercions (identity on arrays; byte/short are masked scalar casts) ------ -(define (na-bytes x) (if (and (jolt-array? x) (eq? (jolt-array-kind x) 'byte)) x (na-byte-array x))) -(define (na-bytes? x) (and (jolt-array? x) (eq? (jolt-array-kind x) 'byte))) -(define (na-identity x) x) -(define (na-byte x) (jolt-byte-cast x)) -(define (na-short x) (jolt-short-cast x)) - -;; --- chunked seqs ----------------------------------------------------------- -;; The chunked-seq accessors (chunked-seq? / chunk-first / chunk-rest / chunk-next) -;; live in seq.ss with the cseq core they read; here we only bind them plus the -;; chunk-builder API (clojure.lang.ChunkBuffer + chunk-cons). chunk-buffer collects -;; appended items, chunk seals them into a pvec chunk, and chunk-cons prepends that -;; chunk onto a rest seq as a real ChunkedCons (cseq-chunked) — empty chunk == just -;; the rest, like clojure.core/chunk-cons. -(define-record-type jolt-chunkbuf (fields (mutable items)) (nongenerative jolt-chunkbuf-v1)) -(define (na-chunk-buffer cap) (make-jolt-chunkbuf '())) -(define (na-chunk-append b x) (jolt-chunkbuf-items-set! b (append (jolt-chunkbuf-items b) (list x))) b) -(define (na-chunk b) (make-pvec (list->vector (jolt-chunkbuf-items b)))) -(define (na-chunk-cons chunk rest) - (if (fx=? 0 (pvec-count chunk)) rest (cseq-chunked chunk 0 rest))) - -;; --- extend the collection dispatchers to see a jolt-array ------------------ -(define %na-count jolt-count) -(set! jolt-count (lambda (c) (if (jolt-array? c) (vector-length (jolt-array-vec c)) (%na-count c)))) -(define %na-seq jolt-seq) -(set! jolt-seq (lambda (c) (if (jolt-array? c) (list->cseq (vector->list (jolt-array-vec c))) (%na-seq c)))) -(define %na-nth jolt-nth) -(set! jolt-nth - (case-lambda - ((c i) (if (jolt-array? c) (vector-ref (jolt-array-vec c) (exact (na-idx i))) (%na-nth c i))) - ((c i d) (if (jolt-array? c) - (let ((v (jolt-array-vec c)) (j (exact (na-idx i)))) - (if (and (>= j 0) (< j (vector-length v))) (vector-ref v j) d)) - (%na-nth c i d))))) -(def-var! "jolt.host" "array-value?" (lambda (x) (if (jolt-array? x) #t jolt-nil))) -(define %na-get jolt-get) -(set! jolt-get - (case-lambda - ((c k) (if (jolt-array? c) (jolt-nth c k jolt-nil) (%na-get c k))) - ((c k d) (if (jolt-array? c) (jolt-nth c k d) (%na-get c k d))))) -;; aset (overlay) writes through jolt.host/ref-put! — mutate the slot, return arr. -;; count/nth/seq/get above are NATIVE-OPS (inlined at call sites), so aget/alength/ -;; array-seq/vec already use the set!-extended globals; ref-put! is a host var -;; (var-deref'd), so re-assert its cell to the array-aware closure. -(define %na-ref-put! jolt-ref-put!) -(set! jolt-ref-put! - (lambda (t k v) - (if (jolt-array? t) (begin (vector-set! (jolt-array-vec t) (exact (na-idx k)) v) t) - (%na-ref-put! t k v)))) -(def-var! "jolt.host" "ref-put!" jolt-ref-put!) - -;; --- array identity: type / class / instance? recognize arrays --------------- -;; (type arr) / (class arr) -> the JVM array class name; (class …) delegates to -;; (jolt-type …) for arrays, so extending jolt-type covers both. -(define %na-type jolt-type) -(set! jolt-type (lambda (x) (if (jolt-array? x) (na-array-class-name x) (%na-type x)))) - -;; instance? over an array class token ([I, [C, …). An array token reaches us as -;; a string ("[C", from (Class/forName "[C")) — the dispatcher leaves it a string -;; (non-array string tokens are already normalized to symbols there); decide it -;; here, deferring everything else. -(register-instance-check-arm! - (lambda (type-sym val) - (let ((tname (cond ((string? type-sym) type-sym) - ((symbol-t? type-sym) (symbol-t-name type-sym)) - (else #f)))) - (if (and tname (> (string-length tname) 0) (char=? (string-ref tname 0) #\[)) - (and (jolt-array? val) (string=? (na-array-class-name val) tname)) - 'pass)))) - -;; clojure.java.io/reader over a char-array reads its chars (the JVM char[] branch). -(def-var! "clojure.java.io" "reader" - (lambda (x) - (if (jolt-array? x) - (host-new "StringReader" - (apply string-append (map jolt-str-render-one (seq->list (jolt-seq x))))) - (jolt-io-reader x)))) - -;; --- bind into clojure.core ------------------------------------------------- -(for-each (lambda (p) (def-var! "clojure.core" (car p) (cdr p))) - (list - (cons "object-array" na-object-array) (cons "int-array" na-int-array) - (cons "long-array" na-long-array) (cons "short-array" na-short-array) - (cons "double-array" na-double-array) (cons "float-array" na-float-array) - (cons "boolean-array" na-boolean-array) - (cons "byte-array" na-byte-array) (cons "char-array" na-char-array) - (cons "array?" (lambda (x) (jolt-array? x))) - (cons "make-array" na-make-array) - (cons "into-array" na-into-array) (cons "to-array" na-to-array) (cons "aclone" na-aclone) - (cons "aset-int" na-aset-int) (cons "aset-long" na-aset-long) - (cons "aset-short" na-aset-short) (cons "aset-double" na-aset-double) - (cons "aset-float" na-aset-float) (cons "aset-char" na-aset-char) - (cons "aset-boolean" na-aset-boolean) (cons "aset-byte" na-aset-byte) - (cons "bytes" na-bytes) (cons "bytes?" na-bytes?) - (cons "booleans" na-identity) (cons "ints" na-identity) (cons "longs" na-identity) - (cons "shorts" na-identity) (cons "doubles" na-identity) (cons "floats" na-identity) - (cons "chars" na-identity) (cons "byte" na-byte) (cons "short" na-short) - (cons "chunk-buffer" na-chunk-buffer) (cons "chunk-append" na-chunk-append) - (cons "chunk" na-chunk) (cons "chunk-cons" na-chunk-cons) - (cons "chunk-first" na-chunk-first) (cons "chunk-rest" na-chunk-rest) - (cons "chunk-next" na-chunk-next) (cons "chunked-seq?" na-chunked-seq?))) - -;; --- clojure.java.io/copy --------------------------------------------------- -;; Copy src -> dst, JVM-style. Raw bytes (byte-array / bytevector / string) and a -;; jhost reader write in one shot; any other source (a stream shim with a .read -;; method, e.g. jolt-lang/http-client's ByteArrayInputStream) drains via .read -;; into a byte-array buffer and .write to dst — both reached through method -;; dispatch, so a library's tagged-table streams work without the host knowing -;; their layout. Lives here (not io.ss) because io.ss loads before byte-array. -(define (jolt-io-copy src dst . _opts) - (define (write-all! bytes) - (record-method-dispatch dst "write" (list->cseq (list bytes 0 (vector-length (jolt-array-vec bytes)))))) - (cond - ((or (bytevector? src) (string? src) - (and (jolt-array? src) (eq? (jolt-array-kind src) 'byte))) - (write-all! (na-byte-array src))) - ((and (jhost? src) (member (jhost-tag src) '("string-reader" "pushback-reader"))) - (write-all! (na-byte-array (drain-reader src)))) - (else - (let ((buf (na-byte-array 8192))) - (let loop () - (let ((n (record-method-dispatch src "read" (list->cseq (list buf 0 8192))))) - (when (and (number? n) (> (jnum->exact n) 0)) - (record-method-dispatch dst "write" (list->cseq (list buf 0 n))) - (loop))))))) - jolt-nil) -(def-var! "clojure.java.io" "copy" jolt-io-copy) diff --git a/host/chez/java/natives-queue.ss b/host/chez/java/natives-queue.ss deleted file mode 100644 index b32889e..0000000 --- a/host/chez/java/natives-queue.ss +++ /dev/null @@ -1,69 +0,0 @@ -;; natives-queue.ss — clojure.lang.PersistentQueue for the Chez host. -;; -;; A functional queue: a `front` Scheme list (the dequeue end, head = front of the -;; queue) + a reversed `rear` Scheme list (the enqueue end, head = most recent). -;; conj adds to rear; peek/first read front; pop drops the front, rebalancing -;; rear->front when front empties — amortized O(1). A queue is jolt-sequential?, so -;; seq=?/seq-hash give cross-type equality (= [1 2 3] (queue 1 2 3)) for free, like -;; the JVM. Loaded after seq/collections/lazy-bridge/records/host-table so every -;; dispatcher it chains is at its latest binding. - -(define-record-type jolt-queue (fields front rear cnt) (nongenerative jolt-queue-v1)) -(define jolt-queue-empty (make-jolt-queue '() '() 0)) - -(define (queue-conj q x) - (if (null? (jolt-queue-front q)) - (make-jolt-queue (list x) '() (fx+ (jolt-queue-cnt q) 1)) - (make-jolt-queue (jolt-queue-front q) (cons x (jolt-queue-rear q)) (fx+ (jolt-queue-cnt q) 1)))) -(define (queue->list q) (append (jolt-queue-front q) (reverse (jolt-queue-rear q)))) -(define (queue-peek q) (if (null? (jolt-queue-front q)) jolt-nil (car (jolt-queue-front q)))) -(define (queue-pop q) - (let ((f (jolt-queue-front q))) - ;; popping an empty PersistentQueue returns it (Clojure's pop: if f==null - ;; return this) — unlike a vector, which throws. - (cond ((null? f) q) - ((null? (cdr f)) (make-jolt-queue (reverse (jolt-queue-rear q)) '() (fx- (jolt-queue-cnt q) 1))) - (else (make-jolt-queue (cdr f) (jolt-queue-rear q) (fx- (jolt-queue-cnt q) 1)))))) - -;; --- extend the collection dispatchers to see a jolt-queue ------------------ -(define %q-seq jolt-seq) -(set! jolt-seq (lambda (x) (if (jolt-queue? x) - (let ((l (queue->list x))) (if (null? l) jolt-nil (list->cseq l))) - (%q-seq x)))) -(define %q-count jolt-count) -(set! jolt-count (lambda (x) (if (jolt-queue? x) (jolt-queue-cnt x) (%q-count x)))) -(define %q-empty? jolt-empty?) -(set! jolt-empty? (lambda (x) (if (jolt-queue? x) (fx=? 0 (jolt-queue-cnt x)) (%q-empty? x)))) -(define %q-peek jolt-peek) -(set! jolt-peek (lambda (x) (if (jolt-queue? x) (queue-peek x) (%q-peek x)))) -(define %q-pop jolt-pop) -(set! jolt-pop (lambda (x) (if (jolt-queue? x) (queue-pop x) (%q-pop x)))) -(define %q-conj1 jolt-conj1) -(set! jolt-conj1 (lambda (coll x) (if (jolt-queue? coll) (queue-conj coll x) (%q-conj1 coll x)))) -;; sequential => seq=?/seq-hash handle queue equality + hashing. -(define %q-sequential? jolt-sequential?) -(set! jolt-sequential? (lambda (x) (or (jolt-queue? x) (%q-sequential? x)))) - -;; printing: render the elements as a parenthesized list (delegate to the seq path). -(define (jolt-seq-or-empty x) (let ((s (jolt-seq x))) (if (jolt-nil? s) jolt-empty-list s))) -(register-pr-readable-arm! jolt-queue? (lambda (x) (jolt-pr-readable (jolt-seq-or-empty x)))) -(register-str-render! jolt-queue? (lambda (x) (jolt-str-render-one (jolt-seq-or-empty x)))) - -;; class / type / instance? recognize a queue. -(register-class-arm! jolt-queue? (lambda (x) "clojure.lang.PersistentQueue")) -(register-instance-check-arm! - (lambda (type-sym val) - (if (jolt-queue? val) - (let ((tn (cond ((string? type-sym) type-sym) - ((symbol-t? type-sym) (symbol-t-name type-sym)) (else "")))) - (and (member (last-dot tn) - '("PersistentQueue" "IPersistentCollection" "Sequential" "Collection" "Object")) - #t)) - 'pass))) - -;; clojure.lang.PersistentQueue/EMPTY + a queue? predicate. -(register-class-statics! "PersistentQueue" (list (cons "EMPTY" jolt-queue-empty))) -(register-class-statics! "clojure.lang.PersistentQueue" (list (cons "EMPTY" jolt-queue-empty))) -(def-var! "clojure.core" "queue?" (lambda (x) (jolt-queue? x))) -;; the FQ class token self-evaluates (for (instance? clojure.lang.PersistentQueue …)). -(def-var! "clojure.core" "clojure.lang.PersistentQueue" "clojure.lang.PersistentQueue") diff --git a/host/chez/java/natives-str.ss b/host/chez/java/natives-str.ss deleted file mode 100644 index d1886ac..0000000 --- a/host/chez/java/natives-str.ss +++ /dev/null @@ -1,400 +0,0 @@ -;; natives-str.ss — java.lang.String method interop on Chez. -;; -;; (.method s arg*) on a string target lowers to record-method-dispatch (emit.ss), -;; which falls through to jolt-string-method here when the target is a string. -;; Covers the -;; portable java.lang.String/CharSequence methods cljc libraries actually call. -;; Case mapping is ASCII (the whole engine is byte-oriented), indexOf returns -1 -;; on miss as on the JVM, indices come in as flonums, char results are Scheme -;; chars, and numeric results are flonums to match jolt's number model. -;; -;; Loaded from rt.ss AFTER regex.ss (the regex methods reuse jolt-re-pattern / -;; regex-t-irx) and records.ss (which calls jolt-string-method). - -;; --- ASCII case mapping (byte-oriented) ------- -(define (ascii-up-char c) - (if (and (char<=? #\a c) (char<=? c #\z)) - (integer->char (fx- (char->integer c) 32)) c)) -(define (ascii-down-char c) - (if (and (char<=? #\A c) (char<=? c #\Z)) - (integer->char (fx+ (char->integer c) 32)) c)) -(define (ascii-string-up s) (list->string (map ascii-up-char (string->list s)))) -(define (ascii-string-down s) (list->string (map ascii-down-char (string->list s)))) - -;; --- ASCII trim: drop leading/trailing chars with code <= space (JVM .trim) --- -(define (str-trim s) - (let ((len (string-length s))) - (let scan-l ((i 0)) - (cond ((fx=? i len) "") - ((char<=? (string-ref s i) #\space) (scan-l (fx+ i 1))) - (else (let scan-r ((j (fx- len 1))) - (if (char<=? (string-ref s j) #\space) - (scan-r (fx- j 1)) - (substring s i (fx+ j 1))))))))) -(define (str-triml s) - (let ((len (string-length s))) - (let loop ((i 0)) - (cond ((fx=? i len) "") - ((char<=? (string-ref s i) #\space) (loop (fx+ i 1))) - (else (substring s i len)))))) -(define (str-trimr s) - (let loop ((j (fx- (string-length s) 1))) - (cond ((fx? (fx+ i nlen) slen) -1) - ((string=? (substring s i (fx+ i nlen)) needle) i) - (else (loop (fx+ i 1))))))) -(define (str-last-index-of s needle) - (let ((nlen (string-length needle)) (slen (string-length s))) - (let loop ((i (fx- slen nlen)) (found -1)) - (cond ((fx its 1-char string; a number -> the char at that -;; code point (JVM treats an int arg to indexOf as a char code); else a string. -(define (str-needle x) - (cond ((char? x) (string x)) - ((number? x) (string (integer->char (exact (truncate x))))) - ((string? x) x) - (else (jolt-str x)))) - -;; literal replace-all (JVM String.replace(CharSequence,CharSequence)). -(define (str-replace-literal s a b) - (let ((alen (string-length a)) (slen (string-length s))) - (if (fx=? alen 0) s - (let loop ((i 0) (acc '())) - (cond ((fx>? (fx+ i alen) slen) - (apply string-append (reverse (cons (substring s i slen) acc)))) - ((string=? (substring s i (fx+ i alen)) a) - (loop (fx+ i alen) (cons b acc))) - (else (loop (fx+ i 1) (cons (substring s i (fx+ i 1)) acc)))))))) - -;; A compiled irregex for a plain-string Java-regex pattern (or a jolt-regex). -(define (str-irx pat) (regex-t-irx (jolt-re-pattern pat))) - -;; JVM String.split: split fully, then drop trailing empty strings. -(define (str-split-drop-trailing parts) - (let loop ((p (reverse parts))) - (if (and (pair? p) (string=? (car p) "")) (loop (cdr p)) (reverse p)))) - -;; Encode a string to bytes (a bytevector) under a named charset. UTF-8 default; -;; ISO-8859-1/latin1/ascii are one byte per char; UTF-16/UTF-32 via Chez's codecs -;; (plain "UTF-16" emits a big-endian BOM then BE, matching the JVM). Shared by -;; .getBytes and decode-bytevector (String.). -(define (charset-encode-bv s csname) - (let ((cs (ascii-string-down (if (string? csname) csname (jolt-str-render-one csname))))) - (cond - ((or (string=? cs "utf-8") (string=? cs "utf8")) (string->utf8 s)) - ((member cs '("iso-8859-1" "latin1" "iso8859-1" "us-ascii" "ascii")) - (let* ((n (string-length s)) (bv (make-bytevector n))) - (do ((i 0 (+ i 1))) ((= i n) bv) - (bytevector-u8-set! bv i (bitwise-and (char->integer (string-ref s i)) #xff))))) - ((string=? cs "utf-16be") (string->utf16 s (endianness big))) - ((string=? cs "utf-16le") (string->utf16 s (endianness little))) - ((or (string=? cs "utf-16") (string=? cs "utf16") (string=? cs "unicode")) - (let ((be (string->utf16 s (endianness big)))) - (let* ((n (bytevector-length be)) (bv (make-bytevector (+ n 2)))) - (bytevector-u8-set! bv 0 #xfe) (bytevector-u8-set! bv 1 #xff) - (bytevector-copy! be 0 bv 2 n) bv))) - ((or (string=? cs "utf-32be") (string=? cs "utf-32") (string=? cs "utf32")) - (string->utf32 s (endianness big))) - ((string=? cs "utf-32le") (string->utf32 s (endianness little))) - (else (string->utf8 s))))) - -;; Object.hashCode parity: Java's specified String hash and Clojure's Symbol hash -;; (Util.hashCombine), so (.hashCode s) / (.hashCode sym) match the JVM. 32-bit int. -(define (jolt-u32 x) (bitwise-and x #xFFFFFFFF)) -(define (jolt-s32 x) (let ((m (jolt-u32 x))) (if (>= m #x80000000) (- m #x100000000) m))) -(define (java-string-hash s) - (let ((n (string-length s))) - (let loop ((i 0) (h 0)) - (if (fxinteger (string-ref s i))))) - (jolt-s32 h))))) -(define (java-hash-combine seed hash) - (let* ((su (jolt-u32 seed)) - (sl (bitwise-arithmetic-shift-left su 6)) - (sr (bitwise-arithmetic-shift-right (jolt-s32 su) 2)) - (add (+ (jolt-u32 hash) #x9e3779b9 sl sr))) - (jolt-s32 (bitwise-xor su (jolt-u32 add))))) -(define (java-symbol-hash name ns) - (java-hash-combine (java-string-hash name) (if ns (java-string-hash ns) 0))) - -(define (jolt-string-method method s rest) - (define (arg n) (list-ref rest n)) - (cond - ((string=? method "toString") s) - ((string=? method "hashCode") (java-string-hash s)) - ((string=? method "toLowerCase") (ascii-string-down s)) - ((string=? method "toUpperCase") (ascii-string-up s)) - ((string=? method "trim") (str-trim s)) - ((string=? method "length") (string-length s)) ; exact int (= JVM) - ((string=? method "isEmpty") (fx=? (string-length s) 0)) - ((string=? method "charAt") (string-ref s (jolt->idx (arg 0)))) - ((string=? method "substring") - (substring s (jolt->idx (arg 0)) - (if (fx>? (length rest) 1) (jolt->idx (arg 1)) (string-length s)))) - ((string=? method "indexOf") - (str-index-of s (str-needle (arg 0)) - (if (fx>? (length rest) 1) (jolt->idx (arg 1)) 0))) - ((string=? method "lastIndexOf") - (str-last-index-of s (str-needle (arg 0)))) - ((string=? method "startsWith") - (let ((p (arg 0))) (and (fx>=? (string-length s) (string-length p)) - (string=? (substring s 0 (string-length p)) p)))) - ((string=? method "endsWith") - (let ((p (arg 0)) (slen (string-length s))) - (and (fx>=? slen (string-length p)) - (string=? (substring s (fx- slen (string-length p)) slen) p)))) - ((string=? method "contains") - (fx>=? (str-index-of s (str-needle (arg 0)) 0) 0)) - ((string=? method "concat") (string-append s (arg 0))) - ((string=? method "replace") (str-replace-literal s (str-needle (arg 0)) (str-needle (arg 1)))) - ((string=? method "equalsIgnoreCase") - (string=? (ascii-string-down s) (ascii-string-down (arg 0)))) - ((string=? method "compareTo") - (let ((o (arg 0))) (cond ((string? s o) 1.0) (else 0.0)))) - ((string=? method "getBytes") - ;; (.getBytes s) / (.getBytes s charset) -> a jolt byte-array (seqable / - ;; countable / alength-able, like (byte-array …)); the JVM returns byte[]. - (na-byte-array - (charset-encode-bv s (if (null? rest) - "utf-8" - (if (string? (arg 0)) (arg 0) (jolt-str-render-one (arg 0))))))) - ((string=? method "matches") (if (irregex-match (str-irx (arg 0)) s) #t #f)) - ((string=? method "replaceAll") (irregex-replace/all (str-irx (arg 0)) s (arg 1))) - ((string=? method "replaceFirst") (irregex-replace (str-irx (arg 0)) s (arg 1))) - ((string=? method "split") - (apply jolt-vector (str-split-drop-trailing (irregex-split (str-irx (arg 0)) s)))) - ;; universal object-methods that reach a string target (seed object-methods): - ;; a thrown string / Exception. ctor (which keeps the message string) answers - ;; getMessage with itself; equals is value equality. - ((or (string=? method "getMessage") (string=? method "getLocalizedMessage")) s) - ((string=? method "equals") (and (string? (arg 0)) (string=? s (arg 0)))) - ;; String.intern: jolt strings aren't pooled, but value equality holds, so the - ;; canonical representation is the string itself. - ((string=? method "intern") s) - ;; A class token is its canonical-name string, so Class methods land here: - ;; (.getName (.getClass x)) / (.getSimpleName …) over the name string. - ((or (string=? method "getName") (string=? method "getCanonicalName")) s) - ((string=? method "getSimpleName") - (let ((i (str-last-index-of s "."))) (if (>= i 0) (substring s (+ i 1) (string-length s)) s))) - ;; .getChars srcBegin srcEnd dst dstBegin — copy s[srcBegin,srcEnd) into the - ;; char-array dst at dstBegin (used by buffered readers, e.g. data.json). - ((string=? method "getChars") - (let ((src-begin (jolt->idx (arg 0))) (src-end (jolt->idx (arg 1))) - (dv (jolt-array-vec (arg 2))) (dst-begin (jolt->idx (arg 3)))) - (let loop ((i src-begin) (j dst-begin)) - (when (fxidx (arg 0)) (jolt->idx (arg 1)))) - ;; Class.isArray over a class-name string: array classes are "[…" (e.g. "[C"). - ((string=? method "isArray") (and (fx>? (string-length s) 0) (char=? (string-ref s 0) #\[))) - (else (error #f (string-append "No method " method " for value"))))) - -;; --- clojure.core str-* primitives (the substrate clojure.string.clj calls) --- -;; clojure.string.clj is pure Clojure over these -;; natives; def-var!'d here so the emitted -;; clojure.string prelude tier's var-derefs resolve: -;; string/ascii-* (ASCII), string/find (index or nil), core-str-* (regex|literal). - -;; (string/split sep s) -> parts, splitting on each non-overlapping sep. -(define (str-literal-split s sep) - (let ((slen (string-length s)) (plen (string-length sep))) - (if (fx=? plen 0) - (map string (string->list s)) - (let loop ((i 0) (start 0) (acc '())) - (cond ((fx>? (fx+ i plen) slen) - (reverse (cons (substring s start slen) acc))) - ((string=? (substring s i (fx+ i plen)) sep) - (loop (fx+ i plen) (fx+ i plen) (cons (substring s start i) acc))) - (else (loop (fx+ i 1) start acc))))))) - -(define (str-upper s) (ascii-string-up s)) -(define (str-lower s) (ascii-string-down s)) -(define (str-reverse-b s) (list->string (reverse (string->list s)))) - -;; (str-find needle haystack) -> exact int index of first occurrence, or nil. -(define (str-find needle s) - (let ((i (str-index-of s needle 0))) - (if (fx stringify each element (Clojure str), join by sep. -;; str-join-strs (defined below) does the join; here we just render each element. -(define (str-join coll . opt) - (let ((sep (if (pair? opt) (jolt-str-render-one (car opt)) ""))) - (str-join-strs (map jolt-str-render-one (seq->list coll)) sep))) - -;; (re-split irx s limit) -> parts, splitting at each match. Keeps interior AND -;; trailing empty strings (the clojure.string wrapper drops trailing for limit 0); -;; a positive limit yields at most `limit` parts (the rest kept unsplit). -;; The clojure.string.clj split wrapper -;; layers the trailing-empty trim on top. -(define (re-split irx s limit) - (let ((len (string-length s))) - (let loop ((start 0) (last 0) (out '())) - (if (and limit (fx>=? (length out) (fx- limit 1))) - (reverse (cons (substring s last len) out)) - (let ((m (and (fx<=? start len) (irregex-search irx s start)))) - (if (not m) - (reverse (cons (substring s last len) out)) - (let ((ms (irregex-match-start-index m 0)) - (me (irregex-match-end-index m 0))) - (if (fx=? me ms) ; zero-width: step past to avoid a stall - (if (fx>=? start len) - (reverse (cons (substring s last len) out)) - (loop (fx+ start 1) last out)) - (loop me me (cons (substring s last ms) out)))))))))) - -;; (str-split pat s [limit]) -> parts. Regex or literal separator; a positive -;; limit caps the part count (the unsplit tail kept), matching core-str-split. -(define (str-split pat s . opt) - (let ((limit (if (and (pair? opt) (not (jolt-nil? (car opt)))) (jolt->idx (car opt)) #f))) - (if (jolt-regex? pat) - (apply jolt-vector (re-split (regex-t-irx pat) s limit)) - (let ((parts (str-literal-split s pat))) - (apply jolt-vector - (if (and limit (fx>? limit 0) (fx>? (length parts) limit)) - (append (list-head parts (fx- limit 1)) - (list (str-join-strs (list-tail parts (fx- limit 1)) pat))) - parts)))))) -(define (str-join-strs strs sep) - (let loop ((xs strs) (first #t) (acc '())) - (cond ((null? xs) (apply string-append (reverse acc))) - (first (loop (cdr xs) #f (cons (car xs) acc))) - (else (loop (cdr xs) #f (cons (car xs) (cons sep acc))))))) - -;; $0/$1... expansion in a string replacement against an irregex match (the -;; JVM/seed replacement syntax). $N -> group N's text (dropped if non-matching). -(define (expand-dollar repl m) - (let ((len (string-length repl))) - (let loop ((i 0) (acc '())) - (if (fx>=? i len) - (apply string-append (reverse acc)) - (let ((c (string-ref repl i))) - (if (and (char=? c #\$) (fxinteger (string-ref repl (fx+ i 1))) 48)) - (g (and (fx<=? n (irregex-match-num-submatches m)) - (irregex-match-substring m n)))) - (loop (fx+ i 2) (if g (cons g acc) acc))) - (loop (fx+ i 1) (cons (string c) acc)))))))) - -;; One match's replacement text. A string gets $N expansion; a fn (jolt closure) -;; is called with the match result (whole string, or [whole g1 ...] when grouped) -;; and its result stringified. -(define (replacement-text replacement m) - (cond - ((string? replacement) (expand-dollar replacement m)) - ((procedure? replacement) (jolt-str-render-one (jolt-invoke replacement (irx-result m)))) - (else (jolt-str-render-one replacement)))) - -;; regex replace, first or all matches. -(define (re-replace irx s replacement all?) - (let ((len (string-length s))) - (let loop ((start 0) (last 0) (acc '())) - (let ((m (and (fx<=? start len) (irregex-search irx s start)))) - (if (not m) - (apply string-append (reverse (cons (substring s last len) acc))) - (let ((ms (irregex-match-start-index m 0)) - (me (irregex-match-end-index m 0))) - (if (fx=? me ms) ; zero-width: step past - (if (fx>=? start len) - (apply string-append (reverse (cons (substring s last len) acc))) - (loop (fx+ start 1) last acc)) - (let ((acc2 (cons (replacement-text replacement m) - (cons (substring s last ms) acc)))) - (if all? - (loop me me acc2) - (apply string-append (reverse (cons (substring s me len) acc2)))))))))))) - -;; (str-replace-all pat repl s) / (str-replace pat repl s) — regex or literal. -(define (str-replace-all pat repl s) - (if (jolt-regex? pat) - (re-replace (regex-t-irx pat) s repl #t) - ;; literal match: a char/number match or replacement (str/replace s \a \b) - ;; coerces to a string, as on the JVM. - (str-replace-literal s (str-needle pat) (str-needle repl)))) -(define (str-replace-literal-first s a b) - (let ((alen (string-length a)) (i (str-index-of s a 0))) - (if (fxlist spec)) - ((or (cseq? spec) (empty-list-t? spec)) (seq->list spec)) - ((symbol-t? spec) (list spec)) - (else '()))) - (target (and (pair? items) (symbol-t? (car items)) (symbol-t-name (car items)))) - (filtered (let scan ((xs (if (pair? items) (cdr items) '()))) - (cond ((null? xs) #f) - ((and (keyword? (car xs)) - (member (keyword-t-name (car xs)) '("only" "refer"))) #t) - (else (scan (cdr xs))))))) - (when (and target (not filtered)) - (chez-register-refer-all! (chez-current-ns) target)))) - specs) - jolt-nil) -(def-var! "clojure.core" "use" chez-runtime-use) -;; import: bring a deftype/defrecord from another ns into the current one. A spec -;; [from-ns Type ...] binds each Type's ctor closure under the current ns, so its -;; (Type. ...) constructor (host-new resolves it as a var) works after :import. -(define (chez-runtime-import . specs) - (for-each - (lambda (spec) - (let ((items (cond ((pvec? spec) (seq->list spec)) - ((or (cseq? spec) (empty-list-t? spec)) (seq->list spec)) - (else '())))) - (when (and (pair? items) (symbol-t? (car items))) - (let ((from (symbol-t-name (car items)))) - (for-each - (lambda (tn) - (when (symbol-t? tn) - (let ((c (var-cell-lookup from (symbol-t-name tn)))) - (when (and c (var-cell-defined? c)) - (def-var! (chez-current-ns) (symbol-t-name tn) (var-cell-root c)))))) - (cdr items)))))) - specs) - jolt-nil) -(def-var! "clojure.core" "import" chez-runtime-import) diff --git a/host/chez/java/records-interop.ss b/host/chez/java/records-interop.ss deleted file mode 100644 index 826db96..0000000 --- a/host/chez/java/records-interop.ss +++ /dev/null @@ -1,163 +0,0 @@ -;; records-interop.ss — JVM-emulation taxonomy split out of records.ss: the -;; ex-info class accessors, the exception supertype hierarchy, and instance-check -;; / case-string (the (instance? Class x) decision table). Loaded right after -;; records.ss; instance-check forward-refs nothing in records.ss at load time. - -;; pmap? guard: ex-info maps are plain hash-maps, never sorted-map htables — and a -;; bare jolt-get on a sorted-map would invoke its comparator on :jolt/type and throw. -(define (ex-info-map? v) - (and (pmap? v) (jolt=2 (jolt-get v jolt-kw-ex-type jolt-nil) jolt-kw-ex-info))) -(define (ex-info-class v) - (let ((c (jolt-get v jolt-kw-class jolt-nil))) - (if (string? c) c "clojure.lang.ExceptionInfo"))) -;; Is `wanted` (simple name) `cls` or a supertype of it? The exception hierarchy -;; lives in the one class graph (class-hierarchy.ss) — resolve the simple name to -;; its graph key and ask jch-isa?, so exceptions and every other class share a -;; single source of truth (ExceptionInfo -> IExceptionInfo is a graph edge). -(define (exception-isa? cls wanted) - (jch-isa? (jch-fqn-of-simple cls) wanted)) - -;; A raw Chez condition (an arity or non-seqable error Chez itself raised, not a -;; jolt ex-info) carries no jolt exception class. Map the ones Clojure raises a -;; specific class for, by message, so (class e) and (instance? C e) match the JVM. -;; Returns a simple class name or #f. -(define (ri-substring? needle hay) - (let ((nl (string-length needle)) (hl (string-length hay))) - (let loop ((i 0)) - (cond ((> (+ i nl) hl) #f) - ((string=? needle (substring hay i (+ i nl))) #t) - (else (loop (+ i 1))))))) -(define (chez-condition-exc-class v) - (and (condition? v) (message-condition? v) - (let ((m (condition-message v))) - (and (string? m) - (cond ((ri-substring? "incorrect number of arguments" m) "ArityException") - ((ri-substring? "not seqable" m) "IllegalArgumentException") - ;; Chez's numeric ops raise "~s is not a real number" on a bad - ;; operand. The JVM throws NullPointerException for a nil operand - ;; (null deref) and ClassCastException for a non-number (can't - ;; cast to Number) — clojure.spec.alpha's conform-explain relies - ;; on the distinction. The offending value rides in the irritants. - ((or (ri-substring? "is not a real number" m) - (ri-substring? "is not a number" m)) - (if (and (irritants-condition? v) - (let loop ((xs (condition-irritants v))) - (and (pair? xs) (or (jolt-nil? (car xs)) (loop (cdr xs)))))) - "NullPointerException" - "ClassCastException")) - (else #f)))))) - -;; instance-check: (type-sym val) — type/protocol membership. Host shims loaded -;; later (io, inst-time, natives-array, natives-queue, host-static-classes) -;; register an arm with register-instance-check-arm! instead of set!-wrapping -;; instance-check; an arm returns #t/#f to decide or 'pass to defer to the next. -;; Newest arm is checked first (matches the old outermost-wins set! order). -;; instance-check-base is the JVM taxonomy fallback when no arm decides. -(define instance-check-registry '()) -(define (register-instance-check-arm! f) ; f: (type-sym val) -> #t | #f | 'pass - (set! instance-check-registry (cons f instance-check-registry))) - -;; (instance? C raw-condition): match when C is the condition's mapped class or a -;; supertype of it (ArityException is also an IllegalArgumentException, etc.). -(register-instance-check-arm! - (lambda (type-sym val) - (let ((k (chez-condition-exc-class val))) - (if k (if (exception-isa? k (last-dot (symbol-t-name type-sym))) #t #f) 'pass)))) - -;; Object / java.lang.Object is the root of the type hierarchy: every non-nil -;; value is an instance of Object; nil is not an instance of anything. -(register-instance-check-arm! - (lambda (type-sym val) - (let ((tn (symbol-t-name type-sym))) - (if (or (string=? tn "Object") (string=? tn "java.lang.Object")) - (not (jolt-nil? val)) - 'pass)))) - -(define (instance-check-base type-sym val) - (let ((tname (symbol-t-name type-sym))) - (cond - ((jrec? val) - (let ((tag (jrec-tag val))) - (or (string=? tag tname) - ;; a simple name matches a qualified tag only at a `.` boundary: - ;; "a.b.IntervalFD" is an IntervalFD, but "a.b.MultiIntervalFD" is NOT - ;; (a raw string-suffix would wrongly match the latter). - (let ((tl (string-length tag)) (nl (string-length tname))) - (and (fx>? tl nl) - (char=? (string-ref tag (fx- (fx- tl nl) 1)) #\.) - (string=? (substring tag (fx- tl nl) tl) tname))) - ;; a protocol/interface the type implements (defprotocol generates an - ;; interface; (instance? SomeProtocol record) is true when the record - ;; implements it — core.match dispatches on instance? IPatternCompile). - (type-satisfies? tag tname) - (type-satisfies? tag (last-dot tname))))) - ((jreify? val) (let ((short (last-dot tname))) - ;; every Clojure reify implements IObj/IMeta (carries metadata). - (or (member short '("IObj" "IMeta")) - (and (memp (lambda (p) (string=? (last-dot p) short)) (jreify-protos val)) #t)))) - ((ex-info-map? val) (exception-isa? (last-dot (ex-info-class val)) (last-dot tname))) - (else (case-string tname val))))) - -(define (instance-check type-sym0 val) - ;; a Class value as the type arg (instance? (class x) y) -> use its name string. - (let* ((type-sym (if (jclass? type-sym0) (jclass-name type-sym0) type-sym0)) - (ts (if (and (string? type-sym) - (or (= 0 (string-length type-sym)) - (not (char=? (string-ref type-sym 0) #\[)))) - (jolt-symbol #f type-sym) - type-sym))) - (let loop ((rs instance-check-registry)) - (if (null? rs) - (instance-check-base ts val) - (let ((r ((car rs) ts val))) - (if (eq? r 'pass) (loop (cdr rs)) r)))))) -(define (case-string tname val) - (cond - ((member tname '("Number" "java.lang.Number")) (number? val)) - ((member tname '("Long" "java.lang.Long" "Integer" "java.lang.Integer")) - (and (number? val) (exact? val) (integer? val))) - ((member tname '("Double" "java.lang.Double" "Float" "java.lang.Float")) (and (number? val) (flonum? val))) - ((member tname '("Ratio" "clojure.lang.Ratio")) (and (number? val) (exact? val) (rational? val) (not (integer? val)))) - ((member tname '("String" "java.lang.String" "CharSequence" "java.lang.CharSequence")) (string? val)) - ((member tname '("Boolean" "java.lang.Boolean")) (boolean? val)) - ((member tname '("Character" "java.lang.Character")) (char? val)) - ((member tname '("Keyword" "clojure.lang.Keyword")) (keyword? val)) - ((member tname '("Symbol" "clojure.lang.Symbol")) (jolt-symbol? val)) - ((member tname '("Atom" "clojure.lang.Atom")) (jolt-atom? val)) - ((member tname '("IFn" "clojure.lang.IFn" "Fn" "clojure.lang.Fn")) (procedure? val)) - ((member tname '("Pattern" "java.util.regex.Pattern")) (regex-t? val)) - ((member tname '("URI" "java.net.URI")) - (and (jhost? val) (string=? (jhost-tag val) "uri"))) - ((member tname '("File" "java.io.File")) (jfile? val)) - ((member tname '("UUID" "java.util.UUID")) (juuid? val)) - (else #f))) - -;; str of a record uses a custom (Object toString) impl if the type defines one -;; (deftype with no default toString relies on this); otherwise the map form -;; without the leading # (Clojure's record .toString). converters.ss loads before -;; records.ss, so this set! sees the registry — forward refs resolve at call time. - -(def-var! "clojure.core" "instance-check" instance-check) - -;; Broad-catch fallback for catch-clause dispatch (analyze-try desugars -;; (catch C e …) to (or (instance? C e) (__catch-broad? "C" e))). A jolt host -;; condition or a raw raised value carries no jolt exception class, so instance? -;; can't place it; a Clojure (catch C e) over such a value matches when C is -;; RuntimeException (or a subclass) / Exception / Throwable — most host runtime -;; errors are RuntimeExceptions. Typed throwables (ex-info, (SomeException. …)) are -;; recognized by instance? as Throwable, so untyped? is false and they dispatch -;; precisely through the instance? arm instead. -(define throwable-type-sym (jolt-symbol #f "Throwable")) -(define (simple-class-name nm) - (let loop ((i (- (string-length nm) 1))) - (cond ((< i 0) nm) - ((char=? (string-ref nm i) #\.) (substring nm (+ i 1) (string-length nm))) - (else (loop (- i 1)))))) -(define (jolt-catch-broad? nm v) - (and (not (instance-check throwable-type-sym v)) - (let ((s (simple-class-name nm))) - (or (exception-isa? s "RuntimeException") - (string=? s "Exception") - (string=? s "Throwable"))))) -(def-var! "clojure.core" "__catch-broad?" - (lambda (nm v) (if (jolt-catch-broad? nm v) #t #f))) diff --git a/host/chez/joltc-selfbuild-smoke.sh b/host/chez/joltc-selfbuild-smoke.sh deleted file mode 100644 index b9f267a..0000000 --- a/host/chez/joltc-selfbuild-smoke.sh +++ /dev/null @@ -1,122 +0,0 @@ -#!/bin/sh -# joltc self-build smoke (jolt-eaj): build joltc as a self-contained binary, then -# use THAT binary to compile a jolt app with Chez and cc removed from the -# environment — the whole point of the feature. The produced app must then run -# and match the same expected output as build-smoke.sh. -root="$(CDPATH= cd -- "$(dirname -- "$0")/../.." && pwd)" -cd "$root" - -# Preflight: building joltc itself needs the Chez kernel dev files (libkernel.a + -# scheme.h) and a C compiler, same as build-smoke.sh. A distro chezscheme package -# ships neither, so skip there (CI included). -csv="$JOLT_CHEZ_CSV" -if [ -z "$csv" ]; then - chez_bin="$(command -v chez || command -v scheme || command -v petite || true)" - if [ -n "$chez_bin" ]; then - base="$(cd "$(dirname "$chez_bin")/.." 2>/dev/null && pwd)" - for d in "$base"/lib/csv*/*/; do - [ -f "${d}libkernel.a" ] && csv="${d%/}" && break - done - fi -fi -if ! command -v cc >/dev/null 2>&1 || [ -z "$csv" ] || [ ! -f "$csv/scheme.h" ] || [ ! -f "$csv/libkernel.a" ]; then - echo "joltc self-build smoke: skipped (Chez kernel dev files or C compiler not available)" - exit 0 -fi -export JOLT_CHEZ_CSV="$csv" - -# 1. Build joltc (debug profile — faster; the self-contained app-build mechanism -# is identical to release, only Chez compile settings differ). -joltc="$root/target/debug/joltc" -echo "joltc self-build smoke: building $joltc" -if ! chez --script host/chez/build-joltc.ss debug "$joltc" >/dev/null 2>&1; then - echo " FAIL: build-joltc.ss exited non-zero" - exit 1 -fi -[ -x "$joltc" ] || { echo " FAIL: no joltc executable produced"; exit 1; } - -# 2. The distributed joltc must run with no Chez install: a basic eval. -got_e="$(env -i HOME="$HOME" "$joltc" -e '(reduce + (range 10))' 2>&1)" -if [ "$got_e" != "45" ]; then - echo " FAIL: joltc -e under empty env gave '$got_e', want 45" - exit 1 -fi - -# 2b. JOLT_TRACE must take effect in the BUILT binary. The env check runs at -# runtime (the launcher), NOT at heap-build where JOLT_TRACE is always unset — so -# an uncaught error shows a tail-frame trace recovering the TCO-elided chain, and -# exactly ONE trace block (the launcher must not double-print it). -got_tr="$(env -i HOME="$HOME" JOLT_TRACE=1 "$joltc" -e '(defn a [x] (+ x 1)) (defn b [x] (a x)) (b :x)' 2>&1)" -if ! printf '%s' "$got_tr" | grep -q ' trace:' || ! printf '%s' "$got_tr" | grep -q 'b'; then - echo " FAIL: JOLT_TRACE=1 in the built joltc produced no tail-frame trace" - echo "--- got ---"; echo "$got_tr"; exit 1 -fi -if [ "$(printf '%s' "$got_tr" | grep -c ' trace:')" != "1" ]; then - echo " FAIL: built joltc double-printed the trace block" - echo "--- got ---"; echo "$got_tr"; exit 1 -fi - -# 3. Build an app through the distributed joltc with an EMPTY environment — no -# PATH at all, so no chez, no cc, no shell tools are reachable. This is the core -# guarantee: joltc compiles apps entirely on its own. -app="$(mktemp -d)/build-app" -cp -r "$root/test/chez/build-app" "$app" -out="$app/app" -echo "joltc self-build smoke: compiling app.core via the binary (no chez/cc on PATH)" -if ! env -i HOME="$HOME" JOLT_PWD="$app" "$joltc" build -m app.core -o "$out" >/dev/null 2>&1; then - echo " FAIL: self-contained jolt build exited non-zero" - rm -rf "$(dirname "$app")" - exit 1 -fi -[ -x "$out" ] || { echo " FAIL: no app executable produced"; rm -rf "$(dirname "$app")"; exit 1; } - -# 4. The produced app runs from a neutral cwd and matches build-smoke's output. -got="$(cd / && "$out" alpha bb ccc 2>&1)" -want='embedded resource ok -HELLO FROM A BUILT BINARY! -HELLO FROM A BUILT BINARY! -args: [alpha bb ccc] -sum: 10 -greet-default: greet:default -greet-loud: greet:loud -greet-soft: greet:soft' -rm -rf "$(dirname "$app")" -if [ "$got" != "$want" ]; then - echo " FAIL: produced app output mismatch" - echo "--- want ---"; echo "$want" - echo "--- got ----"; echo "$got" - exit 1 -fi - -# 5. Static native linking through the distributed joltc: it bundles the Chez -# kernel, so with the system cc (but still no external Chez) it re-links a stub -# that bakes a :jolt/native :static archive into the app. The app then calls the -# C function with the archive removed from disk. Uses the normal PATH so cc — and -# the kernel's link deps (lz4/…) — are found, but Chez stays out of the build. -napp="$(mktemp -d)/native-app" -mkdir -p "$napp/src/app" -printf 'int jolt_static_answer(void){return 42;}\n' > "$napp/greet.c" -cc -c "$napp/greet.c" -o "$napp/greet.o" && ar rcs "$napp/libgreet.a" "$napp/greet.o" -cat > "$napp/src/app/core.clj" <<'EOF' -(ns app.core (:require [jolt.ffi :as ffi])) -(ffi/defcfn answer "jolt_static_answer" [] :int) -(defn -main [& _] (println "answer:" (answer))) -EOF -cat > "$napp/deps.edn" </dev/null 2>&1; then - echo " FAIL: static native build via distributed joltc exited non-zero" - rm -rf "$(dirname "$napp")"; exit 1 -fi -rm -f "$napp/libgreet.a" "$napp/greet.o" # nothing to load at runtime -got_n="$(cd / && "$nout" 2>&1)" -rm -rf "$(dirname "$napp")" -if [ "$got_n" != "answer: 42" ]; then - echo " FAIL: static-linked app (via distributed joltc) output mismatch" - echo "--- got ----"; echo "$got_n"; exit 1 -fi -echo "joltc self-build smoke: passed (joltc runs + builds a working app with no external toolchain, incl. static native linking)" diff --git a/host/chez/lazy-bridge.ss b/host/chez/lazy-bridge.ss deleted file mode 100644 index 76e0043..0000000 --- a/host/chez/lazy-bridge.ss +++ /dev/null @@ -1,95 +0,0 @@ -;; lazy-seq bridge — make-lazy-seq / coll->cells. -;; -;; The `lazy-seq` macro (00-syntax.clj) expands to -;; (make-lazy-seq (fn* [] (coll->cells (do body)))) -;; and `lazy-cat` to (concat (lazy-seq c) ...). These back every overlay fn -;; built on lazy-seq — repeat / iterate / cycle / dedupe / take-nth / keep / -;; interpose / reductions / tree-seq (-> flatten) / lazy-cat. -;; -;; Bridge to the cseq model (seq.ss): a `jolt-lazyseq` is a deferred seq — a 0-arg -;; thunk that, when forced once, yields a seq (cseq | nil). coll->cells coerces the -;; body result to a seq (= jolt-seq), so the thunk already returns a seq; jolt-seq -;; is extended to force a lazyseq. The one trap: (cons x (a-lazy-seq)) must NOT -;; force the tail (else (repeat x) = (lazy-seq (cons x (repeat x))) loops forever), -;; so jolt-cons defers a lazyseq tail into a lazy cseq cell. -;; -;; Loaded LAST (after host-table.ss): %ls-seq then captures the fully-extended -;; jolt-seq (sorted-aware), so a lazy body returning a sorted coll still seqs. - -(define-record-type jolt-lazyseq - (fields (mutable thunk) (mutable val) (mutable realized?)) - (nongenerative jolt-lazyseq-v1)) - -(define (jolt-make-lazy-seq thunk) (make-jolt-lazyseq thunk jolt-nil #f)) - -;; force once and memoize. The thunk is (fn [] (coll->cells body)); coll->cells -;; already coerced the body to a seq (cseq | nil) via the live jolt-seq, so the -;; result needs no further coercion (a nested lazyseq was forced by coll->cells). -(define (force-lazyseq x) - (if (jolt-lazyseq-realized? x) - (jolt-lazyseq-val x) - (let ((r (jolt-invoke (jolt-lazyseq-thunk x)))) - (jolt-lazyseq-val-set! x r) - (jolt-lazyseq-realized?-set! x #t) - (jolt-lazyseq-thunk-set! x #f) - r))) - -;; coll->cells: coerce the body result to the cell representation = a seq | nil. -(define (jolt-coll->cells c) (jolt-seq c)) - -;; extend jolt-seq to force a lazyseq (a lazyseq is seqable -> its realized seq). -(define %ls-seq jolt-seq) -(set! jolt-seq (lambda (x) (if (jolt-lazyseq? x) (force-lazyseq x) (%ls-seq x)))) - -;; (cons x lazyseq): keep the tail lazy — force it only when the cseq cell is -;; walked, so an infinite (repeat/iterate/cycle) stays productive. -(define %ls-cons jolt-cons) -(set! jolt-cons (lambda (x coll) - (if (jolt-lazyseq? coll) - (cseq-lazy x (lambda () (force-lazyseq coll))) - (%ls-cons x coll)))) - -;; (conj lazyseq x): conj onto a seq prepends, like any seq — (conj (rest xs) y). -;; rest returns a lazyseq, so this is a common path; without it conj reports the -;; lazyseq as an "unsupported collection". -(define %ls-conj1 jolt-conj1) -(set! jolt-conj1 (lambda (coll x) - (if (jolt-lazyseq? coll) (jolt-cons x coll) (%ls-conj1 coll x)))) - -;; A lazyseq is a NEW value type, so the dispatchers that DON'T route through -;; jolt-seq must learn it or a raw (unrealized) lazyseq escapes — e.g. the corpus -;; compares (= [1 3 5] (take-nth 2 …)) against the raw lazyseq, and jolt=2 would -;; see an unknown type and return false. Recognizing it as sequential is enough -;; for equality + hash (seq=? / seq-hash coerce via jolt-seq); count / empty? / -;; nth / the printers don't, so coerce those explicitly. -(define %ls-sequential? jolt-sequential?) -(set! jolt-sequential? (lambda (x) (or (jolt-lazyseq? x) (%ls-sequential? x)))) -(define %ls-count jolt-count) -(set! jolt-count (lambda (x) (if (jolt-lazyseq? x) (%ls-count (jolt-seq x)) (%ls-count x)))) -(define %ls-empty? jolt-empty?) -(set! jolt-empty? (lambda (x) (if (jolt-lazyseq? x) (%ls-empty? (jolt-seq x)) (%ls-empty? x)))) -(define %ls-nth jolt-nth) -(set! jolt-nth (case-lambda - ((coll i) (if (jolt-lazyseq? coll) (%ls-nth (jolt-seq coll) i) (%ls-nth coll i))) - ((coll i d) (if (jolt-lazyseq? coll) (%ls-nth (jolt-seq coll) i d) (%ls-nth coll i d))))) -;; a lazy seq prints as its realized seq — force, then re-dispatch through the -;; printer. An empty realized lazy seq is still a sequence, printing "()" (like a -;; JVM LazySeq), not "nil" — so (lazy-seq nil) and (rest '(1)) render "()". -(register-pr-str-arm! jolt-lazyseq? - (lambda (x) (let ((s (jolt-seq x))) (if (jolt-nil? s) "()" (jolt-pr-str s))))) -(register-pr-readable-arm! jolt-lazyseq? - (lambda (x) (let ((s (jolt-seq x))) (if (jolt-nil? s) "()" (jolt-pr-readable s))))) -(register-str-render! jolt-lazyseq? - (lambda (x) (let ((s (jolt-seq x))) (if (jolt-nil? s) "()" (jolt-str-render-one s))))) - -;; seq? — a lazy seq IS a seq (predicates.ss's jolt-seq? predates the lazyseq -;; record). Unlike the native-op dispatchers above (called via a direct top-level -;; reference, so the set! is enough), seq? is reached through var-deref, which -;; reads the var-cell root — so the patched closure must be re-def-var!'d, not just -;; set!. (Exposed once dynamic binding let with-in-str/line-seq reach seq?.) -(define %ls-seq? jolt-seq?) -(set! jolt-seq? (lambda (x) (or (jolt-lazyseq? x) (%ls-seq? x)))) -(def-var! "clojure.core" "seq?" jolt-seq?) - -(def-var! "clojure.core" "make-lazy-seq" jolt-make-lazy-seq) -(def-var! "clojure.core" "coll->cells" jolt-coll->cells) diff --git a/host/chez/loader.ss b/host/chez/loader.ss deleted file mode 100644 index 4ea8bd1..0000000 --- a/host/chez/loader.ss +++ /dev/null @@ -1,397 +0,0 @@ -;; loader.ss — file-based namespace loading + a shell primitive. -;; -;; The corpus/CLI spine compiles one program at a time; namespaces declared in -;; that program see each other because a top-level (do …) unrolls. A real project -;; spans many FILES, so `require` must locate a namespace's source on the search -;; roots and load it — transitively, once each. -;; -;; Loaded by cli.ss AFTER compile-eval.ss (it calls jolt-compile-eval-form). The -;; gates load compile-eval.ss but NOT this file, so the corpus/unit/sci runners -;; keep their alias-only `require` and are unaffected. - -;; --- search roots ----------------------------------------------------------- -;; An ordered list of directory strings. `require` searches them left to right. -;; The CLI seeds this with the project's resolved deps roots (jolt.deps) plus the -;; jolt-core roots so jolt.main/jolt.deps themselves load. -(define source-roots '(".")) -(define (set-source-roots! roots) (set! source-roots roots)) -(define (get-source-roots) source-roots) - -;; --- data readers (#tag literals) ------------------------------------------- -;; A project's data_readers.{clj,cljc} at a source root maps a tag symbol to a -;; qualified reader fn (e.g. {time/date time-literals.data-readers/date}). We -;; merge those into clojure.core/*data-readers* and require each reader's -;; namespace, then while loading source rewrite a registered #tag form into a -;; call (reader-fn 'inner-form) so the value is built at runtime. #inst/#uuid and -;; #"regex" stay built-in (the analyzer lowers them); only tags present in -;; *data-readers* are rewritten. data-readers-active gates the per-form walk so -;; projects without data readers (the common case) pay nothing. -(define data-readers-active #f) -(define (data-readers-table) (var-deref "clojure.core" "*data-readers*")) -;; tag keyword (:#time/date) -> its registered reader symbol, or #f. -(define (data-reader-symbol tag) - (and (keyword? tag) - (let ((nm (keyword-t-name tag))) - (and (> (string-length nm) 0) (char=? (string-ref nm 0) #\#) - (let* ((bare (substring nm 1 (string-length nm))) - (slash (let loop ((i 0)) - (cond ((>= i (string-length bare)) #f) - ((char=? (string-ref bare i) #\/) i) - (else (loop (+ i 1)))))) - (sym (if slash - (jolt-symbol (substring bare 0 slash) (substring bare (+ slash 1) (string-length bare))) - (jolt-symbol #f bare))) - (t (data-readers-table)) - (v (and (pmap? t) (jolt-get t sym)))) - (and v (not (jolt-nil? v)) v)))))) -;; change-tracking walk: rewrite registered #tag forms, keep everything else -;; (and its identity/metadata) intact. Mirrors reader.ss rdr-form->data but keeps -;; set FORMS for the compiler spine instead of building real sets. -(define (ldr-conv-each xs) - (let loop ((xs xs) (acc '()) (changed #f)) - (if (null? xs) (values (reverse acc) changed) - (let ((c (ldr-apply-readers (car xs)))) - (loop (cdr xs) (cons c acc) (or changed (not (eq? c (car xs))))))))) -(define (ldr-apply-readers x) - (cond - ((and (pmap? x) (eq? (jolt-get x rdr-kw-jolt-type) rdr-kw-jolt-tagged)) - (let ((rdr (data-reader-symbol (jolt-get x rdr-kw-tag))) - (inner (ldr-apply-readers (jolt-get x rdr-kw-form)))) - (cond - (rdr - ;; Clojure applies a data reader at read time and substitutes its result - ;; as code. A reader that returns a FORM (a list — e.g. borkdude.html's - ;; #html expands to (->Html (str …))) must be compiled, so splice it in. - ;; A reader that returns a VALUE (time-literals #time/date -> a Date) is - ;; left as a runtime call (reader-fn 'inner): the value rebuilds at - ;; startup, which also keeps a non-serializable constant out of an AOT - ;; build. Apply is guarded — a reader that can't run at load time (its - ;; deps not ready) falls back to the runtime call too. - (let ((result (and (symbol-t? rdr) (not (jolt-nil? (symbol-t-ns rdr))) - (guard (e (#t #f)) - (let ((fn (var-deref (symbol-t-ns rdr) (symbol-t-name rdr)))) - (and (procedure? fn) (jolt-invoke fn inner))))))) - (if (cseq? result) - result - (jolt-list rdr (jolt-list (jolt-symbol #f "quote") inner))))) - ((eq? inner (jolt-get x rdr-kw-form)) x) - (else (rdr-make-tagged (jolt-get x rdr-kw-tag) inner))))) - ((rdr-set-form? x) - (let-values (((items changed) (ldr-conv-each (seq->list (jolt-get x rdr-kw-value))))) - (if changed (rdr-carry-meta x (rdr-make-set items)) x))) - ((pvec? x) - (let-values (((items changed) (ldr-conv-each (vector->list (pvec-v x))))) - (if changed (rdr-carry-meta x (apply jolt-vector items)) x))) - ((pmap? x) - (let ((order (hashtable-ref rdr-map-order x #f))) - (if order - (let-values (((kvs changed) (ldr-conv-each order))) - (if changed (rdr-carry-meta x (rdr-make-map kvs)) x)) - (let-values (((kvs changed) (ldr-conv-each (pmap-fold x (lambda (k v a) (cons k (cons v a))) '())))) - (if changed (rdr-carry-meta x (apply jolt-hash-map kvs)) x))))) - ((cseq? x) - (let-values (((items changed) (ldr-conv-each (seq->list x)))) - (if changed (rdr-carry-meta x (apply jolt-list items)) x))) - (else x))) - -;; read+merge one data_readers file: a literal {tag-sym reader-sym …} map. -(define (merge-data-readers-file path) - (let* ((src (read-file-string path))) - (let-values (((m j) (rdr-read-form src 0 (string-length src)))) - (when (and (not (rdr-eof? m)) (pmap? m)) - (let ((cur (data-readers-table))) - (def-var! "clojure.core" "*data-readers*" - (apply jolt-assoc (if (pmap? cur) cur empty-pmap) - (pmap-fold m (lambda (k v a) (cons k (cons v a))) '())))) - (set! data-readers-active #t) - ;; eagerly load each reader fn's namespace so the rewritten call resolves. - (pmap-fold m (lambda (k v a) - (when (and (symbol-t? v) (symbol-t-ns v) (not (jolt-nil? (symbol-t-ns v)))) - (guard (e (#t #f)) (load-namespace (symbol-t-ns v)))) - a) - #f))))) -(define (load-data-readers!) - (for-each - (lambda (root) - (let ((clj (string-append root "/data_readers.clj")) - (cljc (string-append root "/data_readers.cljc"))) - (cond ((file-exists? clj) (merge-data-readers-file clj)) - ((file-exists? cljc) (merge-data-readers-file cljc))))) - source-roots)) - -;; --- namespace -> file path ------------------------------------------------- -;; "app.commonmark-test" -> "app/commonmark_test": split on '.', munge '-'->'_' -;; per segment, join with '/'. Matches Clojure's ns->file munging. -(define (ns-seg-munge seg) - (list->string (map (lambda (c) (if (char=? c #\-) #\_ c)) (string->list seg)))) -(define (ns-name->rel name) - (let loop ((cs (string->list name)) (seg '()) (segs '())) - (cond - ((null? cs) - (let ((all (reverse (cons (list->string (reverse seg)) segs)))) - (let join ((xs all) (acc "")) - (cond ((null? xs) acc) - ((string=? acc "") (join (cdr xs) (ns-seg-munge (car xs)))) - (else (join (cdr xs) (string-append acc "/" (ns-seg-munge (car xs))))))))) - ((char=? (car cs) #\.) - (loop (cdr cs) '() (cons (list->string (reverse seg)) segs))) - (else (loop (cdr cs) (cons (car cs) seg) segs))))) - -;; First existing /rel.clj or /rel.cljc on the search roots, else #f. -;; A self-contained joltc binary embeds jolt-core + stdlib source keyed by their -;; root-relative path ("clojure/string.clj"); those are checked first, so a -;; `require` resolves with no source on disk. The dev bin/joltc has an empty -;; source store, so the two hashtable probes miss and it falls straight to disk. -(define (resolve-on-roots rel) - (let ((eclj (string-append rel ".clj")) (ecljc (string-append rel ".cljc"))) - (cond - ((string? (hashtable-ref embedded-resources eclj #f)) eclj) - ((string? (hashtable-ref embedded-resources ecljc #f)) ecljc) - (else - (let loop ((roots source-roots)) - (if (null? roots) #f - (let ((clj (string-append (car roots) "/" rel ".clj")) - (cljc (string-append (car roots) "/" rel ".cljc"))) - (cond ((file-exists? clj) clj) - ((file-exists? cljc) cljc) - (else (loop (cdr roots))))))))))) - -;; Read a namespace source. An embedded key (resolve-on-roots above, or the -;; build driver's app-order entries) reads its baked string; everything else is -;; a real path read off disk. Bytevector entries (the bundled boots/stub) are not -;; source, so a string? guard skips them. -(define (ldr-read-source path) - (let ((emb (hashtable-ref embedded-resources path #f))) - (if (string? emb) emb (read-file-string path)))) - -(define (find-ns-file name) (resolve-on-roots (ns-name->rel name))) - -;; --- the loaded set --------------------------------------------------------- -;; Seeded with every namespace that already has vars at load time — the baked -;; prelude/image (clojure.core, clojure.string, jolt.analyzer, …). A `require` of -;; one of those then no-ops instead of hunting for a (nonexistent) source file. -(define loaded-ns (make-hashtable string-hash string=?)) -(vector-for-each (lambda (c) (hashtable-set! loaded-ns (var-cell-ns c) #t)) - (hashtable-values var-table)) - -;; clojure.core.async ships native channel primitives (async.ss) AND a Clojure -;; overlay (stdlib/clojure/core/async.clj) with the higher-level dataflow API -;; (alts!, pipe, mult, mix, pub/sub, map, merge, …). The primitives pre-seed the -;; namespace above, which would make a `require` no-op and skip the overlay. Drop -;; it from the loaded set so a require pulls the overlay from the source roots -;; (like clojure.test); the primitives stay defined either way. -(hashtable-delete! loaded-ns "clojure.core.async") - -;; Does `name` already have vars in the var-table? A namespace baked into the -;; image after the snapshot above — an AOT'd app namespace in a `jolt build` -;; binary — exists in memory with no source file; a later `require` of it must -;; no-op rather than hunt the (absent) source. -(define (ns-has-vars? name) - (let ((found #f)) - (vector-for-each - (lambda (c) (when (and (not found) (string=? (var-cell-ns c) name)) (set! found #t))) - (hashtable-values var-table)) - found)) - -;; Called after a file-backed namespace finishes loading, with (name file). The -;; build driver sets this to record app namespaces in dependency order for AOT -;; emission; a no-op for normal runs. -(define ns-loaded-hook (lambda (name file) #f)) -(define (set-ns-loaded-hook! f) (set! ns-loaded-hook f)) - -;; Read every form from a file and compile+eval it in turn. The first form is -;; normally (ns …), which expands to (in-ns …) and switches the current ns, so -;; later forms compile in that namespace — (chez-current-ns) is re-read each step. -;; -;; Reads by POSITION rather than via __parse-next: a top-level form that reads as -;; nothing — a :cljs-only #? with no matching branch, a #_ discard, a trailing -;; comment — yields rdr-eof but still advances. parse-next collapses that to "no -;; more forms", which would silently drop the entire rest of the file; here we -;; skip the no-op form and continue to true end-of-string. -(define (load-jolt-file path) - (let* ((src (ldr-read-source path)) (end (string-length src))) - ;; parameterize (not a bare set!) so a require nested in this file's ns form - ;; restores path when control returns to the rest of this file. - (parameterize ((rdr-source-file path)) ; list forms read here carry :file = path - (let loop ((i 0)) - (when (< i end) - (let-values (((form j) (rdr-read-form src i end))) - (when (> j i) - (unless (rdr-eof? form) - (when (getenv "JOLT_TRACE_LOAD") - (display " [load-form] " (current-error-port)) - (display (jolt-pr-str form) (current-error-port)) (newline (current-error-port))) - (jolt-compile-eval-form (if data-readers-active (ldr-apply-readers form) form) - (chez-current-ns))) - (loop j)))))))) - -;; load-namespace: load `name`'s source once. Marked loaded BEFORE eval so a -;; dependency cycle terminates (Clojure's behavior). The caller's current ns is -;; restored afterward, since loading the file switched it. -(define (load-namespace name) - (unless (hashtable-ref loaded-ns name #f) - (let ((file (find-ns-file name))) - (cond - (file - (hashtable-set! loaded-ns name #t) ; mark before load so a cycle terminates - (let ((saved (chez-current-ns))) - (load-jolt-file file) - ;; restore the current ns (thread-local); *ns* reads derive from it. - (set-chez-ns! saved)) - (ns-loaded-hook name file)) - ;; No source file but the namespace exists in memory (AOT'd into a built - ;; binary): it's already defined — mark loaded and move on. - ((ns-has-vars? name) - (hashtable-set! loaded-ns name #t)) - (else - (error #f (string-append "Could not locate " (ns-name->rel name) - ".clj (or .cljc) on the source roots") name)))))) - -;; load-file: load an explicit path (a `run FILE`), in the current ns. -(define (jolt-load-file path) - (load-jolt-file path) - jolt-nil) - -;; The target ns name of a require/use spec ([ns …] / (ns …) / bare ns). -(define (spec-target-name spec) - (let ((items (cond ((pvec? spec) (seq->list spec)) - ((or (cseq? spec) (empty-list-t? spec)) (seq->list spec)) - ((symbol-t? spec) (list spec)) - (else '())))) - (and (pair? items) (symbol-t? (car items)) (symbol-t-name (car items))))) - -;; A libspec under a prefix joins onto it: a bare symbol `string` -> `prefix.string`, -;; a vector `[string :as s]` -> `[prefix.string :as s]` (opts preserved). -(define (prefix-join prefix lib) - (cond - ((symbol-t? lib) (jolt-symbol #f (string-append prefix "." (symbol-t-name lib)))) - ((pvec? lib) - (let ((items (seq->list lib))) - (if (and (pair? items) (symbol-t? (car items))) - (apply jolt-vector (jolt-symbol #f (string-append prefix "." (symbol-t-name (car items)))) (cdr items)) - lib))) - (else lib))) - -;; The prefix-list form of a require/use spec: a LIST `(prefix lib …)` expands to -;; one spec per lib (prefix.lib), so (:require (clojure [string :as str])) means -;; clojure.string :as str. A vector / symbol spec is already a single lib. -(define (expand-spec s) - (if (or (cseq? s) (empty-list-t? s)) - (let ((items (seq->list s))) - (if (and (pair? items) (symbol-t? (car items)) (pair? (cdr items))) - (map (lambda (lib) (prefix-join (symbol-t-name (car items)) lib)) (cdr items)) - (list s))) - (list s))) - -;; --- require/use that LOAD --------------------------------------------------- -;; Override the alias-only versions from natives-str.ss. Load each spec's target -;; (no-op if baked/already loaded), THEN register its :as/:refer under the caller -;; ns (chez-register-spec! reads the current ns, restored by load-namespace). -(define (loader-require . specs) - (for-each - (lambda (s0) - (for-each - (lambda (s) - (let ((target (spec-target-name s))) - (when target (load-namespace target))) - (chez-register-spec! (chez-current-ns) s)) - (expand-spec s0))) - specs) - jolt-nil) -(def-var! "clojure.core" "require" loader-require) - -(define (loader-use . specs0) - (for-each - (lambda (spec0) - (for-each - (lambda (spec) - (let ((target (spec-target-name spec))) - (when target (load-namespace target))) - (chez-register-spec! (chez-current-ns) spec) - (let* ((items (cond ((pvec? spec) (seq->list spec)) - ((symbol-t? spec) (list spec)) - (else '()))) - (target (and (pair? items) (symbol-t? (car items)) (symbol-t-name (car items)))) - (filtered (let scan ((xs (if (pair? items) (cdr items) '()))) - (cond ((null? xs) #f) - ((and (keyword? (car xs)) - (member (keyword-t-name (car xs)) '("only" "refer"))) #t) - (else (scan (cdr xs))))))) - (when (and target (not filtered)) - (chez-register-refer-all! (chez-current-ns) target)))) - (expand-spec spec0))) - specs0) - jolt-nil) -(def-var! "clojure.core" "use" loader-use) - -(def-var! "clojure.core" "load-file" jolt-load-file) - -;; The directory of a namespace's resource path: "clojure.tools.reader-test" -> -;; "clojure/tools" (drop the last segment of ns-name->rel). "" for a top-level ns. -(define (ns-rel-dir name) - (let* ((r (ns-name->rel name))) - (let loop ((k (fx- (string-length r) 1))) - (cond ((fx (string-length p) 0) (char=? (string-ref p 0) #\/)) - (substring p 1 (string-length p))) - (else (let ((dir (ns-rel-dir (chez-current-ns)))) - (if (string=? dir "") p (string-append dir "/" p)))))) - (f (resolve-on-roots rel))) - (if f (load-jolt-file f) - (error #f "Could not locate resource on source roots" p)))) - paths) - jolt-nil) -(def-var! "clojure.core" "load" jolt-load) - -;; --- shell primitive (jolt.host/sh, sh-out) --------------------------------- -;; `sh` runs `sh -c CMD`, inheriting stdout/stderr (so git progress shows), and -;; returns the exit code. `sh-out` captures stdout to a string (exit ignored) for -;; commands whose output we parse (git rev-parse). Used by jolt.deps for git. -(define (jolt-sh cmd) (system cmd)) -(def-var! "jolt.host" "sh" jolt-sh) - -(define (jolt-sh-out cmd) - (call-with-values - (lambda () (open-process-ports (string-append "exec sh -c " (sh-quote cmd)) - (buffer-mode block) (native-transcoder))) - (lambda (stdin stdout stderr pid) - (close-port stdin) - (let ((out (get-string-all stdout))) - (close-port stdout) (close-port stderr) - (if (eof-object? out) "" out))))) -(define (sh-quote s) ; single-quote for the outer sh -c - (string-append "'" - (apply string-append - (map (lambda (c) (if (char=? c #\') "'\\''" (string c))) (string->list s))) - "'")) -(def-var! "jolt.host" "sh-out" jolt-sh-out) - -;; Expose source-root control + ns loading to Clojure (jolt.main / jolt.deps). -(def-var! "jolt.host" "set-source-roots!" - (lambda (roots) (set-source-roots! (seq->list roots)) (load-data-readers!) jolt-nil)) -(def-var! "jolt.host" "source-roots" (lambda () (list->cseq source-roots))) -(def-var! "jolt.host" "load-namespace" (lambda (n) (load-namespace n) jolt-nil)) -(def-var! "jolt.host" "file-exists?" (lambda (p) (if (file-exists? p) #t #f))) -(def-var! "jolt.host" "getenv" (lambda (n) (let ((v (getenv n))) (if v v jolt-nil)))) - -;; jolt version string. A self-contained binary build bakes the real tag into the -;; saved heap by emitting (set! jolt-baked-version "…") in flat.ss; a dev run off -;; the seed leaves it #f and falls back to $JOLT_VERSION (bin/joltc sets it from -;; `git describe`), then "dev". -(define jolt-baked-version #f) -(def-var! "jolt.host" "jolt-version" - (lambda () - (or jolt-baked-version - (let ((v (getenv "JOLT_VERSION"))) (and v (> (string-length v) 0) v)) - "dev"))) diff --git a/host/chez/multimethods.ss b/host/chez/multimethods.ss deleted file mode 100644 index 438cd40..0000000 --- a/host/chez/multimethods.ss +++ /dev/null @@ -1,226 +0,0 @@ -;; multimethods — the multimethod dispatch runtime on the Chez host. -;; -;; defmulti/defmethod are macros that expand to ctx-capturing setup CALLS -;; (defmulti-setup / defmethod-setup, + the table ops get-method/methods/ -;; remove-method/prefer-method/prefers), implemented here against -;; the runtime's ns/var machinery. -;; -;; A multimethod VALUE is a jolt-multifn record carrying its dispatch fn and a -;; mutable method table (dispatch-val -> method fn, keyed with jolt= so keyword/ -;; vector/number dispatch values match by value). jolt-invoke dispatches it: -;; an exact method, else an isa?/hierarchy match (resolved through prefer-method -;; and the overlay's isa?/derive/hierarchy), else the :default method. -;; -;; NS resolution: defmulti expands to (defmulti-setup (quote name) ...) with a -;; BARE symbol — the Chez RT has no compile-time current ns at the call site, so a -;; runtime `chez-current-ns` box names where to def-var! the multifn. It defaults -;; to "user" (matching the analyzer's ns for -e user code); the assembled prelude -;; sets it to "clojure.core" around its own load (program-with-prelude), so the -;; print-method/print-dup defmultis land in clojure.core. defmethod-setup and the -;; symbol-taking table ops resolve the multifn via (var-deref (chez-current-ns) …), -;; so they agree with defmulti. Loaded from rt.ss after seq.ss (jolt-invoke), -;; collections.ss (jolt=/key-hash/jolt-hash-map) and the var-cell machinery. - -;; THREAD-LOCAL: a Chez thread-parameter, so each OS thread (an nREPL -;; session worker / future) has its own current ns — vars stay global, only the -;; "current ns" pointer is per-thread, matching Clojure's thread-local *ns*. A new -;; thread inherits the forking thread's value. `star-ns-cell` (the *ns* var cell, -;; captured by dyn-binding.ss once *ns* exists) lets chez-current-ns DERIVE from a -;; thread-local (binding [*ns* ..]) so a bound *ns* drives load-string/analyzer -;; resolution; bootstrap-safe (it's #f until then, so we just read the parameter). -(define chez-current-ns-param (make-thread-parameter "user")) -(define star-ns-cell #f) -(define (chez-current-ns) - (if star-ns-cell - (let ((bv (dyn-binding-value star-ns-cell))) - (if (and (not (eq? bv dyn-no-binding)) (jns? bv)) - (jns-name bv) - (chez-current-ns-param))) - (chez-current-ns-param))) -(define (set-chez-ns! ns) (chez-current-ns-param ns)) - -(define-record-type jolt-multifn - (fields name dispatch-fn methods default hierarchy prefers) - (nongenerative jolt-multifn-v1)) - -(define kw-default (keyword #f "default")) -(define (new-mm-table) (make-hashtable key-hash jolt=)) - -;; (defmulti-setup 'name dispatch & opts) — opts is a flat :default/:hierarchy plist. -(define (parse-mm-opts opts) - (let loop ((o opts) (dk kw-default) (h #f)) - (if (or (null? o) (null? (cdr o))) - (values dk h) - (let ((k (car o)) (v (cadr o))) - (cond - ((and (keyword? k) (not (keyword-t-ns k)) (string=? (keyword-t-name k) "default")) - (loop (cddr o) v h)) - ((and (keyword? k) (not (keyword-t-ns k)) (string=? (keyword-t-name k) "hierarchy")) - (loop (cddr o) dk v)) - (else (loop (cddr o) dk h))))))) - -(define (jolt-defmulti-setup name-sym dispatch . opts) - (let-values (((dk h) (parse-mm-opts opts))) - (let* ((sns (symbol-t-ns name-sym)) - ;; the macro qualifies the name with its EXPANSION ns, so a defmulti - ;; deferred inside a fn (a deftest body) still defines in the ns it - ;; was written in, not whatever ns is current when it finally runs. - (ns (if (string? sns) sns (chez-current-ns))) - (mf (make-jolt-multifn (symbol-t-name name-sym) dispatch - (new-mm-table) dk h (new-mm-table)))) - (def-var! ns (symbol-t-name name-sym) mf) - mf))) - -;; (defmethod-setup 'mm dispatch-val impl) — add a method. Auto-creates the multifn -;; if absent (defmethod before defmulti — rare; identity dispatch as a fallback). -(define (jolt-defmethod-setup mm-sym dval impl . rest) - (let* ((nm (symbol-t-name mm-sym)) - (sns (symbol-t-ns mm-sym)) - (qns (and sns (not (jolt-nil? sns)) (not (null? sns)) sns)) - ;; the macro passes its EXPANSION ns so a defmethod deferred inside a - ;; fn resolves like the JVM (against the ns it was written in, not the - ;; ns current when it runs); absent (old emitted code) fall back to the - ;; runtime ns. - (here (if (and (pair? rest) (string? (car rest))) (car rest) (chez-current-ns))) - ;; qualified (cf.mm/ext) resolves in its own ns (cross-ns defmethod); - ;; unqualified resolves in the writing ns, else a :refer's home ns (so a - ;; defmethod on a referred multifn lands on the real one), else stays in - ;; the writing ns (a shadow, as before). - (mns (cond - (qns (or (chez-resolve-alias here qns) qns)) - ((var-cell-lookup here nm) here) - ((chez-resolve-refer here nm) => values) - (else here))) - (cur (var-deref mns nm)) - (mf (if (jolt-multifn? cur) cur - ;; auto-create: copy the dispatch fn + default from a same-named - ;; clojure.core multifn (e.g. print-method's 2-arg dispatch) so a - ;; (defmethod print-method ...) before naming clojure.core's still - ;; dispatches right — the old 1-arg identity fallback crashed. - (let* ((core (var-deref "clojure.core" nm)) - (disp (if (jolt-multifn? core) - (jolt-multifn-dispatch-fn core) - (var-deref "clojure.core" "identity"))) - (deft (if (jolt-multifn? core) (jolt-multifn-default core) kw-default)) - (m (make-jolt-multifn nm disp (new-mm-table) deft #f (new-mm-table)))) - (def-var! mns nm m) m)))) - (hashtable-set! (jolt-multifn-methods mf) dval impl) - mf)) - -;; --- dispatch ---------------------------------------------------------------- -(define (mm-isa? mf) - ;; the overlay's isa? (the hierarchy system is pure Clojure); a per-mm :hierarchy - ;; is an atom (deref each dispatch, like a Clojure var) or a plain map. - (let* ((isa (var-deref "clojure.core" "isa?")) - (h (jolt-multifn-hierarchy mf)) - (hval (and h (if (jolt-atom? h) (jolt-atom-val h) h)))) - (lambda (x y) (jolt-truthy? (if hval (jolt-invoke isa hval x y) (jolt-invoke isa x y)))))) - -(define (mm-find-isa mf dv) - (let* ((methods (jolt-multifn-methods mf)) - (isa? (mm-isa? mf)) - (default (jolt-multifn-default mf)) - (keys (filter (lambda (k) (not (jolt= k default))) - (vector->list (hashtable-keys methods)))) - (matches (filter (lambda (k) (isa? dv k)) keys))) - (cond - ((null? matches) #f) - ((null? (cdr matches)) (hashtable-ref methods (car matches) #f)) - (else - ;; >1 isa-match: pick the dominant key (x dominates y when x is - ;; prefer-method'd over y, or (isa? x y)); ambiguity with no dominant is an - ;; error, as in Clojure. - (let* ((prefers (jolt-multifn-prefers mf)) - (pref? (lambda (x y) - (let ((px (hashtable-ref prefers x #f))) - (and px (hashtable-ref px y #f) #t)))) - (dom? (lambda (x y) (or (pref? x y) (isa? x y)))) - (best (fold-left (lambda (b k) (if (dom? k b) k b)) (car matches) (cdr matches)))) - (for-each - (lambda (k) - (when (and (not (jolt= k best)) (not (dom? best k))) - (error #f (string-append "Multiple methods in multimethod '" (jolt-multifn-name mf) - "' match dispatch value - and neither is preferred")))) - matches) - (hashtable-ref methods best #f)))))) - -(define (multifn-dispatch mf . args) - (let* ((dv (apply jolt-invoke (jolt-multifn-dispatch-fn mf) args)) - (methods (jolt-multifn-methods mf)) - (direct (hashtable-ref methods dv #f))) - (cond - (direct (apply jolt-invoke direct args)) - ((mm-find-isa mf dv) => (lambda (m) (apply jolt-invoke m args))) - ((hashtable-ref methods (jolt-multifn-default mf) #f) - => (lambda (m) (apply jolt-invoke m args))) - (else (error #f (string-append "No method in multimethod '" (jolt-multifn-name mf) - "' for dispatch value: " (jolt-pr-str dv))))))) - -;; jolt-invoke dispatches a multifn (otherwise falls through to the prior logic). -(define %prev-jolt-invoke jolt-invoke) -(set! jolt-invoke - (lambda (f . args) - (if (jolt-multifn? f) - (apply multifn-dispatch f args) - (apply %prev-jolt-invoke f args)))) - -;; --- table ops --------------------------------------------------------------- -;; prefer-method/remove-method/remove-all-methods/prefers take the name QUOTED; -;; get-method/methods take the multifn VALUE (Clojure semantics). -(define (mm-of-sym sym) (let ((v (var-deref (chez-current-ns) (symbol-t-name sym)))) - (and (jolt-multifn? v) v))) - -(define (jolt-prefer-method-setup mm-sym dval-a dval-b) - (let ((mf (mm-of-sym mm-sym))) - (when mf - (let ((sub (or (hashtable-ref (jolt-multifn-prefers mf) dval-a #f) - (let ((h (new-mm-table))) - (hashtable-set! (jolt-multifn-prefers mf) dval-a h) h)))) - (hashtable-set! sub dval-b #t))) - mf)) - -(define (jolt-remove-method-setup mm-sym dval) - (let ((mf (mm-of-sym mm-sym))) - (when mf (hashtable-delete! (jolt-multifn-methods mf) dval)) - mf)) - -(define (jolt-remove-all-methods-setup mm-sym) - (let ((mf (mm-of-sym mm-sym))) - (when mf (hashtable-clear! (jolt-multifn-methods mf))) - mf)) - -(define (jolt-get-method-setup mf dval) - (if (jolt-multifn? mf) - (or (hashtable-ref (jolt-multifn-methods mf) dval #f) - (hashtable-ref (jolt-multifn-methods mf) (jolt-multifn-default mf) #f) - jolt-nil) - jolt-nil)) - -(define (jolt-methods-setup mf) - (if (jolt-multifn? mf) - (let-values (((ks vs) (hashtable-entries (jolt-multifn-methods mf)))) - (let loop ((i 0) (m (jolt-hash-map))) - (if (fx>=? i (vector-length ks)) m - (loop (fx+ i 1) (jolt-assoc m (vector-ref ks i) (vector-ref vs i)))))) - jolt-nil)) - -(define (jolt-prefers-setup mm-sym) - (let ((mf (mm-of-sym mm-sym))) - (if (not mf) (jolt-hash-map) - (let-values (((ks vs) (hashtable-entries (jolt-multifn-prefers mf)))) - (let loop ((i 0) (m (jolt-hash-map))) - (if (fx>=? i (vector-length ks)) m - ;; each value is an inner set of preferred-over keys -> a jolt set - (loop (fx+ i 1) - (jolt-assoc m (vector-ref ks i) - (apply jolt-hash-set - (vector->list (hashtable-keys (vector-ref vs i)))))))))))) - -(def-var! "clojure.core" "defmulti-setup" jolt-defmulti-setup) -(def-var! "clojure.core" "defmethod-setup" jolt-defmethod-setup) -(def-var! "clojure.core" "prefer-method-setup" jolt-prefer-method-setup) -(def-var! "clojure.core" "remove-method-setup" jolt-remove-method-setup) -(def-var! "clojure.core" "remove-all-methods-setup" jolt-remove-all-methods-setup) -(def-var! "clojure.core" "get-method-setup" jolt-get-method-setup) -(def-var! "clojure.core" "methods-setup" jolt-methods-setup) -(def-var! "clojure.core" "prefers-setup" jolt-prefers-setup) diff --git a/host/chez/natives-coll.ss b/host/chez/natives-coll.ss deleted file mode 100644 index 1dac844..0000000 --- a/host/chez/natives-coll.ss +++ /dev/null @@ -1,28 +0,0 @@ -;; Collection constructors + rand — host-coupled natives the overlay assumes as -;; bare clojure.core vars. The persistent-collection constructors already exist -;; in collections.ss (jolt-hash-map / jolt-hash-set / jolt-vector); this just -;; binds the public clojure.core names to them. Loaded after def-var! (rt.ss) + -;; the collections + seq tiers. hash-map/array-map/hash-set/set/rand semantics. - -;; array-map: insertion-ordered, any size (Clojure's PersistentArrayMap, via -;; createAsIfByAssoc). hash-map: hash order (PersistentHashMap). The map LITERAL -;; ctor (jolt-hash-map, emitted for {...}) is array-ordered up to 8 entries and -;; hash beyond, matching RT.map. -(define (jolt-array-map . kvs) (jolt-array-map-build kvs)) -(define (jolt-hash-map-fn . kvs) (jolt-hash-map-build kvs)) - -;; set lives in the kernel overlay tier (clojure/core/00-kernel.clj): it's a pure -;; composition (apply hash-set (seq coll)) the compiler uses only off the emit path, -;; so the Clojure version lowers to the same code without a bootstrap cycle. - -;; rand: a flonum in [0, n) (n defaults to 1.0) — jolt is all-flonum, so the -;; result is a double like every other number. -(define (jolt-rand . n) - (let ((r (random 1.0))) - (if (null? n) r (* r (exact->inexact (car n)))))) - -(def-var! "clojure.core" "hash-map" jolt-hash-map-fn) -(def-var! "clojure.core" "hash-set" jolt-hash-set) -(def-var! "clojure.core" "array-map" jolt-array-map) -(def-var! "clojure.core" "rand" jolt-rand) -(def-var! "clojure.core" "map-entry?" jolt-map-entry?) diff --git a/host/chez/natives-format.ss b/host/chez/natives-format.ss deleted file mode 100644 index ab33010..0000000 --- a/host/chez/natives-format.ss +++ /dev/null @@ -1,62 +0,0 @@ -;; natives-format.ss — a small %-format engine for clojure.core `format` over the -;; all-flonum number model: %d (integer), %s (str), %f / %.Nf (fixed-point), %x/%X -;; (hex int), %o (octal), %c (char int), %b (boolean), %% (literal). Enough for the -;; corpus, not the full Java Formatter spec. Loaded after natives-misc.ss (uses -;; jolt-str-render-one via converters + jolt-truthy?). - -(define (->long x) (exact (truncate x))) -(define (pad-left s n c) (if (fx>=? (string-length s) n) s (string-append (make-string (fx- n (string-length s)) c) s))) -(define (fmt-float x prec) - (let* ((neg (< x 0)) (ax (abs x)) - (scale (expt 10 prec)) - (scaled (round (* (inexact ax) scale))) - (i (exact (truncate (/ scaled scale)))) - (frac (exact (truncate (- scaled (* i scale)))))) - (string-append (if neg "-" "") - (number->string i) - (if (fx>? prec 0) (string-append "." (pad-left (number->string frac) prec #\0)) "")))) -(define (jolt-format fmt . args) - (let ((out (open-output-string))) - (let loop ((i 0) (as args)) - (if (fx>=? i (string-length fmt)) - (get-output-string out) - (let ((c (string-ref fmt i))) - (if (char=? c #\%) - ;; parse a directive: %[-][0][width][.prec]conv - (let scan ((j (fx+ i 1)) (left #f) (zero #f) (width #f) (prec #f) (seen-dot #f)) - (let ((d (string-ref fmt j))) - (cond - ((char=? d #\%) (write-char #\% out) (loop (fx+ j 1) as)) - ((and (not seen-dot) (not width) (char=? d #\-)) - (scan (fx+ j 1) #t zero width prec seen-dot)) - ((and (not seen-dot) (not width) (char=? d #\0)) - (scan (fx+ j 1) left #t width prec seen-dot)) - ((char=? d #\.) (scan (fx+ j 1) left zero width 0 #t)) - ((and (char>=? d #\0) (char<=? d #\9)) - (if seen-dot - (scan (fx+ j 1) left zero width (fx+ (fx* (or prec 0) 10) (fx- (char->integer d) 48)) seen-dot) - (scan (fx+ j 1) left zero (fx+ (fx* (or width 0) 10) (fx- (char->integer d) 48)) prec seen-dot))) - (else - (let* ((a (if (null? as) jolt-nil (car as))) - (rest (if (null? as) '() (cdr as))) - (s (case d - ((#\d) (number->string (->long a))) - ((#\s) (jolt-str-render-one a)) - ((#\f) (fmt-float a (or prec 6))) - ((#\x) (string-downcase (number->string (->long a) 16))) - ((#\X) (string-upcase (number->string (->long a) 16))) - ((#\o) (number->string (->long a) 8)) - ((#\b) (if (jolt-truthy? a) "true" "false")) - ((#\c) (string (integer->char (->long a)))) - (else (string #\% d)))) - ;; pad to width: left-justify with spaces, else right-justify - ;; (zero-pad only a right-justified number). - (s (if (and width (fx (lambda (m) (jolt-invoke m x))) - ;; everything else (collections, fns, reify, atoms/agents and any reference - ;; type) reads the identity side-table; a value with no entry is nil meta. - (else (hashtable-ref meta-table x jolt-nil)))) - -;; fresh-identity copy of a metadatable value (so attaching meta doesn't mutate -;; the original). cseq/procedure can't be copied meaningfully — keyed in place. -(define (meta-copy x) - (cond - ((pvec? x) (make-pvec (pvec-v x) (pvec-ent x))) - ((pmap? x) (make-pmap (pmap-root x) (pmap-cnt x) (pmap-order x))) - ((pset? x) (make-pset (pset-m x))) - ((jrec? x) (make-jrec (jrec-desc x) (jrec-vec-copy (jrec-vals x)) (jrec-ext x))) - ;; a reify shares its (read-only) method table + protos but gets a fresh - ;; identity, so attaching meta leaves the original's meta untouched. Every - ;; Clojure reify implements IObj. - ((jreify? x) (make-jreify (jreify-methods x) (jreify-protos x))) - ;; () is a shared singleton — a fresh instance keeps meta off every other (). - ((empty-list-t? x) (fresh-empty-list)) - ;; a list/seq node gets a fresh identity too (Clojure's PersistentList is - ;; immutable — (with-meta a-list m) returns a NEW list). Keying meta on the - ;; original mutated it, so (with-meta xs {:k xs}) built a self-referential - ;; cycle that loops *print-meta* printing. - ((cseq? x) (make-cseq (cseq-head x) (cseq-tail x) (cseq-forced? x) - (cseq-list? x) (cseq-cvec x) (cseq-ci x) (cseq-crest x))) - ((jolt-lazyseq? x) (make-jolt-lazyseq (jolt-lazyseq-thunk x) (jolt-lazyseq-val x) - (jolt-lazyseq-realized? x))) - (else x))) ; procedure - -(define (jolt-with-meta x m) - (cond - ((symbol-t? x) (make-symbol-t (symbol-t-ns x) (symbol-t-name x) m)) - ;; a deftype with an explicit clojure.lang.IObj withMeta carries meta in a - ;; field; dispatch to it (see jolt-meta) so the meta survives reconstruction. - ((and (jrec? x) (jrec-cl x "withMeta")) => (lambda (meth) (jolt-invoke meth x m))) - ((or (pvec? x) (pmap? x) (pset? x) (cseq? x) (empty-list-t? x) (jolt-lazyseq? x) (jrec? x) (jreify? x) (procedure? x)) - (let ((c (meta-copy x))) - (if (jolt-nil? m) (hashtable-delete! meta-table c) (hashtable-set! meta-table c m)) - c)) - (else (error #f "with-meta: value does not support metadata" x)))) - -(def-var! "clojure.core" "meta" jolt-meta) -(def-var! "clojure.core" "with-meta" jolt-with-meta) - -;; Carry SRC's collection metadata onto DST (a freshly-built collection of the -;; same kind), as Clojure's ops do — each new collection threads its receiver's -;; meta() forward. Returns DST. The size check is the fast path: programs that -;; never attach collection metadata pay one O(1) check per op, no lookup. -(define (meta-carry src dst) - (if (fx=? 0 (hashtable-size meta-table)) - dst - (let ((m (hashtable-ref meta-table src #f))) - (if m - ;; never attach to the shared () singleton — use a fresh instance - (let ((d (if (empty-list-t? dst) (fresh-empty-list) dst))) - (hashtable-set! meta-table d m) d) - dst)))) - -;; (type x) — Clojure's (or (:type (meta x)) (class x)). With no JVM classes the -;; "class" is a host taxonomy: a record yields its ns-qualified class-name SYMBOL -;; (user.TyR), everything else a keyword (:number/:vector/:seq/…). -;; MUST be total — a non-record value -;; falling through to a crash would read as a divergence, not the right keyword. -;; Forward refs (jolt-lazyseq?, the sorted-htable / wrapper predicates) all bind by -;; call time (every host .ss loads before any user expr runs). -(define ty-kw-type (keyword #f "type")) ; the :type meta key -(define ty-kw-jtype (keyword "jolt" "type")) ; tagged-map discriminator (ex-info) -(define ty-number (keyword #f "number")) -(define ty-string (keyword #f "string")) -(define ty-keyword (keyword #f "keyword")) -(define ty-symbol (keyword #f "symbol")) -(define ty-boolean (keyword #f "boolean")) -(define ty-char (keyword #f "char")) -(define ty-vector (keyword #f "vector")) -(define ty-map (keyword #f "map")) -(define ty-set (keyword #f "set")) -(define ty-seq (keyword #f "seq")) -(define ty-fn (keyword #f "fn")) -(define ty-atom (keyword "jolt" "atom")) -(define ty-volatile (keyword "jolt" "volatile")) -(define ty-regex (keyword "jolt" "regex")) -(define ty-var (keyword "jolt" "var")) -(define ty-transient (keyword "jolt" "transient")) -(define ty-uuid (keyword "jolt" "uuid")) -(define ty-sorted-set (keyword "jolt" "sorted-set")) -(define ty-object (keyword #f "object")) - -(define (jolt-type x) - (let* ((m (jolt-meta x)) - (override (if (jolt-nil? m) jolt-nil (jolt-get m ty-kw-type jolt-nil)))) - (cond - ((not (jolt-nil? override)) override) ; :type meta wins - ;; record -> its ns-qualified class-name STRING (= (class x)). jolt models - ;; classes as strings, so (symbol (str (type r))) is NOT (type r) — as on the - ;; JVM where type is a Class, not a Symbol. - ((jrec? x) (jrec-tag x)) - ((jolt-nil? x) jolt-nil) - ((boolean? x) ty-boolean) - ((number? x) ty-number) - ((string? x) ty-string) - ((keyword? x) ty-keyword) - ((symbol-t? x) ty-symbol) - ((char? x) ty-char) - ;; host wrappers — keyed by their :jolt/* tags (checked before the - ;; collection arms; none of these are pvec/pmap/pset). - ((jolt-atom? x) ty-atom) - ((jvol? x) ty-volatile) - ((jolt-regex? x) ty-regex) - ((var-cell? x) ty-var) - ((jolt-transient? x) ty-transient) - ((juuid? x) ty-uuid) - ((htable-sorted-set? x) ty-sorted-set) - ((htable-sorted-map? x) ty-map) - ;; collections — pvec INCLUDES map entries (:vector). - ((pvec? x) ty-vector) - ((pmap? x) ; a :jolt/type-tagged map (ex-info) -> its tag - (let ((t (jolt-get x ty-kw-jtype jolt-nil))) (if (jolt-nil? t) ty-map t))) - ((pset? x) ty-set) - ((or (cseq? x) (empty-list-t? x) (jolt-lazyseq? x)) ty-seq) - ((procedure? x) ty-fn) - (else ty-object)))) - -;; jolt-type is the keyword TAXONOMY (:string/:set/:jolt/inst/…) — jolt's native -;; value model, with no JVM in it. print-method/print-dup dispatch on it (via -;; __type-tag). The PUBLIC clojure.core/type is Clojure's (or (:type meta) (class -;; x)) — a JVM class — but that mapping belongs to the java host layer (host-class.ss -;; rebinds `type` next to `class`), so this core layer stays JVM-free. -(def-var! "clojure.core" "__type-tag" jolt-type) -(def-var! "clojure.core" "type" jolt-type) diff --git a/host/chez/natives-misc.ss b/host/chez/natives-misc.ss deleted file mode 100644 index ff66458..0000000 --- a/host/chez/natives-misc.ss +++ /dev/null @@ -1,111 +0,0 @@ -;; misc scalar natives — UUID, tagged-literal, bigint, and the hash API. (format / -;; printf moved to natives-format.ss.) -;; -;; Loaded after the printers (pr-str of a uuid is #uuid "…") and converters -;; (jolt-str-render-one for %s / str of a uuid). - -;; --- UUID -------------------------------------------------------------------- -;; A uuid is a record wrapping its canonical 36-char lowercase string. str -> the -;; bare string; pr-str -> #uuid "…"; not map?/coll?. -(define-record-type juuid (fields s) (nongenerative chez-juuid-v1)) -(define (jolt-uuid-pred? x) (juuid? x)) - -(define hexd "0123456789abcdef") -(define (rand-hex) (string-ref hexd (random 16))) -;; v4: 8-4-4-4-12, version nibble (index 14) = 4, variant nibble (index 19) in 8-b. -(define (random-uuid-str) - (let ((cs (make-string 36))) - (let loop ((i 0)) - (if (fx=? i 36) cs - (begin - (string-set! cs i - (cond ((or (fx=? i 8) (fx=? i 13) (fx=? i 18) (fx=? i 23)) #\-) - ((fx=? i 14) #\4) - ((fx=? i 19) (string-ref "89ab" (random 4))) - (else (rand-hex)))) - (loop (fx+ i 1))))))) -(define (jolt-random-uuid) (make-juuid (random-uuid-str))) - -;; #uuid literal -> a uuid value (the emitter lowers the :uuid node to this). The -;; reader already validated the shape; lowercase for value equality. -(define (jolt-uuid-from-string s) (make-juuid (string-downcase s))) - -;; parse-uuid: validate the canonical shape (8-4-4-4-12 hex), lowercase, -> uuid; -;; nil if the string doesn't conform (Clojure parse-uuid), error on a non-string. -(define (hex-char? c) (or (and (char>=? c #\0) (char<=? c #\9)) - (and (char>=? c #\a) (char<=? c #\f)) - (and (char>=? c #\A) (char<=? c #\F)))) -(define (uuid-shape? s) - (and (string? s) (fx=? (string-length s) 36) - (let loop ((i 0)) - (if (fx=? i 36) #t - (let ((c (string-ref s i))) - (cond ((or (fx=? i 8) (fx=? i 13) (fx=? i 18) (fx=? i 23)) (and (char=? c #\-) (loop (fx+ i 1)))) - ((hex-char? c) (loop (fx+ i 1))) - (else #f))))))) -(define (jolt-parse-uuid s) - (cond ((not (string? s)) (error #f "parse-uuid: not a string" s)) - ((uuid-shape? s) (make-juuid (string-downcase s))) - (else jolt-nil))) - -;; uuid? / random-uuid / parse-uuid are OVERLAY fns (they read :jolt/type), so -;; the prelude would clobber a def-var! here — they're asserted in post-prelude.ss. - -;; str of a uuid -> the bare 36-char string; pr-str -> #uuid "…". -(register-str-render! juuid? juuid-s) -(define (juuid-pr u) (string-append "#uuid \"" (juuid-s u) "\"")) -(register-pr-arm! juuid? juuid-pr) -;; two uuids are = iff same string. -(register-eq-arm! (lambda (a b) (or (juuid? a) (juuid? b))) - (lambda (a b) (and (juuid? a) (juuid? b) (string=? (juuid-s a) (juuid-s b))))) - -;; --- bigint / biginteger ----------------------------------------------------- -;; jolt models every number as a double; an integer-valued double prints without -;; a ".0" (jolt-num->string), so bigint is just the number for the corpus range. -;; (Arbitrary-precision beyond 2^53 is a separate concern.) -(define (jolt-bigint x) x) -(def-var! "clojure.core" "bigint" jolt-bigint) -(def-var! "clojure.core" "biginteger" jolt-bigint) - -;; --- tagged-literal ---------------------------------------------------------- -;; (tagged-literal tag form): a tagged value with :tag / :form. tagged-literal? is -;; overlay (reads :jolt/type) so it's overridden in post-prelude.ss. -(define-record-type jtagged (fields tag form) (nongenerative chez-jtagged-v1)) -(define (jolt-tagged-literal tag form) (make-jtagged tag form)) -(define (jolt-tagged-literal-pred? x) (jtagged? x)) -(define kw-tl-tag (keyword #f "tag")) -(define kw-tl-form (keyword #f "form")) -(register-get-arm! jtagged? - (lambda (coll k d) - (cond ((jolt=2 k kw-tl-tag) (jtagged-tag coll)) - ((jolt=2 k kw-tl-form) (jtagged-form coll)) - (else d)))) -(define (jtagged-pr t) (string-append "#" (jolt-pr-str (jtagged-tag t)) " " (jolt-pr-readable (jtagged-form t)))) -(register-pr-arm! jtagged? jtagged-pr) -;; two tagged literals are = iff same tag and (recursively) = form, like the JVM's -;; TaggedLiteral — so they work as map keys / set members. (jolt-hash already -;; hashes the fields structurally, so eq/hash stay consistent.) -(register-eq-arm! (lambda (a b) (or (jtagged? a) (jtagged? b))) - (lambda (a b) (and (jtagged? a) (jtagged? b) - (jolt=2 (jtagged-tag a) (jtagged-tag b)) - (jolt=2 (jtagged-form a) (jtagged-form b))))) -(def-var! "clojure.core" "tagged-literal" jolt-tagged-literal) -;; tagged-literal? is OVERLAY (reads :jolt/type) — asserted in post-prelude.ss. - -;; --- hash family (24-bit masked so int? holds) ------------------------------- -;; The public hash API over jolt-hash (values.ss). hash-ordered/-unordered-coll -;; fold the element hashes the way Clojure's IHash mixers do. -(define (nm-h24 x) (bitwise-and (jolt-hash x) #xffffff)) -(define (nm-hash x) (nm-h24 x)) -(define (nm-hash-combine a b) - (bitwise-and (bitwise-xor (nm-h24 a) (+ (nm-h24 b) #x9e3779)) #xffffff)) -(define (nm-hash-ordered-coll coll) - (let loop ((xs (seq->list (jolt-seq coll))) (h 1)) - (if (null? xs) h (loop (cdr xs) (bitwise-and (+ (* 31 h) (nm-h24 (car xs))) #xffffff))))) -(define (nm-hash-unordered-coll coll) - (let loop ((xs (seq->list (jolt-seq coll))) (h 0)) - (if (null? xs) h (loop (cdr xs) (bitwise-and (+ h (nm-h24 (car xs))) #xffffff))))) -(def-var! "clojure.core" "hash" nm-hash) -(def-var! "clojure.core" "hash-combine" nm-hash-combine) -(def-var! "clojure.core" "hash-ordered-coll" nm-hash-ordered-coll) -(def-var! "clojure.core" "hash-unordered-coll" nm-hash-unordered-coll) diff --git a/host/chez/natives-num.ss b/host/chez/natives-num.ss deleted file mode 100644 index 0944dbe..0000000 --- a/host/chez/natives-num.ss +++ /dev/null @@ -1,88 +0,0 @@ -;; bit ops + string->number parsers — host-coupled natives (bit family, -;; parse-long/double). jolt models every number as a double, so bit ops coerce -;; to an exact integer, operate, and return a flonum. parse-* use strict shapes -;; (Clojure 1.11: nil on malformed, throw on a non-string). - -;; bit ops return EXACT integers (= JVM long). ->int coerces the operand. -(define (->int x) (exact (truncate x))) -(define (jolt-bit-and a b) (bitwise-and (->int a) (->int b))) -(define (jolt-bit-or a b) (bitwise-ior (->int a) (->int b))) -(define (jolt-bit-xor a b) (bitwise-xor (->int a) (->int b))) -(define (jolt-bit-and-not a b) (bitwise-and (->int a) (bitwise-not (->int b)))) -(define (jolt-bit-not a) (bitwise-not (->int a))) -(define (jolt-bit-shift-left x n) (bitwise-arithmetic-shift-left (->int x) (->int n))) -(define (jolt-bit-shift-right x n) (bitwise-arithmetic-shift-right (->int x) (->int n))) -(define (bit-mask n) (bitwise-arithmetic-shift-left 1 (->int n))) -(define (jolt-bit-set x n) (bitwise-ior (->int x) (bit-mask n))) -(define (jolt-bit-clear x n) (bitwise-and (->int x) (bitwise-not (bit-mask n)))) -(define (jolt-bit-flip x n) (bitwise-xor (->int x) (bit-mask n))) -(define (jolt-bit-test x n) (not (zero? (bitwise-and (->int x) (bit-mask n))))) -;; unsigned-bit-shift-right: LOGICAL right shift over a 64-bit long (Java >>>), -;; so a negative operand shifts in zeros from its 64-bit two's-complement window -;; ((>>> -1 1) = 2^63-1), not the sign. The shift count is taken mod 64. -(define (jolt-unsigned-bit-shift-right x n) - (bitwise-arithmetic-shift-right (bitwise-and (->int x) #xFFFFFFFFFFFFFFFF) - (bitwise-and (->int n) 63))) - -;; ---- string->scalar parsers ------------------------------------------------- -(define (ascii-digit? c) (and (char>=? c #\0) (char<=? c #\9))) -(define (skip-digits s i n) (let loop ((i i)) (if (and (< i n) (ascii-digit? (string-ref s i))) (loop (+ i 1)) i))) -(define (sign-at? s i n) (and (< i n) (let ((c (string-ref s i))) (or (char=? c #\+) (char=? c #\-))))) - -(define (parse-long-shape? s) - (let* ((n (string-length s)) (i0 (if (sign-at? s 0 n) 1 0))) - (and (> n i0) (= (skip-digits s i0 n) n)))) - -(define (jolt-parse-long s) - (if (not (string? s)) (error #f "parse-long requires a string" s) - (if (parse-long-shape? s) (string->number s) jolt-nil))) ; exact long - -;; strict float shape: [+-]? ( D+ (. D*)? | . D+ ) ([eE][+-]? D+)? fully anchored. -(define (parse-double-shape? s) - (let ((n (string-length s))) - (and (> n 0) - (call/cc - (lambda (no) - (let* ((i0 (if (sign-at? s 0 n) 1 0)) - (after-int (skip-digits s i0 n)) - (had-int (> after-int i0)) - ;; mantissa end - (jm (cond - ((and had-int (< after-int n) (char=? (string-ref s after-int) #\.)) - (skip-digits s (+ after-int 1) n)) ; D+ . D* - ((and (not had-int) (< i0 n) (char=? (string-ref s i0) #\.)) - (let ((k (skip-digits s (+ i0 1) n))) ; . D+ - (if (> k (+ i0 1)) k (no #f)))) - (had-int after-int) - (else (no #f)))) - ;; optional exponent - (je (if (and (< jm n) (let ((c (string-ref s jm))) (or (char=? c #\e) (char=? c #\E)))) - (let* ((es (if (sign-at? s (+ jm 1) n) (+ jm 2) (+ jm 1))) - (ee (skip-digits s es n))) - (if (> ee es) ee (no #f))) - jm))) - (= je n))))))) - -(define (jolt-parse-double s) - (if (not (string? s)) (error #f "parse-double requires a string" s) - (cond - ((string=? s "Infinity") +inf.0) - ((string=? s "-Infinity") -inf.0) - ((string=? s "NaN") +nan.0) - ((parse-double-shape? s) (exact->inexact (string->number s))) - (else jolt-nil)))) - -(def-var! "clojure.core" "__bit-and" jolt-bit-and) -(def-var! "clojure.core" "__bit-or" jolt-bit-or) -(def-var! "clojure.core" "__bit-xor" jolt-bit-xor) -(def-var! "clojure.core" "__bit-and-not" jolt-bit-and-not) -(def-var! "clojure.core" "bit-not" jolt-bit-not) -(def-var! "clojure.core" "bit-shift-left" jolt-bit-shift-left) -(def-var! "clojure.core" "bit-shift-right" jolt-bit-shift-right) -(def-var! "clojure.core" "bit-set" jolt-bit-set) -(def-var! "clojure.core" "bit-clear" jolt-bit-clear) -(def-var! "clojure.core" "bit-flip" jolt-bit-flip) -(def-var! "clojure.core" "bit-test" jolt-bit-test) -(def-var! "clojure.core" "unsigned-bit-shift-right" jolt-unsigned-bit-shift-right) -(def-var! "clojure.core" "parse-long" jolt-parse-long) -(def-var! "clojure.core" "parse-double" jolt-parse-double) diff --git a/host/chez/natives-reader.ss b/host/chez/natives-reader.ss deleted file mode 100644 index df5c32f..0000000 --- a/host/chez/natives-reader.ss +++ /dev/null @@ -1,58 +0,0 @@ -;; natives-reader.ss — reader/macro runtime-support natives: the #?() reader feature -;; set, the reader-conditional + re-matcher tagged-map constructors, and macroexpand. -;; -;; Loaded late (after ns.ss): macroexpand forward-refs the runtime macro table -;; (host-contract hc-macro?/hc-expand-1) + the analyzer ctx, resolved at call time -;; after the spine loads. The hash / transient? / rseq / cat natives that used to -;; live here moved to natives-misc, transients, natives-seq, and natives-transduce. - -;; --- reader feature set (for #?() conditionals) — mutable list of name strings, -;; default jolt + default. __reader-features returns the strings; -set! replaces. -(define nr-reader-features (list "jolt" "default")) -(define (nr-reader-features-get) (list->cseq nr-reader-features)) -(define (nr-reader-features-set! names) - (set! nr-reader-features - (map (lambda (n) (cond ((keyword-t? n) (keyword-t-name n)) ((string? n) n) (else (jolt-pr-str n)))) - (seq->list (jolt-seq names)))) - jolt-nil) - -;; --- reader-conditional: a tagged map (reader-conditional? is an overlay -;; tagged-value predicate that reads :jolt/type). STAYS NATIVE: building a -;; :jolt/type-tagged map is part of the native value model — an overlay defn -;; returning {:jolt/type ...} silently fails to bind during the seed mint (the -;; guard around each prelude form swallows the load-time error), the same reason -;; every other tagged-value constructor (atom/volatile!/tagged-literal) is native. -;; re-matcher / re-find / re-groups are the stateful matcher API in regex.ss. -(define nr-kw-type (keyword "jolt" "type")) -(define nr-kw-rc (keyword "jolt" "reader-conditional")) -(define nr-kw-form (keyword #f "form")) -(define nr-kw-spl (keyword #f "splicing?")) -(define (nr-reader-conditional form splicing?) - (jolt-hash-map nr-kw-type nr-kw-rc nr-kw-form form nr-kw-spl splicing?)) - -;; --- macroexpand-1 / macroexpand: expand a (quoted) call form via the runtime -;; macro table (host-contract hc-macro?/hc-expand-1; forward-referenced, resolved -;; at call time after the spine loads). macroexpand loops until the head is no -;; longer a macro (subforms are not expanded, matching Clojure). -(define (nr-macroexpand-1 form) - (if (and (cseq? form) (cseq-list? form) (symbol-t? (seq-first form))) - (let ((ctx (make-analyze-ctx (chez-current-ns)))) - (if (hc-macro? ctx (seq-first form)) (hc-expand-1 ctx form) form)) - form)) -(define (nr-macroexpand form) - (let loop ((cur form)) - (let ((nxt (nr-macroexpand-1 cur))) (if (eq? cur nxt) cur (loop nxt))))) - -(def-var! "clojure.core" "__reader-features" nr-reader-features-get) -(def-var! "clojure.core" "__reader-features-set!" nr-reader-features-set!) -(def-var! "clojure.core" "reader-conditional" nr-reader-conditional) -(def-var! "clojure.core" "macroexpand-1" nr-macroexpand-1) - -;; letfn is a special form (the analyzer lowers it to letrec*, checked before any -;; macro), but on the JVM it is also a clojure.core macro that (resolve 'letfn) -;; finds — like let / loop / fn here. Intern a var so resolution matches; the value -;; is never invoked (the analyzer handles every (letfn …) form), and it is NOT -;; marked a macro, so macroexpand leaves a letfn form alone (it is special). -(def-var! "clojure.core" "letfn" - (lambda args (jolt-throw (jolt-ex-info "letfn is a special form" (jolt-hash-map))))) -(def-var! "clojure.core" "macroexpand" nr-macroexpand) diff --git a/host/chez/natives-seq.ss b/host/chez/natives-seq.ss deleted file mode 100644 index 0e6b63f..0000000 --- a/host/chez/natives-seq.ss +++ /dev/null @@ -1,247 +0,0 @@ -;; seq-native shims — native seq fns the overlay assumes are clojure.core -;; natives. Each is a pure fn over the existing seq layer (seq.ss) — collection -;; arities only; the 1-arg transducer arities follow below. Loaded last (after -;; converters.ss for jolt-compare and seq.ss for the reduced record). - -;; reduced / reduced? — the box itself is the jolt-reduced record from seq.ss -;; (so the reduce machinery there can see it); these just expose the constructor -;; and predicate. (deref a-reduced) is handled in atoms.ss. -(define (jolt-reduced-new x) (make-jolt-reduced x)) -(define (jolt-reduced-pred x) (jolt-reduced? x)) -(define (ensure-reduced x) (if (jolt-reduced? x) x (make-jolt-reduced x))) - -;; ============================================================================ -;; transducers — the 1-arg arity of map/filter/take/... returns a -;; transducer (fn [rf] rf') where rf' is a reducing fn with arities -;; []=init, [acc]=complete, [acc x]=step. rf and the mapping/predicate fns are jolt values, so every -;; call routes through jolt-invoke. A `reduced` step stops the fold — reduce-seq -;; (seq.ss) already short-circuits on a jolt-reduced. -;; ============================================================================ -;; The map transducer's step fn supports multiple inputs ([result input & inputs]), -;; so a multi-collection sequence/transduce — or medley's sequence-padded, which -;; calls (f acc i1 i2 …) — applies f across all of them: (rf result (apply f inputs)). -(define (td-map f) - (lambda (rf) - (lambda a - (case (length a) - ((0) (jolt-invoke rf)) - ((1) (jolt-invoke rf (car a))) - (else (jolt-invoke rf (car a) (apply jolt-invoke f (cdr a)))))))) -(define (td-filter pred) - (lambda (rf) - (lambda a - (case (length a) - ((0) (jolt-invoke rf)) - ((1) (jolt-invoke rf (car a))) - (else (if (jolt-truthy? (jolt-invoke pred (cadr a))) - (jolt-invoke rf (car a) (cadr a)) - (car a))))))) -(define (td-remove pred) (td-filter (lambda (x) (jolt-not (jolt-invoke pred x))))) -(define (td-take n) - (lambda (rf) - (let ((left n)) - (lambda a - (case (length a) - ((0) (jolt-invoke rf)) - ((1) (jolt-invoke rf (car a))) - (else (if (<= left 0) - (make-jolt-reduced (car a)) - (let ((r (jolt-invoke rf (car a) (cadr a)))) - (set! left (- left 1)) - (if (<= left 0) (ensure-reduced r) r))))))))) -(define (td-drop n) - (lambda (rf) - (let ((left n)) - (lambda a - (case (length a) - ((0) (jolt-invoke rf)) - ((1) (jolt-invoke rf (car a))) - (else (if (> left 0) (begin (set! left (- left 1)) (car a)) - (jolt-invoke rf (car a) (cadr a))))))))) -(define (td-take-while pred) - (lambda (rf) - (lambda a - (case (length a) - ((0) (jolt-invoke rf)) - ((1) (jolt-invoke rf (car a))) - (else (if (jolt-truthy? (jolt-invoke pred (cadr a))) - (jolt-invoke rf (car a) (cadr a)) - (make-jolt-reduced (car a)))))))) -(define (td-drop-while pred) - (lambda (rf) - (let ((dropping #t)) - (lambda a - (case (length a) - ((0) (jolt-invoke rf)) - ((1) (jolt-invoke rf (car a))) - (else (begin - (when (and dropping (not (jolt-truthy? (jolt-invoke pred (cadr a))))) - (set! dropping #f)) - (if dropping (car a) (jolt-invoke rf (car a) (cadr a)))))))))) -;; (mapcat f) transducer: map f, then splice (cat) f's result into rf, honoring a -;; mid-splice `reduced`. -(define (td-mapcat f) - (lambda (rf) - (lambda a - (case (length a) - ((0) (jolt-invoke rf)) - ((1) (jolt-invoke rf (car a))) - (else (let loop ((acc (car a)) - (xs (seq->list (jolt-seq (jolt-invoke f (cadr a)))))) - (if (or (null? xs) (jolt-reduced? acc)) acc - (loop (jolt-invoke rf acc (car xs)) (cdr xs))))))))) - -;; (into to xform from): transduce `from` through `xform` with conj as the rf. -(define (into-xform to xform from) - (let* ((conj-rf (lambda a (if (fx=? (length a) 1) (car a) ; completion = identity - (jolt-conj1 (car a) (cadr a))))) - (xrf (jolt-invoke xform conj-rf)) - (res (reduce-seq xrf to (jolt-seq from)))) - (jolt-invoke xrf res))) - -;; mapcat: (mapcat f) -> transducer; (mapcat f coll & colls) -> map f across the -;; colls (stops at shortest), then concat the results. -(define (jolt-mapcat f . colls) - (if (null? colls) - (td-mapcat f) - ;; lazily concat the per-element results — no seq->list, so mapcat over an - ;; infinite source stays lazy; the outer lazy-seq node defers the first - ;; element so a side-effecting f does not fire at construction (LazySeq). - (jolt-make-lazy-seq (lambda () (jolt-seq (lazy-concat-seq (apply jolt-map f colls))))))) - -;; take-while / drop-while: 1-arg -> transducer; 2-arg -> a seq over the coll. -(define (take-while-seq pred s) - (if (jolt-nil? s) jolt-empty-list - (let ((x (seq-first s))) - (if (jolt-truthy? (jolt-invoke pred x)) - (cseq-lazy x (lambda () (take-while-seq pred (jolt-seq (seq-more s))))) - jolt-empty-list)))) -(define jolt-take-while - (case-lambda - ((pred) (td-take-while pred)) - ((pred coll) (jolt-make-lazy-seq (lambda () (jolt-seq (take-while-seq pred (jolt-seq coll)))))))) -(define (drop-while-seq pred coll) - (let loop ((s (jolt-seq coll))) - (if (and (not (jolt-nil? s)) (jolt-truthy? (jolt-invoke pred (seq-first s)))) - (loop (jolt-seq (seq-more s))) - (if (jolt-nil? s) jolt-empty-list s)))) -(define jolt-drop-while - (case-lambda - ((pred) (td-drop-while pred)) - ((pred coll) (jolt-make-lazy-seq (lambda () (jolt-seq (drop-while-seq pred coll))))))) - -;; partition: (partition n coll), (partition n step coll), or -;; (partition n step pad coll). Only complete partitions of size n are kept; -;; with pad, a short final partition is padded from pad (and may be < n if pad -;; runs out). Each partition is a seq; the whole result is a lazy seq of seqs. -(define jolt-partition - (case-lambda - ((n coll) (jolt-make-lazy-seq (lambda () (jolt-seq (partition* (->idx n) (->idx n) #f #f coll))))) - ((n step coll) (jolt-make-lazy-seq (lambda () (jolt-seq (partition* (->idx n) (->idx step) #f #f coll))))) - ((n step pad coll) (jolt-make-lazy-seq (lambda () (jolt-seq (partition* (->idx n) (->idx step) #t pad coll))))))) -(define (take-n n s) ; -> (values list-of-first-n remaining-seq taken-count) - (let loop ((n n) (s s) (acc '())) - (if (or (fx<=? n 0) (jolt-nil? s)) - (values (reverse acc) s (length acc)) - (loop (fx- n 1) (jolt-seq (seq-more s)) (cons (seq-first s) acc))))) -(define (partition* n step has-pad pad coll) - (let loop ((s (jolt-seq coll))) - (if (jolt-nil? s) jolt-empty-list - (let-values (((part rest taken) (take-n n s))) - (cond - ;; full partition: emit it, advance `step` from its START - ((fx=? taken n) - (cseq-lazy (list->cseq part) - (lambda () (loop (jolt-seq (advance-by step s)))))) - ;; short final partition with pad: top up to n from pad, then stop - ((and has-pad (fx>? taken 0)) - (let ((padded (append part (take-list (- n taken) (jolt-seq pad))))) - (cseq-lazy (list->cseq padded) (lambda () jolt-empty-list)))) - ;; short final partition, no pad: dropped (Clojure keeps only full ones) - (else jolt-empty-list)))))) -(define (advance-by step s) ; drop `step` elements from s (seq), returns a seq - (let loop ((step step) (s s)) - (if (or (fx<=? step 0) (jolt-nil? s)) s - (loop (fx- step 1) (jolt-seq (seq-more s)))))) -(define (take-list n s) ; up to n elements of seq s as a Scheme list - (let loop ((n n) (s s) (acc '())) - (if (or (fx<=? n 0) (jolt-nil? s)) (reverse acc) - (loop (fx- n 1) (jolt-seq (seq-more s)) (cons (seq-first s) acc))))) - -;; sort: (sort coll) uses compare; (sort cmp coll) uses cmp, whose result may be -;; a 3-way number (<0 / 0 / >0) OR a boolean (a Clojure-style less-than pred). -(define (cmp->less cmp) - (lambda (a b) - (let ((r (jolt-invoke cmp a b))) - (if (number? r) (< r 0) (jolt-truthy? r))))) -(define jolt-sort - (case-lambda - ((coll) (jolt-sort* (cmp->less jolt-compare) coll)) - ((cmp coll) (jolt-sort* (cmp->less cmp) coll)))) -(define (jolt-sort* less? coll) - (let ((s (jolt-seq coll))) - (if (jolt-nil? s) jolt-empty-list - (list->cseq (list-sort less? (seq->list s)))))) - -;; identical?: reference identity (Clojure ==). eq? gives pointer identity over -;; the value model — interned keywords/fixnums/nil compare equal, distinct -;; collections do not. Must NOT be value equality: a deftype whose .equals calls -;; (identical? this o) to short-circuit (e.g. core.logic's Substitutions) would -;; otherwise recur forever (identical? -> = -> equiv -> .equals -> identical?). -(define (jolt-identical? a b) (eq? a b)) - -;; Give the seq.ss native procedures their transducer (1-arg) arity — the emitter -;; lowers (map f)/(filter p)/(take n) at the wrong arity to the bare procedure -;; (value-position path), so widening the procedures is what makes the 1-arg form -;; work. Capture the originals (collection arities) first, then redefine. -(define %prev-jolt-map jolt-map) -(set! jolt-map (lambda (f . colls) - (if (null? colls) (td-map f) (apply %prev-jolt-map f colls)))) -(define %prev-jolt-filter jolt-filter) -(set! jolt-filter (case-lambda ((pred) (td-filter pred)) - ((pred coll) (%prev-jolt-filter pred coll)))) -(define %prev-jolt-remove jolt-remove) -(set! jolt-remove (case-lambda ((pred) (td-remove pred)) - ((pred coll) (%prev-jolt-remove pred coll)))) -(define %prev-jolt-take jolt-take) -(set! jolt-take (case-lambda ((n) (td-take n)) - ((n coll) (%prev-jolt-take n coll)))) -(define %prev-jolt-drop jolt-drop) -(set! jolt-drop (case-lambda ((n) (td-drop n)) - ((n coll) (%prev-jolt-drop n coll)))) -;; into: add the 3-arg (into to xform from). The 2-arg stays the seq.ss fold. -(define %prev-jolt-into jolt-into) -(set! jolt-into (case-lambda ((to from) (%prev-jolt-into to from)) - ((to xform from) (into-xform to xform from)))) - -(def-var! "clojure.core" "reduced" jolt-reduced-new) -(def-var! "clojure.core" "reduced?" jolt-reduced-pred) -(def-var! "clojure.core" "mapcat" jolt-mapcat) -(def-var! "clojure.core" "take-while" jolt-take-while) -(def-var! "clojure.core" "drop-while" jolt-drop-while) -(def-var! "clojure.core" "partition" jolt-partition) -(def-var! "clojure.core" "sort" jolt-sort) -(def-var! "clojure.core" "identical?" jolt-identical?) - -;; rseq: vectors + sorted colls only (Clojure), the reverse of the ascending seq. -(define (jolt-rseq coll) - (cond - ((or (pvec? coll) (htable-sorted? coll)) - (list->cseq (reverse (seq->list (jolt-seq coll))))) - ;; a deftype/record implementing clojure.lang.Reversible (rseq) — e.g. - ;; data.priority-map — drives rseq through its own method. - ((and (jrec? coll) (find-method-any-protocol (jrec-tag coll) "rseq")) - => (lambda (f) (jolt-invoke f coll))) - (else (jolt-throw (jolt-ex-info "rseq requires a vector or sorted collection" (jolt-hash-map)))))) -(def-var! "clojure.core" "rseq" jolt-rseq) - -;; clojure.core/unchecked-* — host-defined wrapping (Java long) arithmetic from -;; seq.ss. def-var!'d here because def-var! isn't bound when seq.ss loads. -(let ((d! (lambda (n v) (def-var! "clojure.core" n v)))) - (d! "unchecked-add" jolt-unchecked-add) (d! "unchecked-add-int" jolt-unchecked-add) - (d! "unchecked-subtract" jolt-unchecked-sub) (d! "unchecked-subtract-int" jolt-unchecked-sub) - (d! "unchecked-multiply" jolt-unchecked-mul) (d! "unchecked-multiply-int" jolt-unchecked-mul) - (d! "unchecked-negate" jolt-uncneg) (d! "unchecked-negate-int" jolt-uncneg) - (d! "unchecked-inc" jolt-uncinc) (d! "unchecked-inc-int" jolt-uncinc) - (d! "unchecked-dec" jolt-uncdec) (d! "unchecked-dec-int" jolt-uncdec) - (d! "unchecked-divide-int" jolt-unchecked-div) (d! "unchecked-remainder-int" jolt-unchecked-rem)) diff --git a/host/chez/natives-transduce.ss b/host/chez/natives-transduce.ss deleted file mode 100644 index 3034b4f..0000000 --- a/host/chez/natives-transduce.ss +++ /dev/null @@ -1,96 +0,0 @@ -;; natives-transduce.ss — the transducer surface: volatiles, the `cat` transducer, -;; and sequence / transduce application. -;; -;; `sequence` and `transduce` are seed natives. The stateful transducer arities -;; (take-nth/map-indexed/partition-by/dedupe/distinct, all overlay) use -;; volatile!/vswap!/vreset!/deref, shimmed here. -;; -;; Volatiles are a native mutable box (jvol) — the overlay vreset!/vswap! drive a -;; volatile through jolt.host/ref-put!+get, but a Chez volatile is a record, not a -;; tagged table, so those overlay versions are overridden natively in -;; post-prelude.ss. transduce/sequence build on the existing into-xform / reduce- -;; seq machinery (natives-seq.ss / seq.ss). Loaded after those + atoms.ss (deref). - -;; --- volatiles --------------------------------------------------------------- -(define-record-type jvol (fields (mutable v)) (nongenerative chez-jvol-v1)) -(define (jolt-volatile! x) (make-jvol x)) -(define (jolt-vreset! vol x) (jvol-v-set! vol x) x) -(define (jolt-vswap! vol f . args) - (let ((nv (apply jolt-invoke f (jvol-v vol) args))) (jvol-v-set! vol nv) nv)) -(define (jolt-volatile-pred? x) (jvol? x)) -;; deref reads a volatile too (partition-all/-by transducers @-deref their box). -(define %xf-deref jolt-deref) -(set! jolt-deref (lambda (x) (if (jvol? x) (jvol-v x) (%xf-deref x)))) - -(def-var! "clojure.core" "volatile!" jolt-volatile!) -(def-var! "clojure.core" "deref" jolt-deref) - -;; --- sequence ---------------------------------------------------------------- -;; transduce lives in the overlay (clojure/core/22-coll.clj): it's a pure -;; composition (xf (reduce xf init coll)) over reduce, so the Clojure version -;; lowers to the same code the native shim did. sequence stays native (below): -;; its transformer iterator drives the reduced box + lazy realization directly. - -;; (sequence coll) -> a seq; (sequence xform coll) -> a LAZY seq of coll transformed -;; by xform. A transformer iterator (mirrors clojure.core's TransformerIterator): -;; pull one input at a time through (xform rf), where rf buffers each emitted value; -;; emit the buffer lazily, pulling more input only when it drains. So an infinite or -;; expensive source is consumed incrementally — (first (sequence (map inc) (range))) -;; returns at once. Honors `reduced` (stop pulling) and runs the 1-arg completion to -;; flush a stateful xform (partition-all / dedupe / a trailing partition). -(define (sequence-xf xform coll) - (let* ((buf (box '())) ; emitted values for the current step, reversed - (rf (case-lambda - (() jolt-nil) - ((acc) acc) - ((acc x) (set-box! buf (cons x (unbox buf))) acc))) - (xrf (jolt-invoke xform rf))) - ;; advance the source until buf holds output or the input is drained+completed. - (define (fill src acc completed) - (let loop ((src src) (acc acc) (completed completed)) - (cond - ((pair? (unbox buf)) (values src acc completed)) - (completed (values src acc #t)) - ((jolt-reduced? acc) - (jolt-invoke xrf (jolt-reduced-val acc)) ; completion may flush - (loop src (jolt-reduced-val acc) #t)) - (else - (let ((s (jolt-seq src))) - (if (jolt-nil? s) - (begin (jolt-invoke xrf acc) (loop src acc #t)) ; complete -> flush - (loop (seq-more s) (jolt-invoke xrf acc (seq-first s)) completed))))))) - ;; Resolve the next chunk now (one fill pulls just enough input to emit or to - ;; exhaust), so the result is a real cseq | empty — `empty` is jolt-empty-list - ;; at the top (so an empty result still prints "()") and jolt-nil inside a tail - ;; (the cseq terminator). The TAILS stay lazy, so an infinite source is fine. - (define (step src acc completed empty) - (let-values (((src2 acc2 comp2) (fill src acc completed))) - (let ((out (reverse (unbox buf)))) - (set-box! buf '()) - (if (null? out) - empty - (let build ((o out)) - (if (null? (cdr o)) - (cseq-lazy (car o) (lambda () (step src2 acc2 comp2 jolt-nil))) - (cseq-lazy (car o) (lambda () (build (cdr o)))))))))) - (step coll jolt-nil #f jolt-empty-list))) - -(define jolt-sequence - (case-lambda - ((coll) (jolt-seq coll)) - ((xform coll) (sequence-xf xform coll)))) - -(def-var! "clojure.core" "sequence" jolt-sequence) - -;; --- cat --------------------------------------------------------------------- -;; cat transducer: each input item is itself a collection, concatenated into the -;; downstream reducing fn. -(define (jolt-cat rf) - (lambda a - (cond - ((null? a) (jolt-invoke rf)) - ((null? (cdr a)) (jolt-invoke rf (car a))) - (else - (let loop ((xs (seq->list (jolt-seq (cadr a)))) (acc (car a))) - (if (null? xs) acc (loop (cdr xs) (jolt-invoke rf acc (car xs))))))))) -(def-var! "clojure.core" "cat" jolt-cat) diff --git a/host/chez/ns.ss b/host/chez/ns.ss deleted file mode 100644 index 435a18e..0000000 --- a/host/chez/ns.ss +++ /dev/null @@ -1,391 +0,0 @@ -;; namespaces — the namespace value model. -;; -;; The namespace ops (find-ns/resolve/in-ns/…) work over the rt.ss var-table -;; (cells carry ns + name + defined?) and the multimethods.ss chez-current-ns -;; box. A namespace VALUE is a `jns` record carrying its name string — distinct -;; from a map/record so (map? ns) is #f, but the overlay's `ns-name` reads -;; (get ns :name); that's overridden natively in post-prelude.ss (loads after -;; the overlay clobbers it). -;; -;; Loaded LAST from rt.ss. The analyzer bakes a def's target ns at compile time, -;; so a runtime in-ns redirects only *ns* / str-of-ns, not later defs in the -;; same program. - -(define-record-type jns (fields name) (nongenerative chez-jns-v1)) - -;; registry: name-string -> jns. Seeded with the two always-present namespaces; -;; grown by in-ns / create-ns. find-ns ALSO derives existence from the var-table -;; (any cell with that ns), so a namespace that only ever had vars def'd into it -;; is still found. -(define ns-registry (make-hashtable string-hash string=?)) -(define (intern-ns! name) - (or (hashtable-ref ns-registry name #f) - (let ((n (make-jns name))) (hashtable-set! ns-registry name n) n))) -(intern-ns! "user") -(intern-ns! "clojure.core") - -;; --- namespace aliases ------------------------------------------------------ -;; (require '[ns :as a]) registers a -> ns so the analyzer can resolve a/foo to -;; ns/foo. Keyed by (compile-ns . alias). The requires are pre-registered at -;; analyze time (compile-eval.ss) — analysis precedes eval, so a runtime require -;; no-op is fine. Also drives jolt-ns-aliases below. -(define ns-alias-table (make-hashtable equal-hash equal?)) -(define (chez-register-alias! cns alias target) - (hashtable-set! ns-alias-table (cons cns alias) target)) -(define (chez-resolve-alias cns alias) - (hashtable-ref ns-alias-table (cons cns alias) #f)) -;; :refer brings an UNQUALIFIED name into cns, resolving to target-ns/name. -(define ns-refer-table (make-hashtable equal-hash equal?)) -(define (chez-register-refer! cns name target) - (hashtable-set! ns-refer-table (cons cns name) target)) -;; refer-all (a bare `use`): cns -> list of fully-referred target ns names. A name -;; not found per-name resolves to the first refer-all target that defines it. -(define ns-refer-all-table (make-hashtable equal-hash equal?)) -(define (chez-register-refer-all! cns target) - (let ((cur (hashtable-ref ns-refer-all-table cns '()))) - (unless (member target cur) - (hashtable-set! ns-refer-all-table cns (cons target cur))))) -(define (chez-resolve-refer cns name) - (or (hashtable-ref ns-refer-table (cons cns name) #f) - (let loop ((ts (hashtable-ref ns-refer-all-table cns '()))) - (cond ((null? ts) #f) - ((let ((c (var-cell-lookup (car ts) name))) (and c (var-cell-defined? c))) (car ts)) - (else (loop (cdr ts))))))) -;; parse a require/use spec FORM and register its :as alias + :refer names under -;; `cns`. spec: [ns :as a :refer [x y] ...] / (ns ...) / bare ns. opts are -;; keyword/value pairs after the ns symbol. -(define (chez-register-spec! cns spec) - (let ((items (cond ((pvec? spec) (seq->list spec)) - ((or (cseq? spec) (empty-list-t? spec)) (seq->list spec)) - (else '())))) - (when (and (pair? items) (symbol-t? (car items))) - (let ((target (symbol-t-name (car items)))) - (let loop ((xs (cdr items))) - (when (and (pair? xs) (pair? (cdr xs))) - (let ((k (car xs)) (v (cadr xs))) - (when (keyword? k) - (cond - ((string=? (keyword-t-name k) "as") - (when (symbol-t? v) (chez-register-alias! cns (symbol-t-name v) target))) - ;; :refer (require) and :only (use) both bring unqualified names - ;; into cns resolving to target/name. - ((or (string=? (keyword-t-name k) "refer") (string=? (keyword-t-name k) "only")) - (cond - ;; :refer :all — bring in every public var (require :refer :all) - ((and (keyword? v) (string=? (keyword-t-name v) "all")) - (chez-register-refer-all! cns target)) - ;; :refer [a b] or :refer (a b) — both forms list names to bring in. - ((or (pvec? v) (cseq? v) (empty-list-t? v)) - (for-each (lambda (n) - (when (symbol-t? n) (chez-register-refer! cns (symbol-t-name n) target))) - (seq->list v)))))))) - (loop (cddr xs)))))))) - -;; a namespace designator -> its name string (a jns or a symbol; the corpus never -;; passes a bare string). -(define (ns-desig->name d) - (if (jns? d) (jns-name d) (symbol-t-name d))) - -(define (ns-has-vars? nm) - (let ((found #f)) - (vector-for-each - (lambda (c) (when (and (not found) (string=? (var-cell-ns c) nm)) (set! found #t))) - (hashtable-values var-table)) - found)) - -(define (jolt-find-ns desig) - (let ((nm (ns-desig->name desig))) - (or (hashtable-ref ns-registry nm #f) - (and (ns-has-vars? nm) (intern-ns! nm)) - jolt-nil))) - -(define (jolt-the-ns desig) - (if (jns? desig) desig - (let ((n (jolt-find-ns desig))) - (if (jns? n) n (error #f "No namespace" desig))))) - -(define (jolt-create-ns desig) (intern-ns! (ns-desig->name desig))) - -;; in-ns: register + switch the current ns + re-bind *ns* + return the jns. This -;; updates only the RUNTIME current ns — subsequent defs in the same program were -;; already ns-baked by the analyzer, so it does not redirect them. It is enough -;; for *ns* / str-of-ns to track the switch. -(define (jolt-in-ns desig) - (let* ((nm (ns-desig->name desig)) (n (intern-ns! nm))) - ;; set the THREAD-LOCAL current ns; *ns* reads derive from it (dyn-binding.ss), - ;; so this is per-thread — concurrent nREPL sessions don't clobber each other. - (set-chez-ns! nm) - n)) - -;; ns-name: a namespace's name as a (no-ns) symbol. Overrides the overlay (which -;; reads (get ns :name) = nil on a jns record) — wired in via post-prelude.ss. -(define (jolt-ns-name desig) - (jolt-symbol #f (jns-name (jolt-the-ns desig)))) - -(define (jolt-all-ns) - (let ((seen (make-hashtable string-hash string=?))) - (vector-for-each (lambda (k) (hashtable-set! seen k #t)) (hashtable-keys ns-registry)) - (vector-for-each (lambda (c) (hashtable-set! seen (var-cell-ns c) #t)) (hashtable-values var-table)) - (list->cseq (map intern-ns! (vector->list (hashtable-keys seen)))))) - -;; ns-publics / ns-map / ns-interns: a {sym -> var-cell} jolt map built by scanning -;; the var-table for defined cells in the namespace. ns-interns/ns-map keep every -;; var; ns-publics drops the ones marked ^:private (defn-/def ^:private), like the -;; JVM. ns-aliases is an empty map (map? is true). -(define (var-private? c) - (let ((m (hashtable-ref var-meta-table c #f))) - (and m (jolt-truthy? (jolt-get m (keyword #f "private")))))) -(define (ns-vars-pmap-when nm keep?) - (let ((m (jolt-hash-map))) - (vector-for-each - (lambda (c) - (when (and (string=? (var-cell-ns c) nm) (var-cell-defined? c) (keep? c)) - (set! m (jolt-assoc m (jolt-symbol #f (var-cell-name c)) c)))) - (hashtable-values var-table)) - m)) -(define (ns-vars-pmap nm) (ns-vars-pmap-when nm (lambda (c) #t))) -(define (jolt-ns-publics desig) (ns-vars-pmap-when (ns-desig->name desig) (lambda (c) (not (var-private? c))))) -(define (jolt-ns-interns desig) (ns-vars-pmap (ns-desig->name desig))) - -;; ns-aliases: the {alias-sym -> ns-value} registered under `desig` -;; (default the current ns) via require :as / alias. Reads ns-alias-table. -(define (jolt-ns-aliases . desig) - (let ((cns (if (pair? desig) (ns-desig->name (car desig)) (chez-current-ns))) - (m (jolt-hash-map))) - (vector-for-each - (lambda (k) - (when (string=? (car k) cns) - (set! m (jolt-assoc m (jolt-symbol #f (cdr k)) - (intern-ns! (hashtable-ref ns-alias-table k #f)))))) - (hashtable-keys ns-alias-table)) - m)) - -;; ns-refers: the {sym -> var} referred into `desig` via refer/use. -(define (jolt-ns-refers desig) - (let ((cns (ns-desig->name desig)) (m (jolt-hash-map))) - (vector-for-each - (lambda (k) - (when (string=? (car k) cns) - (let* ((target (hashtable-ref ns-refer-table k #f)) - (c (and target (var-cell-lookup target (cdr k))))) - (when c (set! m (jolt-assoc m (jolt-symbol #f (cdr k)) c)))))) - (hashtable-keys ns-refer-table)) - m)) - -;; ns-imports: clojure.core auto-imports the 96 public java.lang classes into -;; every ns. jolt has no classloader, but returns that map (short symbol -> -;; canonical class-name token) so (count (ns-imports 'user)) = 96 like the JVM. -(define jolt-default-import-names - '("AbstractMethodError" "Appendable" "ArithmeticException" "ArrayIndexOutOfBoundsException" - "ArrayStoreException" "AssertionError" "BigDecimal" "BigInteger" "Boolean" "Byte" - "Callable" "CharSequence" "Character" "Class" "ClassCastException" "ClassCircularityError" - "ClassFormatError" "ClassLoader" "ClassNotFoundException" "CloneNotSupportedException" - "Cloneable" "Comparable" "Compiler" "Deprecated" "Double" "Enum" - "EnumConstantNotPresentException" "Error" "Exception" "ExceptionInInitializerError" "Float" - "IllegalAccessError" "IllegalAccessException" "IllegalArgumentException" - "IllegalMonitorStateException" "IllegalStateException" "IllegalThreadStateException" - "IncompatibleClassChangeError" "IndexOutOfBoundsException" "InheritableThreadLocal" - "InstantiationError" "InstantiationException" "Integer" "InternalError" "InterruptedException" - "Iterable" "LinkageError" "Long" "Math" "NegativeArraySizeException" "NoClassDefFoundError" - "NoSuchFieldError" "NoSuchFieldException" "NoSuchMethodError" "NoSuchMethodException" - "NullPointerException" "Number" "NumberFormatException" "Object" "OutOfMemoryError" "Override" - "Package" "Process" "ProcessBuilder" "Readable" "Runnable" "Runtime" "RuntimeException" - "RuntimePermission" "SecurityException" "SecurityManager" "Short" "StackOverflowError" - "StackTraceElement" "StrictMath" "String" "StringBuffer" "StringBuilder" - "StringIndexOutOfBoundsException" "SuppressWarnings" "System" "Thread" "Thread$State" - "Thread$UncaughtExceptionHandler" "ThreadDeath" "ThreadGroup" "ThreadLocal" "Throwable" - "TypeNotPresentException" "UnknownError" "UnsatisfiedLinkError" "UnsupportedClassVersionError" - "UnsupportedOperationException" "VerifyError" "VirtualMachineError" "Void")) -(define jolt-default-imports - (let loop ((ns jolt-default-import-names) (m (jolt-hash-map))) - (if (null? ns) m - (loop (cdr ns) - (jolt-assoc m (jolt-symbol #f (car ns)) (string-append "java.lang." (car ns))))))) -(define (jolt-ns-imports . _) jolt-default-imports) - -;; resolve: an unqualified symbol resolves in the current ns then clojure.core; a -;; qualified one in its own ns. Returns the var iff genuinely defined, else nil — -;; never interns an empty cell (var-cell-lookup is non-creating). -;; resolve `sym` in the current ns: a qualified ns part is read as an :as alias -;; (then a real ns); an unqualified name resolves in the current ns, its :refers, -;; then clojure.core. (ns-resolve does the same against an explicit ns.) -(define (jolt-resolve sym) - (let* ((cns (chez-current-ns)) - (sns (symbol-t-ns sym)) (nm (symbol-t-name sym)) - (c (if (string? sns) - (var-cell-lookup (or (chez-resolve-alias cns sns) sns) nm) - (or (var-cell-lookup cns nm) - (let ((ref (chez-resolve-refer cns nm))) (and ref (var-cell-lookup ref nm))) - (var-cell-lookup "clojure.core" nm))))) - (if (and c (var-cell-defined? c)) c jolt-nil))) - -(define (jolt-find-var sym) - (let ((sns (symbol-t-ns sym)) (nm (symbol-t-name sym))) - (if (string? sns) - (let ((c (var-cell-lookup sns nm))) (if (and c (var-cell-defined? c)) c jolt-nil)) - (error #f "find-var requires a fully-qualified symbol" sym)))) - -;; ns-unmap: clear the mapping — drop defined? and reset the root to unbound, so a -;; later resolve returns nil. -(define (jolt-ns-unmap ns-desig sym) - (let ((c (var-cell-lookup (ns-desig->name ns-desig) (symbol-t-name sym)))) - (when c (var-cell-defined?-set! c #f) (var-cell-root-set! c jolt-unbound))) - jolt-nil) - -;; --- ns runtime fns --------------------------------------------------------- -;; ns-resolve: resolve `sym` as if reading it in namespace `ns-desig`. Qualified -;; syms consult that ns's :as aliases; unqualified resolve in the ns, its :refers, -;; then clojure.core. Returns the var or nil (never interns). -(define (jolt-ns-resolve ns-desig sym) - (let* ((cns (ns-desig->name ns-desig)) - (sns (symbol-t-ns sym)) (nm (symbol-t-name sym)) - (c (if (string? sns) - (var-cell-lookup (or (chez-resolve-alias cns sns) sns) nm) - (or (var-cell-lookup cns nm) - (let ((ref (chez-resolve-refer cns nm))) (and ref (var-cell-lookup ref nm))) - (var-cell-lookup "clojure.core" nm))))) - (if (and c (var-cell-defined? c)) c jolt-nil))) - -;; remove-ns: drop the namespace from the registry AND its vars, so find-ns -;; (which also derives existence from the var-table) returns nil afterward. -(define (jolt-remove-ns desig) - (let ((nm (ns-desig->name desig))) - (hashtable-delete! ns-registry nm) - (vector-for-each - (lambda (k) (let ((c (hashtable-ref var-table k #f))) - (when (and c (string=? (var-cell-ns c) nm)) (hashtable-delete! var-table k)))) - (hashtable-keys var-table)) - jolt-nil)) - -;; intern: create/set a var ns/sym to val (or an unbound cell). Returns the var. -(define (jolt-intern ns-desig sym . vopt) - (let ((nm (ns-desig->name ns-desig)) (s (symbol-t-name sym))) - ;; the namespace must exist (Namespace.find), like the JVM's intern - (unless (hashtable-ref ns-registry nm #f) - (jolt-throw (jolt-ex-info (string-append "No namespace: " nm " found") empty-pmap))) - (if (pair? vopt) (def-var! nm s (car vopt)) (declare-var! nm s)))) - -;; alias / ns-unalias: register/drop an :as alias under the current (or given) ns. -;; A runtime alias is registered into the SAME table the analyzer consults, so a -;; later form in the program resolves alias/foo (the spine analyzes form by form). -(define (jolt-alias alias-sym ns-sym) - (chez-register-alias! (chez-current-ns) (symbol-t-name alias-sym) (ns-desig->name ns-sym)) - jolt-nil) -(define (jolt-ns-unalias ns-desig alias-sym) - (hashtable-delete! ns-alias-table (cons (ns-desig->name ns-desig) (symbol-t-name alias-sym))) - jolt-nil) - -;; refer: bring every public var of `ns-sym` into the current ns as an unqualified -;; name (filters accepted/ignored — the corpus uses the bare form). refer-clojure -;; is a no-op (clojure.core always resolves on Chez). -(define (jolt-refer ns-sym . _filters) - (let ((target (ns-desig->name ns-sym)) (cns (chez-current-ns))) - (vector-for-each - (lambda (c) (when (and (string=? (var-cell-ns c) target) (var-cell-defined? c)) - (chez-register-refer! cns (var-cell-name c) target))) - (hashtable-values var-table)) - jolt-nil)) -;; (:refer-clojure :exclude [names…]) — clojure.core always resolves on Chez, so -;; the only thing to track is the EXCLUDE set: an excluded name is not -;; clojure.core/name, so syntax-quote qualifies it to the current ns instead (a ns -;; that excludes and defines its own, e.g. core.logic.fd's ==). -(define ns-core-exclude-table (make-hashtable equal-hash equal?)) ; cns -> (name -> #t) -(define (chez-register-core-exclude! cns name) - (let ((h (or (hashtable-ref ns-core-exclude-table cns #f) - (let ((h (make-hashtable string-hash string=?))) - (hashtable-set! ns-core-exclude-table cns h) h)))) - (hashtable-set! h name #t))) -(define (chez-core-excluded? cns name) - (let ((h (hashtable-ref ns-core-exclude-table cns #f))) - (and h (hashtable-ref h name #f) #t))) -(define (jolt-refer-clojure . args) - (let ((cns (chez-current-ns))) - (let loop ((a args)) - (when (and (pair? a) (pair? (cdr a))) - (when (and (keyword? (car a)) (string=? (keyword-t-name (car a)) "exclude")) - (for-each (lambda (n) (when (symbol-t? n) - (chez-register-core-exclude! cns (symbol-t-name n)))) - (seq->list (cadr a)))) - (loop (cddr a))))) - jolt-nil) - -;; alter-meta! / reset-meta!: a var's metadata lives in var-meta-table (rt.ss); -;; any other reference (atom/agent/namespace) uses the identity meta side-table -;; jolt-meta reads. -(define (jolt-alter-meta! ref f . args) - (if (var-cell? ref) - (let* ((cur (or (hashtable-ref var-meta-table ref #f) (jolt-hash-map))) - (new (apply jolt-invoke f cur args))) - (hashtable-set! var-meta-table ref new) - new) - (let* ((cur (let ((m (jolt-meta ref))) (if (jolt-nil? m) (jolt-hash-map) m))) - (new (apply jolt-invoke f cur args))) - (hashtable-set! meta-table ref new) - new))) -(define (jolt-reset-meta! ref m) - (if (var-cell? ref) - (hashtable-set! var-meta-table ref m) - (hashtable-set! meta-table ref m)) - m) - -;; --- RESOLVE FRICTION: native-op cells ------------------------------------- -;; Native-op primitives (+ map reduce …) are INLINED at emit, so they have no -;; var-cell and (resolve '+) would be nil — diverging from Clojure where it is a -;; var. def-var! each to its value-position procedure so it has a real, defined -;; cell (calls still inline, so no perf hit; #'+ deref and ((resolve '+) 1 2) also -;; work now). The clojure.core prelude, loaded AFTER rt.ss, overwrites the cells -;; for names it also defines in the overlay (map/filter/…); the purely-inlined -;; scalars (+/-/" >) (cons "<=" <=) (cons ">=" >=) - (cons "=" jolt=) (cons "inc" jolt-inc) (cons "dec" jolt-dec) (cons "not" jolt-not) - (cons "min" min) (cons "max" max) - (cons "mod" modulo) (cons "rem" remainder) (cons "quot" quotient) - (cons "vector" jolt-vector) (cons "hash-map" jolt-hash-map) (cons "hash-set" jolt-hash-set) - (cons "conj" jolt-conj) (cons "get" jolt-get) (cons "nth" jolt-nth) (cons "count" jolt-count) - (cons "assoc" jolt-assoc) (cons "dissoc" jolt-dissoc) (cons "contains?" jolt-contains?) - (cons "empty?" jolt-empty?) (cons "peek" jolt-peek) (cons "pop" jolt-pop) - (cons "first" jolt-first) (cons "rest" jolt-rest) (cons "next" jolt-next) (cons "seq" jolt-seq) - (cons "cons" jolt-cons) (cons "list" jolt-list) (cons "reverse" jolt-reverse) (cons "last" jolt-last) - (cons "map" jolt-map) (cons "filter" jolt-filter) (cons "remove" jolt-remove) - (cons "reduce" jolt-reduce) (cons "into" jolt-into) (cons "concat" jolt-concat) (cons "apply" jolt-apply) - (cons "range" jolt-range) (cons "take" jolt-take) (cons "drop" jolt-drop) - (cons "keys" jolt-keys) (cons "vals" jolt-vals) - (cons "even?" jolt-even?) (cons "odd?" jolt-odd?) (cons "pos?" jolt-pos?) (cons "neg?" jolt-neg?) - (cons "zero?" jolt-zero?) (cons "identity" jolt-identity) - (cons "ex-info" jolt-ex-info))) - -;; --- bindings + *ns* -------------------------------------------------------- -(def-var! "clojure.core" "find-ns" jolt-find-ns) -(def-var! "clojure.core" "the-ns" jolt-the-ns) -(def-var! "clojure.core" "create-ns" jolt-create-ns) -(def-var! "clojure.core" "in-ns" jolt-in-ns) -(def-var! "clojure.core" "all-ns" jolt-all-ns) -(def-var! "clojure.core" "ns-publics" jolt-ns-publics) -(def-var! "clojure.core" "ns-map" jolt-ns-interns) -(def-var! "clojure.core" "ns-interns" jolt-ns-interns) -(def-var! "clojure.core" "ns-aliases" jolt-ns-aliases) -(def-var! "clojure.core" "ns-refers" jolt-ns-refers) -(def-var! "clojure.core" "ns-imports" jolt-ns-imports) -(def-var! "clojure.core" "resolve" jolt-resolve) -(def-var! "clojure.core" "ns-resolve" jolt-ns-resolve) -(def-var! "clojure.core" "find-var" jolt-find-var) -(def-var! "clojure.core" "ns-unmap" jolt-ns-unmap) -(def-var! "clojure.core" "remove-ns" jolt-remove-ns) -(def-var! "clojure.core" "intern" jolt-intern) -(def-var! "clojure.core" "alias" jolt-alias) -(def-var! "clojure.core" "ns-unalias" jolt-ns-unalias) -(def-var! "clojure.core" "refer" jolt-refer) -(def-var! "clojure.core" "refer-clojure" jolt-refer-clojure) -(def-var! "clojure.core" "alter-meta!" jolt-alter-meta!) -(def-var! "clojure.core" "reset-meta!" jolt-reset-meta!) -;; *ns* starts at the user namespace (the current ns for -e user code). in-ns -;; re-binds it. (ns-name is overridden natively in post-prelude.ss.) -(def-var! "clojure.core" "*ns*" (intern-ns! "user")) - -;; --- printer patches: a namespace renders as its name (str / pr-str / -e) ---- -(register-pr-arm! jns? jns-name) -(register-str-render! jns? jns-name) diff --git a/host/chez/png.ss b/host/chez/png.ss deleted file mode 100644 index e8a02c4..0000000 --- a/host/chez/png.ss +++ /dev/null @@ -1,122 +0,0 @@ -;; png.ss — jolt.png: a minimal PNG writer, the built-in the -;; ray-tracer-multi example renders through. Truecolor (8-bit RGB), no -;; compression: the IDAT zlib stream uses DEFLATE "stored" (uncompressed) blocks, -;; so there is no compressor to carry — just CRC-32 / Adler-32 framing over Chez -;; bytevectors. def-var!'d into the jolt.png namespace, so a (require '[jolt.png]) -;; resolves it as a baked namespace (no source file). - -;; --- CRC-32 (PNG chunk checksum) -------------------------------------------- -(define png-crc-table - (let ((t (make-vector 256))) - (do ((n 0 (+ n 1))) ((= n 256) t) - (let loop ((c n) (k 0)) - (if (= k 8) - (vector-set! t n c) - (loop (if (odd? c) (bitwise-xor #xedb88320 (bitwise-arithmetic-shift-right c 1)) - (bitwise-arithmetic-shift-right c 1)) - (+ k 1))))))) -(define (png-crc32 bv) - (let ((len (bytevector-length bv))) - (let loop ((i 0) (c #xffffffff)) - (if (= i len) - (bitwise-xor c #xffffffff) - (loop (+ i 1) - (bitwise-xor (bitwise-arithmetic-shift-right c 8) - (vector-ref png-crc-table - (bitwise-and (bitwise-xor c (bytevector-u8-ref bv i)) #xff)))))))) - -;; --- Adler-32 (zlib checksum) ----------------------------------------------- -(define (png-adler32 bv) - (let ((len (bytevector-length bv))) - (let loop ((i 0) (a 1) (b 0)) - (if (= i len) - (bitwise-ior (bitwise-arithmetic-shift-left b 16) a) - (let ((a* (modulo (+ a (bytevector-u8-ref bv i)) 65521))) - (loop (+ i 1) a* (modulo (+ b a*) 65521))))))) - -;; --- byte helpers ----------------------------------------------------------- -(define (png-u32be n) - (let ((bv (make-bytevector 4))) - (bytevector-u8-set! bv 0 (bitwise-and (bitwise-arithmetic-shift-right n 24) #xff)) - (bytevector-u8-set! bv 1 (bitwise-and (bitwise-arithmetic-shift-right n 16) #xff)) - (bytevector-u8-set! bv 2 (bitwise-and (bitwise-arithmetic-shift-right n 8) #xff)) - (bytevector-u8-set! bv 3 (bitwise-and n #xff)) - bv)) -(define (png-bytes . bs) (u8-list->bytevector bs)) -(define (png-cat . bvs) - (let* ((total (apply + (map bytevector-length bvs))) - (out (make-bytevector total))) - (let loop ((bvs bvs) (off 0)) - (if (null? bvs) out - (let ((n (bytevector-length (car bvs)))) - (bytevector-copy! (car bvs) 0 out off n) - (loop (cdr bvs) (+ off n))))))) - -;; one PNG chunk: length(4) + type(4) + data + crc32(type+data)(4) -(define (png-chunk type-str data) - (let ((type (string->utf8 type-str))) - (png-cat (png-u32be (bytevector-length data)) type data - (png-u32be (png-crc32 (png-cat type data)))))) - -;; DEFLATE "stored" stream of raw: ≤65535-byte blocks, each 1 header byte -;; (BFINAL bit) + LEN(2 LE) + NLEN(2 LE) + raw. Wrapped as zlib (0x78 0x01 … -;; adler32). -(define (png-deflate-stored raw) - (let ((len (bytevector-length raw))) - (let loop ((off 0) (acc (list (png-bytes #x78 #x01)))) - (if (>= off len) - (apply png-cat (reverse (cons (png-u32be (png-adler32 raw)) acc))) - (let* ((n (min 65535 (- len off))) - (final (if (>= (+ off n) len) 1 0)) - (block (png-cat (png-bytes final) - (png-bytes (bitwise-and n #xff) (bitwise-arithmetic-shift-right n 8)) - (png-bytes (bitwise-and (bitwise-not n) #xff) - (bitwise-and (bitwise-arithmetic-shift-right (bitwise-not n) 8) #xff)) - (let ((b (make-bytevector n))) (bytevector-copy! raw off b 0 n) b)))) - (loop (+ off n) (cons block acc))))))) - -;; --- the image value -------------------------------------------------------- -(define-record-type pimg (fields w h data (mutable cur)) (nongenerative jolt-png-img-v1)) -(define (png-clamp-byte n) - (let ((x (cond ((and (number? n) (exact? n) (integer? n)) n) - ((number? n) (exact (floor n))) - (else 0)))) - (cond ((< x 0) 0) ((> x 255) 255) (else x)))) - -(define (png-image w h) (make-pimg w h (make-bytevector (* w h 3) 0) 0)) -(define (png-put! img r g b) - (let ((d (pimg-data img)) (c (pimg-cur img))) - (when (<= (+ c 3) (bytevector-length d)) - (bytevector-u8-set! d c (png-clamp-byte r)) - (bytevector-u8-set! d (+ c 1) (png-clamp-byte g)) - (bytevector-u8-set! d (+ c 2) (png-clamp-byte b)) - (pimg-cur-set! img (+ c 3))) - jolt-nil)) - -;; scanlines with a 0 (None) filter byte per row -> raw -> zlib -> IDAT -(define (png-raw img w h) - (let* ((stride (* w 3)) (raw (make-bytevector (* h (+ 1 stride)))) (src (pimg-data img))) - (do ((y 0 (+ y 1))) ((= y h) raw) - (let ((ro (* y (+ 1 stride)))) - (bytevector-u8-set! raw ro 0) ; filter: None - (bytevector-copy! src (* y stride) raw (+ ro 1) stride))))) - -(define png-signature (png-bytes #x89 #x50 #x4e #x47 #x0d #x0a #x1a #x0a)) -(define (png-ihdr w h) - (png-cat (png-u32be w) (png-u32be h) - (png-bytes 8 2 0 0 0))) ; bitdepth 8, colortype 2 (RGB), deflate, filter 0, no interlace - -(define (png-write img w h path) - (let* ((idat (png-deflate-stored (png-raw img w h))) - (bytes (png-cat png-signature - (png-chunk "IHDR" (png-ihdr w h)) - (png-chunk "IDAT" idat) - (png-chunk "IEND" (make-bytevector 0)))) - (p (open-file-output-port path (file-options no-fail) (buffer-mode block)))) - (put-bytevector p bytes) - (close-port p) - jolt-nil)) - -(def-var! "jolt.png" "image" png-image) -(def-var! "jolt.png" "put!" png-put!) -(def-var! "jolt.png" "write" png-write) diff --git a/host/chez/post-prelude.ss b/host/chez/post-prelude.ss deleted file mode 100644 index fefaec4..0000000 --- a/host/chez/post-prelude.ss +++ /dev/null @@ -1,150 +0,0 @@ -;; post-prelude overrides — loaded AFTER the assembled clojure.core -;; prelude, so these win over the overlay's own def-var!. -;; -;; A few clojure.core predicates are implemented in the overlay by inspecting a -;; tagged value's :jolt/type key (e.g. (get x :jolt/type)). That key doesn't -;; exist for native representations: a jolt char is a Scheme char, an atom is a -;; Chez record. The overlay's def-var! loads after rt.ss, so it clobbers the -;; correct native shims (predicates.ss / atoms.ss) with versions that return -;; false on every Chez value. Re-assert the native versions here. -(def-var! "clojure.core" "char?" jolt-char-pred?) -(def-var! "clojure.core" "atom?" jolt-atom?) -;; atom watches/validators: the overlay drives these via jolt.host/ref-put! on a -;; tagged table (get a :watches), which a Chez atom record is not — re-assert the -;; native versions (defined in atoms.ss), and swap!/reset! notify+validate there. -(def-var! "clojure.core" "add-watch" jolt-add-watch) -(def-var! "clojure.core" "remove-watch" jolt-remove-watch) -(def-var! "clojure.core" "set-validator!" jolt-set-validator!) -(def-var! "clojure.core" "get-validator" jolt-get-validator) -;; volatiles: a Chez volatile is a jvol record, but the overlay vreset!/vswap!/ -;; volatile? drive it via jolt.host/ref-put!+get / :jolt/type (tagged-table only). -;; Override with the native versions (defined in natives-transduce.ss). -(def-var! "clojure.core" "vreset!" jolt-vreset!) -(def-var! "clojure.core" "vswap!" jolt-vswap!) -(def-var! "clojure.core" "volatile?" jolt-volatile-pred?) -;; bound?: the overlay reads (get v :root) — nil on a Chez var-cell record, so it -;; would wrongly report every var unbound. Native version (defined in vars.ss). -(def-var! "clojure.core" "bound?" jolt-bound?) -;; uuid?/random-uuid/parse-uuid/tagged-literal? are overlay (read :jolt/type or -;; build tagged tables) — re-assert the native versions (natives-misc.ss). -(def-var! "clojure.core" "uuid?" jolt-uuid-pred?) -(def-var! "clojure.core" "random-uuid" jolt-random-uuid) -(def-var! "clojure.core" "parse-uuid" jolt-parse-uuid) -(def-var! "clojure.core" "tagged-literal?" jolt-tagged-literal-pred?) -;; ns-name: the overlay reads (get ns :name) — nil on a jns namespace record. -;; Native version (defined in ns.ss) returns the namespace's name symbol. -(def-var! "clojure.core" "ns-name" jolt-ns-name) -;; concurrency: the overlay's future-done?/future-cancelled?/realized? read a -;; future-map's :cached/:cancelled keys, and promise/deliver are a non-blocking -;; atom shim. A Chez future/promise is a record, and we want JVM (blocking, -;; shared-heap) semantics — re-assert the native versions. realized? -;; wraps the overlay (which still handles delay/lazy-seq/atom) for non-futures. -(def-var! "clojure.core" "future-done?" jolt-native-future-done?) -(def-var! "clojure.core" "future-cancelled?" jolt-native-future-cancelled?) -(def-var! "clojure.core" "future?" jolt-future?) -(def-var! "clojure.core" "promise" jolt-promise-new) -(def-var! "clojure.core" "deliver" jolt-deliver) -;; agents: the overlay (50-io) is a synchronous shim (agent = atom, send applies -;; immediately). Re-assert the native async agents (per-agent serialized worker), -;; matching the JVM. await/restart-agent are new (the overlay has neither). -(def-var! "clojure.core" "agent" jolt-agent-new) -(def-var! "clojure.core" "agent?" jolt-agent?) -(def-var! "clojure.core" "send" jolt-agent-send) -(def-var! "clojure.core" "send-off" jolt-agent-send) -(def-var! "clojure.core" "await" jolt-agent-await) -(def-var! "clojure.core" "agent-error" jolt-agent-error) -(def-var! "clojure.core" "restart-agent" jolt-agent-restart) -(def-var! "clojure.core" "deref" jolt-deref) -(let ((overlay-realized? (var-deref "clojure.core" "realized?"))) - (def-var! "clojure.core" "realized?" - (lambda (x) - (cond - ((or (jolt-future? x) (jolt-promise? x) (jolt-delay? x)) (jolt-conc-realized? x)) - ;; a lazy-seq carries its own realized? flag (lazy-bridge.ss). The overlay - ;; realized? reads :jolt/type and throws on a jolt-lazyseq record. - ((jolt-lazyseq? x) (jolt-lazyseq-realized? x)) - ;; a seq cell answers by its forced flag: the rest of a realized lazy - ;; chain is a cseq under jolt's seq model, and (realized? (rest s)) after - ;; a next must be true like the JVM's realized LazySeq — never a throw - ;; whose message renders the (possibly infinite) seq. - ;; a PLAIN seq (list/cons/range — not a lazy-seq wrapper) is not an - ;; IPending on the JVM: realized? throws. - ((or (cseq? x) (empty-list-t? x)) - (jolt-throw (jolt-host-throwable - "java.lang.ClassCastException" - (string-append "class " (guard (e (#t "?")) (jolt-class-name x)) - " cannot be cast to class clojure.lang.IPending")))) - (else (jolt-invoke overlay-realized? x)))))) -;; clojure.edn/read over a reader: drain the jhost reader, then read through the -;; overlay read-string so the opts map (:readers/:default/:eof) is honored. -(def-var! "clojure.edn" "read" - (case-lambda - ((reader) (chez-edn-read reader)) - ((opts reader) - (jolt-invoke (var-deref "clojure.edn" "read-string") opts - (if (reader-jhost? reader) (drain-reader reader) (jolt-str-render-one reader)))))) -;; line-seq: a jhost reader (io/reader result) -> drain+split; a map-reader (the -;; overlay's :read-line-fn model, e.g. with-in-str) -> the overlay version. -(let ((overlay-line-seq (var-deref "clojure.core" "line-seq"))) - (def-var! "clojure.core" "line-seq" - (lambda (rdr) - (if (reader-jhost? rdr) (chez-line-seq rdr) (jolt-invoke overlay-line-seq rdr))))) -;; JVM-parity numeric tower. integer?/float? are on the compiler emit/inference -;; path (so they stay native) but the overlay (20-coll.clj) still carries an -;; all-flonum int?/double? (int? -> integer?, double? -> not-integer) that -;; misclassifies exact rationals (e.g. (double? 1/2) -> true). Re-assert the -;; native tower-correct versions so they win over those overlay defs. int?/double? -;; alias integer?/float?. == is value-equality. (ratio?/rational? are now correct -;; in the overlay, built on jolt.host tower tests, so they need no re-assertion.) -(def-var! "clojure.core" "integer?" jolt-integer?) -(def-var! "clojure.core" "int?" jolt-integer?) -(def-var! "clojure.core" "float?" jolt-float?) -(def-var! "clojure.core" "double?" jolt-float?) -;; ratio?/rational? now live (correctly) in the overlay, so they no longer need a -;; native re-assertion here. decimal? stays (bigdec re-binds it). -(def-var! "clojure.core" "decimal?" jolt-decimal?) -(def-var! "clojure.core" "==" jolt-num-equiv) -;; chunked-seq? is true for a vector's seq (a real chunked-seq); the overlay's -;; always-false stub loaded over the host fn, so re-assert it. -(def-var! "clojure.core" "chunked-seq?" na-chunked-seq?) -;; record? is a host type check — true only for a defrecord, not a bare deftype -;; (jrec-record?), matching the JVM (instance? IRecord). The overlay's -;; (some? (get x :jolt/deftype)) get-trick would invoke a sorted-map comparator. -(def-var! "clojure.core" "record?" (lambda (x) (jrec-record? x))) - -;; read / read+string over a HOST reader jhost (java.io StringReader/PushbackReader): -;; the overlay's IReader protocol only covers the reify map-reader, so a (read -;; pushback-reader) — cuerdas' string interpolation — would miss. Intercept a host -;; reader; everything else (the *in* reify) delegates to the overlay. -(let ((ov-read (var-deref "clojure.core" "read"))) - (def-var! "clojure.core" "read" - (case-lambda - (() (jolt-invoke ov-read)) - ((stream) - (if (reader-jhost? stream) - (let-values (((form found?) (host-reader-read-form stream))) - (if found? form (jolt-throw (jolt-ex-info "EOF while reading" empty-pmap)))) - (jolt-invoke ov-read stream))) - ((stream e? ev) - (if (reader-jhost? stream) - (let-values (((form found?) (host-reader-read-form stream))) - (cond (found? form) - ((jolt-truthy? e?) (jolt-throw (jolt-ex-info "EOF while reading" empty-pmap))) - (else ev))) - (jolt-invoke ov-read stream e? ev)))))) -(let ((ov-rps (var-deref "clojure.core" "read+string"))) - (def-var! "clojure.core" "read+string" - (case-lambda - (() (jolt-invoke ov-rps)) - ((stream) (jolt-invoke (var-deref "clojure.core" "read+string") stream #t jolt-nil)) - ((stream e? ev) - (if (reader-jhost? stream) - (let* ((s (drain-reader stream)) (pr (jolt-parse-next s))) - (if (jolt-nil? pr) - (begin (reader-refill! stream "") - (if (jolt-truthy? e?) (jolt-throw (jolt-ex-info "EOF while reading" empty-pmap)) - (jolt-vector ev ""))) - (let ((rest (jolt-nth pr 1))) - (reader-refill! stream rest) - (jolt-vector (jolt-nth pr 0) (substring s 0 (- (string-length s) (string-length rest))))))) - (jolt-invoke ov-rps stream e? ev)))))) diff --git a/host/chez/predicates.ss b/host/chez/predicates.ss deleted file mode 100644 index 9419755..0000000 --- a/host/chez/predicates.ss +++ /dev/null @@ -1,110 +0,0 @@ -;; type predicates + simple accessors — host-coupled natives. -;; -;; These are host primitives (not clojure.core overlay fns), so they're never -;; def-var!'d by the assembled prelude; the Chez host must provide them. -;; map?/vector?/set? are STRICT over the persistent-collection records, seq? is -;; true only for real sequences, coll? is the union. Record arms are added by -;; records.ss, which extends these dispatchers. - -(define (jolt-map? x) (pmap? x)) -;; a map entry is a pvec under the hood AND is vector? — Clojure's MapEntry -;; implements IPersistentVector, so (vector? (first {:a 1})) is true. -(define (jolt-vector? x) (pvec? x)) -(define (jolt-set? x) (pset? x)) -(define (jolt-seq? x) (or (cseq? x) (empty-list-t? x))) -;; list? lives in the overlay (clojure/core/20-coll.clj) — see jolt.host/cseq? etc. -(define (jolt-coll-pred? x) - (or (pvec? x) (pmap? x) (pset? x) (cseq? x) (empty-list-t? x) (jolt-lazyseq? x))) -(define (jolt-number? x) (number? x)) -(define (jolt-string? x) (string? x)) -(define (jolt-char-pred? x) (char? x)) -;; JVM-parity number-type predicates over the Chez numeric tower. integer? is the -;; INTEGER TYPE (exact integer = Long/BigInt), NOT integer-VALUED: (integer? 3.0) -;; is false on the JVM (3.0 is a Double). float? = flonum (double). ratio? = exact -;; non-integer (= JVM Ratio). rational? = exact (integer or ratio; jolt has no -;; BigDecimal). decimal? is always false (no BigDecimal type). -(define (jolt-integer? x) (and (number? x) (exact? x) (integer? x))) -(define (jolt-float? x) (and (number? x) (flonum? x))) -;; ratio?/rational? live in the overlay (clojure/core/20-coll.clj), built on the -;; jolt.host tower tests. decimal? stays native: the optional bigdec module -;; (java/bigdec.ss) re-binds it to jbigdec?, so it can't be a static overlay const. -(define (jolt-decimal? x) #f) -(define (jolt-fn? x) (procedure? x)) -(define (jolt-boolean-pred? x) (boolean? x)) - -;; (boolean x) coerces truthiness (nil/false -> false, else true). MUST stay native: -;; the backend's emit path calls clojure.core/boolean for every :if node -;; (backend_scheme.clj bool tracking), so it has to exist before ANY compilation, -;; including the kernel overlay tier (whose own fns contain `if`). Migrating it even -;; to the kernel tier deadlocks: compiling the tier that defines boolean needs boolean. -(define (jolt-boolean x) (if (jolt-truthy? x) #t #f)) - -;; (name x): keyword/symbol -> name string; string -> itself. -(define (jolt-name x) - (cond - ((keyword? x) (keyword-t-name x)) - ((symbol-t? x) (symbol-t-name x)) - ((string? x) x) - (else (error #f "name: expected string/symbol/keyword" x)))) - -;; (namespace x): keyword/symbol ns string, or nil when unqualified. -(define (jolt-namespace x) - (let ((ns (cond ((keyword? x) (keyword-t-ns x)) - ((symbol-t? x) (symbol-t-ns x)) - (else (error #f "namespace: expected symbol/keyword" x))))) - (if (or (jolt-nil? ns) (not ns) (eq? ns '())) jolt-nil ns))) - -(def-var! "clojure.core" "nil?" jolt-nil?) -(def-var! "clojure.core" "number?" jolt-number?) -(def-var! "clojure.core" "string?" jolt-string?) -(def-var! "clojure.core" "char?" jolt-char-pred?) -(def-var! "clojure.core" "integer?" jolt-integer?) -(def-var! "clojure.core" "float?" jolt-float?) -(def-var! "clojure.core" "decimal?" jolt-decimal?) -;; == numeric value-equality (ignores exactness, unlike =): (== 3 3.0) -> true. -;; 1-arity is trivially true; 2+ args must all be numbers (Numbers.equiv throws -;; otherwise). Uses Scheme = (value across the tower), not jolt= (category-aware). -(define (jolt-num-equiv . xs) - ;; 1-arity short-circuits to true for ANY value (Clojure's == 1-arg returns true - ;; before the number check); 2+ args must all be numbers. - (if (and (pair? xs) (null? (cdr xs))) - #t - (let all-num? ((ys xs)) - (cond - ((null? ys) (or (null? xs) (apply = xs))) - ((number? (car ys)) (all-num? (cdr ys))) - (else (error #f "== requires numbers" xs)))))) -(def-var! "clojure.core" "==" jolt-num-equiv) -(def-var! "clojure.core" "symbol?" jolt-symbol?) -(def-var! "clojure.core" "keyword?" keyword?) -(def-var! "clojure.core" "map?" jolt-map?) -(def-var! "clojure.core" "vector?" jolt-vector?) -(def-var! "clojure.core" "set?" jolt-set?) -(def-var! "clojure.core" "seq?" jolt-seq?) -(def-var! "clojure.core" "coll?" jolt-coll-pred?) -(def-var! "clojure.core" "fn?" jolt-fn?) -(def-var! "clojure.core" "boolean?" jolt-boolean-pred?) -(def-var! "clojure.core" "boolean" jolt-boolean) -(def-var! "clojure.core" "name" jolt-name) -(def-var! "clojure.core" "namespace" jolt-namespace) - -;; --- jolt.host raw type-test primitives ------------------------------------- -;; Some clojure.core predicates bottom out at host tests overlay Clojure can't -;; reach. Expose the ones the migratable predicates need so the overlay versions -;; lower to exactly these calls — no perf loss. rational-type? is the Chez TYPE -;; test (exact rational), distinct from clojure.core/rational? (which gates on -;; number? first). exact? is wrapped TOTAL (Chez's raw exact? errors on a -;; non-number); rational-type? already returns #f for a non-match. -;; -;; Only the tests consumed by the migrated predicates (ratio?/rational? -> exact?, -;; rational-type?; list? -> cseq?/cseq-list?/empty-list?) are exposed. The rest of -;; the predicate web stays native and is NOT exposed: map?/set?/seq?/coll? are -;; extended at runtime with sorted/record/lazy arms, decimal? is extended by the -;; optional bigdec module, integer?/float? are on the compiler emit/inference path, -;; and vector? is reached by the kernel-tier peek during bootstrap. -(define (jh-exact? x) (and (number? x) (exact? x))) -(def-var! "jolt.host" "exact?" jh-exact?) -(def-var! "jolt.host" "rational-type?" rational?) -(def-var! "jolt.host" "cseq?" cseq?) -(def-var! "jolt.host" "empty-list?" empty-list-t?) -(def-var! "jolt.host" "cseq-list?" cseq-list?) diff --git a/host/chez/printing.ss b/host/chez/printing.ss deleted file mode 100644 index 5df1dbf..0000000 --- a/host/chez/printing.ss +++ /dev/null @@ -1,144 +0,0 @@ -;; readable printer + output seams — the __pr-str1 / __write / __with-out-str -;; host seams the overlay's pr-str/pr/prn/print/println/*-str family is built on -;; (jolt-core/clojure/core/20-coll.clj). -;; -;; jolt-pr-str (rt.ss) is STR-style: strings render raw. pr-str needs READABLE -;; (pr) style: strings quoted+escaped at every nesting level. This adds the -;; readable renderer; it mirrors jolt-pr-str but quotes strings and recurses into -;; itself, delegating scalars (nil/bool/number/keyword/symbol/char/regex) to -;; jolt-pr-str (already readable for those). The canonical ORDERED printer is -;; still future work — unordered colls render in HAMT order, compared via `=`. - -;; inner string escape (no surrounding quotes): " \ newline tab return. -(define (jolt-str-escape s) - (let loop ((cs (string->list s)) (acc '())) - (if (null? cs) - (list->string (reverse acc)) - (loop (cdr cs) - (let ((c (car cs))) - (case c - ((#\") (cons #\" (cons #\\ acc))) - ((#\\) (cons #\\ (cons #\\ acc))) - ((#\newline) (cons #\n (cons #\\ acc))) - ((#\tab) (cons #\t (cons #\\ acc))) - ((#\return) (cons #\r (cons #\\ acc))) - (else (cons c acc)))))))) - -;; A host shim registers a type's readable rendering via register-pr-readable-arm!, -;; or register-pr-arm! for types whose str and readable forms match (most host types: -;; inst, uuid, record, var, …). Disjoint types, checked before the base cases. -(define jolt-pr-readable-arms '()) -(define (register-pr-readable-arm! pred render) - (set! jolt-pr-readable-arms (cons (cons pred render) jolt-pr-readable-arms))) -(define (register-pr-arm! pred render) - (register-pr-str-arm! pred render) - (register-pr-readable-arm! pred render)) -(define (jolt-pr-readable-base x) - (cond - ((string? x) (string-append "\"" (jolt-str-escape x) "\"")) - ;; pr renders the infinities / NaN in READABLE form (##Inf reads back), unlike - ;; str's "Infinity"/"-Infinity"/"NaN". Applies at every nesting level. - ((and (flonum? x) (fl= x +inf.0)) "##Inf") - ((and (flonum? x) (fl= x -inf.0)) "##-Inf") - ((and (flonum? x) (not (fl= x x))) "##NaN") - ;; transients print as a cold tagged type (print-method routes this through a - ;; multimethod; the readable fallback renders it directly). - ;; forward refs to transients.ss (loaded later) — resolved at call time. - ((jolt-transient? x) - (case (jolt-transient-kind x) - ((vec) "#") ((set) "#") (else "#"))) - ((pvec? x) (if (jolt-print-hash?) "#" - (with-deeper-print - (string-append "[" (jolt-str-join (jolt-limited-vec-strs x jolt-pr-readable)) "]")))) - ((pset? x) (if (jolt-print-hash?) "#" - (with-deeper-print - (string-append "#{" (jolt-str-join (jolt-limited-list-strs - (pset-fold x (lambda (e a) (cons (jolt-pr-readable e) a)) '()))) "}")))) - ((pmap? x) (if (jolt-print-hash?) "#" - (with-deeper-print - (string-append "{" (jolt-str-join (jolt-limited-list-strs - (pmap-fold x (lambda (k v a) - (cons (string-append (jolt-pr-readable k) " " (jolt-pr-readable v)) a)) '()))) "}")))) - ((empty-list-t? x) (if (jolt-print-hash?) "#" "()")) - ((cseq? x) (if (jolt-print-hash?) "#" - (with-deeper-print - (string-append "(" (jolt-str-join (jolt-limited-seq-strs x jolt-pr-readable)) ")")))) - (else (jolt-pr-str x)))) -(define (jolt-pr-readable-dispatch x) - (let loop ((as jolt-pr-readable-arms)) - (cond ((null? as) (jolt-pr-readable-base x)) - (((caar as) x) ((cdar as) x)) - (else (loop (cdr as)))))) - -;; *print-meta* support. The var is def'd after this file loads, so capture its -;; cell lazily; jolt-var-get (patched by dyn-binding.ss) honors a `binding`. -(define pr-meta-cell #f) -(define (pr-print-meta?) - (unless pr-meta-cell (set! pr-meta-cell (jolt-var "clojure.core" "*print-meta*"))) - (jolt-truthy? (jolt-var-get pr-meta-cell))) -;; The metadata to print before x, or jolt-nil. A var prints as #'ns/name (its -;; {:ns :name} is derived, not user metadata) and a procedure is opaque — skip both. -(define (pr-user-meta x) - (if (or (var-cell? x) (procedure? x)) jolt-nil (jolt-meta x))) - -(define (jolt-pr-readable x) - (if (pr-print-meta?) - (let ((m (pr-user-meta x))) - (if (jolt-nil? m) - (jolt-pr-readable-dispatch x) - (string-append "^" (jolt-pr-readable-dispatch m) " " (jolt-pr-readable-dispatch x)))) - (jolt-pr-readable-dispatch x))) - -;; __pr-str1: render ONE value readably (the overlay's pr-str joins these). -(define (jolt-pr-str1 x) (jolt-pr-readable x)) - -;; __write: push a string to output. Normally this goes to the current Chez port -;; (so __with-out-str's redirect captures it). When clojure.pprint is active it -;; installs __pprint-write-hook; jolt-write then offers each string to the hook, -;; which routes it column-aware into a clojure.pprint pretty-writer if *out* is -;; bound to one (returns truthy) and otherwise declines (returns nil) so the -;; string falls through to the port. This is the JVM behaviour where core print -;; honours *out*; jolt only needs it for the pretty-printer. -(define jolt-pprint-write-hook jolt-nil) -;; suppressed while __with-out-str captures output to a string port: there the -;; redirect, not *out*, defines where text goes (pr-str / print-str rely on it). -(define jolt-pprint-hook-suppressed (make-thread-parameter #f)) -(define (jolt-write s) - (if (and (not (jolt-nil? jolt-pprint-write-hook)) - (not (jolt-pprint-hook-suppressed)) - (jolt-truthy? (jolt-invoke jolt-pprint-write-hook s))) - jolt-nil - (begin (display s) jolt-nil))) -(def-var! "clojure.core" "__set-pprint-write-hook!" - (lambda (f) (set! jolt-pprint-write-hook f) jolt-nil)) -;; clojure.pprint wraps its writing in this so core print routes into the active -;; pretty-writer even under an outer with-out-str (which sets suppressed). A -;; pr-str/print-str nested inside then re-suppresses, so its capture still works. -(def-var! "clojure.core" "__with-pprint-routing" - (lambda (thunk) - (parameterize ((jolt-pprint-hook-suppressed #f)) (jolt-invoke thunk)))) - -;; __with-out-str: run a jolt thunk with *out* rebound to a string port, return -;; the captured text. -(define (jolt-with-out-str thunk) - (with-output-to-string - (lambda () (parameterize ((jolt-pprint-hook-suppressed #t)) (jolt-invoke thunk))))) - -;; __eprint / __eprintf: stderr seams. Flush each write — like the JVM's -;; auto-flushing System.err — so a long-running process (a server that never -;; returns from -main) shows its log lines instead of leaving them in a buffer -;; that only drains at exit. -(define (jolt-eprint s) - (display s (current-error-port)) - (flush-output-port (current-error-port)) - jolt-nil) -(define (jolt-eprintf fmt . args) - (apply fprintf (current-error-port) fmt args) - (flush-output-port (current-error-port)) - jolt-nil) - -(def-var! "clojure.core" "__pr-str1" jolt-pr-str1) -(def-var! "clojure.core" "__write" jolt-write) -(def-var! "clojure.core" "__with-out-str" jolt-with-out-str) -(def-var! "clojure.core" "__eprint" jolt-eprint) -(def-var! "clojure.core" "__eprintf" jolt-eprintf) diff --git a/host/chez/reader.ss b/host/chez/reader.ss deleted file mode 100644 index 068bfa3..0000000 --- a/host/chez/reader.ss +++ /dev/null @@ -1,1007 +0,0 @@ -;; Chez-side Clojure data reader. -;; -;; The data half of runtime read/eval: a recursive-descent reader that parses -;; ONE Clojure form off a string and produces jolt runtime values. Two host -;; seams hang off it: -;; read-string : string -> first form (clojure.core seam, src 772) -;; __parse-next : string -> [form rest] | nil (the *in* family seam, src 801) -;; read / read+string / with-in-str / line-seq / clojure.edn are Clojure over -;; these (jolt-core/clojure/core/50-io.clj, stdlib/clojure/edn.clj). -;; -;; Form shapes: -;; sets -> {:jolt/type :jolt/set :value [...]} (a FORM, not a set) -;; #tag frm -> {:jolt/type :jolt/tagged :tag :#tag :form ...} (NO data reader) -;; #"src" -> {:jolt/type :jolt/tagged :tag :regex :form "src"} -;; 'x `x ~x ~@x @x -> (quote x)/(syntax-quote x)/(unquote x)/ -;; (unquote-splicing x)/(clojure.core/deref x) -;; ^meta sym -> symbol carrying meta ({:tag "Name"} | {:kw true} | the map) -;; read-string of blank / comment-only input is nil (the documented seed wart), -;; NOT an EOF throw. - -;; Reader forms reuse these interned keywords for their tag structure. -(define rdr-kw-jolt-type (keyword "jolt" "type")) -(define rdr-kw-jolt-set (keyword "jolt" "set")) -(define rdr-kw-jolt-tagged (keyword "jolt" "tagged")) -(define rdr-kw-value (keyword #f "value")) -(define rdr-kw-tag (keyword #f "tag")) -(define rdr-kw-form (keyword #f "form")) - -;; A unique sentinel meaning "no form here" (EOF, or a close delimiter that the -;; caller — read-seq — must consume). Never a legal jolt value, so unambiguous. -(define rdr-eof (list 'reader-eof)) -(define (rdr-eof? x) (eq? x rdr-eof)) - -;; A splicing reader conditional #?@(...) yields this wrapper; the enclosing -;; sequence reader splices its items in place (never a legal jolt value). -(define-record-type rdr-splice-t (fields items) (nongenerative rdr-splice-v1)) - -(define (rdr-ws? c) - (or (char-whitespace? c) (char=? c #\,))) - -;; `'` (apostrophe) is a NON-terminating macro char in Clojure (isTerminatingMacro -;; is false for it), so it's a valid symbol constituent after the first char: -;; inc'/+'/foo' read as single symbols. A LEADING ' still dispatches as quote -;; (handled before token reading begins). Omit it from the terminator set. -(define (rdr-terminator? c) - (or (rdr-ws? c) - (memv c '(#\( #\) #\[ #\] #\{ #\} #\" #\; #\@ #\^ #\` #\~ #\\)))) - -(define (rdr-digit? c) (and (char>=? c #\0) (char<=? c #\9))) -(define (rdr-octal? c) (and (char>=? c #\0) (char<=? c #\7))) -(define (rdr-all-digits? s from to) - (and (> to from) - (let loop ((i from)) - (cond ((>= i to) #t) - ((rdr-digit? (string-ref s i)) (loop (+ i 1))) - (else #f))))) -;; every char of s in [from,to) is an octal digit (and the span is non-empty). -(define (rdr-all-octal? s from to) - (and (fx= i end) i) - ((rdr-ws? (string-ref s i)) (loop (+ i 1))) - ((char=? (string-ref s i) #\;) - (let eol ((j (+ i 1))) - (if (or (>= j end) (char=? (string-ref s j) #\newline) - (char=? (string-ref s j) #\return)) - (loop j) - (eol (+ j 1))))) - (else i)))) - -;; --- numbers ---------------------------------------------------------------- -;; A token is a number iff it (after an optional sign) starts with a digit and -;; parses. Ratios and big-N/M decimals use all-double rendering -;; for division; ints/bignums stay exact (Chez's tower IS Clojure's). -(define (rdr-string-index-char str c) - (let ((n (string-length str))) - (let loop ((i 0)) - (cond ((>= i n) #f) - ((char=? (string-ref str i) c) i) - (else (loop (+ i 1))))))) - -;; Numeric tower (JVM parity): integer literals read as exact integers (= Long/ -;; BigInt, arbitrary precision), a/b ratios as exact rationals (= Ratio), and -;; decimal/exponent literals as flonums (= double). -(define (rdr-try-number tok) - (rdr-try-number-raw tok)) - -(define (rdr-try-number-raw tok) - (let ((len (string-length tok))) - (and (> len 0) - (let* ((c0 (string-ref tok 0)) - (signed (or (char=? c0 #\+) (char=? c0 #\-))) - (start (if signed 1 0))) - (and (> len start) - (rdr-digit? (string-ref tok start)) - (rdr-number-body tok start signed c0)))))) - -;; parse DDD in base `radix` (2..36); #f on a bad digit. Scheme string->number only -;; does radix 2/8/10/16, so Clojure's NrDDD (e.g. 36rZ) needs a manual parse. -(define (rdr-parse-radix digits radix) - (let ((len (string-length digits))) - (and (> len 0) - (let loop ((i 0) (acc 0)) - (if (>= i len) - acc - (let* ((c (char-downcase (string-ref digits i))) - (d (cond ((and (char>=? c #\0) (char<=? c #\9)) (- (char->integer c) 48)) - ((and (char>=? c #\a) (char<=? c #\z)) (+ 10 (- (char->integer c) 97))) - (else #f)))) - (and d (< d radix) (loop (+ i 1) (+ (* acc radix) d))))))))) - -(define (rdr-number-body tok start signed sign-ch) - (let* ((sign (if (and signed (char=? sign-ch #\-)) -1 1)) - (len (string-length tok)) - (body (substring tok start len)) - (blen (string-length body)) - (slash (rdr-string-index-char body #\/))) - (cond - ;; ratio a/b -> exact rational (= JVM Ratio); reduces to an exact integer - ;; when d divides n. Both parts must be plain digit runs (1/-1 is an - ;; invalid token); a zero denominator is the JVM's divide error. - (slash - (let ((ns (substring body 0 slash)) - (ds (substring body (+ slash 1) blen))) - (and (rdr-all-digits? ns 0 (string-length ns)) - (rdr-all-digits? ds 0 (string-length ds)) - (let ((n (string->number ns)) (d (string->number ds))) - (when (= d 0) - (jolt-throw (jolt-host-throwable "java.lang.ArithmeticException" "Divide by zero"))) - (* sign (/ n d)))))) - ;; hex 0x.. - ((and (>= blen 2) (char=? (string-ref body 0) #\0) - (or (char=? (string-ref body 1) #\x) (char=? (string-ref body 1) #\X))) - (let ((h (string->number (substring body 2 blen) 16))) - (and h (* sign h)))) - ;; radix NrDDD (Clojure 2r1010 / 16rFF / 36rZ): N in decimal, DDD in base N - ((let ((ri (or (rdr-string-index-char body #\r) (rdr-string-index-char body #\R)))) - (and ri (> ri 0) (< (+ ri 1) blen) ri)) - => (lambda (ri) - (let ((radix (string->number (substring body 0 ri)))) - (and radix (integer? radix) (>= radix 2) (<= radix 36) - (let ((v (rdr-parse-radix (substring body (+ ri 1) blen) radix))) - (and v (* sign v))))))) - ;; octal 0NNN: a leading 0 followed by octal digits (Clojure reads 042 as 34, - ;; not decimal 42). "0" alone, 0x.., 0r.. and a float "0.5" are handled - ;; elsewhere or fall through (a non-octal digit fails rdr-all-octal?). - ((and (>= blen 2) (char=? (string-ref body 0) #\0) (rdr-all-octal? body 1 blen)) - (let ((o (rdr-parse-radix (substring body 1 blen) 8))) (and o (* sign o)))) - ;; a leading zero on a plain multi-digit integer is invalid (the octal - ;; branch above accepted real octals; 08/09 match the JVM's trailing - ;; "invalid number" alternative) - ((and (>= blen 2) (char=? (string-ref body 0) #\0) (rdr-all-digits? body 1 blen)) - #f) - ;; bigint suffix N - ((and (> blen 1) (char=? (string-ref body (- blen 1)) #\N)) - (let ((n (string->number (substring body 0 (- blen 1))))) - (and n (integer? n) (* sign n)))) - ;; bigdecimal suffix M -> a :bigdec form carrying the numeric text; the back - ;; end lowers it to a runtime jbigdec. - ((and (> blen 1) (char=? (string-ref body (- blen 1)) #\M)) - (let ((n (string->number (substring body 0 (- blen 1))))) - (and n (real? n) - (rdr-make-tagged (keyword #f "bigdec") (substring tok 0 (- len 1)))))) - (else - (let ((n (string->number tok))) ; tok carries its own sign - ;; keep exactness: "42" -> exact int, "3.14"/"1e3" -> flonum. - (and (number? n) (real? n) n)))))) - -;; --- string / char literals ------------------------------------------------- -(define (rdr-hex->int s i n) ; n hex digits at i -> (values int j) - (let loop ((k 0) (acc 0) (j i)) - (if (= k n) - (values acc j) - (loop (+ k 1) (+ (* acc 16) (rdr-hexdigit (string-ref s j))) (+ j 1))))) - -(define (rdr-hexdigit c) - (cond ((and (char>=? c #\0) (char<=? c #\9)) (- (char->integer c) 48)) - ((and (char>=? c #\a) (char<=? c #\f)) (+ 10 (- (char->integer c) 97))) - ((and (char>=? c #\A) (char<=? c #\F)) (+ 10 (- (char->integer c) 65))) - (else (error 'reader "bad hex digit" c)))) - -;; opening quote already consumed; read to the closing quote, processing escapes. -(define (rdr-read-string-lit s i end) - (let loop ((i i) (acc '())) - (when (>= i end) (jolt-throw (jolt-ex-info "EOF while reading string" empty-pmap))) - (let ((c (string-ref s i))) - (cond - ((char=? c #\") (values (list->string (reverse acc)) (+ i 1))) - ((char=? c #\\) - (let ((e (string-ref s (+ i 1)))) - (case e - ((#\n) (loop (+ i 2) (cons #\newline acc))) - ((#\t) (loop (+ i 2) (cons #\tab acc))) - ((#\r) (loop (+ i 2) (cons #\return acc))) - ((#\\) (loop (+ i 2) (cons #\\ acc))) - ((#\") (loop (+ i 2) (cons #\" acc))) - ((#\b) (loop (+ i 2) (cons #\backspace acc))) - ((#\f) (loop (+ i 2) (cons #\page acc))) - ;; octal escape \ooo: 1-3 octal digits (Clojure's \0..\377), so \000 - ;; is one null char, not \0 + literal "00". - ((#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7) - (let oct ((j (+ i 1)) (val 0) (cnt 0)) - (if (and (fxinteger (string-ref s j)) 48)) (fx+ cnt 1)) - (begin - (when (> val 255) - (jolt-throw (jolt-ex-info "Octal escape sequence must be in range [0, 377]" empty-pmap))) - (loop j (cons (integer->char val) acc)))))) - ((#\u) - (let-values (((cp j) (rdr-hex->int s (+ i 2) 4))) - ;; A \u escape is a UTF-16 code unit. jolt chars are Unicode scalars, - ;; so combine a high+low surrogate pair (😃 -> U+1F603) into - ;; the one scalar char. A lone surrogate has no scalar — emit U+FFFD - ;; rather than crash (the irreducible UTF-16/scalar divergence). - (cond - ((and (fx>=? cp #xD800) (fx<=? cp #xDBFF) - (fxint s (+ j 2) 4))) - (if (and (fx>=? lo #xDC00) (fx<=? lo #xDFFF)) - (loop k (cons (integer->char - (fx+ #x10000 (fx* (fx- cp #xD800) 1024) (fx- lo #xDC00))) acc)) - (loop j (cons #\xFFFD acc))))) - ((and (fx>=? cp #xD800) (fx<=? cp #xDFFF)) (loop j (cons #\xFFFD acc))) - (else (loop j (cons (integer->char cp) acc)))))) - (else (jolt-throw (jolt-ex-info (string-append "Unsupported escape character: \\" (string e)) - empty-pmap)))))) - (else (loop (+ i 1) (cons c acc))))))) - -;; backslash already consumed; read a Clojure character literal. -(define (rdr-read-char s i end) - (when (>= i end) (jolt-throw (jolt-ex-info "EOF while reading char" empty-pmap))) - (let ((c0 (string-ref s i))) - (if (char-alphabetic? c0) - ;; named / unicode / single-letter: collect the alnum run - (let loop ((j (+ i 1))) - (if (and (< j end) - (let ((c (string-ref s j))) - (or (char-alphabetic? c) (char-numeric? c)))) - (loop (+ j 1)) - (let ((name (substring s i j))) - (if (= (string-length name) 1) - (values c0 j) - (values (rdr-named-char name) j))))) - ;; any other single char (\( \\ \; \space-as-symbol handled above) - (values c0 (+ i 1))))) - -(define (rdr-named-char name) - (cond - ((string=? name "newline") #\newline) - ((string=? name "space") #\space) - ((string=? name "tab") #\tab) - ((string=? name "return") #\return) - ((string=? name "backspace") #\backspace) - ((string=? name "formfeed") #\page) - ((char=? (string-ref name 0) #\u) - (integer->char (string->number (substring name 1 (string-length name)) 16))) - ((char=? (string-ref name 0) #\o) - (let ((v (string->number (substring name 1 (string-length name)) 8))) - (when (or (not v) (> v 255)) - (jolt-throw (jolt-ex-info "Octal escape sequence must be in range [0, 377]" empty-pmap))) - (integer->char v))) - (else (jolt-throw (jolt-ex-info (string-append "Unsupported character: \\" name) - empty-pmap))))) - -;; --- token (symbol / keyword / number / nil|true|false) --------------------- -(define (rdr-read-token s i end) - (let loop ((j i)) - (if (and (< j end) (not (rdr-terminator? (string-ref s j)))) - (loop (+ j 1)) - (values (substring s i j) j)))) - -;; split a "ns/name" token on the FIRST slash (a lone "/" is name "/") -(define (rdr-sym-parts tok) - (let ((slash (rdr-string-index-char tok #\/))) - (if (or (not slash) (= (string-length tok) 1) (= slash 0)) - (values #f tok) - (values (substring tok 0 slash) (substring tok (+ slash 1) (string-length tok)))))) - -(define (rdr-numeric-lead? tok) - (let ((len (string-length tok))) - (and (> len 0) - (let ((c0 (string-ref tok 0))) - (or (rdr-digit? c0) - (and (or (char=? c0 #\+) (char=? c0 #\-)) (> len 1) - (rdr-digit? (string-ref tok 1)))))))) -(define (rdr-invalid-token tok) - (jolt-throw (jolt-host-throwable "java.lang.RuntimeException" - (string-append "Invalid token: " tok)))) -(define (rdr-token->value tok) - (let ((n (rdr-try-number tok))) - (cond - (n n) - ;; a token that starts like a number but doesn't parse as one is an - ;; invalid number (1a, 08, 0x2g, 2r2), never a symbol — like the JVM. - ((rdr-numeric-lead? tok) - (jolt-throw (jolt-host-throwable "java.lang.NumberFormatException" - (string-append "Invalid number: " tok)))) - ((string=? tok "nil") jolt-nil) - ((string=? tok "true") #t) - ((string=? tok "false") #f) - (else - (let ((len (string-length tok))) - ;; a lone "/" is the division symbol, and "ns//" names it in a - ;; namespace (clojure.core//); otherwise a leading or trailing slash - ;; leaves an empty ns/name part — an invalid token. - (when (and (> len 1) - (or (char=? (string-ref tok 0) #\/) - (and (char=? (string-ref tok (- len 1)) #\/) - (not (and (> len 2) (char=? (string-ref tok (- len 2)) #\/)))))) - (rdr-invalid-token tok)) - (let-values (((ns name) (rdr-sym-parts tok))) (jolt-symbol ns name))))))) - -;; --- collections ------------------------------------------------------------ -;; Read forms until the close delimiter; returns (values reversed?-no list j). -(define (rdr-read-seq s i end close) - (let loop ((i i) (acc '())) - (let ((i (rdr-skip-ws s i end))) - (cond - ((>= i end) (jolt-throw (jolt-ex-info "EOF while reading" empty-pmap))) - ((char=? (string-ref s i) close) (values (reverse acc) (+ i 1))) - (else - (let-values (((form j) (rdr-read-form s i end))) - (cond - ((rdr-eof? form) (loop j acc)) ; a #_ discard or no-match #? — re-check at j - ((rdr-splice-t? form) ; #?@ — splice the matched collection's items - (loop j (append (reverse (rdr-splice-t-items form)) acc))) - (else (loop j (cons form acc)))))))))) - -;; Map literals must preserve SOURCE key order so the analyzer emits the value -;; expressions in source order (Clojure guarantees left-to-right map-literal eval). -;; A pmap is hash-ordered, so record each reader-built map's (k1 v1 k2 v2 ...) form -;; sequence in a weak side-table the host contract's form-map-pairs consults. -(define rdr-map-order (make-weak-eq-hashtable)) -(define (rdr-make-map es) - ;; the JVM reader rejects duplicate literal keys before building the map - (let dupchk ((kvs es) (seen empty-pset)) - (when (pair? kvs) - (let ((k (car kvs))) - (when (jolt-truthy? (jolt-contains? seen k)) - (jolt-throw (jolt-host-throwable "java.lang.IllegalArgumentException" - (string-append "Duplicate key: " (jolt-pr-str k))))) - (dupchk (cddr kvs) (pset-conj seen k))))) - (let ((m (apply jolt-hash-map es))) - (when (pair? es) (hashtable-set! rdr-map-order m es)) - m)) - -(define (rdr-make-set elems) - (jolt-hash-map rdr-kw-jolt-type rdr-kw-jolt-set - rdr-kw-value (apply jolt-vector elems))) - -(define (rdr-make-tagged tag form) - (jolt-hash-map rdr-kw-jolt-type rdr-kw-jolt-tagged - rdr-kw-tag tag rdr-kw-form form)) - -;; --- metadata --------------------------------------------------------------- -(define (rdr-meta-map m) - (cond - ((keyword? m) (jolt-hash-map m #t)) - ;; ^Type -> {:tag Type} with the SYMBOL (Clojure parity — core.match's - ;; array-tag and other libs look the tag up as a symbol; jolt's tag consumers - ;; tolerate a symbol). ^"Type" keeps the string. - ((symbol-t? m) (jolt-hash-map rdr-kw-tag m)) - ((string? m) (jolt-hash-map rdr-kw-tag m)) - ((pmap? m) m) - (else (jolt-hash-map rdr-kw-tag m)))) - -(define (rdr-merge-meta old new) - (if (pmap? old) - (pmap-fold-fwd new (lambda (k v acc) (jolt-assoc1 acc k v)) old) - new)) - -(define (rdr-attach-meta target meta) - (cond - ((symbol-t? target) - (make-symbol-t (symbol-t-ns target) (symbol-t-name target) - (rdr-merge-meta (symbol-t-meta target) meta))) - ;; Lists/vectors/maps/sets attach metadata to the value itself, as Clojure's - ;; reader does. Reading DATA (read-string, edn) then preserves it. A list form - ;; is code: ^Type (expr) is a compile-time hint on the FORM, read off the form - ;; for :tag and discarded at runtime (a hint on an evaluated form is dropped). - ;; A vector/map/set LITERAL keeps it as a runtime value: the analyzer re-emits a - ;; (with-meta form meta) for a meta-carrying collection literal in code, so - ;; (meta ^{:tag :int} [1 2]) / ^:foo {} still works. - (else - ;; Merge onto any metadata the target already carries (a list form picks up - ;; :line/:column first, then ^meta folds its keys on top). - (let* ((old (jolt-meta target)) - (merged (rdr-merge-meta (if (jolt-nil? old) jolt-nil old) meta)) - (c (jolt-with-meta target merged))) - ;; jolt-with-meta copies a pmap, giving it a fresh identity the rdr-map-order - ;; side-table (source key order for left-to-right map-literal eval) loses — - ;; carry the order entry over to the copy. - (let ((order (and (pmap? target) (hashtable-ref rdr-map-order target #f)))) - (when order (hashtable-set! rdr-map-order c order))) - c)))) - -;; --- source position -------------------------------------------------------- -;; List forms (code) carry 1-based :line/:column, plus :file when the compiler -;; bound rdr-source-file. read-string leaves the file unset. The analyzer reads -;; this back via jolt.host/form-position to stamp :pos on call nodes; macros and -;; (meta (read-string "(…)")) see it too. -(define rdr-source-file (make-thread-parameter #f)) -(define rdr-kw-line (keyword #f "line")) -(define rdr-kw-column (keyword #f "column")) -(define rdr-kw-file (keyword #f "file")) - -;; Forms are read left-to-right, so the indices queried are non-decreasing within -;; one source string — keep a cursor and count newlines only over the delta -;; (O(n) total, not O(n^2)). A different string or a backward index resets it. -(define rdr-pos-cursor (make-thread-parameter #f)) ; #f | (vector s i line col) -(define (rdr-line-col-at s i) - (let* ((cur (rdr-pos-cursor)) - (reuse (and (vector? cur) (eq? (vector-ref cur 0) s) - (fx<=? (vector-ref cur 1) i))) - (k0 (if reuse (vector-ref cur 1) 0)) - (l0 (if reuse (vector-ref cur 2) 1)) - (c0 (if reuse (vector-ref cur 3) 1))) - (let loop ((k k0) (line l0) (col c0)) - (if (fx>=? k i) - (begin (rdr-pos-cursor (vector s k line col)) (values line col)) - (if (char=? (string-ref s k) #\newline) - (loop (fx+ k 1) (fx+ line 1) 1) - (loop (fx+ k 1) line (fx+ col 1))))))) - -(define (rdr-pos-meta line col) - (let ((f (rdr-source-file))) - (if f - (jolt-hash-map rdr-kw-line line rdr-kw-column col rdr-kw-file f) - (jolt-hash-map rdr-kw-line line rdr-kw-column col)))) - -(define (rdr-attach-pos lst line col) - (if (empty-list-t? lst) ; () is interned, can't carry meta (= Clojure) - lst - (rdr-attach-meta lst (rdr-pos-meta line col)))) - -;; --- # dispatch ------------------------------------------------------------- -;; #(...) anonymous fn shorthand: % -> p1, %N -> pN, %& -> rest. The -;; fixed arity is the MAX positional used (Clojure: #(do %2 %&) -> [p1 p2 & rest]). -;; Param names carry a trailing "#" so a #() inside a syntax-quote still reads them -;; as auto-gensyms. -(define rdr-anon-counter 0) -(define (rdr-anon-gensym) - (set! rdr-anon-counter (+ rdr-anon-counter 1)) - (jolt-symbol #f (string-append "p__" (number->string rdr-anon-counter) "#"))) -(define (rdr-pct-index nm) ; % ->1, %& ->'rest, %N ->N, else #f - (cond ((string=? nm "%") 1) - ((string=? nm "%&") 'rest) - ((and (> (string-length nm) 1) (char=? (string-ref nm 0) #\%)) - (let ((n (string->number (substring nm 1 (string-length nm))))) - (if (and n (integer? n) (>= n 1)) n #f))) - (else #f))) -(define (rdr-anon-set? f) (and (pmap? f) (eq? (jolt-get f rdr-kw-jolt-type) rdr-kw-jolt-set))) -(define (rdr-anon-scan f max-box rest-box) - (cond - ((symbol-t? f) - (let ((idx (rdr-pct-index (symbol-t-name f)))) - (cond ((eq? idx 'rest) (set-box! rest-box #t)) - ((and idx (> idx (unbox max-box))) (set-box! max-box idx))))) - ((or (pvec? f) (cseq? f) (empty-list-t? f)) - (for-each (lambda (x) (rdr-anon-scan x max-box rest-box)) (seq->list f))) - ((rdr-anon-set? f) - (for-each (lambda (x) (rdr-anon-scan x max-box rest-box)) (seq->list (jolt-get f rdr-kw-value)))) - ((pmap? f) - (for-each (lambda (x) (rdr-anon-scan x max-box rest-box)) (or (hashtable-ref rdr-map-order f #f) '()))))) -(define (rdr-anon-replace f slots rest-sym) - (cond - ((symbol-t? f) - (let ((idx (rdr-pct-index (symbol-t-name f)))) - (cond ((eq? idx 'rest) rest-sym) (idx (vector-ref slots (- idx 1))) (else f)))) - ((pvec? f) (apply jolt-vector (map (lambda (x) (rdr-anon-replace x slots rest-sym)) (seq->list f)))) - ((or (cseq? f) (empty-list-t? f)) - (apply jolt-list (map (lambda (x) (rdr-anon-replace x slots rest-sym)) (seq->list f)))) - ((rdr-anon-set? f) - (rdr-make-set (map (lambda (x) (rdr-anon-replace x slots rest-sym)) (seq->list (jolt-get f rdr-kw-value))))) - ((pmap? f) - (let ((kv (hashtable-ref rdr-map-order f #f))) - (if kv (rdr-make-map (map (lambda (x) (rdr-anon-replace x slots rest-sym)) kv)) f))) - (else f))) -(define (rdr-read-anon-fn s i end) ; i at the '(' after '#' - (let-values (((form j) (rdr-read-form s i end))) - (let ((max-box (box 0)) (rest-box (box #f))) - (rdr-anon-scan form max-box rest-box) - (let* ((n (unbox max-box)) - (slots (make-vector n))) - (let loop ((k 0)) (when (< k n) (vector-set! slots k (rdr-anon-gensym)) (loop (+ k 1)))) - (let* ((rest-sym (if (unbox rest-box) (rdr-anon-gensym) #f)) - (body (rdr-anon-replace form slots rest-sym)) - (params (append (vector->list slots) - (if rest-sym (list (jolt-symbol #f "&") rest-sym) '())))) - (values (jolt-list (jolt-symbol #f "fn*") (apply jolt-vector params) body) j)))))) - -;; reader conditionals: jolt's feature set is {:jolt :clj :default}; -;; the FIRST clause whose feature key is in the set wins (clause order, like -;; Clojure). jolt is a Clojure/JVM-compatible host — it emulates clojure.lang.* -;; and java.* interop — so it reads the :clj branch of a .cljc library (the JVM -;; code path its host shims target), not the :cljs one. A library can still -;; override with a :jolt-specific branch (place it before :clj). -(define rdr-features '("jolt" "clj" "default")) -(define (rdr-feature? kw) - (and (keyword? kw) (jolt-nil? (let ((n (keyword-t-ns kw))) (if n n jolt-nil))) - (and (member (keyword-t-name kw) rdr-features) #t))) -(define (rdr-read-reader-cond s i end) ; i is past the '?' - (let* ((splice (and (< i end) (char=? (string-ref s i) #\@))) - (start (if splice (+ i 1) i))) - (let-values (((form j) (rdr-read-form s start end))) - (when (rdr-eof? form) (jolt-throw (jolt-ex-info "EOF after #?" empty-pmap))) - (let ((items (cond ((pvec? form) (seq->list form)) - ((or (cseq? form) (empty-list-t? form)) (seq->list form)) - (else '())))) - (let loop ((xs items)) - (cond ((or (null? xs) (null? (cdr xs))) (values rdr-eof j)) ; no match -> discard - ((rdr-feature? (car xs)) - (if splice - ;; #?@ — the matched value is a collection whose ITEMS splice - ;; into the enclosing sequence (read-seq expands the wrapper). - (let ((v (cadr xs))) - (values (make-rdr-splice-t - (cond ((pvec? v) (seq->list v)) - ((or (cseq? v) (empty-list-t? v)) (seq->list v)) - (else (list v)))) - j)) - (values (cadr xs) j))) - (else (loop (cddr xs))))))))) - -(define (rdr-string-rindex-char str c) - (let loop ((i (- (string-length str) 1))) - (cond ((< i 0) #f) ((char=? (string-ref str i) c) i) (else (loop (- i 1)))))) - -;; A record/type literal tag (#ns.Type{..} / #ns.Type[..]) is any tag containing -;; a dot — Clojure routes those to a constructor instead of a data reader. -(define (rdr-record-tag? tok) (and (rdr-string-rindex-char tok #\.) #t)) - -;; #a.b.C{..} -> (a.b/map->C {..}); #a.b.C[..] -> (a.b/->C ..). The factory call -;; compiles like any invoke; defrecord interns map->C/->C in the type's ns. -(define (rdr-record-ctor-form tok form) - (let* ((di (rdr-string-rindex-char tok #\.)) - (ns (substring tok 0 di)) - (simple (substring tok (+ di 1) (string-length tok)))) - (cond - ((pmap? form) - (jolt-list (jolt-symbol ns (string-append "map->" simple)) form)) - ((pvec? form) - (apply jolt-list (jolt-symbol ns (string-append "->" simple)) - (vector->list (pvec-v form)))) - (else (jolt-throw (jolt-ex-info - (string-append "Unreadable constructor form: #" tok) - empty-pmap)))))) - -;; #:ns{…} namespaced map literal: a bare keyword/symbol key gets `ns`, a `:_/x` -;; key is un-namespaced, an already-qualified key stays. #::{…} uses the current -;; ns; #::alias{…} resolves the alias. -(define (rdr-nsmap-key mapns k) - (cond - ((keyword? k) - (let ((kns (keyword-t-ns k)) (kn (keyword-t-name k))) - (cond ((and (string? kns) (string=? kns "_")) (keyword #f kn)) - (kns k) - (else (keyword mapns kn))))) - ((symbol-t? k) - (let ((kns (symbol-t-ns k)) (kn (symbol-t-name k))) - (cond ((and (string? kns) (string=? kns "_")) (jolt-symbol #f kn)) - (kns k) - (else (jolt-symbol mapns kn))))) - (else k))) -(define (rdr-nsmap-kvs mapns es) - (cond ((null? es) '()) - ((null? (cdr es)) es) - (else (cons (rdr-nsmap-key mapns (car es)) - (cons (cadr es) (rdr-nsmap-kvs mapns (cddr es))))))) -(define (rdr-read-ns-map s i end) ; i points just past "#:" - (let* ((auto? (and (< i end) (char=? (string-ref s i) #\:))) - (i2 (if auto? (+ i 1) i))) - (let loop ((j i2)) - (cond - ((>= j end) (jolt-throw (jolt-ex-info "EOF in namespaced map literal" empty-pmap))) - ((char=? (string-ref s j) #\{) - (let* ((nstok (substring s i2 j)) - (mapns (if auto? - (if (string=? nstok "") (chez-current-ns) - (let ((a (chez-resolve-alias (chez-current-ns) nstok))) (if a a nstok))) - nstok))) - (let-values (((es k) (rdr-read-seq s (+ j 1) end #\}))) - (values (rdr-make-map (rdr-nsmap-kvs mapns es)) k)))) - (else (loop (+ j 1))))))) - -(define (rdr-read-dispatch s i end) ; i points just past the '#' - (when (>= i end) (jolt-throw (jolt-ex-info "EOF after #" empty-pmap))) - (let ((c (string-ref s i))) - (cond - ((char=? c #\{) ; #{...} set - (let-values (((elems j) (rdr-read-seq s (+ i 1) end #\}))) - (values (rdr-make-set elems) j))) - ((char=? c #\() ; #(...) anonymous fn shorthand - (rdr-read-anon-fn s i end)) - ((char=? c #\") ; #"..." -> a regex VALUE (Clojure parity: - ;; the reader constructs the Pattern, so a macro gets a regex, not a form). - ;; The analyzer compiles a regex value to the same :regex IR leaf via its - ;; source string. - (let-values (((src j) (rdr-read-regex s (+ i 1) end))) - (values (jolt-re-pattern src) j))) - ((char=? c #\_) ; #_ discard the next form - (let-values (((d j) (rdr-read-form s (+ i 1) end))) - (when (rdr-eof? d) (jolt-throw (jolt-ex-info "EOF after #_" empty-pmap))) - ;; edn validates the discarded element (its tags go through the same - ;; :readers/:default pipeline; an unreadable one throws) - (let ((cb (rdr-discard-cb))) - (when cb (jolt-invoke cb d))) - (rdr-read-form s j end))) - ((char=? c #\') ; #'x var-quote -> (var x) - (let-values (((form j) (rdr-read-form s (+ i 1) end))) - (values (jolt-list (jolt-symbol #f "var") form) j))) - ((char=? c #\^) ; #^meta — deprecated metadata syntax = ^meta - (let-values (((mform j) (rdr-read-form s (+ i 1) end))) - (let-values (((target k) (rdr-read-form s j end))) - (when (rdr-eof? target) - (jolt-throw (jolt-ex-info "EOF after #^meta" empty-pmap))) - (values (rdr-attach-meta target (rdr-meta-map mform)) k)))) - ((char=? c #\#) ; ## symbolic value: ##Inf / ##-Inf / ##NaN - (let-values (((tok j) (rdr-read-token s (+ i 1) end))) - (values (cond ((string=? tok "Inf") +inf.0) - ((string=? tok "-Inf") -inf.0) - ((string=? tok "NaN") +nan.0) - (else (jolt-throw (jolt-ex-info (string-append "unknown ## literal: " tok) - empty-pmap)))) - j))) - ((char=? c #\?) ; #?(...) / #?@(...) reader conditional - (rdr-read-reader-cond s (+ i 1) end)) - ((char=? c #\:) ; #:ns{...} namespaced map literal - (rdr-read-ns-map s (+ i 1) end)) - (else ; #tag form -> tagged {:tag :#tag :form ...} - (let-values (((tok j) (rdr-read-token s i end))) - (let-values (((form k) (rdr-read-form s j end))) - (when (rdr-eof? form) (jolt-throw (jolt-ex-info "EOF after #tag" empty-pmap))) - (if (rdr-record-tag? tok) ; #ns.Type{..}/[..] record literal - (values (rdr-record-ctor-form tok form) k) - (values (rdr-make-tagged (keyword #f (string-append "#" tok)) form) k)))))))) - -;; regex literal source: raw chars to the closing quote; \" is an escaped quote, -;; every other backslash sequence is kept verbatim (regex engine semantics). -(define (rdr-read-regex s i end) - (let loop ((i i) (acc '())) - (when (>= i end) (jolt-throw (jolt-ex-info "EOF while reading regex" empty-pmap))) - (let ((c (string-ref s i))) - (cond - ((char=? c #\") (values (list->string (reverse acc)) (+ i 1))) - ((and (char=? c #\\) (< (+ i 1) end) (char=? (string-ref s (+ i 1)) #\")) - (loop (+ i 2) (cons #\" acc))) - ((char=? c #\\) - (loop (+ i 2) (cons (string-ref s (+ i 1)) (cons #\\ acc)))) - (else (loop (+ i 1) (cons c acc))))))) - -;; --- keyword ---------------------------------------------------------------- -(define (rdr-read-keyword s i end) ; i points just past the leading ':' - ;; ::kw is auto-resolved against the current ns: ::name -> current-ns/name, - ;; ::alias/name -> the alias's target ns / name (Clojure's reader semantics). - (let ((auto? (and (< i end) (char=? (string-ref s i) #\:)))) - (let ((i (if auto? (+ i 1) i))) - (let-values (((tok j) (rdr-read-token s i end))) - (let ((len (string-length tok))) - ;; ":" and "::" alone, a leading or trailing slash (a name of exactly - ;; "/" is fine, :ns//), or an auto-resolved keyword in edn (no - ;; resolution context) are invalid tokens. - (when (or (= len 0) - (and (> len 1) (char=? (string-ref tok 0) #\/)) - (and (> len 1) (char=? (string-ref tok (- len 1)) #\/) - (not (and (> len 2) (char=? (string-ref tok (- len 2)) #\/))))) - (rdr-invalid-token (string-append (if auto? "::" ":") tok))) - (when (and auto? (rdr-edn-mode)) - (rdr-invalid-token (string-append "::" tok)))) - (let-values (((ns name) (rdr-sym-parts tok))) - (if auto? - (let* ((cur (chez-current-ns)) - (rns (if (string? ns) - (let ((a (chez-resolve-alias cur ns))) (if a a ns)) - cur))) - (values (keyword rns name) j)) - (values (keyword ns name) j))))))) - -;; --- the main dispatch ------------------------------------------------------ -;; Returns (values form j). form is rdr-eof at end-of-input or at an unconsumed -;; close delimiter (read-seq consumes the close itself). -(define (rdr-read-form s i end) - (let ((i (rdr-skip-ws s i end))) - (if (>= i end) - (values rdr-eof i) - (let ((c (string-ref s i))) - (cond - ((char=? c #\() (let-values (((line col) (rdr-line-col-at s i))) - (let-values (((es j) (rdr-read-seq s (+ i 1) end #\)))) - (values (rdr-attach-pos (apply jolt-list es) line col) j)))) - ((char=? c #\[) (let-values (((es j) (rdr-read-seq s (+ i 1) end #\]))) - (values (apply jolt-vector es) j))) - ((char=? c #\{) (let-values (((es j) (rdr-read-seq s (+ i 1) end #\}))) - (values (rdr-make-map es) j))) - ((or (char=? c #\)) (char=? c #\]) (char=? c #\})) - (values rdr-eof i)) ; unconsumed close — read-seq handles it - ((char=? c #\") (rdr-read-string-lit s (+ i 1) end)) - ((char=? c #\\) (rdr-read-char s (+ i 1) end)) - ((char=? c #\:) (rdr-read-keyword s (+ i 1) end)) - ((char=? c #\#) (rdr-read-dispatch s (+ i 1) end)) - ((char=? c #\') (rdr-wrap s (+ i 1) end (jolt-symbol #f "quote"))) - ;; syntax-quote of a self-evaluating literal collapses to the literal at - ;; READ time (Clojure's reader), so nested backticks over a literal are - ;; inert: ``42 reads as 42, ```"meow" as "meow". - ((char=? c #\`) - (let-values (((form j) (rdr-read-form s (+ i 1) end))) - (when (rdr-eof? form) (jolt-throw (jolt-ex-info "EOF after `" empty-pmap))) - (values (if (rdr-self-eval-literal? form) - form - (jolt-list (jolt-symbol #f "syntax-quote") form)) - j))) - ((char=? c #\@) (rdr-wrap s (+ i 1) end (jolt-symbol "clojure.core" "deref"))) - ;; ~ / ~@ read as clojure.core/unquote(-splicing), like the JVM reader — - ;; so code that inspects pattern/template data (core.logic's defne) sees - ;; the qualified symbol it expects. - ((char=? c #\~) - (if (and (< (+ i 1) end) (char=? (string-ref s (+ i 1)) #\@)) - (rdr-wrap s (+ i 2) end (jolt-symbol "clojure.core" "unquote-splicing")) - (rdr-wrap s (+ i 1) end (jolt-symbol "clojure.core" "unquote")))) - ((char=? c #\^) - (let-values (((mform j) (rdr-read-form s (+ i 1) end))) - (let-values (((target k) (rdr-read-form s j end))) - (when (rdr-eof? target) - (jolt-throw (jolt-ex-info "EOF after ^meta" empty-pmap))) - (values (rdr-attach-meta target (rdr-meta-map mform)) k)))) - (else - (let-values (((tok j) (rdr-read-token s i end))) - (values (rdr-token->value tok) j)))))))) - -;; wrap the next form in a 2-element list (READER-MACRO form) -;; self-evaluating literals (NOT symbols/collections) — syntax-quote passes these -;; through unchanged, collapsed at read time. -(define (rdr-self-eval-literal? x) - (or (jolt-nil? x) (boolean? x) (number? x) (string? x) (keyword? x) (char? x))) - -(define (rdr-wrap s i end head) - (let-values (((form j) (rdr-read-form s i end))) - (when (rdr-eof? form) - (jolt-throw (jolt-ex-info "EOF while reading reader macro" empty-pmap))) - (values (jolt-list head form) j))) - -;; --- form -> data ----------------------------------------------------------- -;; read-string/read return DATA, so set literal FORMS ({:jolt/type :jolt/set -;; :value [...]}) become real sets, recursing through maps/vectors/lists. The -;; COMPILER reads via rdr-read-form and keeps the set FORM (the analyzer lowers -;; it), so this conversion runs only on the data seams. Structural sharing keeps -;; identity (and the rdr-map-order entry + metadata) for any branch with no set. -(define (rdr-set-form? x) - (and (pmap? x) (eq? (jolt-get x rdr-kw-jolt-type) rdr-kw-jolt-set) - (not (jolt-nil? (jolt-get x rdr-kw-value))))) - -(define (rdr-conv-each xs) ; (values converted-list changed?) - (let loop ((xs xs) (acc '()) (changed #f)) - (if (null? xs) - (values (reverse acc) changed) - (let ((c (rdr-form->data (car xs)))) - (loop (cdr xs) (cons c acc) (or changed (not (eq? c (car xs))))))))) - -;; carry the reader metadata, converting its nested forms too — a set/tagged -;; literal inside a ^{…} map (^{:k #{…}}) must become a value like the rest of -;; the data, not stay the tagged set-form. -(define (rdr-carry-meta src dst) - (let ((m (jolt-meta src))) (if (jolt-nil? m) dst (jolt-with-meta dst (rdr-form->data m))))) - -;; tag keyword (:#time/date) -> its *data-readers* reader fn, or #f. The fn's -;; namespace must already be loaded (the loader requires them when a project's -;; data_readers.{clj,cljc} registers a tag). -(define (rdr-data-reader-fn tag) - (and (keyword? tag) - (let ((nm (keyword-t-name tag))) - (and (> (string-length nm) 0) (char=? (string-ref nm 0) #\#) - (let* ((bare (substring nm 1 (string-length nm))) - (slash (let loop ((i 0)) - (cond ((>= i (string-length bare)) #f) - ((char=? (string-ref bare i) #\/) i) - (else (loop (+ i 1)))))) - (sym (if slash - (jolt-symbol (substring bare 0 slash) (substring bare (+ slash 1) (string-length bare))) - (jolt-symbol #f bare))) - (dr (var-deref "clojure.core" "*data-readers*")) - (v (and (pmap? dr) (jolt-get dr sym)))) - (and v (not (jolt-nil? v)) (symbol-t? v) (not (jolt-nil? (symbol-t-ns v))) - (guard (e (#t #f)) - (let ((fn (var-deref (symbol-t-ns v) (symbol-t-name v)))) - (and (procedure? fn) fn))))))))) -;; the bare tag SYMBOL for a :#name / :#ns/name reader keyword (strip the leading -;; #, split a qualified tag on /). *default-data-reader-fn* receives it. -(define (rdr-tag->symbol tag) - (let* ((nm (keyword-t-name tag)) - (bare (if (and (> (string-length nm) 0) (char=? (string-ref nm 0) #\#)) - (substring nm 1 (string-length nm)) nm))) - (let loop ((i 0)) - (cond ((>= i (string-length bare)) (jolt-symbol #f bare)) - ((char=? (string-ref bare i) #\/) - (jolt-symbol (substring bare 0 i) (substring bare (+ i 1) (string-length bare)))) - (else (loop (+ i 1))))))) -;; *default-data-reader-fn* — a (fn [tag value]) consulted for an unregistered -;; tag, or #f when unset/nil. Honors a `binding` (var-deref reads the stack). -(define (rdr-default-data-reader-fn) - (guard (e (#t #f)) - (let ((v (var-deref "clojure.core" "*default-data-reader-fn*"))) - (and (not (jolt-nil? v)) (procedure? v) v)))) - -;; strict #inst validation: RFC-3339 calendar fields must be real (month 1-12, -;; day valid for the month incl. leap years, hour < 24, minute/second < 60). -(define (rdr-2dig s i) - (and (< (+ i 1) (string-length s)) - (rdr-digit? (string-ref s i)) (rdr-digit? (string-ref s (+ i 1))) - (+ (* 10 (- (char->integer (string-ref s i)) 48)) - (- (char->integer (string-ref s (+ i 1))) 48)))) -(define (rdr-leap? y) (and (= 0 (modulo y 4)) (or (not (= 0 (modulo y 100))) (= 0 (modulo y 400))))) -(define (rdr-inst-throw s) - (jolt-throw (jolt-host-throwable "java.lang.RuntimeException" - (string-append "Unrecognized date/time syntax: " s)))) -(define (rdr-validate-inst! s) - ;; progressive RFC-3339 like clojure.instant: yyyy[-MM[-dd[Thh[:mm[:ss[.f]]]]]] - ;; with an optional Z/±hh:mm offset; each present field must be in range - ;; (months 1-12, day valid for the month incl. leap years, hour < 24, min < 60). - (let* ((len (string-length s)) - (y (and (>= len 4) (rdr-all-digits? s 0 4) (string->number (substring s 0 4))))) - (unless y (rdr-inst-throw s)) - (when (>= len 5) - (unless (char=? (string-ref s 4) #\-) (rdr-inst-throw s)) - (let ((mo (rdr-2dig s 5))) - (unless (and mo (>= mo 1) (<= mo 12)) (rdr-inst-throw s)) - (when (>= len 8) - (unless (char=? (string-ref s 7) #\-) (rdr-inst-throw s)) - (let ((d (rdr-2dig s 8))) - (unless (and d (>= d 1) - (<= d (vector-ref (if (rdr-leap? y) - '#(31 29 31 30 31 30 31 31 30 31 30 31) - '#(31 28 31 30 31 30 31 31 30 31 30 31)) - (- mo 1)))) - (rdr-inst-throw s)) - (when (>= len 11) - (unless (char=? (string-ref s 10) #\T) (rdr-inst-throw s)) - (let ((h (rdr-2dig s 11))) - (unless (and h (<= h 23)) (rdr-inst-throw s)) - (when (>= len 14) - (when (char=? (string-ref s 13) #\:) - (let ((mi (rdr-2dig s 14))) - (unless (and mi (<= mi 59)) (rdr-inst-throw s))))))))))))) -;; strict #uuid: canonical 8-4-4-4-12 hex groups. -(define (rdr-validate-uuid! s) - (define (hexrun? from to) - (let loop ((i from)) - (cond ((>= i to) #t) - ((let ((c (char-downcase (string-ref s i)))) - (or (rdr-digit? c) (and (char>=? c #\a) (char<=? c #\f)))) - (loop (+ i 1))) - (else #f)))) - (unless (and (= (string-length s) 36) - (char=? (string-ref s 8) #\-) (char=? (string-ref s 13) #\-) - (char=? (string-ref s 18) #\-) (char=? (string-ref s 23) #\-) - (hexrun? 0 8) (hexrun? 9 13) (hexrun? 14 18) (hexrun? 19 23) (hexrun? 24 36)) - (jolt-throw (jolt-host-throwable "java.lang.IllegalArgumentException" - (string-append "Invalid UUID string: " s))))) - -;; read-string / read data seam: construct the value for a #tag literal. #inst, -;; #uuid and #"regex" are built in; any other tag is applied from *data-readers*, -;; then *default-data-reader-fn*. An unregistered tag with no default handler stays -;; a tagged FORM (lenient — clojure.edn raises instead). -(define (rdr-construct-tag tag inner) - (cond - ((eq? tag (keyword #f "#inst")) - (when (string? inner) (rdr-validate-inst! inner)) - (jolt-inst-from-string inner)) - ((eq? tag (keyword #f "#uuid")) - (when (string? inner) (rdr-validate-uuid! inner)) - (jolt-uuid-from-string inner)) - ((eq? tag (keyword #f "regex")) (jolt-re-pattern inner)) - ;; the M-literal form: construct the BigDecimal from its numeric text - ((eq? tag (keyword #f "bigdec")) (jolt-bigdec-from-string inner)) - (else (let ((fn (rdr-data-reader-fn tag))) - (if fn (jolt-invoke fn inner) - (let ((dfn (rdr-default-data-reader-fn))) - (if dfn (jolt-invoke dfn (rdr-tag->symbol tag) inner) - ;; no reader for the tag: a proper tagged-literal value, like - ;; Clojure's *default-data-reader-fn* (tagged-literal), so - ;; tagged-literal? / :tag / :form / printing all work — not the - ;; internal reader form. clojure.edn reads raw forms via - ;; __read-form-raw, so its :readers/:default path is unaffected. - (jolt-tagged-literal (rdr-tag->symbol tag) inner)))))))) - -;; rdr-form->data*: convert the VALUE structure (set/tagged/nested forms). The -;; wrapper below adds the metadata, so the unchanged branches return x bare. -(define (rdr-form->data* x) - (cond - ((and (pmap? x) (eq? (jolt-get x rdr-kw-jolt-type) rdr-kw-jolt-tagged)) - (rdr-construct-tag (jolt-get x rdr-kw-tag) (rdr-form->data (jolt-get x rdr-kw-form)))) - ((rdr-set-form? x) - (let ((items (jolt-get x rdr-kw-value))) - (let loop ((i 0) (s empty-pset)) - (if (fx>=? i (pvec-count items)) s - (let ((v (rdr-form->data (pvec-nth-d items i jolt-nil)))) - (when (jolt-truthy? (jolt-contains? s v)) - (jolt-throw (jolt-host-throwable "java.lang.IllegalArgumentException" - (string-append "Duplicate key: " (jolt-pr-str v))))) - (loop (fx+ i 1) (pset-conj s v))))))) - ((pvec? x) - (let-values (((items changed) (rdr-conv-each (vector->list (pvec-v x))))) - (if changed (apply jolt-vector items) x))) - ((pmap? x) - (let ((order (hashtable-ref rdr-map-order x #f))) - (if order - (let-values (((kvs changed) (rdr-conv-each order))) - (if changed (rdr-make-map kvs) x)) - (let-values (((kvs changed) - (rdr-conv-each (pmap-fold x (lambda (k v a) (cons k (cons v a))) '())))) - (if changed (apply jolt-hash-map kvs) x))))) - ((cseq? x) - (let-values (((items changed) (rdr-conv-each (seq->list x)))) - (if changed (apply jolt-list items) x))) - (else x))) -;; Read DATA always carries metadata, converting its nested forms too — Clojure's -;; reader reads a ^{…} map with the same read() as any value, so a set/tagged -;; literal in metadata is a value, not a form. Carry it whether or not the value -;; itself changed (a set-form in the metadata of an otherwise-unchanged value). -(define (rdr-form->data x) - (let ((v (rdr-form->data* x)) (m (jolt-meta x))) - (if (jolt-nil? m) v (jolt-with-meta v (rdr-form->data m))))) - -;; --- the two host seams ----------------------------------------------------- -;; a top-level read: a stray close delimiter is unmatched (read-seq consumes the -;; close of an open collection; anything reaching here is unbalanced input). -(define (rdr-read-top s i end) - (let ((k (rdr-skip-ws s i end))) - (when (and (< k end) - (let ((c (string-ref s k))) - (or (char=? c #\)) (char=? c #\]) (char=? c #\})))) - (jolt-throw (jolt-ex-info (string-append "Unmatched delimiter: " - (string (string-ref s k))) - empty-pmap))) - (rdr-read-form s k end))) - -;; clojure.core/read-string: first form, or nil for blank / comment-only input -;; (parse-string wart, matched deliberately). jolt-read-form-raw keeps set FORMS -;; for the compiler spine (compile-eval); the data seam converts them to sets. -(define (jolt-read-form-raw s) - (let-values (((form j) (rdr-read-top s 0 (string-length s)))) - (if (rdr-eof? form) jolt-nil form))) - -;; the edn seam: strict mode (no auto-resolved keywords), each #_ discard handed -;; to the callback for tag validation, and a distinct EOF sentinel so the edn -;; layer can honor its :eof option (nil input is a plain EOF). -(define (jolt-read-form-edn s cb) - (if (jolt-nil? s) - (keyword "jolt" "reader-eof") - (parameterize ((rdr-edn-mode #t) - (rdr-discard-cb (if (jolt-nil? cb) #f cb))) - (let-values (((form j) (rdr-read-top s 0 (string-length s)))) - (if (rdr-eof? form) (keyword "jolt" "reader-eof") form))))) -(define (jolt-read-string s) - (let ((form (jolt-read-form-raw s))) - (if (jolt-nil? form) form (rdr-form->data form)))) - -;; __parse-next: [form rest-of-string] or nil when only whitespace/comments left. -(define (jolt-parse-next s) - (let ((end (string-length s))) - (let-values (((form j) (rdr-read-top s 0 end))) - (if (rdr-eof? form) - jolt-nil - (jolt-vector (rdr-form->data form) (substring s j end)))))) - -;; __read-tagged: apply a built-in data reader to an already-read form. The tag -;; is the :#name keyword the reader produced; #uuid/#inst reuse the inst-time ctors. -(define (jolt-read-tagged tag form) - (cond - ((eq? tag (keyword #f "#uuid")) - (when (string? form) (rdr-validate-uuid! form)) - (jolt-uuid-from-string form)) - ((eq? tag (keyword #f "#inst")) - (when (string? form) (rdr-validate-inst! form)) - (jolt-inst-from-string form)) - ((eq? tag (keyword #f "bigdec")) (jolt-bigdec-from-string form)) - ;; No registered reader: consult *default-data-reader-fn*, else throw a clean, - ;; catchable ex-info naming the tag, like the JVM's "No reader function for tag - ;; foobar" (empty-pmap is a VALUE — the old (empty-pmap) applied it as a - ;; procedure and crashed the Chez VM). - (else (let ((dfn (rdr-default-data-reader-fn))) - (if dfn (jolt-invoke dfn (rdr-tag->symbol tag) form) - (let* ((nm (keyword-t-name tag)) - (bare (if (and (> (string-length nm) 0) (char=? (string-ref nm 0) #\#)) - (substring nm 1 (string-length nm)) nm))) - (jolt-throw (jolt-ex-info (string-append "No reader function for tag " bare) empty-pmap)))))))) - -(def-var! "clojure.core" "read-string" jolt-read-string) -(def-var! "clojure.core" "__parse-next" jolt-parse-next) -(def-var! "clojure.core" "__read-tagged" jolt-read-tagged) -;; __read-form-raw: the read form WITHOUT building values — set/tagged literals -;; stay FORMS. clojure.edn reads this so it applies a #tag through its :readers/ -;; :default (a #inst can be overridden to defer), rather than read-string building -;; the built-in #inst eagerly (which fails on a non-string like #inst ^:ref […]). -(def-var! "clojure.core" "__read-form-raw" jolt-read-form-raw) -(def-var! "clojure.core" "__read-form-edn" jolt-read-form-edn) diff --git a/host/chez/records.ss b/host/chez/records.ss deleted file mode 100644 index 806e9f8..0000000 --- a/host/chez/records.ss +++ /dev/null @@ -1,1100 +0,0 @@ -;; records + protocols — the deftype/defrecord + defprotocol/extend-type -;; subsystem. -;; -;; A record is a `jrec`: a shared per-type descriptor + a flat vector of field -;; values in declared order, plus an extension map for any non-field keys assoc'd -;; on (jolt-nil when there are none — the common case). This lays fields out like a -;; native struct: construction allocates one vector, not a chain of cons cells, and -;; a field read is an index lookup, not a list scan. It is map?/coll?, equal to -;; another jrec of the same type with equal fields (never equal to a plain map), -;; and prints as #ns.Name{...}. -;; The collection dispatchers (jolt-get/count/keys/vals/seq/assoc/contains?/=/ -;; hash/conj + the printers) are set!-extended with a jrec arm that delegates to -;; the original — the transients.ss pattern — so all record logic lives here and -;; the hot collection paths are untouched. (get r :jolt/deftype) returns the tag, -;; so the overlay record? predicate works unchanged. -;; -;; Loaded after collections/seq/values/converters/printing/transients/multimethods -;; (the dispatchers it wraps + chez-current-ns). - -;; The per-type descriptor: built once at deftype/defrecord definition and shared -;; by every instance. Holds the tag, the field keywords in declared order, and an -;; eq?-keyed keyword->index table (field keys are interned, so identity lookup). -(define-record-type (jrdesc make-jrdesc-rec jrdesc?) - (fields tag fkeys index) (nongenerative chez-jrdesc-v1)) -(define (make-jrdesc tag fkey-list) - (let ((index (make-eq-hashtable))) - (let loop ((ks fkey-list) (i 0)) - (unless (null? ks) (hashtable-set! index (car ks) i) (loop (cdr ks) (+ i 1)))) - (make-jrdesc-rec tag (list->vector fkey-list) index))) -;; An instance: the shared descriptor, the field-value vector, and an extension -;; map (jolt-nil unless non-field keys have been assoc'd on). -(define-record-type (jrec make-jrec jrec?) (fields desc vals ext) (nongenerative chez-jrec-v2)) -(define (jrec-tag r) (jrdesc-tag (jrec-desc r))) - -;; defrecord vs deftype: a defrecord IS a map (map?/seq/keys/assoc over its -;; fields); a bare deftype is an opaque object with only its declared interfaces, -;; never a map (Clojure semantics). defrecord registers its type tag here; the -;; default jrec-as-map behaviour (map?/record?/field-seq) is gated on it, while -;; method dispatch (a deftype implementing ISeq/Counted/…) stays open to any jrec. -(define chez-record-type-tbl (make-hashtable string-hash string=?)) -(define (jrec-record? x) (and (jrec? x) (hashtable-ref chez-record-type-tbl (jrec-tag x) #f) #t)) -;; every deftype/defrecord tag, and a simple-name -> tag index. An extend-protocol -;; in a DIFFERENT ns names the type bare (it is :import-ed), so register-method -;; resolves "Raw" to its real tag "a.util.Raw" here instead of prepending the -;; calling ns. The local ns is preferred, so a same-named local type still wins. -(define chez-deftype-tag-set (make-hashtable string-hash string=?)) -;; ctor procedure -> its class tag: the type NAME var holds the ctor (a jolt-ism; -;; the JVM resolves it to the class), so class-key maps the ctor back to the -;; class for (ancestors TypeName) / (isa? x TypeName) / derive on the type. -(define chez-deftype-ctor-tag (make-weak-eq-hashtable)) -(define chez-simple-name-tag (make-hashtable string-hash string=?)) -;; a jrec that is coll? — a record, or a deftype implementing a collection -;; interface (its seq/count/nth/valAt/cons method is registered). find-method-any- -;; protocol is defined later; resolved at call time. An opaque deftype is not coll?. -(define (jrec-collection? x) - (and (jrec? x) - (or (jrec-record? x) - (let ((tag (jrec-tag x))) - ;; coll? is instance? IPersistentCollection — its marker is `cons` - ;; (and ISeq's `first`). ILookup(valAt) / Indexed(nth) / Counted(count) - ;; / Seqable(seq) alone do NOT make a value coll?, matching the JVM - ;; (e.g. core.logic's LVar implements only valAt and is not coll?). - (or (find-method-any-protocol tag "cons") - (find-method-any-protocol tag "first")))) - #t)) -;; a jrec that is map? — a record, or a deftype implementing clojure.lang -;; .IPersistentMap (clojure.core.cache's caches do). `without` (dissoc) is the -;; map-distinctive method: vectors/sets implement Associative/ILookup but not it. -(define (jrec-maplike? x) - (and (jrec? x) - (or (jrec-record? x) - (find-method-any-protocol (jrec-tag x) "without")) - #t)) -(define jolt-deftype-kw (keyword "jolt" "deftype")) -;; unique present-vs-absent sentinel for extension-map lookups (so a present nil -;; in the extension map is distinguished from a genuine miss). -(define jrec-absent (list 'jrec-absent)) - -;; --- whole-program inference registries ------------------------------------- -;; Populated at definition/load time (deftype/defrecord and defprotocol forms run -;; before `jolt build` re-emits), read by the inference driver to seed record and -;; protocol-method types across fn boundaries. A no-op for the runtime itself; the -;; tables just accumulate. jolt.host/record-shapes and /protocol-methods (host- -;; contract.ss) materialize them into the shape jolt.passes.types expects. - -;; ctor-key "ns/->Name" -> (vector field-kw-list field-tag-list type-tag). -;; field-tag-list parallels the fields: "num", a record simple-name string, or #f. -(define chez-record-shapes-tbl (make-hashtable string-hash string=?)) -;; method var-key "ns/method" -> (cons proto-name method-name). -(define chez-protocol-methods-tbl (make-hashtable string-hash string=?)) -;; type-tag "ns.Name" -> #(bool ...) marking which fields are ^double, so the ctor -;; and set! coerce them to flonums (JVM primitive-field semantics, and what makes -;; reading the field back as :double sound for fl-ops). -(define chez-record-dbl-tbl (make-hashtable string-hash string=?)) -(define (chez-double-tag? t) (and (string? t) (string=? t "double"))) - -(define (register-record-shape! ctor-key field-kws field-tags type-tag) - (hashtable-set! chez-record-shapes-tbl ctor-key - (vector field-kws field-tags type-tag)) - (hashtable-set! chez-record-dbl-tbl type-tag - (list->vector (map chez-double-tag? field-tags)))) - -;; simple name of a dotted/slashed string: the segment after the last . or /. -(define (chez-shape-simple-name s) - (let loop ((i (- (string-length s) 1))) - (cond ((< i 0) s) - ((or (char=? (string-ref s i) #\.) (char=? (string-ref s i) #\/)) - (substring s (+ i 1) (string-length s))) - (else (loop (- i 1)))))) - -;; resolve a field's declared type tag to what jolt.passes.types wants: "num" -;; passes through; a record name (simple "Vec3" or qualified "ns.Vec3") resolves -;; to its ctor-key (so the field reads back as that record); anything else -> nil. -(define (chez-resolve-field-tag tag by-name) - (cond ((or (not tag) (jolt-nil-t? tag)) jolt-nil) - ((string=? tag "num") "num") - ((string=? tag "double") "double") ; a ^double field reads back as a flonum - (else (let ((ck (hashtable-ref by-name (chez-shape-simple-name tag) #f))) - (if ck ck jolt-nil))))) - -;; materialize chez-record-shapes-tbl into "ns/->Name" -> {:fields :tags :type}, -;; the shape record-type-from-entry consumes. -(define (chez-record-shapes-map) - (let ((by-name (make-hashtable string-hash string=?)) - (kw-fields (keyword #f "fields")) (kw-tags (keyword #f "tags")) (kw-type (keyword #f "type")) - (out (jolt-hash-map))) - ;; index simple record name (from the type tag "ns.Name") -> ctor-key for - ;; nested-field-tag resolution. - (let-values (((ks vs) (hashtable-entries chez-record-shapes-tbl))) - (vector-for-each - (lambda (k v) (hashtable-set! by-name (chez-shape-simple-name (vector-ref v 2)) k)) ks vs) - (vector-for-each - (lambda (k v) - (let* ((fields (vector-ref v 0)) (tags (vector-ref v 1)) (type-tag (vector-ref v 2)) - (rtags (map (lambda (t) (chez-resolve-field-tag t by-name)) tags))) - (set! out (jolt-assoc out k - (jolt-hash-map kw-fields (apply jolt-vector fields) - kw-tags (apply jolt-vector rtags) - kw-type type-tag))))) - ks vs)) - out)) - -;; resolve a record TYPE name (a ^Type param hint's tag) to the ctor-key -;; "ns/->Name" the inference seeds with. Prefer the ctor in `ns` (the compile ns); -;; else any registered record with that simple name (cross-ns / imported). #f if -;; the name isn't a record type (so a ^double/^String hint resolves to nil). -(define (chez-find-ctor-key name ns) - (let* ((simple (chez-shape-simple-name name)) - (target (string-append "->" simple)) - (preferred (string-append ns "/->" simple))) - (if (hashtable-ref chez-record-shapes-tbl preferred #f) - preferred - (let loop ((ks (vector->list (hashtable-keys chez-record-shapes-tbl)))) - (cond ((null? ks) #f) - ((string=? (chez-shape-simple-name (car ks)) target) (car ks)) - (else (loop (cdr ks)))))))) - -;; materialize chez-protocol-methods-tbl into "ns/method" -> [proto method]. -(define (chez-protocol-methods-map) - (let ((out (jolt-hash-map))) - (let-values (((ks vs) (hashtable-entries chez-protocol-methods-tbl))) - (vector-for-each - (lambda (k v) (set! out (jolt-assoc out k (jolt-vector (car v) (cdr v))))) - ks vs)) - out)) - -;; index of a declared field key, or #f (only an interned keyword can be one). -(define (jrec-field-index r k) (hashtable-ref (jrdesc-index (jrec-desc r)) k #f)) -;; a vector-copy that doesn't depend on the optional rnrs vector-copy being present. -(define (jrec-vec-copy v) - (let* ((n (vector-length v)) (out (make-vector n))) - (let loop ((i 0)) (when (< i n) (vector-set! out i (vector-ref v i)) (loop (+ i 1)))) - out)) -;; extension-map entries as an (k . v) alist in iteration order. -(define (jrec-ext-pairs ext) - (let loop ((s (jolt-seq ext)) (acc '())) - (if (jolt-nil? s) (reverse acc) - (let ((e (seq-first s))) - (loop (jolt-seq (seq-more s)) (cons (cons (jolt-nth e 0) (jolt-nth e 1)) acc)))))) - -;; lookup with default d: a declared field reads index+vector-ref (a present nil -;; returns nil), then the extension map, then d. -(define (jrec-lookup r k d) - (if (eq? k jolt-deftype-kw) - (jrec-tag r) - (let ((i (jrec-field-index r k))) - (if i (vector-ref (jrec-vals r) i) - (let ((ext (jrec-ext r))) - (if (jolt-nil? ext) d - (let ((v (jolt-get ext k jrec-absent))) - (if (eq? v jrec-absent) d v)))))))) -(define (jrec-has? r k) - (and (not (eq? k jolt-deftype-kw)) - (or (and (jrec-field-index r k) #t) - (let ((ext (jrec-ext r))) - (and (not (jolt-nil? ext)) - (not (eq? jrec-absent (jolt-get ext k jrec-absent)))))))) -;; The get path: like jrec-lookup, but a deftype's ILookup valAt runs when a key -;; is genuinely missing from both the fields and the extension map. -(define (jrec-ref coll k d) - (if (eq? k jolt-deftype-kw) - (jrec-tag coll) - (let ((i (jrec-field-index coll k))) - (if i (vector-ref (jrec-vals coll) i) - (let* ((ext (jrec-ext coll)) - (v (if (jolt-nil? ext) jrec-absent (jolt-get ext k jrec-absent)))) - (if (eq? v jrec-absent) - (cond ((find-method-any-protocol (jrec-tag coll) "valAt") - => (lambda (m) (jolt-invoke m coll k d))) - (else d)) - v)))))) -;; bare-index field read for a statically-known record field — emitted by `jolt -;; build --opt` for a struct-typed receiver, where i is the field's declared slot. -;; When r is the expected record it reads the value vector directly: no field-key -;; hashtable lookup, no jolt-get dispatch. Falls back to jolt-get otherwise (a map -;; downgraded by dissoc, or a value the inference mistyped), so it stays correct -;; even if the static type is wrong. -(define (jrec-field-at r i k) - (if (and (jrec? r) (fx< i (vector-length (jrec-vals r)))) - (vector-ref (jrec-vals r) i) - (jolt-get r k))) - -;; mutate a deftype's mutable field in place: the value vector is mutable, so -;; vector-set! updates the field. (set! field v) inside a method lowers to this; -;; returns v, as set! does. -(define (jolt-set-field! inst k v) - (if (jrec? inst) - (let ((i (jrec-field-index inst k))) - (if i (let* ((flags (hashtable-ref chez-record-dbl-tbl (jrec-tag inst) #f)) - ;; a ^double field stays a flonum across set!, like the ctor — - ;; keeps a later field read sound to unbox. - (v2 (if (and flags (fx< i (vector-length flags)) (vector-ref flags i) - (number? v) (not (flonum? v))) - (exact->inexact v) v))) - (vector-set! (jrec-vals inst) i v2) v2) - (error #f "set! of an unknown field" k))) - (error #f "set! of a field on a non-record" inst))) -(define (jrec-ext=? ea eb) - (cond ((and (jolt-nil? ea) (jolt-nil? eb)) #t) - ((or (jolt-nil? ea) (jolt-nil? eb)) #f) - (else (jolt=2 ea eb)))) -(define (jrec=? a b) - (and (string=? (jrec-tag a) (jrec-tag b)) - (= (vector-length (jrec-vals a)) (vector-length (jrec-vals b))) - (let ((va (jrec-vals a)) (vb (jrec-vals b)) (n (vector-length (jrec-vals a)))) - (let loop ((i 0)) - (or (= i n) - (and (jolt=2 (vector-ref va i) (vector-ref vb i)) (loop (+ i 1)))))) - (jrec-ext=? (jrec-ext a) (jrec-ext b)))) -(define (jrec-hash r) - (let* ((fkeys (jrdesc-fkeys (jrec-desc r))) (vals (jrec-vals r)) (n (vector-length vals)) - (base (let loop ((i 0) (acc (string-hash (jrec-tag r)))) - (if (= i n) acc - (loop (+ i 1) (+ acc (jolt-hash (vector-ref fkeys i)) - (jolt-hash (vector-ref vals i)))))))) - (let ((ext (jrec-ext r))) - (if (jolt-nil? ext) base (+ base (jolt-hash ext)))))) -(define (jrec-pr r) ; #ns.Name{:k v, :k v} - (let ((fkeys (jrdesc-fkeys (jrec-desc r))) (vals (jrec-vals r))) - (string-append "#" (jrec-tag r) "{" - (let ((n (vector-length vals))) - (let loop ((i 0) (first #t) (acc "")) - (if (= i n) - (let ((ext (jrec-ext r))) - (if (jolt-nil? ext) acc - (let eloop ((es (jrec-ext-pairs ext)) (first first) (acc acc)) - (if (null? es) acc - (eloop (cdr es) #f - (string-append acc (if first "" ", ") - (jolt-pr-readable (caar es)) " " (jolt-pr-readable (cdar es)))))))) - (loop (+ i 1) #f - (string-append acc (if first "" ", ") - (jolt-pr-readable (vector-ref fkeys i)) " " (jolt-pr-readable (vector-ref vals i))))))) - "}"))) - -;; ---- extend the collection dispatchers with a jrec arm ---------------------- -;; equality for a jrec: a deftype implementing IPersistentCollection/equiv (e.g. -;; core.cache's caches, which equiv to their backing map) compares through that -;; method, so (= cache {…}) works; a plain record has no equiv and falls back to -;; field-wise jrec=? (and a record is never = a plain map). -(register-eq-arm! (lambda (a b) (or (jrec? a) (jrec? b))) - (lambda (a b) - (cond ((and (jrec? a) (jrec-cl a "equiv")) => (lambda (m) (if (jolt-truthy? (jolt-invoke m a b)) #t #f))) - ((and (jrec? b) (jrec-cl b "equiv")) => (lambda (m) (if (jolt-truthy? (jolt-invoke m b a)) #t #f))) - ;; a deftype with a custom Object.equals (but no equiv) governs - ;; its own value equality and map-key identity — core.logic's - ;; LVar/LCons key substitutions on id, ignoring metadata, so - ;; structural jrec=? (which sees the meta field) is wrong here. - ((and (jrec? a) (jrec-cl a "equals")) => (lambda (m) (if (jolt-truthy? (jolt-invoke m a b)) #t #f))) - ((and (jrec? b) (jrec-cl b "equals")) => (lambda (m) (if (jolt-truthy? (jolt-invoke m b a)) #t #f))) - ((and (jrec? a) (jrec? b)) (jrec=? a b)) - (else #f)))) -;; a deftype's declared hashCode governs its map/set hashing (paired with the -;; equals/equiv above so the hash/eq contract holds); a plain record hashes its -;; fields structurally via jrec-hash. -(register-hash-arm! jrec? - (lambda (x) (let ((m (jrec-cl x "hashCode"))) - (if m (jolt-invoke m x) (jrec-hash x))))) -;; get on a jrec: a real field reads raw (so a deftype method's own field bindings, -;; compiled to (get inst :field), never recurse); a NON-field key on a deftype that -;; implements clojure.lang.ILookup routes to its valAt (core.match's pattern types -;; compute ::tag in valAt), else the default. -;; jrec is the hottest get target (every record field read); jolt-get-dispatch -;; (collections.ss) checks jrec? directly and calls jrec-ref, skipping the get-arm -;; walk. This registration is the equivalent fallback for any other caller. -(register-get-arm! jrec? jrec-ref) -;; A jrec is a defrecord (map of fields) by default, BUT a deftype that -;; implements a clojure.lang collection interface carries the op as an inline -;; method — prefer that method, else fall back to the field/map behavior. (jrec-cl -;; finds the method; find-method-any-protocol / jolt-invoke resolve at call time.) -;; Same lookup as collections.ss rec-coll-method — one definition, aliased here. -(define jrec-cl rec-coll-method) - -;; iface-method: the single deftype/reify interface-method lookup. Returns the -;; impl fn for METHOD declared by V (a deftype/record OR a reify), or #f. NARGS -;; (including `this`) selects the matching arity for a deftype; #f means any -;; arity. Core fns route interface dispatch through this instead of each -;; re-deriving jrec-vs-reify lookup and arity handling. -(define (iface-method v method nargs) - (cond ((jrec? v) - (if nargs (find-method-any-protocol-arity (jrec-tag v) method nargs) - (find-method-any-protocol (jrec-tag v) method))) - ((jreify? v) (let ((rm (reified-methods v))) (and rm (hashtable-ref rm method #f)))) - (else #f))) -;; Call METHOD on V with ARGS (a list, `this` excluded) if V declares it, else run -;; FALLBACK. The one seam a core fn's deftype/reify arm collapses to. -(define (iface-call v method args fallback) - (let ((m (iface-method v method (+ 1 (length args))))) - (if m (apply jolt-invoke m v args) (fallback)))) -(define %r-jolt-count jolt-count) -(set! jolt-count (lambda (coll) - (cond ((jrec-cl coll "count") => (lambda (m) (jolt-invoke m coll))) - ((jrec? coll) (+ (vector-length (jrec-vals coll)) - (let ((ext (jrec-ext coll))) (if (jolt-nil? ext) 0 (%r-jolt-count ext))))) - (else (%r-jolt-count coll))))) -;; contains?: a deftype implementing Associative/containsKey (e.g. core.cache's -;; caches) answers through that; a plain defrecord checks its fields. -(define %r-jolt-contains? jolt-contains?) -(set! jolt-contains? (lambda (coll k) - (cond ((jrec-cl coll "containsKey") => (lambda (m) (if (jolt-truthy? (jolt-invoke m coll k)) #t #f))) - ((jrec? coll) (jrec-has? coll k)) - (else (%r-jolt-contains? coll k))))) -;; assoc: replacing a declared field copies the value vector; any other key grows -;; the extension map (the value vector is shared — fields are immutable). -(define %r-jolt-assoc1 jolt-assoc1) -(set! jolt-assoc1 (lambda (coll k v) - (cond ((jrec-cl coll "assoc") => (lambda (m) (jolt-invoke m coll k v))) - ((jrec? coll) - (let ((i (and (keyword? k) (jrec-field-index coll k)))) - (if i - (let ((nv (jrec-vec-copy (jrec-vals coll)))) - (vector-set! nv i v) - (make-jrec (jrec-desc coll) nv (jrec-ext coll))) - (let ((ext (jrec-ext coll))) - (make-jrec (jrec-desc coll) (jrec-vals coll) - (%r-jolt-assoc1 (if (jolt-nil? ext) empty-pmap ext) k v)))))) - (else (%r-jolt-assoc1 coll k v))))) -;; dissoc: a deftype implementing IPersistentMap/without answers through it. -;; Removing a declared field downgrades a plain record to a map (JVM parity); an -;; extension key drops from the ext map (normalized back to jolt-nil when empty). -(define (jrec->map-without r drop-k) - (let* ((fkeys (jrdesc-fkeys (jrec-desc r))) (vals (jrec-vals r)) (n (vector-length vals))) - (let loop ((i 0) (m empty-pmap)) - (if (= i n) - (let ((ext (jrec-ext r))) - (if (jolt-nil? ext) m - (fold-left (lambda (mm p) (%r-jolt-assoc1 mm (car p) (cdr p))) m (jrec-ext-pairs ext)))) - (let ((fk (vector-ref fkeys i))) - (loop (+ i 1) (if (eq? fk drop-k) m (%r-jolt-assoc1 m fk (vector-ref vals i))))))))) -(define %r-jolt-dissoc jolt-dissoc) -(define (jrec-dissoc1 coll k) - (if (not (jrec? coll)) - (%r-jolt-dissoc coll k) ; an earlier declared-field dissoc downgraded it - (let ((i (and (keyword? k) (jrec-field-index coll k)))) - (if i (jrec->map-without coll k) - (let ((ext (jrec-ext coll))) - (if (jolt-nil? ext) coll - (let ((ne (%r-jolt-dissoc ext k))) - (make-jrec (jrec-desc coll) (jrec-vals coll) - (if (= 0 (%r-jolt-count ne)) jolt-nil ne))))))))) -(set! jolt-dissoc (lambda (coll . ks) - (cond ((jrec-cl coll "without") - => (lambda (m) (fold-left (lambda (c k) (jolt-invoke m c k)) coll ks))) - ((jrec? coll) (fold-left jrec-dissoc1 coll ks)) - (else (apply %r-jolt-dissoc coll ks))))) -;; keys/vals over a jrec read its entry seq (jolt-seq is method-first, so a -;; map-like deftype delegates to its Seqable; a defrecord's seq is its fields, so -;; the result is unchanged for records). -(define (jrec-seq-col m which) - (let loop ((s (jolt-seq m)) (acc '())) - (if (jolt-nil? s) (list->cseq (reverse acc)) - (loop (jolt-seq (seq-more s)) (cons (jolt-nth (seq-first s) which) acc))))) -(define %r-jolt-keys jolt-keys) -(set! jolt-keys (lambda (m) (if (jrec? m) (jrec-seq-col m 0) (%r-jolt-keys m)))) -(define %r-jolt-vals jolt-vals) -(set! jolt-vals (lambda (m) (if (jrec? m) (jrec-seq-col m 1) (%r-jolt-vals m)))) -;; a record's seq is its field map-entries in declared order, then any extensions. -(define (jrec-entry-list r) - (let* ((fkeys (jrdesc-fkeys (jrec-desc r))) (vals (jrec-vals r)) (n (vector-length vals))) - (let loop ((i 0) (acc '())) - (if (= i n) - (let ((ext (jrec-ext r))) - (append (reverse acc) - (if (jolt-nil? ext) '() - (map (lambda (p) (make-map-entry (car p) (cdr p))) (jrec-ext-pairs ext))))) - (loop (+ i 1) (cons (make-map-entry (vector-ref fkeys i) (vector-ref vals i)) acc)))))) -(define %r-jolt-seq jolt-seq) -(set! jolt-seq (lambda (x) - (cond ((jrec-cl x "seq") => (lambda (m) (jolt-seq (jolt-invoke m x)))) - ;; a record seqs its fields; a bare deftype is not seqable (falls through - ;; to %r-jolt-seq, which errors like the JVM). - ((jrec-record? x) (list->cseq (jrec-entry-list x))) - (else (%r-jolt-seq x))))) -(define %r-jolt-conj1 jolt-conj1) -(set! jolt-conj1 (lambda (coll x) - (cond ((jrec-cl coll "cons") => (lambda (m) (jolt-invoke m coll x))) - ((jrec? coll) (jolt-assoc1 coll (jolt-nth x 0) (jolt-nth x 1))) - (else (%r-jolt-conj1 coll x))))) -;; peek/pop on a deftype implementing IPersistentStack (data.priority-map, which -;; core.cache's LRU/LU caches lean on) dispatch to its methods. -;; empty? over a jrec: a map-like deftype is empty iff its entry seq is (data -;; .priority-map's peek calls (.isEmpty this) -> empty?). jolt-seq is method-first. -(define %r-jolt-empty? jolt-empty?) -(set! jolt-empty? (lambda (coll) - (if (jrec-collection? coll) (jolt-nil? (jolt-seq coll)) (%r-jolt-empty? coll)))) -(define %r-jolt-peek jolt-peek) -(set! jolt-peek (lambda (coll) - (cond ((jrec-cl coll "peek") => (lambda (m) (jolt-invoke m coll))) - (else (%r-jolt-peek coll))))) -(define %r-jolt-pop jolt-pop) -(set! jolt-pop (lambda (coll) - (cond ((jrec-cl coll "pop") => (lambda (m) (jolt-invoke m coll))) - (else (%r-jolt-pop coll))))) -(register-pr-arm! jrec? jrec-pr) - -;; records are map? and coll? (Clojure: a record IS an associative map). The -;; predicates.ss vars hold a snapshot, so re-def-var! after extending. record? is -;; the overlay's (some? (get x :jolt/deftype)) — works for free since the get -;; override returns the tag for that key. -;; only a defrecord is a map (Clojure: a record IS an associative map); a bare -;; deftype is not. coll? additionally covers a deftype implementing a collection -;; interface. predicates.ss vars hold a snapshot, so re-def-var! after extending. -(define %r-jolt-map? jolt-map?) -(set! jolt-map? (lambda (x) (or (jrec-maplike? x) (%r-jolt-map? x)))) -(def-var! "clojure.core" "map?" jolt-map?) -(def-var! "clojure.core" "coll?" (lambda (x) (or (jrec-collection? x) (jolt-coll-pred? x)))) - -;; ---- protocol registry ------------------------------------------------------ -;; type-tag -> (proto-name -> (method-name -> fn)) -(define type-registry (make-hashtable string-hash string=?)) -(define (register-protocol-method type-tag proto method fn) - (let* ((ti (or (hashtable-ref type-registry type-tag #f) - (let ((h (make-hashtable string-hash string=?))) (hashtable-set! type-registry type-tag h) h))) - (pi (or (hashtable-ref ti proto #f) - (let ((h (make-hashtable string-hash string=?))) (hashtable-set! ti proto h) h)))) - (hashtable-set! pi method fn))) -(define (find-protocol-method type-tag proto method) - (let ((ti (hashtable-ref type-registry type-tag #f))) - (and ti (let ((pi (hashtable-ref ti proto #f))) (and pi (hashtable-ref pi method #f)))))) -(define (find-method-any-protocol type-tag method) - (let ((ti (hashtable-ref type-registry type-tag #f))) - (and ti (let loop ((protos (vector->list (hashtable-keys ti)))) - (and (pair? protos) - (let ((f (hashtable-ref (hashtable-ref ti (car protos) #f) method #f))) - (or f (loop (cdr protos))))))))) -;; A deftype can implement a method NAME at two arities from two interfaces (e.g. -;; data.priority-map's seq: Seqable.seq[this] and Sorted.seq[this ascending]), -;; registered under different protocols. Pick the impl whose procedure accepts -;; the call's arg count (this + args); fall back to any same-named impl. -(define (proc-accepts? f n) - (and (procedure? f) (bitwise-bit-set? (procedure-arity-mask f) n))) -(define (find-method-any-protocol-arity type-tag method nargs) - (let ((ti (hashtable-ref type-registry type-tag #f))) - (and ti (let loop ((protos (vector->list (hashtable-keys ti))) (fallback #f)) - (if (null? protos) - fallback - (let ((f (hashtable-ref (hashtable-ref ti (car protos) #f) method #f))) - (cond ((and f (proc-accepts? f nargs)) f) - (else (loop (cdr protos) (or fallback f)))))))))) -(define (type-satisfies? type-tag proto) - (let ((ti (hashtable-ref type-registry type-tag #f))) - (and ti (hashtable-ref ti proto #f) #t))) -;; True when a deftype/record instance DECLARES a method by this name (an inline -;; protocol impl), so clojure.core can prefer it over generic collection behavior -;; — e.g. (empty priority-map) must use the type's own empty, not return {}. -(def-var! "jolt.host" "jrec-method?" - (lambda (v name) (if (and (jrec? v) (find-method-any-protocol (jrec-tag v) name)) #t #f))) - -;; host type-tag candidates for a non-record value (extend-protocol on builtins). -(define (value-host-tags obj) - ;; numbers dispatch by actual type (a Double is NOT a Long): flonum -> Double, - ;; exact ratio -> Ratio, exact integer -> Long. - (cond ((flonum? obj) '("Double" "Float" "Number" "Object")) - ((and (number? obj) (exact? obj) (not (integer? obj))) '("Ratio" "Number" "Object")) - ((number? obj) '("Long" "Integer" "BigInteger" "BigInt" "Number" "Object")) - ((string? obj) '("String" "CharSequence" "Object")) - ((boolean? obj) '("Boolean" "Object")) - ((keyword? obj) (jch-tags "clojure.lang.Keyword")) - ((jolt-symbol? obj) (jch-tags "clojure.lang.Symbol")) - ((pvec? obj) (jch-tags "clojure.lang.PersistentVector")) - ((pmap? obj) (jch-tags "clojure.lang.PersistentArrayMap")) - ((pset? obj) (jch-tags "clojure.lang.PersistentHashSet")) - ;; jolt models every seq as a list (no distinct LazySeq), so a seq also - ;; reports PersistentList / IPersistentList / IPersistentStack — extend-protocol - ;; clojure.lang.IPersistentList (algo.monads' writer monad) dispatches on one. - ((or (cseq? obj) (empty-list-t? obj)) (jch-tags "clojure.lang.PersistentList")) - ;; a lazy seq (map/filter/… result) is clojure.lang.LazySeq: a Sequential - ;; ISeq, but not a PersistentList — matching the JVM so extend-protocol / - ;; instance? on a deferred seq dispatch like an eager one where they should. - ((jolt-lazyseq? obj) (jch-tags "clojure.lang.LazySeq")) - ;; a var is clojure.lang.Var (also IDeref / IFn) — reitit's Expand protocol - ;; extends to Var so a #'handler route dispatches. - ((var-cell? obj) (jch-tags "clojure.lang.Var")) - ;; java.net.URI jhost — extend-protocol java.net.URI (hiccup ToURI/ToStr). - ((and (jhost? obj) (string=? (jhost-tag obj) "uri")) '("URI" "java.net.URI" "Object")) - ;; a ByteBuffer — extend-protocol java.nio.ByteBuffer (aws-api util). - ((and (jhost? obj) (string=? (jhost-tag obj) "byte-buffer")) '("ByteBuffer" "java.nio.ByteBuffer" "Object")) - ;; java.io readers/writers — so (extend-protocol java.io.Reader …) (data.csv) - ;; and the like dispatch on one. A PushbackReader is also a Reader. - ((and (jhost? obj) (string=? (jhost-tag obj) "string-reader")) - '("StringReader" "java.io.StringReader" "Reader" "java.io.Reader" "Object")) - ((and (jhost? obj) (string=? (jhost-tag obj) "pushback-reader")) - '("PushbackReader" "java.io.PushbackReader" "FilterReader" "java.io.FilterReader" "Reader" "java.io.Reader" "Object")) - ((and (jhost? obj) (string=? (jhost-tag obj) "char-reader")) - '("Reader" "java.io.Reader" "Object")) - ((and (jhost? obj) (string=? (jhost-tag obj) "char-writer")) - '("Writer" "java.io.Writer" "Object")) - ((and (jhost? obj) (string=? (jhost-tag obj) "writer")) - '("Writer" "java.io.Writer" "Object")) - ;; arrays dispatch by their JVM array-class name — extend-protocol to - ;; (Class/forName "[B") for byte[] (data.json, aws-api), "[C" for char[]. - ((and (jolt-array? obj) (eq? (jolt-array-kind obj) 'byte)) '("[B" "Object")) - ((and (jolt-array? obj) (eq? (jolt-array-kind obj) 'char)) '("[C" "Object")) - ((jolt-array? obj) '("[Ljava.lang.Object;" "Object")) - ;; a regex VALUE — extend-protocol java.util.regex.Pattern (core.match.regex). - ((regex-t? obj) '("Pattern" "java.util.regex.Pattern" "Object")) - ;; host value types a library may extend a protocol to by class (data.json - ;; extends JSONWriter to java.util.UUID / java.util.Date / java.math.BigDecimal). - ((juuid? obj) '("UUID" "java.util.UUID" "Object")) - ((jinst? obj) '("Date" "java.util.Date" "Timestamp" "java.sql.Timestamp" "Object")) - ((jbigdec? obj) '("BigDecimal" "java.math.BigDecimal" "Number" "Object")) - ((and (jhost? obj) (string=? (jhost-tag obj) "instant")) '("Instant" "java.time.Instant" "Object")) - ((and (jhost? obj) (string=? (jhost-tag obj) "local-date")) '("LocalDate" "java.time.LocalDate" "Object")) - ((and (jhost? obj) (string=? (jhost-tag obj) "local-time")) '("LocalTime" "java.time.LocalTime" "Object")) - ((and (jhost? obj) (string=? (jhost-tag obj) "local-date-time")) '("LocalDateTime" "java.time.LocalDateTime" "Object")) - ((and (jhost? obj) (string=? (jhost-tag obj) "duration")) '("Duration" "java.time.Duration" "TemporalAmount" "java.time.temporal.TemporalAmount" "Object")) - ((and (jhost? obj) (string=? (jhost-tag obj) "period")) '("Period" "java.time.Period" "TemporalAmount" "java.time.temporal.TemporalAmount" "Object")) - ((and (jhost? obj) (string=? (jhost-tag obj) "month-enum")) '("Month" "java.time.Month" "Object")) - ((and (jhost? obj) (string=? (jhost-tag obj) "dow-enum")) '("DayOfWeek" "java.time.DayOfWeek" "Object")) - ((and (jhost? obj) (string=? (jhost-tag obj) "year")) '("Year" "java.time.Year" "Object")) - ((and (jhost? obj) (string=? (jhost-tag obj) "year-month")) '("YearMonth" "java.time.YearMonth" "Object")) - ((and (jhost? obj) (string=? (jhost-tag obj) "chrono-unit")) '("ChronoUnit" "java.time.temporal.ChronoUnit" "TemporalUnit" "java.time.temporal.TemporalUnit" "Object")) - ((and (jhost? obj) (string=? (jhost-tag obj) "chrono-field")) '("ChronoField" "java.time.temporal.ChronoField" "TemporalField" "java.time.temporal.TemporalField" "Object")) - ((and (jhost? obj) (string=? (jhost-tag obj) "zone-offset")) '("ZoneOffset" "java.time.ZoneOffset" "ZoneId" "java.time.ZoneId" "Object")) - ((and (jhost? obj) (string=? (jhost-tag obj) "zone-id")) '("ZoneId" "java.time.ZoneId" "Object")) - ((and (jhost? obj) (string=? (jhost-tag obj) "zoned-date-time")) '("ZonedDateTime" "java.time.ZonedDateTime" "Object")) - ((and (jhost? obj) (string=? (jhost-tag obj) "offset-date-time")) '("OffsetDateTime" "java.time.OffsetDateTime" "Object")) - ((and (jhost? obj) (string=? (jhost-tag obj) "offset-time")) '("OffsetTime" "java.time.OffsetTime" "Object")) - ((and (jhost? obj) (string=? (jhost-tag obj) "clock")) '("Clock" "java.time.Clock" "Object")) - ;; java.sql.Date — a distinct class from java.util.Date so a protocol - ;; extended to both (data.json's JSONWriter) routes a sql.Date to its impl. - ((and (jhost? obj) (string=? (jhost-tag obj) "sql-date")) '("java.sql.Date" "Date" "java.util.Date" "Object")) - ;; a bare procedure (fn) — extend-protocol to clojure.lang.{Fn,IFn,AFn}. - ((procedure? obj) (jch-tags "clojure.lang.AFunction")) - ((jolt-nil? obj) '("nil")) - ;; a defrecord IS the clojure.lang map/record interfaces, so a protocol - ;; extended to IRecord / IPersistentMap / Associative / Seqable / … (and not - ;; to the record's own type) dispatches to it — e.g. core.logic extends - ;; IWalkTerm to clojure.lang.IRecord, and walking a record value must hit - ;; that, not the Object default (which would recur forever). The record's - ;; own type is tried first (dispatch checks jrec-tag before these tags). - ((jrec-record? obj) - (cons (jrec-tag obj) - '("IRecord" "clojure.lang.IRecord" "IPersistentMap" "clojure.lang.IPersistentMap" - "APersistentMap" "Associative" "ILookup" "Seqable" "Counted" - "IPersistentCollection" "IObj" "IMeta" "Map" "java.util.Map" - "Iterable" "java.lang.Iterable" "Object"))) - ;; a bare deftype is opaque — its declared interfaces dispatch via the - ;; inline methods registered under its own tag (tried before these tags). - ((jrec? obj) (list (jrec-tag obj) "Object")) - (else '("Object")))) - -(define (record-tag obj) (and (jrec? obj) (jrec-tag obj))) - -;; ---- the native that handles the analyzer/overlay call ---------------------- -;; make-deftype-ctor: (name-sym field-kws field-tags field-muts) -> ctor closure. -;; The tag is baked at definition time in the type's ns (chez-current-ns). -(define (make-deftype-ctor name-sym field-kws . rest-args) - (let* ((tag (string-append (chez-current-ns) "." (symbol-t-name name-sym))) - (kws (seq->list field-kws)) - (field-tags (if (pair? rest-args) (seq->list (car rest-args)) '())) - ;; which fields are ^double — coerced to a flonum on construction (JVM - ;; primitive-field parity), so reading them back is a genuine flonum. - (dbl-flags (list->vector (map chez-double-tag? field-tags))) - (ndbl (vector-length dbl-flags)) - (desc (make-jrdesc tag kws)) - (nf (length kws)) - (ctor (lambda args - ;; fill the value vector from the positional args, padding missing - ;; trailing fields with nil and ignoring any extras. - (let ((v (make-vector nf jolt-nil))) - (let loop ((as args) (i 0)) - (if (or (null? as) (= i nf)) (make-jrec desc v jolt-nil) - (let ((a (car as))) - (vector-set! v i - (if (and (fx< i ndbl) (vector-ref dbl-flags i) - (number? a) (not (flonum? a))) - (exact->inexact a) a)) - (loop (cdr as) (+ i 1))))))))) - ;; Register the ctor under its fully-qualified tag ("ns.Name") — a bare - ;; (Name. …) in the DEFINING ns is qualified to this by the analyzer, so a - ;; deftype whose simple name collides with a built-in host class (tools.reader's - ;; PushbackReader vs java.io.PushbackReader) still resolves correctly there. - (register-class-ctor! tag ctor) - ;; Also register the simple name so (Name. …) resolves ns-agnostically across - ;; files — BUT never clobber a built-in host class of the same simple name (an - ;; unrelated ns's bare (Name. …) must still reach the built-in). A prior deftype - ;; (tracked in chez-simple-name-tag) is fine to overwrite (last def wins / redef). - (when (or (not (hashtable-ref class-ctors-tbl (symbol-t-name name-sym) #f)) - (hashtable-ref chez-simple-name-tag (symbol-t-name name-sym) #f)) - (register-class-ctor! (symbol-t-name name-sym) ctor)) - ;; index the tag so a cross-ns extend-protocol resolves the bare type name. - (hashtable-set! chez-deftype-tag-set tag #t) - (hashtable-set! chez-simple-name-tag (symbol-t-name name-sym) tag) - ;; graft the type onto the class graph so isa?/supers/ancestors see it. A - ;; bare deftype is an IType; defrecord (which runs register-record-type! - ;; right after) replaces the row with the record interface set. - (jch-set-supers! tag '("clojure.lang.IType")) - (hashtable-set! chez-deftype-ctor-tag ctor tag) - ;; record the shape for whole-program inference, keyed by the positional - ;; ctor var "ns/->Name" the analyzer resolves a (->Name …) call to. - (register-record-shape! (string-append (chez-current-ns) "/->" (symbol-t-name name-sym)) - kws field-tags tag) - ctor)) - -;; make-protocol: a protocol value the overlay reads via (get p :name)/(get p :methods). -(define (make-protocol name-str methods) - (jolt-hash-map (keyword #f "jolt/type") (keyword #f "jolt/protocol") - (keyword #f "name") (jolt-symbol jolt-nil name-str) - (keyword #f "methods") methods)) - -;; register-protocol-methods!: record each method's var-key -> [proto method] for -;; the inference driver (devirtualization). Dispatch itself is by the receiver's -;; type tag at call time, so this table is read only by `jolt build` inference. -;; Called by defprotocol-emitted code in the protocol's ns. -(define (register-protocol-methods! proto-name method-names) - (let ((ns (chez-current-ns))) - (for-each (lambda (mn) - (let ((m (if (symbol-t? mn) (symbol-t-name mn) mn))) - (hashtable-set! chez-protocol-methods-tbl - (string-append ns "/" m) (cons proto-name m)))) - (seq->list method-names))) - jolt-nil) - -;; register-method: extend-type/extend register an impl. Host type names keep a -;; bare canonical tag; record names qualify to the current ns. -(define host-type-set - (let ((h (make-hashtable string-hash string=?))) - (for-each (lambda (n) (hashtable-set! h n #t)) - '("Long" "Integer" "Number" "Double" "Ratio" "BigInt" "BigInteger" - "String" "CharSequence" "Boolean" "Character" - "Keyword" "Symbol" "Named" "Object" "nil" - "Fn" "IFn" "AFn" "URI" "Var" "IDeref" - "PersistentVector" "APersistentVector" "IPersistentVector" - "PersistentArrayMap" "APersistentMap" "IPersistentMap" - "PersistentHashSet" "APersistentSet" "IPersistentSet" - "ASeq" "ISeq" "IPersistentCollection" "Associative" "Sequential" - "PersistentList" "IPersistentList" "IPersistentStack" - "Map" "java.util.Map" "List" "java.util.List" "Set" "java.util.Set" - "Collection" "java.util.Collection" "Iterable" "java.lang.Iterable" - "UUID" "BigDecimal" "Date" "Timestamp" "Instant" "java.sql.Date" - "Pattern" "java.util.regex.Pattern" - ;; java.time value types (extend-protocol Duration / ZonedDateTime / …) - "Duration" "Period" "LocalDate" "LocalTime" "LocalDateTime" - "ZonedDateTime" "OffsetDateTime" "OffsetTime" "ZoneId" "ZoneOffset" - "Clock" "Year" "YearMonth" "Month" "DayOfWeek" - "ChronoUnit" "ChronoField" "TemporalAmount" "TemporalUnit" "TemporalField" - ;; ByteBuffer + JVM array classes (extend-protocol to (Class/forName "[B")) - "ByteBuffer" "java.nio.ByteBuffer" - "[B" "[C" "[I" "[J" "[D" "[Ljava.lang.Object;" - ;; java.io readers/writers — extend-protocol java.io.Reader (data.csv) - "Reader" "java.io.Reader" "Writer" "java.io.Writer" - "StringReader" "java.io.StringReader" "PushbackReader" "java.io.PushbackReader" - "BufferedReader" "java.io.BufferedReader" "FilterReader" "java.io.FilterReader" - "InputStream" "java.io.InputStream" "OutputStream" "java.io.OutputStream")) - h)) -(define (strip-prefix s p) - (let ((pl (string-length p))) - (and (> (string-length s) pl) (string=? (substring s 0 pl) p) (substring s pl (string-length s))))) -(define (canonical-host-tag type-name) - (let ((base (or (strip-prefix type-name "java.lang.") - (strip-prefix type-name "java.util.regex.") - (strip-prefix type-name "java.util.") - (strip-prefix type-name "java.net.") - (strip-prefix type-name "java.math.") - (strip-prefix type-name "java.time.") - (strip-prefix type-name "clojure.lang.") - type-name))) - ;; a host class if the literal set lists it OR the class graph models it — both - ;; feed value-host-tags (which emits the same bare segment), so a protocol - ;; extended to any modeled class keys under a tag the value reports. A - ;; deftype/defrecord is in the graph too (its ancestry), but its VALUES report - ;; the ns-qualified tag, not the bare segment — so a name that resolves to a - ;; deftype never canonicalizes through the graph arm. - (and (or (hashtable-ref host-type-set base #f) - (and (not (hashtable-ref chez-simple-name-tag type-name #f)) - (not (hashtable-ref chez-deftype-tag-set type-name #f)) - (or (jch-known? base) (jch-known? type-name)))) - base))) -;; An extend/extend-type/extend-protocol registration marks the tag as an -;; extender of the protocol (recorded inside type-registry so the per-case prune -;; restores it). deftype/defrecord inline impls go through register-inline-method -;; and skip the mark: the JVM compiles inline protocol methods into the class, so -;; extenders excludes them. -(define extend-mark "__jolt_extend__") -(define (mark-extend! tag proto-name) - (let ((ti (hashtable-ref type-registry tag #f))) - (when ti (let ((pi (hashtable-ref ti proto-name #f))) - (when pi (hashtable-set! pi extend-mark #t)))))) -(define (register-method type-name proto-name method-name fn) - (let* ((host (canonical-host-tag type-name)) - (local (string-append (chez-current-ns) "." type-name)) - ;; a host class -> its canonical tag; a deftype defined in THIS ns -> the - ;; local tag; an :import-ed deftype from another ns -> its real tag via the - ;; simple-name index; otherwise the local tag (a forward extend). - (tag (cond (host host) - ((hashtable-ref chez-deftype-tag-set local #f) local) - ((hashtable-ref chez-simple-name-tag type-name #f)) - (else local)))) - (register-protocol-method tag proto-name method-name fn) - (mark-extend! tag proto-name) - jolt-nil)) - -;; register-inline-method: a deftype/defrecord inline impl. Registers for dispatch -;; under the ns-qualified record tag but does NOT mark it as an extender. -(define (register-inline-method type-name proto-name method-name fn) - (register-protocol-method (string-append (chez-current-ns) "." type-name) proto-name method-name fn) - jolt-nil) -;; record that a deftype/defrecord implements a protocol even when it adds no -;; methods (a MARKER protocol, e.g. core.match's IPseudoPattern) — so -;; instance?/satisfies? on the protocol hold. -(define (register-inline-protocol! type-name proto-name) - (let* ((tag (string-append (chez-current-ns) "." type-name)) - (ti (or (hashtable-ref type-registry tag #f) - (let ((h (make-hashtable string-hash string=?))) (hashtable-set! type-registry tag h) h)))) - (unless (hashtable-ref ti proto-name #f) - (hashtable-set! ti proto-name (make-hashtable string-hash string=?)))) - ;; the protocol's interface joins the type's class ancestry, spelled like the - ;; JVM interface (munged ns; the defining ns is assumed to be the current one — - ;; the macro passes only the simple protocol name). - (let ((iface (string-append (jch-munge-segments (chez-current-ns)) "." proto-name))) - (jch-mark-interface! iface) - (jch-register-supers! (string-append (chez-current-ns) "." type-name) (list iface))) - jolt-nil) - -;; protocol-resolve: the impl procedure for obj — by record type tag, a reify's -;; instance-local method, or the protocol's extended impls over obj's host tags. -;; Raises if none implements the method. The dispatchN entry points apply it -;; directly so a protocol call doesn't cons a rest-list (the impl fn is always a -;; procedure, registered by register-(inline-)method/extend). -(define (protocol-resolve proto-name method-name obj) - (cond - ((and (jrec? obj) (find-protocol-method (jrec-tag obj) proto-name method-name))) - ((reified-methods obj) - => (lambda (rm) - (or (hashtable-ref rm method-name #f) - ;; not implemented on the reify — fall back to the protocol's - ;; extended impls over the reify's host tags (e.g. an Object/default - ;; extension). malli reifies some protocols and leans on the default. - (let loop ((tags (value-host-tags obj))) - (cond ((null? tags) (error #f (string-append "No reified method " method-name))) - ((find-protocol-method (car tags) proto-name method-name)) - (else (loop (cdr tags)))))))) - (else - (let loop ((tags (value-host-tags obj))) - (cond ((null? tags) (error #f (string-append "No method " method-name " in " proto-name))) - ((find-protocol-method (car tags) proto-name method-name)) - (else (loop (cdr tags)))))))) -;; Fixed-arity entry points the protocol-method shims call: no rest-list, no seq -;; round-trip — apply the resolved impl directly. defprotocol emits one clause per -;; declared arity that calls the matching dispatchN. -(define (protocol-dispatch1 proto-name method-name obj) - ((protocol-resolve proto-name method-name obj) obj)) -(define (protocol-dispatch2 proto-name method-name obj a) - ((protocol-resolve proto-name method-name obj) obj a)) -(define (protocol-dispatch3 proto-name method-name obj a b) - ((protocol-resolve proto-name method-name obj) obj a b)) -;; the variadic fallback (a declared arity of 4+ args) takes a seqable rest. -(define (protocol-dispatch proto-name method-name obj rest-args) - (let ((rest (if (jolt-nil? rest-args) '() (seq->list rest-args)))) - (apply (protocol-resolve proto-name method-name obj) obj rest))) - -;; devirt-resolve: the impl for a call the inference proved monomorphic. Try the -;; static type tag directly (the fast path that skips receiver-type computation), -;; and fall back to ordinary dispatch when it misses — a record can satisfy a -;; protocol via an Object/host-tag default rather than a direct impl, which -;; find-protocol-method on its own tag wouldn't see. Mirrors jrec-field-at falling -;; back to jolt-get: correct regardless of how precise the inference was. -(define (devirt-resolve type-tag proto-name method-name obj) - (or (find-protocol-method type-tag proto-name method-name) - (protocol-resolve proto-name method-name obj))) - -;; dot-dispatch fallback used by emit for (.method record args): find the method -;; in ANY protocol the record's type implements. -;; java.util.Iterator over a jolt seqable: (.iterator coll) returns a jiterator -;; holding a mutable cursor over (seq coll); (.hasNext it)/(.next it) walk it. -;; hiccup/compiler's run! loop iterates collections this way. -(define-record-type jiterator (fields (mutable cur)) (nongenerative jolt-iterator-v1)) -;; (seq an-iterator) / (iterator-seq it): a jiterator wraps the remaining seq in -;; cur, so seq just yields it — clojure.test's (iterator-seq (.iterator coll)). -(let ((prev-seq jolt-seq)) - (set! jolt-seq (lambda (x) (if (jiterator? x) (jiterator-cur x) (prev-seq x))))) -;; A Chez condition's message string (for Throwable .getMessage/.toString): the -;; &message text plus any &irritants, or display-condition output as a fallback. -(define (condition->message-string c) - (if (message-condition? c) - (let* ((m (condition-message c)) - (irr (if (irritants-condition? c) (condition-irritants c) '())) - (append-irr (lambda () - (let loop ((xs irr) (acc m)) - (if (null? xs) acc - (loop (cdr xs) (string-append acc " " (jolt-pr-str (car xs))))))))) - ;; some Chez conditions (open-input-file etc.) carry a format-template - ;; message ("failed for ~a: ~(~a~)") whose irritants fill the directives; - ;; format it in. Fall back to appending the irritants if that fails. - (if (and (string? m) (let scan ((i 0)) - (cond ((>= i (string-length m)) #f) - ((char=? (string-ref m i) #\~) #t) - (else (scan (+ i 1)))))) - (guard (e (#t (append-irr))) (apply format m irr)) - (append-irr))) - (with-output-to-string (lambda () (display-condition c))))) -;; expose a Chez condition's message to Clojure (ex-message returns nil for raw -;; host conditions): the nREPL eval handler surfaces it instead of an opaque -;; "#". -(def-var! "jolt.host" "condition-message" - (lambda (c) (if (condition? c) (condition->message-string c) jolt-nil))) -(define (record-method-dispatch-base obj method-name rest-args) - (let ((rest (if (jolt-nil? rest-args) '() (seq->list rest-args)))) - (cond - ((and (jrec? obj) (find-method-any-protocol-arity (jrec-tag obj) method-name (+ 1 (length rest)))) - => (lambda (f) (apply jolt-invoke f obj rest))) - ;; (.field inst): a deftype/record field read with no matching method. - ;; Clojure reads the field for (.q x) just like (.-q x); a declared method - ;; (above) wins, this is the field-accessor fallback. - ((and (jrec? obj) (null? rest) (jrec-has? obj (keyword #f method-name))) - (jrec-lookup obj (keyword #f method-name) jolt-nil)) - ;; a defrecord is Associative / ILookup / IPersistentMap / Seqable / Counted, - ;; so its clojure.lang interface methods delegate to the map fns when not - ;; overridden by a declared method — reitit's impl calls (.assoc match k v), - ;; (.valAt …), (.without …) directly. A bare deftype implements these via its - ;; own declared methods (handled above), so this is record-only. - ((and (jrec-record? obj) - (member method-name '("valAt" "assoc" "without" "containsKey" "cons" - "count" "seq" "equiv" "entryAt" "empty"))) - (cond - ((string=? method-name "valAt") - (if (null? (cdr rest)) (jolt-get obj (car rest) jolt-nil) (jolt-get obj (car rest) (cadr rest)))) - ((string=? method-name "assoc") (jolt-assoc1 obj (car rest) (cadr rest))) - ((string=? method-name "without") (jolt-dissoc obj (car rest))) - ((string=? method-name "containsKey") (if (jolt-truthy? (jolt-contains? obj (car rest))) #t #f)) - ((string=? method-name "cons") (jolt-conj1 obj (car rest))) - ((string=? method-name "count") (jolt-count obj)) - ((string=? method-name "seq") (jolt-seq obj)) - ((string=? method-name "equiv") (if (jolt= obj (car rest)) #t #f)) - ((string=? method-name "entryAt") - (if (jolt-truthy? (jolt-contains? obj (car rest))) - (make-map-entry (car rest) (jolt-get obj (car rest) jolt-nil)) jolt-nil)) - (else jolt-nil))) ; .empty of a record is nil on the JVM - ((reified-methods obj) - => (lambda (rm) (let ((f (hashtable-ref rm method-name #f))) - (if f (apply jolt-invoke f obj rest) (error #f (string-append "No method " method-name)))))) - ;; java.lang.String interop: defined in natives-str.ss, loaded - ;; after this file (free reference, resolved at call time). - ((string? obj) (jolt-string-method method-name obj rest)) - ((jiterator? obj) - (cond ((string=? method-name "hasNext") (not (jolt-nil? (jolt-seq (jiterator-cur obj))))) - ((string=? method-name "next") - (let ((s (jolt-seq (jiterator-cur obj)))) - (if (jolt-nil? s) (error #f "iterator exhausted") - (let ((v (jolt-first s))) (jiterator-cur-set! obj (jolt-rest s)) v)))) - (else (error #f (string-append "No method " method-name " on Iterator"))))) - ((string=? method-name "iterator") (make-jiterator (jolt-seq obj))) - ;; clojure.lang.Keyword interop: a Keyword carries an interned `sym` field - ;; (the symbol form, ns + name) plus the Named methods. honeysql/reitit read - ;; (.sym k) on their :clj branch to recover the symbol without the colon. - ((keyword-t? obj) - (cond ((string=? method-name "sym") - (jolt-symbol (keyword-t-ns obj) (keyword-t-name obj))) - ((string=? method-name "getName") (keyword-t-name obj)) - ((string=? method-name "getNamespace") (or (keyword-t-ns obj) jolt-nil)) - ((string=? method-name "toString") - (string-append ":" (if (keyword-t-ns obj) (string-append (keyword-t-ns obj) "/") "") - (keyword-t-name obj))) - ((string=? method-name "hashCode") (keyword-t-khash obj)) - ((string=? method-name "equals") (and (pair? rest) (eq? obj (car rest)))) - (else (error #f (string-append "No method " method-name " on Keyword"))))) - ;; clojure.lang.Symbol interop: the Named methods + getName/getNamespace. - ((symbol-t? obj) - (cond ((string=? method-name "getName") (symbol-t-name obj)) - ((string=? method-name "getNamespace") (or (symbol-t-ns obj) jolt-nil)) - ((string=? method-name "toString") - (string-append (if (symbol-t-ns obj) (string-append (symbol-t-ns obj) "/") "") - (symbol-t-name obj))) - ((string=? method-name "equals") (and (pair? rest) (jolt=2 obj (car rest)))) - ((string=? method-name "hashCode") - (java-symbol-hash (symbol-t-name obj) (symbol-t-ns obj))) - (else (error #f (string-append "No method " method-name " on Symbol"))))) - ;; clojure.lang.Namespace: name/getName yield the ns name as a Symbol (JVM: - ;; Namespace.name is a Symbol). clojure.spec.alpha reads (.name *ns*). - ((jns? obj) - (cond ((or (string=? method-name "name") (string=? method-name "getName")) - (jolt-symbol #f (jns-name obj))) - ((string=? method-name "toString") (jns-name obj)) - (else (error #f (string-append "No method " method-name " on Namespace"))))) - ;; clojure.lang.Var: ns -> its Namespace, sym -> the simple-name Symbol. - ;; clojure.spec.alpha's ->sym reads (.name (.ns v)) and (.sym v). - ((var-cell? obj) - (cond ((string=? method-name "ns") (intern-ns! (var-cell-ns obj))) - ((or (string=? method-name "sym") (string=? method-name "name")) - (jolt-symbol #f (var-cell-name obj))) - ((string=? method-name "getName") - (jolt-symbol (var-cell-ns obj) (var-cell-name obj))) - ((string=? method-name "toString") (string-append "#'" (var-cell-ns obj) "/" (var-cell-name obj))) - (else (error #f (string-append "No method " method-name " on Var"))))) - ;; java.lang.Throwable interop over a Chez condition. A jolt host error - ;; (`error`/`assertion-violationf`) raises a Chez condition; Clojure code - ;; that catches it as a Throwable reads (.getMessage e) / (.toString e). - ((condition? obj) - (cond ((or (string=? method-name "getMessage") (string=? method-name "getLocalizedMessage")) - (condition->message-string obj)) - ((string=? method-name "toString") (condition->message-string obj)) - ((string=? method-name "getCause") jolt-nil) - ;; java.sql.SQLException chaining — jolt errors don't chain (nil). - ((string=? method-name "getNextException") jolt-nil) - ((string=? method-name "getStackTrace") (jolt-vector)) - ((string=? method-name "printStackTrace") jolt-nil) - (else (error #f (string-append "No method " method-name " on Throwable"))))) - ;; java.lang.Character interop: (.toString \+) -> "+", etc. - ((char? obj) - (cond ((string=? method-name "toString") (string obj)) - ((string=? method-name "charValue") obj) - ((string=? method-name "hashCode") (char->integer obj)) - ((string=? method-name "equals") (and (pair? rest) (char? (car rest)) (char=? obj (car rest)))) - ((string=? method-name "compareTo") - (let ((o (car rest))) (cond ((char? obj o) 1) (else 0)))) - (else (error #f (string-append "No method " method-name " on char"))))) - ;; java.util.List .indexOf / .lastIndexOf over any seqable (vector / list / - ;; seq) — -1 when absent, like the JVM (medley/index-of reads this). - ((or (string=? method-name "indexOf") (string=? method-name "lastIndexOf")) - (let ((target (car rest)) (last? (string=? method-name "lastIndexOf"))) - (let loop ((s (jolt-seq obj)) (i 0) (found -1)) - (cond ((jolt-nil? s) found) - ((jolt=2 (seq-first s) target) - (if last? (loop (jolt-seq (seq-more s)) (fx+ i 1) i) i)) - (else (loop (jolt-seq (seq-more s)) (fx+ i 1) found)))))) - ;; java.util.Collection.contains over a list/seq (vectors/sets handle it in - ;; dot-coll-method): value membership, like the JVM. - ((string=? method-name "contains") - (let ((target (car rest))) - (let loop ((s (jolt-seq obj))) - (cond ((jolt-nil? s) #f) - ((jolt=2 (seq-first s) target) #t) - (else (loop (jolt-seq (seq-more s)))))))) - ;; universal Object methods on any remaining value (boolean, etc.). - ((string=? method-name "toString") (jolt-str-render-one obj)) - ((string=? method-name "hashCode") (jolt-hash obj)) - ((string=? method-name "equals") (and (pair? rest) (if (jolt= obj (car rest)) #t #f))) - (else (error #f (string-append "No method " method-name " for value: " - (jolt-pr-str obj))))))) - -;; ---- method-dispatch arm registry ------------------------------------------ -;; A .method call (record-method-dispatch) is resolved by an ordered list of arms -;; (ascending priority), each (obj method-name rest-args) -> result | 'pass. -;; This replaces a stack of (set! record-method-dispatch ...) rebindings across -;; six files whose precedence was implicit in load order — priority is now -;; explicit data. record-method-dispatch-base is the final fallback (the -;; string/keyword/symbol/Object-method surface). A host shim / library registers -;; an arm with register-method-arm! instead of set!-wrapping the dispatcher. -(define method-dispatch-arms '()) ; list of (priority . arm), ascending priority -(define (register-method-arm! priority arm) - (set! method-dispatch-arms - (let ins ((as method-dispatch-arms)) - (cond ((null? as) (list (cons priority arm))) - ((< priority (caar as)) (cons (cons priority arm) as)) - (else (cons (car as) (ins (cdr as)))))))) -(define (record-method-dispatch obj method-name rest-args) - (let loop ((as method-dispatch-arms)) - (if (null? as) - (record-method-dispatch-base obj method-name rest-args) - (let ((r ((cdar as) obj method-name rest-args))) - (if (eq? r 'pass) (loop (cdr as)) r))))) - -;; (.getClass x): a universal Object method reached by EVERY value before any -;; per-type arm — the class token for the value (jolt has no Class objects; the -;; token is the canonical name string, on which .getName/.getSimpleName work). -;; One arm, so a type arm that only whitelists its own methods can't steal it. -(register-method-arm! 5 - (lambda (obj method-name rest-args) - (if (string=? method-name "getClass") (jolt-class obj) 'pass))) - -;; reify: instance-local method table. obj is a jreify carrying a method ht + -;; the protocol short-names it implements (for satisfies?/instance?). -(define-record-type jreify (fields methods protos) (nongenerative chez-jreify-v1)) -(define (reified-methods obj) (and (jreify? obj) (jreify-methods obj))) -;; (get reify k) / (:k reify) routes to a reify's ILookup valAt — clojure.spec.alpha -;; reifies fspec/regex specs as clojure.lang.ILookup and reads (:args spec) off them. -(register-get-arm! jreify? - (lambda (coll k d) - (let ((m (and (reified-methods coll) (hashtable-ref (reified-methods coll) "valAt" #f)))) - (if m (jolt-invoke m coll k d) d)))) -(define (make-reified methods-map . proto-names) - (let ((ht (make-hashtable string-hash string=?)) - (protos (if (and (pair? proto-names) (null? (cdr proto-names)) (jolt-coll-pred? (car proto-names))) - (seq->list (car proto-names)) proto-names))) - (for-each (lambda (p) (hashtable-set! ht (if (keyword? p) (keyword-t-name p) p) - (jolt-get methods-map p jolt-nil))) - (seq->list (jolt-keys methods-map))) - (make-jreify ht (map (lambda (p) (if (symbol-t? p) (symbol-t-name p) p)) protos)))) - -;; satisfies?: does obj's type implement the protocol? -(define (jolt-satisfies? proto obj) - (let* ((pn (jolt-get proto (keyword #f "name") jolt-nil)) - (pn-str (if (symbol-t? pn) (symbol-t-name pn) pn))) - (cond - ((jrec? obj) (type-satisfies? (jrec-tag obj) pn-str)) - ((jreify? obj) - (let ((short (last-dot pn-str))) - (and (memp (lambda (p) (string=? (last-dot p) short)) (jreify-protos obj)) #t))) - (else (let loop ((tags (value-host-tags obj))) - (cond ((null? tags) #f) - ((type-satisfies? (car tags) pn-str) #t) - (else (loop (cdr tags))))))))) -(define (last-dot s) - (let loop ((i (- (string-length s) 1))) - (cond ((< i 0) s) ((char=? (string-ref s i) #\.) (substring s (+ i 1) (string-length s))) (else (loop (- i 1)))))) -(define (memp pred lst) (cond ((null? lst) #f) ((pred (car lst)) lst) (else (memp pred (cdr lst))))) - -;; extenders: type-tags that extend a protocol via extend/extend-type/extend- -;; protocol, as symbols (extends? reads this). Inline deftype/defrecord impls are -;; excluded — only tags carrying the extend mark count, matching the JVM. -(define (extenders proto) - (let* ((pn (jolt-get proto (keyword #f "name") jolt-nil)) - (pn-str (if (symbol-t? pn) (symbol-t-name pn) pn)) - (out '())) - (vector-for-each - (lambda (tag) - (let ((ti (hashtable-ref type-registry tag #f))) - (when ti (let ((pi (hashtable-ref ti pn-str #f))) - (when (and pi (hashtable-ref pi extend-mark #f)) - (set! out (cons (jolt-symbol jolt-nil tag) out))))))) - (hashtable-keys type-registry)) - (if (null? out) jolt-nil (list->cseq out)))) - -;; jolt exception values (ex-info + host-constructed throwables) are ex-info-shaped -;; maps tagged :jolt/type :jolt/ex-info; (class …)/instance? read the JVM class off -;; the optional :jolt/class key, defaulting to clojure.lang.ExceptionInfo. -(register-str-render! jrec? - (lambda (v) - (let ((f (find-protocol-method (jrec-tag v) "Object" "toString"))) - (if f (jolt-invoke f v) - (let ((s (jrec-pr v))) (substring s 1 (string-length s))))))) - -;; `type` lives in natives-meta.ss: it needs jolt-meta for the :type -;; override and a total value->taxonomy mapping, so it sits with meta — a record -;; yields (jolt-symbol #f (jrec-tag x)), the ns.Name class-name symbol. - -(def-var! "clojure.core" "make-deftype-ctor" make-deftype-ctor) - -;; defrecord marks its type a record (deftype does not), keyed by the same -;; "ns.Name" tag make-deftype-ctor bakes — so jrec-record? distinguishes the two. -(define (register-record-type! name-sym) - (let ((tag (string-append (chez-current-ns) "." (symbol-t-name name-sym)))) - (hashtable-set! chez-record-type-tbl tag #t) - ;; a defrecord's class ancestry: replace the deftype IType row with the - ;; record interfaces (their closure supplies Associative/Seqable/ILookup/…), - ;; keeping any protocol interfaces already grafted by the inline - ;; registrations that ran between the deftype ctor and this call. - (let ((protos (filter (lambda (s) (not (string=? s "clojure.lang.IType"))) - (jch-direct-supers tag)))) - (jch-set-supers! tag (append protos - '("clojure.lang.IRecord" "clojure.lang.IObj" - "clojure.lang.IPersistentMap" "java.util.Map" - "clojure.lang.IHashEq" "java.io.Serializable"))))) - jolt-nil) -(def-var! "clojure.core" "register-record-type!" register-record-type!) -(def-var! "clojure.core" "make-protocol" make-protocol) -(def-var! "clojure.core" "register-protocol-methods!" register-protocol-methods!) -(def-var! "clojure.core" "register-method" register-method) -(def-var! "clojure.core" "register-inline-method" register-inline-method) -(def-var! "clojure.core" "register-inline-protocol!" register-inline-protocol!) -(def-var! "jolt.host" "set-field!" jolt-set-field!) -(def-var! "clojure.core" "protocol-dispatch" (lambda (pn mn obj rest) (protocol-dispatch pn mn obj rest))) -(def-var! "clojure.core" "protocol-dispatch1" (lambda (pn mn obj) (protocol-dispatch1 pn mn obj))) -(def-var! "clojure.core" "protocol-dispatch2" (lambda (pn mn obj a) (protocol-dispatch2 pn mn obj a))) -(def-var! "clojure.core" "protocol-dispatch3" (lambda (pn mn obj a b) (protocol-dispatch3 pn mn obj a b))) -(def-var! "clojure.core" "satisfies?" jolt-satisfies?) -(def-var! "clojure.core" "extenders" extenders) -(def-var! "clojure.core" "make-reified" (lambda (mm . rest) (apply make-reified mm rest))) -(def-var! "clojure.core" "record-method-dispatch" (lambda (obj m rest) (record-method-dispatch obj m rest))) diff --git a/host/chez/regex.ss b/host/chez/regex.ss deleted file mode 100644 index d320284..0000000 --- a/host/chez/regex.ss +++ /dev/null @@ -1,274 +0,0 @@ -;; regex on Chez via vendored irregex. -;; -;; Chez has no regex at all. We vendor -;; Alex Shinn's irregex (vendor/irregex, BSD) — a portable Scheme regex with -;; PCRE/Java-style STRING patterns — and wrap jolt's re-* surface over it. -;; -;; irregex maps cleanly onto the Clojure fns: irregex-match is an anchored -;; whole-string match (= re-matches), irregex-search finds the first match -;; anywhere (= re-find), irregex-match-substring extracts group N (0 = whole). -;; Results follow Clojure shape: a 0-group match is the whole string; a grouped -;; match is a jolt VECTOR [whole g1 ...] (a non-participating group is nil); a nil -;; result is jolt-nil; re-seq is a jolt seq (nil when there are no matches). -;; -;; The re-* fns are def-var!'d into clojure.core so prelude / -e code resolves -;; them at runtime (they're NOT subset native-ops: irregex's Unicode/property- -;; class semantics keep them out -;; of the subset-parity corpus). Loaded from rt.ss after def-var! is defined. - -;; irregex.scm is portable R[457]RS; two small adaptations for Chez's top level: -;; a cond-expand at expression position (Chez's is library-only), and `error` -;; called with a lone string (Chez's error wants who+msg). The wrapper normalizes -;; both without changing behavior for valid patterns. -(define-syntax cond-expand - (syntax-rules (else) - ((_ (else e ...)) (begin e ...)) - ((_ (else e ...) c ...) (begin e ...)) - ((_ (req e ...) c ...) (cond-expand c ...)) - ((_) (if #f #f)))) -(define %chez-error error) -(define (error . args) - (if (and (pair? args) (string? (car args))) - (apply %chez-error #f args) - (apply %chez-error args))) -(load "vendor/irregex/irregex.scm") - -;; irregex rejects a quantifier applied to anything that already contains one — -;; including a GROUP like (a+)* — because sre-repeater? recurses through submatch. -;; Java only rejects a DANGLING double quantifier (a**); it allows a quantifier on -;; a group whose body is quantified. Restrict the check to a bare leading * / + so -;; a** still errors but (a+)* parses (cuerdas's format tokenizer needs this). -(set! sre-repeater? - (lambda (sre) (and (pair? sre) (memq (car sre) '(* +)) #t))) - -;; Unicode property classes \p{...}: irregex's string syntax has no -;; \p{...}, so translate a fixed set of property names -;; to ASCII char classes before compiling. ASCII-only — \p{L} would need -;; UTF-8 high bytes counted as letters, which a Unicode-char Scheme string can't -;; reproduce byte-for-byte; the corpus tests ASCII inputs, where they agree. An -;; unmapped name is left as-is (irregex errors, as before — no new behavior). The -;; ORIGINAL source is kept for printing; only the compiled pattern is translated. -(define (prop-class name) - (cond - ;; L/Alpha: ASCII letters + non-ASCII up to just below the UTF-16 surrogate gap - ;; (D800). This covers essentially every real letter (Latin/Greek/Cyrillic/CJK/… - ;; live below D800); the supplementary planes above it are rare and a range that - ;; reaches them makes irregex's char-set construction call integer->char on a - ;; surrogate and crash. N/Z stay ASCII-only. - ((or (string=? name "L") (string=? name "Alpha")) "a-zA-Z\\x80-\\x{D7FF}") - ((string=? name "Lu") "A-Z") - ((string=? name "Ll") "a-z") - ((or (string=? name "N") (string=? name "Nd") (string=? name "Digit")) "0-9") - ((or (string=? name "Z") (string=? name "Zs")) " ") - ((string=? name "Ps") "([{") - ((string=? name "Pe") ")\\]}") - (else #f))) -;; Tracks whether the cursor is inside a [...] char class: a \p{X} there emits the -;; class CONTENT (inlined), standalone it emits a wrapping [X]. Escapes -;; (\[, \]) don't toggle the class. \P (negation) only wraps when standalone. -(define (translate-prop-classes src) - (let ((len (string-length src)) (out (open-output-string))) - (let loop ((i 0) (in-class #f)) - (if (fx>=? i len) - (get-output-string out) - (let ((c (string-ref src i))) - (cond - ;; \p{Name} / \P{Name} - ((and (char=? c #\\) (fx=? j len) #f) - ((char=? (string-ref src j) #\}) j) - (else (scan (fx+ j 1)))))) - (cls (and close (prop-class (substring src (fx+ i 3) close))))) - (cond - ((not cls) (write-char c out) (loop (fx+ i 1) in-class)) - (in-class (display cls out) (loop (fx+ close 1) in-class)) - (else - (display "[" out) - (when (char=? (string-ref src (fx+ i 1)) #\P) (display "^" out)) - (display cls out) (display "]" out) - (loop (fx+ close 1) in-class))))) - ;; any other escape: copy the pair verbatim, don't toggle class state - ((and (char=? c #\\) (fx=? i len) - (get-output-string out) - (let ((c (string-ref src i))) - (cond - ;; an escape pair: \w-style shorthand sets after-shorthand inside a class - ((and (char=? c #\\) (fx…)) -;; and groups with a flag irregex can't express are left untouched for irregex. -(define (regex-flag->opt c) - (cond ((char=? c #\s) 'single-line) ; DOTALL — . matches newline - ((char=? c #\i) 'case-insensitive) - ((char=? c #\m) 'multi-line) ; ^/$ match at line boundaries - (else #f))) -(define (regex-parse-flags src) - (let loop ((s src) (opts '())) - (if (and (>= (string-length s) 4) - (char=? (string-ref s 0) #\() (char=? (string-ref s 1) #\?)) - (let scan ((i 2) (fs '())) - (cond - ((>= i (string-length s)) (values (reverse opts) s)) - ((char=? (string-ref s i) #\)) - (let ((mapped (map regex-flag->opt fs))) - (if (and (pair? fs) (for-all (lambda (x) x) mapped)) - (loop (substring s (+ i 1) (string-length s)) (append opts mapped)) - (values (reverse opts) s)))) ; unmappable flag — leave as-is - ((char=? (string-ref s i) #\:) (values (reverse opts) s)) ; scoped group - (else (scan (+ i 1) (cons (string-ref s i) fs))))) - (values (reverse opts) s)))) - -;; A jolt regex value: the source string (for printing / str) + the compiled -;; irregex. regex? recognizes it; the printer renders #"source". -(define-record-type regex-t (fields source irx) (nongenerative jolt-regex-v1)) -;; A capturing pattern is compiled with irregex's BACKTRACKING matcher ('backtrack), -;; not its DFA. java.util.regex is itself a leftmost-first backtracking engine, so -;; this matches the JVM's submatch semantics; irregex's DFA is POSIX leftmost-longest -;; and, worse, leaks a non-participating alternation group's capture (e.g. -;; #"(?:([0-9])|([0-9])r([0-9]+))" on "2r11" left group 1 = "2"), which broke -;; tools.reader's number reader. Non-capturing patterns keep the fast DFA — with no -;; groups to read, its whole-match result is all a caller sees. The count comes from -;; a first cheap compile; a capturing pattern is recompiled once (patterns compile -;; once and cache in the regex-t). -(define (jolt-regex source) - (let-values (((opts pat) (regex-parse-flags source))) - (let* ((p (translate-prop-classes (escape-class-shorthand-dash pat))) - (irx (apply irregex p opts))) - (make-regex-t source - (if (> (irregex-num-submatches irx) 0) - (apply irregex p 'backtrack opts) - irx))))) -(define (jolt-regex? x) (regex-t? x)) -(define (jolt-re-pattern x) (if (regex-t? x) x (jolt-regex x))) - -;; An irregex match -> the Clojure result: whole string (no groups) or the -;; [whole g1 ... gn] vector (nil for a non-participating group). -(define (irx-result m) - (let ((n (irregex-match-num-submatches m))) - (if (= n 0) - (irregex-match-substring m 0) - (let loop ((i n) (acc '())) - (if (< i 0) - (apply jolt-vector acc) - (let ((s (irregex-match-substring m i))) - (loop (- i 1) (cons (if s s jolt-nil) acc)))))))) - -(define (jolt-re-matches re s) - (let ((m (irregex-match (regex-t-irx (jolt-re-pattern re)) s))) - (if m (irx-result m) jolt-nil))) - -;; A stateful matcher (java.util.regex.Matcher): the compiled pattern, the target -;; string, the next search position, and the last successful irregex match. re-find -;; over a matcher steps through non-overlapping matches; re-groups returns the -;; groups of the last one. -(define-record-type matcher-t - (fields irx str (mutable pos) (mutable last)) - (nongenerative jolt-matcher-v1)) -(define (jolt-re-matcher re s) - (make-matcher-t (regex-t-irx (jolt-re-pattern re)) s 0 #f)) -(define (jolt-matcher? x) (matcher-t? x)) - -;; re-find: stateless over (re s), or stateful over a matcher (advance + remember). -(define jolt-re-find - (case-lambda - ((re s) - (let ((m (irregex-search (regex-t-irx (jolt-re-pattern re)) s))) - (if m (irx-result m) jolt-nil))) - ((m) - (let* ((str (matcher-t-str m)) - (len (string-length str)) - (start (matcher-t-pos m)) - (mm (and (<= start len) (irregex-search (matcher-t-irx m) str start)))) - (if mm - (let ((ms (irregex-match-start-index mm 0)) - (e (irregex-match-end-index mm 0))) - (matcher-t-last-set! m mm) - ;; advance past this match: to its end, or one past a zero-width match - ;; (which may sit past the search origin, e.g. a lookahead/boundary). - (matcher-t-pos-set! m (if (> e ms) e (+ e 1))) - (irx-result mm)) - (begin (matcher-t-last-set! m #f) jolt-nil)))))) - -;; re-groups: the groups of the matcher's last successful find. Throws when no -;; match has succeeded, like Clojure's IllegalStateException "No match found". -(define (jolt-re-groups m) - (let ((last (matcher-t-last m))) - (if last (irx-result last) - (jolt-throw (jolt-ex-info "No match found" (jolt-hash-map)))))) - -;; java.util.regex.Matcher methods over a matcher-t. .matches anchors a full-region -;; match and remembers it for .group; .group n returns submatch n (0 = whole) or -;; nil; .groupCount is the pattern's capturing-group count. -(define (jolt-matcher-matches m) - (let ((mm (irregex-match (matcher-t-irx m) (matcher-t-str m)))) - (matcher-t-last-set! m mm) - (if mm #t #f))) -(define (jolt-matcher-group m . n) - (let ((last (matcher-t-last m))) - (if last - (let ((s (irregex-match-substring last (if (pair? n) (->idx (car n)) 0)))) - (if s s jolt-nil)) - (jolt-throw (jolt-ex-info "No match available" (jolt-hash-map)))))) -(define (jolt-matcher-group-count m) (irregex-num-submatches (matcher-t-irx m))) - -;; All non-overlapping matches, left to right. Advance past each match end (or by -;; one on a zero-width match). nil when there are no matches (Clojure: seq-able as -;; nil, so (if-let [m (re-seq ...)] ...) works). -(define (jolt-re-seq re s) - (let ((irx (regex-t-irx (jolt-re-pattern re))) - (len (string-length s))) - (let loop ((start 0) (acc '())) - (let ((m (and (<= start len) (irregex-search irx s start)))) - (if m - (let ((ms (irregex-match-start-index m 0)) - (e (irregex-match-end-index m 0))) - ;; to the match end, or one past a zero-width match (relative to its - ;; own start, which may be past the search origin). - (loop (if (> e ms) e (+ e 1)) (cons (irx-result m) acc))) - (list->cseq (reverse acc))))))) - -(def-var! "clojure.core" "re-pattern" jolt-re-pattern) -(def-var! "clojure.core" "re-matches" jolt-re-matches) -(def-var! "clojure.core" "re-find" jolt-re-find) -(def-var! "clojure.core" "re-seq" jolt-re-seq) -(def-var! "clojure.core" "re-matcher" jolt-re-matcher) -(def-var! "clojure.core" "re-groups" jolt-re-groups) -(def-var! "clojure.core" "regex?" jolt-regex?) diff --git a/host/chez/remint.sh b/host/chez/remint.sh deleted file mode 100755 index a39eed8..0000000 --- a/host/chez/remint.sh +++ /dev/null @@ -1,30 +0,0 @@ -#!/bin/sh -# Re-mint the checked-in Chez seed. Run after changing a seed source — the reader -# (host/chez/reader.ss), the analyzer/IR/backend (jolt-core/jolt/*.clj), or the -# clojure.core overlay (jolt-core/clojure/core/*.clj). Iterates bootstrap.ss from the -# current seed to a byte-fixpoint and overwrites host/chez/seed/. -set -e -root="$(CDPATH= cd -- "$(dirname -- "$0")/../.." && pwd)" -cd "$root" -tmp="$(mktemp -d)" -trap 'rm -rf "$tmp"' EXIT - -cp host/chez/seed/prelude.ss "$tmp/cur-p.ss" -cp host/chez/seed/image.ss "$tmp/cur-i.ss" -i=0 -while [ "$i" -lt 8 ]; do - i=$((i + 1)) - chez --script host/chez/bootstrap.ss \ - "$tmp/cur-p.ss" "$tmp/cur-i.ss" "$tmp/new-p.ss" "$tmp/new-i.ss" >/dev/null - if diff -q "$tmp/cur-p.ss" "$tmp/new-p.ss" >/dev/null \ - && diff -q "$tmp/cur-i.ss" "$tmp/new-i.ss" >/dev/null; then - cp "$tmp/new-p.ss" host/chez/seed/prelude.ss - cp "$tmp/new-i.ss" host/chez/seed/image.ss - echo "re-minted seed (converged after $i pass(es))" - exit 0 - fi - cp "$tmp/new-p.ss" "$tmp/cur-p.ss" - cp "$tmp/new-i.ss" "$tmp/cur-i.ss" -done -echo "re-mint did not converge in 8 passes" >&2 -exit 1 diff --git a/host/chez/rt.ss b/host/chez/rt.ss deleted file mode 100644 index 0649697..0000000 --- a/host/chez/rt.ss +++ /dev/null @@ -1,639 +0,0 @@ -;; The minimal Chez RT the emitted Scheme rests on. -;; -;; Sits above the value model (values.ss) and below an emitted program. Adds the -;; two things the back end's output references that aren't in the value layer: -;; 1. the var-cell late-binding registry (Clojure vars — a global root that a -;; reference reads at call time, so redefinition / mutual recursion work); -;; 2. the rt primitive shims the emitter names (jolt-inc/dec/not) and jolt's -;; number printing (all jolt numbers model Clojure doubles; integer-valued -;; print without a trailing ".0"). -;; -;; Emitted programs do `(load "host/chez/rt.ss")`; this loads values.ss in turn. - -(load "host/chez/values.ss") -;; Resolve a libc entry point at RUN time. A literal (foreign-procedure "name" …) -;; in COMPILED code becomes a fasl relocation resolved when the boot loads — on a -;; platform lacking the symbol (chmod/sigaddset on Windows) that kills the boot -;; before any guard can run. eval defers the lookup to evaluation time, where the -;; guard works; returns #f when the entry doesn't exist. -(define (jolt-foreign-proc-safe name args res) - (guard (e (#t #f)) - (load-shared-object #f) - (and (foreign-entry? name) - (eval `(foreign-procedure ,name ,args ,res))))) - -(load "host/chez/collections.ss") -(load "host/chez/seq.ss") - -;; --- rt arithmetic / logic shims (named in the emitter's native-ops) ---------- -(define (jolt-inc x) (+ x 1)) -(define (jolt-dec x) (- x 1)) -;; Coerce a ^long-hinted argument to a fixnum at fn entry, the way the JVM's -;; longCast coerces a primitive-long parameter: truncate a flonum toward zero, -;; pass an exact integer through, error if it doesn't fit a fixnum or isn't a -;; number. The hint is a promise the value is a fixnum-range long; the body's fx* -;; ops rely on it. (^double params coerce with the built-in exact->inexact.) -;; A ^long is a 64-bit value; a Chez fixnum is only 61-bit, so a value that -;; overflows the fixnum range (a full-width long, e.g. from unchecked / wrapping -;; arithmetic) passes through as an exact integer rather than erroring. fx ops in -;; the body still require fixnums (they raise on a bignum), but generic / -;; unchecked-* ops handle it. -(define (jolt->fx x) - (cond ((fixnum? x) x) - ((and (number? x) (exact? x) (integer? x)) x) - ((flonum? x) (exact (truncate x))) - ((rational? x) (exact (truncate x))) - (else (error 'jolt "^long hint: not a number" x)))) -;; jolt `not`: only nil and false are falsey. -(define (jolt-not x) (if (jolt-truthy? x) #f #t)) - -;; --- exceptions -------------------------------------------------------------- -;; throw raises a Chez condition WRAPPING the jolt value; catch (emitted as -;; `guard`) and jolt-report-uncaught unwrap it back via jolt-unwrap-throw. -;; Raising the value RAW broke when a throw crossed the host/`eval` boundary: -;; Chez re-wrapped the non-condition into a compound condition whose -;; message-extraction APPLIES the value (crashing on an empty-map :data -> -;; "attempt to apply non-procedure"), and the real message was lost. A real -;; condition propagates intact through any number of eval boundaries. -;; Capture the live continuation at the throw site (identity-tagged with the -;; thrown value) so an uncaught error can walk the native frames back to a Clojure -;; stack trace (source-registry.ss). call/cc is paid only on a throw, never per -;; call; the captured k is walked, never invoked. -(define jolt-throw-cont (make-thread-parameter #f)) - -;; --- tail-frame history: a ring of rings (opt-in) ---------------------------- -;; TCO erases tail-called frames from the native continuation, so an uncaught -;; error's backtrace shows only the surviving non-tail spine — the immediate error -;; site is often a tail call and is missing. When tracing is enabled (JOLT_TRACE, -;; wired in compile-eval.ss), each compiled fn records its frame-name on entry, and -;; the reporter reads this history to recover TCO-elided frames. -;; -;; The store is MIT-Scheme's "history" shape — a ring of rings. The OUTER ring -;; holds one RIB per non-tail subproblem (the real call spine); each rib's INNER -;; ring holds the recent tail-calls made AT that subproblem. A non-tail entry -;; advances the outer ring (a fresh rib); a tail entry rotates the current rib's -;; inner ring. So a tight tail loop (mutual recursion, a non-recur self-tail-call) -;; churns ONE rib's small inner ring instead of flushing the outer spine — the -;; caller context that led into the loop survives. Both rings are fixed-size, so -;; the whole history is bounded: a constant space factor, NOT a change to the -;; asymptotic space TCO guarantees. -;; -;; Whether an entry is tail or non-tail is set by the CALLER: the emitter marks a -;; tail call with (jolt-trace-mark! #t) right before it; a non-tail entry is the -;; default. NOTE this is best-effort: a tail call routed through jolt-invoke to a -;; target that has no entry prologue (a core/native fn, an anonymous fn held in a -;; var) does not consume the mark, so a following non-tail frame can be mislabeled -;; as a tail rotation — a cosmetic mis-grouping in the trace, never a wrong result. -(define jolt-trace-outer-size 48) ; ribs (non-tail spine depth kept) -(define jolt-trace-inner-size 6) ; tail-calls kept per subproblem -;; A history: #(ribs-vector outer-head outer-count). A rib: #(name-vector head count). -(define (jolt-make-rib) (vector (make-vector jolt-trace-inner-size #f) 0 0)) -(define (jolt-make-history) - (let ((ribs (make-vector jolt-trace-outer-size #f))) - (let loop ((i 0)) - (when (fx? k cnt) - (reverse acc) - (loop (fx+ k 1) - (cons (vector-ref buf (fxmod (fx+ (fx- head k) jolt-trace-inner-size) - jolt-trace-inner-size)) - acc)))))) -;; The whole history flattened to frame-names, most-recent (deepest) first: -;; current rib's tail-history, then its non-tail caller's, and so on outward. -(define (jolt-trace-snapshot) - (let ((h (jolt-trace-ring))) - (if (not h) '() - (let* ((ribs (vector-ref h 0)) (oh (vector-ref h 1)) (oc (vector-ref h 2))) - (let loop ((k 1) (acc '())) - (if (fx>? k oc) - (apply append (reverse acc)) - (let ((idx (fxmod (fx+ (fx- oh k) jolt-trace-outer-size) jolt-trace-outer-size))) - (loop (fx+ k 1) (cons (jolt-rib-names (vector-ref ribs idx)) acc))))))))) - -(define-condition-type &jolt-throw &condition - make-jolt-throw-condition jolt-throw-condition? - (value jolt-throw-condition-value)) -;; Fallback &message for a leaked condition; the real message always comes from -;; the unwrapped value via ex-message. -(define (jolt-throw-message v) - (if (and (pmap? v) - (jolt=2 (jolt-get v jolt-kw-ex-type jolt-nil) jolt-kw-ex-info)) - (let ((m (jolt-get v jolt-kw-message jolt-nil))) - (if (string? m) m "jolt error")) - "jolt error")) -(define (jolt-throw v) - (call/cc (lambda (k) - (jolt-throw-cont (cons v k)) - (raise (condition (make-message-condition (jolt-throw-message v)) - (make-jolt-throw-condition v)))))) -(define (jolt-unwrap-throw x) - (if (jolt-throw-condition? x) (jolt-throw-condition-value x) x)) -;; ex-info builds the tagged map {:jolt/type :jolt/ex-info :message :data :cause} -;; — a real jolt-hash-map, so the ex-data/ex-message/ex-cause tier fns read it -;; via jolt-get for free. Arity 2 (msg data) or 3 (msg data cause). -(define jolt-kw-ex-type (keyword "jolt" "type")) -(define jolt-kw-ex-info (keyword "jolt" "ex-info")) -(define jolt-kw-message (keyword #f "message")) -(define jolt-kw-data (keyword #f "data")) -(define jolt-kw-cause (keyword #f "cause")) -(define (jolt-ex-info msg data . more) - (jolt-hash-map jolt-kw-ex-type jolt-kw-ex-info - jolt-kw-message msg - jolt-kw-data data - jolt-kw-cause (if (null? more) jolt-nil (car more)))) -;; A host-constructed throwable (RuntimeException. etc.): an ex-info-shaped map -;; carrying its canonical JVM :jolt/class, so (class …) / instance? / .getMessage / -;; ex-message all reflect the real type. Plain ex-info has no :jolt/class (its class -;; defaults to clojure.lang.ExceptionInfo), so those maps stay byte-identical. -(define jolt-kw-class (keyword "jolt" "class")) -(define (jolt-host-throwable class-name msg . more) - (jolt-hash-map jolt-kw-ex-type jolt-kw-ex-info - jolt-kw-class class-name - jolt-kw-message msg - jolt-kw-data jolt-nil - jolt-kw-cause (if (null? more) jolt-nil (car more)))) - -;; --- host interop ------------------------------------------------------------ -;; (.method target arg*) lowers to (jolt-host-call "method" target arg*). JVM -;; interop has no general Chez analog, but the few methods jolt-core's io tier -;; calls map onto Chez equivalents: a writer's .write is a port display; a File's -;; .isDirectory / .listFiles work over a path string (Chez has no File type, so -;; file-seq's File branch is unreachable here — these keep the forms honest). An -;; unsupported method raises rather than silently returning nil. -(define (jolt-host-call method target . args) - (cond - ((string=? method "write") (display (car args) target) jolt-nil) - ((string=? method "isDirectory") (if (file-directory? target) #t #f)) - ((string=? method "listFiles") (list->cseq (directory-list target))) - (else (error 'jolt-host-call (string-append "unsupported host method: ." method))))) - -;; --- var cells: late-bound global roots (Clojure vars) ----------------------- -;; A var is a mutable cell keyed by "ns/name". A `:def` sets the root; a `:var` -;; reference reads it at use time (late binding), so a forward/mutually-recursive -;; reference resolves to whatever the cell holds when the call actually runs. -;; declare / (def name) with no init reserves a cell holding this placeholder -;; until the real def overwrites it (a forward reference resolves to the cell, and -;; correct code never reads it before the binding def runs). -(define jolt-unbound (string->symbol "#")) -;; `defined?` distinguishes a genuinely interned var (def / declare / a native-op -;; cell) from a cell lazily materialised by a forward `var-deref` / `(var x)` on a -;; not-yet-defined name — `resolve` returns the cell iff defined?. -;; ns-unmap clears it. Avoids the (def x nil) edge of probing the root. -(define-record-type var-cell (fields ns name (mutable root) (mutable defined?)) (nongenerative var-cell-v2)) -(define var-table (make-hashtable string-hash string=?)) -(define (jolt-var ns name) - (let ((k (string-append ns "/" name))) - (or (hashtable-ref var-table k #f) - (let ((c (make-var-cell ns name jolt-nil #f))) - (hashtable-set! var-table k c) - c)))) -;; non-creating lookup (resolve / find-var / ns-unmap): #f when absent, so a -;; probe never interns an empty cell. -(define (var-cell-lookup ns name) (hashtable-ref var-table (string-append ns "/" name) #f)) -(define (var-deref ns name) (var-cell-root (jolt-var ns name))) -;; def-var! / declare-var! return the VAR CELL, not the value — Clojure's `def` -;; evaluates to #'ns/name (a first-class var), so (var? (def x 1)) is true and -;; (pr-str (def x 1)) is "#'ns/x". The prelude's def-var! forms discard the -;; return, so this is transparent there. -;; proc -> (ns . name) for the var it was def'd into, so (class a-fn) can report a -;; JVM-style class name and clojure.spec.alpha's fn-sym can recover the symbol of a -;; bare-fn predicate. Weak so GC'd fns drop out. Last def of a given proc wins. -(define proc-name-tbl (make-weak-eq-hashtable)) -(define (def-var! ns name v) - ;; first def of a given proc wins, so an alias like (def inc' inc) — which binds - ;; the SAME proc to a second var — doesn't rename inc. - (when (and (procedure? v) (not (hashtable-contains? proc-name-tbl v))) - (hashtable-set! proc-name-tbl v (cons ns name))) - (let ((c (jolt-var ns name))) (var-cell-root-set! c v) (var-cell-defined?-set! c #t) c)) -;; jolt.host/throwable — build a typed throwable a library can throw so (class …), -;; instance?, .getMessage and ex-message all reflect the named JVM class (e.g. an -;; http client throwing java.net.ConnectException). Strictly better than a -;; hand-rolled :jolt/ex-info table, which carries only the class. -(def-var! "jolt.host" "throwable" jolt-host-throwable) -;; var def-time metadata: the :def emit passes the def's reader meta -;; (^:private / ^Type tag / docstring -> {:doc}) here, stored in an eq side-table -;; keyed by the cell. jolt-meta (natives-meta.ss) merges it onto {:ns :name}, -;; which it derives from the cell — so EVERY var (plain def, native-op, declare) -;; reports {:ns :name} like Clojure, with the user meta layered on when present. -(define var-meta-table (make-eq-hashtable)) -(define jolt-kw-var-ns (keyword #f "ns")) -(define jolt-kw-var-name (keyword #f "name")) -(define (def-var-with-meta! ns name v m) - (let ((c (def-var! ns name v))) (hashtable-set! var-meta-table c m) c)) -;; runtime-macro registry: a var whose root holds a macro -;; expander fn is flagged here, so the ON-CHEZ analyzer's form-macro?/form-expand-1 -;; (host-contract.ss) expand it. The prelude emits each core/stdlib defmacro as a -;; def-var! of its (cross-compiled) expander followed by (mark-macro! ns name). -;; Keyed by cell (eq), like var-meta-table — survives a later (def name ...) that -;; replaces the expander but keeps the same cell, matching Clojure (a defmacro IS a -;; def whose var carries :macro). -(define var-macro-table (make-eq-hashtable)) -(define (mark-macro! ns name) - (let ((c (jolt-var ns name))) (hashtable-set! var-macro-table c #t) c)) -(define (macro-var? cell) (and cell (hashtable-ref var-macro-table cell #f) #t)) -;; declare / (def name) with no init: reserve the cell ONLY if absent. An -;; existing root is left intact — Clojure's (def x) with no init does not clobber -;; a prior binding (do (def x 7) (def x) x) => 7. Returns the cell either way. -(define (declare-var! ns name) - (let ((k (string-append ns "/" name))) - (or (hashtable-ref var-table k #f) - (let ((c (make-var-cell ns name jolt-unbound #t))) ; declared => interned/resolvable - (hashtable-set! var-table k c) - c)))) - -;; regex: defines regex-t + the re-* fns (def-var!'d into -;; clojure.core), so it loads after def-var! and before the printer below (which -;; renders a regex-t as #"source"). -(load "host/chez/regex.ss") - -;; atoms: host-coupled mutable cells; def-var!'d into clojure.core -;; (atom/deref/swap!/reset! + the compare/vals kernel). Loads after def-var! and -;; jolt-invoke (seq.ss) / jolt= (values.ss) / jolt-vector (collections.ss). -(load "host/chez/atoms.ss") - -;; type predicates + simple accessors: seed natives the overlay -;; assumes (map?/vector?/nil?/number?/.../name/namespace), def-var!'d into -;; clojure.core. Loads after the value-model record predicates they wrap. -(load "host/chez/predicates.ss") - -;; --- jolt number printing ---------------------------------------------------- -;; jolt has a numeric tower (exact integer / ratio / double, distinguished by -;; class). Exact integer-valued values print without a ".0" ((+ 1 2) -> "3"); -;; a double prints with one ((* 1.0 5) -> "5.0", as the JVM does). -(define (jolt-num->string x) - (cond - ;; the -e / element printer renders the infinities and NaN in READABLE form - ;; (##Inf reads back, like Clojure's REPL/pr); str/print uses "Infinity"/"NaN" - ;; (see jolt-str-render-one in converters.ss). - ((and (flonum? x) (fl= x +inf.0)) "##Inf") - ((and (flonum? x) (fl= x -inf.0)) "##-Inf") - ((and (flonum? x) (not (fl= x x))) "##NaN") - ((and (exact? x) (integer? x)) (number->string x)) - (else (number->string x)))) - -;; Program-final-value printer. jolt's `-e` prints in str-style: strings raw (no -;; quotes), chars as `\c`/`\newline`, collections recursively. NOTE: maps/sets -;; render in HAMT-iteration order, which is not a stable insertion order — -;; so unordered values are compared via `=` (true/false), not printed form. -(define (jolt-str-join strs) - (cond ((null? strs) "") ((null? (cdr strs)) (car strs)) - (else (string-append (car strs) " " (jolt-str-join (cdr strs)))))) -(define (jolt-char->string c) - (string-append "\\" (case c ((#\newline) "newline") ((#\space) "space") ((#\tab) "tab") - ((#\return) "return") (else (string c))))) -;; Program-final printer: jolt's `-e` is str-style at the top level, where a -;; bare nil renders as the empty string (a nil ELEMENT inside a collection still -;; prints "nil", which jolt-pr-str handles). -(define (jolt-final-str x) (if (jolt-nil? x) "" (jolt-pr-str x))) -;; --- *print-level* / *print-length* ----------------------------------------- -;; Both vars default to nil (= unlimited). A non-nil number limits collection -;; nesting depth / element count in BOTH printers (jolt-pr-str here and -;; jolt-pr-readable in printing.ss). Cells captured lazily — the vars are def'd -;; after rt.ss. The nil default takes a fast path: jolt-print-hash? is #f and the -;; limited-string walkers never truncate. -(define plevel-cell #f) -(define plength-cell #f) -(define (jolt-print-level) - (unless plevel-cell (set! plevel-cell (jolt-var "clojure.core" "*print-level*"))) - (let ((v (jolt-var-get plevel-cell))) (and (number? v) v))) -(define (jolt-print-length) - (unless plength-cell (set! plength-cell (jolt-var "clojure.core" "*print-length*"))) - (let ((v (jolt-var-get plength-cell))) (and (number? v) v))) -(define jolt-print-depth (make-thread-parameter 0)) -;; A collection at depth >= *print-level* renders as "#". The top-level collection -;; is depth 0, so *print-level* 0 collapses any collection, 1 keeps the outermost. -(define (jolt-print-hash?) - (let ((lvl (jolt-print-level))) (and lvl (fx>=? (jolt-print-depth) lvl)))) -;; Rendered element strings of a vector (by index), honoring *print-length*: at -;; most N, then "...". render-one runs at the current (already bumped) depth. -(define (jolt-limited-vec-strs x render-one) - (let ((len (pvec-count x)) (lim (jolt-print-length))) - (let loop ((i 0) (acc '())) - (cond ((fx>=? i len) (reverse acc)) - ((and lim (fx>=? i lim)) (reverse (cons "..." acc))) - (else (loop (fx+ i 1) (cons (render-one (pvec-nth-d x i jolt-nil)) acc))))))) -;; Rendered element strings of a seq, walked lazily so an infinite seq is realized -;; only up to *print-length*. -(define (jolt-limited-seq-strs s render-one) - (let ((lim (jolt-print-length))) - (let loop ((s s) (i 0) (acc '())) - (cond ((jolt-nil? s) (reverse acc)) - ((and lim (fx>=? i lim)) (reverse (cons "..." acc))) - (else (loop (jolt-seq (seq-more s)) (fx+ i 1) (cons (render-one (seq-first s)) acc))))))) -;; Truncate an already-collected element-string list (set / map, finite) to -;; *print-length*, appending "..." when more remain. -(define (jolt-limited-list-strs strs) - (let ((lim (jolt-print-length))) - (if (not lim) strs - (let loop ((s strs) (i 0) (acc '())) - (cond ((null? s) (reverse acc)) - ((fx>=? i lim) (reverse (cons "..." acc))) - (else (loop (cdr s) (fx+ i 1) (cons (car s) acc)))))))) -;; bump the print depth around a collection's element rendering — but only when -;; *print-level* is set, since depth is consulted only to enforce it. With the -;; common nil default this is a plain begin, so printing pays no parameterize. -(define-syntax with-deeper-print - (syntax-rules () - ((_ body ...) (if (jolt-print-level) - (parameterize ((jolt-print-depth (fx+ (jolt-print-depth) 1))) body ...) - (begin body ...))))) - -;; A host shim registers a type's str-style rendering via register-pr-str-arm! (or -;; register-pr-arm! in printing.ss for both printers at once) instead of -;; set!-wrapping jolt-pr-str. Disjoint types, checked before the base cases. -(define jolt-pr-str-arms '()) -(define (register-pr-str-arm! pred render) - (set! jolt-pr-str-arms (cons (cons pred render) jolt-pr-str-arms))) -(define (jolt-pr-str-base x) - (cond - ((jolt-nil? x) "nil") - ((eq? x #t) "true") - ((eq? x #f) "false") - ((number? x) (jolt-num->string x)) - ((string? x) x) - ((char? x) (jolt-char->string x)) - ((keyword? x) (let ((ns (keyword-t-ns x))) - (if ns (string-append ":" ns "/" (keyword-t-name x)) (string-append ":" (keyword-t-name x))))) - ((jolt-symbol? x) (let ((ns (symbol-t-ns x))) - (if (or (jolt-nil? ns) (not ns) (eq? ns '())) (symbol-t-name x) - (string-append ns "/" (symbol-t-name x))))) - ((regex-t? x) (string-append "#\"" (regex-t-source x) "\"")) - ((pvec? x) (if (jolt-print-hash?) "#" - (with-deeper-print - (string-append "[" (jolt-str-join (jolt-limited-vec-strs x jolt-pr-str)) "]")))) - ((pset? x) (if (jolt-print-hash?) "#" - (with-deeper-print - (string-append "#{" (jolt-str-join (jolt-limited-list-strs - (pset-fold x (lambda (e a) (cons (jolt-pr-str e) a)) '()))) "}")))) - ((pmap? x) (if (jolt-print-hash?) "#" - (with-deeper-print - (string-append "{" (jolt-str-join (jolt-limited-list-strs - (pmap-fold x (lambda (k v a) (cons (string-append (jolt-pr-str k) " " (jolt-pr-str v)) a)) '()))) "}")))) - ;; lists / cons / lazy seqs all print as (...) — forces a finite seq (or up to - ;; *print-length* of an infinite one). - ((empty-list-t? x) (if (jolt-print-hash?) "#" "()")) - ((cseq? x) (if (jolt-print-hash?) "#" - (with-deeper-print - (string-append "(" (jolt-str-join (jolt-limited-seq-strs x jolt-pr-str)) ")")))) - (else (format "~a" x)))) -(define (jolt-pr-str x) - (let loop ((as jolt-pr-str-arms)) - (cond ((null? as) (jolt-pr-str-base x)) - (((caar as) x) ((cdar as) x)) - (else (loop (cdr as)))))) - -;; converters + string ops: str/subs/vec/keyword/symbol/compare/int/ -;; double/gensym — host-coupled seed natives def-var!'d into clojure.core. Loaded -;; LAST because `str` reuses jolt-pr-str (defined just above). -(load "host/chez/converters.ss") - -;; transients: copy-on-write transient collections + persistent disj; -;; extends get/count/contains? to see through a transient. After collections.ss -;; (the persistent ops it delegates to). -(load "host/chez/transients.ss") - -;; seq-native shims: mapcat/take-while/drop-while/partition/sort + -;; reduced/reduced?/identical? — seed-native fns the overlay assumes are core -;; natives. Over the seq layer + jolt-compare, so loaded after converters.ss. -(load "host/chez/natives-seq.ss") - -;; readable printer + output seams: __pr-str1/__write/ -;; __with-out-str/__eprint/__eprintf — the host seams the overlay print family -;; (pr-str/pr/prn/print/println/*-str) is built on. After converters.ss (uses -;; jolt-pr-str/jolt-str-join) + seq.ss (jolt-invoke). -(load "host/chez/printing.ss") - -;; collection constructors + rand: bind the public -;; clojure.core names hash-map/hash-set/array-map/set/rand to the existing -;; pmap/pset ctors. After collections.ss (the ctors) + seq.ss (seq->list). -(load "host/chez/natives-coll.ss") - -;; bit ops + parse-long/parse-double: host-coupled scalar -;; seed natives over the all-flonum number model. -(load "host/chez/natives-num.ss") - -;; multimethods: defmulti/defmethod dispatch runtime. Needs jolt-invoke -;; (seq.ss), jolt=/key-hash/jolt-hash-map (collections.ss), jolt-atom? (atoms.ss), -;; jolt-pr-str (above), and the var-cell machinery — so loaded last. -(load "host/chez/multimethods.ss") - -;; the single JVM class/interface graph — value-host-tags, instance?, isa?/supers, -;; and the exception hierarchy all derive from it. Before records.ss so -;; value-host-tags can build on jch-tags. -(load "host/chez/java/class-hierarchy.ss") - -;; records + protocols: defrecord/deftype/defprotocol/ -;; extend-type/reify. A jrec record type set!-extended into the collection -;; dispatchers + a protocol registry. After multimethods.ss (chez-current-ns) and -;; the dispatchers/printers it wraps (collections/seq/values/converters/printing/ -;; transients). -(load "host/chez/records.ss") -(load "host/chez/java/records-interop.ss") ; exception hierarchy + instance-check taxonomy - -;; metadata: meta / with-meta over an identity-keyed -;; side-table. After records.ss (jrec) + the collection ctors it copies. -(load "host/chez/natives-meta.ss") - -;; host class tokens: bare class names (String/Keyword/File...) -> -;; canonical JVM class-name strings + (class x). After natives-meta.ss (jolt-type) -;; and the printer (jolt-str-render-one). -(load "host/chez/java/host-class.ss") - -;; dynamic vars: *clojure-version* / *unchecked-math* constants the host -;; binds natively. After collections.ss (jolt-hash-map) + def-var!. -(load "host/chez/dynamic-var-defaults.ss") - -;; host tables + sorted collections: jolt.host/tagged-table/ -;; ref-put!/ref-get + the 25-sorted tier's runtime (sorted-map/sorted-set routed -;; through their :ops table). Loaded LAST — wraps the jrec-extended dispatchers -;; (records.ss), jolt-disj (transients.ss), and value-host-tags (records.ss). -(load "host/chez/host-table.ss") - -;; lazy-seq bridge: make-lazy-seq / coll->cells over the -;; cseq model — unblocks every overlay fn built on the lazy-seq macro (repeat/ -;; iterate/cycle/dedupe/take-nth/keep/interpose/reductions/tree-seq/lazy-cat). -;; Loaded LAST so %ls-seq captures the fully-extended (sorted-aware) jolt-seq. -(load "host/chez/lazy-bridge.ss") - -;; transducer surface: native volatile boxes, cat, + -;; the transduce/sequence entry points over into-xform/reduce-seq. After -;; natives-seq.ss (into-xform), seq.ss (reduce-seq) + atoms.ss (deref). -(load "host/chez/natives-transduce.ss") - -;; vars as first-class objects: var?/var-get/deref/invoke/=/ -;; pr-str over the rt.ss var-cell. After natives-transduce.ss (chains deref) + the -;; printers. emit lowers :the-var to (jolt-var ns name). -(load "host/chez/vars.ss") - -;; misc scalar natives: UUID (random-uuid/parse-uuid/uuid?), format/ -;; printf, tagged-literal, bigint. After the printers + converters (str/pr-str of -;; a uuid). Overlay names (uuid?/random-uuid/parse-uuid/tagged-literal?) re-asserted -;; in post-prelude.ss. -(load "host/chez/natives-misc.ss") - -;; format / printf: the %-directive engine. After natives-misc.ss + converters.ss -;; (jolt-str-render-one). -(load "host/chez/natives-format.ss") - -;; namespaces: the namespace value model — find-ns/ns-name/ -;; all-ns/the-ns/create-ns/in-ns/ns-publics/ns-map/ns-interns/ns-aliases/resolve/ -;; find-var/ns-unmap/*ns*, over the var-table + chez-current-ns. Loaded LAST: needs -;; var-cell + var-cell-defined?, jolt-symbol/jolt-hash-map/jolt-assoc, chez-current-ns -;; (multimethods.ss), list->cseq (seq.ss), and the fully-patched printers (vars.ss). -(load "host/chez/ns.ss") - -;; dynamic var binding: the per-thread binding stack + -;; push/pop/get-thread-bindings/__thread-bound?/var-set/alter-var-root/__local-var. -;; Chains var-deref (rt.ss) and jolt-var-get (vars.ss) onto the stack, so a `binding` -;; frame is seen by every var read. Loaded LAST: needs the fully-extended var-read -;; paths + jolt-hash-map/pmap-fold/pmap-assoc (collections.ss). -(load "host/chez/dyn-binding.ss") - -;; java.lang.String method interop: jolt-string-method, the -;; portable String/CharSequence surface record-method-dispatch falls through to on -;; a string target. After regex.ss (jolt-re-pattern/regex-t-irx) + records.ss -;; (which references jolt-string-method). -(load "host/chez/java/natives-str.ss") - -;; host class statics + constructors: host-static-ref/ -;; host-static-call/host-new + the jhost method registry. Loads LAST — it extends -;; record-method-dispatch (records.ss) and reuses natives-str helpers (str-trim, -;; ascii-string-down, re-split, str-split-drop-trailing) + the regex-t accessors. -(load "host/chez/java/host-static.ss") ; registries + jhost + coercion helpers -(load "host/chez/java/host-static-methods.ss") ; Class/member static methods + fields -(load "host/chez/java/host-static-classes.ss") ; instantiable host object classes -(load "host/chez/java/byte-buffer.ss") ; java.nio.ByteBuffer over a byte-array - -;; generic dot-form dispatch: field access + map/vector member access -;; for the `.` / `.-field` desugar. Loads after host-static.ss so it wraps every -;; record-method-dispatch arm (jhost/number/regex/jrec/string) and falls through. -(load "host/chez/java/dot-forms.ss") - -;; java.io.File + host file I/O: path-backed jfile record, slurp/spit/ -;; flush, file-seq dir primitives, clojure.java.io/file. Loads LAST so its jfile -;; arm wraps the fully-built record-method-dispatch and the str/type/instance-check -;; extensions sit over every prior shim. -(load "host/chez/java/io.ss") - -;; #inst values + java.time formatting: jinst (RFC3339 ms) + -;; DateTimeFormatter/Instant/ZoneId/LocalDateTime/FormatStyle/Locale/Date. Loads -;; LAST — it extends record-method-dispatch / jolt-get / jolt= / jolt-hash / -;; jolt-pr-str / jolt-type / instance-check and uses host-static.ss's registries. -(load "host/chez/java/inst-time.ss") - -;; java.time value types: LocalDate / LocalTime / LocalDateTime / Instant as -;; tz-free jhost values (epoch-day / nano-of-day / epoch-ms). Loads after -;; inst-time.ss — it reuses its civil<->days helpers, the jhost registries, and -;; re-registers a few LocalDateTime/Instant statics to use the richer reps. -(load "host/chez/java/java-time.ss") - -;; Chez-side data reader: read-string / __parse-next / -;; __read-tagged. Loads after inst-time.ss — __read-tagged reuses its #uuid/#inst -;; constructors, and the reader needs the full value/collection layer above. -(load "host/chez/reader.ss") - -;; clojure.math: native flonum-math shims def-var!'d into the -;; clojure.math ns. Self-contained (only def-var! + Chez math), order-independent. -(load "host/chez/java/math.ss") - -;; reader/macro runtime support: #?() feature set, reader-conditional + re-matcher -;; tagged-map ctors, macroexpand. After ns.ss; macroexpand call-time-refs the macro -;; table (host-contract) + analyzer ctx. -(load "host/chez/natives-reader.ss") - -;; Java-style arrays: object/typed array constructors + a jolt-array -;; backing; extends count/nth/seq/get/ref-put! so the overlay aget/aset/alength see -;; it. After the dispatchers it chains. -(load "host/chez/java/natives-array.ss") - -;; java.io byte/char streams (FileInputStream/…/ByteArrayOutputStream/Buffered*) -;; over Chez ports. After io.ss (extends its slurp/__close/reader-jhost?) and -;; natives-array.ss (the byte-array <-> bytevector bridge). -(load "host/chez/java/io-streams.ss") - -;; clojure.lang.PersistentQueue: a functional queue + EMPTY static. -;; Chains seq/count/empty?/peek/pop/conj/sequential?/class/instance?/printer, so -;; load after natives-array (the dispatchers it extends). -(load "host/chez/java/natives-queue.ss") - -;; syntax-quote form builders: __sqcat/__sqvec/__sqmap/__sqset/ -;; __sq1, def-var!'d into clojure.core. A cross-compiled macro expander (analyzer -;; on Chez) calls these to build its expansion as reader forms. Needs the -;; collection/seq layer + def-var!; order-independent past those. -(load "host/chez/syntax-quote.ss") - -;; concurrency: real OS-thread futures + blocking promises, shared-heap -;; (JVM) semantics. Loaded LAST — chains the fully-built jolt-deref and conveys the -;; thread-local binding stack (dyn-binding.ss) into workers. pmap/pcalls/pvalues -;; (overlay, over `future`) light up once future-call exists here. -(load "host/chez/java/concurrency.ss") - -;; clojure.core.async: real-thread blocking channels + go/go-loop/ -;; thread macros, def-var!'d into clojure.core.async. After concurrency.ss (reuses -;; ms->duration) and the collection/seq layer. -(load "host/chez/java/async.ss") - -;; BigDecimal: the jbigdec value type + bigdec/decimal?/class/equality/ -;; printing. Loads LAST so its set!-wraps of jolt-class/jolt=2/the printers sit -;; outermost over every earlier extension. -(load "host/chez/java/bigdec.ss") - -;; Native stack traces: jv$ns$name -> source registry + continuation frame walk + -;; uncaught-throwable renderer. After the printers/equality it relies on. -(load "host/chez/source-registry.ss") diff --git a/host/chez/run-corpus.ss b/host/chez/run-corpus.ss deleted file mode 100644 index 4dbad37..0000000 --- a/host/chez/run-corpus.ss +++ /dev/null @@ -1,205 +0,0 @@ -;; run-corpus.ss — the standing correctness gate. -;; -;; Loads the checked-in seed (host/chez/seed/{prelude,image}.ss) + the spine, -;; reads test/chez/corpus.edn, and for each row evaluates :actual and -;; :expected through jolt-compile-eval and compares by value-equality (jolt=). The -;; corpus :expected is JVM-sourced (test/conformance/regen-corpus.clj), so this -;; measures jolt-on-Chez against reference Clojure. -;; -;; Each case runs as its own top-level program (a top-level do unrolls, so a macro -;; defined earlier in the program is usable later), and mutable global state is -;; reset between cases so there is no leakage — same isolation a fresh process gives. -;; -;; chez --script host/chez/run-corpus.ss -;; JOLT_CHEZ_ZJ_FLOOR=N override the regression floor (default 3390) -;; JOLT_CORPUS_LIMIT=N every-Nth stride (fast iteration; floor drops to 0) -;; JOLT_DUMP_CRASH_LABELS=1 list crash + allowlisted labels -(import (chezscheme)) - -(load "host/chez/rt.ss") -(set-chez-ns! "clojure.core") -(load "host/chez/seed/prelude.ss") -(load "host/chez/post-prelude.ss") -(set-chez-ns! "user") -(load "host/chez/host-contract.ss") -(load "host/chez/seed/image.ss") -(load "host/chez/compile-eval.ss") - -(define (slurp path) - (call-with-input-file path - (lambda (p) - (let loop ((cs '()) (c (read-char p))) - (if (eof-object? c) (list->string (reverse cs)) - (loop (cons c cs) (read-char p))))))) - -(define corpus (jolt-read-string (slurp "test/chez/corpus.edn"))) -(define kw-label (keyword #f "label")) -(define kw-actual (keyword #f "actual")) -(define kw-expected (keyword #f "expected")) -(define kw-throws (keyword #f "throws")) - -;; --- per-case isolation: snapshot the world after setup, restore it each case ---- -;; (1) var-table keys a case ADDS (its defs) are removed; (2) a base cell whose ROOT -;; a case mutated (e.g. in-ns rebinds clojure.core/*ns*) is restored; (3) the ns + -;; type registries are pruned to their base keys; (4) global-hierarchy's contents -;; (mutated by derive) are reset to a fresh hierarchy. -(define zj-base (let ((h (make-hashtable string-hash string=?))) - (vector-for-each (lambda (k) (hashtable-set! h k #t)) (hashtable-keys var-table)) h)) -(define zj-roots '()) -(vector-for-each (lambda (k) (let ((c (hashtable-ref var-table k #f))) - (when c (set! zj-roots (cons (cons c (var-cell-root c)) zj-roots))))) - (hashtable-keys var-table)) -(define (zj-snap ht) (let ((h (make-hashtable string-hash string=?))) - (vector-for-each (lambda (k) (hashtable-set! h k #t)) (hashtable-keys ht)) h)) -(define (zj-prune! ht base) (vector-for-each - (lambda (k) (unless (hashtable-ref base k #f) (hashtable-delete! ht k))) (hashtable-keys ht))) -(define zj-ns-base (zj-snap ns-registry)) -(define zj-type-base (zj-snap type-registry)) -(define zj-ghier (var-cell-lookup "clojure.core" "global-hierarchy")) -(define (zj-reset!) - (vector-for-each (lambda (k) (unless (hashtable-ref zj-base k #f) (hashtable-delete! var-table k))) - (hashtable-keys var-table)) - (for-each (lambda (cr) (unless (eq? (var-cell-root (car cr)) (cdr cr)) - (var-cell-root-set! (car cr) (cdr cr)))) zj-roots) - (zj-prune! ns-registry zj-ns-base) - (zj-prune! type-registry zj-type-base) - (hashtable-clear! ns-alias-table) - (hashtable-clear! ns-refer-table) - (hashtable-clear! ns-refer-all-table) - (when zj-ghier (jolt-invoke (var-deref "clojure.core" "reset!") - (var-cell-root zj-ghier) (jolt-invoke (var-deref "clojure.core" "make-hierarchy")))) - (set-chez-ns! "user")) - -(define kw-message (keyword #f "message")) -(define (zj-err->str e) - (cond ((and (pmap? e) (string? (jolt-get e kw-message))) (jolt-get e kw-message)) - ((condition? e) (call-with-string-output-port (lambda (p) (display-condition e p)))) - ((string? e) e) - (else (call-with-string-output-port (lambda (p) (write e p)))))) -(define (zj-clean s) - (list->string (map (lambda (c) (if (or (char=? c #\tab) (char=? c #\newline)) #\space c)) - (string->list s)))) - -;; --- allowlist: conformance gaps vs the JVM spec (no JVM host on Chez) ----------- -;; Keyed by label. jolt does not match because it has no Class objects / Java arrays -;; / BigDecimal, supports the :jolt reader-conditional, or prints its own forms for -;; transients/atoms/Infinity. These DIVERGE but are tolerated; the gate fails only on -;; a NEW (unlisted) divergence or a drop below the floor. -(define known-fail-labels - '("getMessage on a thrown string" - "close on throw" "macroexpand-1" - "bean is the map" "proxy resolves nil" - "transient vector" "transient map" - "atom override fires nested" - "reader conditional" "reader cond :jolt" "reader cond no match" - "reader cond splice" "reader cond splice no match" - "nil nested" "bool nested" - "no param vector")) -(define known-fail (make-hashtable string-hash string=?)) -(for-each (lambda (l) (hashtable-set! known-fail l #t)) known-fail-labels) - -;; Cases skipped like :throws so they can't perturb the pass count: -;; - "promise undelivered" BLOCKS forever on a shared-heap host (deref of an -;; undelivered promise), so one hung case can't stall the run. -;; - the future-cancel races: whether `future-cancel` catches a trivial -;; `(future 1)` in-flight is pure thread-scheduling luck (the JVM expects the -;; future still queued; on a loaded host it may already have completed). A racy -;; outcome must not be a deterministic gate criterion — counting it inflates the -;; floor on a fast machine and trips CI on a slow one. -(define skip-blocking (make-hashtable string-hash string=?)) -(for-each (lambda (l) (hashtable-set! skip-blocking l #t)) - '("promise undelivered" - "cancel an in-flight future returns true" - "future-cancelled? after cancel")) - -;; Coarse crash bucket for the punch-list (informational; not gate-critical). -(define (crash-reason m) - (define (has? sub) (let loop ((i 0)) - (cond ((> (+ i (string-length sub)) (string-length m)) #f) - ((string=? (substring m i (+ i (string-length sub))) sub) #t) - (else (loop (+ i 1)))))) - (cond ((has? "unsupported stdlib") "emit: unsupported stdlib fn") - ((has? "unsupported host") "emit: unsupported host call") - ((has? "host-static") "emit: host-static") - ((has? "uncompil") "analyzer: uncompilable") - ((has? "Unknown class") "runtime: unknown class") - ((has? "No constructor") "runtime: no constructor") - ((has? "No method") "runtime: no method") - ((has? "not a fn") "runtime: not a fn") - ((has? "not seqable") "runtime: not seqable") - (else (substring m 0 (min 56 (string-length m)))))) - -;; --- run ------------------------------------------------------------------------ -(define limit (let ((s (getenv "JOLT_CORPUS_LIMIT"))) - (and s (string->number s)))) -(define stride (if (and limit (> limit 0)) (max 1 (quotient (pvec-count corpus) limit)) 1)) - -(define pass 0) (define throws 0) -(define crashes '()) ; (label . reason) -(define diverged '()) ; (label . got) — NEW divergence; gate fails -(define known-hit '()) ; label -(define crash-keys (make-hashtable string-hash string=?)) -(define (bucket! ht k) (hashtable-set! ht k (+ 1 (hashtable-ref ht k 0)))) - -(define t0 (current-time)) -(let loop ((i 0)) - (when (< i (pvec-count corpus)) - (let* ((row (pvec-nth-d corpus i jolt-nil)) - (label (jolt-get row kw-label)) - (ev-src (jolt-get row kw-expected)) - (av-src (jolt-get row kw-actual))) - (cond - ((or (eq? ev-src kw-throws) (hashtable-ref skip-blocking label #f)) - (set! throws (+ throws 1))) - (else - (guard (e (#t (let ((r (crash-reason (zj-clean (zj-err->str e))))) - (bucket! crash-keys r) - (set! crashes (cons (cons label r) crashes))))) - ;; discard a case's own stdout (a (println ...) side effect) so it can't - ;; pollute the gate report — as if the case ran in its own process. - (let* ((sink (open-output-string)) - (av (parameterize ((current-output-port sink)) (jolt-compile-eval av-src "user"))) - (ev (parameterize ((current-output-port sink)) (jolt-compile-eval ev-src "user")))) - (cond - ((jolt= ev av) (set! pass (+ pass 1))) - ((hashtable-ref known-fail label #f) (set! known-hit (cons label known-hit))) - (else (set! diverged (cons (cons label (zj-clean (jolt-final-str av))) diverged)))))) - (zj-reset!)))) - (loop (+ i stride)))) - -(define n-eval (+ pass (length crashes) (length diverged) (length known-hit))) -(define secs (let ((d (time-difference (current-time) t0))) - (+ (time-second d) (/ (time-nanosecond d) 1e9)))) -(printf "\nCorpus parity: ~a/~a evaluated cases pass (~as)\n" - pass n-eval (/ (round (* secs 10)) 10.0)) -(printf " crash: ~a NEW divergence: ~a known: ~a (throws skipped: ~a)\n" - (length crashes) (length diverged) (length known-hit) throws) - -(when (> (hashtable-size crash-keys) 0) - (printf "\ncrash reasons:\n") - (let-values (((ks vs) (hashtable-entries crash-keys))) - (for-each (lambda (pair) (printf " ~a x ~a\n" (cdr pair) (car pair))) - (list-sort (lambda (a b) (> (cdr a) (cdr b))) - (vector->list (vector-map cons ks vs)))))) -(when (getenv "JOLT_DUMP_CRASH_LABELS") - (printf "\nCRASH LABELS:\n") - (for-each (lambda (p) (printf " [~a] :: ~a\n" (cdr p) (car p))) - (list-sort (lambda (a b) (string (length diverged) 0) - (printf "\nNEW divergences (ran, wrong value) — gate FAILS:\n") - (for-each (lambda (p) (printf " [~a] got ~a\n" (car p) (cdr p))) - (list-head diverged (min 40 (length diverged))))) -(when (> (length known-hit) 0) - (printf "\n~a known (allowlisted) failures tolerated.\n" (length known-hit))) - -;; Regression floor: fail on any NEW divergence or if pass drops below the floor. -(define base-floor (let ((s (getenv "JOLT_CHEZ_ZJ_FLOOR"))) - (if s (string->number s) 3390))) -(define floor (if limit 0 base-floor)) -(when (or (> (length diverged) 0) (< pass floor)) - (printf "REGRESSION: pass ~a < floor ~a or ~a new divergence(s)\n" - pass floor (length diverged))) -(flush-output-port) -(exit (if (or (> (length diverged) 0) (< pass floor)) 1 0)) diff --git a/host/chez/run-devirt.ss b/host/chez/run-devirt.ss deleted file mode 100644 index 82fc185..0000000 --- a/host/chez/run-devirt.ss +++ /dev/null @@ -1,104 +0,0 @@ -;; run-devirt.ss — protocol-call devirtualization gate (backend_scheme emit). -;; -;; The inference annotates a monomorphic protocol call with :devirt-type/-proto/ -;; -method (jolt.passes.types); the back end then resolves the impl by that static -;; tag. This gate pins both halves: the emitted form uses find-protocol-method, and -;; evaluating it returns the same value the ordinary dispatch would — for a record's -;; inline impl, an extend-type impl, and across distinct receiver types. -;; -;; chez --script host/chez/run-devirt.ss -(import (chezscheme)) -(load "host/chez/rt.ss") -(set-chez-ns! "clojure.core") -(load "host/chez/seed/prelude.ss") -(load "host/chez/post-prelude.ss") -(set-chez-ns! "user") -(load "host/chez/host-contract.ss") -(load "host/chez/seed/image.ss") -(load "host/chez/compile-eval.ss") - -(define analyze (var-deref "jolt.analyzer" "analyze")) -(define emit (var-deref "jolt.backend-scheme" "emit")) -(define kw (lambda (n) (keyword #f n))) - -(define (evals src) (jolt-compile-eval (string-append "(do " src ")") "user")) -;; define two record types implementing one protocol — Circle via an inline impl, -;; Square via extend-type — plus instances to dispatch on. -(evals "(defprotocol Shape (area [s]))") -(evals "(defrecord Circle [r] Shape (area [s] (:r s)))") -(evals "(defrecord Square [w])") -(evals "(extend-type Square Shape (area [s] (* (:w s) (:w s))))") -(evals "(def c (->Circle 7))") -(evals "(def sq (->Square 5))") - -;; analyze (area RECV), annotate it as a devirt call on `type`, and emit. RECV is a -;; var name (c/sq) the emitted code resolves at eval time. -(define (devirt-emit type recv) - (let* ((ir (analyze (make-analyze-ctx "user") (jolt-ce-read (string-append "(area " recv ")")))) - (dv (jolt-assoc ir (kw "devirt-type") type (kw "devirt-proto") "Shape" - (kw "devirt-method") "area"))) - (emit dv))) - -(define fails 0) (define total 0) -(define (check label actual expected) - (set! total (+ total 1)) - (unless (equal? actual expected) - (set! fails (+ fails 1)) - (printf " FAIL ~a: got ~s expected ~s\n" label actual expected))) -(define (has-sub? s sub) - (let ((n (string-length s)) (m (string-length sub))) - (let loop ((i 0)) (cond ((> (+ i m) n) #f) - ((string=? (substring s i (+ i m)) sub) #t) - (else (loop (+ i 1))))))) -;; eval an emitted Scheme string in the loaded runtime (var-deref resolves c/sq). -(define (run-emit scm) (eval (read (open-input-string scm)) (interaction-environment))) - -(let ((e (devirt-emit "user.Circle" "c"))) - (check "emit uses devirt-resolve" (has-sub? e "devirt-resolve") #t) - (check "devirt inline impl == dispatch" (run-emit e) (evals "(area c)"))) ; 7 - -(let ((e (devirt-emit "user.Square" "sq"))) - (check "devirt extend-type impl == dispatch" (run-emit e) (evals "(area sq)"))) ; 25 - -;; a normal (no devirt) call still goes through dispatch and agrees — the path the -;; megamorphic / unknown-receiver site keeps. -(let ((e (emit (analyze (make-analyze-ctx "user") (jolt-ce-read "(area c)"))))) - (check "non-devirt path no devirt-resolve" (has-sub? e "devirt-resolve") #f) - (check "non-devirt still dispatches" (run-emit e) 7)) - -;; a record that relies on the protocol's Object default (no direct impl): the -;; inference still types it as a concrete record and annotates devirt, so the -;; emitted call must resolve the same value dispatch would. find-protocol-method -;; on the record's own tag misses here, so the devirt path has to fall back to -;; ordinary dispatch (else it applies #f and crashes). -(evals "(extend-protocol Shape Object (area [s] :obj-default))") -(evals "(defrecord Plain [n])") -(evals "(def pl (->Plain 9))") -(let ((e (devirt-emit "user.Plain" "pl"))) - (check "devirt Object-default == dispatch" (run-emit e) (evals "(area pl)"))) ; :obj-default - -;; in a direct-link build a devirt site caches the resolved impl in a per-site cell -;; (resolved once, reused) instead of resolving per call. Annotate the (area x) in a -;; def body and emit the top form; the result must carry the cell and still be right. -(let* ((set-direct-link! (var-deref "jolt.backend-scheme" "set-direct-link!")) - (emit-top-form (var-deref "jolt.backend-scheme" "emit-top-form")) - (dn (analyze (make-analyze-ctx "user") (jolt-ce-read "(def usearea (fn [x] (area x)))"))) - (ar0 (jolt-nth (jolt-get (jolt-get dn (kw "init")) (kw "arities")) 0)) - (inv (jolt-get ar0 (kw "body"))) - (inv2 (jolt-assoc inv (kw "devirt-type") "user.Circle" (kw "devirt-proto") "Shape" (kw "devirt-method") "area")) - (dn2 (jolt-assoc dn (kw "init") - (jolt-assoc (jolt-get dn (kw "init")) (kw "arities") - (jolt-vector (jolt-assoc ar0 (kw "body") inv2)))))) - (set-direct-link! #t) - (let ((e (emit-top-form dn2))) - (set-direct-link! #f) - (check "devirt in a def caches in a per-site cell" (has-sub? e "_dvc$") #t) - (check "cached cell still resolves the impl" (has-sub? e "devirt-resolve") #t) - ;; eval the def, then call it: caches on first call, reuses after — still 7. - (run-emit e) - (check "cached devirt == dispatch (1st call)" (jolt-invoke (var-deref "user" "usearea") (var-deref "user" "c")) 7) - (check "cached devirt == dispatch (2nd call, from cell)" (jolt-invoke (var-deref "user" "usearea") (var-deref "user" "c")) 7))) - -(if (= fails 0) - (begin (printf "devirt gate: ~a/~a passed\n" total total) (exit 0)) - (begin (printf "devirt gate: ~a/~a passed (~a failed)\n" (- total fails) total fails) (exit 1))) diff --git a/host/chez/run-fieldnum.ss b/host/chez/run-fieldnum.ss deleted file mode 100644 index 567b5c3..0000000 --- a/host/chez/run-fieldnum.ss +++ /dev/null @@ -1,82 +0,0 @@ -;; run-fieldnum.ss — ^double record field reads unbox to fl-ops (jolt-evr9 R2). -;; -;; A record field tagged ^double reads back as a flonum (:double in the lattice), -;; so hintless arithmetic over those fields — (* (:x a) (:x b)) — lowers to fl-ops, -;; the same machinery as a ^double param. Two halves pinned here: (1) the ctor -;; coerces a ^double field to a flonum at construction (JVM parity, and what makes -;; the fl-op sound), and (2) field-field arithmetic over a record param (typed by -;; the whole-program fixpoint) emits fl*. -;; -;; chez --script host/chez/run-fieldnum.ss -(import (chezscheme)) -(load "host/chez/rt.ss") -(set-chez-ns! "clojure.core") -(load "host/chez/seed/prelude.ss") -(load "host/chez/post-prelude.ss") -(set-chez-ns! "user") -(load "host/chez/host-contract.ss") -(load "host/chez/seed/image.ss") -(load "host/chez/compile-eval.ss") - -(define analyze (var-deref "jolt.analyzer" "analyze")) -(define set-record-shapes! (var-deref "jolt.passes.types" "set-record-shapes!")) -(define set-protocol-methods! (var-deref "jolt.passes.types" "set-protocol-methods!")) -(define wp-infer! (var-deref "jolt.passes.types" "wp-infer!")) -(define run-passes (var-deref "jolt.passes" "run-passes")) -(define emit (var-deref "jolt.backend-scheme" "emit")) - -(define (anode src) (analyze (make-analyze-ctx "user") (jolt-ce-read src))) -(define (evals src) (jolt-compile-eval (string-append "(do " src ")") "user")) -(define (contains-sub? s sub) - (let ((n (string-length s)) (m (string-length sub))) - (let loop ((i 0)) - (cond ((> (+ i m) n) #f) - ((string=? (substring s i (+ i m)) sub) #t) - (else (loop (+ i 1))))))) - -(define fails 0) (define total 0) -(define (check label actual expected) - (set! total (+ total 1)) - (unless (equal? actual expected) - (set! fails (+ fails 1)) - (printf " FAIL ~a: got ~s expected ~s\n" label actual expected))) - -;; a record with ^double fields; the ctor must coerce an integer arg to a flonum. -(evals "(defrecord V [^double x ^double y])") -(check "ctor coerces ^double field to flonum" (flonum? (evals "(:x (->V 1 2))")) #t) -(check "coerced field value matches" (evals "(:x (->V 1 2))") 1.0) -(check "a flonum arg passes through" (evals "(:y (->V 1.5 2.5))") 2.5) - -;; dot is hintless; its caller passes V instances, so the fixpoint types a/b as V -;; records, the ^double fields read :double, and the field-field arithmetic unboxes. -(define dot (anode "(def dot (fn [a b] (+ (* (:x a) (:x b)) (* (:y a) (:y b)))))")) -(define used (anode "(def used (fn [] (dot (->V 1.0 2.0) (->V 3.0 4.0))))")) -(set-record-shapes! (chez-record-shapes-map)) -(set-protocol-methods! (jolt-hash-map)) -(wp-infer! (jolt-vector dot used)) -(set-optimize! #t) -(define dot-emit (emit (run-passes dot (make-analyze-ctx "user")))) -(check "field-field arithmetic unboxes to fl*" (contains-sub? dot-emit "fl*") #t) -(check "field-field arithmetic unboxes to fl+" (contains-sub? dot-emit "fl+") #t) - -;; a ^V param hint types the param with no inferable caller (open-world / cross-fn: -;; the receiver isn't a ctor return). This is the record-ctor-key path — without it -;; the hint is dead and the reads fall back to generic jolt-get + boxed arithmetic. -(define hinted (anode "(def hyp (fn [^V v] (+ (* (:x v) (:x v)) (* (:y v) (:y v)))))")) -(define hint-emit (emit (run-passes hinted (make-analyze-ctx "user")))) -(check "^V param hint bare-indexes field reads" (contains-sub? hint-emit "jrec-field-at") #t) -(check "^V param hint unboxes arithmetic" (contains-sub? hint-emit "fl*") #t) -(check "^V param hint leaves no generic jolt-get" (contains-sub? hint-emit "jolt-get") #f) - -;; an UNTAGGED field stays generic — no fl-op (the read is :any, not :double). -(evals "(defrecord W [p q])") -(define dotw (anode "(def dotw (fn [a b] (* (:p a) (:p b))))")) -(define usew (anode "(def usew (fn [] (dotw (->W 1.0 2.0) (->W 3.0 4.0))))")) -(set-record-shapes! (chez-record-shapes-map)) -(wp-infer! (jolt-vector dotw usew)) -(check "untagged field stays generic (no fl*)" - (contains-sub? (emit (run-passes dotw (make-analyze-ctx "user"))) "fl*") #f) - -(if (= fails 0) - (begin (printf "fieldnum gate: ~a/~a passed\n" total total) (exit 0)) - (begin (printf "fieldnum gate: ~a/~a passed (~a failed)\n" (- total fails) total fails) (exit 1))) diff --git a/host/chez/run-fieldread.ss b/host/chez/run-fieldread.ss deleted file mode 100644 index c09b58d..0000000 --- a/host/chez/run-fieldread.ss +++ /dev/null @@ -1,72 +0,0 @@ -;; run-fieldread.ss — native record field-read gate (backend_scheme emit). -;; -;; When the inference types a keyword-lookup receiver as a record (it carries the -;; field-order :shape + :hint :struct), the back end reads the field by its static -;; slot via jrec-field-at instead of jolt-get. This gate pins the emit shape and -;; that the value matches jolt-get — for a declared field, a non-field key (no -;; bare path), and a default-arg form (no bare path). -;; -;; chez --script host/chez/run-fieldread.ss -(import (chezscheme)) -(load "host/chez/rt.ss") -(set-chez-ns! "clojure.core") -(load "host/chez/seed/prelude.ss") -(load "host/chez/post-prelude.ss") -(set-chez-ns! "user") -(load "host/chez/host-contract.ss") -(load "host/chez/seed/image.ss") -(load "host/chez/compile-eval.ss") - -(define analyze (var-deref "jolt.analyzer" "analyze")) -(define emit (var-deref "jolt.backend-scheme" "emit")) -(define kw (lambda (n) (keyword #f n))) -(define (evals src) (jolt-compile-eval (string-append "(do " src ")") "user")) - -(evals "(defrecord Vec3 [x y z])") -(evals "(def a (->Vec3 10 20 30))") - -;; emit (:KEY a [default]) with arg 0 marked as a Vec3 struct receiver. -(define (mark-emit src) - (let* ((ir (analyze (make-analyze-ctx "user") (jolt-ce-read src))) - (a0 (jolt-nth (jolt-get ir (kw "args")) 0)) - (marked (jolt-assoc a0 (kw "hint") (kw "struct") - (kw "shape") (jolt-vector (kw "x") (kw "y") (kw "z")))) - (args (jolt-get ir (kw "args"))) - (args2 (jolt-assoc args 0 marked))) - (emit (jolt-assoc ir (kw "args") args2)))) - -(define (run-emit scm) (eval (read (open-input-string scm)) (interaction-environment))) -(define (has-sub? s sub) - (let ((n (string-length s)) (m (string-length sub))) - (let loop ((i 0)) (cond ((> (+ i m) n) #f) - ((string=? (substring s i (+ i m)) sub) #t) - (else (loop (+ i 1))))))) -(define fails 0) (define total 0) -(define (check label actual expected) - (set! total (+ total 1)) - (unless (equal? actual expected) - (set! fails (+ fails 1)) - (printf " FAIL ~a: got ~s expected ~s\n" label actual expected))) - -;; a declared field -> bare-index path, value matches jolt-get -(let ((e (mark-emit "(:y a)"))) - (check "declared field uses jrec-field-at" (has-sub? e "jrec-field-at") #t) - (check "field 1 -> static slot 1" (has-sub? e " 1 ") #t) - (check "bare read == jolt-get" (run-emit e) (evals "(:y a)"))) ; 20 - -;; first/last fields too -(check "field x == jolt-get" (run-emit (mark-emit "(:x a)")) (evals "(:x a)")) ; 10 -(check "field z == jolt-get" (run-emit (mark-emit "(:z a)")) (evals "(:z a)")) ; 30 - -;; a key that is NOT a declared field -> no bare path, still correct (nil) -(let ((e (mark-emit "(:w a)"))) - (check "non-field key no jrec-field-at" (has-sub? e "jrec-field-at") #f) - (check "non-field key == jolt-get" (run-emit e) (evals "(:w a)"))) ; nil - -;; a default-arg form keeps jolt-get (the bare path is no-default only) -(let ((e (mark-emit "(:y a 99)"))) - (check "default-arg keeps jolt-get" (has-sub? e "jrec-field-at") #f)) - -(if (= fails 0) - (begin (printf "fieldread gate: ~a/~a passed\n" total total) (exit 0)) - (begin (printf "fieldread gate: ~a/~a passed (~a failed)\n" (- total fails) total fails) (exit 1))) diff --git a/host/chez/run-infer.ss b/host/chez/run-infer.ss deleted file mode 100644 index 2125ef3..0000000 --- a/host/chez/run-infer.ss +++ /dev/null @@ -1,106 +0,0 @@ -;; run-infer.ss — inference / success-type-checking gate (jolt.passes.types). -;; -;; The corpus and unit gates compile through run-passes' const-fold-only branch, -;; so the inference walk (jolt.passes.types) runs only under `jolt build --opt` — -;; buildsmoke exercises it on one trivial app and asserts stdout only. This gate -;; drives the pass DIRECTLY: analyze a source string to IR, then call the public -;; checker/driver entry points (check-form, infer-body, the set-*! registries) and -;; assert their observable output (diagnostic counts, collected calls/escapes). It -;; pins the behavior the inference walk's internal state produces, so a refactor of -;; that state is gate-validatable. -;; -;; chez --script host/chez/run-infer.ss -(import (chezscheme)) - -(load "host/chez/rt.ss") -(set-chez-ns! "clojure.core") -(load "host/chez/seed/prelude.ss") -(load "host/chez/post-prelude.ss") -(set-chez-ns! "user") -(load "host/chez/host-contract.ss") -(load "host/chez/seed/image.ss") -(load "host/chez/compile-eval.ss") - -(define analyze (var-deref "jolt.analyzer" "analyze")) -(define check-form (var-deref "jolt.passes.types" "check-form")) -(define infer-body (var-deref "jolt.passes.types" "infer-body")) -(define reset-escapes! (var-deref "jolt.passes.types" "reset-escapes!")) -(define collected-escapes (var-deref "jolt.passes.types" "collected-escapes")) -(define set-record-shapes! (var-deref "jolt.passes.types" "set-record-shapes!")) -(define set-vtypes! (var-deref "jolt.passes.types" "set-vtypes!")) -(define set-check-mode! (var-deref "jolt.passes.types" "set-check-mode!")) -(define run-inference (var-deref "jolt.passes.types" "run-inference")) -(define take-diags! (var-deref "jolt.passes.types" "take-diags!")) - -;; analyze a source string to its IR node (fresh ctx, ns "user", no passes). -(define (anode src) (analyze (make-analyze-ctx "user") (jolt-ce-read src))) -;; number of success-type diagnostics check-form produces for src. -(define (diags src strict?) (jolt-count (check-form (anode src) strict?))) - -(define fails 0) -(define total 0) -(define (check label actual expected) - (set! total (+ total 1)) - (unless (equal? actual expected) - (set! fails (+ fails 1)) - (printf " FAIL ~a: got ~s expected ~s\n" label actual expected))) - -;; --- core error-domain checking (strict not required) ----------------------- -(check "num-op on keyword" (diags "(+ 1 :k)" #f) 1) -(check "num-op all numbers" (diags "(+ 1 2)" #f) 0) -(check "count on number" (diags "(count 5)" #f) 1) -(check "count on vector" (diags "(count [1 2])" #f) 0) -(check "lenient (:k 5)" (diags "(:k 5)" #f) 0) -(check "call a number" (diags "(5 1)" #f) 1) -(check "nested count return type" (diags "(+ 1 (count :k))" #f) 1) - -;; --- walk arms thread the type env ------------------------------------------ -(check "let binds kw" (diags "(let [x :k] (+ x 1))" #f) 1) -(check "let binds ok" (diags "(let [x 1] (+ x 1))" #f) 0) -(check "if then branch error" (diags "(if true (+ 1 :k) 2)" #f) 1) -(check "do statement error" (diags "(do (+ 1 :k) 2)" #f) 1) -(check "mapv seeds element type" (diags "(mapv (fn [x] (+ x 1)) [:a :b])" #f) 1) -(check "mapv ok element type" (diags "(mapv (fn [x] (+ x 1)) [1 2])" #f) 0) -(check "reduce seeds element" (diags "(reduce (fn [acc x] (+ acc x)) 0 [:a])" #f) 1) - -;; --- strict user-function domains (checking-box / diag-memo / user-sig) ------ -(check "user wrong arg type" (diags "(do (defn f [x] (+ x 1)) (f :k))" #t) 1) -(check "user wrong arity" (diags "(do (defn g [x] x) (g 1 2))" #t) 1) -(check "user call ok" (diags "(do (defn h [x] (+ x 1)) (h 3))" #t) 0) -(check "user domains off w/o strict" (diags "(do (defn f [x] (+ x 1)) (f :k))" #f) 0) -;; recursive user fn terminates (cycle guard) and still flags the bad arg -(check "user recursive terminates" - (diags "(do (defn rf [x] (+ x (rf x))) (rf :k))" #t) 1) - -;; --- infer-body collects calls + escapes ------------------------------------ -(reset-escapes!) -(let ((r (infer-body (anode "(do (foo 1) (bar 2) (map inc [1]))") (jolt-hash-map)))) - (check "infer-body calls" (jolt-count (jolt-nth r 2)) 3) ; foo, bar, map - (check "infer-body escapes" (jolt-count (collected-escapes)) 1)) ; inc (value position) - -;; --- the record-shapes registry feeds call-result types -------------------- -;; without shapes a (->P …) call result is :any (accepted); with the registry it -;; types as a struct, so an arithmetic op over it is provably not-a-number. -(check "ctor result :any w/o shapes" (diags "(+ (->P 1) 1)" #f) 0) -(set-record-shapes! - (jolt-hash-map "user/->P" - (jolt-hash-map (keyword #f "fields") (jolt-vector (keyword #f "x")) - (keyword #f "tags") (jolt-vector jolt-nil) - (keyword #f "type") "user.P"))) -(check "ctor result struct w/ shapes" (diags "(+ (->P 1) 1)" #f) 1) -(set-record-shapes! (jolt-hash-map)) - -;; --- the opt-path checker: run-inference emits, take-diags! drains ----------- -;; (set-check-mode! on strict?) arms checking during the next run-inference; the -;; diagnostics are stashed for take-diags! to drain once. -(set-check-mode! #t #f) -(run-inference (anode "(+ 1 :k)")) -(check "take-diags drains run-inference" (jolt-count (take-diags!)) 1) -(check "take-diags re-drained empty" (jolt-count (take-diags!)) 0) -(set-check-mode! #f #f) -(run-inference (anode "(+ 1 :k)")) -(check "no diags when check-mode off" (jolt-count (take-diags!)) 0) - -(if (= fails 0) - (begin (printf "infer gate: ~a/~a passed\n" total total) (exit 0)) - (begin (printf "infer gate: ~a/~a passed (~a failed)\n" (- total fails) total fails) (exit 1))) diff --git a/host/chez/run-narrow.ss b/host/chez/run-narrow.ss deleted file mode 100644 index cb3c3d7..0000000 --- a/host/chez/run-narrow.ss +++ /dev/null @@ -1,76 +0,0 @@ -;; run-narrow.ss — nilable record types + flow-sensitive some?/nil? narrowing. -;; -;; A protocol method (or `if`) returning a record-or-nil types as a NILABLE record: -;; some?/nil? do NOT fold on it (it might be nil), so a runtime guard stays. Inside -;; (if (some? x) ..) / (if x ..) the then-branch narrows x to the non-nil record, so -;; its field reads bare-index and unbox. This is the ray tracer's -;; (let [scattered (scatter ..)] (if (some? scattered) (.. (:ray scattered) ..))). -;; -;; The load-bearing soundness check: the nil case must still take the else branch — -;; narrowing must NOT fold the guard away (else a real nil reaches the bare read). -;; -;; chez --script host/chez/run-narrow.ss -(import (chezscheme)) -(load "host/chez/rt.ss") -(set-chez-ns! "clojure.core") -(load "host/chez/seed/prelude.ss") -(load "host/chez/post-prelude.ss") -(set-chez-ns! "user") -(load "host/chez/host-contract.ss") -(load "host/chez/seed/image.ss") -(load "host/chez/compile-eval.ss") - -(define analyze (var-deref "jolt.analyzer" "analyze")) -(define set-record-shapes! (var-deref "jolt.passes.types" "set-record-shapes!")) -(define set-protocol-methods! (var-deref "jolt.passes.types" "set-protocol-methods!")) -(define wp-infer! (var-deref "jolt.passes.types" "wp-infer!")) -(define run-passes (var-deref "jolt.passes" "run-passes")) -(define emit (var-deref "jolt.backend-scheme" "emit")) -(define (anode src) (analyze (make-analyze-ctx "user") (jolt-ce-read src))) -(define (evals src) (jolt-compile-eval (string-append "(do " src ")") "user")) -(define (built scm) (eval (read (open-input-string scm)) (interaction-environment))) -(define (sub? s t)(let((n(string-length s))(m(string-length t)))(let loop((i 0))(cond((>(+ i m)n)#f)((string=?(substring s i(+ i m))t)#t)(else(loop(+ i 1))))))) -(define fails 0) (define total 0) -(define (check label actual expected) - (set! total (+ total 1)) - (unless (equal? actual expected) - (set! fails (+ fails 1)) - (printf " FAIL ~a: got ~s expected ~s\n" label actual expected))) - -(evals "(defrecord R [^double k])") -(evals "(defprotocol P (m [x]))") -(evals "(defrecord A [v] P (m [x] (->R 1.0)))") -(evals "(defrecord B [v] P (m [x] (if (< (:v x) 0) (->R 2.0) nil)))") ; B.m returns R-or-nil -(set-record-shapes! (chez-record-shapes-map)) -(set-protocol-methods! (chez-protocol-methods-map)) -(set-optimize! #t) -(define na (anode "(defrecord A [v] P (m [x] (->R 1.0)))")) -(define nb (anode "(defrecord B [v] P (m [x] (if (< (:v x) 0) (->R 2.0) nil)))")) -;; guarded read: inside (some? s), s narrows to non-nil R -> (:k s) bare-indexes + unboxes -(define f (anode "(def f (fn [a] (let [s (m a)] (if (some? s) (* (:k s) 2.0) 0.0))))")) -(wp-infer! (jolt-vector na nb f)) -(define fe (emit (run-passes f (make-analyze-ctx "user")))) -(check "guarded nullable read bare-indexes" (sub? fe "jrec-field-at") #t) -(check "guarded nullable read unboxes to fl*" (sub? fe "fl*") #t) - -;; CORRECTNESS + the load-bearing soundness check: the nil case must take the else -;; branch (the guard is preserved), not run the bare read on nil. -(built fe) -(define ff (var-deref "user" "f")) -(check "non-nil (A.m -> R 1.0)" (jolt-invoke ff (evals "(->A 5)")) 2.0) -(check "non-nil (B.m v<0 -> R 2.0)" (jolt-invoke ff (evals "(->B -5)")) 4.0) -(check "nil case takes else (guard preserved, no crash)" - (jolt-invoke ff (evals "(->B 5)")) 0.0) - -;; an UNGUARDED nullable read must stay safe: jrec-field-at falls back to jolt-get on -;; nil. (Its result type is conservative — no unbox — so this just checks no crash.) -(define g (anode "(def g (fn [a] (let [s (m a)] (:k s))))")) -(define ge (emit (run-passes g (make-analyze-ctx "user")))) -(built ge) -(define gg (var-deref "user" "g")) -(check "unguarded nullable read on nil returns nil" (jolt-nil? (jolt-invoke gg (evals "(->B 5)"))) #t) -(check "unguarded nullable read on non-nil returns the field" (jolt-invoke gg (evals "(->A 5)")) 1.0) - -(if (= fails 0) - (begin (printf "narrow gate: ~a/~a passed\n" total total) (exit 0)) - (begin (printf "narrow gate: ~a/~a passed (~a failed)\n" (- total fails) total fails) (exit 1))) diff --git a/host/chez/run-numwp.ss b/host/chez/run-numwp.ss deleted file mode 100644 index d2a7a0a..0000000 --- a/host/chez/run-numwp.ss +++ /dev/null @@ -1,108 +0,0 @@ -;; run-numwp.ss — hintless whole-program :double inference gate (jolt-evr9 R3). -;; -;; run-wp.ss drives the structural (record) fixpoint; this drives its numeric -;; refinement: a hintless fn whose every call site passes a flonum has its param -;; typed :double, which the back end then unboxes to fl-ops — no ^double hint. The -;; bridge is a synthetic [param :double] nhint (jolt.passes/inject-wp-nhints) that -;; the existing hint-directed pass + entry coercion consume unchanged. -;; -;; Soundness pinned here: :double only (never :long — an untyped integer can be a -;; bignum), so a caller passing an integer leaves the param generic; an escaped fn -;; keeps :any. -;; -;; chez --script host/chez/run-numwp.ss -(import (chezscheme)) -(load "host/chez/rt.ss") -(set-chez-ns! "clojure.core") -(load "host/chez/seed/prelude.ss") -(load "host/chez/post-prelude.ss") -(set-chez-ns! "user") -(load "host/chez/host-contract.ss") -(load "host/chez/seed/image.ss") -(load "host/chez/compile-eval.ss") - -(define analyze (var-deref "jolt.analyzer" "analyze")) -(define set-record-shapes! (var-deref "jolt.passes.types" "set-record-shapes!")) -(define set-protocol-methods! (var-deref "jolt.passes.types" "set-protocol-methods!")) -(define wp-infer! (var-deref "jolt.passes.types" "wp-infer!")) -(define param-num-seeds-for (var-deref "jolt.passes.types" "param-num-seeds-for")) -(define inject-wp-nhints (var-deref "jolt.passes" "inject-wp-nhints")) -(define annotate (var-deref "jolt.passes.numeric" "annotate")) -(define run-passes (var-deref "jolt.passes" "run-passes")) -(define emit (var-deref "jolt.backend-scheme" "emit")) -(define pr-str (var-deref "clojure.core" "pr-str")) - -(define (anode src) (analyze (make-analyze-ctx "user") (jolt-ce-read src))) -(define (contains-sub? s sub) - (let ((n (string-length s)) (m (string-length sub))) - (let loop ((i 0)) - (cond ((> (+ i m) n) #f) - ((string=? (substring s i (+ i m)) sub) #t) - (else (loop (+ i 1))))))) - -(define fails 0) (define total 0) -(define (check label actual expected) - (set! total (+ total 1)) - (unless (equal? actual expected) - (set! fails (+ fails 1)) - (printf " FAIL ~a: got ~s expected ~s\n" label actual expected))) - -(set-record-shapes! (jolt-hash-map)) -(set-protocol-methods! (jolt-hash-map)) - -;; sq is hintless; its only caller passes a flonum literal, so the fixpoint must -;; type x :double across the fn boundary. -(define sq (anode "(def sq (fn [x] (* x x)))")) -(define usef (anode "(def usef (fn [] (sq 2.0)))")) -(wp-infer! (jolt-vector sq usef)) - -(define nseed (param-num-seeds-for "user/sq")) -(check "sq has a numeric param seed" (jolt-truthy? nseed) #t) -(when (jolt-truthy? nseed) - (check "x seeded :double" (contains-sub? (pr-str nseed) ":double") #t)) - -;; the bridge: inject the derived nhint, run the numeric pass, emit -> fl*. -(define sq-opt (annotate (inject-wp-nhints sq))) -(check "sq body unboxes to fl*" (contains-sub? (emit sq-opt) "fl*") #t) -;; and the param is coerced at entry like a ^double param (no-op on a real flonum). -(check "sq coerces param at entry" (contains-sub? (emit sq-opt) "exact->inexact") #t) - -;; a caller passing an INTEGER must NOT make the param :double — an untyped integer -;; can be a bignum, so fl-ops would diverge. The param stays generic. -(define sqi (anode "(def sqi (fn [x] (* x x)))")) -(define usei (anode "(def usei (fn [] (sqi 2)))")) -(wp-infer! (jolt-vector sqi usei)) -(check "integer caller leaves param generic" - (jolt-truthy? (param-num-seeds-for "user/sqi")) #f) - -;; a fn used in value position (escapes) has unknown callers -> no double seed. -(define esc (anode "(def esc (fn [x] (* x x)))")) -(define hof (anode "(def hof (fn [g] (g 2.0)))")) -(define ecl (anode "(def ecaller (fn [] (hof esc)))")) ; esc escapes -(wp-infer! (jolt-vector esc hof ecl)) -(check "escaped fn keeps no double seed" - (jolt-truthy? (param-num-seeds-for "user/esc")) #f) - -;; :double flows through a returning helper: mag returns a flonum, so a param fed -;; only (mag _) results types :double too (cross-fn return propagation). -(define mag (anode "(def mag (fn [a] (* a 2.0)))")) -(define dist (anode "(def dist (fn [b] (+ b b)))")) -(define dcl (anode "(def dcaller (fn [] (dist (mag 3.0))))")) -(wp-infer! (jolt-vector mag dist dcl)) -(check "param fed a flonum-returning call types :double" - (jolt-truthy? (param-num-seeds-for "user/dist")) #t) - -;; end to end through the real build pipeline: with optimize on, run-passes wires -;; the WP fixpoint's :double seeds into the numeric pass (inject-wp-nhints) so the -;; emitted def unboxes — proves the production path fires, not just the bridge in -;; isolation. -(set-optimize! #t) -(define sq2 (anode "(def sq2 (fn [x] (* x x)))")) -(define use2 (anode "(def use2 (fn [] (sq2 4.0)))")) -(wp-infer! (jolt-vector sq2 use2)) -(check "run-passes unboxes a hintless double fn" - (contains-sub? (emit (run-passes sq2 (make-analyze-ctx "user"))) "fl*") #t) - -(if (= fails 0) - (begin (printf "numwp gate: ~a/~a passed\n" total total) (exit 0)) - (begin (printf "numwp gate: ~a/~a passed (~a failed)\n" (- total fails) total fails) (exit 1))) diff --git a/host/chez/run-protoret.ss b/host/chez/run-protoret.ss deleted file mode 100644 index 86485c7..0000000 --- a/host/chez/run-protoret.ss +++ /dev/null @@ -1,70 +0,0 @@ -;; run-protoret.ss — protocol-method return-type inference gate. -;; -;; A protocol method whose impls all return the same record type has a monomorphic -;; return: collect-pm-rets! joins the impl return types, and call-ret-type then types -;; a (method recv ..) call as that record — so a field read off the result bare- -;; indexes. This is the ray tracer's (:ray (scatter material ..)): scatter's impls -;; all return a ScatterResult, so the bounced ray types without a hint. -;; -;; chez --script host/chez/run-protoret.ss -(import (chezscheme)) -(load "host/chez/rt.ss") -(set-chez-ns! "clojure.core") -(load "host/chez/seed/prelude.ss") -(load "host/chez/post-prelude.ss") -(set-chez-ns! "user") -(load "host/chez/host-contract.ss") -(load "host/chez/seed/image.ss") -(load "host/chez/compile-eval.ss") - -(define analyze (var-deref "jolt.analyzer" "analyze")) -(define set-record-shapes! (var-deref "jolt.passes.types" "set-record-shapes!")) -(define set-protocol-methods! (var-deref "jolt.passes.types" "set-protocol-methods!")) -(define wp-infer! (var-deref "jolt.passes.types" "wp-infer!")) -(define run-passes (var-deref "jolt.passes" "run-passes")) -(define emit (var-deref "jolt.backend-scheme" "emit")) -(define (anode src) (analyze (make-analyze-ctx "user") (jolt-ce-read src))) -(define (evals src) (jolt-compile-eval (string-append "(do " src ")") "user")) -(define (sub? s t)(let((n(string-length s))(m(string-length t)))(let loop((i 0))(cond((>(+ i m)n)#f)((string=?(substring s i(+ i m))t)#t)(else(loop(+ i 1))))))) - -(define fails 0) (define total 0) -(define (check label actual expected) - (set! total (+ total 1)) - (unless (equal? actual expected) - (set! fails (+ fails 1)) - (printf " FAIL ~a: got ~s expected ~s\n" label actual expected))) - -(evals "(defrecord R [^double k])") -(evals "(defprotocol P (m [x]))") -(evals "(defrecord A [v] P (m [x] (->R 1.0)))") -(evals "(defrecord B [v] P (m [x] (->R 2.0)))") -(evals "(defprotocol Q (q [x]))") -(evals "(defrecord C [v] Q (q [x] (->R 3.0)))") -(evals "(defrecord D [v] Q (q [x] 7)))") ; one impl returns a number, not R -(set-record-shapes! (chez-record-shapes-map)) -(set-protocol-methods! (chez-protocol-methods-map)) -(set-optimize! #t) - -;; analyze the impl-registering forms + a consumer; the fixpoint collects the -;; impl return types. (the analyzed defrecord nodes carry register-inline-method.) -(define na (anode "(defrecord A [v] P (m [x] (->R 1.0)))")) -(define nb (anode "(defrecord B [v] P (m [x] (->R 2.0)))")) -(define nc (anode "(defrecord C [v] Q (q [x] (->R 3.0)))")) -(define nd (anode "(defrecord D [v] Q (q [x] 7))")) -(define f (anode "(def f (fn [a] (* (:k (m a)) 2.0)))")) -(define g (anode "(def g (fn [a] (:k (q a))))")) -(wp-infer! (jolt-vector na nb nc nd f g)) - -;; m's impls all return R -> (:k (m a)) reads off an R -> bare-index + unbox. -(define fe (emit (run-passes f (make-analyze-ctx "user")))) -(check "monomorphic protocol return bare-indexes the field read" (sub? fe "jrec-field-at") #t) -(check "monomorphic protocol return unboxes the ^double field" (sub? fe "fl") #t) - -;; q's impls return R and a number -> joined to non-record -> stays generic (sound). -(define ge (emit (run-passes g (make-analyze-ctx "user")))) -(check "mixed-return protocol keeps generic jolt-get" (sub? ge "jolt-get") #t) -(check "mixed-return protocol does not bare-index" (sub? ge "jrec-field-at") #f) - -(if (= fails 0) - (begin (printf "protoret gate: ~a/~a passed\n" total total) (exit 0)) - (begin (printf "protoret gate: ~a/~a passed (~a failed)\n" (- total fails) total fails) (exit 1))) diff --git a/host/chez/run-sci.ss b/host/chez/run-sci.ss deleted file mode 100644 index 700b234..0000000 --- a/host/chez/run-sci.ss +++ /dev/null @@ -1,81 +0,0 @@ -;; run-sci.ss — SCI conformance: load borkdude/sci's own source (vendor/sci) through -;; joltc and require its forms to compile+eval. A real-world Clojure-compatibility -;; stress test. Floor-gated like the corpus: a regression below -;; the floor (or the count today, 210/218) fails. Raise the floor as host gaps close -;; (the tail is genuine gaps — set! on vars, some macro/def shapes). -;; -;; chez --script host/chez/run-sci.ss -;; JOLT_SCI_FLOOR=N override the floor (default 210) -;; SCI_VERBOSE=1 print each failing form's error -(import (chezscheme)) - -;; Skip cleanly when the submodule isn't checked out. -(unless (file-exists? "vendor/sci/src/sci/core.cljc") - (display "skip: vendor/sci not checked out (git submodule update --init vendor/sci)\n") - (exit 0)) - -(load "host/chez/rt.ss") -(set-chez-ns! "clojure.core") -(load "host/chez/seed/prelude.ss") -(load "host/chez/post-prelude.ss") -(set-chez-ns! "user") -(load "host/chez/host-contract.ss") -(load "host/chez/seed/image.ss") -(load "host/chez/compile-eval.ss") - -;; SCI's .cljc selects host code via #?(:clj ...) with no :jolt branch — read clj. -(set! rdr-features (list "clj" "jolt" "default")) - -(define (slurp path) - (call-with-input-file path - (lambda (p) (let loop ((cs '()) (c (read-char p))) - (if (eof-object? c) (list->string (reverse cs)) (loop (cons c cs) (read-char p))))))) - -;; Load every form in a file, evaluating each in the current ns (an (ns ...) form -;; switches it). Returns (ok . fail); failures are tolerated (lenient — SCI requires -;; host libs that don't exist here). -(define (load-forms path verbose) - (let ((src (slurp path)) (ok 0) (fail 0)) - (let ((end (string-length src))) - (let loop ((i 0)) - (call-with-values (lambda () (rdr-read-form src i end)) - (lambda (form j) - (unless (rdr-eof? form) - (guard (e (#t (set! fail (+ fail 1)) - (when verbose - (printf " FAIL: ~a\n" (call-with-string-output-port - (lambda (p) (display-condition (if (condition? e) e - (make-message-condition (jolt-final-str e))) p))))))) - (jolt-compile-eval-form form (chez-current-ns)) - (set! ok (+ ok 1))) - (loop j)))))) - (cons ok fail))) - -(define verbose (and (getenv "SCI_VERBOSE") #t)) - -;; stubs first (host shims SCI's source expects) -(for-each (lambda (f) (load-forms (string-append "stdlib/clojure/sci/" f) verbose)) - '("lang_stubs.clj" "io_stubs.clj" "host_stubs.clj")) - -(define sci-base "vendor/sci/src/sci/") -(define load-order - '("impl/macros.cljc" "impl/protocols.cljc" "impl/types.cljc" "impl/unrestrict.cljc" - "impl/vars.cljc" "lang.cljc" "impl/utils.cljc" "ctx_store.cljc" "impl/deftype.cljc" - "impl/records.cljc" "impl/core_protocols.cljc" "impl/hierarchies.cljc" - "impl/destructure.cljc" "impl/doseq_macro.cljc" "impl/for_macro.cljc" "impl/fns.cljc" - "impl/multimethods.cljc" "impl/namespaces.cljc" "core.cljc")) - -(define total-ok 0) (define total-fail 0) -(for-each - (lambda (f) - (let* ((r (load-forms (string-append sci-base f) verbose)) (ok (car r)) (fail (cdr r))) - (set! total-ok (+ total-ok ok)) (set! total-fail (+ total-fail fail)) - (printf " ~a: ~a ok, ~a fail\n" f ok fail))) - load-order) - -(printf "\nSCI load: ~a/~a forms ok (~a fail)\n" total-ok (+ total-ok total-fail) total-fail) -(define floor (let ((s (getenv "JOLT_SCI_FLOOR"))) (if s (string->number s) 210))) -(when (< total-ok floor) - (printf "REGRESSION: ~a forms loaded < floor ~a\n" total-ok floor)) -(flush-output-port) -(exit (if (< total-ok floor) 1 0)) diff --git a/host/chez/run-unit.ss b/host/chez/run-unit.ss deleted file mode 100644 index c756ae8..0000000 --- a/host/chez/run-unit.ss +++ /dev/null @@ -1,105 +0,0 @@ -;; run-unit.ss — host-specific unit gate. -;; -;; Loads the checked-in seed + spine, reads test/chez/unit.edn, and for each case -;; evaluates :expr (wrapped in (do ...), as `joltc -e` does) and compares its PRINTED -;; value (jolt-final-str) to the literal :expected string. :expected :throws asserts -;; the case raises. These cover host-specific behavior (dot-forms, java statics, io, -;; reader, walk, …) that isn't in the JVM-portable corpus. Global state is reset -;; between cases for per-case isolation. -;; -;; chez --script host/chez/run-unit.ss -(import (chezscheme)) - -(load "host/chez/rt.ss") -(set-chez-ns! "clojure.core") -(load "host/chez/seed/prelude.ss") -(load "host/chez/post-prelude.ss") -(set-chez-ns! "user") -(load "host/chez/host-contract.ss") -(load "host/chez/seed/image.ss") -(load "host/chez/compile-eval.ss") - -(define (slurp path) - (call-with-input-file path - (lambda (p) - (let loop ((cs '()) (c (read-char p))) - (if (eof-object? c) (list->string (reverse cs)) - (loop (cons c cs) (read-char p))))))) - -(define cases (jolt-read-string (slurp "test/chez/unit.edn"))) -(define kw-suite (keyword #f "suite")) -(define kw-expr (keyword #f "expr")) -(define kw-expected (keyword #f "expected")) -(define kw-throws (keyword #f "throws")) - -;; --- per-case isolation (snapshot the world after setup, restore each case) ------- -(define zj-base (let ((h (make-hashtable string-hash string=?))) - (vector-for-each (lambda (k) (hashtable-set! h k #t)) (hashtable-keys var-table)) h)) -(define zj-roots '()) -(vector-for-each (lambda (k) (let ((c (hashtable-ref var-table k #f))) - (when c (set! zj-roots (cons (cons c (var-cell-root c)) zj-roots))))) - (hashtable-keys var-table)) -(define (zj-snap ht) (let ((h (make-hashtable string-hash string=?))) - (vector-for-each (lambda (k) (hashtable-set! h k #t)) (hashtable-keys ht)) h)) -(define (zj-prune! ht base) (vector-for-each - (lambda (k) (unless (hashtable-ref base k #f) (hashtable-delete! ht k))) (hashtable-keys ht))) -(define zj-ns-base (zj-snap ns-registry)) -(define zj-type-base (zj-snap type-registry)) -(define zj-ghier (var-cell-lookup "clojure.core" "global-hierarchy")) -(define (zj-reset!) - (vector-for-each (lambda (k) (unless (hashtable-ref zj-base k #f) (hashtable-delete! var-table k))) - (hashtable-keys var-table)) - (for-each (lambda (cr) (unless (eq? (var-cell-root (car cr)) (cdr cr)) - (var-cell-root-set! (car cr) (cdr cr)))) zj-roots) - (zj-prune! ns-registry zj-ns-base) - (zj-prune! type-registry zj-type-base) - (hashtable-clear! ns-alias-table) - (hashtable-clear! ns-refer-table) - (hashtable-clear! ns-refer-all-table) - (clear-thread-interrupt!) ; a case that set the runner thread's interrupt flag mustn't leak - (when zj-ghier (jolt-invoke (var-deref "clojure.core" "reset!") - (var-cell-root zj-ghier) (jolt-invoke (var-deref "clojure.core" "make-hierarchy")))) - (set-chez-ns! "user")) - -;; --- run ------------------------------------------------------------------------ -(define pass 0) -(define fails '()) ; (suite expr msg) -(define suite-pass (make-hashtable string-hash string=?)) -(define suite-total (make-hashtable string-hash string=?)) -(define (bump! ht k) (hashtable-set! ht k (+ 1 (hashtable-ref ht k 0)))) - -(let loop ((i 0)) - (when (< i (pvec-count cases)) - (let* ((row (pvec-nth-d cases i jolt-nil)) - (suite (jolt-get row kw-suite)) - (expr (jolt-get row kw-expr)) - (expected (jolt-get row kw-expected)) - (throws? (eq? expected kw-throws)) - (sink (open-output-string))) - (bump! suite-total suite) - (guard (e (#t (if throws? - (begin (set! pass (+ pass 1)) (bump! suite-pass suite)) - (set! fails (cons (list suite expr "raised") fails))))) - (let ((got (jolt-final-str - (parameterize ((current-output-port sink)) - (jolt-compile-eval (string-append "(do " expr ")") "user"))))) - (cond - (throws? (set! fails (cons (list suite expr (string-append "expected throw; got " got)) fails))) - ((string=? got expected) (begin (set! pass (+ pass 1)) (bump! suite-pass suite))) - (else (set! fails (cons (list suite expr - (string-append "want `" expected "` got `" got "`")) fails)))))) - (zj-reset!)) - (loop (+ i 1)))) - -(printf "\nunit gate: ~a/~a passed\n" pass (pvec-count cases)) -(let-values (((ks vs) (hashtable-entries suite-total))) - (for-each (lambda (p) - (printf " ~a/~a ~a\n" (hashtable-ref suite-pass (car p) 0) (cdr p) (car p))) - (list-sort (lambda (a b) (stringlist (vector-map cons ks vs))))) -(when (> (length fails) 0) - (printf "\n~a FAIL(s):\n" (length fails)) - (for-each (lambda (f) (printf " [~a] ~a\n ~a\n" (car f) (caddr f) (cadr f))) - (list-head (reverse fails) (min 40 (length fails))))) -(flush-output-port) -(exit (if (> (length fails) 0) 1 0)) diff --git a/host/chez/run-wp.ss b/host/chez/run-wp.ss deleted file mode 100644 index 84fbf2b..0000000 --- a/host/chez/run-wp.ss +++ /dev/null @@ -1,108 +0,0 @@ -;; run-wp.ss — whole-program param-type fixpoint gate (jolt.passes.types/wp-infer!). -;; -;; run-infer.ss drives the per-form inference; this drives the inter-procedural -;; driver: analyze a multi-def unit, run wp-infer!, and assert that a record type -;; flows across fn boundaries — a callee's param picks up its caller's ctor return -;; type, so a field read off it is marked for the bare-index back-end path. -;; -;; chez --script host/chez/run-wp.ss -(import (chezscheme)) -(load "host/chez/rt.ss") -(set-chez-ns! "clojure.core") -(load "host/chez/seed/prelude.ss") -(load "host/chez/post-prelude.ss") -(set-chez-ns! "user") -(load "host/chez/host-contract.ss") -(load "host/chez/seed/image.ss") -(load "host/chez/compile-eval.ss") - -(define analyze (var-deref "jolt.analyzer" "analyze")) -(define run-inference (var-deref "jolt.passes.types" "run-inference")) -(define set-record-shapes! (var-deref "jolt.passes.types" "set-record-shapes!")) -(define set-protocol-methods! (var-deref "jolt.passes.types" "set-protocol-methods!")) -(define wp-infer! (var-deref "jolt.passes.types" "wp-infer!")) -(define param-seeds-for (var-deref "jolt.passes.types" "param-seeds-for")) -(define reinfer-def (var-deref "jolt.passes.types" "reinfer-def")) -(define pr-str (var-deref "clojure.core" "pr-str")) - -(define (anode src) (analyze (make-analyze-ctx "user") (jolt-ce-read src))) -(define (contains-sub? s sub) - (let ((n (string-length s)) (m (string-length sub))) - (let loop ((i 0)) - (cond ((> (+ i m) n) #f) - ((string=? (substring s i (+ i m)) sub) #t) - (else (loop (+ i 1))))))) - -(define fails 0) (define total 0) -(define (check label actual expected) - (set! total (+ total 1)) - (unless (equal? actual expected) - (set! fails (+ fails 1)) - (printf " FAIL ~a: got ~s expected ~s\n" label actual expected))) - -;; Node record shape (left/right untagged), like binary-trees. -(set-record-shapes! - (jolt-hash-map "user/->Node" - (jolt-hash-map (keyword #f "fields") (jolt-vector (keyword #f "left") (keyword #f "right")) - (keyword #f "tags") (jolt-vector jolt-nil jolt-nil) - (keyword #f "type") "user.Node"))) -(set-protocol-methods! (jolt-hash-map)) - -;; a 3-def unit: make-tree returns ->Node, run calls check-tree with a make-tree -;; result, so check-tree's `node` param must be inferred as a Node. -(define mt (anode "(def make-tree (fn [depth] (if (zero? depth) (->Node nil nil) (->Node (make-tree (dec depth)) (make-tree (dec depth))))))")) -(define ct (anode "(def check-tree (fn [node] (:left node)))")) -(define rn (anode "(def run (fn [d] (check-tree (make-tree d))))")) - -(wp-infer! (jolt-vector mt ct rn)) - -;; check-tree's param `node` should be seeded with a struct carrying the Node type -(define seed (param-seeds-for "user/check-tree")) -(check "check-tree has a param seed" (jolt-truthy? seed) #t) -(when (jolt-truthy? seed) - (check "node seeded as user.Node struct" - (contains-sub? (pr-str seed) "user.Node") #t)) - -;; reinfer-def then must mark the (:left node) read site for the bare-index path -(define marked (reinfer-def ct seed)) -(check "read site marked :hint :struct" (contains-sub? (pr-str marked) ":hint :struct") #t) - -;; a fn used only via value position (escape) must NOT be specialized — unknown -;; callers make a concrete seed unsound. -(define ev (anode "(def use-it (fn [f] (f 1)))")) -(define ec (anode "(def caller (fn [] (use-it check-tree)))")) ; check-tree escapes -(wp-infer! (jolt-vector mt ct rn ev ec)) -(check "escaped fn keeps no param seed" (jolt-truthy? (param-seeds-for "user/check-tree")) #f) - -;; a self-recursive fn that recurses on a NILABLE field (an untagged record field -;; is :any, so the child can be nil) must NOT be specialized — the recursion can -;; pass nil, so typing the param as a non-nil record would be unsound. -(define ctr (anode "(def walk (fn [node] (let [l (:left node)] (if (nil? l) 1 (walk l)))))")) -(define rnr (anode "(def run2 (fn [d] (walk (make-tree d))))")) -(wp-infer! (jolt-vector mt ctr rnr)) -(check "self-recursive nilable param not specialized" - (jolt-truthy? (param-seeds-for "user/walk")) #f) - -;; a self-recursive fn that recurses passing the SAME record type (make-tree always -;; returns a Node) is still safe to specialize — the recursion preserves the type. -(define mtt (anode "(def grow (fn [n acc] (if (zero? n) acc (grow (dec n) (->Node acc acc)))))")) -(define gcl (anode "(def gcaller (fn [] (grow 5 (->Node nil nil))))")) -(wp-infer! (jolt-vector mtt gcl)) -(check "self-recursive same-type param keeps its seed" - (jolt-truthy? (param-seeds-for "user/grow")) #t) - -;; a recursive fn that threads a param STRAIGHT THROUGH its recursion (same arg at -;; the same position) must keep that param's type — a pass-through self-call adds no -;; information and must not poison the param to :any. This is the ray tracer's -;; hittables, passed unchanged through ray-cast's recursion while its reduce element -;; reads the records' fields. -(define cwalk (anode "(def cwalk (fn [hs] (reduce (fn [acc h] (:left h)) nil hs)))")) -(define crec (anode "(def crec (fn [hs d] (if (< d 0) nil (do (cwalk hs) (crec hs (- d 1))))))")) -(define cdrv (anode "(def cdrive (fn [] (crec [(->Node nil nil) (->Node nil nil)] 5)))")) -(wp-infer! (jolt-vector cwalk crec cdrv)) -(check "recursion pass-through param keeps its vec element type" - (contains-sub? (pr-str (param-seeds-for "user/crec")) "user.Node") #t) - -(if (= fails 0) - (begin (printf "wp gate: ~a/~a passed\n" total total) (exit 0)) - (begin (printf "wp gate: ~a/~a passed (~a failed)\n" (- total fails) total fails) (exit 1))) diff --git a/host/chez/seed/README.md b/host/chez/seed/README.md deleted file mode 100644 index 65833b8..0000000 --- a/host/chez/seed/README.md +++ /dev/null @@ -1,25 +0,0 @@ -# Chez bootstrap seed - -These two files are the **bootstrap compiler** for jolt — the seed that makes -the build self-hosting: - -- `prelude.ss` — the `clojure.core` prelude (all tiers + clojure.string/walk/ - template/edn/set/pprint) as Scheme `def-var!` forms. -- `image.ss` — the compiler image (`jolt.ir` + `jolt.analyzer` + - `jolt.backend-scheme`) as Scheme `def-var!` forms. - -Both are **generated**, not hand-written. They are checked in because a fresh -checkout must be able to build jolt-on-Chez using only Chez: `host/chez/bootstrap.ss` -loads this seed, then rebuilds the prelude + image from the `.clj`/`.ss` sources via -the on-Chez compiler (read → analyze → emit, all on Chez). The seed is a **joint -byte-fixpoint**: rebuilding from an up-to-date seed reproduces it exactly. -`make selfhost` (`host/chez/selfcheck.sh`) runs `host/chez/bootstrap.ss` and diffs -the rebuilt artifacts against the checked-in seed. - -## Re-minting - -When the seed sources change (the core tiers, the compiler namespaces, the host -contract, the reader, `emit-image.ss`), the seed drifts and `make selfhost` -fails. Re-mint it by running `host/chez/bootstrap.ss` and writing the freshly -rebuilt prelude/image back to `host/chez/seed/prelude.ss` / -`host/chez/seed/image.ss`, then commit the refreshed files. diff --git a/host/chez/seed/image.ss b/host/chez/seed/image.ss deleted file mode 100644 index c51e971..0000000 --- a/host/chez/seed/image.ss +++ /dev/null @@ -1,636 +0,0 @@ -(guard (e (#t #f)) - (def-var! "jolt.ir" "const" (letrec ((const (lambda (v) (let fnrec8455 ((v v)) (let* ((_o$8456 (keyword #f "op")) (_o$8457 (keyword #f "const")) (_o$8458 (keyword #f "val")) (_o$8459 v)) (jolt-hash-map _o$8456 _o$8457 _o$8458 _o$8459)))))) const))) -(guard (e (#t #f)) - (def-var! "jolt.ir" "local" (letrec ((local (lambda (name) (let fnrec8460 ((name name)) (let* ((_o$8461 (keyword #f "op")) (_o$8462 (keyword #f "local")) (_o$8463 (keyword #f "name")) (_o$8464 name)) (jolt-hash-map _o$8461 _o$8462 _o$8463 _o$8464)))))) local))) -(guard (e (#t #f)) - (def-var! "jolt.ir" "var-ref" (letrec ((var-ref (lambda (ns name) (let fnrec8465 ((ns ns) (name name)) (let* ((_o$8466 (keyword #f "op")) (_o$8467 (keyword #f "var")) (_o$8468 (keyword #f "ns")) (_o$8469 ns) (_o$8470 (keyword #f "name")) (_o$8471 name)) (jolt-hash-map _o$8466 _o$8467 _o$8468 _o$8469 _o$8470 _o$8471)))))) var-ref))) -(guard (e (#t #f)) - (def-var! "jolt.ir" "the-var" (letrec ((the-var (lambda (ns name) (let fnrec8472 ((ns ns) (name name)) (let* ((_o$8473 (keyword #f "op")) (_o$8474 (keyword #f "the-var")) (_o$8475 (keyword #f "ns")) (_o$8476 ns) (_o$8477 (keyword #f "name")) (_o$8478 name)) (jolt-hash-map _o$8473 _o$8474 _o$8475 _o$8476 _o$8477 _o$8478)))))) the-var))) -(guard (e (#t #f)) - (def-var! "jolt.ir" "host-ref" (letrec ((host-ref (lambda (name) (let fnrec8479 ((name name)) (let* ((_o$8480 (keyword #f "op")) (_o$8481 (keyword #f "host")) (_o$8482 (keyword #f "name")) (_o$8483 name)) (jolt-hash-map _o$8480 _o$8481 _o$8482 _o$8483)))))) host-ref))) -(guard (e (#t #f)) - (def-var! "jolt.ir" "host-static" (letrec ((host-static (lambda (class member) (let fnrec8484 ((class class) (member member)) (let* ((_o$8485 (keyword #f "op")) (_o$8486 (keyword #f "host-static")) (_o$8487 (keyword #f "class")) (_o$8488 class) (_o$8489 (keyword #f "member")) (_o$8490 member)) (jolt-hash-map _o$8485 _o$8486 _o$8487 _o$8488 _o$8489 _o$8490)))))) host-static))) -(guard (e (#t #f)) - (def-var! "jolt.ir" "host-new" (letrec ((host-new (lambda (class args) (let fnrec8491 ((class class) (args args)) (let* ((_o$8492 (keyword #f "op")) (_o$8493 (keyword #f "host-new")) (_o$8494 (keyword #f "class")) (_o$8495 class) (_o$8496 (keyword #f "args")) (_o$8497 args)) (jolt-hash-map _o$8492 _o$8493 _o$8494 _o$8495 _o$8496 _o$8497)))))) host-new))) -(guard (e (#t #f)) - (def-var! "jolt.ir" "if-node" (letrec ((if-node (lambda (test then _else) (let fnrec8498 ((test test) (then then) (_else _else)) (let* ((_o$8499 (keyword #f "op")) (_o$8500 (keyword #f "if")) (_o$8501 (keyword #f "test")) (_o$8502 test) (_o$8503 (keyword #f "then")) (_o$8504 then) (_o$8505 (keyword #f "else")) (_o$8506 _else)) (jolt-hash-map _o$8499 _o$8500 _o$8501 _o$8502 _o$8503 _o$8504 _o$8505 _o$8506)))))) if-node))) -(guard (e (#t #f)) - (def-var! "jolt.ir" "do-node" (letrec ((do-node (lambda (statements ret) (let fnrec8507 ((statements statements) (ret ret)) (let* ((_o$8508 (keyword #f "op")) (_o$8509 (keyword #f "do")) (_o$8510 (keyword #f "statements")) (_o$8511 statements) (_o$8512 (keyword #f "ret")) (_o$8513 ret)) (jolt-hash-map _o$8508 _o$8509 _o$8510 _o$8511 _o$8512 _o$8513)))))) do-node))) -(guard (e (#t #f)) - (def-var! "jolt.ir" "invoke" (letrec ((invoke (lambda (f args) (let fnrec8514 ((f f) (args args)) (let* ((_o$8515 (keyword #f "op")) (_o$8516 (keyword #f "invoke")) (_o$8517 (keyword #f "fn")) (_o$8518 f) (_o$8519 (keyword #f "args")) (_o$8520 args)) (jolt-hash-map _o$8515 _o$8516 _o$8517 _o$8518 _o$8519 _o$8520)))))) invoke))) -(guard (e (#t #f)) - (def-var! "jolt.ir" "def-node" (letrec ((def-node (case-lambda ((ns name init) (let fnrec8521 ((ns ns) (name name) (init init)) (let* ((_o$8522 (keyword #f "op")) (_o$8523 (keyword #f "def")) (_o$8524 (keyword #f "ns")) (_o$8525 ns) (_o$8526 (keyword #f "name")) (_o$8527 name) (_o$8528 (keyword #f "init")) (_o$8529 init)) (jolt-hash-map _o$8522 _o$8523 _o$8524 _o$8525 _o$8526 _o$8527 _o$8528 _o$8529)))) ((ns name init meta) (let fnrec8530 ((ns ns) (name name) (init init) (meta meta)) (if (jolt-truthy? meta) (let* ((_o$8531 (keyword #f "op")) (_o$8532 (keyword #f "def")) (_o$8533 (keyword #f "ns")) (_o$8534 ns) (_o$8535 (keyword #f "name")) (_o$8536 name) (_o$8537 (keyword #f "init")) (_o$8538 init) (_o$8539 (keyword #f "meta")) (_o$8540 meta)) (jolt-hash-map _o$8531 _o$8532 _o$8533 _o$8534 _o$8535 _o$8536 _o$8537 _o$8538 _o$8539 _o$8540)) (let* ((_o$8541 (keyword #f "op")) (_o$8542 (keyword #f "def")) (_o$8543 (keyword #f "ns")) (_o$8544 ns) (_o$8545 (keyword #f "name")) (_o$8546 name) (_o$8547 (keyword #f "init")) (_o$8548 init)) (jolt-hash-map _o$8541 _o$8542 _o$8543 _o$8544 _o$8545 _o$8546 _o$8547 _o$8548)))))))) def-node))) -(guard (e (#t #f)) - (def-var! "jolt.ir" "let-node" (letrec ((let-node (lambda (bindings body) (let fnrec8549 ((bindings bindings) (body body)) (let* ((_o$8550 (keyword #f "op")) (_o$8551 (keyword #f "let")) (_o$8552 (keyword #f "bindings")) (_o$8553 bindings) (_o$8554 (keyword #f "body")) (_o$8555 body)) (jolt-hash-map _o$8550 _o$8551 _o$8552 _o$8553 _o$8554 _o$8555)))))) let-node))) -(guard (e (#t #f)) - (def-var! "jolt.ir" "fn-node" (letrec ((fn-node (lambda (name arities) (let fnrec8556 ((name name) (arities arities)) (if (jolt-truthy? name) (let* ((_o$8557 (keyword #f "op")) (_o$8558 (keyword #f "fn")) (_o$8559 (keyword #f "name")) (_o$8560 name) (_o$8561 (keyword #f "arities")) (_o$8562 arities)) (jolt-hash-map _o$8557 _o$8558 _o$8559 _o$8560 _o$8561 _o$8562)) (let* ((_o$8563 (keyword #f "op")) (_o$8564 (keyword #f "fn")) (_o$8565 (keyword #f "arities")) (_o$8566 arities)) (jolt-hash-map _o$8563 _o$8564 _o$8565 _o$8566))))))) fn-node))) -(guard (e (#t #f)) - (def-var! "jolt.ir" "vector-node" (letrec ((vector-node (lambda (items) (let fnrec8567 ((items items)) (let* ((_o$8568 (keyword #f "op")) (_o$8569 (keyword #f "vector")) (_o$8570 (keyword #f "items")) (_o$8571 items)) (jolt-hash-map _o$8568 _o$8569 _o$8570 _o$8571)))))) vector-node))) -(guard (e (#t #f)) - (def-var! "jolt.ir" "map-node" (letrec ((map-node (lambda (pairs) (let fnrec8572 ((pairs pairs)) (let* ((_o$8573 (keyword #f "op")) (_o$8574 (keyword #f "map")) (_o$8575 (keyword #f "pairs")) (_o$8576 pairs)) (jolt-hash-map _o$8573 _o$8574 _o$8575 _o$8576)))))) map-node))) -(guard (e (#t #f)) - (def-var! "jolt.ir" "set-node" (letrec ((set-node (lambda (items) (let fnrec8577 ((items items)) (let* ((_o$8578 (keyword #f "op")) (_o$8579 (keyword #f "set")) (_o$8580 (keyword #f "items")) (_o$8581 items)) (jolt-hash-map _o$8578 _o$8579 _o$8580 _o$8581)))))) set-node))) -(guard (e (#t #f)) - (def-var! "jolt.ir" "quote-node" (letrec ((quote-node (lambda (form) (let fnrec8582 ((form form)) (let* ((_o$8583 (keyword #f "op")) (_o$8584 (keyword #f "quote")) (_o$8585 (keyword #f "form")) (_o$8586 form)) (jolt-hash-map _o$8583 _o$8584 _o$8585 _o$8586)))))) quote-node))) -(guard (e (#t #f)) - (def-var! "jolt.ir" "throw-node" (letrec ((throw-node (lambda (expr) (let fnrec8587 ((expr expr)) (let* ((_o$8588 (keyword #f "op")) (_o$8589 (keyword #f "throw")) (_o$8590 (keyword #f "expr")) (_o$8591 expr)) (jolt-hash-map _o$8588 _o$8589 _o$8590 _o$8591)))))) throw-node))) -(guard (e (#t #f)) - (def-var! "jolt.ir" "coerce-node" (letrec ((coerce-node (lambda (kind expr) (let fnrec8592 ((kind kind) (expr expr)) (let* ((_o$8593 (keyword #f "op")) (_o$8594 (keyword #f "coerce")) (_o$8595 (keyword #f "kind")) (_o$8596 kind) (_o$8597 (keyword #f "expr")) (_o$8598 expr)) (jolt-hash-map _o$8593 _o$8594 _o$8595 _o$8596 _o$8597 _o$8598)))))) coerce-node))) -(guard (e (#t #f)) - (def-var! "jolt.ir" "map-ir-children" (letrec ((map-ir-children (lambda (f node) (let fnrec8599 ((f f) (node node)) (let* ((op (jolt-get node (keyword #f "op")))) (if (jolt= op (keyword #f "if")) (let* ((_a$8600 node) (_a$8601 (keyword #f "test")) (_a$8602 (jolt-invoke f (jolt-get node (keyword #f "test")))) (_a$8603 (keyword #f "then")) (_a$8604 (jolt-invoke f (jolt-get node (keyword #f "then")))) (_a$8605 (keyword #f "else")) (_a$8606 (jolt-invoke f (jolt-get node (keyword #f "else"))))) (jolt-assoc _a$8600 _a$8601 _a$8602 _a$8603 _a$8604 _a$8605 _a$8606)) (if (jolt= op (keyword #f "do")) (let* ((_a$8607 node) (_a$8608 (keyword #f "statements")) (_a$8609 (jolt-invoke (var-deref "clojure.core" "mapv") f (jolt-get node (keyword #f "statements")))) (_a$8610 (keyword #f "ret")) (_a$8611 (jolt-invoke f (jolt-get node (keyword #f "ret"))))) (jolt-assoc _a$8607 _a$8608 _a$8609 _a$8610 _a$8611)) (if (jolt= op (keyword #f "throw")) (jolt-assoc node (keyword #f "expr") (jolt-invoke f (jolt-get node (keyword #f "expr")))) (if (jolt= op (keyword #f "coerce")) (jolt-assoc node (keyword #f "expr") (jolt-invoke f (jolt-get node (keyword #f "expr")))) (if (jolt= op (keyword #f "set-var")) (jolt-assoc node (keyword #f "val") (jolt-invoke f (jolt-get node (keyword #f "val")))) (if (jolt= op (keyword #f "set-field")) (let* ((_a$8612 node) (_a$8613 (keyword #f "obj")) (_a$8614 (jolt-invoke f (jolt-get node (keyword #f "obj")))) (_a$8615 (keyword #f "val")) (_a$8616 (jolt-invoke f (jolt-get node (keyword #f "val"))))) (jolt-assoc _a$8612 _a$8613 _a$8614 _a$8615 _a$8616)) (if (jolt= op (keyword #f "defmacro")) (jolt-assoc node (keyword #f "fn") (jolt-invoke f (jolt-get node (keyword #f "fn")))) (if (jolt= op (keyword #f "ffi-callable")) (jolt-assoc node (keyword #f "fn") (jolt-invoke f (jolt-get node (keyword #f "fn")))) (if (jolt= op (keyword #f "invoke")) (let* ((_a$8617 node) (_a$8618 (keyword #f "fn")) (_a$8619 (jolt-invoke f (jolt-get node (keyword #f "fn")))) (_a$8620 (keyword #f "args")) (_a$8621 (jolt-invoke (var-deref "clojure.core" "mapv") f (jolt-get node (keyword #f "args"))))) (jolt-assoc _a$8617 _a$8618 _a$8619 _a$8620 _a$8621)) (if (jolt= op (keyword #f "vector")) (jolt-assoc node (keyword #f "items") (jolt-invoke (var-deref "clojure.core" "mapv") f (jolt-get node (keyword #f "items")))) (if (jolt= op (keyword #f "set")) (jolt-assoc node (keyword #f "items") (jolt-invoke (var-deref "clojure.core" "mapv") f (jolt-get node (keyword #f "items")))) (if (jolt= op (keyword #f "map")) (jolt-assoc node (keyword #f "pairs") (let* ((_a$8625 (var-deref "clojure.core" "mapv")) (_a$8626 (lambda (pr) (let fnrec8622 ((pr pr)) (let* ((_o$8623 (jolt-invoke f (jolt-nth pr 0))) (_o$8624 (jolt-invoke f (jolt-nth pr 1)))) (jolt-vector _o$8623 _o$8624))))) (_a$8627 (jolt-get node (keyword #f "pairs")))) (jolt-invoke _a$8625 _a$8626 _a$8627))) (if (jolt= op (keyword #f "let")) (let* ((_a$8634 node) (_a$8635 (keyword #f "bindings")) (_a$8636 (let* ((_a$8631 (var-deref "clojure.core" "mapv")) (_a$8632 (lambda (b) (let fnrec8628 ((b b)) (let* ((_o$8629 (jolt-nth b 0)) (_o$8630 (jolt-invoke f (jolt-nth b 1)))) (jolt-vector _o$8629 _o$8630))))) (_a$8633 (jolt-get node (keyword #f "bindings")))) (jolt-invoke _a$8631 _a$8632 _a$8633))) (_a$8637 (keyword #f "body")) (_a$8638 (jolt-invoke f (jolt-get node (keyword #f "body"))))) (jolt-assoc _a$8634 _a$8635 _a$8636 _a$8637 _a$8638)) (if (jolt= op (keyword #f "loop")) (let* ((_a$8645 node) (_a$8646 (keyword #f "bindings")) (_a$8647 (let* ((_a$8642 (var-deref "clojure.core" "mapv")) (_a$8643 (lambda (b) (let fnrec8639 ((b b)) (let* ((_o$8640 (jolt-nth b 0)) (_o$8641 (jolt-invoke f (jolt-nth b 1)))) (jolt-vector _o$8640 _o$8641))))) (_a$8644 (jolt-get node (keyword #f "bindings")))) (jolt-invoke _a$8642 _a$8643 _a$8644))) (_a$8648 (keyword #f "body")) (_a$8649 (jolt-invoke f (jolt-get node (keyword #f "body"))))) (jolt-assoc _a$8645 _a$8646 _a$8647 _a$8648 _a$8649)) (if (jolt= op (keyword #f "recur")) (jolt-assoc node (keyword #f "args") (jolt-invoke (var-deref "clojure.core" "mapv") f (jolt-get node (keyword #f "args")))) (if (jolt= op (keyword #f "fn")) (jolt-assoc node (keyword #f "arities") (let* ((_a$8651 (var-deref "clojure.core" "mapv")) (_a$8652 (lambda (a) (let fnrec8650 ((a a)) (jolt-assoc a (keyword #f "body") (jolt-invoke f (jolt-get a (keyword #f "body"))))))) (_a$8653 (jolt-get node (keyword #f "arities")))) (jolt-invoke _a$8651 _a$8652 _a$8653))) (if (jolt= op (keyword #f "def")) (let* ((n (jolt-assoc node (keyword #f "init") (jolt-invoke f (jolt-get node (keyword #f "init")))))) (if (jolt-truthy? (jolt-get node (keyword #f "meta-expr"))) (jolt-assoc n (keyword #f "meta-expr") (jolt-invoke f (jolt-get node (keyword #f "meta-expr")))) n)) (if (jolt= op (keyword #f "host-call")) (let* ((_a$8654 node) (_a$8655 (keyword #f "target")) (_a$8656 (jolt-invoke f (jolt-get node (keyword #f "target")))) (_a$8657 (keyword #f "args")) (_a$8658 (jolt-invoke (var-deref "clojure.core" "mapv") f (jolt-get node (keyword #f "args"))))) (jolt-assoc _a$8654 _a$8655 _a$8656 _a$8657 _a$8658)) (if (jolt= op (keyword #f "host-new")) (jolt-assoc node (keyword #f "args") (jolt-invoke (var-deref "clojure.core" "mapv") f (jolt-get node (keyword #f "args")))) (if (jolt= op (keyword #f "try")) (let* ((n (jolt-assoc node (keyword #f "body") (jolt-invoke f (jolt-get node (keyword #f "body"))))) (n (if (jolt-truthy? (jolt-get node (keyword #f "catch-body"))) (jolt-assoc n (keyword #f "catch-body") (jolt-invoke f (jolt-get node (keyword #f "catch-body")))) n)) (n (if (jolt-truthy? (jolt-get node (keyword #f "finally"))) (jolt-assoc n (keyword #f "finally") (jolt-invoke f (jolt-get node (keyword #f "finally")))) n))) n) (if (jolt-truthy? (keyword #f "else")) node jolt-nil)))))))))))))))))))))))))) map-ir-children))) -(guard (e (#t #f)) - (def-var! "jolt.ir" "reduce-ir-children" (letrec ((reduce-ir-children (lambda (f acc node) (let fnrec8659 ((f f) (acc acc) (node node)) (let* ((op (jolt-get node (keyword #f "op")))) (if (jolt= op (keyword #f "if")) (let* ((_a$8663 f) (_a$8664 (let* ((_a$8660 f) (_a$8661 (jolt-invoke f acc (jolt-get node (keyword #f "test")))) (_a$8662 (jolt-get node (keyword #f "then")))) (jolt-invoke _a$8660 _a$8661 _a$8662))) (_a$8665 (jolt-get node (keyword #f "else")))) (jolt-invoke _a$8663 _a$8664 _a$8665)) (if (jolt= op (keyword #f "do")) (let* ((_a$8666 f) (_a$8667 (jolt-reduce f acc (jolt-get node (keyword #f "statements")))) (_a$8668 (jolt-get node (keyword #f "ret")))) (jolt-invoke _a$8666 _a$8667 _a$8668)) (if (jolt= op (keyword #f "throw")) (jolt-invoke f acc (jolt-get node (keyword #f "expr"))) (if (jolt= op (keyword #f "coerce")) (jolt-invoke f acc (jolt-get node (keyword #f "expr"))) (if (jolt= op (keyword #f "set-var")) (jolt-invoke f acc (jolt-get node (keyword #f "val"))) (if (jolt= op (keyword #f "set-field")) (let* ((_a$8669 f) (_a$8670 (jolt-invoke f acc (jolt-get node (keyword #f "obj")))) (_a$8671 (jolt-get node (keyword #f "val")))) (jolt-invoke _a$8669 _a$8670 _a$8671)) (if (jolt= op (keyword #f "defmacro")) (jolt-invoke f acc (jolt-get node (keyword #f "fn"))) (if (jolt= op (keyword #f "ffi-callable")) (jolt-invoke f acc (jolt-get node (keyword #f "fn"))) (if (jolt= op (keyword #f "invoke")) (let* ((_a$8672 f) (_a$8673 (jolt-invoke f acc (jolt-get node (keyword #f "fn")))) (_a$8674 (jolt-get node (keyword #f "args")))) (jolt-reduce _a$8672 _a$8673 _a$8674)) (if (jolt= op (keyword #f "vector")) (jolt-reduce f acc (jolt-get node (keyword #f "items"))) (if (jolt= op (keyword #f "set")) (jolt-reduce f acc (jolt-get node (keyword #f "items"))) (if (jolt= op (keyword #f "map")) (let* ((_a$8679 (lambda (a pr) (let fnrec8675 ((a a) (pr pr)) (let* ((_a$8676 f) (_a$8677 (jolt-invoke f a (jolt-nth pr 0))) (_a$8678 (jolt-nth pr 1))) (jolt-invoke _a$8676 _a$8677 _a$8678))))) (_a$8680 acc) (_a$8681 (jolt-get node (keyword #f "pairs")))) (jolt-reduce _a$8679 _a$8680 _a$8681)) (if (jolt= op (keyword #f "let")) (let* ((_a$8686 f) (_a$8687 (let* ((_a$8683 (lambda (a b) (let fnrec8682 ((a a) (b b)) (jolt-invoke f a (jolt-nth b 1))))) (_a$8684 acc) (_a$8685 (jolt-get node (keyword #f "bindings")))) (jolt-reduce _a$8683 _a$8684 _a$8685))) (_a$8688 (jolt-get node (keyword #f "body")))) (jolt-invoke _a$8686 _a$8687 _a$8688)) (if (jolt= op (keyword #f "loop")) (let* ((_a$8693 f) (_a$8694 (let* ((_a$8690 (lambda (a b) (let fnrec8689 ((a a) (b b)) (jolt-invoke f a (jolt-nth b 1))))) (_a$8691 acc) (_a$8692 (jolt-get node (keyword #f "bindings")))) (jolt-reduce _a$8690 _a$8691 _a$8692))) (_a$8695 (jolt-get node (keyword #f "body")))) (jolt-invoke _a$8693 _a$8694 _a$8695)) (if (jolt= op (keyword #f "recur")) (jolt-reduce f acc (jolt-get node (keyword #f "args"))) (if (jolt= op (keyword #f "fn")) (let* ((_a$8697 (lambda (a ar) (let fnrec8696 ((a a) (ar ar)) (jolt-invoke f a (jolt-get ar (keyword #f "body")))))) (_a$8698 acc) (_a$8699 (jolt-get node (keyword #f "arities")))) (jolt-reduce _a$8697 _a$8698 _a$8699)) (if (jolt= op (keyword #f "def")) (let* ((a (if (jolt-truthy? (jolt-get node (keyword #f "init"))) (jolt-invoke f acc (jolt-get node (keyword #f "init"))) acc))) (if (jolt-truthy? (jolt-get node (keyword #f "meta-expr"))) (jolt-invoke f a (jolt-get node (keyword #f "meta-expr"))) a)) (if (jolt= op (keyword #f "host-call")) (let* ((_a$8700 f) (_a$8701 (jolt-invoke f acc (jolt-get node (keyword #f "target")))) (_a$8702 (jolt-get node (keyword #f "args")))) (jolt-reduce _a$8700 _a$8701 _a$8702)) (if (jolt= op (keyword #f "host-new")) (jolt-reduce f acc (jolt-get node (keyword #f "args"))) (if (jolt= op (keyword #f "try")) (let* ((a (jolt-invoke f acc (jolt-get node (keyword #f "body")))) (a (if (jolt-truthy? (jolt-get node (keyword #f "catch-body"))) (jolt-invoke f a (jolt-get node (keyword #f "catch-body"))) a)) (a (if (jolt-truthy? (jolt-get node (keyword #f "finally"))) (jolt-invoke f a (jolt-get node (keyword #f "finally"))) a))) a) (if (jolt-truthy? (keyword #f "else")) acc jolt-nil)))))))))))))))))))))))))) reduce-ir-children))) -(guard (e (#t #f)) - (declare-var! "jolt.analyzer" "analyze")) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.analyzer" "handled" (let* ((_o$8703 "quote") (_o$8704 "if") (_o$8705 "do") (_o$8706 "def") (_o$8707 "fn*") (_o$8708 "let*") (_o$8709 "loop*") (_o$8710 "recur") (_o$8711 "throw") (_o$8712 "try") (_o$8713 "syntax-quote") (_o$8714 "var") (_o$8715 "letfn*") (_o$8716 "set!") (_o$8717 "defmacro")) (jolt-hash-set _o$8703 _o$8704 _o$8705 _o$8706 _o$8707 _o$8708 _o$8709 _o$8710 _o$8711 _o$8712 _o$8713 _o$8714 _o$8715 _o$8716 _o$8717)) (let* ((_o$8718 (keyword #f "private")) (_o$8719 #t)) (jolt-hash-map _o$8718 _o$8719)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.analyzer" "uncompilable" (letrec ((uncompilable (lambda (why) (let fnrec8720 ((why why)) (jolt-throw (jolt-invoke (var-deref "clojure.core" "str") "jolt/uncompilable: " why)))))) uncompilable) (let* ((_o$8721 (keyword #f "private")) (_o$8722 #t)) (jolt-hash-map _o$8721 _o$8722)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.analyzer" "gensym-counter" (jolt-invoke (var-deref "clojure.core" "atom") 0) (let* ((_o$8723 (keyword #f "private")) (_o$8724 #t)) (jolt-hash-map _o$8723 _o$8724)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.analyzer" "gen-name" (letrec ((gen-name (lambda (prefix) (let fnrec8725 ((prefix prefix)) (let* ((n (jolt-invoke (var-deref "clojure.core" "deref") (var-deref "jolt.analyzer" "gensym-counter")))) (begin (jolt-invoke (var-deref "clojure.core" "swap!") (var-deref "jolt.analyzer" "gensym-counter") jolt-inc) (jolt-invoke (var-deref "clojure.core" "str") "_r$" prefix n))))))) gen-name) (let* ((_o$8726 (keyword #f "private")) (_o$8727 #t)) (jolt-hash-map _o$8726 _o$8727)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.analyzer" "empty-env" (letrec ((empty-env (lambda () (let fnrec8728 () (let* ((_o$8729 (keyword #f "locals")) (_o$8730 (jolt-hash-set)) (_o$8731 (keyword #f "hints")) (_o$8732 (jolt-hash-map))) (jolt-hash-map _o$8729 _o$8730 _o$8731 _o$8732)))))) empty-env) (let* ((_o$8733 (keyword #f "private")) (_o$8734 #t)) (jolt-hash-map _o$8733 _o$8734)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.analyzer" "local?" (letrec ((local? (lambda (env nm) (let fnrec8735 ((env env) (nm nm)) (jolt-contains? (jolt-get env (keyword #f "locals")) nm))))) local?) (let* ((_o$8736 (keyword #f "private")) (_o$8737 #t)) (jolt-hash-map _o$8736 _o$8737)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.analyzer" "add-locals" (letrec ((add-locals (lambda (env names) (let fnrec8738 ((env env) (names names)) (jolt-invoke (var-deref "clojure.core" "update") env (keyword #f "locals") (lambda (p__97_) (let fnrec8739 ((p__97_ p__97_)) (jolt-reduce jolt-conj p__97_ names)))))))) add-locals) (let* ((_o$8740 (keyword #f "private")) (_o$8741 #t)) (jolt-hash-map _o$8740 _o$8741)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.analyzer" "amp-env-map" (letrec ((amp-env-map (lambda (env) (let fnrec8742 ((env env)) (let* ((_a$8744 (lambda (m n) (let fnrec8743 ((m m) (n n)) (jolt-assoc m (jolt-invoke (var-deref "clojure.core" "symbol") n) jolt-nil)))) (_a$8745 (jolt-hash-map)) (_a$8746 (jolt-get env (keyword #f "locals")))) (jolt-reduce _a$8744 _a$8745 _a$8746)))))) amp-env-map) (let* ((_o$8747 (keyword #f "private")) (_o$8748 #t)) (jolt-hash-map _o$8747 _o$8748)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.analyzer" "with-recur" (letrec ((with-recur (lambda (env name) (let fnrec8749 ((env env) (name name)) (jolt-assoc env (keyword #f "recur") name))))) with-recur) (let* ((_o$8750 (keyword #f "private")) (_o$8751 #t)) (jolt-hash-map _o$8750 _o$8751)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.analyzer" "hint-of" (letrec ((hint-of (lambda (ctx sym) (let fnrec8752 ((ctx ctx) (sym sym)) (let* ((m (jolt-invoke (var-deref "jolt.host" "form-sym-meta") sym))) (if (jolt-nil? m) jolt-nil (if (jolt-truthy? (jolt-get m (keyword #f "struct"))) (keyword #f "struct") (if (jolt-truthy? (keyword #f "else")) (let* ((t (jolt-get m (keyword #f "tag")))) (if (jolt-truthy? (let* ((and__25__auto t)) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "jolt.host" "record-type?") ctx t) and__25__auto))) (keyword #f "struct") jolt-nil)) jolt-nil)))))))) hint-of) (let* ((_o$8753 (keyword #f "private")) (_o$8754 #t)) (jolt-hash-map _o$8753 _o$8754)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.analyzer" "add-hint" (letrec ((add-hint (lambda (env nm h) (let fnrec8755 ((env env) (nm nm) (h h)) (if (jolt-truthy? h) (jolt-assoc env (keyword #f "hints") (jolt-assoc (jolt-get env (keyword #f "hints")) nm h)) env))))) add-hint) (let* ((_o$8756 (keyword #f "private")) (_o$8757 #t)) (jolt-hash-map _o$8756 _o$8757)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.analyzer" "phint-of" (letrec ((phint-of (lambda (ctx sym) (let fnrec8758 ((ctx ctx) (sym sym)) (let* ((m (jolt-invoke (var-deref "jolt.host" "form-sym-meta") sym))) (if (jolt-truthy? m) (let* ((t (jolt-get m (keyword #f "tag")))) (if (jolt-truthy? t) (jolt-invoke (var-deref "jolt.host" "record-ctor-key") ctx t) jolt-nil)) jolt-nil)))))) phint-of) (let* ((_o$8759 (keyword #f "private")) (_o$8760 #t)) (jolt-hash-map _o$8759 _o$8760)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.analyzer" "tag->nkind" (letrec ((tag->nkind (lambda (t) (let fnrec8761 ((t t)) (let* ((s (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "form-sym?") t)) (jolt-invoke (var-deref "jolt.host" "form-sym-name") t) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "string?") t)) t (if (jolt-truthy? (keyword #f "else")) jolt-nil jolt-nil))))) (if (jolt= s "double") (keyword #f "double") (if (jolt= s "long") (keyword #f "long") (if (jolt-truthy? (keyword #f "else")) jolt-nil jolt-nil)))))))) tag->nkind) (let* ((_o$8762 (keyword #f "private")) (_o$8763 #t)) (jolt-hash-map _o$8762 _o$8763)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.analyzer" "nhint-of" (letrec ((nhint-of (lambda (ctx sym) (let fnrec8764 ((ctx ctx) (sym sym)) (let* ((m (jolt-invoke (var-deref "jolt.host" "form-sym-meta") sym))) (if (jolt-truthy? m) (jolt-invoke (var-deref "jolt.analyzer" "tag->nkind") (jolt-get m (keyword #f "tag"))) jolt-nil)))))) nhint-of) (let* ((_o$8765 (keyword #f "private")) (_o$8766 #t)) (jolt-hash-map _o$8765 _o$8766)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.analyzer" "with-ret-nhint" (letrec ((with-ret-nhint (lambda (node kind) (let fnrec8767 ((node node) (kind kind)) (if (jolt-truthy? (let* ((and__25__auto kind)) (if (jolt-truthy? and__25__auto) (jolt= (keyword #f "fn") (jolt-get node (keyword #f "op"))) and__25__auto))) (jolt-assoc node (keyword #f "arities") (let* ((_a$8769 (var-deref "clojure.core" "mapv")) (_a$8770 (lambda (a) (let fnrec8768 ((a a)) (if (jolt-truthy? (jolt-get a (keyword #f "ret-nhint"))) a (jolt-assoc a (keyword #f "ret-nhint") kind))))) (_a$8771 (jolt-get node (keyword #f "arities")))) (jolt-invoke _a$8769 _a$8770 _a$8771))) node))))) with-ret-nhint) (let* ((_o$8772 (keyword #f "private")) (_o$8773 #t)) (jolt-hash-map _o$8772 _o$8773)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.analyzer" "analyze-seq" (letrec ((analyze-seq (lambda (ctx forms env) (let fnrec8774 ((ctx ctx) (forms forms) (env env)) (let* ((v (jolt-invoke (var-deref "clojure.core" "mapv") (lambda (p__98_) (let fnrec8775 ((p__98_ p__98_)) (jolt-invoke (var-deref "jolt.analyzer" "analyze") ctx p__98_ env))) forms)) (n (jolt-count v))) (if (jolt-zero? n) (jolt-invoke (var-deref "jolt.ir" "const") jolt-nil) (if (jolt= 1 n) (jolt-first v) (if (jolt-truthy? (keyword #f "else")) (let* ((_a$8776 (var-deref "jolt.ir" "do-node")) (_a$8777 (jolt-invoke (var-deref "clojure.core" "subvec") v 0 (jolt-dec n))) (_a$8778 (jolt-peek v))) (jolt-invoke _a$8776 _a$8777 _a$8778)) jolt-nil)))))))) analyze-seq) (let* ((_o$8779 (keyword #f "private")) (_o$8780 #t)) (jolt-hash-map _o$8779 _o$8780)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.analyzer" "analyze-bindings" (letrec ((analyze-bindings (lambda (ctx bvec env) (let fnrec8781 ((ctx ctx) (bvec bvec) (env env)) (let* ((i 0) (env env) (pairs (jolt-vector))) (let loop8782 ((i i) (env env) (pairs pairs)) (if (jolt-n< i (jolt-count bvec)) (let* ((bsym (jolt-nth bvec i))) (begin (if (jolt-not (jolt-invoke (var-deref "jolt.host" "form-sym?") bsym)) (jolt-invoke (var-deref "jolt.analyzer" "uncompilable") "destructuring binding") jolt-nil) (let* ((nm (jolt-invoke (var-deref "jolt.host" "form-sym-name") bsym)) (init (jolt-invoke (var-deref "jolt.analyzer" "analyze") ctx (jolt-nth bvec (jolt-inc i)) env))) (let* ((_a$8789 (jolt-n+ i 2)) (_a$8790 (let* ((_a$8783 (var-deref "jolt.analyzer" "add-hint")) (_a$8784 (jolt-invoke (var-deref "jolt.analyzer" "add-locals") env (jolt-vector nm))) (_a$8785 nm) (_a$8786 (jolt-invoke (var-deref "jolt.analyzer" "hint-of") ctx bsym))) (jolt-invoke _a$8783 _a$8784 _a$8785 _a$8786))) (_a$8791 (jolt-conj pairs (let* ((_o$8787 nm) (_o$8788 init)) (jolt-vector _o$8787 _o$8788))))) (loop8782 _a$8789 _a$8790 _a$8791))))) (let* ((_o$8792 pairs) (_o$8793 env)) (jolt-vector _o$8792 _o$8793))))))))) analyze-bindings) (let* ((_o$8794 (keyword #f "private")) (_o$8795 #t)) (jolt-hash-map _o$8794 _o$8795)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.analyzer" "parse-params" (letrec ((parse-params (lambda (ctx pvec) (let fnrec8796 ((ctx ctx) (pvec pvec)) (let* ((i 0) (fixed (jolt-vector)) (rest-name jolt-nil) (hints (jolt-vector)) (phints (jolt-vector)) (nhints (jolt-vector))) (let loop8797 ((i i) (fixed fixed) (rest-name rest-name) (hints hints) (phints phints) (nhints nhints)) (if (jolt-n< i (jolt-count pvec)) (let* ((p (jolt-nth pvec i))) (begin (if (jolt-not (jolt-invoke (var-deref "jolt.host" "form-sym?") p)) (jolt-invoke (var-deref "jolt.analyzer" "uncompilable") "destructuring fn param") jolt-nil) (if (jolt= "&" (jolt-invoke (var-deref "jolt.host" "form-sym-name") p)) (let* ((r (jolt-nth pvec (jolt-inc i)))) (begin (if (jolt-not (jolt-invoke (var-deref "jolt.host" "form-sym?") r)) (jolt-invoke (var-deref "jolt.analyzer" "uncompilable") "destructuring fn rest") jolt-nil) (let* ((_a$8798 (jolt-n+ i 2)) (_a$8799 fixed) (_a$8800 (jolt-invoke (var-deref "jolt.host" "form-sym-name") r)) (_a$8801 hints) (_a$8802 phints) (_a$8803 nhints)) (loop8797 _a$8798 _a$8799 _a$8800 _a$8801 _a$8802 _a$8803)))) (let* ((nm (jolt-invoke (var-deref "jolt.host" "form-sym-name") p)) (h (jolt-invoke (var-deref "jolt.analyzer" "hint-of") ctx p)) (ph (jolt-invoke (var-deref "jolt.analyzer" "phint-of") ctx p)) (nh (jolt-invoke (var-deref "jolt.analyzer" "nhint-of") ctx p))) (let* ((_a$8810 (jolt-inc i)) (_a$8811 (jolt-conj fixed nm)) (_a$8812 rest-name) (_a$8813 (if (jolt-truthy? h) (jolt-conj hints (let* ((_o$8804 nm) (_o$8805 h)) (jolt-vector _o$8804 _o$8805))) hints)) (_a$8814 (if (jolt-truthy? ph) (jolt-conj phints (let* ((_o$8806 nm) (_o$8807 ph)) (jolt-vector _o$8806 _o$8807))) phints)) (_a$8815 (if (jolt-truthy? nh) (jolt-conj nhints (let* ((_o$8808 nm) (_o$8809 nh)) (jolt-vector _o$8808 _o$8809))) nhints))) (loop8797 _a$8810 _a$8811 _a$8812 _a$8813 _a$8814 _a$8815)))))) (let* ((_o$8816 (keyword #f "fixed")) (_o$8817 fixed) (_o$8818 (keyword #f "rest")) (_o$8819 rest-name) (_o$8820 (keyword #f "hints")) (_o$8821 hints) (_o$8822 (keyword #f "phints")) (_o$8823 phints) (_o$8824 (keyword #f "nhints")) (_o$8825 nhints)) (jolt-hash-map _o$8816 _o$8817 _o$8818 _o$8819 _o$8820 _o$8821 _o$8822 _o$8823 _o$8824 _o$8825))))))))) parse-params) (let* ((_o$8826 (keyword #f "private")) (_o$8827 #t)) (jolt-hash-map _o$8826 _o$8827)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.analyzer" "uniquify-params" (letrec ((uniquify-params (lambda (names) (let fnrec8828 ((names names)) (let* ((n (jolt-count names))) (let* ((i 0) (out (jolt-vector))) (let loop8829 ((i i) (out out)) (if (jolt-n< i n) (let* ((nm (jolt-nth names i)) (dup? (let* ((j (jolt-inc i))) (let loop8830 ((j j)) (if (jolt-n>= j n) #f (if (jolt= nm (jolt-nth names j)) #t (if (jolt-truthy? (keyword #f "else")) (loop8830 (jolt-inc j)) jolt-nil))))))) (let* ((_a$8831 (jolt-inc i)) (_a$8832 (jolt-conj out (if (jolt-truthy? dup?) (jolt-invoke (var-deref "jolt.analyzer" "gen-name") (jolt-invoke (var-deref "clojure.core" "str") nm "_")) nm)))) (loop8829 _a$8831 _a$8832))) out)))))))) uniquify-params) (let* ((_o$8833 (keyword #f "private")) (_o$8834 #t)) (jolt-hash-map _o$8833 _o$8834)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.analyzer" "analyze-arity" (letrec ((analyze-arity (lambda (ctx pvec body env fn-name) (let fnrec8835 ((ctx ctx) (pvec pvec) (body body) (env env) (fn-name fn-name)) (let* ((pp (jolt-invoke (var-deref "jolt.analyzer" "parse-params") ctx (jolt-invoke (var-deref "clojure.core" "vec") (jolt-invoke (var-deref "jolt.host" "form-vec-items") pvec)))) (fixed (jolt-invoke (var-deref "jolt.analyzer" "uniquify-params") (jolt-get pp (keyword #f "fixed")))) (rst (jolt-get pp (keyword #f "rest"))) (rname (jolt-invoke (var-deref "jolt.analyzer" "gen-name") (let* ((_a$8836 (var-deref "clojure.core" "str")) (_a$8837 (jolt-invoke (var-deref "jolt.host" "compile-ns") ctx)) (_a$8838 "/") (_a$8839 (let* ((or__26__auto fn-name)) (if (jolt-truthy? or__26__auto) or__26__auto "fn"))) (_a$8840 "--")) (jolt-invoke _a$8836 _a$8837 _a$8838 _a$8839 _a$8840)))) (names (let* ((G__149 (jolt-invoke (var-deref "clojure.core" "vec") fixed))) (let* ((G__150 (if (jolt-truthy? rst) (jolt-conj G__149 rst) G__149))) (let* ((G__151 (if (jolt-truthy? fn-name) (jolt-conj G__150 fn-name) G__150))) G__151)))) (env0 (jolt-invoke (var-deref "jolt.analyzer" "with-recur") (jolt-invoke (var-deref "jolt.analyzer" "add-locals") env names) rname)) (env* (let* ((_a$8846 (lambda (e pr) (let fnrec8841 ((e e) (pr pr)) (let* ((_a$8842 (var-deref "jolt.analyzer" "add-hint")) (_a$8843 e) (_a$8844 (jolt-nth pr 0)) (_a$8845 (jolt-nth pr 1))) (jolt-invoke _a$8842 _a$8843 _a$8844 _a$8845))))) (_a$8847 env0) (_a$8848 (jolt-get pp (keyword #f "hints")))) (jolt-reduce _a$8846 _a$8847 _a$8848))) (arity (let* ((_o$8849 (keyword #f "params")) (_o$8850 fixed) (_o$8851 (keyword #f "recur-name")) (_o$8852 rname) (_o$8853 (keyword #f "body")) (_o$8854 (jolt-invoke (var-deref "jolt.analyzer" "analyze-seq") ctx body env*))) (jolt-hash-map _o$8849 _o$8850 _o$8851 _o$8852 _o$8853 _o$8854))) (arity (if (jolt-truthy? (jolt-seq (jolt-get pp (keyword #f "phints")))) (jolt-assoc arity (keyword #f "phints") (jolt-get pp (keyword #f "phints"))) arity)) (arity (if (jolt-truthy? (jolt-seq (jolt-get pp (keyword #f "nhints")))) (jolt-assoc arity (keyword #f "nhints") (jolt-get pp (keyword #f "nhints"))) arity))) (if (jolt-truthy? rst) (jolt-assoc arity (keyword #f "rest") rst) arity)))))) analyze-arity) (let* ((_o$8855 (keyword #f "private")) (_o$8856 #t)) (jolt-hash-map _o$8855 _o$8856)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.analyzer" "strip-arglist-meta" (letrec ((strip-arglist-meta (lambda (form) (let fnrec8857 ((form form)) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "form-list?") form)) (let* ((es (jolt-invoke (var-deref "clojure.core" "vec") (jolt-invoke (var-deref "jolt.host" "form-elements") form)))) (if (jolt-truthy? (let* ((and__25__auto (jolt= 3 (jolt-count es)))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt-invoke (var-deref "jolt.host" "form-sym?") (jolt-first es)))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt= "with-meta" (jolt-invoke (var-deref "jolt.host" "form-sym-name") (jolt-first es))))) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "jolt.host" "form-vec?") (jolt-nth es 1)) and__25__auto)) and__25__auto)) and__25__auto))) (jolt-nth es 1) form)) form))))) strip-arglist-meta) (let* ((_o$8858 (keyword #f "private")) (_o$8859 #t)) (jolt-hash-map _o$8858 _o$8859)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.analyzer" "analyze-fn" (letrec ((analyze-fn (lambda (ctx items env) (let fnrec8860 ((ctx ctx) (items items) (env env)) (let* ((named (jolt-invoke (var-deref "jolt.host" "form-sym?") (jolt-nth items 1))) (fn-name (if (jolt-truthy? named) (jolt-invoke (var-deref "jolt.host" "form-sym-name") (jolt-nth items 1)) jolt-nil)) (rest-items (if (jolt-truthy? named) (jolt-drop 2 items) (jolt-drop 1 items))) (first* (jolt-invoke (var-deref "jolt.analyzer" "strip-arglist-meta") (jolt-first rest-items)))) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "form-vec?") first*)) (jolt-invoke (var-deref "jolt.ir" "fn-node") fn-name (jolt-vector (jolt-invoke (var-deref "jolt.analyzer" "analyze-arity") ctx first* (jolt-rest rest-items) env fn-name))) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "form-list?") first*)) (jolt-invoke (var-deref "jolt.ir" "fn-node") fn-name (jolt-invoke (var-deref "clojure.core" "mapv") (lambda (clause) (let fnrec8861 ((clause clause)) (let* ((cl (jolt-invoke (var-deref "clojure.core" "vec") (jolt-invoke (var-deref "jolt.host" "form-elements") clause)))) (let* ((_a$8862 (var-deref "jolt.analyzer" "analyze-arity")) (_a$8863 ctx) (_a$8864 (jolt-invoke (var-deref "jolt.analyzer" "strip-arglist-meta") (jolt-first cl))) (_a$8865 (jolt-rest cl)) (_a$8866 env) (_a$8867 fn-name)) (jolt-invoke _a$8862 _a$8863 _a$8864 _a$8865 _a$8866 _a$8867))))) rest-items)) (if (jolt-truthy? (keyword #f "else")) (jolt-invoke (var-deref "jolt.analyzer" "uncompilable") "fn: bad params") jolt-nil)))))))) analyze-fn) (let* ((_o$8868 (keyword #f "private")) (_o$8869 #t)) (jolt-hash-map _o$8868 _o$8869)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.analyzer" "catch-all-names" (let* ((_o$8870 "Throwable") (_o$8871 "java.lang.Throwable") (_o$8872 "Object") (_o$8873 "java.lang.Object")) (jolt-hash-set _o$8870 _o$8871 _o$8872 _o$8873)) (let* ((_o$8874 (keyword #f "private")) (_o$8875 #t)) (jolt-hash-map _o$8874 _o$8875)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.analyzer" "analyze-try" (letrec ((analyze-try (lambda (ctx items env) (let fnrec8876 ((ctx ctx) (items items) (env env)) (let* ((clauses (jolt-rest items)) (body (jolt-invoke (var-deref "clojure.core" "atom") (jolt-vector))) (catches (jolt-invoke (var-deref "clojure.core" "atom") (jolt-vector))) (finally-body (jolt-invoke (var-deref "clojure.core" "atom") jolt-nil))) (begin (begin (jolt-count (jolt-map (lambda (c) (let fnrec8877 ((c c)) (begin (let* ((head (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "form-list?") c)) (jolt-first (jolt-invoke (var-deref "clojure.core" "vec") (jolt-invoke (var-deref "jolt.host" "form-elements") c))) jolt-nil)) (hname (if (jolt-truthy? (let* ((and__25__auto head)) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "jolt.host" "form-sym?") head) and__25__auto))) (jolt-invoke (var-deref "jolt.host" "form-sym-name") head) jolt-nil))) (if (jolt= hname "catch") (let* ((cl (jolt-invoke (var-deref "clojure.core" "vec") (jolt-invoke (var-deref "jolt.host" "form-elements") c)))) (begin (if (let* ((or__26__auto (jolt-n< (jolt-count cl) 3))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-not (jolt-invoke (var-deref "jolt.host" "form-sym?") (jolt-nth cl 2))))) (jolt-throw "Unable to parse catch clause; expected (catch class binding body*)") jolt-nil) (jolt-invoke (var-deref "clojure.core" "swap!") catches jolt-conj cl))) (if (jolt= hname "finally") (jolt-invoke (var-deref "clojure.core" "reset!") finally-body (jolt-rest (jolt-invoke (var-deref "clojure.core" "vec") (jolt-invoke (var-deref "jolt.host" "form-elements") c)))) (if (jolt-truthy? (keyword #f "else")) (jolt-invoke (var-deref "clojure.core" "swap!") body jolt-conj c) jolt-nil)))) jolt-nil))) clauses)) jolt-nil) (let* ((n (let* ((_o$8878 (keyword #f "op")) (_o$8879 (keyword #f "try")) (_o$8880 (keyword #f "body")) (_o$8881 (jolt-invoke (var-deref "jolt.analyzer" "analyze-seq") ctx (jolt-invoke (var-deref "clojure.core" "deref") body) env))) (jolt-hash-map _o$8878 _o$8879 _o$8880 _o$8881))) (n (if (jolt-truthy? (jolt-seq (jolt-invoke (var-deref "clojure.core" "deref") catches))) (let* ((evar-name (jolt-invoke (var-deref "jolt.analyzer" "gen-name") "catch")) (raw-name (jolt-invoke (var-deref "jolt.analyzer" "gen-name") "catch-raw")) (evar (jolt-invoke (var-deref "clojure.core" "symbol") evar-name)) (dispatch (let* ((_a$8886 (lambda (_else cl) (let fnrec8882 ((_else _else) (cl cl)) (let* ((cform (jolt-nth cl 1)) (bindsym (jolt-nth cl 2)) (bodyf (jolt-drop 3 cl)) (letform (jolt-cons (jolt-symbol #f "let") (jolt-cons (jolt-vector bindsym evar) bodyf))) (fullname (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "form-sym?") cform)) (jolt-invoke (var-deref "jolt.host" "form-sym-name") cform) jolt-nil)) (catch-all? (let* ((or__26__auto (jolt-not (jolt-invoke (var-deref "jolt.host" "form-sym?") cform)))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-contains? (var-deref "jolt.analyzer" "catch-all-names") fullname))))) (if (jolt-truthy? catch-all?) letform (jolt-list (jolt-symbol #f "if") (let* ((_a$8883 (jolt-symbol #f "or")) (_a$8884 (jolt-list (jolt-symbol #f "instance?") cform evar)) (_a$8885 (jolt-list (jolt-symbol #f "__catch-broad?") fullname evar))) (jolt-list _a$8883 _a$8884 _a$8885)) letform _else)))))) (_a$8887 (jolt-list (jolt-symbol #f "throw") evar)) (_a$8888 (jolt-reverse (jolt-invoke (var-deref "clojure.core" "deref") catches)))) (jolt-reduce _a$8886 _a$8887 _a$8888)))) (jolt-assoc n (keyword #f "catch-sym") evar-name (keyword #f "catch-raw-sym") raw-name (keyword #f "catch-body") (let* ((_a$8889 (var-deref "jolt.analyzer" "analyze-seq")) (_a$8890 ctx) (_a$8891 (jolt-list dispatch)) (_a$8892 (jolt-invoke (var-deref "jolt.analyzer" "add-locals") env (jolt-vector evar-name)))) (jolt-invoke _a$8889 _a$8890 _a$8891 _a$8892)))) n)) (n (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "deref") finally-body)) (jolt-assoc n (keyword #f "finally") (jolt-invoke (var-deref "jolt.analyzer" "analyze-seq") ctx (jolt-invoke (var-deref "clojure.core" "deref") finally-body) env)) n))) n))))))) analyze-try) (let* ((_o$8893 (keyword #f "private")) (_o$8894 #t)) (jolt-hash-map _o$8893 _o$8894)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.analyzer" "analyze-letfn*" (letrec ((analyze-letfn* (lambda (ctx items env) (let fnrec8895 ((ctx ctx) (items items) (env env)) (let* ((bvec (jolt-invoke (var-deref "clojure.core" "vec") (jolt-invoke (var-deref "jolt.host" "form-vec-items") (jolt-nth items 1)))) (n (jolt-quot (jolt-count bvec) 2)) (names (let* ((_a$8897 (var-deref "clojure.core" "mapv")) (_a$8898 (lambda (i) (let fnrec8896 ((i i)) (jolt-invoke (var-deref "jolt.host" "form-sym-name") (jolt-nth bvec (jolt-n* 2 i)))))) (_a$8899 (jolt-range n))) (jolt-invoke _a$8897 _a$8898 _a$8899))) (env* (jolt-invoke (var-deref "jolt.analyzer" "add-locals") env names)) (binds (let* ((_a$8903 (var-deref "clojure.core" "mapv")) (_a$8904 (lambda (i) (let fnrec8900 ((i i)) (let* ((_o$8901 (jolt-nth names i)) (_o$8902 (jolt-invoke (var-deref "jolt.analyzer" "analyze") ctx (jolt-nth bvec (jolt-inc (jolt-n* 2 i))) env*))) (jolt-vector _o$8901 _o$8902))))) (_a$8905 (jolt-range n))) (jolt-invoke _a$8903 _a$8904 _a$8905)))) (let* ((_o$8906 (keyword #f "op")) (_o$8907 (keyword #f "let")) (_o$8908 (keyword #f "letrec")) (_o$8909 #t) (_o$8910 (keyword #f "bindings")) (_o$8911 binds) (_o$8912 (keyword #f "body")) (_o$8913 (jolt-invoke (var-deref "jolt.analyzer" "analyze-seq") ctx (jolt-drop 2 items) env*))) (jolt-hash-map _o$8906 _o$8907 _o$8908 _o$8909 _o$8910 _o$8911 _o$8912 _o$8913))))))) analyze-letfn*) (let* ((_o$8914 (keyword #f "private")) (_o$8915 #t)) (jolt-hash-map _o$8914 _o$8915)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.analyzer" "field-head?" (letrec ((field-head? (lambda (nm) (let fnrec8916 ((nm nm)) (let* ((and__25__auto (jolt-n> (jolt-count nm) 2))) (if (jolt-truthy? and__25__auto) (jolt= ".-" (jolt-invoke (var-deref "clojure.core" "subs") nm 0 2)) and__25__auto)))))) field-head?) (let* ((_o$8917 (keyword #f "private")) (_o$8918 #t)) (jolt-hash-map _o$8917 _o$8918)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.analyzer" "def-meta-expr" (letrec ((def-meta-expr (lambda (ctx base env) (let fnrec8919 ((ctx ctx) (base base) (env env)) (if (jolt-pos? (jolt-count base)) (jolt-invoke (var-deref "jolt.ir" "map-node") (let* ((_a$8923 (var-deref "clojure.core" "mapv")) (_a$8924 (lambda (p) (let fnrec8920 ((p p)) (let* ((k (jolt-first p)) (v (jolt-invoke (var-deref "clojure.core" "second") p))) (let* ((_o$8921 (jolt-invoke (var-deref "jolt.ir" "const") k)) (_o$8922 (if (jolt= k (keyword #f "tag")) (jolt-invoke (var-deref "jolt.ir" "quote-node") v) (jolt-invoke (var-deref "jolt.analyzer" "analyze") ctx v env)))) (jolt-vector _o$8921 _o$8922)))))) (_a$8925 (jolt-seq base))) (jolt-invoke _a$8923 _a$8924 _a$8925))) jolt-nil))))) def-meta-expr) (let* ((_o$8926 (keyword #f "private")) (_o$8927 #t)) (jolt-hash-map _o$8926 _o$8927)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.analyzer" "analyze-def" (letrec ((analyze-def (lambda (ctx items env) (let fnrec8928 ((ctx ctx) (items items) (env env)) (let* ((name-sym (jolt-nth items 1))) (begin (if (jolt-not (jolt-invoke (var-deref "jolt.host" "form-sym?") name-sym)) (jolt-invoke (var-deref "jolt.analyzer" "uncompilable") "def name with map metadata") jolt-nil) (if (jolt-n< (jolt-count items) 3) (let* ((nm (jolt-invoke (var-deref "jolt.host" "form-sym-name") name-sym)) (cur (jolt-invoke (var-deref "jolt.host" "compile-ns") ctx))) (begin (jolt-invoke (var-deref "jolt.host" "host-intern!") ctx cur nm) (let* ((_o$8929 (keyword #f "op")) (_o$8930 (keyword #f "def")) (_o$8931 (keyword #f "ns")) (_o$8932 cur) (_o$8933 (keyword #f "name")) (_o$8934 nm) (_o$8935 (keyword #f "no-init")) (_o$8936 #t)) (jolt-hash-map _o$8929 _o$8930 _o$8931 _o$8932 _o$8933 _o$8934 _o$8935 _o$8936)))) (let* ((nm (jolt-invoke (var-deref "jolt.host" "form-sym-name") name-sym)) (cur (jolt-invoke (var-deref "jolt.host" "compile-ns") ctx)) (has-doc (let* ((and__25__auto (jolt-n> (jolt-count items) 3))) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "clojure.core" "string?") (jolt-nth items 2)) and__25__auto))) (val-form (jolt-nth items (if (jolt-truthy? has-doc) 3 2))) (base0 (let* ((or__26__auto (jolt-invoke (var-deref "jolt.host" "form-sym-meta") name-sym))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-hash-map)))) (tag (jolt-get base0 (keyword #f "tag"))) (tag-name (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "form-sym?") tag)) (jolt-invoke (var-deref "jolt.host" "form-sym-name") tag) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "string?") tag)) tag (if (jolt-truthy? (keyword #f "else")) jolt-nil jolt-nil)))) (base-meta (if (jolt-truthy? tag-name) (let* ((c (jolt-invoke (var-deref "jolt.host" "resolve-class-hint") tag-name))) (if (jolt-truthy? c) (jolt-assoc base0 (keyword #f "tag") c) base0)) base0)) (node-meta (if (jolt-truthy? has-doc) (jolt-assoc base-meta (keyword #f "doc") (jolt-nth items 2)) base-meta))) (begin (jolt-invoke (var-deref "jolt.host" "host-intern!") ctx cur nm) (let* ((node (jolt-invoke (var-deref "jolt.ir" "def-node") cur nm (let* ((_a$8937 (var-deref "jolt.analyzer" "with-ret-nhint")) (_a$8938 (jolt-invoke (var-deref "jolt.analyzer" "analyze") ctx val-form env)) (_a$8939 (jolt-invoke (var-deref "jolt.analyzer" "tag->nkind") tag))) (jolt-invoke _a$8937 _a$8938 _a$8939)) node-meta)) (me (jolt-invoke (var-deref "jolt.analyzer" "def-meta-expr") ctx node-meta env))) (if (jolt-truthy? me) (jolt-assoc node (keyword #f "meta-expr") me) node))))))))))) analyze-def) (let* ((_o$8940 (keyword #f "private")) (_o$8941 #t)) (jolt-hash-map _o$8940 _o$8941)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.analyzer" "analyze-set!" (letrec ((analyze-set! (lambda (ctx items env) (let fnrec8942 ((ctx ctx) (items items) (env env)) (let* ((target (jolt-nth items 1)) (val-node (jolt-invoke (var-deref "jolt.analyzer" "analyze") ctx (jolt-nth items 2) env)) (ti (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "form-list?") target)) (jolt-invoke (var-deref "clojure.core" "vec") (jolt-invoke (var-deref "jolt.host" "form-elements") target)) jolt-nil)) (thead (if (jolt-truthy? (let* ((and__25__auto ti)) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt-pos? (jolt-count ti)))) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "jolt.host" "form-sym?") (jolt-first ti)) and__25__auto)) and__25__auto))) (jolt-invoke (var-deref "jolt.host" "form-sym-name") (jolt-first ti)) jolt-nil))) (if (jolt-truthy? (let* ((and__25__auto thead)) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "jolt.analyzer" "field-head?") thead) and__25__auto))) (let* ((_o$8943 (keyword #f "op")) (_o$8944 (keyword #f "set-field")) (_o$8945 (keyword #f "obj")) (_o$8946 (jolt-invoke (var-deref "jolt.analyzer" "analyze") ctx (jolt-nth ti 1) env)) (_o$8947 (keyword #f "field")) (_o$8948 (jolt-invoke (var-deref "clojure.core" "subs") thead 2)) (_o$8949 (keyword #f "val")) (_o$8950 val-node)) (jolt-hash-map _o$8943 _o$8944 _o$8945 _o$8946 _o$8947 _o$8948 _o$8949 _o$8950)) (if (jolt-truthy? (let* ((and__25__auto (jolt= thead "."))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt-n>= (jolt-count ti) 3))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt-invoke (var-deref "jolt.host" "form-sym?") (jolt-nth ti 1)))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt-invoke (var-deref "jolt.host" "form-sym?") (jolt-nth ti 2)))) (if (jolt-truthy? and__25__auto) (jolt= (keyword #f "class") (jolt-get (jolt-invoke (var-deref "jolt.host" "resolve-global") ctx (jolt-nth ti 1)) (keyword #f "kind"))) and__25__auto)) and__25__auto)) and__25__auto)) and__25__auto))) (let* ((_a$8954 (var-deref "jolt.ir" "invoke")) (_a$8955 (jolt-invoke (var-deref "jolt.ir" "var-ref") "jolt.host" "set-static-field!")) (_a$8956 (let* ((_o$8951 (jolt-invoke (var-deref "jolt.ir" "const") (jolt-get (jolt-invoke (var-deref "jolt.host" "resolve-global") ctx (jolt-nth ti 1)) (keyword #f "name")))) (_o$8952 (jolt-invoke (var-deref "jolt.ir" "const") (jolt-invoke (var-deref "jolt.host" "form-sym-name") (jolt-nth ti 2)))) (_o$8953 val-node)) (jolt-vector _o$8951 _o$8952 _o$8953)))) (jolt-invoke _a$8954 _a$8955 _a$8956)) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "form-sym?") target)) (begin (if (jolt-truthy? (jolt-invoke (var-deref "jolt.analyzer" "local?") env (jolt-invoke (var-deref "jolt.host" "form-sym-name") target))) (jolt-invoke (var-deref "jolt.analyzer" "uncompilable") "set! of a local") jolt-nil) (let* ((r (jolt-invoke (var-deref "jolt.host" "resolve-global") ctx target))) (begin (if (jolt-not (jolt= (keyword #f "var") (jolt-get r (keyword #f "kind")))) (jolt-invoke (var-deref "jolt.analyzer" "uncompilable") "set! of a non-var") jolt-nil) (let* ((_o$8960 (keyword #f "op")) (_o$8961 (keyword #f "set-var")) (_o$8962 (keyword #f "the-var")) (_o$8963 (let* ((_a$8957 (var-deref "jolt.ir" "the-var")) (_a$8958 (jolt-get r (keyword #f "ns"))) (_a$8959 (jolt-get r (keyword #f "name")))) (jolt-invoke _a$8957 _a$8958 _a$8959))) (_o$8964 (keyword #f "val")) (_o$8965 val-node)) (jolt-hash-map _o$8960 _o$8961 _o$8962 _o$8963 _o$8964 _o$8965))))) (if (jolt-truthy? (keyword #f "else")) (jolt-invoke (var-deref "jolt.analyzer" "uncompilable") "set! of an unsupported target") jolt-nil))))))))) analyze-set!) (let* ((_o$8966 (keyword #f "private")) (_o$8967 #t)) (jolt-hash-map _o$8966 _o$8967)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.analyzer" "analyze-special" (letrec ((analyze-special (lambda (ctx op items env) (let fnrec8968 ((ctx ctx) (op op) (items items) (env env)) (let* ((G__152 op)) (if (jolt= G__152 "quote") (let* ((qf (jolt-invoke (var-deref "clojure.core" "second") items)) (m (jolt-invoke (var-deref "jolt.host" "form-coll-meta") qf)) (m (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "map?") m)) (let* ((u (jolt-dissoc m (keyword #f "line") (keyword #f "column") (keyword #f "end-line") (keyword #f "end-column") (keyword #f "file")))) (if (jolt-truthy? (jolt-seq u)) u jolt-nil)) jolt-nil))) (if (jolt-nil? m) (jolt-invoke (var-deref "jolt.ir" "quote-node") qf) (let* ((_a$8971 (var-deref "jolt.ir" "invoke")) (_a$8972 (jolt-invoke (var-deref "jolt.ir" "var-ref") "clojure.core" "with-meta")) (_a$8973 (let* ((_o$8969 (jolt-invoke (var-deref "jolt.ir" "quote-node") qf)) (_o$8970 (jolt-invoke (var-deref "jolt.ir" "quote-node") m))) (jolt-vector _o$8969 _o$8970)))) (jolt-invoke _a$8971 _a$8972 _a$8973)))) (if (jolt= G__152 "if") (begin (if (let* ((or__26__auto (jolt-n< (jolt-count items) 3))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-n> (jolt-count items) 4))) (jolt-throw (jolt-invoke (var-deref "clojure.core" "str") "Wrong number of args (" (jolt-dec (jolt-count items)) ") passed to: if")) jolt-nil) (let* ((_a$8974 (var-deref "jolt.ir" "if-node")) (_a$8975 (jolt-invoke (var-deref "jolt.analyzer" "analyze") ctx (jolt-nth items 1) env)) (_a$8976 (jolt-invoke (var-deref "jolt.analyzer" "analyze") ctx (jolt-nth items 2) env)) (_a$8977 (if (jolt-n> (jolt-count items) 3) (jolt-invoke (var-deref "jolt.analyzer" "analyze") ctx (jolt-nth items 3) env) (jolt-invoke (var-deref "jolt.ir" "const") jolt-nil)))) (jolt-invoke _a$8974 _a$8975 _a$8976 _a$8977))) (if (jolt= G__152 "do") (jolt-invoke (var-deref "jolt.analyzer" "analyze-seq") ctx (jolt-rest items) env) (if (jolt= G__152 "throw") (jolt-invoke (var-deref "jolt.ir" "throw-node") (jolt-invoke (var-deref "jolt.analyzer" "analyze") ctx (jolt-nth items 1) env)) (if (jolt= G__152 "def") (jolt-invoke (var-deref "jolt.analyzer" "analyze-def") ctx items env) (if (jolt= G__152 "let*") (let* ((bvec (jolt-invoke (var-deref "clojure.core" "vec") (jolt-invoke (var-deref "jolt.host" "form-vec-items") (jolt-nth items 1)))) (r (jolt-invoke (var-deref "jolt.analyzer" "analyze-bindings") ctx bvec env))) (let* ((_a$8982 (var-deref "jolt.ir" "let-node")) (_a$8983 (jolt-first r)) (_a$8984 (let* ((_a$8978 (var-deref "jolt.analyzer" "analyze-seq")) (_a$8979 ctx) (_a$8980 (jolt-drop 2 items)) (_a$8981 (jolt-invoke (var-deref "clojure.core" "second") r))) (jolt-invoke _a$8978 _a$8979 _a$8980 _a$8981)))) (jolt-invoke _a$8982 _a$8983 _a$8984))) (if (jolt= G__152 "loop*") (let* ((bvec (jolt-invoke (var-deref "clojure.core" "vec") (jolt-invoke (var-deref "jolt.host" "form-vec-items") (jolt-nth items 1)))) (rname (jolt-invoke (var-deref "jolt.analyzer" "gen-name") "loop")) (r (jolt-invoke (var-deref "jolt.analyzer" "analyze-bindings") ctx bvec env)) (env** (jolt-invoke (var-deref "jolt.analyzer" "with-recur") (jolt-invoke (var-deref "clojure.core" "second") r) rname))) (let* ((_o$8985 (keyword #f "op")) (_o$8986 (keyword #f "loop")) (_o$8987 (keyword #f "recur-name")) (_o$8988 rname) (_o$8989 (keyword #f "bindings")) (_o$8990 (jolt-first r)) (_o$8991 (keyword #f "body")) (_o$8992 (jolt-invoke (var-deref "jolt.analyzer" "analyze-seq") ctx (jolt-drop 2 items) env**))) (jolt-hash-map _o$8985 _o$8986 _o$8987 _o$8988 _o$8989 _o$8990 _o$8991 _o$8992))) (if (jolt= G__152 "recur") (let* ((rt (jolt-get env (keyword #f "recur")))) (begin (if (jolt-not rt) (jolt-invoke (var-deref "jolt.analyzer" "uncompilable") "recur outside loop/fn") jolt-nil) (let* ((_o$8997 (keyword #f "op")) (_o$8998 (keyword #f "recur")) (_o$8999 (keyword #f "recur-name")) (_o$9000 rt) (_o$9001 (keyword #f "args")) (_o$9002 (let* ((_a$8994 (var-deref "clojure.core" "mapv")) (_a$8995 (lambda (p__99_) (let fnrec8993 ((p__99_ p__99_)) (jolt-invoke (var-deref "jolt.analyzer" "analyze") ctx p__99_ env)))) (_a$8996 (jolt-rest items))) (jolt-invoke _a$8994 _a$8995 _a$8996)))) (jolt-hash-map _o$8997 _o$8998 _o$8999 _o$9000 _o$9001 _o$9002)))) (if (jolt= G__152 "try") (jolt-invoke (var-deref "jolt.analyzer" "analyze-try") ctx items env) (if (jolt= G__152 "letfn*") (jolt-invoke (var-deref "jolt.analyzer" "analyze-letfn*") ctx items env) (if (jolt= G__152 "fn*") (jolt-invoke (var-deref "jolt.analyzer" "analyze-fn") ctx items env) (if (jolt= G__152 "syntax-quote") (jolt-invoke (var-deref "jolt.analyzer" "analyze") ctx (jolt-invoke (var-deref "jolt.host" "form-syntax-quote-lower") ctx (jolt-invoke (var-deref "clojure.core" "second") items)) env) (if (jolt= G__152 "var") (let* ((sym (jolt-invoke (var-deref "clojure.core" "second") items)) (r (jolt-invoke (var-deref "jolt.host" "resolve-global") ctx sym))) (if (jolt= (keyword #f "var") (jolt-get r (keyword #f "kind"))) (let* ((_a$9003 (var-deref "jolt.ir" "the-var")) (_a$9004 (jolt-get r (keyword #f "ns"))) (_a$9005 (jolt-get r (keyword #f "name")))) (jolt-invoke _a$9003 _a$9004 _a$9005)) (jolt-invoke (var-deref "jolt.analyzer" "uncompilable") (jolt-invoke (var-deref "clojure.core" "str") "var of non-var " (jolt-invoke (var-deref "jolt.host" "form-sym-name") sym))))) (if (jolt= G__152 "defmacro") (let* ((name-sym (jolt-nth items 1)) (nm (jolt-invoke (var-deref "jolt.host" "form-sym-name") name-sym)) (cur (jolt-invoke (var-deref "jolt.host" "compile-ns") ctx)) (after (jolt-drop 2 items)) (after (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "string?") (jolt-first after))) (jolt-rest after) after)) (after (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "form-map?") (jolt-first after))) (jolt-rest after) after)) (fn-form (jolt-cons (jolt-invoke (var-deref "clojure.core" "symbol") "fn") after))) (begin (jolt-invoke (var-deref "jolt.host" "host-intern!") ctx cur nm) (let* ((_o$9006 (keyword #f "op")) (_o$9007 (keyword #f "defmacro")) (_o$9008 (keyword #f "ns")) (_o$9009 cur) (_o$9010 (keyword #f "name")) (_o$9011 nm) (_o$9012 (keyword #f "fn")) (_o$9013 (jolt-invoke (var-deref "jolt.analyzer" "analyze") ctx fn-form env))) (jolt-hash-map _o$9006 _o$9007 _o$9008 _o$9009 _o$9010 _o$9011 _o$9012 _o$9013)))) (if (jolt= G__152 "set!") (jolt-invoke (var-deref "jolt.analyzer" "analyze-set!") ctx items env) (jolt-invoke (var-deref "jolt.analyzer" "uncompilable") (jolt-invoke (var-deref "clojure.core" "str") "special form " op)))))))))))))))))))))) analyze-special) (let* ((_o$9014 (keyword #f "private")) (_o$9015 #t)) (jolt-hash-map _o$9014 _o$9015)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.analyzer" "method-head?" (letrec ((method-head? (lambda (nm) (let fnrec9016 ((nm nm)) (let* ((and__25__auto (jolt-n> (jolt-count nm) 1))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt= "." (jolt-invoke (var-deref "clojure.core" "subs") nm 0 1)))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt-not (jolt= "-" (jolt-invoke (var-deref "clojure.core" "subs") nm 1 2))))) (if (jolt-truthy? and__25__auto) (jolt-not (jolt= "." (jolt-invoke (var-deref "clojure.core" "subs") nm 1 2))) and__25__auto)) and__25__auto)) and__25__auto)))))) method-head?) (let* ((_o$9017 (keyword #f "private")) (_o$9018 #t)) (jolt-hash-map _o$9017 _o$9018)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.analyzer" "analyze-host-call" (letrec ((analyze-host-call (lambda (ctx hname items env) (let fnrec9019 ((ctx ctx) (hname hname) (items items) (env env)) (begin (if (jolt-n< (jolt-count items) 2) (jolt-throw (jolt-invoke (var-deref "clojure.core" "str") "Malformed member expression, expecting (.method target ...): " hname)) jolt-nil) (let* ((_o$9024 (keyword #f "op")) (_o$9025 (keyword #f "host-call")) (_o$9026 (keyword #f "method")) (_o$9027 (jolt-invoke (var-deref "clojure.core" "subs") hname 1)) (_o$9028 (keyword #f "target")) (_o$9029 (jolt-invoke (var-deref "jolt.analyzer" "analyze") ctx (jolt-nth items 1) env)) (_o$9030 (keyword #f "args")) (_o$9031 (let* ((_a$9021 (var-deref "clojure.core" "mapv")) (_a$9022 (lambda (p__100_) (let fnrec9020 ((p__100_ p__100_)) (jolt-invoke (var-deref "jolt.analyzer" "analyze") ctx p__100_ env)))) (_a$9023 (jolt-drop 2 items))) (jolt-invoke _a$9021 _a$9022 _a$9023)))) (jolt-hash-map _o$9024 _o$9025 _o$9026 _o$9027 _o$9028 _o$9029 _o$9030 _o$9031))))))) analyze-host-call) (let* ((_o$9032 (keyword #f "private")) (_o$9033 #t)) (jolt-hash-map _o$9032 _o$9033)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.analyzer" "ctor-head?" (letrec ((ctor-head? (lambda (nm) (let fnrec9034 ((nm nm)) (let* ((and__25__auto (jolt-n> (jolt-count nm) 1))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt= "." (let* ((_a$9035 (var-deref "clojure.core" "subs")) (_a$9036 nm) (_a$9037 (jolt-dec (jolt-count nm))) (_a$9038 (jolt-count nm))) (jolt-invoke _a$9035 _a$9036 _a$9037 _a$9038))))) (if (jolt-truthy? and__25__auto) (jolt-not (jolt= "." (jolt-invoke (var-deref "clojure.core" "subs") nm 0 1))) and__25__auto)) and__25__auto)))))) ctor-head?) (let* ((_o$9039 (keyword #f "private")) (_o$9040 #t)) (jolt-hash-map _o$9039 _o$9040)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.analyzer" "analyze-ctor" (letrec ((analyze-ctor (lambda (ctx class args env) (let fnrec9041 ((ctx ctx) (class class) (args args) (env env)) (let* ((_a$9043 (var-deref "jolt.ir" "host-new")) (_a$9044 (let* ((or__26__auto (jolt-invoke (var-deref "jolt.host" "deftype-ctor-class") ctx class))) (if (jolt-truthy? or__26__auto) or__26__auto class))) (_a$9045 (jolt-invoke (var-deref "clojure.core" "mapv") (lambda (p__101_) (let fnrec9042 ((p__101_ p__101_)) (jolt-invoke (var-deref "jolt.analyzer" "analyze") ctx p__101_ env))) args))) (jolt-invoke _a$9043 _a$9044 _a$9045)))))) analyze-ctor) (let* ((_o$9046 (keyword #f "private")) (_o$9047 #t)) (jolt-hash-map _o$9046 _o$9047)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.analyzer" "analyze-ffi-fn" (letrec ((analyze-ffi-fn (lambda (ctx items env) (let fnrec9048 ((ctx ctx) (items items) (env env)) (begin (if (jolt-not (jolt-n<= 4 (jolt-count items) 5)) (jolt-throw (jolt-invoke (var-deref "clojure.core" "str") "jolt.ffi/foreign-fn expects (foreign-fn \"sym\" [argtypes] rettype [:blocking])")) jolt-nil) (let* ((_o$9049 (keyword #f "op")) (_o$9050 (keyword #f "ffi-fn")) (_o$9051 (keyword #f "csym")) (_o$9052 (jolt-nth items 1)) (_o$9053 (keyword #f "argtypes")) (_o$9054 (jolt-invoke (var-deref "clojure.core" "mapv") (var-deref "clojure.core" "name") (jolt-invoke (var-deref "jolt.host" "form-vec-items") (jolt-nth items 2)))) (_o$9055 (keyword #f "rettype")) (_o$9056 (jolt-invoke (var-deref "clojure.core" "name") (jolt-nth items 3))) (_o$9057 (keyword #f "blocking")) (_o$9058 (let* ((and__25__auto (jolt= 5 (jolt-count items)))) (if (jolt-truthy? and__25__auto) (jolt= "blocking" (jolt-invoke (var-deref "clojure.core" "name") (jolt-nth items 4))) and__25__auto)))) (jolt-hash-map _o$9049 _o$9050 _o$9051 _o$9052 _o$9053 _o$9054 _o$9055 _o$9056 _o$9057 _o$9058))))))) analyze-ffi-fn) (let* ((_o$9059 (keyword #f "private")) (_o$9060 #t)) (jolt-hash-map _o$9059 _o$9060)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.analyzer" "analyze-ffi-callable" (letrec ((analyze-ffi-callable (lambda (ctx items env) (let fnrec9061 ((ctx ctx) (items items) (env env)) (begin (if (jolt-not (jolt-n<= 4 (jolt-count items) 5)) (jolt-throw (jolt-invoke (var-deref "clojure.core" "str") "jolt.ffi/foreign-callable expects (foreign-callable f [argtypes] rettype [:collect-safe])")) jolt-nil) (let* ((_o$9062 (keyword #f "op")) (_o$9063 (keyword #f "ffi-callable")) (_o$9064 (keyword #f "fn")) (_o$9065 (jolt-invoke (var-deref "jolt.analyzer" "analyze") ctx (jolt-nth items 1) env)) (_o$9066 (keyword #f "argtypes")) (_o$9067 (jolt-invoke (var-deref "clojure.core" "mapv") (var-deref "clojure.core" "name") (jolt-invoke (var-deref "jolt.host" "form-vec-items") (jolt-nth items 2)))) (_o$9068 (keyword #f "rettype")) (_o$9069 (jolt-invoke (var-deref "clojure.core" "name") (jolt-nth items 3))) (_o$9070 (keyword #f "collect-safe")) (_o$9071 (let* ((and__25__auto (jolt= 5 (jolt-count items)))) (if (jolt-truthy? and__25__auto) (jolt= "collect-safe" (jolt-invoke (var-deref "clojure.core" "name") (jolt-nth items 4))) and__25__auto)))) (jolt-hash-map _o$9062 _o$9063 _o$9064 _o$9065 _o$9066 _o$9067 _o$9068 _o$9069 _o$9070 _o$9071))))))) analyze-ffi-callable) (let* ((_o$9072 (keyword #f "private")) (_o$9073 #t)) (jolt-hash-map _o$9072 _o$9073)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.analyzer" "analyze-dot" (letrec ((analyze-dot (lambda (ctx items env) (let fnrec9074 ((ctx ctx) (items items) (env env)) (begin (if (jolt-n< (jolt-count items) 3) (jolt-throw (jolt-invoke (var-deref "clojure.core" "str") "Malformed (. target member ...) form")) jolt-nil) (let* ((member0 (jolt-nth items 2)) (items (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "form-list?") member0)) (let* ((ml (jolt-invoke (var-deref "clojure.core" "vec") (jolt-invoke (var-deref "jolt.host" "form-elements") member0)))) (let* ((_a$9078 (let* ((_o$9075 (jolt-nth items 0)) (_o$9076 (jolt-nth items 1)) (_o$9077 (jolt-first ml))) (jolt-vector _o$9075 _o$9076 _o$9077))) (_a$9079 (jolt-rest ml))) (jolt-into _a$9078 _a$9079))) items)) (target (jolt-nth items 1)) (member (jolt-nth items 2)) (class-target (if (jolt-truthy? (let* ((and__25__auto (jolt-invoke (var-deref "jolt.host" "form-sym?") target))) (if (jolt-truthy? and__25__auto) (jolt-not (jolt-invoke (var-deref "jolt.analyzer" "local?") env (jolt-invoke (var-deref "jolt.host" "form-sym-name") target))) and__25__auto))) (let* ((r (jolt-invoke (var-deref "jolt.host" "resolve-global") ctx target))) (if (jolt= (keyword #f "class") (jolt-get r (keyword #f "kind"))) (jolt-get r (keyword #f "name")) jolt-nil)) jolt-nil))) (if (jolt-truthy? (let* ((and__25__auto class-target)) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "jolt.host" "form-sym?") member) and__25__auto))) (let* ((_a$9084 (var-deref "jolt.ir" "invoke")) (_a$9085 (jolt-invoke (var-deref "jolt.ir" "host-static") class-target (jolt-invoke (var-deref "jolt.host" "form-sym-name") member))) (_a$9086 (let* ((_a$9081 (var-deref "clojure.core" "mapv")) (_a$9082 (lambda (p__102_) (let fnrec9080 ((p__102_ p__102_)) (jolt-invoke (var-deref "jolt.analyzer" "analyze") ctx p__102_ env)))) (_a$9083 (jolt-drop 3 items))) (jolt-invoke _a$9081 _a$9082 _a$9083)))) (jolt-invoke _a$9084 _a$9085 _a$9086)) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "form-sym?") member)) (let* ((_o$9091 (keyword #f "op")) (_o$9092 (keyword #f "host-call")) (_o$9093 (keyword #f "method")) (_o$9094 (jolt-invoke (var-deref "jolt.host" "form-sym-name") member)) (_o$9095 (keyword #f "target")) (_o$9096 (jolt-invoke (var-deref "jolt.analyzer" "analyze") ctx target env)) (_o$9097 (keyword #f "args")) (_o$9098 (let* ((_a$9088 (var-deref "clojure.core" "mapv")) (_a$9089 (lambda (p__103_) (let fnrec9087 ((p__103_ p__103_)) (jolt-invoke (var-deref "jolt.analyzer" "analyze") ctx p__103_ env)))) (_a$9090 (jolt-drop 3 items))) (jolt-invoke _a$9088 _a$9089 _a$9090)))) (jolt-hash-map _o$9091 _o$9092 _o$9093 _o$9094 _o$9095 _o$9096 _o$9097 _o$9098)) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "form-keyword?") member)) (let* ((_a$9099 (var-deref "jolt.ir" "invoke")) (_a$9100 (jolt-invoke (var-deref "jolt.analyzer" "analyze") ctx member env)) (_a$9101 (jolt-vector (jolt-invoke (var-deref "jolt.analyzer" "analyze") ctx (jolt-nth items 1) env)))) (jolt-invoke _a$9099 _a$9100 _a$9101)) (if (jolt-truthy? (keyword #f "else")) (jolt-invoke (var-deref "jolt.analyzer" "uncompilable") "special form . (non-symbol member)") jolt-nil)))))))))) analyze-dot) (let* ((_o$9102 (keyword #f "private")) (_o$9103 #t)) (jolt-hash-map _o$9102 _o$9103)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.analyzer" "analyze-field" (letrec ((analyze-field (lambda (ctx hname items env) (let fnrec9104 ((ctx ctx) (hname hname) (items items) (env env)) (begin (if (jolt-n< (jolt-count items) 2) (jolt-throw (jolt-invoke (var-deref "clojure.core" "str") "Malformed (.-field target) form")) jolt-nil) (let* ((_o$9105 (keyword #f "op")) (_o$9106 (keyword #f "host-call")) (_o$9107 (keyword #f "method")) (_o$9108 (jolt-invoke (var-deref "clojure.core" "subs") hname 1)) (_o$9109 (keyword #f "target")) (_o$9110 (jolt-invoke (var-deref "jolt.analyzer" "analyze") ctx (jolt-nth items 1) env)) (_o$9111 (keyword #f "args")) (_o$9112 (jolt-vector))) (jolt-hash-map _o$9105 _o$9106 _o$9107 _o$9108 _o$9109 _o$9110 _o$9111 _o$9112))))))) analyze-field) (let* ((_o$9113 (keyword #f "private")) (_o$9114 #t)) (jolt-hash-map _o$9113 _o$9114)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.analyzer" "analyze-symbol" (letrec ((analyze-symbol (lambda (ctx form env) (let fnrec9115 ((ctx ctx) (form form) (env env)) (let* ((nm (jolt-invoke (var-deref "jolt.host" "form-sym-name") form)) (ns (jolt-invoke (var-deref "jolt.host" "form-sym-ns") form))) (if (jolt-truthy? (let* ((and__25__auto (jolt-nil? ns))) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "jolt.analyzer" "local?") env nm) and__25__auto))) (let* ((h (jolt-get (jolt-get env (keyword #f "hints")) nm))) (if (jolt-truthy? h) (jolt-assoc (jolt-invoke (var-deref "jolt.ir" "local") nm) (keyword #f "hint") h) (jolt-invoke (var-deref "jolt.ir" "local") nm))) (if (jolt-truthy? ns) (let* ((r (jolt-invoke (var-deref "jolt.host" "resolve-global") ctx form))) (if (jolt= (keyword #f "var") (jolt-get r (keyword #f "kind"))) (let* ((G__153 (let* ((_a$9116 (var-deref "jolt.ir" "var-ref")) (_a$9117 (jolt-get r (keyword #f "ns"))) (_a$9118 (jolt-get r (keyword #f "name")))) (jolt-invoke _a$9116 _a$9117 _a$9118)))) (let* ((G__154 (if (jolt-truthy? (jolt-get r (keyword #f "num-ret"))) (jolt-assoc G__153 (keyword #f "num-ret") (jolt-get r (keyword #f "num-ret"))) G__153))) G__154)) (jolt-invoke (var-deref "jolt.ir" "host-static") ns nm))) (if (jolt-truthy? (keyword #f "else")) (let* ((r (jolt-invoke (var-deref "jolt.host" "resolve-global") ctx form))) (let* ((G__155 (jolt-get r (keyword #f "kind")))) (if (jolt= G__155 (keyword #f "var")) (let* ((G__156 (let* ((_a$9119 (var-deref "jolt.ir" "var-ref")) (_a$9120 (jolt-get r (keyword #f "ns"))) (_a$9121 (jolt-get r (keyword #f "name")))) (jolt-invoke _a$9119 _a$9120 _a$9121)))) (let* ((G__157 (if (jolt-truthy? (jolt-get r (keyword #f "num-ret"))) (jolt-assoc G__156 (keyword #f "num-ret") (jolt-get r (keyword #f "num-ret"))) G__156))) G__157)) (if (jolt= G__155 (keyword #f "host")) (jolt-invoke (var-deref "jolt.ir" "host-ref") (jolt-get r (keyword #f "name"))) (if (jolt= G__155 (keyword #f "class")) (jolt-invoke (var-deref "jolt.ir" "const") (jolt-get r (keyword #f "name"))) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "late-bind?") ctx)) (jolt-invoke (var-deref "jolt.ir" "var-ref") (jolt-invoke (var-deref "jolt.host" "compile-ns") ctx) nm) (jolt-invoke (var-deref "jolt.analyzer" "uncompilable") (jolt-invoke (var-deref "clojure.core" "str") "Unable to resolve symbol: " nm " in this context")))))))) jolt-nil)))))))) analyze-symbol) (let* ((_o$9122 (keyword #f "private")) (_o$9123 #t)) (jolt-hash-map _o$9122 _o$9123)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.analyzer" "unchecked-arith" (letrec ((unchecked-arith (lambda (hname n) (let fnrec9124 ((hname hname) (n n)) (if (jolt= hname "+") "unchecked-add" (if (jolt= hname "*") "unchecked-multiply" (if (jolt= hname "-") (if (jolt= n 2) "unchecked-negate" "unchecked-subtract") (if (jolt= hname "inc") "unchecked-inc" (if (jolt= hname "dec") "unchecked-dec" (if (jolt-truthy? (keyword #f "else")) jolt-nil jolt-nil)))))))))) unchecked-arith) (let* ((_o$9125 (keyword #f "private")) (_o$9126 #t)) (jolt-hash-map _o$9125 _o$9126)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.analyzer" "analyze-list" (letrec ((analyze-list (lambda (ctx form env) (let fnrec9127 ((ctx ctx) (form form) (env env)) (let* ((items (jolt-invoke (var-deref "clojure.core" "vec") (jolt-invoke (var-deref "jolt.host" "form-elements") form)))) (if (jolt-zero? (jolt-count items)) (jolt-invoke (var-deref "jolt.ir" "quote-node") form) (let* ((head (jolt-first items)) (hname (if (jolt-truthy? (let* ((and__25__auto (jolt-invoke (var-deref "jolt.host" "form-sym?") head))) (if (jolt-truthy? and__25__auto) (jolt-nil? (jolt-invoke (var-deref "jolt.host" "form-sym-ns") head)) and__25__auto))) (jolt-invoke (var-deref "jolt.host" "form-sym-name") head) jolt-nil)) (sf-name (let* ((or__26__auto hname)) (if (jolt-truthy? or__26__auto) or__26__auto (if (jolt-truthy? (let* ((and__25__auto (jolt-invoke (var-deref "jolt.host" "form-sym?") head))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt= "clojure.core" (jolt-invoke (var-deref "jolt.host" "form-sym-ns") head)))) (if (jolt-truthy? and__25__auto) (jolt-contains? (var-deref "jolt.analyzer" "handled") (jolt-invoke (var-deref "jolt.host" "form-sym-name") head)) and__25__auto)) and__25__auto))) (jolt-invoke (var-deref "jolt.host" "form-sym-name") head) jolt-nil)))) (shadowed (let* ((and__25__auto hname)) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "jolt.analyzer" "local?") env hname) and__25__auto))) (unm (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "unchecked-math?"))) (let* ((opn (if (jolt-truthy? (let* ((and__25__auto hname)) (if (jolt-truthy? and__25__auto) (jolt-not shadowed) and__25__auto))) hname (if (jolt-truthy? (let* ((and__25__auto (jolt-invoke (var-deref "jolt.host" "form-sym?") head))) (if (jolt-truthy? and__25__auto) (jolt= "clojure.core" (jolt-invoke (var-deref "jolt.host" "form-sym-ns") head)) and__25__auto))) (jolt-invoke (var-deref "jolt.host" "form-sym-name") head) jolt-nil)))) (if (jolt-truthy? opn) (jolt-invoke (var-deref "jolt.analyzer" "unchecked-arith") opn (jolt-count items)) jolt-nil)) jolt-nil))) (if (jolt-truthy? unm) (jolt-invoke (var-deref "jolt.analyzer" "analyze") ctx (let* ((_a$9128 (jolt-invoke (var-deref "clojure.core" "symbol") unm)) (_a$9129 (jolt-rest items))) (jolt-cons _a$9128 _a$9129)) env) (if (jolt-truthy? (let* ((and__25__auto (jolt-invoke (var-deref "jolt.host" "form-sym?") head))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt-not shadowed))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt-not (jolt-contains? (var-deref "jolt.analyzer" "handled") sf-name)))) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "jolt.host" "form-macro?") ctx head) and__25__auto)) and__25__auto)) and__25__auto))) (let* ((node (jolt-invoke (var-deref "jolt.analyzer" "analyze") ctx (jolt-invoke (var-deref "jolt.host" "form-expand-1") ctx form (jolt-invoke (var-deref "jolt.analyzer" "amp-env-map") env)) env)) (p (jolt-invoke (var-deref "jolt.host" "form-position") form))) (if (jolt-truthy? (let* ((and__25__auto p)) (if (jolt-truthy? and__25__auto) (jolt= (keyword #f "def") (jolt-get node (keyword #f "op"))) and__25__auto))) (jolt-assoc node (keyword #f "pos") p) node)) (if (jolt-truthy? (let* ((and__25__auto (jolt-invoke (var-deref "jolt.host" "form-sym?") head))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt= "jolt.ffi" (jolt-invoke (var-deref "jolt.host" "form-sym-ns") head)))) (if (jolt-truthy? and__25__auto) (jolt= "__cfn" (jolt-invoke (var-deref "jolt.host" "form-sym-name") head)) and__25__auto)) and__25__auto))) (jolt-invoke (var-deref "jolt.analyzer" "analyze-ffi-fn") ctx items env) (if (jolt-truthy? (let* ((and__25__auto (jolt-invoke (var-deref "jolt.host" "form-sym?") head))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt= "jolt.ffi" (jolt-invoke (var-deref "jolt.host" "form-sym-ns") head)))) (if (jolt-truthy? and__25__auto) (jolt= "__ccallable" (jolt-invoke (var-deref "jolt.host" "form-sym-name") head)) and__25__auto)) and__25__auto))) (jolt-invoke (var-deref "jolt.analyzer" "analyze-ffi-callable") ctx items env) (if (jolt-truthy? (let* ((and__25__auto sf-name)) (if (jolt-truthy? and__25__auto) (jolt-contains? (var-deref "jolt.analyzer" "handled") sf-name) and__25__auto))) (let* ((node (jolt-invoke (var-deref "jolt.analyzer" "analyze-special") ctx sf-name items env)) (p (jolt-invoke (var-deref "jolt.host" "form-position") form))) (if (jolt-truthy? (let* ((and__25__auto p)) (if (jolt-truthy? and__25__auto) (jolt= (keyword #f "def") (jolt-get node (keyword #f "op"))) and__25__auto))) (jolt-assoc node (keyword #f "pos") p) node)) (if (jolt-truthy? (let* ((and__25__auto hname)) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt-not shadowed))) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "jolt.analyzer" "method-head?") hname) and__25__auto)) and__25__auto))) (jolt-invoke (var-deref "jolt.analyzer" "analyze-host-call") ctx hname items env) (if (jolt-truthy? (let* ((and__25__auto hname)) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt-not shadowed))) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "jolt.analyzer" "ctor-head?") hname) and__25__auto)) and__25__auto))) (let* ((_a$9130 (var-deref "jolt.analyzer" "analyze-ctor")) (_a$9131 ctx) (_a$9132 (jolt-invoke (var-deref "clojure.core" "subs") hname 0 (jolt-dec (jolt-count hname)))) (_a$9133 (jolt-rest items)) (_a$9134 env)) (jolt-invoke _a$9130 _a$9131 _a$9132 _a$9133 _a$9134)) (if (jolt-truthy? (let* ((and__25__auto (jolt= hname "new"))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt-not shadowed))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt-n>= (jolt-count items) 2))) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "jolt.host" "form-sym?") (jolt-nth items 1)) and__25__auto)) and__25__auto)) and__25__auto))) (let* ((_a$9135 (var-deref "jolt.analyzer" "analyze-ctor")) (_a$9136 ctx) (_a$9137 (jolt-invoke (var-deref "jolt.host" "form-sym-name") (jolt-nth items 1))) (_a$9138 (jolt-drop 2 items)) (_a$9139 env)) (jolt-invoke _a$9135 _a$9136 _a$9137 _a$9138 _a$9139)) (if (let* ((and__25__auto (jolt= hname "."))) (if (jolt-truthy? and__25__auto) (jolt-not shadowed) and__25__auto)) (jolt-invoke (var-deref "jolt.analyzer" "analyze-dot") ctx items env) (if (jolt-truthy? (let* ((and__25__auto hname)) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt-not shadowed))) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "jolt.analyzer" "field-head?") hname) and__25__auto)) and__25__auto))) (jolt-invoke (var-deref "jolt.analyzer" "analyze-field") ctx hname items env) (if (jolt-truthy? (let* ((and__25__auto hname)) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt-not shadowed))) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "jolt.host" "form-special?") hname) and__25__auto)) and__25__auto))) (jolt-invoke (var-deref "jolt.analyzer" "uncompilable") (jolt-invoke (var-deref "clojure.core" "str") "special form " hname)) (if (jolt-truthy? (keyword #f "else")) (let* ((n (let* ((_a$9144 (var-deref "jolt.ir" "invoke")) (_a$9145 (jolt-invoke (var-deref "jolt.analyzer" "analyze") ctx head env)) (_a$9146 (let* ((_a$9141 (var-deref "clojure.core" "mapv")) (_a$9142 (lambda (p__104_) (let fnrec9140 ((p__104_ p__104_)) (jolt-invoke (var-deref "jolt.analyzer" "analyze") ctx p__104_ env)))) (_a$9143 (jolt-rest items))) (jolt-invoke _a$9141 _a$9142 _a$9143)))) (jolt-invoke _a$9144 _a$9145 _a$9146))) (p (jolt-invoke (var-deref "jolt.host" "form-position") form))) (if (jolt-truthy? p) (jolt-assoc n (keyword #f "pos") p) n)) jolt-nil))))))))))))))))))) analyze-list) (let* ((_o$9147 (keyword #f "private")) (_o$9148 #t)) (jolt-hash-map _o$9147 _o$9148)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.analyzer" "with-coll-meta" (letrec ((with-coll-meta (lambda (ctx form env node) (let fnrec9149 ((ctx ctx) (form form) (env env) (node node)) (let* ((m (jolt-invoke (var-deref "jolt.host" "form-coll-meta") form))) (if (jolt-nil? m) node (let* ((_a$9152 (var-deref "jolt.ir" "invoke")) (_a$9153 (jolt-invoke (var-deref "jolt.ir" "var-ref") "clojure.core" "with-meta")) (_a$9154 (let* ((_o$9150 node) (_o$9151 (jolt-invoke (var-deref "jolt.analyzer" "analyze") ctx m env))) (jolt-vector _o$9150 _o$9151)))) (jolt-invoke _a$9152 _a$9153 _a$9154)))))))) with-coll-meta) (let* ((_o$9155 (keyword #f "private")) (_o$9156 #t)) (jolt-hash-map _o$9155 _o$9156)))) -(guard (e (#t #f)) - (def-var! "jolt.analyzer" "analyze" (letrec ((analyze (case-lambda ((ctx form) (let fnrec9157 ((ctx ctx) (form form)) (analyze ctx form (jolt-invoke (var-deref "jolt.analyzer" "empty-env"))))) ((ctx form env) (let fnrec9158 ((ctx ctx) (form form) (env env)) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "form-literal?") form)) (jolt-invoke (var-deref "jolt.ir" "const") form) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "form-sym?") form)) (jolt-invoke (var-deref "jolt.analyzer" "analyze-symbol") ctx form env) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "form-vec?") form)) (jolt-invoke (var-deref "jolt.analyzer" "with-coll-meta") ctx form env (jolt-invoke (var-deref "jolt.ir" "vector-node") (let* ((_a$9160 (var-deref "clojure.core" "mapv")) (_a$9161 (lambda (p__105_) (let fnrec9159 ((p__105_ p__105_)) (analyze ctx p__105_ env)))) (_a$9162 (jolt-invoke (var-deref "jolt.host" "form-vec-items") form))) (jolt-invoke _a$9160 _a$9161 _a$9162)))) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "form-map?") form)) (jolt-invoke (var-deref "jolt.analyzer" "with-coll-meta") ctx form env (jolt-invoke (var-deref "jolt.ir" "map-node") (let* ((_a$9166 (var-deref "clojure.core" "mapv")) (_a$9167 (lambda (p) (let fnrec9163 ((p p)) (let* ((_o$9164 (analyze ctx (jolt-first p) env)) (_o$9165 (analyze ctx (jolt-invoke (var-deref "clojure.core" "second") p) env))) (jolt-vector _o$9164 _o$9165))))) (_a$9168 (jolt-invoke (var-deref "jolt.host" "form-map-pairs") form))) (jolt-invoke _a$9166 _a$9167 _a$9168)))) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "form-set?") form)) (jolt-invoke (var-deref "jolt.analyzer" "with-coll-meta") ctx form env (jolt-invoke (var-deref "jolt.ir" "set-node") (let* ((_a$9170 (var-deref "clojure.core" "mapv")) (_a$9171 (lambda (p__106_) (let fnrec9169 ((p__106_ p__106_)) (analyze ctx p__106_ env)))) (_a$9172 (jolt-invoke (var-deref "jolt.host" "form-set-items") form))) (jolt-invoke _a$9170 _a$9171 _a$9172)))) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "form-list?") form)) (jolt-invoke (var-deref "jolt.analyzer" "analyze-list") ctx form env) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "form-regex?") form)) (let* ((_o$9173 (keyword #f "op")) (_o$9174 (keyword #f "regex")) (_o$9175 (keyword #f "source")) (_o$9176 (jolt-invoke (var-deref "jolt.host" "form-regex-source") form))) (jolt-hash-map _o$9173 _o$9174 _o$9175 _o$9176)) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "form-inst?") form)) (let* ((_o$9177 (keyword #f "op")) (_o$9178 (keyword #f "inst")) (_o$9179 (keyword #f "source")) (_o$9180 (jolt-invoke (var-deref "jolt.host" "form-inst-source") form))) (jolt-hash-map _o$9177 _o$9178 _o$9179 _o$9180)) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "form-uuid?") form)) (let* ((_o$9181 (keyword #f "op")) (_o$9182 (keyword #f "uuid")) (_o$9183 (keyword #f "source")) (_o$9184 (jolt-invoke (var-deref "jolt.host" "form-uuid-source") form))) (jolt-hash-map _o$9181 _o$9182 _o$9183 _o$9184)) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "form-bigdec?") form)) (let* ((_o$9185 (keyword #f "op")) (_o$9186 (keyword #f "bigdec")) (_o$9187 (keyword #f "source")) (_o$9188 (jolt-invoke (var-deref "jolt.host" "form-bigdec-source") form))) (jolt-hash-map _o$9185 _o$9186 _o$9187 _o$9188)) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "form-ns-value?") form)) (let* ((_o$9189 (keyword #f "op")) (_o$9190 (keyword #f "the-ns")) (_o$9191 (keyword #f "name")) (_o$9192 (jolt-invoke (var-deref "jolt.host" "form-ns-value-name") form))) (jolt-hash-map _o$9189 _o$9190 _o$9191 _o$9192)) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "form-var-value?") form)) (let* ((_a$9193 (var-deref "jolt.ir" "the-var")) (_a$9194 (jolt-invoke (var-deref "jolt.host" "form-var-value-ns") form)) (_a$9195 (jolt-invoke (var-deref "jolt.host" "form-var-value-name") form))) (jolt-invoke _a$9193 _a$9194 _a$9195)) (if (jolt-truthy? (keyword #f "else")) (jolt-invoke (var-deref "jolt.analyzer" "uncompilable") "unsupported form") jolt-nil)))))))))))))))))) analyze))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.backend-scheme" "native-ops" (let* ((_o$7267 "+") (_o$7268 "jolt-n+") (_o$7269 "-") (_o$7270 "jolt-n-") (_o$7271 "*") (_o$7272 "jolt-n*") (_o$7273 "/") (_o$7274 "jolt-n-div") (_o$7275 "<") (_o$7276 "jolt-n<") (_o$7277 ">") (_o$7278 "jolt-n>") (_o$7279 "<=") (_o$7280 "jolt-n<=") (_o$7281 ">=") (_o$7282 "jolt-n>=") (_o$7283 "=") (_o$7284 "jolt=") (_o$7285 "inc") (_o$7286 "jolt-inc") (_o$7287 "dec") (_o$7288 "jolt-dec") (_o$7289 "not") (_o$7290 "jolt-not") (_o$7291 "min") (_o$7292 "jolt-n-min") (_o$7293 "max") (_o$7294 "jolt-n-max") (_o$7295 "mod") (_o$7296 "jolt-mod") (_o$7297 "rem") (_o$7298 "jolt-rem") (_o$7299 "quot") (_o$7300 "jolt-quot") (_o$7301 "vector") (_o$7302 "jolt-vector") (_o$7303 "hash-map") (_o$7304 "jolt-hash-map-fn") (_o$7305 "hash-set") (_o$7306 "jolt-hash-set") (_o$7307 "conj") (_o$7308 "jolt-conj") (_o$7309 "get") (_o$7310 "jolt-get") (_o$7311 "nth") (_o$7312 "jolt-nth") (_o$7313 "count") (_o$7314 "jolt-count") (_o$7315 "assoc") (_o$7316 "jolt-assoc") (_o$7317 "dissoc") (_o$7318 "jolt-dissoc") (_o$7319 "contains?") (_o$7320 "jolt-contains?") (_o$7321 "empty?") (_o$7322 "jolt-empty?") (_o$7323 "peek") (_o$7324 "jolt-peek") (_o$7325 "pop") (_o$7326 "jolt-pop") (_o$7327 "first") (_o$7328 "jolt-first") (_o$7329 "rest") (_o$7330 "jolt-rest") (_o$7331 "next") (_o$7332 "jolt-next") (_o$7333 "seq") (_o$7334 "jolt-seq") (_o$7335 "cons") (_o$7336 "jolt-cons") (_o$7337 "list") (_o$7338 "jolt-list") (_o$7339 "reverse") (_o$7340 "jolt-reverse") (_o$7341 "last") (_o$7342 "jolt-last") (_o$7343 "map") (_o$7344 "jolt-map") (_o$7345 "filter") (_o$7346 "jolt-filter") (_o$7347 "remove") (_o$7348 "jolt-remove") (_o$7349 "reduce") (_o$7350 "jolt-reduce") (_o$7351 "into") (_o$7352 "jolt-into") (_o$7353 "concat") (_o$7354 "jolt-concat") (_o$7355 "apply") (_o$7356 "jolt-apply") (_o$7357 "range") (_o$7358 "jolt-range") (_o$7359 "take") (_o$7360 "jolt-take") (_o$7361 "drop") (_o$7362 "jolt-drop") (_o$7363 "keys") (_o$7364 "jolt-keys") (_o$7365 "vals") (_o$7366 "jolt-vals") (_o$7367 "even?") (_o$7368 "jolt-even?") (_o$7369 "odd?") (_o$7370 "jolt-odd?") (_o$7371 "pos?") (_o$7372 "jolt-pos?") (_o$7373 "neg?") (_o$7374 "jolt-neg?") (_o$7375 "zero?") (_o$7376 "jolt-zero?") (_o$7377 "identity") (_o$7378 "jolt-identity") (_o$7379 "nil?") (_o$7380 "jolt-nil?") (_o$7381 "some?") (_o$7382 "jolt-some?") (_o$7383 "ex-info") (_o$7384 "jolt-ex-info") (_o$7385 "bit-and") (_o$7386 "bitwise-and") (_o$7387 "bit-or") (_o$7388 "bitwise-ior") (_o$7389 "bit-xor") (_o$7390 "bitwise-xor") (_o$7391 "bit-not") (_o$7392 "bitwise-not") (_o$7393 "bit-shift-left") (_o$7394 "jolt-bit-shift-left") (_o$7395 "bit-shift-right") (_o$7396 "jolt-bit-shift-right") (_o$7397 "unsigned-bit-shift-right") (_o$7398 "jolt-unsigned-bit-shift-right") (_o$7399 "protocol-dispatch1") (_o$7400 "protocol-dispatch1") (_o$7401 "protocol-dispatch2") (_o$7402 "protocol-dispatch2") (_o$7403 "protocol-dispatch3") (_o$7404 "protocol-dispatch3")) (jolt-hash-map _o$7267 _o$7268 _o$7269 _o$7270 _o$7271 _o$7272 _o$7273 _o$7274 _o$7275 _o$7276 _o$7277 _o$7278 _o$7279 _o$7280 _o$7281 _o$7282 _o$7283 _o$7284 _o$7285 _o$7286 _o$7287 _o$7288 _o$7289 _o$7290 _o$7291 _o$7292 _o$7293 _o$7294 _o$7295 _o$7296 _o$7297 _o$7298 _o$7299 _o$7300 _o$7301 _o$7302 _o$7303 _o$7304 _o$7305 _o$7306 _o$7307 _o$7308 _o$7309 _o$7310 _o$7311 _o$7312 _o$7313 _o$7314 _o$7315 _o$7316 _o$7317 _o$7318 _o$7319 _o$7320 _o$7321 _o$7322 _o$7323 _o$7324 _o$7325 _o$7326 _o$7327 _o$7328 _o$7329 _o$7330 _o$7331 _o$7332 _o$7333 _o$7334 _o$7335 _o$7336 _o$7337 _o$7338 _o$7339 _o$7340 _o$7341 _o$7342 _o$7343 _o$7344 _o$7345 _o$7346 _o$7347 _o$7348 _o$7349 _o$7350 _o$7351 _o$7352 _o$7353 _o$7354 _o$7355 _o$7356 _o$7357 _o$7358 _o$7359 _o$7360 _o$7361 _o$7362 _o$7363 _o$7364 _o$7365 _o$7366 _o$7367 _o$7368 _o$7369 _o$7370 _o$7371 _o$7372 _o$7373 _o$7374 _o$7375 _o$7376 _o$7377 _o$7378 _o$7379 _o$7380 _o$7381 _o$7382 _o$7383 _o$7384 _o$7385 _o$7386 _o$7387 _o$7388 _o$7389 _o$7390 _o$7391 _o$7392 _o$7393 _o$7394 _o$7395 _o$7396 _o$7397 _o$7398 _o$7399 _o$7400 _o$7401 _o$7402 _o$7403 _o$7404)) (let* ((_o$7405 (keyword #f "private")) (_o$7406 #t)) (jolt-hash-map _o$7405 _o$7406)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.backend-scheme" "core-value-procs" (jolt-invoke (var-deref "clojure.core" "merge") (var-deref "jolt.backend-scheme" "native-ops") (let* ((_o$7407 "+") (_o$7408 "jolt-add") (_o$7409 "-") (_o$7410 "jolt-sub") (_o$7411 "*") (_o$7412 "jolt-mul") (_o$7413 "/") (_o$7414 "jolt-div") (_o$7415 "min") (_o$7416 "jolt-min") (_o$7417 "max") (_o$7418 "jolt-max") (_o$7419 "<") (_o$7420 "jolt-lt") (_o$7421 ">") (_o$7422 "jolt-gt") (_o$7423 "<=") (_o$7424 "jolt-le") (_o$7425 ">=") (_o$7426 "jolt-ge")) (jolt-hash-map _o$7407 _o$7408 _o$7409 _o$7410 _o$7411 _o$7412 _o$7413 _o$7414 _o$7415 _o$7416 _o$7417 _o$7418 _o$7419 _o$7420 _o$7421 _o$7422 _o$7423 _o$7424 _o$7425 _o$7426))) (let* ((_o$7427 (keyword #f "private")) (_o$7428 #t)) (jolt-hash-map _o$7427 _o$7428)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.backend-scheme" "op-arity" (let* ((_o$7482 "inc") (_o$7483 (lambda (p__42_) (let fnrec7429 ((p__42_ p__42_)) (jolt= p__42_ 1)))) (_o$7484 "dec") (_o$7485 (lambda (p__43_) (let fnrec7430 ((p__43_ p__43_)) (jolt= p__43_ 1)))) (_o$7486 "not") (_o$7487 (lambda (p__44_) (let fnrec7431 ((p__44_ p__44_)) (jolt= p__44_ 1)))) (_o$7488 "count") (_o$7489 (lambda (p__45_) (let fnrec7432 ((p__45_ p__45_)) (jolt= p__45_ 1)))) (_o$7490 "empty?") (_o$7491 (lambda (p__46_) (let fnrec7433 ((p__46_ p__46_)) (jolt= p__46_ 1)))) (_o$7492 "peek") (_o$7493 (lambda (p__47_) (let fnrec7434 ((p__47_ p__47_)) (jolt= p__47_ 1)))) (_o$7494 "pop") (_o$7495 (lambda (p__48_) (let fnrec7435 ((p__48_ p__48_)) (jolt= p__48_ 1)))) (_o$7496 "mod") (_o$7497 (lambda (p__49_) (let fnrec7436 ((p__49_ p__49_)) (jolt= p__49_ 2)))) (_o$7498 "rem") (_o$7499 (lambda (p__50_) (let fnrec7437 ((p__50_ p__50_)) (jolt= p__50_ 2)))) (_o$7500 "quot") (_o$7501 (lambda (p__51_) (let fnrec7438 ((p__51_ p__51_)) (jolt= p__51_ 2)))) (_o$7502 "contains?") (_o$7503 (lambda (p__52_) (let fnrec7439 ((p__52_ p__52_)) (jolt= p__52_ 2)))) (_o$7504 "get") (_o$7505 (lambda (p__53_) (let fnrec7440 ((p__53_ p__53_)) (let* ((or__26__auto (jolt= p__53_ 2))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt= p__53_ 3)))))) (_o$7506 "nth") (_o$7507 (lambda (p__54_) (let fnrec7441 ((p__54_ p__54_)) (let* ((or__26__auto (jolt= p__54_ 2))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt= p__54_ 3)))))) (_o$7508 "assoc") (_o$7509 (lambda (p__55_) (let fnrec7442 ((p__55_ p__55_)) (let* ((and__25__auto (jolt-n>= p__55_ 3))) (if (jolt-truthy? and__25__auto) (jolt-odd? p__55_) and__25__auto))))) (_o$7510 "dissoc") (_o$7511 (lambda (p__56_) (let fnrec7443 ((p__56_ p__56_)) (jolt-n>= p__56_ 1)))) (_o$7512 "conj") (_o$7513 (lambda (p__57_) (let fnrec7444 ((p__57_ p__57_)) (jolt-n>= p__57_ 1)))) (_o$7514 "first") (_o$7515 (lambda (p__58_) (let fnrec7445 ((p__58_ p__58_)) (jolt= p__58_ 1)))) (_o$7516 "rest") (_o$7517 (lambda (p__59_) (let fnrec7446 ((p__59_ p__59_)) (jolt= p__59_ 1)))) (_o$7518 "next") (_o$7519 (lambda (p__60_) (let fnrec7447 ((p__60_ p__60_)) (jolt= p__60_ 1)))) (_o$7520 "seq") (_o$7521 (lambda (p__61_) (let fnrec7448 ((p__61_ p__61_)) (jolt= p__61_ 1)))) (_o$7522 "reverse") (_o$7523 (lambda (p__62_) (let fnrec7449 ((p__62_ p__62_)) (jolt= p__62_ 1)))) (_o$7524 "last") (_o$7525 (lambda (p__63_) (let fnrec7450 ((p__63_ p__63_)) (jolt= p__63_ 1)))) (_o$7526 "keys") (_o$7527 (lambda (p__64_) (let fnrec7451 ((p__64_ p__64_)) (jolt= p__64_ 1)))) (_o$7528 "vals") (_o$7529 (lambda (p__65_) (let fnrec7452 ((p__65_ p__65_)) (jolt= p__65_ 1)))) (_o$7530 "even?") (_o$7531 (lambda (p__66_) (let fnrec7453 ((p__66_ p__66_)) (jolt= p__66_ 1)))) (_o$7532 "odd?") (_o$7533 (lambda (p__67_) (let fnrec7454 ((p__67_ p__67_)) (jolt= p__67_ 1)))) (_o$7534 "pos?") (_o$7535 (lambda (p__68_) (let fnrec7455 ((p__68_ p__68_)) (jolt= p__68_ 1)))) (_o$7536 "neg?") (_o$7537 (lambda (p__69_) (let fnrec7456 ((p__69_ p__69_)) (jolt= p__69_ 1)))) (_o$7538 "zero?") (_o$7539 (lambda (p__70_) (let fnrec7457 ((p__70_ p__70_)) (jolt= p__70_ 1)))) (_o$7540 "identity") (_o$7541 (lambda (p__71_) (let fnrec7458 ((p__71_ p__71_)) (jolt= p__71_ 1)))) (_o$7542 "nil?") (_o$7543 (lambda (p__72_) (let fnrec7459 ((p__72_ p__72_)) (jolt= p__72_ 1)))) (_o$7544 "some?") (_o$7545 (lambda (p__73_) (let fnrec7460 ((p__73_ p__73_)) (jolt= p__73_ 1)))) (_o$7546 "protocol-dispatch1") (_o$7547 (lambda (p__74_) (let fnrec7461 ((p__74_ p__74_)) (jolt= p__74_ 3)))) (_o$7548 "protocol-dispatch2") (_o$7549 (lambda (p__75_) (let fnrec7462 ((p__75_ p__75_)) (jolt= p__75_ 4)))) (_o$7550 "protocol-dispatch3") (_o$7551 (lambda (p__76_) (let fnrec7463 ((p__76_ p__76_)) (jolt= p__76_ 5)))) (_o$7552 "cons") (_o$7553 (lambda (p__77_) (let fnrec7464 ((p__77_ p__77_)) (jolt= p__77_ 2)))) (_o$7554 "filter") (_o$7555 (lambda (p__78_) (let fnrec7465 ((p__78_ p__78_)) (jolt= p__78_ 2)))) (_o$7556 "remove") (_o$7557 (lambda (p__79_) (let fnrec7466 ((p__79_ p__79_)) (jolt= p__79_ 2)))) (_o$7558 "into") (_o$7559 (lambda (p__80_) (let fnrec7467 ((p__80_ p__80_)) (jolt= p__80_ 2)))) (_o$7560 "take") (_o$7561 (lambda (p__81_) (let fnrec7468 ((p__81_ p__81_)) (jolt= p__81_ 2)))) (_o$7562 "drop") (_o$7563 (lambda (p__82_) (let fnrec7469 ((p__82_ p__82_)) (jolt= p__82_ 2)))) (_o$7564 "map") (_o$7565 (lambda (p__83_) (let fnrec7470 ((p__83_ p__83_)) (jolt-n>= p__83_ 2)))) (_o$7566 "apply") (_o$7567 (lambda (p__84_) (let fnrec7471 ((p__84_ p__84_)) (jolt-n>= p__84_ 2)))) (_o$7568 "reduce") (_o$7569 (lambda (p__85_) (let fnrec7472 ((p__85_ p__85_)) (let* ((or__26__auto (jolt= p__85_ 2))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt= p__85_ 3)))))) (_o$7570 "range") (_o$7571 (lambda (p__86_) (let fnrec7473 ((p__86_ p__86_)) (let* ((and__25__auto (jolt-n>= p__86_ 0))) (if (jolt-truthy? and__25__auto) (jolt-n<= p__86_ 3) and__25__auto))))) (_o$7572 "ex-info") (_o$7573 (lambda (p__87_) (let fnrec7474 ((p__87_ p__87_)) (let* ((or__26__auto (jolt= p__87_ 2))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt= p__87_ 3)))))) (_o$7574 "bit-and") (_o$7575 (lambda (p__88_) (let fnrec7475 ((p__88_ p__88_)) (jolt= p__88_ 2)))) (_o$7576 "bit-or") (_o$7577 (lambda (p__89_) (let fnrec7476 ((p__89_ p__89_)) (jolt= p__89_ 2)))) (_o$7578 "bit-xor") (_o$7579 (lambda (p__90_) (let fnrec7477 ((p__90_ p__90_)) (jolt= p__90_ 2)))) (_o$7580 "bit-not") (_o$7581 (lambda (p__91_) (let fnrec7478 ((p__91_ p__91_)) (jolt= p__91_ 1)))) (_o$7582 "bit-shift-left") (_o$7583 (lambda (p__92_) (let fnrec7479 ((p__92_ p__92_)) (jolt= p__92_ 2)))) (_o$7584 "bit-shift-right") (_o$7585 (lambda (p__93_) (let fnrec7480 ((p__93_ p__93_)) (jolt= p__93_ 2)))) (_o$7586 "unsigned-bit-shift-right") (_o$7587 (lambda (p__94_) (let fnrec7481 ((p__94_ p__94_)) (jolt= p__94_ 2))))) (jolt-hash-map _o$7482 _o$7483 _o$7484 _o$7485 _o$7486 _o$7487 _o$7488 _o$7489 _o$7490 _o$7491 _o$7492 _o$7493 _o$7494 _o$7495 _o$7496 _o$7497 _o$7498 _o$7499 _o$7500 _o$7501 _o$7502 _o$7503 _o$7504 _o$7505 _o$7506 _o$7507 _o$7508 _o$7509 _o$7510 _o$7511 _o$7512 _o$7513 _o$7514 _o$7515 _o$7516 _o$7517 _o$7518 _o$7519 _o$7520 _o$7521 _o$7522 _o$7523 _o$7524 _o$7525 _o$7526 _o$7527 _o$7528 _o$7529 _o$7530 _o$7531 _o$7532 _o$7533 _o$7534 _o$7535 _o$7536 _o$7537 _o$7538 _o$7539 _o$7540 _o$7541 _o$7542 _o$7543 _o$7544 _o$7545 _o$7546 _o$7547 _o$7548 _o$7549 _o$7550 _o$7551 _o$7552 _o$7553 _o$7554 _o$7555 _o$7556 _o$7557 _o$7558 _o$7559 _o$7560 _o$7561 _o$7562 _o$7563 _o$7564 _o$7565 _o$7566 _o$7567 _o$7568 _o$7569 _o$7570 _o$7571 _o$7572 _o$7573 _o$7574 _o$7575 _o$7576 _o$7577 _o$7578 _o$7579 _o$7580 _o$7581 _o$7582 _o$7583 _o$7584 _o$7585 _o$7586 _o$7587)) (let* ((_o$7588 (keyword #f "private")) (_o$7589 #t)) (jolt-hash-map _o$7588 _o$7589)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.backend-scheme" "cmp1-ops" (let* ((_o$7590 "jolt-n<") (_o$7591 "jolt-n>") (_o$7592 "jolt-n<=") (_o$7593 "jolt-n>=")) (jolt-hash-set _o$7590 _o$7591 _o$7592 _o$7593)) (let* ((_o$7594 (keyword #f "private")) (_o$7595 #t)) (jolt-hash-map _o$7594 _o$7595)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.backend-scheme" "supported-host-methods" (let* ((_o$7596 "isDirectory") (_o$7597 "listFiles")) (jolt-hash-set _o$7596 _o$7597)) (let* ((_o$7598 (keyword #f "private")) (_o$7599 #t)) (jolt-hash-map _o$7598 _o$7599)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.backend-scheme" "bool-returning-ops" (let* ((_o$7600 "jolt-n<") (_o$7601 "jolt-n<=") (_o$7602 "jolt-n>") (_o$7603 "jolt-n>=") (_o$7604 "jolt=") (_o$7605 "jolt-not") (_o$7606 "jolt-even?") (_o$7607 "jolt-odd?") (_o$7608 "jolt-pos?") (_o$7609 "jolt-neg?") (_o$7610 "jolt-zero?") (_o$7611 "jolt-empty?") (_o$7612 "jolt-contains?") (_o$7613 "jolt-nil?") (_o$7614 "jolt-some?")) (jolt-hash-set _o$7600 _o$7601 _o$7602 _o$7603 _o$7604 _o$7605 _o$7606 _o$7607 _o$7608 _o$7609 _o$7610 _o$7611 _o$7612 _o$7613 _o$7614)) (let* ((_o$7615 (keyword #f "private")) (_o$7616 #t)) (jolt-hash-map _o$7615 _o$7616)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.backend-scheme" "dbl-ops" (let* ((_o$7617 "+") (_o$7618 "fl+") (_o$7619 "-") (_o$7620 "fl-") (_o$7621 "*") (_o$7622 "fl*") (_o$7623 "/") (_o$7624 "fl/") (_o$7625 "min") (_o$7626 "flmin") (_o$7627 "max") (_o$7628 "flmax") (_o$7629 "<") (_o$7630 "fl") (_o$7632 "fl>?") (_o$7633 "<=") (_o$7634 "fl<=?") (_o$7635 ">=") (_o$7636 "fl>=?") (_o$7637 "=") (_o$7638 "fl=?") (_o$7639 "==") (_o$7640 "fl=?")) (jolt-hash-map _o$7617 _o$7618 _o$7619 _o$7620 _o$7621 _o$7622 _o$7623 _o$7624 _o$7625 _o$7626 _o$7627 _o$7628 _o$7629 _o$7630 _o$7631 _o$7632 _o$7633 _o$7634 _o$7635 _o$7636 _o$7637 _o$7638 _o$7639 _o$7640)) (let* ((_o$7641 (keyword #f "private")) (_o$7642 #t)) (jolt-hash-map _o$7641 _o$7642)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.backend-scheme" "lng-ops" (let* ((_o$7643 "+") (_o$7644 "fx+") (_o$7645 "-") (_o$7646 "fx-") (_o$7647 "*") (_o$7648 "fx*") (_o$7649 "min") (_o$7650 "jolt-l-min") (_o$7651 "max") (_o$7652 "jolt-l-max") (_o$7653 "unchecked-add") (_o$7654 "jolt-uncadd2") (_o$7655 "unchecked-subtract") (_o$7656 "jolt-uncsub2") (_o$7657 "unchecked-multiply") (_o$7658 "jolt-uncmul2") (_o$7659 "quot") (_o$7660 "jolt-l-quot") (_o$7661 "rem") (_o$7662 "jolt-l-rem") (_o$7663 "mod") (_o$7664 "jolt-l-mod") (_o$7665 "<") (_o$7666 "jolt-l<") (_o$7667 ">") (_o$7668 "jolt-l>") (_o$7669 "<=") (_o$7670 "jolt-l<=") (_o$7671 ">=") (_o$7672 "jolt-l>=") (_o$7673 "=") (_o$7674 "jolt-l=") (_o$7675 "==") (_o$7676 "jolt-l=")) (jolt-hash-map _o$7643 _o$7644 _o$7645 _o$7646 _o$7647 _o$7648 _o$7649 _o$7650 _o$7651 _o$7652 _o$7653 _o$7654 _o$7655 _o$7656 _o$7657 _o$7658 _o$7659 _o$7660 _o$7661 _o$7662 _o$7663 _o$7664 _o$7665 _o$7666 _o$7667 _o$7668 _o$7669 _o$7670 _o$7671 _o$7672 _o$7673 _o$7674 _o$7675 _o$7676)) (let* ((_o$7677 (keyword #f "private")) (_o$7678 #t)) (jolt-hash-map _o$7677 _o$7678)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.backend-scheme" "bd-ops" (let* ((_o$7679 "+") (_o$7680 "jbd-add") (_o$7681 "-") (_o$7682 "jbd-sub") (_o$7683 "*") (_o$7684 "jbd-mul") (_o$7685 "/") (_o$7686 "jbd-div") (_o$7687 "min") (_o$7688 "jbd-min") (_o$7689 "max") (_o$7690 "jbd-max") (_o$7691 "quot") (_o$7692 "jbd-quot") (_o$7693 "rem") (_o$7694 "jbd-rem") (_o$7695 "<") (_o$7696 "jbd-lt?") (_o$7697 ">") (_o$7698 "jbd-gt?") (_o$7699 "<=") (_o$7700 "jbd-le?") (_o$7701 ">=") (_o$7702 "jbd-ge?") (_o$7703 "zero?") (_o$7704 "jbd-zero?") (_o$7705 "pos?") (_o$7706 "jbd-pos?") (_o$7707 "neg?") (_o$7708 "jbd-neg?")) (jolt-hash-map _o$7679 _o$7680 _o$7681 _o$7682 _o$7683 _o$7684 _o$7685 _o$7686 _o$7687 _o$7688 _o$7689 _o$7690 _o$7691 _o$7692 _o$7693 _o$7694 _o$7695 _o$7696 _o$7697 _o$7698 _o$7699 _o$7700 _o$7701 _o$7702 _o$7703 _o$7704 _o$7705 _o$7706 _o$7707 _o$7708)) (let* ((_o$7709 (keyword #f "private")) (_o$7710 #t)) (jolt-hash-map _o$7709 _o$7710)))) -(guard (e (#t #f)) - (def-var! "jolt.backend-scheme" "prelude-mode?" (jolt-invoke (var-deref "clojure.core" "atom") #f))) -(guard (e (#t #f)) - (def-var! "jolt.backend-scheme" "set-prelude-mode!" (letrec ((set-prelude-mode! (lambda (on) (let fnrec7711 ((on on)) (jolt-invoke (var-deref "clojure.core" "reset!") (var-deref "jolt.backend-scheme" "prelude-mode?") on))))) set-prelude-mode!))) -(guard (e (#t #f)) - (def-var! "jolt.backend-scheme" "direct-link?" (jolt-invoke (var-deref "clojure.core" "atom") #f))) -(guard (e (#t #f)) - (def-var! "jolt.backend-scheme" "set-direct-link!" (letrec ((set-direct-link! (lambda (on) (let fnrec7712 ((on on)) (jolt-invoke (var-deref "clojure.core" "reset!") (var-deref "jolt.backend-scheme" "direct-link?") on))))) set-direct-link!))) -(guard (e (#t #f)) - (def-var! "jolt.backend-scheme" "direct-link-defined" (jolt-invoke (var-deref "clojure.core" "atom") (jolt-hash-set)))) -(guard (e (#t #f)) - (def-var! "jolt.backend-scheme" "direct-link-fns" (jolt-invoke (var-deref "clojure.core" "atom") (jolt-hash-set)))) -(guard (e (#t #f)) - (def-var! "jolt.backend-scheme" "direct-link-reset!" (letrec ((direct-link-reset! (lambda () (let fnrec7713 () (begin (jolt-invoke (var-deref "clojure.core" "reset!") (var-deref "jolt.backend-scheme" "direct-link-defined") (jolt-hash-set)) (jolt-invoke (var-deref "clojure.core" "reset!") (var-deref "jolt.backend-scheme" "direct-link-fns") (jolt-hash-set))))))) direct-link-reset!))) -(guard (e (#t #f)) - (def-var! "jolt.backend-scheme" "var-cache?" (jolt-invoke (var-deref "clojure.core" "atom") #f))) -(guard (e (#t #f)) - (def-var! "jolt.backend-scheme" "set-var-cache!" (letrec ((set-var-cache! (lambda (on) (let fnrec7714 ((on on)) (jolt-invoke (var-deref "clojure.core" "reset!") (var-deref "jolt.backend-scheme" "var-cache?") on))))) set-var-cache!))) -(guard (e (#t #f)) - (def-var! "jolt.backend-scheme" "trace-frames?" (jolt-invoke (var-deref "clojure.core" "atom") #f))) -(guard (e (#t #f)) - (def-var! "jolt.backend-scheme" "set-trace-frames!" (letrec ((set-trace-frames! (lambda (on) (let fnrec7715 ((on on)) (jolt-invoke (var-deref "clojure.core" "reset!") (var-deref "jolt.backend-scheme" "trace-frames?") on))))) set-trace-frames!))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.backend-scheme" "dl-munge" (letrec ((dl-munge (lambda (s) (let fnrec7716 ((s s)) (jolt-invoke (var-deref "clojure.string" "replace") (jolt-invoke (var-deref "clojure.string" "replace") (jolt-invoke (var-deref "clojure.string" "replace") s "$" "_D_") "#" "_H_") "'" "_Q_"))))) dl-munge) (let* ((_o$7717 (keyword #f "private")) (_o$7718 #t)) (jolt-hash-map _o$7717 _o$7718)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.backend-scheme" "dl-name" (letrec ((dl-name (lambda (ns nm) (let fnrec7719 ((ns ns) (nm nm)) (let* ((_a$7720 (var-deref "clojure.core" "str")) (_a$7721 "jv$") (_a$7722 (jolt-invoke (var-deref "jolt.backend-scheme" "dl-munge") ns)) (_a$7723 "$") (_a$7724 (jolt-invoke (var-deref "jolt.backend-scheme" "dl-munge") nm))) (jolt-invoke _a$7720 _a$7721 _a$7722 _a$7723 _a$7724)))))) dl-name) (let* ((_o$7725 (keyword #f "private")) (_o$7726 #t)) (jolt-hash-map _o$7725 _o$7726)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.backend-scheme" "dl-fqn" (letrec ((dl-fqn (lambda (ns nm) (let fnrec7727 ((ns ns) (nm nm)) (jolt-invoke (var-deref "clojure.core" "str") ns "/" nm))))) dl-fqn) (let* ((_o$7728 (keyword #f "private")) (_o$7729 #t)) (jolt-hash-map _o$7728 _o$7729)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.backend-scheme" "direct-linkable?" (letrec ((direct-linkable? (lambda (ns nm) (let fnrec7730 ((ns ns) (nm nm)) (let* ((and__25__auto (jolt-invoke (var-deref "clojure.core" "deref") (var-deref "jolt.backend-scheme" "direct-link?")))) (if (jolt-truthy? and__25__auto) (let* ((_a$7731 (jolt-invoke (var-deref "clojure.core" "deref") (var-deref "jolt.backend-scheme" "direct-link-defined"))) (_a$7732 (jolt-invoke (var-deref "jolt.backend-scheme" "dl-fqn") ns nm))) (jolt-contains? _a$7731 _a$7732)) and__25__auto)))))) direct-linkable?) (let* ((_o$7733 (keyword #f "private")) (_o$7734 #t)) (jolt-hash-map _o$7733 _o$7734)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.backend-scheme" "direct-link-fn?" (letrec ((direct-link-fn? (lambda (ns nm) (let fnrec7735 ((ns ns) (nm nm)) (let* ((_a$7736 (jolt-invoke (var-deref "clojure.core" "deref") (var-deref "jolt.backend-scheme" "direct-link-fns"))) (_a$7737 (jolt-invoke (var-deref "jolt.backend-scheme" "dl-fqn") ns nm))) (jolt-contains? _a$7736 _a$7737)))))) direct-link-fn?) (let* ((_o$7738 (keyword #f "private")) (_o$7739 #t)) (jolt-hash-map _o$7738 _o$7739)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.backend-scheme" "*recur-target*" jolt-nil (let* ((_o$7740 (keyword #f "dynamic")) (_o$7741 #t)) (jolt-hash-map _o$7740 _o$7741)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.backend-scheme" "*known-procs*" (jolt-hash-set) (let* ((_o$7742 (keyword #f "dynamic")) (_o$7743 #t)) (jolt-hash-map _o$7742 _o$7743)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.backend-scheme" "*tail?*" #f (let* ((_o$7744 (keyword #f "dynamic")) (_o$7745 #t)) (jolt-hash-map _o$7744 _o$7745)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.backend-scheme" "gensym-counter" (jolt-invoke (var-deref "clojure.core" "atom") 0) (let* ((_o$7746 (keyword #f "private")) (_o$7747 #t)) (jolt-hash-map _o$7746 _o$7747)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.backend-scheme" "fresh-label" (letrec ((fresh-label (lambda (prefix) (let fnrec7748 ((prefix prefix)) (jolt-invoke (var-deref "clojure.core" "str") prefix (jolt-invoke (var-deref "clojure.core" "swap!") (var-deref "jolt.backend-scheme" "gensym-counter") jolt-inc)))))) fresh-label) (let* ((_o$7749 (keyword #f "private")) (_o$7750 #t)) (jolt-hash-map _o$7749 _o$7750)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.backend-scheme" "cache-cells" (jolt-invoke (var-deref "clojure.core" "atom") jolt-nil) (let* ((_o$7751 (keyword #f "private")) (_o$7752 #t)) (jolt-hash-map _o$7751 _o$7752)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.backend-scheme" "emit-with-cells" (letrec ((emit-with-cells (lambda (emit-thunk) (let fnrec7753 ((emit-thunk emit-thunk)) (let* ((cells (jolt-invoke (var-deref "clojure.core" "atom") (jolt-vector))) (prev (jolt-invoke (var-deref "clojure.core" "deref") (var-deref "jolt.backend-scheme" "cache-cells"))) (_ (jolt-invoke (var-deref "clojure.core" "reset!") (var-deref "jolt.backend-scheme" "cache-cells") cells)) (raw (jolt-invoke emit-thunk)) (_ (jolt-invoke (var-deref "clojure.core" "reset!") (var-deref "jolt.backend-scheme" "cache-cells") prev))) (if (jolt-truthy? (jolt-seq (jolt-invoke (var-deref "clojure.core" "deref") cells))) (jolt-invoke (var-deref "clojure.core" "str") "(let (" (jolt-invoke (var-deref "clojure.string" "join") " " (let* ((_a$7755 (lambda (c) (let fnrec7754 ((c c)) (jolt-invoke (var-deref "clojure.core" "str") "(" c " #f)")))) (_a$7756 (jolt-invoke (var-deref "clojure.core" "deref") cells))) (jolt-map _a$7755 _a$7756))) ") " raw ")") raw)))))) emit-with-cells) (let* ((_o$7757 (keyword #f "private")) (_o$7758 #t)) (jolt-hash-map _o$7757 _o$7758)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.backend-scheme" "scheme-reserved" (let* ((_o$7759 "if") (_o$7760 "begin") (_o$7761 "lambda") (_o$7762 "let") (_o$7763 "let*") (_o$7764 "letrec") (_o$7765 "letrec*") (_o$7766 "quote") (_o$7767 "quasiquote") (_o$7768 "unquote") (_o$7769 "set!") (_o$7770 "define") (_o$7771 "define-syntax") (_o$7772 "cond") (_o$7773 "case") (_o$7774 "when") (_o$7775 "unless") (_o$7776 "and") (_o$7777 "or") (_o$7778 "do") (_o$7779 "else") (_o$7780 "guard") (_o$7781 "parameterize") (_o$7782 "delay") (_o$7783 "values")) (jolt-hash-set _o$7759 _o$7760 _o$7761 _o$7762 _o$7763 _o$7764 _o$7765 _o$7766 _o$7767 _o$7768 _o$7769 _o$7770 _o$7771 _o$7772 _o$7773 _o$7774 _o$7775 _o$7776 _o$7777 _o$7778 _o$7779 _o$7780 _o$7781 _o$7782 _o$7783)) (let* ((_o$7784 (keyword #f "private")) (_o$7785 #t)) (jolt-hash-map _o$7784 _o$7785)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.backend-scheme" "bare-native-names" (jolt-invoke (var-deref "clojure.core" "set") (jolt-invoke (var-deref "clojure.core" "keep") (lambda (G__141) (let fnrec7786 ((G__141 G__141)) (let* ((G__142 G__141) (k (jolt-nth G__142 0 jolt-nil)) (v (jolt-nth G__142 1 jolt-nil))) (if (jolt= k v) k jolt-nil)))) (var-deref "jolt.backend-scheme" "native-ops"))) (let* ((_o$7787 (keyword #f "private")) (_o$7788 #t)) (jolt-hash-map _o$7787 _o$7788)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.backend-scheme" "munge-name" (letrec ((munge-name (lambda (s) (let fnrec7789 ((s s)) (let* ((s (jolt-invoke (var-deref "clojure.string" "replace") (jolt-invoke (var-deref "clojure.string" "replace") s "#" "_") "'" "_PRIME_"))) (if (let* ((or__26__auto (jolt-contains? (var-deref "jolt.backend-scheme" "scheme-reserved") s))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-contains? (var-deref "jolt.backend-scheme" "bare-native-names") s))) (jolt-invoke (var-deref "clojure.core" "str") "_" s) s)))))) munge-name) (let* ((_o$7790 (keyword #f "private")) (_o$7791 #t)) (jolt-hash-map _o$7790 _o$7791)))) -(guard (e (#t #f)) - (declare-var! "jolt.backend-scheme" "emit")) -(guard (e (#t #f)) - (declare-var! "jolt.backend-scheme" "emit*")) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.backend-scheme" "tail-transparent-ops" (let* ((_o$7792 (keyword #f "if")) (_o$7793 (keyword #f "do")) (_o$7794 (keyword #f "let")) (_o$7795 (keyword #f "loop")) (_o$7796 (keyword #f "invoke"))) (jolt-hash-set _o$7792 _o$7793 _o$7794 _o$7795 _o$7796)) (let* ((_o$7797 (keyword #f "private")) (_o$7798 #t)) (jolt-hash-map _o$7797 _o$7798)))) -(guard (e (#t #f)) - (def-var! "jolt.backend-scheme" "emit" (letrec ((emit (lambda (node) (let fnrec7799 ((node node)) (if (jolt-truthy? (let* ((and__25__auto (var-deref "jolt.backend-scheme" "*tail?*"))) (if (jolt-truthy? and__25__auto) (jolt-not (jolt-invoke (var-deref "jolt.backend-scheme" "tail-transparent-ops") (jolt-get node (keyword #f "op")))) and__25__auto))) (let* ((frame__20__auto (jolt-invoke (var-deref "clojure.core" "array-map") (jolt-var "jolt.backend-scheme" "*tail?*") #f))) (begin (jolt-invoke (var-deref "clojure.core" "push-thread-bindings") frame__20__auto) (dynamic-wind (lambda () #f) (lambda () (jolt-invoke (var-deref "jolt.backend-scheme" "emit*") node)) (lambda () (jolt-invoke (var-deref "clojure.core" "pop-thread-bindings")))))) (jolt-invoke (var-deref "jolt.backend-scheme" "emit*") node)))))) emit))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.backend-scheme" "char-escape" (letrec ((char-escape (lambda (cp) (let fnrec7800 ((cp cp)) (if (jolt= cp 34) "\\\"" (if (jolt= cp 92) "\\\\" (if (jolt= cp 10) "\\n" (if (jolt= cp 9) "\\t" (if (jolt= cp 13) "\\r" (if (let* ((and__25__auto (jolt-n>= cp 32))) (if (jolt-truthy? and__25__auto) (jolt-n< cp 127) and__25__auto)) (jolt-invoke (var-deref "clojure.core" "str") (jolt-invoke (var-deref "clojure.core" "char") cp)) (if (jolt-truthy? (keyword #f "else")) (jolt-invoke (var-deref "clojure.core" "str") "\\x" (jolt-invoke (var-deref "clojure.core" "format") "%x" cp) ";") jolt-nil))))))))))) char-escape) (let* ((_o$7801 (keyword #f "private")) (_o$7802 #t)) (jolt-hash-map _o$7801 _o$7802)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.backend-scheme" "chez-str-lit" (letrec ((chez-str-lit (lambda (s) (let fnrec7803 ((s s)) (jolt-invoke (var-deref "clojure.core" "str") "\"" (jolt-apply (var-deref "clojure.core" "str") (jolt-map (lambda (c) (let fnrec7804 ((c c)) (jolt-invoke (var-deref "jolt.backend-scheme" "char-escape") (jolt-invoke (var-deref "clojure.core" "int") c)))) s)) "\""))))) chez-str-lit) (let* ((_o$7805 (keyword #f "private")) (_o$7806 #t)) (jolt-hash-map _o$7805 _o$7806)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.backend-scheme" "emit-const" (letrec ((emit-const (lambda (v) (let fnrec7807 ((v v)) (if (jolt-nil? v) "jolt-nil" (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "boolean?") v)) (if (jolt-truthy? v) "#t" "#f") (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "number?") v)) (if (jolt= v +inf.0) "+inf.0" (if (jolt= v -inf.0) "-inf.0" (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "not=") v v)) "+nan.0" (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "float?") v)) (let* ((s (jolt-invoke (var-deref "clojure.core" "str") v))) (if (jolt-truthy? (let* ((or__26__auto (jolt-invoke (var-deref "clojure.string" "includes?") s "."))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-invoke (var-deref "clojure.string" "includes?") s "e")))) s (jolt-invoke (var-deref "clojure.core" "str") s ".0"))) (if (jolt-truthy? (keyword #f "else")) (jolt-invoke (var-deref "clojure.core" "str") v) jolt-nil))))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "string?") v)) (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") v) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "keyword?") v)) (let* ((temp__16__auto (jolt-invoke (var-deref "clojure.core" "namespace") v))) (if (jolt-truthy? temp__16__auto) (let* ((kns temp__16__auto)) (let* ((_a$7808 (var-deref "clojure.core" "str")) (_a$7809 "(keyword ") (_a$7810 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") kns)) (_a$7811 " ") (_a$7812 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-invoke (var-deref "clojure.core" "name") v))) (_a$7813 ")")) (jolt-invoke _a$7808 _a$7809 _a$7810 _a$7811 _a$7812 _a$7813))) (jolt-invoke (var-deref "clojure.core" "str") "(keyword #f " (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-invoke (var-deref "clojure.core" "name") v)) ")"))) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "form-char?") v)) (jolt-invoke (var-deref "clojure.core" "str") "(integer->char " (jolt-invoke (var-deref "jolt.host" "form-char-code") v) ")") (if (jolt-truthy? (keyword #f "else")) (jolt-throw (let* ((_a$7814 (jolt-invoke (var-deref "clojure.core" "str") "emit-const: unsupported literal " (jolt-invoke (var-deref "clojure.core" "pr-str") v))) (_a$7815 (jolt-hash-map))) (jolt-ex-info _a$7814 _a$7815))) jolt-nil))))))))))) emit-const) (let* ((_o$7816 (keyword #f "private")) (_o$7817 #t)) (jolt-hash-map _o$7816 _o$7817)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.backend-scheme" "emit-ordered" (letrec ((emit-ordered (lambda (ctor arg-strs) (let fnrec7818 ((ctor ctor) (arg-strs arg-strs)) (if (jolt-n< (jolt-count arg-strs) 2) (jolt-invoke (var-deref "clojure.core" "str") "(" ctor (if (jolt-empty? arg-strs) "" (jolt-invoke (var-deref "clojure.core" "str") " " (jolt-invoke (var-deref "clojure.string" "join") " " arg-strs))) ")") (let* ((tmps (jolt-map (lambda (_) (let fnrec7819 ((_ _)) (jolt-invoke (var-deref "jolt.backend-scheme" "fresh-label") "_o$"))) arg-strs)) (binds (jolt-invoke (var-deref "clojure.string" "join") " " (jolt-map (lambda (t a) (let fnrec7820 ((t t) (a a)) (jolt-invoke (var-deref "clojure.core" "str") "(" t " " a ")"))) tmps arg-strs)))) (jolt-invoke (var-deref "clojure.core" "str") "(let* (" binds ") (" ctor " " (jolt-invoke (var-deref "clojure.string" "join") " " tmps) "))"))))))) emit-ordered) (let* ((_o$7821 (keyword #f "private")) (_o$7822 #t)) (jolt-hash-map _o$7821 _o$7822)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.backend-scheme" "side-effect-free?" (letrec ((side-effect-free? (lambda (n) (let fnrec7823 ((n n)) (let* ((_a$7829 (let* ((_o$7824 (keyword #f "const")) (_o$7825 (keyword #f "local")) (_o$7826 (keyword #f "var")) (_o$7827 (keyword #f "the-var")) (_o$7828 (keyword #f "quote"))) (jolt-hash-set _o$7824 _o$7825 _o$7826 _o$7827 _o$7828))) (_a$7830 (jolt-get n (keyword #f "op")))) (jolt-contains? _a$7829 _a$7830)))))) side-effect-free?) (let* ((_o$7831 (keyword #f "private")) (_o$7832 #t)) (jolt-hash-map _o$7831 _o$7832)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.backend-scheme" "needs-order?" (letrec ((needs-order? (lambda (nodes) (let fnrec7833 ((nodes nodes)) (jolt-n> (jolt-count (jolt-remove (var-deref "jolt.backend-scheme" "side-effect-free?") nodes)) 1))))) needs-order?) (let* ((_o$7834 (keyword #f "private")) (_o$7835 #t)) (jolt-hash-map _o$7834 _o$7835)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.backend-scheme" "ordered-call" (letrec ((ordered-call (lambda (nodes strs build) (let fnrec7836 ((nodes nodes) (strs strs) (build build)) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.backend-scheme" "needs-order?") nodes)) (let* ((tmps (jolt-invoke (var-deref "clojure.core" "mapv") (lambda (_) (let fnrec7837 ((_ _)) (jolt-invoke (var-deref "jolt.backend-scheme" "fresh-label") "_a$"))) strs)) (binds (jolt-invoke (var-deref "clojure.string" "join") " " (jolt-map (lambda (t a) (let fnrec7838 ((t t) (a a)) (jolt-invoke (var-deref "clojure.core" "str") "(" t " " a ")"))) tmps strs)))) (jolt-invoke (var-deref "clojure.core" "str") "(let* (" binds ") " (jolt-invoke build tmps) ")")) (jolt-invoke build strs)))))) ordered-call) (let* ((_o$7839 (keyword #f "private")) (_o$7840 #t)) (jolt-hash-map _o$7839 _o$7840)))) -(guard (e (#t #f)) - (declare-var! "jolt.backend-scheme" "emit-quoted")) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.backend-scheme" "emit-quoted-map" (letrec ((emit-quoted-map (lambda (pairs) (let fnrec7841 ((pairs pairs)) (jolt-invoke (var-deref "clojure.core" "str") "(jolt-hash-map " (jolt-invoke (var-deref "clojure.string" "join") " " (jolt-invoke (var-deref "clojure.core" "mapcat") (lambda (p) (let fnrec7842 ((p p)) (let* ((_o$7843 (jolt-invoke (var-deref "jolt.backend-scheme" "emit-quoted") (jolt-nth p 0))) (_o$7844 (jolt-invoke (var-deref "jolt.backend-scheme" "emit-quoted") (jolt-nth p 1)))) (jolt-vector _o$7843 _o$7844)))) pairs)) ")"))))) emit-quoted-map) (let* ((_o$7845 (keyword #f "private")) (_o$7846 #t)) (jolt-hash-map _o$7845 _o$7846)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.backend-scheme" "emit-quoted-map-value" (letrec ((emit-quoted-map-value (lambda (m) (let fnrec7847 ((m m)) (let* ((pairs (jolt-invoke (var-deref "clojure.core" "sort") (let* ((_a$7853 (lambda (k) (let fnrec7848 ((k k)) (let* ((_a$7849 (var-deref "clojure.core" "str")) (_a$7850 (jolt-invoke (var-deref "jolt.backend-scheme" "emit-quoted") k)) (_a$7851 " ") (_a$7852 (jolt-invoke (var-deref "jolt.backend-scheme" "emit-quoted") (jolt-get m k)))) (jolt-invoke _a$7849 _a$7850 _a$7851 _a$7852))))) (_a$7854 (jolt-keys m))) (jolt-map _a$7853 _a$7854))))) (jolt-invoke (var-deref "clojure.core" "str") "(jolt-hash-map " (jolt-invoke (var-deref "clojure.string" "join") " " pairs) ")")))))) emit-quoted-map-value) (let* ((_o$7855 (keyword #f "private")) (_o$7856 #t)) (jolt-hash-map _o$7855 _o$7856)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.backend-scheme" "emit-quoted" (letrec ((emit-quoted (lambda (form) (let fnrec7857 ((form form)) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "form-char?") form)) (jolt-invoke (var-deref "jolt.backend-scheme" "emit-const") form) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "form-literal?") form)) (jolt-invoke (var-deref "jolt.backend-scheme" "emit-const") form) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "form-sym?") form)) (let* ((m (jolt-invoke (var-deref "jolt.host" "form-sym-meta") form)) (sns (jolt-invoke (var-deref "jolt.host" "form-sym-ns") form)) (nm (jolt-invoke (var-deref "jolt.host" "form-sym-name") form))) (if (jolt-truthy? (let* ((and__25__auto m)) (if (jolt-truthy? and__25__auto) (jolt-pos? (jolt-count m)) and__25__auto))) (let* ((_a$7858 (var-deref "clojure.core" "str")) (_a$7859 "(jolt-symbol/meta ") (_a$7860 (if (jolt-truthy? sns) (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") sns) "#f")) (_a$7861 " ") (_a$7862 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") nm)) (_a$7863 " ") (_a$7864 (emit-quoted m)) (_a$7865 ")")) (jolt-invoke _a$7858 _a$7859 _a$7860 _a$7861 _a$7862 _a$7863 _a$7864 _a$7865)) (let* ((_a$7866 (var-deref "clojure.core" "str")) (_a$7867 "(jolt-symbol ") (_a$7868 (if (jolt-truthy? sns) (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") sns) "#f")) (_a$7869 " ") (_a$7870 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") nm)) (_a$7871 ")")) (jolt-invoke _a$7866 _a$7867 _a$7868 _a$7869 _a$7870 _a$7871)))) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "form-set?") form)) (jolt-invoke (var-deref "clojure.core" "str") "(jolt-hash-set " (jolt-invoke (var-deref "clojure.string" "join") " " (jolt-invoke (var-deref "clojure.core" "sort") (jolt-map emit-quoted (jolt-invoke (var-deref "jolt.host" "form-set-items") form)))) ")") (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "form-list?") form)) (jolt-invoke (var-deref "clojure.core" "str") "(jolt-list " (jolt-invoke (var-deref "clojure.string" "join") " " (jolt-map emit-quoted (jolt-invoke (var-deref "jolt.host" "form-elements") form))) ")") (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "form-vec?") form)) (jolt-invoke (var-deref "clojure.core" "str") "(jolt-vector " (jolt-invoke (var-deref "clojure.string" "join") " " (jolt-map emit-quoted (jolt-invoke (var-deref "jolt.host" "form-vec-items") form))) ")") (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "form-map?") form)) (jolt-invoke (var-deref "jolt.backend-scheme" "emit-quoted-map") (jolt-invoke (var-deref "jolt.host" "form-map-pairs") form)) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "form-regex?") form)) (jolt-invoke (var-deref "clojure.core" "str") "(jolt-regex " (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-invoke (var-deref "jolt.host" "form-regex-source") form)) ")") (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "form-inst?") form)) (jolt-invoke (var-deref "clojure.core" "str") "(jolt-inst-from-string " (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-invoke (var-deref "jolt.host" "form-inst-source") form)) ")") (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "form-uuid?") form)) (jolt-invoke (var-deref "clojure.core" "str") "(jolt-uuid-from-string " (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-invoke (var-deref "jolt.host" "form-uuid-source") form)) ")") (if (jolt-truthy? (let* ((and__25__auto (jolt-invoke (var-deref "clojure.core" "map?") form))) (if (jolt-truthy? and__25__auto) (jolt= (keyword "jolt" "tagged") (jolt-get form (keyword "jolt" "type"))) and__25__auto))) (let* ((nm (jolt-invoke (var-deref "clojure.core" "name") (jolt-get form (keyword #f "tag")))) (tsym (if (jolt= (integer->char 35) (jolt-first nm)) (jolt-invoke (var-deref "clojure.core" "subs") nm 1) nm))) (let* ((_a$7872 (var-deref "clojure.core" "str")) (_a$7873 "(jolt-tagged-literal (jolt-symbol #f ") (_a$7874 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") tsym)) (_a$7875 ") ") (_a$7876 (emit-quoted (jolt-get form (keyword #f "form")))) (_a$7877 ")")) (jolt-invoke _a$7872 _a$7873 _a$7874 _a$7875 _a$7876 _a$7877))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "map?") form)) (jolt-invoke (var-deref "jolt.backend-scheme" "emit-quoted-map-value") form) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "vector?") form)) (jolt-invoke (var-deref "clojure.core" "str") "(jolt-vector " (jolt-invoke (var-deref "clojure.string" "join") " " (jolt-map emit-quoted form)) ")") (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "set?") form)) (jolt-invoke (var-deref "clojure.core" "str") "(jolt-hash-set " (jolt-invoke (var-deref "clojure.string" "join") " " (jolt-invoke (var-deref "clojure.core" "sort") (jolt-map emit-quoted form))) ")") (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "seq?") form)) (jolt-invoke (var-deref "clojure.core" "str") "(jolt-list " (jolt-invoke (var-deref "clojure.string" "join") " " (jolt-map emit-quoted form)) ")") (if (jolt-truthy? (keyword #f "else")) (jolt-throw (let* ((_a$7878 (jolt-invoke (var-deref "clojure.core" "str") "emit-quoted: unsupported quoted form " (jolt-invoke (var-deref "clojure.core" "pr-str") form))) (_a$7879 (jolt-hash-map))) (jolt-ex-info _a$7878 _a$7879))) jolt-nil)))))))))))))))))))) emit-quoted) (let* ((_o$7880 (keyword #f "private")) (_o$7881 #t)) (jolt-hash-map _o$7880 _o$7881)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.backend-scheme" "jmeta-nonempty?" (letrec ((jmeta-nonempty? (lambda (m) (let fnrec7882 ((m m)) (let* ((and__25__auto (jolt-invoke (var-deref "clojure.core" "map?") m))) (if (jolt-truthy? and__25__auto) (jolt-pos? (jolt-count m)) and__25__auto)))))) jmeta-nonempty?) (let* ((_o$7883 (keyword #f "private")) (_o$7884 #t)) (jolt-hash-map _o$7883 _o$7884)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.backend-scheme" "emit-def-meta" (letrec ((emit-def-meta (lambda (node) (let fnrec7885 ((node node)) (if (jolt-truthy? (jolt-get node (keyword #f "meta-expr"))) (jolt-invoke (var-deref "jolt.backend-scheme" "emit") (jolt-get node (keyword #f "meta-expr"))) (jolt-invoke (var-deref "jolt.backend-scheme" "emit-quoted") (jolt-get node (keyword #f "meta")))))))) emit-def-meta) (let* ((_o$7886 (keyword #f "private")) (_o$7887 #t)) (jolt-hash-map _o$7886 _o$7887)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.backend-scheme" "emit-binding" (letrec ((emit-binding (lambda (b) (let fnrec7888 ((b b)) (let* ((_a$7889 (var-deref "clojure.core" "str")) (_a$7890 "(") (_a$7891 (jolt-invoke (var-deref "jolt.backend-scheme" "munge-name") (jolt-nth b 0))) (_a$7892 " ") (_a$7893 (jolt-invoke (var-deref "jolt.backend-scheme" "emit") (jolt-nth b 1))) (_a$7894 ")")) (jolt-invoke _a$7889 _a$7890 _a$7891 _a$7892 _a$7893 _a$7894)))))) emit-binding) (let* ((_o$7895 (keyword #f "private")) (_o$7896 #t)) (jolt-hash-map _o$7895 _o$7896)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.backend-scheme" "emit-let" (letrec ((emit-let (lambda (node) (let fnrec7897 ((node node)) (let* ((kw (if (jolt-truthy? (jolt-get node (keyword #f "letrec"))) "letrec*" "let*")) (binds (let* ((frame__20__auto (jolt-invoke (var-deref "clojure.core" "array-map") (jolt-var "jolt.backend-scheme" "*tail?*") #f))) (begin (jolt-invoke (var-deref "clojure.core" "push-thread-bindings") frame__20__auto) (dynamic-wind (lambda () #f) (lambda () (jolt-invoke (var-deref "clojure.string" "join") " " (jolt-invoke (var-deref "clojure.core" "mapv") (var-deref "jolt.backend-scheme" "emit-binding") (jolt-get node (keyword #f "bindings"))))) (lambda () (jolt-invoke (var-deref "clojure.core" "pop-thread-bindings")))))))) (jolt-invoke (var-deref "clojure.core" "str") "(" kw " (" binds ") " (jolt-invoke (var-deref "jolt.backend-scheme" "emit") (jolt-get node (keyword #f "body"))) ")")))))) emit-let) (let* ((_o$7898 (keyword #f "private")) (_o$7899 #t)) (jolt-hash-map _o$7898 _o$7899)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.backend-scheme" "emit-loop" (letrec ((emit-loop (lambda (node) (let fnrec7900 ((node node)) (let* ((label (jolt-invoke (var-deref "jolt.backend-scheme" "fresh-label") "loop")) (pairs (jolt-get node (keyword #f "bindings"))) (names (jolt-map (lambda (p__95_) (let fnrec7901 ((p__95_ p__95_)) (jolt-invoke (var-deref "jolt.backend-scheme" "munge-name") (jolt-nth p__95_ 0)))) pairs)) (inits (let* ((frame__20__auto (jolt-invoke (var-deref "clojure.core" "array-map") (jolt-var "jolt.backend-scheme" "*tail?*") #f))) (begin (jolt-invoke (var-deref "clojure.core" "push-thread-bindings") frame__20__auto) (dynamic-wind (lambda () #f) (lambda () (jolt-invoke (var-deref "clojure.core" "mapv") (lambda (p__96_) (let fnrec7902 ((p__96_ p__96_)) (jolt-invoke (var-deref "jolt.backend-scheme" "emit") (jolt-nth p__96_ 1)))) pairs)) (lambda () (jolt-invoke (var-deref "clojure.core" "pop-thread-bindings"))))))) (seq-bs (jolt-invoke (var-deref "clojure.string" "join") " " (jolt-map (lambda (n i) (let fnrec7903 ((n n) (i i)) (jolt-invoke (var-deref "clojure.core" "str") "(" n " " i ")"))) names inits))) (rebinds (jolt-invoke (var-deref "clojure.string" "join") " " (jolt-map (lambda (n) (let fnrec7904 ((n n)) (jolt-invoke (var-deref "clojure.core" "str") "(" n " " n ")"))) names))) (body (let* ((frame__20__auto (jolt-invoke (var-deref "clojure.core" "array-map") (jolt-var "jolt.backend-scheme" "*recur-target*") label))) (begin (jolt-invoke (var-deref "clojure.core" "push-thread-bindings") frame__20__auto) (dynamic-wind (lambda () #f) (lambda () (jolt-invoke (var-deref "jolt.backend-scheme" "emit") (jolt-get node (keyword #f "body")))) (lambda () (jolt-invoke (var-deref "clojure.core" "pop-thread-bindings")))))))) (jolt-invoke (var-deref "clojure.core" "str") "(let* (" seq-bs ") (let " label " (" rebinds ") " body "))")))))) emit-loop) (let* ((_o$7905 (keyword #f "private")) (_o$7906 #t)) (jolt-hash-map _o$7905 _o$7906)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.backend-scheme" "ffi-types" (let* ((_o$7907 "int") (_o$7908 "int") (_o$7909 "uint") (_o$7910 "unsigned-int") (_o$7911 "long") (_o$7912 "long") (_o$7913 "ulong") (_o$7914 "unsigned-long") (_o$7915 "int64") (_o$7916 "integer-64") (_o$7917 "uint64") (_o$7918 "unsigned-64") (_o$7919 "size_t") (_o$7920 "size_t") (_o$7921 "ssize_t") (_o$7922 "ssize_t") (_o$7923 "iptr") (_o$7924 "iptr") (_o$7925 "uptr") (_o$7926 "uptr") (_o$7927 "double") (_o$7928 "double") (_o$7929 "float") (_o$7930 "float") (_o$7931 "pointer") (_o$7932 "void*") (_o$7933 "void*") (_o$7934 "void*") (_o$7935 "string") (_o$7936 "string") (_o$7937 "void") (_o$7938 "void") (_o$7939 "uint8") (_o$7940 "unsigned-8") (_o$7941 "u8") (_o$7942 "unsigned-8") (_o$7943 "byte") (_o$7944 "unsigned-8") (_o$7945 "char") (_o$7946 "char")) (jolt-hash-map _o$7907 _o$7908 _o$7909 _o$7910 _o$7911 _o$7912 _o$7913 _o$7914 _o$7915 _o$7916 _o$7917 _o$7918 _o$7919 _o$7920 _o$7921 _o$7922 _o$7923 _o$7924 _o$7925 _o$7926 _o$7927 _o$7928 _o$7929 _o$7930 _o$7931 _o$7932 _o$7933 _o$7934 _o$7935 _o$7936 _o$7937 _o$7938 _o$7939 _o$7940 _o$7941 _o$7942 _o$7943 _o$7944 _o$7945 _o$7946)) (let* ((_o$7947 (keyword #f "private")) (_o$7948 #t)) (jolt-hash-map _o$7947 _o$7948)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.backend-scheme" "ffi-type->chez" (letrec ((ffi-type->chez (lambda (t) (let fnrec7949 ((t t)) (let* ((or__26__auto (jolt-invoke (var-deref "jolt.backend-scheme" "ffi-types") t))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-throw (let* ((_a$7950 (jolt-invoke (var-deref "clojure.core" "str") "jolt.ffi: unknown foreign type :" t)) (_a$7951 (jolt-hash-map))) (jolt-ex-info _a$7950 _a$7951))))))))) ffi-type->chez) (let* ((_o$7952 (keyword #f "private")) (_o$7953 #t)) (jolt-hash-map _o$7952 _o$7953)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.backend-scheme" "emit-ffi-fn" (letrec ((emit-ffi-fn (lambda (node) (let fnrec7954 ((node node)) (let* ((_a$7955 (var-deref "clojure.core" "str")) (_a$7956 "(foreign-procedure ") (_a$7957 (if (jolt-truthy? (jolt-get node (keyword #f "blocking"))) "__collect_safe " jolt-nil)) (_a$7958 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-get node (keyword #f "csym")))) (_a$7959 " (") (_a$7960 (jolt-invoke (var-deref "clojure.string" "join") " " (jolt-map (var-deref "jolt.backend-scheme" "ffi-type->chez") (jolt-get node (keyword #f "argtypes"))))) (_a$7961 ") ") (_a$7962 (jolt-invoke (var-deref "jolt.backend-scheme" "ffi-type->chez") (jolt-get node (keyword #f "rettype")))) (_a$7963 ")")) (jolt-invoke _a$7955 _a$7956 _a$7957 _a$7958 _a$7959 _a$7960 _a$7961 _a$7962 _a$7963)))))) emit-ffi-fn) (let* ((_o$7964 (keyword #f "private")) (_o$7965 #t)) (jolt-hash-map _o$7964 _o$7965)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.backend-scheme" "emit-ffi-callable" (letrec ((emit-ffi-callable (lambda (node) (let fnrec7966 ((node node)) (let* ((_a$7967 (var-deref "clojure.core" "str")) (_a$7968 "(jolt-ffi-register-callable! (foreign-callable ") (_a$7969 (if (jolt-truthy? (jolt-get node (keyword #f "collect-safe"))) "__collect_safe " jolt-nil)) (_a$7970 (jolt-invoke (var-deref "jolt.backend-scheme" "emit") (jolt-get node (keyword #f "fn")))) (_a$7971 " (") (_a$7972 (jolt-invoke (var-deref "clojure.string" "join") " " (jolt-map (var-deref "jolt.backend-scheme" "ffi-type->chez") (jolt-get node (keyword #f "argtypes"))))) (_a$7973 ") ") (_a$7974 (jolt-invoke (var-deref "jolt.backend-scheme" "ffi-type->chez") (jolt-get node (keyword #f "rettype")))) (_a$7975 "))")) (jolt-invoke _a$7967 _a$7968 _a$7969 _a$7970 _a$7971 _a$7972 _a$7973 _a$7974 _a$7975)))))) emit-ffi-callable) (let* ((_o$7976 (keyword #f "private")) (_o$7977 #t)) (jolt-hash-map _o$7976 _o$7977)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.backend-scheme" "emit-recur" (letrec ((emit-recur (lambda (node) (let fnrec7978 ((node node)) (begin (if (jolt-not (var-deref "jolt.backend-scheme" "*recur-target*")) (jolt-throw (jolt-ex-info "emit: recur outside a loop/fn target" (jolt-hash-map))) jolt-nil) (let* ((arg-nodes (jolt-get node (keyword #f "args")))) (let* ((_a$7980 (var-deref "jolt.backend-scheme" "ordered-call")) (_a$7981 arg-nodes) (_a$7982 (jolt-invoke (var-deref "clojure.core" "mapv") (var-deref "jolt.backend-scheme" "emit") arg-nodes)) (_a$7983 (lambda (as) (let fnrec7979 ((as as)) (jolt-invoke (var-deref "clojure.core" "str") "(" (var-deref "jolt.backend-scheme" "*recur-target*") " " (jolt-invoke (var-deref "clojure.string" "join") " " as) ")"))))) (jolt-invoke _a$7980 _a$7981 _a$7982 _a$7983)))))))) emit-recur) (let* ((_o$7984 (keyword #f "private")) (_o$7985 #t)) (jolt-hash-map _o$7984 _o$7985)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.backend-scheme" "nhint-init" (letrec ((nhint-init (lambda (nh orig munged) (let fnrec7986 ((nh nh) (orig orig) (munged munged)) (let* ((k (jolt-get nh orig))) (if (jolt= k (keyword #f "double")) (jolt-invoke (var-deref "clojure.core" "str") "(exact->inexact " munged ")") (if (jolt= k (keyword #f "long")) (jolt-invoke (var-deref "clojure.core" "str") "(jolt->fx " munged ")") (if (jolt-truthy? (keyword #f "else")) munged jolt-nil)))))))) nhint-init) (let* ((_o$7987 (keyword #f "private")) (_o$7988 #t)) (jolt-hash-map _o$7987 _o$7988)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.backend-scheme" "emit-arity-clause" (letrec ((emit-arity-clause (lambda (a) (let fnrec7989 ((a a)) (let* ((orig (jolt-get a (keyword #f "params"))) (nh (let* ((_a$7990 (jolt-hash-map)) (_a$7991 (jolt-get a (keyword #f "nhints")))) (jolt-into _a$7990 _a$7991))) (params (jolt-map (var-deref "jolt.backend-scheme" "munge-name") orig)) (restp (let* ((temp__27__auto (jolt-get a (keyword #f "rest")))) (if (jolt-truthy? temp__27__auto) (let* ((r temp__27__auto)) (jolt-invoke (var-deref "jolt.backend-scheme" "munge-name") r)) jolt-nil))) (label (jolt-invoke (var-deref "jolt.backend-scheme" "fresh-label") "fnrec")) (ret (jolt-get a (keyword #f "ret-nhint"))) (body-tail? (jolt-not (let* ((or__26__auto (jolt= ret (keyword #f "double")))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt= ret (keyword #f "long")))))) (body (let* ((frame__20__auto (jolt-invoke (var-deref "clojure.core" "array-map") (jolt-var "jolt.backend-scheme" "*recur-target*") label (jolt-var "jolt.backend-scheme" "*tail?*") body-tail?))) (begin (jolt-invoke (var-deref "clojure.core" "push-thread-bindings") frame__20__auto) (dynamic-wind (lambda () #f) (lambda () (jolt-invoke (var-deref "jolt.backend-scheme" "emit") (jolt-get a (keyword #f "body")))) (lambda () (jolt-invoke (var-deref "clojure.core" "pop-thread-bindings"))))))) (paramlist (if (jolt-truthy? (let* ((and__25__auto restp)) (if (jolt-truthy? and__25__auto) (jolt-empty? params) and__25__auto))) restp (if (jolt-truthy? restp) (jolt-invoke (var-deref "clojure.core" "str") "(" (jolt-invoke (var-deref "clojure.string" "join") " " params) " . " restp ")") (if (jolt-truthy? (keyword #f "else")) (jolt-invoke (var-deref "clojure.core" "str") "(" (jolt-invoke (var-deref "clojure.string" "join") " " params) ")") jolt-nil)))) (pbind (jolt-map (lambda (o p) (let fnrec7992 ((o o) (p p)) (jolt-invoke (var-deref "clojure.core" "str") "(" p " " (jolt-invoke (var-deref "jolt.backend-scheme" "nhint-init") nh o p) ")"))) orig params)) (binds (if (jolt-truthy? restp) (jolt-concat pbind (jolt-vector (jolt-invoke (var-deref "clojure.core" "str") "(" restp " (list->cseq " restp "))"))) pbind)) (lett (jolt-invoke (var-deref "clojure.core" "str") "(let " label " (" (jolt-invoke (var-deref "clojure.string" "join") " " binds) ") " body ")")) (ret (jolt-get a (keyword #f "ret-nhint")))) (let* ((_o$7993 paramlist) (_o$7994 (if (jolt= ret (keyword #f "double")) (jolt-invoke (var-deref "clojure.core" "str") "(exact->inexact " lett ")") (if (jolt= ret (keyword #f "long")) (jolt-invoke (var-deref "clojure.core" "str") "(jolt->fx " lett ")") (if (jolt-truthy? (keyword #f "else")) lett jolt-nil))))) (jolt-vector _o$7993 _o$7994))))))) emit-arity-clause) (let* ((_o$7995 (keyword #f "private")) (_o$7996 #t)) (jolt-hash-map _o$7995 _o$7996)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.backend-scheme" "emit-fn" (letrec ((emit-fn (lambda (node) (let fnrec7997 ((node node)) (let* ((arities (jolt-get node (keyword #f "arities"))) (self (let* ((temp__27__auto (jolt-get node (keyword #f "name")))) (if (jolt-truthy? temp__27__auto) (let* ((nm temp__27__auto)) (jolt-invoke (var-deref "jolt.backend-scheme" "munge-name") nm)) jolt-nil))) (clauses (let* ((frame__20__auto (jolt-invoke (var-deref "clojure.core" "array-map") (jolt-var "jolt.backend-scheme" "*known-procs*") (if (jolt-truthy? self) (jolt-conj (var-deref "jolt.backend-scheme" "*known-procs*") self) (var-deref "jolt.backend-scheme" "*known-procs*"))))) (begin (jolt-invoke (var-deref "clojure.core" "push-thread-bindings") frame__20__auto) (dynamic-wind (lambda () #f) (lambda () (jolt-invoke (var-deref "clojure.core" "mapv") (var-deref "jolt.backend-scheme" "emit-arity-clause") arities)) (lambda () (jolt-invoke (var-deref "clojure.core" "pop-thread-bindings"))))))) (clauses (if (jolt-truthy? (let* ((and__25__auto (jolt-invoke (var-deref "clojure.core" "deref") (var-deref "jolt.backend-scheme" "trace-frames?")))) (if (jolt-truthy? and__25__auto) self and__25__auto))) (jolt-invoke (var-deref "clojure.core" "mapv") (lambda (c) (let fnrec7998 ((c c)) (let* ((_o$8005 (jolt-nth c 0)) (_o$8006 (let* ((_a$7999 (var-deref "clojure.core" "str")) (_a$8000 "(begin (jolt-trace-push! ") (_a$8001 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") self)) (_a$8002 ") ") (_a$8003 (jolt-nth c 1)) (_a$8004 ")")) (jolt-invoke _a$7999 _a$8000 _a$8001 _a$8002 _a$8003 _a$8004)))) (jolt-vector _o$8005 _o$8006)))) clauses) clauses)) (_lambda (if (jolt= 1 (jolt-count clauses)) (let* ((c (jolt-first clauses))) (let* ((_a$8007 (var-deref "clojure.core" "str")) (_a$8008 "(lambda ") (_a$8009 (jolt-nth c 0)) (_a$8010 " ") (_a$8011 (jolt-nth c 1)) (_a$8012 ")")) (jolt-invoke _a$8007 _a$8008 _a$8009 _a$8010 _a$8011 _a$8012))) (jolt-invoke (var-deref "clojure.core" "str") "(case-lambda " (jolt-invoke (var-deref "clojure.string" "join") " " (jolt-map (lambda (c) (let fnrec8013 ((c c)) (let* ((_a$8014 (var-deref "clojure.core" "str")) (_a$8015 "(") (_a$8016 (jolt-nth c 0)) (_a$8017 " ") (_a$8018 (jolt-nth c 1)) (_a$8019 ")")) (jolt-invoke _a$8014 _a$8015 _a$8016 _a$8017 _a$8018 _a$8019)))) clauses)) ")")))) (let* ((temp__16__auto (jolt-get node (keyword #f "name")))) (if (jolt-truthy? temp__16__auto) (let* ((nm temp__16__auto)) (let* ((m (jolt-invoke (var-deref "jolt.backend-scheme" "munge-name") nm))) (jolt-invoke (var-deref "clojure.core" "str") "(letrec ((" m " " _lambda ")) " m ")"))) _lambda))))))) emit-fn) (let* ((_o$8020 (keyword #f "private")) (_o$8021 #t)) (jolt-hash-map _o$8020 _o$8021)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.backend-scheme" "native-op" (letrec ((native-op (lambda (fnode nargs) (let fnrec8022 ((fnode fnode) (nargs nargs)) (let* ((nm (let* ((G__143 (jolt-get fnode (keyword #f "op")))) (if (jolt= G__143 (keyword #f "var")) (if (jolt= "clojure.core" (jolt-get fnode (keyword #f "ns"))) (jolt-get fnode (keyword #f "name")) jolt-nil) (if (jolt= G__143 (keyword #f "host")) (jolt-get fnode (keyword #f "name")) jolt-nil)))) (op (if (jolt-truthy? nm) (jolt-invoke (var-deref "jolt.backend-scheme" "native-ops") nm) jolt-nil)) (arity-ok (if (jolt-truthy? nm) (jolt-invoke (var-deref "jolt.backend-scheme" "op-arity") nm) jolt-nil))) (if (jolt-nil? op) jolt-nil (if (jolt-truthy? (let* ((and__25__auto arity-ok)) (if (jolt-truthy? and__25__auto) (jolt-not (jolt-invoke arity-ok nargs)) and__25__auto))) jolt-nil (if (jolt-truthy? (keyword #f "else")) op jolt-nil)))))))) native-op) (let* ((_o$8023 (keyword #f "private")) (_o$8024 #t)) (jolt-hash-map _o$8023 _o$8024)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.backend-scheme" "ifn-kind" (letrec ((ifn-kind (lambda (fnode) (let fnrec8025 ((fnode fnode)) (let* ((G__144 (jolt-get fnode (keyword #f "op")))) (if (jolt= G__144 (keyword #f "const")) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "keyword?") (jolt-get fnode (keyword #f "val")))) (keyword #f "keyword") jolt-nil) (if (let* ((or__26__auto (jolt= G__144 (keyword #f "map")))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt= G__144 (keyword #f "set")))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt= G__144 (keyword #f "vector")))))) (keyword #f "coll") jolt-nil))))))) ifn-kind) (let* ((_o$8026 (keyword #f "private")) (_o$8027 #t)) (jolt-hash-map _o$8026 _o$8027)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.backend-scheme" "stdlib-var?" (letrec ((stdlib-var? (lambda (n) (let fnrec8028 ((n n)) (let* ((and__25__auto (jolt= (keyword #f "var") (jolt-get n (keyword #f "op"))))) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "clojure.string" "starts-with?") (let* ((or__26__auto (jolt-get n (keyword #f "ns")))) (if (jolt-truthy? or__26__auto) or__26__auto "")) "clojure.") and__25__auto)))))) stdlib-var?) (let* ((_o$8029 (keyword #f "private")) (_o$8030 #t)) (jolt-hash-map _o$8029 _o$8030)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.backend-scheme" "emit-numeric" (letrec ((emit-numeric (lambda (kind nm args order-args) (let fnrec8031 ((kind kind) (nm nm) (args args) (order-args order-args)) (if (let* ((and__25__auto (jolt= kind (keyword #f "double")))) (if (jolt-truthy? and__25__auto) (jolt= nm "inc") and__25__auto)) (jolt-invoke (var-deref "clojure.core" "str") "(fl+ " (jolt-first args) " 1.0)") (if (let* ((and__25__auto (jolt= kind (keyword #f "double")))) (if (jolt-truthy? and__25__auto) (jolt= nm "dec") and__25__auto)) (jolt-invoke (var-deref "clojure.core" "str") "(fl- " (jolt-first args) " 1.0)") (if (let* ((and__25__auto (jolt= kind (keyword #f "long")))) (if (jolt-truthy? and__25__auto) (jolt= nm "inc") and__25__auto)) (jolt-invoke (var-deref "clojure.core" "str") "(jolt-l-inc " (jolt-first args) ")") (if (let* ((and__25__auto (jolt= kind (keyword #f "long")))) (if (jolt-truthy? and__25__auto) (jolt= nm "dec") and__25__auto)) (jolt-invoke (var-deref "clojure.core" "str") "(jolt-l-dec " (jolt-first args) ")") (if (let* ((and__25__auto (jolt= kind (keyword #f "long")))) (if (jolt-truthy? and__25__auto) (jolt= nm "unchecked-inc") and__25__auto)) (jolt-invoke (var-deref "clojure.core" "str") "(jolt-uncinc " (jolt-first args) ")") (if (let* ((and__25__auto (jolt= kind (keyword #f "long")))) (if (jolt-truthy? and__25__auto) (jolt= nm "unchecked-dec") and__25__auto)) (jolt-invoke (var-deref "clojure.core" "str") "(jolt-uncdec " (jolt-first args) ")") (if (jolt-truthy? (keyword #f "else")) (let* ((op (let* ((G__145 kind)) (if (jolt= G__145 (keyword #f "double")) (jolt-invoke (var-deref "jolt.backend-scheme" "dbl-ops") nm) (if (jolt= G__145 (keyword #f "long")) (jolt-invoke (var-deref "jolt.backend-scheme" "lng-ops") nm) (if (jolt= G__145 (keyword #f "bigdec")) (jolt-invoke (var-deref "jolt.backend-scheme" "bd-ops") nm) (jolt-throw (let* ((_a$8032 (jolt-invoke (var-deref "clojure.core" "str") "No matching clause: " G__145)) (_a$8033 (jolt-hash-map))) (jolt-ex-info _a$8032 _a$8033))))))))) (jolt-invoke order-args (lambda (as) (let fnrec8034 ((as as)) (jolt-invoke (var-deref "clojure.core" "str") "(" op " " (jolt-invoke (var-deref "clojure.string" "join") " " as) ")"))))) jolt-nil))))))))))) emit-numeric) (let* ((_o$8035 (keyword #f "private")) (_o$8036 #t)) (jolt-hash-map _o$8035 _o$8036)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.backend-scheme" "struct-field-index" (letrec ((struct-field-index (lambda (shape kw) (let fnrec8037 ((shape shape) (kw kw)) (if (jolt-truthy? shape) (let* ((i 0)) (let loop8038 ((i i)) (if (jolt-n>= i (jolt-count shape)) jolt-nil (if (jolt= (jolt-nth shape i) kw) i (if (jolt-truthy? (keyword #f "else")) (loop8038 (jolt-inc i)) jolt-nil))))) jolt-nil))))) struct-field-index) (let* ((_o$8039 (keyword #f "private")) (_o$8040 #t)) (jolt-hash-map _o$8039 _o$8040)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.backend-scheme" "plain-call" (letrec ((plain-call (lambda (callee operand-strs) (let fnrec8041 ((callee callee) (operand-strs operand-strs)) (jolt-invoke (var-deref "clojure.core" "str") "(" callee (if (jolt-truthy? (jolt-seq operand-strs)) (jolt-invoke (var-deref "clojure.core" "str") " " (jolt-invoke (var-deref "clojure.string" "join") " " operand-strs)) "") ")"))))) plain-call) (let* ((_o$8042 (keyword #f "private")) (_o$8043 #t)) (jolt-hash-map _o$8042 _o$8043)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.backend-scheme" "tail-marked-call" (letrec ((tail-marked-call (lambda (callee operand-strs) (let fnrec8044 ((callee callee) (operand-strs operand-strs)) (let* ((tmps (jolt-invoke (var-deref "clojure.core" "mapv") (lambda (_) (let fnrec8045 ((_ _)) (jolt-invoke (var-deref "jolt.backend-scheme" "fresh-label") "_tt$"))) operand-strs)) (binds (jolt-invoke (var-deref "clojure.string" "join") " " (jolt-map (lambda (t a) (let fnrec8046 ((t t) (a a)) (jolt-invoke (var-deref "clojure.core" "str") "(" t " " a ")"))) tmps operand-strs)))) (jolt-invoke (var-deref "clojure.core" "str") "(let* (" binds ") (jolt-trace-mark! #t) " (jolt-invoke (var-deref "jolt.backend-scheme" "plain-call") callee tmps) ")")))))) tail-marked-call) (let* ((_o$8047 (keyword #f "private")) (_o$8048 #t)) (jolt-hash-map _o$8047 _o$8048)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.backend-scheme" "emit-call" (letrec ((emit-call (lambda (tail? callee operand-strs) (let fnrec8049 ((tail? tail?) (callee callee) (operand-strs operand-strs)) (if (jolt-truthy? (let* ((and__25__auto (jolt-invoke (var-deref "clojure.core" "deref") (var-deref "jolt.backend-scheme" "trace-frames?")))) (if (jolt-truthy? and__25__auto) tail? and__25__auto))) (jolt-invoke (var-deref "jolt.backend-scheme" "tail-marked-call") callee operand-strs) (jolt-invoke (var-deref "jolt.backend-scheme" "plain-call") callee operand-strs)))))) emit-call) (let* ((_o$8050 (keyword #f "private")) (_o$8051 #t)) (jolt-hash-map _o$8050 _o$8051)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.backend-scheme" "emit-invoke" (letrec ((emit-invoke (lambda (node) (let fnrec8052 ((node node)) (let* ((tail? (var-deref "jolt.backend-scheme" "*tail?*"))) (let* ((frame__20__auto (jolt-invoke (var-deref "clojure.core" "array-map") (jolt-var "jolt.backend-scheme" "*tail?*") #f))) (begin (jolt-invoke (var-deref "clojure.core" "push-thread-bindings") frame__20__auto) (dynamic-wind (lambda () #f) (lambda () (let* ((fnode (jolt-get node (keyword #f "fn"))) (arg-nodes (jolt-get node (keyword #f "args"))) (args (jolt-invoke (var-deref "clojure.core" "mapv") (var-deref "jolt.backend-scheme" "emit") arg-nodes)) (nop (jolt-invoke (var-deref "jolt.backend-scheme" "native-op") fnode (jolt-count args))) (kind (jolt-invoke (var-deref "jolt.backend-scheme" "ifn-kind") fnode)) (order-args (lambda (build) (let fnrec8053 ((build build)) (jolt-invoke (var-deref "jolt.backend-scheme" "ordered-call") arg-nodes args build)))) (defstr (lambda (as) (let fnrec8054 ((as as)) (if (jolt-n> (jolt-count as) 1) (jolt-invoke (var-deref "clojure.core" "str") " " (jolt-nth as 1)) "")))) (invoke (lambda () (let fnrec8055 () (let* ((_a$8057 (var-deref "jolt.backend-scheme" "ordered-call")) (_a$8058 (jolt-cons fnode arg-nodes)) (_a$8059 (jolt-cons (jolt-invoke (var-deref "jolt.backend-scheme" "emit") fnode) args)) (_a$8060 (lambda (operands) (let fnrec8056 ((operands operands)) (jolt-invoke (var-deref "jolt.backend-scheme" "emit-call") tail? "jolt-invoke" operands))))) (jolt-invoke _a$8057 _a$8058 _a$8059 _a$8060)))))) (if (jolt-truthy? (jolt-get node (keyword #f "devirt-type"))) (jolt-invoke order-args (lambda (as) (let fnrec8061 ((as as)) (let* ((r (jolt-invoke (var-deref "jolt.backend-scheme" "fresh-label") "_r$")) (dv (let* ((_a$8062 (var-deref "clojure.core" "str")) (_a$8063 "(devirt-resolve ") (_a$8064 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-get node (keyword #f "devirt-type")))) (_a$8065 " ") (_a$8066 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-get node (keyword #f "devirt-proto")))) (_a$8067 " ") (_a$8068 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-get node (keyword #f "devirt-method")))) (_a$8069 " ") (_a$8070 r) (_a$8071 ")")) (jolt-invoke _a$8062 _a$8063 _a$8064 _a$8065 _a$8066 _a$8067 _a$8068 _a$8069 _a$8070 _a$8071))) (cells (jolt-invoke (var-deref "clojure.core" "deref") (var-deref "jolt.backend-scheme" "cache-cells"))) (resolver (if (jolt-truthy? cells) (let* ((c (jolt-invoke (var-deref "jolt.backend-scheme" "fresh-label") "_dvc$"))) (begin (jolt-invoke (var-deref "clojure.core" "swap!") cells jolt-conj c) (jolt-invoke (var-deref "clojure.core" "str") "(or " c " (let ((_f " dv ")) (set! " c " _f) _f))"))) dv))) (let* ((_a$8072 (var-deref "clojure.core" "str")) (_a$8073 "(let* ((") (_a$8074 r) (_a$8075 " ") (_a$8076 (jolt-first as)) (_a$8077 ")) (") (_a$8078 resolver) (_a$8079 " ") (_a$8080 (jolt-invoke (var-deref "clojure.string" "join") " " (jolt-cons r (jolt-rest as)))) (_a$8081 "))")) (jolt-invoke _a$8072 _a$8073 _a$8074 _a$8075 _a$8076 _a$8077 _a$8078 _a$8079 _a$8080 _a$8081)))))) (if (jolt-truthy? (jolt-get node (keyword #f "num-kind"))) (let* ((_a$8082 (var-deref "jolt.backend-scheme" "emit-numeric")) (_a$8083 (jolt-get node (keyword #f "num-kind"))) (_a$8084 (jolt-get fnode (keyword #f "name"))) (_a$8085 args) (_a$8086 order-args)) (jolt-invoke _a$8082 _a$8083 _a$8084 _a$8085 _a$8086)) (if (jolt-truthy? (let* ((and__25__auto nop)) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt-empty? args))) (if (jolt-truthy? and__25__auto) (jolt= nop "+") and__25__auto)) and__25__auto))) "0" (if (jolt-truthy? (let* ((and__25__auto nop)) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt-empty? args))) (if (jolt-truthy? and__25__auto) (jolt= nop "*") and__25__auto)) and__25__auto))) "1" (if (jolt-truthy? (let* ((and__25__auto nop)) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt= 1 (jolt-count args)))) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "jolt.backend-scheme" "cmp1-ops") nop) and__25__auto)) and__25__auto))) (jolt-invoke (var-deref "clojure.core" "str") "(begin " (jolt-first args) " #t)") (if (jolt-truthy? nop) (jolt-invoke order-args (lambda (as) (let fnrec8087 ((as as)) (jolt-invoke (var-deref "clojure.core" "str") "(" nop " " (jolt-invoke (var-deref "clojure.string" "join") " " as) ")")))) (if (jolt= kind (keyword #f "keyword")) (let* ((recv (jolt-first arg-nodes)) (idx (if (let* ((and__25__auto (jolt= (keyword #f "struct") (jolt-get recv (keyword #f "hint"))))) (if (jolt-truthy? and__25__auto) (jolt= 1 (jolt-count arg-nodes)) and__25__auto)) (let* ((_a$8088 (var-deref "jolt.backend-scheme" "struct-field-index")) (_a$8089 (jolt-get recv (keyword #f "shape"))) (_a$8090 (jolt-get fnode (keyword #f "val")))) (jolt-invoke _a$8088 _a$8089 _a$8090)) jolt-nil))) (if (jolt-truthy? idx) (jolt-invoke order-args (lambda (as) (let fnrec8091 ((as as)) (let* ((_a$8092 (var-deref "clojure.core" "str")) (_a$8093 "(jrec-field-at ") (_a$8094 (jolt-first as)) (_a$8095 " ") (_a$8096 idx) (_a$8097 " ") (_a$8098 (jolt-invoke (var-deref "jolt.backend-scheme" "emit") fnode)) (_a$8099 ")")) (jolt-invoke _a$8092 _a$8093 _a$8094 _a$8095 _a$8096 _a$8097 _a$8098 _a$8099))))) (jolt-invoke order-args (lambda (as) (let fnrec8100 ((as as)) (let* ((_a$8101 (var-deref "clojure.core" "str")) (_a$8102 "(jolt-get ") (_a$8103 (jolt-first as)) (_a$8104 " ") (_a$8105 (jolt-invoke (var-deref "jolt.backend-scheme" "emit") fnode)) (_a$8106 (jolt-invoke defstr as)) (_a$8107 ")")) (jolt-invoke _a$8101 _a$8102 _a$8103 _a$8104 _a$8105 _a$8106 _a$8107))))))) (if (jolt= kind (keyword #f "coll")) (let* ((_a$8115 (var-deref "jolt.backend-scheme" "ordered-call")) (_a$8116 (jolt-cons fnode arg-nodes)) (_a$8117 (jolt-cons (jolt-invoke (var-deref "jolt.backend-scheme" "emit") fnode) args)) (_a$8118 (lambda (G__146) (let fnrec8108 ((G__146 G__146)) (let* ((G__147 G__146) (c (jolt-nth G__147 0 jolt-nil)) (as (jolt-invoke (var-deref "clojure.core" "nthnext") G__147 1))) (let* ((_a$8109 (var-deref "clojure.core" "str")) (_a$8110 (if (let* ((and__25__auto (jolt= (keyword #f "vector") (jolt-get fnode (keyword #f "op"))))) (if (jolt-truthy? and__25__auto) (jolt= 1 (jolt-count as)) and__25__auto)) "(jolt-nth " "(jolt-get ")) (_a$8111 c) (_a$8112 " ") (_a$8113 (jolt-invoke (var-deref "clojure.string" "join") " " as)) (_a$8114 ")")) (jolt-invoke _a$8109 _a$8110 _a$8111 _a$8112 _a$8113 _a$8114))))))) (jolt-invoke _a$8115 _a$8116 _a$8117 _a$8118)) (if (jolt-truthy? (let* ((and__25__auto (jolt-invoke (var-deref "jolt.backend-scheme" "stdlib-var?") fnode))) (if (jolt-truthy? and__25__auto) (jolt-not (jolt-invoke (var-deref "clojure.core" "deref") (var-deref "jolt.backend-scheme" "prelude-mode?"))) and__25__auto))) (jolt-throw (let* ((_a$8125 (let* ((_a$8119 (var-deref "clojure.core" "str")) (_a$8120 "emit: unsupported stdlib fn `") (_a$8121 (jolt-get fnode (keyword #f "ns"))) (_a$8122 "/") (_a$8123 (jolt-get fnode (keyword #f "name"))) (_a$8124 "` (no core on Chez yet)")) (jolt-invoke _a$8119 _a$8120 _a$8121 _a$8122 _a$8123 _a$8124))) (_a$8126 (jolt-hash-map))) (jolt-ex-info _a$8125 _a$8126))) (if (jolt= (keyword #f "host-static") (jolt-get fnode (keyword #f "op"))) (jolt-invoke order-args (lambda (as) (let fnrec8127 ((as as)) (let* ((_a$8128 (var-deref "clojure.core" "str")) (_a$8129 "(host-static-call ") (_a$8130 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-get fnode (keyword #f "class")))) (_a$8131 " ") (_a$8132 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-get fnode (keyword #f "member")))) (_a$8133 (if (jolt-empty? as) "" (jolt-invoke (var-deref "clojure.core" "str") " " (jolt-invoke (var-deref "clojure.string" "join") " " as)))) (_a$8134 ")")) (jolt-invoke _a$8128 _a$8129 _a$8130 _a$8131 _a$8132 _a$8133 _a$8134))))) (if (jolt= (keyword #f "host") (jolt-get fnode (keyword #f "op"))) (jolt-throw (let* ((_a$8135 (jolt-invoke (var-deref "clojure.core" "str") "emit: unsupported host call `" (jolt-get fnode (keyword #f "name")) "`")) (_a$8136 (jolt-hash-map))) (jolt-ex-info _a$8135 _a$8136))) (if (jolt= (keyword #f "local") (jolt-get fnode (keyword #f "op"))) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.backend-scheme" "*known-procs*") (jolt-invoke (var-deref "jolt.backend-scheme" "munge-name") (jolt-get fnode (keyword #f "name"))))) (jolt-invoke order-args (lambda (as) (let fnrec8137 ((as as)) (jolt-invoke (var-deref "jolt.backend-scheme" "emit-call") tail? (jolt-invoke (var-deref "jolt.backend-scheme" "munge-name") (jolt-get fnode (keyword #f "name"))) as)))) (jolt-invoke invoke)) (if (jolt-truthy? (let* ((and__25__auto (jolt= (keyword #f "var") (jolt-get fnode (keyword #f "op"))))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (let* ((_a$8138 (var-deref "jolt.backend-scheme" "direct-linkable?")) (_a$8139 (jolt-get fnode (keyword #f "ns"))) (_a$8140 (jolt-get fnode (keyword #f "name")))) (jolt-invoke _a$8138 _a$8139 _a$8140)))) (if (jolt-truthy? and__25__auto) (let* ((_a$8141 (var-deref "jolt.backend-scheme" "direct-link-fn?")) (_a$8142 (jolt-get fnode (keyword #f "ns"))) (_a$8143 (jolt-get fnode (keyword #f "name")))) (jolt-invoke _a$8141 _a$8142 _a$8143)) and__25__auto)) and__25__auto))) (jolt-invoke order-args (lambda (as) (let fnrec8144 ((as as)) (jolt-invoke (var-deref "jolt.backend-scheme" "emit-call") tail? (let* ((_a$8145 (var-deref "jolt.backend-scheme" "dl-name")) (_a$8146 (jolt-get fnode (keyword #f "ns"))) (_a$8147 (jolt-get fnode (keyword #f "name")))) (jolt-invoke _a$8145 _a$8146 _a$8147)) as)))) (if (jolt= (keyword #f "var") (jolt-get fnode (keyword #f "op"))) (jolt-invoke invoke) (if (jolt-truthy? (keyword #f "else")) (jolt-invoke invoke) jolt-nil))))))))))))))))) (lambda () (jolt-invoke (var-deref "clojure.core" "pop-thread-bindings"))))))))))) emit-invoke) (let* ((_o$8148 (keyword #f "private")) (_o$8149 #t)) (jolt-hash-map _o$8148 _o$8149)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.backend-scheme" "emit-try" (letrec ((emit-try (lambda (node) (let fnrec8150 ((node node)) (let* ((core (let* ((temp__16__auto (jolt-get node (keyword #f "catch-sym")))) (if (jolt-truthy? temp__16__auto) (let* ((cs temp__16__auto)) (let* ((raw (jolt-invoke (var-deref "jolt.backend-scheme" "munge-name") (jolt-get node (keyword #f "catch-raw-sym"))))) (let* ((_a$8151 (var-deref "clojure.core" "str")) (_a$8152 "(guard (") (_a$8153 raw) (_a$8154 " (else (let ((") (_a$8155 (jolt-invoke (var-deref "jolt.backend-scheme" "munge-name") cs)) (_a$8156 " (jolt-unwrap-throw ") (_a$8157 raw) (_a$8158 "))) ") (_a$8159 (jolt-invoke (var-deref "jolt.backend-scheme" "emit") (jolt-get node (keyword #f "catch-body")))) (_a$8160 "))) ") (_a$8161 (jolt-invoke (var-deref "jolt.backend-scheme" "emit") (jolt-get node (keyword #f "body")))) (_a$8162 ")")) (jolt-invoke _a$8151 _a$8152 _a$8153 _a$8154 _a$8155 _a$8156 _a$8157 _a$8158 _a$8159 _a$8160 _a$8161 _a$8162)))) (jolt-invoke (var-deref "jolt.backend-scheme" "emit") (jolt-get node (keyword #f "body"))))))) (let* ((temp__16__auto (jolt-get node (keyword #f "finally")))) (if (jolt-truthy? temp__16__auto) (let* ((fin temp__16__auto)) (jolt-invoke (var-deref "clojure.core" "str") "(dynamic-wind (lambda () #f) (lambda () " core ") (lambda () " (jolt-invoke (var-deref "jolt.backend-scheme" "emit") fin) "))")) core))))))) emit-try) (let* ((_o$8163 (keyword #f "private")) (_o$8164 #t)) (jolt-hash-map _o$8163 _o$8164)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.backend-scheme" "returns-scheme-bool?" (letrec ((returns-scheme-bool? (case-lambda ((node) (let fnrec8165 ((node node)) (returns-scheme-bool? node (jolt-hash-set)))) ((node bools) (let fnrec8166 ((node node) (bools bools)) (if (jolt-truthy? (let* ((and__25__auto (jolt= (keyword #f "const") (jolt-get node (keyword #f "op"))))) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "clojure.core" "boolean?") (jolt-get node (keyword #f "val"))) and__25__auto))) #t (if (jolt= (keyword #f "invoke") (jolt-get node (keyword #f "op"))) (let* ((nop (let* ((_a$8167 (var-deref "jolt.backend-scheme" "native-op")) (_a$8168 (jolt-get node (keyword #f "fn"))) (_a$8169 (jolt-count (jolt-get node (keyword #f "args"))))) (jolt-invoke _a$8167 _a$8168 _a$8169)))) (jolt-invoke (var-deref "clojure.core" "boolean") (let* ((and__25__auto nop)) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "jolt.backend-scheme" "bool-returning-ops") nop) and__25__auto)))) (if (jolt= (keyword #f "local") (jolt-get node (keyword #f "op"))) (jolt-contains? bools (jolt-get node (keyword #f "name"))) (if (jolt= (keyword #f "if") (jolt-get node (keyword #f "op"))) (let* ((and__25__auto (returns-scheme-bool? (jolt-get node (keyword #f "then")) bools))) (if (jolt-truthy? and__25__auto) (returns-scheme-bool? (jolt-get node (keyword #f "else")) bools) and__25__auto)) (if (jolt= (keyword #f "let") (jolt-get node (keyword #f "op"))) (let* ((bools_PRIME_ (let* ((_a$8171 (lambda (s b) (let fnrec8170 ((s s) (b b)) (if (jolt-truthy? (returns-scheme-bool? (jolt-nth b 1) s)) (jolt-conj s (jolt-nth b 0)) (jolt-invoke (var-deref "clojure.core" "disj") s (jolt-nth b 0)))))) (_a$8172 bools) (_a$8173 (jolt-get node (keyword #f "bindings")))) (jolt-reduce _a$8171 _a$8172 _a$8173)))) (returns-scheme-bool? (jolt-get node (keyword #f "body")) bools_PRIME_)) (if (jolt-truthy? (keyword #f "else")) #f jolt-nil))))))))))) returns-scheme-bool?) (let* ((_o$8174 (keyword #f "private")) (_o$8175 #t)) (jolt-hash-map _o$8174 _o$8175)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.backend-scheme" "trace-source-reg" (letrec ((trace-source-reg (lambda (node) (let fnrec8176 ((node node)) (let* ((init (jolt-get node (keyword #f "init"))) (pos (jolt-get node (keyword #f "pos")))) (if (jolt-truthy? (let* ((and__25__auto (jolt-invoke (var-deref "clojure.core" "deref") (var-deref "jolt.backend-scheme" "trace-frames?")))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt= (keyword #f "fn") (jolt-get init (keyword #f "op"))))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt-get init (keyword #f "name")))) (if (jolt-truthy? and__25__auto) pos and__25__auto)) and__25__auto)) and__25__auto))) (let* ((_a$8177 (var-deref "clojure.core" "str")) (_a$8178 " (jolt-register-source! ") (_a$8179 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-invoke (var-deref "jolt.backend-scheme" "munge-name") (jolt-get init (keyword #f "name"))))) (_a$8180 " ") (_a$8181 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-get node (keyword #f "ns")))) (_a$8182 " ") (_a$8183 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-get node (keyword #f "name")))) (_a$8184 " ") (_a$8185 (if (jolt-truthy? (jolt-get pos (keyword #f "file"))) (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-get pos (keyword #f "file"))) "jolt-nil")) (_a$8186 " ") (_a$8187 (let* ((or__26__auto (jolt-get pos (keyword #f "line")))) (if (jolt-truthy? or__26__auto) or__26__auto 0))) (_a$8188 ")")) (jolt-invoke _a$8177 _a$8178 _a$8179 _a$8180 _a$8181 _a$8182 _a$8183 _a$8184 _a$8185 _a$8186 _a$8187 _a$8188)) "")))))) trace-source-reg) (let* ((_o$8189 (keyword #f "private")) (_o$8190 #t)) (jolt-hash-map _o$8189 _o$8190)))) -(guard (e (#t #f)) - (def-var! "jolt.backend-scheme" "emit*" (letrec ((emit* (lambda (node) (let fnrec8191 ((node node)) (let* ((G__148 (jolt-get node (keyword #f "op")))) (if (jolt= G__148 (keyword #f "const")) (jolt-invoke (var-deref "jolt.backend-scheme" "emit-const") (jolt-get node (keyword #f "val"))) (if (jolt= G__148 (keyword #f "local")) (jolt-invoke (var-deref "jolt.backend-scheme" "munge-name") (jolt-get node (keyword #f "name"))) (if (jolt= G__148 (keyword #f "var")) (let* ((core-proc (let* ((and__25__auto (jolt= "clojure.core" (jolt-get node (keyword #f "ns"))))) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "jolt.backend-scheme" "core-value-procs") (jolt-get node (keyword #f "name"))) and__25__auto)))) (if (jolt-truthy? core-proc) core-proc (if (jolt-truthy? (let* ((_a$8192 (var-deref "jolt.backend-scheme" "direct-linkable?")) (_a$8193 (jolt-get node (keyword #f "ns"))) (_a$8194 (jolt-get node (keyword #f "name")))) (jolt-invoke _a$8192 _a$8193 _a$8194))) (let* ((_a$8195 (var-deref "jolt.backend-scheme" "dl-name")) (_a$8196 (jolt-get node (keyword #f "ns"))) (_a$8197 (jolt-get node (keyword #f "name")))) (jolt-invoke _a$8195 _a$8196 _a$8197)) (if (jolt-truthy? (let* ((and__25__auto (jolt-invoke (var-deref "jolt.backend-scheme" "stdlib-var?") node))) (if (jolt-truthy? and__25__auto) (jolt-not (jolt-invoke (var-deref "clojure.core" "deref") (var-deref "jolt.backend-scheme" "prelude-mode?"))) and__25__auto))) (jolt-throw (let* ((_a$8204 (let* ((_a$8198 (var-deref "clojure.core" "str")) (_a$8199 "emit: unsupported stdlib ref `") (_a$8200 (jolt-get node (keyword #f "ns"))) (_a$8201 "/") (_a$8202 (jolt-get node (keyword #f "name"))) (_a$8203 "` (no core on Chez yet)")) (jolt-invoke _a$8198 _a$8199 _a$8200 _a$8201 _a$8202 _a$8203))) (_a$8205 (jolt-hash-map))) (jolt-ex-info _a$8204 _a$8205))) (if (jolt-truthy? (keyword #f "else")) (let* ((cells (jolt-invoke (var-deref "clojure.core" "deref") (var-deref "jolt.backend-scheme" "cache-cells"))) (nslit (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-get node (keyword #f "ns")))) (nmlit (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-get node (keyword #f "name"))))) (if (jolt-truthy? (let* ((and__25__auto (jolt-invoke (var-deref "clojure.core" "deref") (var-deref "jolt.backend-scheme" "var-cache?")))) (if (jolt-truthy? and__25__auto) cells and__25__auto))) (let* ((c (jolt-invoke (var-deref "jolt.backend-scheme" "fresh-label") "_vc$"))) (begin (jolt-invoke (var-deref "clojure.core" "swap!") cells jolt-conj c) (jolt-invoke (var-deref "clojure.core" "str") "(var-cell-deref (or " c " (let ((_v (jolt-var " nslit " " nmlit "))) (set! " c " _v) _v)))"))) (jolt-invoke (var-deref "clojure.core" "str") "(var-deref " nslit " " nmlit ")"))) jolt-nil))))) (if (jolt= G__148 (keyword #f "the-var")) (let* ((_a$8206 (var-deref "clojure.core" "str")) (_a$8207 "(jolt-var ") (_a$8208 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-get node (keyword #f "ns")))) (_a$8209 " ") (_a$8210 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-get node (keyword #f "name")))) (_a$8211 ")")) (jolt-invoke _a$8206 _a$8207 _a$8208 _a$8209 _a$8210 _a$8211)) (if (jolt= G__148 (keyword #f "set-var")) (let* ((_a$8212 (var-deref "clojure.core" "str")) (_a$8213 "(jolt-var-set ") (_a$8214 (jolt-invoke (var-deref "jolt.backend-scheme" "emit") (jolt-get node (keyword #f "the-var")))) (_a$8215 " ") (_a$8216 (jolt-invoke (var-deref "jolt.backend-scheme" "emit") (jolt-get node (keyword #f "val")))) (_a$8217 ")")) (jolt-invoke _a$8212 _a$8213 _a$8214 _a$8215 _a$8216 _a$8217)) (if (jolt= G__148 (keyword #f "set-field")) (let* ((_a$8218 (var-deref "clojure.core" "str")) (_a$8219 "(jolt-set-field! ") (_a$8220 (jolt-invoke (var-deref "jolt.backend-scheme" "emit") (jolt-get node (keyword #f "obj")))) (_a$8221 " (keyword #f ") (_a$8222 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-get node (keyword #f "field")))) (_a$8223 ") ") (_a$8224 (jolt-invoke (var-deref "jolt.backend-scheme" "emit") (jolt-get node (keyword #f "val")))) (_a$8225 ")")) (jolt-invoke _a$8218 _a$8219 _a$8220 _a$8221 _a$8222 _a$8223 _a$8224 _a$8225)) (if (jolt= G__148 (keyword #f "defmacro")) (let* ((_a$8226 (var-deref "clojure.core" "str")) (_a$8227 "(begin (def-var! ") (_a$8228 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-get node (keyword #f "ns")))) (_a$8229 " ") (_a$8230 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-get node (keyword #f "name")))) (_a$8231 " ") (_a$8232 (jolt-invoke (var-deref "jolt.backend-scheme" "emit") (jolt-get node (keyword #f "fn")))) (_a$8233 ") (mark-macro! ") (_a$8234 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-get node (keyword #f "ns")))) (_a$8235 " ") (_a$8236 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-get node (keyword #f "name")))) (_a$8237 ") jolt-nil)")) (jolt-invoke _a$8226 _a$8227 _a$8228 _a$8229 _a$8230 _a$8231 _a$8232 _a$8233 _a$8234 _a$8235 _a$8236 _a$8237)) (if (jolt= G__148 (keyword #f "host")) (jolt-throw (let* ((_a$8238 (jolt-invoke (var-deref "clojure.core" "str") "emit: unsupported host ref `" (jolt-get node (keyword #f "name")) "`")) (_a$8239 (jolt-hash-map))) (jolt-ex-info _a$8238 _a$8239))) (if (jolt= G__148 (keyword #f "host-static")) (let* ((_a$8240 (var-deref "clojure.core" "str")) (_a$8241 "(host-static-ref ") (_a$8242 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-get node (keyword #f "class")))) (_a$8243 " ") (_a$8244 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-get node (keyword #f "member")))) (_a$8245 ")")) (jolt-invoke _a$8240 _a$8241 _a$8242 _a$8243 _a$8244 _a$8245)) (if (jolt= G__148 (keyword #f "host-new")) (let* ((_a$8246 (var-deref "clojure.core" "str")) (_a$8247 "(host-new ") (_a$8248 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-get node (keyword #f "class")))) (_a$8249 (let* ((args (jolt-map (var-deref "jolt.backend-scheme" "emit") (jolt-get node (keyword #f "args"))))) (if (jolt-empty? args) "" (jolt-invoke (var-deref "clojure.core" "str") " " (jolt-invoke (var-deref "clojure.string" "join") " " args))))) (_a$8250 ")")) (jolt-invoke _a$8246 _a$8247 _a$8248 _a$8249 _a$8250)) (if (jolt= G__148 (keyword #f "if")) (let* ((test (jolt-get node (keyword #f "test"))) (t (let* ((frame__20__auto (jolt-invoke (var-deref "clojure.core" "array-map") (jolt-var "jolt.backend-scheme" "*tail?*") #f))) (begin (jolt-invoke (var-deref "clojure.core" "push-thread-bindings") frame__20__auto) (dynamic-wind (lambda () #f) (lambda () (if (jolt-truthy? (jolt-invoke (var-deref "jolt.backend-scheme" "returns-scheme-bool?") test)) (jolt-invoke (var-deref "jolt.backend-scheme" "emit") test) (jolt-invoke (var-deref "clojure.core" "str") "(jolt-truthy? " (jolt-invoke (var-deref "jolt.backend-scheme" "emit") test) ")"))) (lambda () (jolt-invoke (var-deref "clojure.core" "pop-thread-bindings")))))))) (let* ((_a$8251 (var-deref "clojure.core" "str")) (_a$8252 "(if ") (_a$8253 t) (_a$8254 " ") (_a$8255 (jolt-invoke (var-deref "jolt.backend-scheme" "emit") (jolt-get node (keyword #f "then")))) (_a$8256 " ") (_a$8257 (jolt-invoke (var-deref "jolt.backend-scheme" "emit") (jolt-get node (keyword #f "else")))) (_a$8258 ")")) (jolt-invoke _a$8251 _a$8252 _a$8253 _a$8254 _a$8255 _a$8256 _a$8257 _a$8258))) (if (jolt= G__148 (keyword #f "do")) (let* ((_a$8259 (var-deref "clojure.core" "str")) (_a$8260 "(begin ") (_a$8261 (let* ((frame__20__auto (jolt-invoke (var-deref "clojure.core" "array-map") (jolt-var "jolt.backend-scheme" "*tail?*") #f))) (begin (jolt-invoke (var-deref "clojure.core" "push-thread-bindings") frame__20__auto) (dynamic-wind (lambda () #f) (lambda () (jolt-invoke (var-deref "clojure.string" "join") " " (jolt-invoke (var-deref "clojure.core" "mapv") (var-deref "jolt.backend-scheme" "emit") (jolt-get node (keyword #f "statements"))))) (lambda () (jolt-invoke (var-deref "clojure.core" "pop-thread-bindings"))))))) (_a$8262 (if (jolt-empty? (jolt-get node (keyword #f "statements"))) "" " ")) (_a$8263 (jolt-invoke (var-deref "jolt.backend-scheme" "emit") (jolt-get node (keyword #f "ret")))) (_a$8264 ")")) (jolt-invoke _a$8259 _a$8260 _a$8261 _a$8262 _a$8263 _a$8264)) (if (jolt= G__148 (keyword #f "invoke")) (jolt-invoke (var-deref "jolt.backend-scheme" "emit-invoke") node) (if (jolt= G__148 (keyword #f "vector")) (jolt-invoke (var-deref "jolt.backend-scheme" "emit-ordered") "jolt-vector" (jolt-map (var-deref "jolt.backend-scheme" "emit") (jolt-get node (keyword #f "items")))) (if (jolt= G__148 (keyword #f "set")) (jolt-invoke (var-deref "jolt.backend-scheme" "emit-ordered") "jolt-hash-set" (jolt-map (var-deref "jolt.backend-scheme" "emit") (jolt-get node (keyword #f "items")))) (if (jolt= G__148 (keyword #f "map")) (jolt-invoke (var-deref "jolt.backend-scheme" "emit-ordered") "jolt-hash-map" (let* ((_a$8268 (var-deref "clojure.core" "mapcat")) (_a$8269 (lambda (p) (let fnrec8265 ((p p)) (let* ((_o$8266 (jolt-invoke (var-deref "jolt.backend-scheme" "emit") (jolt-nth p 0))) (_o$8267 (jolt-invoke (var-deref "jolt.backend-scheme" "emit") (jolt-nth p 1)))) (jolt-vector _o$8266 _o$8267))))) (_a$8270 (jolt-get node (keyword #f "pairs")))) (jolt-invoke _a$8268 _a$8269 _a$8270))) (if (jolt= G__148 (keyword #f "quote")) (jolt-invoke (var-deref "jolt.backend-scheme" "emit-quoted") (jolt-get node (keyword #f "form"))) (if (jolt= G__148 (keyword #f "throw")) (jolt-invoke (var-deref "clojure.core" "str") "(jolt-throw " (jolt-invoke (var-deref "jolt.backend-scheme" "emit") (jolt-get node (keyword #f "expr"))) ")") (if (jolt= G__148 (keyword #f "coerce")) (let* ((e (jolt-invoke (var-deref "jolt.backend-scheme" "emit") (jolt-get node (keyword #f "expr"))))) (if (jolt= (keyword #f "double") (jolt-get node (keyword #f "kind"))) (jolt-invoke (var-deref "clojure.core" "str") "(exact->inexact " e ")") (if (jolt= (keyword #f "long") (jolt-get node (keyword #f "kind"))) (jolt-invoke (var-deref "clojure.core" "str") "(jolt->fx " e ")") (if (jolt-truthy? (keyword #f "else")) e jolt-nil)))) (if (jolt= G__148 (keyword #f "try")) (jolt-invoke (var-deref "jolt.backend-scheme" "emit-try") node) (if (jolt= G__148 (keyword #f "regex")) (jolt-invoke (var-deref "clojure.core" "str") "(jolt-regex " (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-get node (keyword #f "source"))) ")") (if (jolt= G__148 (keyword #f "inst")) (jolt-invoke (var-deref "clojure.core" "str") "(jolt-inst-from-string " (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-get node (keyword #f "source"))) ")") (if (jolt= G__148 (keyword #f "uuid")) (jolt-invoke (var-deref "clojure.core" "str") "(jolt-uuid-from-string " (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-get node (keyword #f "source"))) ")") (if (jolt= G__148 (keyword #f "bigdec")) (jolt-invoke (var-deref "clojure.core" "str") "(jolt-bigdec-from-string " (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-get node (keyword #f "source"))) ")") (if (jolt= G__148 (keyword #f "the-ns")) (jolt-invoke (var-deref "clojure.core" "str") "(intern-ns! " (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-get node (keyword #f "name"))) ")") (if (jolt= G__148 (keyword #f "host-call")) (let* ((m (jolt-get node (keyword #f "method"))) (target (jolt-invoke (var-deref "jolt.backend-scheme" "emit") (jolt-get node (keyword #f "target")))) (args (jolt-map (var-deref "jolt.backend-scheme" "emit") (jolt-get node (keyword #f "args"))))) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.backend-scheme" "supported-host-methods") m)) (let* ((_a$8271 (var-deref "clojure.core" "str")) (_a$8272 "(jolt-host-call ") (_a$8273 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") m)) (_a$8274 " ") (_a$8275 target) (_a$8276 (if (jolt-empty? args) "" (jolt-invoke (var-deref "clojure.core" "str") " " (jolt-invoke (var-deref "clojure.string" "join") " " args)))) (_a$8277 ")")) (jolt-invoke _a$8271 _a$8272 _a$8273 _a$8274 _a$8275 _a$8276 _a$8277)) (let* ((_a$8278 (var-deref "clojure.core" "str")) (_a$8279 "(record-method-dispatch ") (_a$8280 target) (_a$8281 " ") (_a$8282 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") m)) (_a$8283 " (jolt-vector") (_a$8284 (if (jolt-empty? args) "" (jolt-invoke (var-deref "clojure.core" "str") " " (jolt-invoke (var-deref "clojure.string" "join") " " args)))) (_a$8285 "))")) (jolt-invoke _a$8278 _a$8279 _a$8280 _a$8281 _a$8282 _a$8283 _a$8284 _a$8285)))) (if (jolt= G__148 (keyword #f "let")) (jolt-invoke (var-deref "jolt.backend-scheme" "emit-let") node) (if (jolt= G__148 (keyword #f "loop")) (jolt-invoke (var-deref "jolt.backend-scheme" "emit-loop") node) (if (jolt= G__148 (keyword #f "recur")) (jolt-invoke (var-deref "jolt.backend-scheme" "emit-recur") node) (if (jolt= G__148 (keyword #f "ffi-fn")) (jolt-invoke (var-deref "jolt.backend-scheme" "emit-ffi-fn") node) (if (jolt= G__148 (keyword #f "ffi-callable")) (jolt-invoke (var-deref "jolt.backend-scheme" "emit-ffi-callable") node) (if (jolt= G__148 (keyword #f "fn")) (jolt-invoke (var-deref "jolt.backend-scheme" "emit-fn") node) (if (jolt= G__148 (keyword #f "def")) (let* ((reg (jolt-invoke (var-deref "jolt.backend-scheme" "trace-source-reg") node)) (d (if (jolt-truthy? (jolt-get node (keyword #f "no-init"))) (let* ((_a$8286 (var-deref "clojure.core" "str")) (_a$8287 "(declare-var! ") (_a$8288 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-get node (keyword #f "ns")))) (_a$8289 " ") (_a$8290 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-get node (keyword #f "name")))) (_a$8291 ")")) (jolt-invoke _a$8286 _a$8287 _a$8288 _a$8289 _a$8290 _a$8291)) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.backend-scheme" "jmeta-nonempty?") (jolt-get node (keyword #f "meta")))) (let* ((_a$8293 (var-deref "clojure.core" "str")) (_a$8294 "(def-var-with-meta! ") (_a$8295 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-get node (keyword #f "ns")))) (_a$8296 " ") (_a$8297 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-get node (keyword #f "name")))) (_a$8298 " ") (_a$8299 (jolt-invoke (var-deref "jolt.backend-scheme" "emit-with-cells") (lambda () (let fnrec8292 () (jolt-invoke (var-deref "jolt.backend-scheme" "emit") (jolt-get node (keyword #f "init"))))))) (_a$8300 " ") (_a$8301 (jolt-invoke (var-deref "jolt.backend-scheme" "emit-def-meta") node)) (_a$8302 ")")) (jolt-invoke _a$8293 _a$8294 _a$8295 _a$8296 _a$8297 _a$8298 _a$8299 _a$8300 _a$8301 _a$8302)) (if (jolt-truthy? (keyword #f "else")) (let* ((_a$8304 (var-deref "clojure.core" "str")) (_a$8305 "(def-var! ") (_a$8306 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-get node (keyword #f "ns")))) (_a$8307 " ") (_a$8308 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-get node (keyword #f "name")))) (_a$8309 " ") (_a$8310 (jolt-invoke (var-deref "jolt.backend-scheme" "emit-with-cells") (lambda () (let fnrec8303 () (jolt-invoke (var-deref "jolt.backend-scheme" "emit") (jolt-get node (keyword #f "init"))))))) (_a$8311 ")")) (jolt-invoke _a$8304 _a$8305 _a$8306 _a$8307 _a$8308 _a$8309 _a$8310 _a$8311)) jolt-nil))))) (if (jolt= reg "") d (jolt-invoke (var-deref "clojure.core" "str") "(begin " d reg ")"))) (jolt-throw (let* ((_a$8312 (jolt-invoke (var-deref "clojure.core" "str") "emit: op not yet ported / unhandled: " (jolt-invoke (var-deref "clojure.core" "pr-str") (jolt-get node (keyword #f "op"))))) (_a$8313 (jolt-hash-map))) (jolt-ex-info _a$8312 _a$8313))))))))))))))))))))))))))))))))))))))))) emit*))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.backend-scheme" "dl-opt-out?" (letrec ((dl-opt-out? (lambda (m) (let fnrec8314 ((m m)) (let* ((or__26__auto (jolt-get m (keyword #f "dynamic")))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-get m (keyword #f "redef")))))))) dl-opt-out?) (let* ((_o$8315 (keyword #f "private")) (_o$8316 #t)) (jolt-hash-map _o$8315 _o$8316)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.backend-scheme" "emit-def-cached" (letrec ((emit-def-cached (lambda (node) (let fnrec8317 ((node node)) (let* ((ns (jolt-get node (keyword #f "ns"))) (nm (jolt-get node (keyword #f "name"))) (dl? (let* ((and__25__auto (jolt-invoke (var-deref "clojure.core" "deref") (var-deref "jolt.backend-scheme" "direct-link?")))) (if (jolt-truthy? and__25__auto) (jolt-not (jolt-invoke (var-deref "jolt.backend-scheme" "dl-opt-out?") (jolt-get node (keyword #f "meta")))) and__25__auto))) (b (jolt-invoke (var-deref "jolt.backend-scheme" "dl-name") ns nm)) (fn? (jolt= (keyword #f "fn") (jolt-get (jolt-get node (keyword #f "init")) (keyword #f "op")))) (pos (jolt-get node (keyword #f "pos"))) (frame-name (if (jolt-truthy? fn?) (let* ((temp__16__auto (jolt-get (jolt-get node (keyword #f "init")) (keyword #f "name")))) (if (jolt-truthy? temp__16__auto) (let* ((fnm temp__16__auto)) (jolt-invoke (var-deref "jolt.backend-scheme" "munge-name") fnm)) b)) jolt-nil)) (reg (if (jolt-truthy? (let* ((and__25__auto dl?)) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto fn?)) (if (jolt-truthy? and__25__auto) pos and__25__auto)) and__25__auto))) (let* ((_a$8318 (var-deref "clojure.core" "str")) (_a$8319 " (jolt-register-source! ") (_a$8320 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") frame-name)) (_a$8321 " ") (_a$8322 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") ns)) (_a$8323 " ") (_a$8324 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") nm)) (_a$8325 " ") (_a$8326 (if (jolt-truthy? (jolt-get pos (keyword #f "file"))) (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-get pos (keyword #f "file"))) "jolt-nil")) (_a$8327 " ") (_a$8328 (let* ((or__26__auto (jolt-get pos (keyword #f "line")))) (if (jolt-truthy? or__26__auto) or__26__auto 0))) (_a$8329 ")")) (jolt-invoke _a$8318 _a$8319 _a$8320 _a$8321 _a$8322 _a$8323 _a$8324 _a$8325 _a$8326 _a$8327 _a$8328 _a$8329)) jolt-nil)) (_ (if (jolt-truthy? dl?) (begin (jolt-invoke (var-deref "clojure.core" "swap!") (var-deref "jolt.backend-scheme" "direct-link-defined") jolt-conj (jolt-invoke (var-deref "jolt.backend-scheme" "dl-fqn") ns nm)) (if (jolt-truthy? fn?) (jolt-invoke (var-deref "clojure.core" "swap!") (var-deref "jolt.backend-scheme" "direct-link-fns") jolt-conj (jolt-invoke (var-deref "jolt.backend-scheme" "dl-fqn") ns nm)) jolt-nil)) jolt-nil)) (init (jolt-invoke (var-deref "jolt.backend-scheme" "emit-with-cells") (lambda () (let fnrec8330 () (jolt-invoke (var-deref "jolt.backend-scheme" "emit") (jolt-get node (keyword #f "init")))))))) (if (jolt-truthy? dl?) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.backend-scheme" "jmeta-nonempty?") (jolt-get node (keyword #f "meta")))) (let* ((_a$8331 (var-deref "clojure.core" "str")) (_a$8332 "(begin (define ") (_a$8333 b) (_a$8334 " ") (_a$8335 init) (_a$8336 ") (def-var-with-meta! ") (_a$8337 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") ns)) (_a$8338 " ") (_a$8339 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") nm)) (_a$8340 " ") (_a$8341 b) (_a$8342 " ") (_a$8343 (jolt-invoke (var-deref "jolt.backend-scheme" "emit-def-meta") node)) (_a$8344 ")") (_a$8345 (let* ((or__26__auto reg)) (if (jolt-truthy? or__26__auto) or__26__auto ""))) (_a$8346 ")")) (jolt-invoke _a$8331 _a$8332 _a$8333 _a$8334 _a$8335 _a$8336 _a$8337 _a$8338 _a$8339 _a$8340 _a$8341 _a$8342 _a$8343 _a$8344 _a$8345 _a$8346)) (let* ((_a$8347 (var-deref "clojure.core" "str")) (_a$8348 "(begin (define ") (_a$8349 b) (_a$8350 " ") (_a$8351 init) (_a$8352 ") (def-var! ") (_a$8353 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") ns)) (_a$8354 " ") (_a$8355 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") nm)) (_a$8356 " ") (_a$8357 b) (_a$8358 ")") (_a$8359 (let* ((or__26__auto reg)) (if (jolt-truthy? or__26__auto) or__26__auto ""))) (_a$8360 ")")) (jolt-invoke _a$8347 _a$8348 _a$8349 _a$8350 _a$8351 _a$8352 _a$8353 _a$8354 _a$8355 _a$8356 _a$8357 _a$8358 _a$8359 _a$8360))) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.backend-scheme" "jmeta-nonempty?") (jolt-get node (keyword #f "meta")))) (let* ((_a$8361 (var-deref "clojure.core" "str")) (_a$8362 "(def-var-with-meta! ") (_a$8363 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") ns)) (_a$8364 " ") (_a$8365 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") nm)) (_a$8366 " ") (_a$8367 init) (_a$8368 " ") (_a$8369 (jolt-invoke (var-deref "jolt.backend-scheme" "emit-def-meta") node)) (_a$8370 ")")) (jolt-invoke _a$8361 _a$8362 _a$8363 _a$8364 _a$8365 _a$8366 _a$8367 _a$8368 _a$8369 _a$8370)) (if (jolt-truthy? (keyword #f "else")) (let* ((_a$8371 (var-deref "clojure.core" "str")) (_a$8372 "(def-var! ") (_a$8373 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") ns)) (_a$8374 " ") (_a$8375 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") nm)) (_a$8376 " ") (_a$8377 init) (_a$8378 ")")) (jolt-invoke _a$8371 _a$8372 _a$8373 _a$8374 _a$8375 _a$8376 _a$8377 _a$8378)) jolt-nil)))))))) emit-def-cached) (let* ((_o$8379 (keyword #f "private")) (_o$8380 #t)) (jolt-hash-map _o$8379 _o$8380)))) -(guard (e (#t #f)) - (def-var! "jolt.backend-scheme" "emit-top-form" (letrec ((emit-top-form (lambda (node) (let fnrec8381 ((node node)) (if (jolt-not (jolt-invoke (var-deref "clojure.core" "deref") (var-deref "jolt.backend-scheme" "direct-link?"))) (jolt-invoke (var-deref "jolt.backend-scheme" "emit") node) (if (jolt= (keyword #f "do") (jolt-get node (keyword #f "op"))) (let* ((_a$8382 (var-deref "clojure.core" "str")) (_a$8383 "(begin ") (_a$8384 (jolt-invoke (var-deref "clojure.string" "join") " " (jolt-map emit-top-form (jolt-get node (keyword #f "statements"))))) (_a$8385 (if (jolt-empty? (jolt-get node (keyword #f "statements"))) "" " ")) (_a$8386 (emit-top-form (jolt-get node (keyword #f "ret")))) (_a$8387 ")")) (jolt-invoke _a$8382 _a$8383 _a$8384 _a$8385 _a$8386 _a$8387)) (if (let* ((and__25__auto (jolt= (keyword #f "def") (jolt-get node (keyword #f "op"))))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt-not (jolt-get node (keyword #f "no-init"))))) (if (jolt-truthy? and__25__auto) (jolt-not (jolt-invoke (var-deref "jolt.backend-scheme" "dl-opt-out?") (jolt-get node (keyword #f "meta")))) and__25__auto)) and__25__auto)) (jolt-invoke (var-deref "jolt.backend-scheme" "emit-def-cached") node) (if (jolt-truthy? (keyword #f "else")) (jolt-invoke (var-deref "jolt.backend-scheme" "emit") node) jolt-nil)))))))) emit-top-form))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.fold" "foldable" (let* ((_o$8388 "+") (_o$8389 jolt-add) (_o$8390 "-") (_o$8391 jolt-sub) (_o$8392 "*") (_o$8393 jolt-mul) (_o$8394 "/") (_o$8395 jolt-div) (_o$8396 "<") (_o$8397 jolt-lt) (_o$8398 ">") (_o$8399 jolt-gt) (_o$8400 "<=") (_o$8401 jolt-le) (_o$8402 ">=") (_o$8403 jolt-ge) (_o$8404 "=") (_o$8405 jolt=) (_o$8406 "inc") (_o$8407 jolt-inc) (_o$8408 "dec") (_o$8409 jolt-dec) (_o$8410 "mod") (_o$8411 jolt-mod) (_o$8412 "rem") (_o$8413 jolt-rem) (_o$8414 "quot") (_o$8415 jolt-quot) (_o$8416 "bit-and") (_o$8417 (var-deref "clojure.core" "__bit-and")) (_o$8418 "bit-or") (_o$8419 (var-deref "clojure.core" "__bit-or")) (_o$8420 "bit-xor") (_o$8421 (var-deref "clojure.core" "__bit-xor"))) (jolt-hash-map _o$8388 _o$8389 _o$8390 _o$8391 _o$8392 _o$8393 _o$8394 _o$8395 _o$8396 _o$8397 _o$8398 _o$8399 _o$8400 _o$8401 _o$8402 _o$8403 _o$8404 _o$8405 _o$8406 _o$8407 _o$8408 _o$8409 _o$8410 _o$8411 _o$8412 _o$8413 _o$8414 _o$8415 _o$8416 _o$8417 _o$8418 _o$8419 _o$8420 _o$8421)) (let* ((_o$8422 (keyword #f "private")) (_o$8423 #t)) (jolt-hash-map _o$8422 _o$8423)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.fold" "const?" (letrec ((const? (lambda (n) (let fnrec8424 ((n n)) (jolt= (keyword #f "const") (jolt-get n (keyword #f "op"))))))) const?) (let* ((_o$8425 (keyword #f "private")) (_o$8426 #t)) (jolt-hash-map _o$8425 _o$8426)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.fold" "const-num?" (letrec ((const-num? (lambda (n) (let fnrec8427 ((n n)) (let* ((and__25__auto (jolt-invoke (var-deref "jolt.passes.fold" "const?") n))) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "clojure.core" "number?") (jolt-get n (keyword #f "val"))) and__25__auto)))))) const-num?) (let* ((_o$8428 (keyword #f "private")) (_o$8429 #t)) (jolt-hash-map _o$8428 _o$8429)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.fold" "fold-fn" (letrec ((fold-fn (lambda (fnode) (let fnrec8430 ((fnode fnode)) (let* ((op (jolt-get fnode (keyword #f "op")))) (if (let* ((or__26__auto (let* ((and__25__auto (jolt= op (keyword #f "var")))) (if (jolt-truthy? and__25__auto) (jolt= "clojure.core" (jolt-get fnode (keyword #f "ns"))) and__25__auto)))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt= op (keyword #f "host")))) (jolt-get (var-deref "jolt.passes.fold" "foldable") (jolt-get fnode (keyword #f "name"))) jolt-nil)))))) fold-fn) (let* ((_o$8431 (keyword #f "private")) (_o$8432 #t)) (jolt-hash-map _o$8431 _o$8432)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.fold" "const-fold" (letrec ((const-fold (lambda (node) (let fnrec8433 ((node node)) (let* ((op (jolt-get node (keyword #f "op")))) (if (jolt= op (keyword #f "invoke")) (let* ((n (jolt-invoke (var-deref "jolt.ir" "map-ir-children") const-fold node)) (ff (jolt-invoke (var-deref "jolt.passes.fold" "fold-fn") (jolt-get n (keyword #f "fn")))) (args (jolt-get n (keyword #f "args"))) (folded (if (jolt-truthy? (let* ((and__25__auto ff)) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt-pos? (jolt-count args)))) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "clojure.core" "every?") (var-deref "jolt.passes.fold" "const-num?") args) and__25__auto)) and__25__auto))) (guard (_r$catch-raw1629 (else (let ((_r$catch1628 (jolt-unwrap-throw _r$catch-raw1629))) (let* ((e _r$catch1628)) jolt-nil)))) (let* ((_o$8435 (keyword #f "op")) (_o$8436 (keyword #f "const")) (_o$8437 (keyword #f "val")) (_o$8438 (jolt-apply ff (jolt-invoke (var-deref "clojure.core" "mapv") (lambda (a) (let fnrec8434 ((a a)) (jolt-get a (keyword #f "val")))) args)))) (jolt-hash-map _o$8435 _o$8436 _o$8437 _o$8438))) jolt-nil))) (let* ((or__26__auto folded)) (if (jolt-truthy? or__26__auto) or__26__auto n))) (if (jolt= op (keyword #f "if")) (let* ((t (const-fold (jolt-get node (keyword #f "test"))))) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.passes.fold" "const?") t)) (if (let* ((or__26__auto (jolt-nil? (jolt-get t (keyword #f "val"))))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt= #f (jolt-get t (keyword #f "val"))))) (const-fold (jolt-get node (keyword #f "else"))) (const-fold (jolt-get node (keyword #f "then")))) (let* ((_a$8439 node) (_a$8440 (keyword #f "test")) (_a$8441 t) (_a$8442 (keyword #f "then")) (_a$8443 (const-fold (jolt-get node (keyword #f "then")))) (_a$8444 (keyword #f "else")) (_a$8445 (const-fold (jolt-get node (keyword #f "else"))))) (jolt-assoc _a$8439 _a$8440 _a$8441 _a$8442 _a$8443 _a$8444 _a$8445)))) (if (jolt-truthy? (keyword #f "else")) (jolt-invoke (var-deref "jolt.ir" "map-ir-children") const-fold node) jolt-nil)))))))) const-fold) (let* ((_o$8446 (keyword #f "doc")) (_o$8447 "Bottom-up constant folding: a call of a foldable numeric fn whose args are\n all constant numbers becomes a constant; an if with a constant test becomes\n the taken branch.")) (jolt-hash-map _o$8446 _o$8447)))) -(guard (e (#t #f)) - (def-var! "jolt.passes.fold" "scalar-const?" (letrec ((scalar-const? (lambda (n) (let fnrec8448 ((n n)) (let* ((and__25__auto (jolt= (keyword #f "const") (jolt-get n (keyword #f "op"))))) (if (jolt-truthy? and__25__auto) (let* ((v (jolt-get n (keyword #f "val")))) (let* ((or__26__auto (jolt-invoke (var-deref "clojure.core" "keyword?") v))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt-invoke (var-deref "clojure.core" "string?") v))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt-invoke (var-deref "clojure.core" "number?") v))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-invoke (var-deref "clojure.core" "boolean?") v)))))))) and__25__auto)))))) scalar-const?))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.fold" "kw-callee?" (letrec ((kw-callee? (lambda (fnode) (let fnrec8449 ((fnode fnode)) (let* ((and__25__auto (jolt= (keyword #f "const") (jolt-get fnode (keyword #f "op"))))) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "clojure.core" "keyword?") (jolt-get fnode (keyword #f "val"))) and__25__auto)))))) kw-callee?) (let* ((_o$8450 (keyword #f "doc")) (_o$8451 "True if fnode is a constant keyword used as a function head \x2014; the (:k m) form.")) (jolt-hash-map _o$8450 _o$8451)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.fold" "get-callee?" (letrec ((get-callee? (lambda (fnode) (let fnrec8452 ((fnode fnode)) (let* ((or__26__auto (let* ((and__25__auto (jolt= (keyword #f "var") (jolt-get fnode (keyword #f "op"))))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt= "clojure.core" (jolt-get fnode (keyword #f "ns"))))) (if (jolt-truthy? and__25__auto) (jolt= "get" (jolt-get fnode (keyword #f "name"))) and__25__auto)) and__25__auto)))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((and__25__auto (jolt= (keyword #f "host") (jolt-get fnode (keyword #f "op"))))) (if (jolt-truthy? and__25__auto) (jolt= "get" (jolt-get fnode (keyword #f "name"))) and__25__auto)))))))) get-callee?) (let* ((_o$8453 (keyword #f "doc")) (_o$8454 "True if fnode is the clojure.core/get (or host get) callee \x2014; the (get m k) form.")) (jolt-hash-map _o$8453 _o$8454)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.numeric" "int-lit?" (letrec ((int-lit? (lambda (n) (let fnrec6706 ((n n)) (let* ((and__25__auto (jolt= (keyword #f "const") (jolt-get n (keyword #f "op"))))) (if (jolt-truthy? and__25__auto) (let* ((v (jolt-get n (keyword #f "val")))) (let* ((and__25__auto (jolt-invoke (var-deref "clojure.core" "number?") v))) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "clojure.core" "integer?") v) and__25__auto))) and__25__auto)))))) int-lit?) (let* ((_o$6707 (keyword #f "private")) (_o$6708 #t)) (jolt-hash-map _o$6707 _o$6708)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.numeric" "float-lit?" (letrec ((float-lit? (lambda (n) (let fnrec6709 ((n n)) (let* ((and__25__auto (jolt= (keyword #f "const") (jolt-get n (keyword #f "op"))))) (if (jolt-truthy? and__25__auto) (let* ((v (jolt-get n (keyword #f "val")))) (let* ((and__25__auto (jolt-invoke (var-deref "clojure.core" "number?") v))) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "clojure.core" "float?") v) and__25__auto))) and__25__auto)))))) float-lit?) (let* ((_o$6710 (keyword #f "private")) (_o$6711 #t)) (jolt-hash-map _o$6710 _o$6711)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.numeric" "dbl-spec" (letrec ((dbl-spec (lambda (nm n) (let fnrec6712 ((nm nm) (n n)) (if (let* ((and__25__auto (jolt-n>= n 1))) (if (jolt-truthy? and__25__auto) (jolt-contains? (let* ((_o$6713 "+") (_o$6714 "-") (_o$6715 "*") (_o$6716 "/") (_o$6717 "min") (_o$6718 "max")) (jolt-hash-set _o$6713 _o$6714 _o$6715 _o$6716 _o$6717 _o$6718)) nm) and__25__auto)) (keyword #f "double") (if (let* ((and__25__auto (jolt= n 1))) (if (jolt-truthy? and__25__auto) (jolt-contains? (let* ((_o$6719 "inc") (_o$6720 "dec")) (jolt-hash-set _o$6719 _o$6720)) nm) and__25__auto)) (keyword #f "double") (if (let* ((and__25__auto (jolt-n>= n 2))) (if (jolt-truthy? and__25__auto) (jolt-contains? (let* ((_o$6721 "<") (_o$6722 ">") (_o$6723 "<=") (_o$6724 ">=") (_o$6725 "=") (_o$6726 "==")) (jolt-hash-set _o$6721 _o$6722 _o$6723 _o$6724 _o$6725 _o$6726)) nm) and__25__auto)) (keyword #f "bool") (if (jolt-truthy? (keyword #f "else")) jolt-nil jolt-nil)))))))) dbl-spec) (let* ((_o$6727 (keyword #f "private")) (_o$6728 #t)) (jolt-hash-map _o$6727 _o$6728)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.numeric" "lng-spec" (letrec ((lng-spec (lambda (nm n) (let fnrec6729 ((nm nm) (n n)) (if (let* ((and__25__auto (jolt-n>= n 1))) (if (jolt-truthy? and__25__auto) (jolt-contains? (let* ((_o$6730 "+") (_o$6731 "-") (_o$6732 "*") (_o$6733 "min") (_o$6734 "max") (_o$6735 "unchecked-add") (_o$6736 "unchecked-subtract") (_o$6737 "unchecked-multiply")) (jolt-hash-set _o$6730 _o$6731 _o$6732 _o$6733 _o$6734 _o$6735 _o$6736 _o$6737)) nm) and__25__auto)) (keyword #f "long") (if (let* ((and__25__auto (jolt= n 1))) (if (jolt-truthy? and__25__auto) (jolt-contains? (let* ((_o$6738 "inc") (_o$6739 "dec") (_o$6740 "unchecked-inc") (_o$6741 "unchecked-dec")) (jolt-hash-set _o$6738 _o$6739 _o$6740 _o$6741)) nm) and__25__auto)) (keyword #f "long") (if (let* ((and__25__auto (jolt= n 2))) (if (jolt-truthy? and__25__auto) (jolt-contains? (let* ((_o$6742 "quot") (_o$6743 "rem") (_o$6744 "mod")) (jolt-hash-set _o$6742 _o$6743 _o$6744)) nm) and__25__auto)) (keyword #f "long") (if (let* ((and__25__auto (jolt-n>= n 2))) (if (jolt-truthy? and__25__auto) (jolt-contains? (let* ((_o$6745 "<") (_o$6746 ">") (_o$6747 "<=") (_o$6748 ">=") (_o$6749 "=") (_o$6750 "==")) (jolt-hash-set _o$6745 _o$6746 _o$6747 _o$6748 _o$6749 _o$6750)) nm) and__25__auto)) (keyword #f "bool") (if (jolt-truthy? (keyword #f "else")) jolt-nil jolt-nil))))))))) lng-spec) (let* ((_o$6751 (keyword #f "private")) (_o$6752 #t)) (jolt-hash-map _o$6751 _o$6752)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.numeric" "bd-spec" (letrec ((bd-spec (lambda (nm n) (let fnrec6753 ((nm nm) (n n)) (if (let* ((and__25__auto (jolt-n>= n 1))) (if (jolt-truthy? and__25__auto) (jolt-contains? (let* ((_o$6754 "+") (_o$6755 "-") (_o$6756 "*") (_o$6757 "/") (_o$6758 "min") (_o$6759 "max")) (jolt-hash-set _o$6754 _o$6755 _o$6756 _o$6757 _o$6758 _o$6759)) nm) and__25__auto)) (keyword #f "bigdec") (if (let* ((and__25__auto (jolt= n 2))) (if (jolt-truthy? and__25__auto) (jolt-contains? (let* ((_o$6760 "quot") (_o$6761 "rem")) (jolt-hash-set _o$6760 _o$6761)) nm) and__25__auto)) (keyword #f "bigdec") (if (let* ((and__25__auto (jolt= n 1))) (if (jolt-truthy? and__25__auto) (jolt-contains? (let* ((_o$6762 "zero?") (_o$6763 "pos?") (_o$6764 "neg?")) (jolt-hash-set _o$6762 _o$6763 _o$6764)) nm) and__25__auto)) (keyword #f "bool") (if (let* ((and__25__auto (jolt-n>= n 2))) (if (jolt-truthy? and__25__auto) (jolt-contains? (let* ((_o$6765 "<") (_o$6766 ">") (_o$6767 "<=") (_o$6768 ">=")) (jolt-hash-set _o$6765 _o$6766 _o$6767 _o$6768)) nm) and__25__auto)) (keyword #f "bool") (if (jolt-truthy? (keyword #f "else")) jolt-nil jolt-nil))))))))) bd-spec) (let* ((_o$6769 (keyword #f "private")) (_o$6770 #t)) (jolt-hash-map _o$6769 _o$6770)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.numeric" "propagate" (letrec ((propagate (lambda (spec) (let fnrec6771 ((spec spec)) (if (jolt= spec (keyword #f "bool")) jolt-nil spec))))) propagate) (let* ((_o$6772 (keyword #f "private")) (_o$6773 #t)) (jolt-hash-map _o$6772 _o$6773)))) -(guard (e (#t #f)) - (declare-var! "jolt.passes.numeric" "an")) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.numeric" "recur-kinds" (letrec ((recur-kinds (lambda (node tenv) (let fnrec6774 ((node node) (tenv tenv)) (let* ((op (jolt-get node (keyword #f "op")))) (if (jolt= op (keyword #f "recur")) (jolt-vector (let* ((_a$6776 (var-deref "clojure.core" "mapv")) (_a$6777 (lambda (a) (let fnrec6775 ((a a)) (jolt-nth (jolt-invoke (var-deref "jolt.passes.numeric" "an") a tenv) 0)))) (_a$6778 (jolt-get node (keyword #f "args")))) (jolt-invoke _a$6776 _a$6777 _a$6778))) (if (jolt= op (keyword #f "let")) (let* ((_a$6786 (jolt-get node (keyword #f "body"))) (_a$6787 (let* ((_a$6783 (lambda (te b) (let fnrec6779 ((te te) (b b)) (let* ((_a$6780 te) (_a$6781 (jolt-nth b 0)) (_a$6782 (jolt-nth (jolt-invoke (var-deref "jolt.passes.numeric" "an") (jolt-nth b 1) te) 0))) (jolt-assoc _a$6780 _a$6781 _a$6782))))) (_a$6784 tenv) (_a$6785 (jolt-get node (keyword #f "bindings")))) (jolt-reduce _a$6783 _a$6784 _a$6785)))) (recur-kinds _a$6786 _a$6787)) (if (jolt= op (keyword #f "if")) (let* ((_a$6788 (recur-kinds (jolt-get node (keyword #f "then")) tenv)) (_a$6789 (recur-kinds (jolt-get node (keyword #f "else")) tenv))) (jolt-concat _a$6788 _a$6789)) (if (jolt= op (keyword #f "do")) (recur-kinds (jolt-get node (keyword #f "ret")) tenv) (if (jolt-truthy? (keyword #f "else")) (jolt-vector) jolt-nil)))))))))) recur-kinds) (let* ((_o$6790 (keyword #f "private")) (_o$6791 #t)) (jolt-hash-map _o$6790 _o$6791)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.numeric" "recur-arg-lists" (letrec ((recur-arg-lists (lambda (node) (let fnrec6792 ((node node)) (let* ((op (jolt-get node (keyword #f "op")))) (if (jolt= op (keyword #f "recur")) (jolt-vector (jolt-get node (keyword #f "args"))) (if (jolt= op (keyword #f "let")) (recur-arg-lists (jolt-get node (keyword #f "body"))) (if (jolt= op (keyword #f "if")) (let* ((_a$6793 (recur-arg-lists (jolt-get node (keyword #f "then")))) (_a$6794 (recur-arg-lists (jolt-get node (keyword #f "else"))))) (jolt-concat _a$6793 _a$6794)) (if (jolt= op (keyword #f "do")) (recur-arg-lists (jolt-get node (keyword #f "ret"))) (if (jolt-truthy? (keyword #f "else")) (jolt-vector) jolt-nil)))))))))) recur-arg-lists) (let* ((_o$6795 (keyword #f "private")) (_o$6796 #t)) (jolt-hash-map _o$6795 _o$6796)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.numeric" "counter-step?" (letrec ((counter-step? (lambda (arg vname) (let fnrec6797 ((arg arg) (vname vname)) (if (let* ((and__25__auto (jolt= (keyword #f "local") (jolt-get arg (keyword #f "op"))))) (if (jolt-truthy? and__25__auto) (jolt= vname (jolt-get arg (keyword #f "name"))) and__25__auto)) #t (if (jolt= (keyword #f "invoke") (jolt-get arg (keyword #f "op"))) (let* ((f (jolt-get arg (keyword #f "fn"))) (as (jolt-get arg (keyword #f "args")))) (let* ((and__25__auto (jolt= (keyword #f "var") (jolt-get f (keyword #f "op"))))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt= "clojure.core" (jolt-get f (keyword #f "ns"))))) (if (jolt-truthy? and__25__auto) (let* ((nm (jolt-get f (keyword #f "name"))) (v? (lambda (n) (let fnrec6798 ((n n)) (let* ((and__25__auto (jolt= (keyword #f "local") (jolt-get n (keyword #f "op"))))) (if (jolt-truthy? and__25__auto) (jolt= vname (jolt-get n (keyword #f "name"))) and__25__auto)))))) (if (let* ((and__25__auto (jolt-contains? (let* ((_o$6799 "inc") (_o$6800 "dec") (_o$6801 "unchecked-inc") (_o$6802 "unchecked-dec")) (jolt-hash-set _o$6799 _o$6800 _o$6801 _o$6802)) nm))) (if (jolt-truthy? and__25__auto) (jolt= 1 (jolt-count as)) and__25__auto)) (jolt-invoke v? (jolt-nth as 0)) (if (let* ((and__25__auto (jolt-contains? (let* ((_o$6803 "+") (_o$6804 "unchecked-add")) (jolt-hash-set _o$6803 _o$6804)) nm))) (if (jolt-truthy? and__25__auto) (jolt= 2 (jolt-count as)) and__25__auto)) (let* ((or__26__auto (let* ((and__25__auto (jolt-invoke v? (jolt-nth as 0)))) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "jolt.passes.numeric" "int-lit?") (jolt-nth as 1)) and__25__auto)))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((and__25__auto (jolt-invoke v? (jolt-nth as 1)))) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "jolt.passes.numeric" "int-lit?") (jolt-nth as 0)) and__25__auto)))) (if (let* ((and__25__auto (jolt-contains? (let* ((_o$6805 "-") (_o$6806 "unchecked-subtract")) (jolt-hash-set _o$6805 _o$6806)) nm))) (if (jolt-truthy? and__25__auto) (jolt= 2 (jolt-count as)) and__25__auto)) (let* ((and__25__auto (jolt-invoke v? (jolt-nth as 0)))) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "jolt.passes.numeric" "int-lit?") (jolt-nth as 1)) and__25__auto)) (if (jolt-truthy? (keyword #f "else")) #f jolt-nil))))) and__25__auto)) and__25__auto))) (if (jolt-truthy? (keyword #f "else")) #f jolt-nil))))))) counter-step?) (let* ((_o$6807 (keyword #f "private")) (_o$6808 #t)) (jolt-hash-map _o$6807 _o$6808)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.numeric" "loop-kinds" (letrec ((loop-kinds (lambda (names seed body tenv) (let fnrec6809 ((names names) (seed seed) (body body) (tenv tenv)) (let* ((cur seed) (iter 0)) (let loop6810 ((cur cur) (iter iter)) (if (jolt-n> iter (jolt-count names)) cur (let* ((te (let* ((_a$6815 (lambda (t i) (let fnrec6811 ((t t) (i i)) (let* ((_a$6812 t) (_a$6813 (jolt-nth names i)) (_a$6814 (jolt-nth cur i))) (jolt-assoc _a$6812 _a$6813 _a$6814))))) (_a$6816 tenv) (_a$6817 (jolt-range (jolt-count names)))) (jolt-reduce _a$6815 _a$6816 _a$6817))) (rks (jolt-invoke (var-deref "jolt.passes.numeric" "recur-kinds") body te)) (nxt (let* ((_a$6820 (var-deref "clojure.core" "mapv")) (_a$6821 (lambda (j) (let fnrec6818 ((j j)) (let* ((k (jolt-nth cur j))) (if (jolt-truthy? (let* ((and__25__auto k)) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "clojure.core" "every?") (lambda (rk) (let fnrec6819 ((rk rk)) (jolt= k (jolt-nth rk j)))) rks) and__25__auto))) k jolt-nil))))) (_a$6822 (jolt-range (jolt-count names)))) (jolt-invoke _a$6820 _a$6821 _a$6822)))) (if (jolt= nxt cur) cur (loop6810 nxt (jolt-inc iter))))))))))) loop-kinds) (let* ((_o$6823 (keyword #f "private")) (_o$6824 #t)) (jolt-hash-map _o$6823 _o$6824)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.numeric" "arity-env" (letrec ((arity-env (lambda (tenv a) (let fnrec6825 ((tenv tenv) (a a)) (let* ((nh (let* ((_a$6826 (jolt-hash-map)) (_a$6827 (jolt-get a (keyword #f "nhints")))) (jolt-into _a$6826 _a$6827))) (pe (let* ((_a$6829 (lambda (e p) (let fnrec6828 ((e e) (p p)) (jolt-assoc e p (jolt-get nh p))))) (_a$6830 tenv) (_a$6831 (jolt-get a (keyword #f "params")))) (jolt-reduce _a$6829 _a$6830 _a$6831)))) (if (jolt-truthy? (jolt-get a (keyword #f "rest"))) (jolt-assoc pe (jolt-get a (keyword #f "rest")) jolt-nil) pe)))))) arity-env) (let* ((_o$6832 (keyword #f "private")) (_o$6833 #t)) (jolt-hash-map _o$6832 _o$6833)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.numeric" "an-invoke" (letrec ((an-invoke (lambda (node tenv) (let fnrec6834 ((node node) (tenv tenv)) (let* ((fnode (jolt-get node (keyword #f "fn"))) (nm (if (let* ((and__25__auto (jolt= (keyword #f "var") (jolt-get fnode (keyword #f "op"))))) (if (jolt-truthy? and__25__auto) (jolt= "clojure.core" (jolt-get fnode (keyword #f "ns"))) and__25__auto)) (jolt-get fnode (keyword #f "name")) jolt-nil)) (ars (let* ((_a$6836 (var-deref "clojure.core" "mapv")) (_a$6837 (lambda (a) (let fnrec6835 ((a a)) (jolt-invoke (var-deref "jolt.passes.numeric" "an") a tenv)))) (_a$6838 (jolt-get node (keyword #f "args")))) (jolt-invoke _a$6836 _a$6837 _a$6838))) (argnodes (jolt-invoke (var-deref "clojure.core" "mapv") (lambda (r) (let fnrec6839 ((r r)) (jolt-nth r 1))) ars)) (node1 (jolt-assoc node (keyword #f "args") argnodes)) (n (jolt-count ars))) (if (jolt= (keyword #f "double") (jolt-get node (keyword #f "num-read"))) (let* ((_o$6840 (keyword #f "double")) (_o$6841 node1)) (jolt-vector _o$6840 _o$6841)) (if (jolt-truthy? (jolt-get fnode (keyword #f "num-ret"))) (let* ((_o$6842 (jolt-get fnode (keyword #f "num-ret"))) (_o$6843 node1)) (jolt-vector _o$6842 _o$6843)) (if (jolt-nil? nm) (let* ((_o$6844 jolt-nil) (_o$6845 node1)) (jolt-vector _o$6844 _o$6845)) (if (jolt-truthy? (keyword #f "else")) (let* ((cls (jolt-invoke (var-deref "clojure.core" "mapv") (lambda (r) (let fnrec6846 ((r r)) (let* ((k (jolt-nth r 0)) (nd (jolt-nth r 1))) (if (jolt= k (keyword #f "double")) (keyword #f "double") (if (jolt= k (keyword #f "long")) (keyword #f "long") (if (jolt= k (keyword #f "bigdec")) (keyword #f "bigdec") (if (jolt-truthy? (jolt-invoke (var-deref "jolt.passes.numeric" "int-lit?") nd)) (keyword #f "wild") (if (jolt-truthy? (keyword #f "else")) (keyword #f "no") jolt-nil)))))))) ars)) (ok? (lambda (allowed need) (let fnrec6847 ((allowed allowed) (need need)) (let* ((and__25__auto (jolt-pos? n))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt-invoke (var-deref "clojure.core" "every?") (lambda (c) (let fnrec6848 ((c c)) (let* ((or__26__auto (jolt= c (keyword #f "wild")))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt= c allowed))))) cls))) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "clojure.core" "some") (lambda (c) (let fnrec6849 ((c c)) (jolt= c need))) cls) and__25__auto)) and__25__auto))))) (ds (jolt-invoke (var-deref "jolt.passes.numeric" "dbl-spec") nm n)) (ls (jolt-invoke (var-deref "jolt.passes.numeric" "lng-spec") nm n)) (bs (jolt-invoke (var-deref "jolt.passes.numeric" "bd-spec") nm n))) (if (jolt-truthy? (let* ((and__25__auto ds)) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt-invoke ok? (keyword #f "double") (keyword #f "double")))) (if (jolt-truthy? and__25__auto) (let* ((or__26__auto (jolt-not (jolt-contains? (let* ((_o$6850 "min") (_o$6851 "max")) (jolt-hash-set _o$6850 _o$6851)) nm)))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-invoke (var-deref "clojure.core" "every?") (lambda (c) (let fnrec6852 ((c c)) (jolt= c (keyword #f "double")))) cls))) and__25__auto)) and__25__auto))) (let* ((args_PRIME_ (jolt-invoke (var-deref "clojure.core" "mapv") (lambda (nd) (let fnrec6853 ((nd nd)) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.passes.numeric" "int-lit?") nd)) (jolt-assoc nd (keyword #f "val") (jolt-invoke (var-deref "clojure.core" "double") (jolt-get nd (keyword #f "val")))) nd))) argnodes))) (let* ((_o$6854 (jolt-invoke (var-deref "jolt.passes.numeric" "propagate") ds)) (_o$6855 (jolt-assoc node1 (keyword #f "args") args_PRIME_ (keyword #f "num-kind") (keyword #f "double")))) (jolt-vector _o$6854 _o$6855))) (if (jolt-truthy? (let* ((and__25__auto ls)) (if (jolt-truthy? and__25__auto) (jolt-invoke ok? (keyword #f "long") (keyword #f "long")) and__25__auto))) (let* ((_o$6856 (jolt-invoke (var-deref "jolt.passes.numeric" "propagate") ls)) (_o$6857 (jolt-assoc node1 (keyword #f "num-kind") (keyword #f "long")))) (jolt-vector _o$6856 _o$6857)) (if (jolt-truthy? (let* ((and__25__auto bs)) (if (jolt-truthy? and__25__auto) (jolt-invoke ok? (keyword #f "bigdec") (keyword #f "bigdec")) and__25__auto))) (let* ((_o$6858 (jolt-invoke (var-deref "jolt.passes.numeric" "propagate") bs)) (_o$6859 (jolt-assoc node1 (keyword #f "num-kind") (keyword #f "bigdec")))) (jolt-vector _o$6858 _o$6859)) (if (jolt-truthy? (keyword #f "else")) (let* ((_o$6860 jolt-nil) (_o$6861 node1)) (jolt-vector _o$6860 _o$6861)) jolt-nil))))) jolt-nil))))))))) an-invoke) (let* ((_o$6862 (keyword #f "private")) (_o$6863 #t) (_o$6864 (keyword #f "doc")) (_o$6865 "Annotate an :invoke with its numeric kind. An arithmetic core op specializes to\n the Chez fl*/fx* op only when every operand is the same kind (:double or :long),\n except an integer literal is :wild \x2014; valid in either \x2014; so (+ ^double x 2) stays\n double. A call to a ^double/^long-returning var yields that kind without lowering\n the call (its body already coerces the return).")) (jolt-hash-map _o$6862 _o$6863 _o$6864 _o$6865)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.numeric" "an" (letrec ((an (lambda (node tenv) (let fnrec6866 ((node node) (tenv tenv)) (let* ((op (jolt-get node (keyword #f "op")))) (if (jolt= op (keyword #f "const")) (let* ((_o$6867 (if (jolt-truthy? (jolt-invoke (var-deref "jolt.passes.numeric" "float-lit?") node)) (keyword #f "double") jolt-nil)) (_o$6868 node)) (jolt-vector _o$6867 _o$6868)) (if (jolt= op (keyword #f "bigdec")) (let* ((_o$6869 (keyword #f "bigdec")) (_o$6870 node)) (jolt-vector _o$6869 _o$6870)) (if (jolt= op (keyword #f "local")) (let* ((_o$6871 (jolt-get tenv (jolt-get node (keyword #f "name")))) (_o$6872 node)) (jolt-vector _o$6871 _o$6872)) (if (jolt= op (keyword #f "coerce")) (let* ((_o$6873 (jolt-get node (keyword #f "kind"))) (_o$6874 (jolt-assoc node (keyword #f "expr") (jolt-nth (an (jolt-get node (keyword #f "expr")) tenv) 1)))) (jolt-vector _o$6873 _o$6874)) (if (jolt= op (keyword #f "invoke")) (jolt-invoke (var-deref "jolt.passes.numeric" "an-invoke") node tenv) (if (jolt= op (keyword #f "let")) (let* ((res (let* ((_a$6885 (lambda (acc b) (let fnrec6875 ((acc acc) (b b)) (let* ((te (jolt-nth acc 0)) (binds (jolt-nth acc 1)) (ir (an (jolt-nth b 1) te))) (let* ((_o$6881 (let* ((_a$6876 te) (_a$6877 (jolt-nth b 0)) (_a$6878 (jolt-nth ir 0))) (jolt-assoc _a$6876 _a$6877 _a$6878))) (_o$6882 (jolt-conj binds (let* ((_o$6879 (jolt-nth b 0)) (_o$6880 (jolt-nth ir 1))) (jolt-vector _o$6879 _o$6880))))) (jolt-vector _o$6881 _o$6882)))))) (_a$6886 (let* ((_o$6883 tenv) (_o$6884 (jolt-vector))) (jolt-vector _o$6883 _o$6884))) (_a$6887 (jolt-get node (keyword #f "bindings")))) (jolt-reduce _a$6885 _a$6886 _a$6887))) (br (let* ((_a$6888 (jolt-get node (keyword #f "body"))) (_a$6889 (jolt-nth res 0))) (an _a$6888 _a$6889)))) (let* ((_o$6895 (jolt-nth br 0)) (_o$6896 (let* ((_a$6890 node) (_a$6891 (keyword #f "bindings")) (_a$6892 (jolt-nth res 1)) (_a$6893 (keyword #f "body")) (_a$6894 (jolt-nth br 1))) (jolt-assoc _a$6890 _a$6891 _a$6892 _a$6893 _a$6894)))) (jolt-vector _o$6895 _o$6896))) (if (jolt= op (keyword #f "loop")) (let* ((binds (jolt-get node (keyword #f "bindings"))) (names (jolt-invoke (var-deref "clojure.core" "mapv") (lambda (b) (let fnrec6897 ((b b)) (jolt-nth b 0))) binds)) (ik (jolt-invoke (var-deref "clojure.core" "mapv") (lambda (b) (let fnrec6898 ((b b)) (jolt-nth (an (jolt-nth b 1) tenv) 0))) binds)) (rlists (jolt-invoke (var-deref "jolt.passes.numeric" "recur-arg-lists") (jolt-get node (keyword #f "body")))) (seed (let* ((_a$6904 (var-deref "clojure.core" "mapv")) (_a$6905 (lambda (j) (let fnrec6899 ((j j)) (let* ((k (jolt-nth ik j)) (b (jolt-nth binds j))) (if (jolt-truthy? k) k (if (jolt-truthy? (let* ((and__25__auto (jolt-seq rlists))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt-invoke (var-deref "jolt.passes.numeric" "int-lit?") (jolt-nth b 1)))) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "clojure.core" "every?") (lambda (args) (let fnrec6900 ((args args)) (let* ((_a$6901 (var-deref "jolt.passes.numeric" "counter-step?")) (_a$6902 (jolt-nth args j)) (_a$6903 (jolt-nth b 0))) (jolt-invoke _a$6901 _a$6902 _a$6903)))) rlists) and__25__auto)) and__25__auto))) (keyword #f "long") (if (jolt-truthy? (keyword #f "else")) jolt-nil jolt-nil))))))) (_a$6906 (jolt-range (jolt-count names)))) (jolt-invoke _a$6904 _a$6905 _a$6906))) (lk (jolt-invoke (var-deref "jolt.passes.numeric" "loop-kinds") names seed (jolt-get node (keyword #f "body")) tenv)) (te (let* ((_a$6911 (lambda (t i) (let fnrec6907 ((t t) (i i)) (let* ((_a$6908 t) (_a$6909 (jolt-nth names i)) (_a$6910 (jolt-nth lk i))) (jolt-assoc _a$6908 _a$6909 _a$6910))))) (_a$6912 tenv) (_a$6913 (jolt-range (jolt-count names)))) (jolt-reduce _a$6911 _a$6912 _a$6913)))) (let* ((_o$6922 jolt-nil) (_o$6923 (let* ((_a$6917 node) (_a$6918 (keyword #f "bindings")) (_a$6919 (jolt-invoke (var-deref "clojure.core" "mapv") (lambda (b) (let fnrec6914 ((b b)) (let* ((_o$6915 (jolt-nth b 0)) (_o$6916 (jolt-nth (an (jolt-nth b 1) tenv) 1))) (jolt-vector _o$6915 _o$6916)))) binds)) (_a$6920 (keyword #f "body")) (_a$6921 (jolt-nth (an (jolt-get node (keyword #f "body")) te) 1))) (jolt-assoc _a$6917 _a$6918 _a$6919 _a$6920 _a$6921)))) (jolt-vector _o$6922 _o$6923))) (if (jolt= op (keyword #f "if")) (let* ((tr (an (jolt-get node (keyword #f "test")) tenv)) (thn (an (jolt-get node (keyword #f "then")) tenv)) (els (an (jolt-get node (keyword #f "else")) tenv)) (tk (jolt-nth thn 0)) (ek (jolt-nth els 0))) (let* ((_o$6931 (if (jolt= tk ek) tk jolt-nil)) (_o$6932 (let* ((_a$6924 node) (_a$6925 (keyword #f "test")) (_a$6926 (jolt-nth tr 1)) (_a$6927 (keyword #f "then")) (_a$6928 (jolt-nth thn 1)) (_a$6929 (keyword #f "else")) (_a$6930 (jolt-nth els 1))) (jolt-assoc _a$6924 _a$6925 _a$6926 _a$6927 _a$6928 _a$6929 _a$6930)))) (jolt-vector _o$6931 _o$6932))) (if (jolt= op (keyword #f "do")) (let* ((stmts (let* ((_a$6934 (var-deref "clojure.core" "mapv")) (_a$6935 (lambda (s) (let fnrec6933 ((s s)) (jolt-nth (an s tenv) 1)))) (_a$6936 (jolt-get node (keyword #f "statements")))) (jolt-invoke _a$6934 _a$6935 _a$6936))) (r (an (jolt-get node (keyword #f "ret")) tenv))) (let* ((_o$6937 (jolt-nth r 0)) (_o$6938 (jolt-assoc node (keyword #f "statements") stmts (keyword #f "ret") (jolt-nth r 1)))) (jolt-vector _o$6937 _o$6938))) (if (jolt= op (keyword #f "fn")) (let* ((_o$6945 jolt-nil) (_o$6946 (jolt-assoc node (keyword #f "arities") (let* ((_a$6942 (var-deref "clojure.core" "mapv")) (_a$6943 (lambda (a) (let fnrec6939 ((a a)) (jolt-assoc a (keyword #f "body") (jolt-nth (let* ((_a$6940 (jolt-get a (keyword #f "body"))) (_a$6941 (jolt-invoke (var-deref "jolt.passes.numeric" "arity-env") tenv a))) (an _a$6940 _a$6941)) 1))))) (_a$6944 (jolt-get node (keyword #f "arities")))) (jolt-invoke _a$6942 _a$6943 _a$6944))))) (jolt-vector _o$6945 _o$6946)) (if (jolt= op (keyword #f "def")) (let* ((_o$6947 jolt-nil) (_o$6948 (jolt-assoc node (keyword #f "init") (jolt-nth (an (jolt-get node (keyword #f "init")) tenv) 1)))) (jolt-vector _o$6947 _o$6948)) (if (jolt-truthy? (keyword #f "else")) (let* ((_o$6950 jolt-nil) (_o$6951 (jolt-invoke (var-deref "jolt.ir" "map-ir-children") (lambda (c) (let fnrec6949 ((c c)) (jolt-nth (an c tenv) 1))) node))) (jolt-vector _o$6950 _o$6951)) jolt-nil))))))))))))))))) an) (let* ((_o$6952 (keyword #f "private")) (_o$6953 #t)) (jolt-hash-map _o$6952 _o$6953)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.numeric" "annotate" (letrec ((annotate (lambda (node) (let fnrec6954 ((node node)) (jolt-nth (jolt-invoke (var-deref "jolt.passes.numeric" "an") node (jolt-hash-map)) 1))))) annotate) (let* ((_o$6955 (keyword #f "doc")) (_o$6956 "Tag arithmetic nodes with :num-kind from local numeric type-flow. Returns the\n rewritten IR (no kind escapes to the caller).")) (jolt-hash-map _o$6955 _o$6956)))) -(guard (e (#t #f)) - (def-var! "jolt.passes.inline" "dirty" (jolt-invoke (var-deref "clojure.core" "atom") #f))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.inline" "mark!" (letrec ((mark! (lambda () (let fnrec6957 () (jolt-invoke (var-deref "clojure.core" "reset!") (var-deref "jolt.passes.inline" "dirty") #t))))) mark!) (let* ((_o$6958 (keyword #f "private")) (_o$6959 #t)) (jolt-hash-map _o$6958 _o$6959)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.inline" "rec-shapes" (jolt-invoke (var-deref "clojure.core" "atom") (jolt-hash-map)) (let* ((_o$6960 (keyword #f "private")) (_o$6961 #t)) (jolt-hash-map _o$6960 _o$6961)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.inline" "set-rec-shapes!" (letrec ((set-rec-shapes! (lambda (m) (let fnrec6962 ((m m)) (jolt-invoke (var-deref "clojure.core" "reset!") (var-deref "jolt.passes.inline" "rec-shapes") (let* ((or__26__auto m)) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-hash-map)))))))) set-rec-shapes!) (let* ((_o$6963 (keyword #f "doc")) (_o$6964 "Install the record-ctor shape registry the record fold consults.")) (jolt-hash-map _o$6963 _o$6964)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.inline" "fresh-counter" (jolt-invoke (var-deref "clojure.core" "atom") 0) (let* ((_o$6965 (keyword #f "private")) (_o$6966 #t)) (jolt-hash-map _o$6965 _o$6966)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.inline" "fresh" (letrec ((fresh (lambda (base) (let fnrec6967 ((base base)) (let* ((n (jolt-invoke (var-deref "clojure.core" "deref") (var-deref "jolt.passes.inline" "fresh-counter")))) (begin (jolt-invoke (var-deref "clojure.core" "swap!") (var-deref "jolt.passes.inline" "fresh-counter") jolt-inc) (jolt-invoke (var-deref "clojure.core" "str") base "__il" n))))))) fresh) (let* ((_o$6968 (keyword #f "private")) (_o$6969 #t)) (jolt-hash-map _o$6968 _o$6969)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.inline" "safe-op?" (letrec ((safe-op? (lambda (op) (let fnrec6970 ((op op)) (let* ((or__26__auto (jolt= op (keyword #f "const")))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt= op (keyword #f "local")))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt= op (keyword #f "var")))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt= op (keyword #f "host")))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt= op (keyword #f "the-var")))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt= op (keyword #f "quote")))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt= op (keyword #f "if")))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt= op (keyword #f "do")))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt= op (keyword #f "let")))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt= op (keyword #f "invoke")))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt= op (keyword #f "map")))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt= op (keyword #f "vector")))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt= op (keyword #f "set")))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt= op (keyword #f "throw")))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt= op (keyword #f "coerce")))))))))))))))))))))))))))))))))) safe-op?) (let* ((_o$6971 (keyword #f "private")) (_o$6972 #t)) (jolt-hash-map _o$6971 _o$6972)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.inline" "inline-budget" 120 (let* ((_o$6973 (keyword #f "private")) (_o$6974 #t)) (jolt-hash-map _o$6973 _o$6974)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.inline" "body-size" (letrec ((body-size (lambda (node) (let fnrec6975 ((node node)) (if (jolt-not (jolt-invoke (var-deref "jolt.passes.inline" "safe-op?") (jolt-get node (keyword #f "op")))) 100000 (jolt-invoke (var-deref "jolt.ir" "reduce-ir-children") (lambda (acc c) (let fnrec6976 ((acc acc) (c c)) (jolt-n+ acc (body-size c)))) 1 node)))))) body-size) (let* ((_o$6977 (keyword #f "private")) (_o$6978 #t) (_o$6979 (keyword #f "doc")) (_o$6980 "Node count of an inline-eligible body. A disallowed op contributes a number\n larger than any budget, so the caller's (<= size budget) test fails and we\n never try to inline (or alpha-rename) such a body. Only reached for safe ops,\n so the shared child fold covers it exactly (leaves fold to 1).")) (jolt-hash-map _o$6977 _o$6978 _o$6979 _o$6980)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.inline" "subst" (letrec ((subst (lambda (node env) (let fnrec6981 ((node node) (env env)) (let* ((op (jolt-get node (keyword #f "op")))) (if (jolt= op (keyword #f "local")) (let* ((r (jolt-get env (jolt-get node (keyword #f "name"))))) (if (jolt-truthy? r) (if (jolt-truthy? (let* ((and__25__auto (jolt= (keyword #f "local") (jolt-get r (keyword #f "op"))))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt-get node (keyword #f "hint")))) (if (jolt-truthy? and__25__auto) (jolt-not (jolt-get r (keyword #f "hint"))) and__25__auto)) and__25__auto))) (jolt-assoc r (keyword #f "hint") (jolt-get node (keyword #f "hint"))) r) node)) (if (jolt= op (keyword #f "let")) (let* ((res (let* ((_a$6993 (lambda (acc b) (let fnrec6982 ((acc acc) (b b)) (let* ((e (jolt-nth acc 0)) (binds (jolt-nth acc 1)) (nm (jolt-nth b 0)) (init (subst (jolt-nth b 1) e)) (f (jolt-invoke (var-deref "jolt.passes.inline" "fresh") nm))) (let* ((_o$6989 (jolt-assoc e nm (let* ((_o$6983 (keyword #f "op")) (_o$6984 (keyword #f "local")) (_o$6985 (keyword #f "name")) (_o$6986 f)) (jolt-hash-map _o$6983 _o$6984 _o$6985 _o$6986)))) (_o$6990 (jolt-conj binds (let* ((_o$6987 f) (_o$6988 init)) (jolt-vector _o$6987 _o$6988))))) (jolt-vector _o$6989 _o$6990)))))) (_a$6994 (let* ((_o$6991 env) (_o$6992 (jolt-vector))) (jolt-vector _o$6991 _o$6992))) (_a$6995 (jolt-get node (keyword #f "bindings")))) (jolt-reduce _a$6993 _a$6994 _a$6995)))) (let* ((_a$6998 node) (_a$6999 (keyword #f "bindings")) (_a$7000 (jolt-nth res 1)) (_a$7001 (keyword #f "body")) (_a$7002 (let* ((_a$6996 (jolt-get node (keyword #f "body"))) (_a$6997 (jolt-nth res 0))) (subst _a$6996 _a$6997)))) (jolt-assoc _a$6998 _a$6999 _a$7000 _a$7001 _a$7002))) (if (jolt-truthy? (keyword #f "else")) (jolt-invoke (var-deref "jolt.ir" "map-ir-children") (lambda (c) (let fnrec7003 ((c c)) (subst c env))) node) jolt-nil)))))))) subst) (let* ((_o$7004 (keyword #f "private")) (_o$7005 #t) (_o$7006 (keyword #f "doc")) (_o$7007 "Substitute locals in node per env (a map name -> replacement IR node), and\n alpha-rename every inner :let binder to a globally fresh name (so the spliced\n body shares no name with the caller). env seeds the params: a trivial arg\n (local/const) maps a param straight to the arg node (copy propagation \x2014; this\n is what lets scalar-replace see a map-literal arg through the call boundary);\n a non-trivial arg maps the param to a fresh :local that a wrapping let binds.")) (jolt-hash-map _o$7004 _o$7005 _o$7006 _o$7007)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.inline" "trivial-arg?" (letrec ((trivial-arg? (lambda (n) (let fnrec7008 ((n n)) (let* ((op (jolt-get n (keyword #f "op")))) (let* ((or__26__auto (jolt= op (keyword #f "local")))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt= op (keyword #f "const"))))))))) trivial-arg?) (let* ((_o$7009 (keyword #f "private")) (_o$7010 #t)) (jolt-hash-map _o$7009 _o$7010)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.inline" "body-closed?" (letrec ((body-closed? (lambda (node scope) (let fnrec7011 ((node node) (scope scope)) (let* ((op (jolt-get node (keyword #f "op")))) (if (jolt= op (keyword #f "local")) (jolt-contains? scope (jolt-get node (keyword #f "name"))) (if (jolt= op (keyword #f "let")) (let* ((res (let* ((_a$7017 (lambda (acc b) (let fnrec7012 ((acc acc) (b b)) (let* ((sc (jolt-nth acc 0)) (ok (jolt-nth acc 1))) (if (jolt-not ok) acc (let* ((_o$7013 (jolt-conj sc (jolt-nth b 0))) (_o$7014 (body-closed? (jolt-nth b 1) sc))) (jolt-vector _o$7013 _o$7014))))))) (_a$7018 (let* ((_o$7015 scope) (_o$7016 #t)) (jolt-vector _o$7015 _o$7016))) (_a$7019 (jolt-get node (keyword #f "bindings")))) (jolt-reduce _a$7017 _a$7018 _a$7019)))) (let* ((and__25__auto (jolt-nth res 1))) (if (jolt-truthy? and__25__auto) (let* ((_a$7020 (jolt-get node (keyword #f "body"))) (_a$7021 (jolt-nth res 0))) (body-closed? _a$7020 _a$7021)) and__25__auto))) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.passes.inline" "safe-op?") op)) (jolt-invoke (var-deref "jolt.ir" "reduce-ir-children") (lambda (ok c) (let fnrec7022 ((ok ok) (c c)) (let* ((and__25__auto ok)) (if (jolt-truthy? and__25__auto) (body-closed? c scope) and__25__auto)))) #t node) (if (jolt-truthy? (keyword #f "else")) #f jolt-nil))))))))) body-closed?) (let* ((_o$7023 (keyword #f "private")) (_o$7024 #t) (_o$7025 (keyword #f "doc")) (_o$7026 "True if every :local in node is bound \x2014; by a param (in the initial scope set)\n or by an enclosing :let within the body. A self-recursive fn fails this: the\n analyzer binds the fn's own name as a local, so its body has a FREE local (the\n self-reference) that would dangle once the body is spliced elsewhere.")) (jolt-hash-map _o$7023 _o$7024 _o$7025 _o$7026)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.inline" "try-inline" (letrec ((try-inline (lambda (node ctx) (let fnrec7027 ((node node) (ctx ctx)) (let* ((f (jolt-get node (keyword #f "fn")))) (if (jolt= (keyword #f "var") (jolt-get f (keyword #f "op"))) (let* ((stash (let* ((_a$7028 (var-deref "jolt.host" "inline-ir")) (_a$7029 ctx) (_a$7030 (jolt-get f (keyword #f "ns"))) (_a$7031 (jolt-get f (keyword #f "name")))) (jolt-invoke _a$7028 _a$7029 _a$7030 _a$7031)))) (if (jolt-truthy? stash) (let* ((params (jolt-get stash (keyword #f "params"))) (body (jolt-get stash (keyword #f "body"))) (nh (let* ((_a$7036 (lambda (m pr) (let fnrec7032 ((m m) (pr pr)) (let* ((_a$7033 m) (_a$7034 (jolt-nth pr 0)) (_a$7035 (jolt-nth pr 1))) (jolt-assoc _a$7033 _a$7034 _a$7035))))) (_a$7037 (jolt-hash-map)) (_a$7038 (jolt-get stash (keyword #f "nhints")))) (jolt-reduce _a$7036 _a$7037 _a$7038))) (ret (jolt-get stash (keyword #f "ret"))) (args (jolt-get node (keyword #f "args")))) (if (jolt-truthy? (let* ((and__25__auto (let* ((_a$7039 (jolt-count params)) (_a$7040 (jolt-count args))) (jolt= _a$7039 _a$7040)))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt-n<= (jolt-invoke (var-deref "jolt.passes.inline" "body-size") body) (var-deref "jolt.passes.inline" "inline-budget")))) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "jolt.passes.inline" "body-closed?") body (jolt-reduce jolt-conj (jolt-hash-set) params)) and__25__auto)) and__25__auto))) (let* ((n (jolt-count params)) (res (let* ((i 0) (env (jolt-hash-map)) (binds (jolt-vector))) (let loop7041 ((i i) (env env) (binds binds)) (if (jolt-n< i n) (let* ((p (jolt-nth params i)) (a (jolt-nth args i)) (k (jolt-get nh p))) (if (jolt-truthy? k) (let* ((f (jolt-invoke (var-deref "jolt.passes.inline" "fresh") p))) (let* ((_a$7048 (jolt-inc i)) (_a$7049 (jolt-assoc env p (let* ((_o$7042 (keyword #f "op")) (_o$7043 (keyword #f "local")) (_o$7044 (keyword #f "name")) (_o$7045 f)) (jolt-hash-map _o$7042 _o$7043 _o$7044 _o$7045)))) (_a$7050 (jolt-conj binds (let* ((_o$7046 f) (_o$7047 (jolt-invoke (var-deref "jolt.ir" "coerce-node") k a))) (jolt-vector _o$7046 _o$7047))))) (loop7041 _a$7048 _a$7049 _a$7050))) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.passes.inline" "trivial-arg?") a)) (let* ((_a$7051 (jolt-inc i)) (_a$7052 (jolt-assoc env p a)) (_a$7053 binds)) (loop7041 _a$7051 _a$7052 _a$7053)) (if (jolt-truthy? (keyword #f "else")) (let* ((f (jolt-invoke (var-deref "jolt.passes.inline" "fresh") p))) (let* ((_a$7060 (jolt-inc i)) (_a$7061 (jolt-assoc env p (let* ((_o$7054 (keyword #f "op")) (_o$7055 (keyword #f "local")) (_o$7056 (keyword #f "name")) (_o$7057 f)) (jolt-hash-map _o$7054 _o$7055 _o$7056 _o$7057)))) (_a$7062 (jolt-conj binds (let* ((_o$7058 f) (_o$7059 a)) (jolt-vector _o$7058 _o$7059))))) (loop7041 _a$7060 _a$7061 _a$7062))) jolt-nil)))) (let* ((_o$7063 env) (_o$7064 binds)) (jolt-vector _o$7063 _o$7064)))))) (env (jolt-nth res 0)) (binds (jolt-nth res 1)) (rbody0 (jolt-invoke (var-deref "jolt.passes.inline" "subst") body env)) (rbody (if (jolt-truthy? ret) (jolt-invoke (var-deref "jolt.ir" "coerce-node") ret rbody0) rbody0))) (begin (jolt-invoke (var-deref "jolt.passes.inline" "mark!")) (if (jolt= 0 (jolt-count binds)) rbody (let* ((_o$7065 (keyword #f "op")) (_o$7066 (keyword #f "let")) (_o$7067 (keyword #f "bindings")) (_o$7068 binds) (_o$7069 (keyword #f "body")) (_o$7070 rbody)) (jolt-hash-map _o$7065 _o$7066 _o$7067 _o$7068 _o$7069 _o$7070))))) node)) node)) node)))))) try-inline) (let* ((_o$7071 (keyword #f "private")) (_o$7072 #t) (_o$7073 (keyword #f "doc")) (_o$7074 "node is an :invoke whose children are already inlined. If its :fn is a var\n with a stashed, in-budget, arity-matching inline body, return the spliced\n let; else node.")) (jolt-hash-map _o$7071 _o$7072 _o$7073 _o$7074)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.inline" "inline-node" (letrec ((inline-node (lambda (node ctx) (let fnrec7075 ((node node) (ctx ctx)) (if (jolt= (keyword #f "invoke") (jolt-get node (keyword #f "op"))) (jolt-invoke (var-deref "jolt.passes.inline" "try-inline") (jolt-invoke (var-deref "jolt.ir" "map-ir-children") (lambda (c) (let fnrec7076 ((c c)) (inline-node c ctx))) node) ctx) (jolt-invoke (var-deref "jolt.ir" "map-ir-children") (lambda (c) (let fnrec7077 ((c c)) (inline-node c ctx))) node)))))) inline-node) (let* ((_o$7078 (keyword #f "doc")) (_o$7079 "Bottom-up: inline children first, then attempt to inline this node.")) (jolt-hash-map _o$7078 _o$7079)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.inline" "flatten-let-bindings" (letrec ((flatten-let-bindings (lambda (binds) (let fnrec7080 ((binds binds)) (let* ((_a$7086 (lambda (out b) (let fnrec7081 ((out out) (b b)) (let* ((nm (jolt-nth b 0)) (init (jolt-nth b 1))) (if (jolt= (keyword #f "let") (jolt-get init (keyword #f "op"))) (begin (jolt-invoke (var-deref "jolt.passes.inline" "mark!")) (let* ((_a$7084 (jolt-reduce jolt-conj out (jolt-get init (keyword #f "bindings")))) (_a$7085 (let* ((_o$7082 nm) (_o$7083 (jolt-get init (keyword #f "body")))) (jolt-vector _o$7082 _o$7083)))) (jolt-conj _a$7084 _a$7085))) (jolt-conj out b)))))) (_a$7087 (jolt-vector)) (_a$7088 binds)) (jolt-reduce _a$7086 _a$7087 _a$7088)))))) flatten-let-bindings) (let* ((_o$7089 (keyword #f "private")) (_o$7090 #t)) (jolt-hash-map _o$7089 _o$7090)))) -(guard (e (#t #f)) - (def-var! "jolt.passes.inline" "flatten-lets" (letrec ((flatten-lets (lambda (node) (let fnrec7091 ((node node)) (if (jolt= (keyword #f "let") (jolt-get node (keyword #f "op"))) (let* ((n (jolt-invoke (var-deref "jolt.ir" "map-ir-children") flatten-lets node))) (jolt-assoc n (keyword #f "bindings") (jolt-invoke (var-deref "jolt.passes.inline" "flatten-let-bindings") (jolt-get n (keyword #f "bindings"))))) (jolt-invoke (var-deref "jolt.ir" "map-ir-children") flatten-lets node)))))) flatten-lets))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.inline" "pure-fns" (let* ((_o$7092 "+") (_o$7093 "-") (_o$7094 "*") (_o$7095 "/") (_o$7096 "<") (_o$7097 ">") (_o$7098 "<=") (_o$7099 ">=") (_o$7100 "=") (_o$7101 "not=") (_o$7102 "inc") (_o$7103 "dec") (_o$7104 "mod") (_o$7105 "rem") (_o$7106 "quot") (_o$7107 "min") (_o$7108 "max") (_o$7109 "abs") (_o$7110 "nil?") (_o$7111 "some?") (_o$7112 "not") (_o$7113 "get") (_o$7114 "zero?") (_o$7115 "pos?") (_o$7116 "neg?") (_o$7117 "even?") (_o$7118 "odd?") (_o$7119 "bit-and") (_o$7120 "bit-or") (_o$7121 "bit-xor")) (jolt-hash-set _o$7092 _o$7093 _o$7094 _o$7095 _o$7096 _o$7097 _o$7098 _o$7099 _o$7100 _o$7101 _o$7102 _o$7103 _o$7104 _o$7105 _o$7106 _o$7107 _o$7108 _o$7109 _o$7110 _o$7111 _o$7112 _o$7113 _o$7114 _o$7115 _o$7116 _o$7117 _o$7118 _o$7119 _o$7120 _o$7121)) (let* ((_o$7122 (keyword #f "private")) (_o$7123 #t)) (jolt-hash-map _o$7122 _o$7123)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.inline" "pure-fn?" (letrec ((pure-fn? (lambda (f) (let fnrec7124 ((f f)) (let* ((op (jolt-get f (keyword #f "op")))) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.passes.fold" "kw-callee?") f)) #t (if (jolt= op (keyword #f "var")) (let* ((and__25__auto (jolt= "clojure.core" (jolt-get f (keyword #f "ns"))))) (if (jolt-truthy? and__25__auto) (jolt-contains? (var-deref "jolt.passes.inline" "pure-fns") (jolt-get f (keyword #f "name"))) and__25__auto)) (if (jolt= op (keyword #f "host")) (jolt-contains? (var-deref "jolt.passes.inline" "pure-fns") (jolt-get f (keyword #f "name"))) (if (jolt-truthy? (keyword #f "else")) #f jolt-nil))))))))) pure-fn?) (let* ((_o$7125 (keyword #f "private")) (_o$7126 #t)) (jolt-hash-map _o$7125 _o$7126)))) -(guard (e (#t #f)) - (declare-var! "jolt.passes.inline" "ctor-shape")) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.inline" "pure?" (letrec ((pure? (lambda (node) (let fnrec7127 ((node node)) (let* ((op (jolt-get node (keyword #f "op")))) (if (jolt= op (keyword #f "invoke")) (let* ((and__25__auto (let* ((or__26__auto (jolt-invoke (var-deref "jolt.passes.inline" "pure-fn?") (jolt-get node (keyword #f "fn"))))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-invoke (var-deref "jolt.passes.inline" "ctor-shape") node))))) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "clojure.core" "every?") pure? (jolt-get node (keyword #f "args"))) and__25__auto)) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.passes.inline" "safe-op?") op)) (jolt-invoke (var-deref "jolt.ir" "reduce-ir-children") (lambda (ok c) (let fnrec7128 ((ok ok) (c c)) (let* ((and__25__auto ok)) (if (jolt-truthy? and__25__auto) (pure? c) and__25__auto)))) #t node) (if (jolt-truthy? (keyword #f "else")) #f jolt-nil)))))))) pure?) (let* ((_o$7129 (keyword #f "private")) (_o$7130 #t) (_o$7131 (keyword #f "doc")) (_o$7132 "Conservative: true only for expressions with no side effects that are safe to\n duplicate or discard. A var/host ref is a pure read; an invoke is pure for a\n known-pure fn (arithmetic, comparison, keyword lookup, get) or a record\n constructor (an immutable struct alloc) whose args are themselves pure.")) (jolt-hash-map _o$7129 _o$7130 _o$7131 _o$7132)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.inline" "const-key-map?" (letrec ((const-key-map? (lambda (node) (let fnrec7133 ((node node)) (let* ((prs (jolt-get node (keyword #f "pairs")))) (let* ((and__25__auto (jolt-n> (jolt-count prs) 0))) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "clojure.core" "every?") (lambda (pr) (let fnrec7134 ((pr pr)) (jolt-invoke (var-deref "jolt.passes.fold" "scalar-const?") (jolt-nth pr 0)))) prs) and__25__auto))))))) const-key-map?) (let* ((_o$7135 (keyword #f "private")) (_o$7136 #t)) (jolt-hash-map _o$7135 _o$7136)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.inline" "all-vals-pure?" (letrec ((all-vals-pure? (lambda (node) (let fnrec7137 ((node node)) (let* ((_a$7139 (var-deref "clojure.core" "every?")) (_a$7140 (lambda (pr) (let fnrec7138 ((pr pr)) (jolt-invoke (var-deref "jolt.passes.inline" "pure?") (jolt-nth pr 1))))) (_a$7141 (jolt-get node (keyword #f "pairs")))) (jolt-invoke _a$7139 _a$7140 _a$7141)))))) all-vals-pure?) (let* ((_o$7142 (keyword #f "private")) (_o$7143 #t)) (jolt-hash-map _o$7142 _o$7143)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.inline" "map-val" (letrec ((map-val (lambda (mapnode k) (let fnrec7144 ((mapnode mapnode) (k k)) (let* ((prs (jolt-get mapnode (keyword #f "pairs"))) (n (jolt-count prs))) (let* ((i 0)) (let loop7145 ((i i)) (if (jolt-n< i n) (let* ((pr (jolt-nth prs i))) (if (jolt= (jolt-get (jolt-nth pr 0) (keyword #f "val")) k) (jolt-nth pr 1) (loop7145 (jolt-inc i)))) (let* ((_o$7146 (keyword #f "op")) (_o$7147 (keyword #f "const")) (_o$7148 (keyword #f "val")) (_o$7149 jolt-nil)) (jolt-hash-map _o$7146 _o$7147 _o$7148 _o$7149)))))))))) map-val) (let* ((_o$7150 (keyword #f "private")) (_o$7151 #t) (_o$7152 (keyword #f "doc")) (_o$7153 "The value IR at scalar key k in a const-key map node, or a nil constant when k\n is absent (struct-eligible literal: a missing key reads nil, like the back end).")) (jolt-hash-map _o$7150 _o$7151 _o$7152 _o$7153)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.inline" "lookup-key" (letrec ((lookup-key (lambda (node nm) (let fnrec7154 ((node node) (nm nm)) (if (jolt= (keyword #f "invoke") (jolt-get node (keyword #f "op"))) (let* ((f (jolt-get node (keyword #f "fn"))) (args (jolt-get node (keyword #f "args")))) (if (jolt-truthy? (let* ((and__25__auto (jolt-invoke (var-deref "jolt.passes.fold" "kw-callee?") f))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt= 1 (jolt-count args)))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt= (keyword #f "local") (jolt-get (jolt-nth args 0) (keyword #f "op"))))) (if (jolt-truthy? and__25__auto) (jolt= nm (jolt-get (jolt-nth args 0) (keyword #f "name"))) and__25__auto)) and__25__auto)) and__25__auto))) (jolt-get f (keyword #f "val")) (if (jolt-truthy? (let* ((and__25__auto (jolt-invoke (var-deref "jolt.passes.fold" "get-callee?") f))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt= 2 (jolt-count args)))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt= (keyword #f "local") (jolt-get (jolt-nth args 0) (keyword #f "op"))))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt= nm (jolt-get (jolt-nth args 0) (keyword #f "name"))))) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "jolt.passes.fold" "scalar-const?") (jolt-nth args 1)) and__25__auto)) and__25__auto)) and__25__auto)) and__25__auto))) (jolt-get (jolt-nth args 1) (keyword #f "val")) (if (jolt-truthy? (keyword #f "else")) jolt-nil jolt-nil)))) jolt-nil))))) lookup-key) (let* ((_o$7155 (keyword #f "private")) (_o$7156 #t) (_o$7157 (keyword #f "doc")) (_o$7158 "If node is a constant-keyword lookup of (:local nm) \x2014; either (:k nm) or\n (get nm :k) \x2014; return the keyword k; else nil.")) (jolt-hash-map _o$7155 _o$7156 _o$7157 _o$7158)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.inline" "any-binding-named?" (letrec ((any-binding-named? (lambda (binds nm) (let fnrec7159 ((binds binds) (nm nm)) (let* ((i 0)) (let loop7160 ((i i)) (if (jolt-n< i (jolt-count binds)) (if (jolt= nm (jolt-nth (jolt-nth binds i) 0)) #t (loop7160 (jolt-inc i))) #f))))))) any-binding-named?) (let* ((_o$7161 (keyword #f "private")) (_o$7162 #t)) (jolt-hash-map _o$7161 _o$7162)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.inline" "any-name?" (letrec ((any-name? (lambda (names nm) (let fnrec7163 ((names names) (nm nm)) (let* ((i 0)) (let loop7164 ((i i)) (if (jolt-n< i (jolt-count names)) (if (jolt= nm (jolt-nth names i)) #t (loop7164 (jolt-inc i))) #f))))))) any-name?) (let* ((_o$7165 (keyword #f "private")) (_o$7166 #t)) (jolt-hash-map _o$7165 _o$7166)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.inline" "local-escapes?" (letrec ((local-escapes? (lambda (node nm) (let fnrec7167 ((node node) (nm nm)) (let* ((op (jolt-get node (keyword #f "op"))) (k (jolt-invoke (var-deref "jolt.passes.inline" "lookup-key") node nm))) (if (jolt-truthy? k) (let* ((args (jolt-get node (keyword #f "args")))) (if (jolt-n> (jolt-count args) 1) (let* ((i 1)) (let loop7168 ((i i)) (if (jolt-n< i (jolt-count args)) (if (jolt-truthy? (local-escapes? (jolt-nth args i) nm)) #t (loop7168 (jolt-inc i))) #f))) #f)) (if (jolt= op (keyword #f "local")) (jolt= nm (jolt-get node (keyword #f "name"))) (if (jolt= op (keyword #f "const")) #f (if (jolt= op (keyword #f "var")) #f (if (jolt= op (keyword #f "host")) #f (if (jolt= op (keyword #f "the-var")) #f (if (jolt= op (keyword #f "quote")) #f (if (jolt= op (keyword #f "if")) (let* ((or__26__auto (local-escapes? (jolt-get node (keyword #f "test")) nm))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (local-escapes? (jolt-get node (keyword #f "then")) nm))) (if (jolt-truthy? or__26__auto) or__26__auto (local-escapes? (jolt-get node (keyword #f "else")) nm))))) (if (jolt= op (keyword #f "do")) (let* ((or__26__auto (let* ((i 0) (ss (jolt-get node (keyword #f "statements")))) (let loop7169 ((i i) (ss ss)) (if (jolt-n< i (jolt-count ss)) (if (jolt-truthy? (local-escapes? (jolt-nth ss i) nm)) #t (loop7169 (jolt-inc i) ss)) #f))))) (if (jolt-truthy? or__26__auto) or__26__auto (local-escapes? (jolt-get node (keyword #f "ret")) nm))) (if (jolt= op (keyword #f "throw")) (local-escapes? (jolt-get node (keyword #f "expr")) nm) (if (jolt= op (keyword #f "invoke")) (let* ((or__26__auto (local-escapes? (jolt-get node (keyword #f "fn")) nm))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((i 0) (as (jolt-get node (keyword #f "args")))) (let loop7170 ((i i) (as as)) (if (jolt-n< i (jolt-count as)) (if (jolt-truthy? (local-escapes? (jolt-nth as i) nm)) #t (loop7170 (jolt-inc i) as)) #f))))) (if (jolt= op (keyword #f "vector")) (let* ((i 0) (xs (jolt-get node (keyword #f "items")))) (let loop7171 ((i i) (xs xs)) (if (jolt-n< i (jolt-count xs)) (if (jolt-truthy? (local-escapes? (jolt-nth xs i) nm)) #t (loop7171 (jolt-inc i) xs)) #f))) (if (jolt= op (keyword #f "set")) (let* ((i 0) (xs (jolt-get node (keyword #f "items")))) (let loop7172 ((i i) (xs xs)) (if (jolt-n< i (jolt-count xs)) (if (jolt-truthy? (local-escapes? (jolt-nth xs i) nm)) #t (loop7172 (jolt-inc i) xs)) #f))) (if (jolt= op (keyword #f "map")) (let* ((i 0) (ps (jolt-get node (keyword #f "pairs")))) (let loop7173 ((i i) (ps ps)) (if (jolt-n< i (jolt-count ps)) (if (jolt-truthy? (let* ((or__26__auto (local-escapes? (jolt-nth (jolt-nth ps i) 0) nm))) (if (jolt-truthy? or__26__auto) or__26__auto (local-escapes? (jolt-nth (jolt-nth ps i) 1) nm)))) #t (loop7173 (jolt-inc i) ps)) #f))) (if (jolt= op (keyword #f "let")) (let* ((binds (jolt-get node (keyword #f "bindings")))) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.passes.inline" "any-binding-named?") binds nm)) #t (let* ((or__26__auto (let* ((i 0)) (let loop7174 ((i i)) (if (jolt-n< i (jolt-count binds)) (if (jolt-truthy? (local-escapes? (jolt-nth (jolt-nth binds i) 1) nm)) #t (loop7174 (jolt-inc i))) #f))))) (if (jolt-truthy? or__26__auto) or__26__auto (local-escapes? (jolt-get node (keyword #f "body")) nm))))) (if (jolt= op (keyword #f "recur")) (let* ((i 0) (as (jolt-get node (keyword #f "args")))) (let loop7175 ((i i) (as as)) (if (jolt-n< i (jolt-count as)) (if (jolt-truthy? (local-escapes? (jolt-nth as i) nm)) #t (loop7175 (jolt-inc i) as)) #f))) (if (jolt= op (keyword #f "loop")) (let* ((binds (jolt-get node (keyword #f "bindings")))) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.passes.inline" "any-binding-named?") binds nm)) #t (let* ((or__26__auto (let* ((i 0)) (let loop7176 ((i i)) (if (jolt-n< i (jolt-count binds)) (if (jolt-truthy? (local-escapes? (jolt-nth (jolt-nth binds i) 1) nm)) #t (loop7176 (jolt-inc i))) #f))))) (if (jolt-truthy? or__26__auto) or__26__auto (local-escapes? (jolt-get node (keyword #f "body")) nm))))) (if (jolt= op (keyword #f "fn")) (let* ((i 0) (ars (jolt-get node (keyword #f "arities")))) (let loop7177 ((i i) (ars ars)) (if (jolt-n< i (jolt-count ars)) (let* ((ar (jolt-nth ars i)) (ps (jolt-get ar (keyword #f "params")))) (if (jolt-truthy? (let* ((or__26__auto (jolt-invoke (var-deref "jolt.passes.inline" "any-name?") ps nm))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt= nm (jolt-get ar (keyword #f "rest")))))) #t (if (jolt-truthy? (local-escapes? (jolt-get ar (keyword #f "body")) nm)) #t (loop7177 (jolt-inc i) ars)))) #f))) (if (jolt= op (keyword #f "try")) (let* ((or__26__auto (local-escapes? (jolt-get node (keyword #f "body")) nm))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (let* ((cb (jolt-get node (keyword #f "catch-body")))) (let* ((and__25__auto cb)) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt-not (jolt= nm (jolt-get node (keyword #f "catch-sym")))))) (if (jolt-truthy? and__25__auto) (local-escapes? cb nm) and__25__auto)) and__25__auto))))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((f (jolt-get node (keyword #f "finally")))) (let* ((and__25__auto f)) (if (jolt-truthy? and__25__auto) (local-escapes? f nm) and__25__auto))))))) (if (jolt= op (keyword #f "def")) (local-escapes? (jolt-get node (keyword #f "init")) nm) (if (jolt-truthy? (keyword #f "else")) #t jolt-nil)))))))))))))))))))))))))) local-escapes?) (let* ((_o$7178 (keyword #f "private")) (_o$7179 #t) (_o$7180 (keyword #f "doc")) (_o$7181 "Does local nm escape in node \x2014; i.e. is it used anywhere other than as the\n subject of a constant-keyword lookup? Precise over straight-line expression\n ops; conservatively true for loop/fn/try/recur/def (and any rebinding of nm),\n so scalar replacement only fires where the whole use region is simple.\n\n Stays an explicit per-op walk (not the shared reduce-ir-children fold): its\n default is conservatively TRUE, and the lookup-subject and rebinding cases\n inspect node shape beyond child purity \x2014; folding an unhandled op over its\n children would under-report escape and is unsound for scalar replacement.")) (jolt-hash-map _o$7178 _o$7179 _o$7180 _o$7181)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.inline" "ctor-shape" (letrec ((ctor-shape (lambda (node) (let fnrec7182 ((node node)) (if (jolt= (keyword #f "invoke") (jolt-get node (keyword #f "op"))) (let* ((f (jolt-get node (keyword #f "fn")))) (if (jolt= (keyword #f "var") (jolt-get f (keyword #f "op"))) (let* ((rs (let* ((_a$7187 (jolt-invoke (var-deref "clojure.core" "deref") (var-deref "jolt.passes.inline" "rec-shapes"))) (_a$7188 (let* ((_a$7183 (var-deref "clojure.core" "str")) (_a$7184 (jolt-get f (keyword #f "ns"))) (_a$7185 "/") (_a$7186 (jolt-get f (keyword #f "name")))) (jolt-invoke _a$7183 _a$7184 _a$7185 _a$7186)))) (jolt-get _a$7187 _a$7188)))) (if (jolt-truthy? (let* ((and__25__auto rs)) (if (jolt-truthy? and__25__auto) (let* ((_a$7189 (jolt-count (jolt-get rs (keyword #f "fields")))) (_a$7190 (jolt-count (jolt-get node (keyword #f "args"))))) (jolt= _a$7189 _a$7190)) and__25__auto))) rs jolt-nil)) jolt-nil)) jolt-nil))))) ctor-shape) (let* ((_o$7191 (keyword #f "private")) (_o$7192 #t) (_o$7193 (keyword #f "doc")) (_o$7194 "If node is a record-constructor :invoke (its :fn a :var whose ns/name is a\n registered ctor key, with arg count matching the declared field count), return\n that record's shape entry; else nil.")) (jolt-hash-map _o$7191 _o$7192 _o$7193 _o$7194)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.inline" "ctor-all-args-pure?" (letrec ((ctor-all-args-pure? (lambda (node) (let fnrec7195 ((node node)) (jolt-invoke (var-deref "clojure.core" "every?") (var-deref "jolt.passes.inline" "pure?") (jolt-get node (keyword #f "args"))))))) ctor-all-args-pure?) (let* ((_o$7196 (keyword #f "private")) (_o$7197 #t)) (jolt-hash-map _o$7196 _o$7197)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.inline" "field-index" (letrec ((field-index (lambda (fields k) (let fnrec7198 ((fields fields) (k k)) (let* ((n (jolt-count fields))) (let* ((i 0)) (let loop7199 ((i i)) (if (jolt-n< i n) (if (jolt= (jolt-nth fields i) k) i (loop7199 (jolt-inc i))) jolt-nil)))))))) field-index) (let* ((_o$7200 (keyword #f "private")) (_o$7201 #t) (_o$7202 (keyword #f "doc")) (_o$7203 "Index of scalar key k in the declared field tuple fields, or nil.")) (jolt-hash-map _o$7200 _o$7201 _o$7202 _o$7203)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.inline" "ctor-val" (letrec ((ctor-val (lambda (ctor rs k) (let fnrec7204 ((ctor ctor) (rs rs) (k k)) (let* ((_a$7205 (jolt-get ctor (keyword #f "args"))) (_a$7206 (jolt-invoke (var-deref "jolt.passes.inline" "field-index") (jolt-get rs (keyword #f "fields")) k))) (jolt-nth _a$7205 _a$7206)))))) ctor-val) (let* ((_o$7207 (keyword #f "private")) (_o$7208 #t) (_o$7209 (keyword #f "doc")) (_o$7210 "The positional arg IR at declared field k of record ctor node (shape rs). Only\n called for a key known to be a field, so the index is always present.")) (jolt-hash-map _o$7207 _o$7208 _o$7209 _o$7210)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.inline" "collect-keys!" (letrec ((collect-keys! (lambda (node nm acc) (let fnrec7211 ((node node) (nm nm) (acc acc)) (let* ((k (jolt-invoke (var-deref "jolt.passes.inline" "lookup-key") node nm))) (if (jolt-truthy? k) (jolt-invoke (var-deref "clojure.core" "swap!") acc jolt-conj k) (jolt-invoke (var-deref "jolt.ir" "map-ir-children") (lambda (c) (let fnrec7212 ((c c)) (begin (collect-keys! c nm acc) c))) node))))))) collect-keys!) (let* ((_o$7213 (keyword #f "private")) (_o$7214 #t) (_o$7215 (keyword #f "doc")) (_o$7216 "Accumulate (into atom acc) every constant-keyword lookup key applied to local\n nm in node. The caller has proven (via local-escapes?) that nm appears only as\n a lookup subject and is never rebound, so a uniform recursion suffices: at a\n lookup of nm we record the key and stop (its subject is nm itself); elsewhere\n we recurse into children.")) (jolt-hash-map _o$7213 _o$7214 _o$7215 _o$7216)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.inline" "lookups-all-fields?" (letrec ((lookups-all-fields? (lambda (nodes nm fields) (let fnrec7217 ((nodes nodes) (nm nm) (fields fields)) (jolt-invoke (var-deref "clojure.core" "every?") (lambda (node) (let fnrec7218 ((node node)) (let* ((acc (jolt-invoke (var-deref "clojure.core" "atom") (jolt-hash-set)))) (begin (jolt-invoke (var-deref "jolt.passes.inline" "collect-keys!") node nm acc) (let* ((_a$7220 (var-deref "clojure.core" "every?")) (_a$7221 (lambda (k) (let fnrec7219 ((k k)) (jolt-invoke (var-deref "jolt.passes.inline" "field-index") fields k)))) (_a$7222 (jolt-invoke (var-deref "clojure.core" "deref") acc))) (jolt-invoke _a$7220 _a$7221 _a$7222)))))) nodes))))) lookups-all-fields?) (let* ((_o$7223 (keyword #f "private")) (_o$7224 #t) (_o$7225 (keyword #f "doc")) (_o$7226 "True if every lookup of nm across nodes uses a declared field in fields \x2014; the\n record-only guard that keeps a :jolt/deftype/unknown-key read (not a positional\n arg) from being folded to the wrong value.")) (jolt-hash-map _o$7223 _o$7224 _o$7225 _o$7226)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.inline" "src-val" (letrec ((src-val (lambda (src k) (let fnrec7227 ((src src) (k k)) (if (jolt= (keyword #f "map") (jolt-get src (keyword #f "op"))) (jolt-invoke (var-deref "jolt.passes.inline" "map-val") src k) (jolt-invoke (var-deref "jolt.passes.inline" "ctor-val") src (jolt-invoke (var-deref "jolt.passes.inline" "ctor-shape") src) k)))))) src-val) (let* ((_o$7228 (keyword #f "private")) (_o$7229 #t) (_o$7230 (keyword #f "doc")) (_o$7231 "Field value at k from a foldable struct source \x2014; a const-key map (absent key\n -> nil, struct-map semantics) or a record ctor (k is always a declared field\n here, guaranteed by lookups-all-fields?).")) (jolt-hash-map _o$7228 _o$7229 _o$7230 _o$7231)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.inline" "subst-lookup" (letrec ((subst-lookup (lambda (node nm src) (let fnrec7232 ((node node) (nm nm) (src src)) (let* ((k (jolt-invoke (var-deref "jolt.passes.inline" "lookup-key") node nm))) (if (jolt-truthy? k) (jolt-invoke (var-deref "jolt.passes.inline" "src-val") src k) (jolt-invoke (var-deref "jolt.ir" "map-ir-children") (lambda (c) (let fnrec7233 ((c c)) (subst-lookup c nm src))) node))))))) subst-lookup) (let* ((_o$7234 (keyword #f "private")) (_o$7235 #t) (_o$7236 (keyword #f "doc")) (_o$7237 "Replace every (:k nm)/(get nm :k) in node with the source value at k. The\n caller guarantees (via local-escapes?) that nm is never rebound here and\n appears only as a lookup subject, so no shadowing logic is needed.")) (jolt-hash-map _o$7234 _o$7235 _o$7236 _o$7237)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.inline" "fold-kw-literal" (letrec ((fold-kw-literal (lambda (node) (let fnrec7238 ((node node)) (let* ((f (jolt-get node (keyword #f "fn"))) (args (jolt-get node (keyword #f "args")))) (if (jolt-truthy? (let* ((and__25__auto (jolt-invoke (var-deref "jolt.passes.fold" "kw-callee?") f))) (if (jolt-truthy? and__25__auto) (jolt= 1 (jolt-count args)) and__25__auto))) (let* ((m (jolt-nth args 0)) (k (jolt-get f (keyword #f "val")))) (if (jolt-truthy? (let* ((and__25__auto (jolt= (keyword #f "map") (jolt-get m (keyword #f "op"))))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt-invoke (var-deref "jolt.passes.inline" "const-key-map?") m))) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "jolt.passes.inline" "all-vals-pure?") m) and__25__auto)) and__25__auto))) (begin (jolt-invoke (var-deref "jolt.passes.inline" "mark!")) (jolt-invoke (var-deref "jolt.passes.inline" "map-val") m k)) (let* ((rs (jolt-invoke (var-deref "jolt.passes.inline" "ctor-shape") m))) (if (jolt-truthy? (let* ((and__25__auto rs)) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt-invoke (var-deref "jolt.passes.inline" "ctor-all-args-pure?") m))) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "jolt.passes.inline" "field-index") (jolt-get rs (keyword #f "fields")) k) and__25__auto)) and__25__auto))) (begin (jolt-invoke (var-deref "jolt.passes.inline" "mark!")) (jolt-invoke (var-deref "jolt.passes.inline" "ctor-val") m rs k)) node)))) node)))))) fold-kw-literal) (let* ((_o$7239 (keyword #f "private")) (_o$7240 #t) (_o$7241 (keyword #f "doc")) (_o$7242 "(a) (:k ) -> the value at k. is a const-key pure map\n ((:k {:k a ..}) -> a) or a pure record ctor ((:k (->Rec a ..)) -> the arg for\n field k). Siblings are duplicated/discarded, so all must be pure; a record\n lookup folds only for a declared field.")) (jolt-hash-map _o$7239 _o$7240 _o$7241 _o$7242)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.inline" "elim-let-structs" (letrec ((elim-let-structs (lambda (node) (let fnrec7243 ((node node)) (let* ((binds (jolt-get node (keyword #f "bindings"))) (n (jolt-count binds)) (body (jolt-get node (keyword #f "body")))) (let* ((i 0)) (let loop7244 ((i i)) (if (jolt-n< i n) (let* ((b (jolt-nth binds i)) (nm (jolt-nth b 0)) (init (jolt-nth b 1)) (ismap (let* ((and__25__auto (jolt= (keyword #f "map") (jolt-get init (keyword #f "op"))))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt-invoke (var-deref "jolt.passes.inline" "const-key-map?") init))) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "jolt.passes.inline" "all-vals-pure?") init) and__25__auto)) and__25__auto))) (rs (if (jolt-not ismap) (jolt-invoke (var-deref "jolt.passes.inline" "ctor-shape") init) jolt-nil)) (isrec (let* ((and__25__auto rs)) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "jolt.passes.inline" "ctor-all-args-pure?") init) and__25__auto)))) (if (jolt-truthy? (let* ((and__25__auto (let* ((or__26__auto ismap)) (if (jolt-truthy? or__26__auto) or__26__auto isrec)))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt-not (jolt-invoke (var-deref "jolt.passes.inline" "any-binding-named?") (jolt-invoke (var-deref "clojure.core" "subvec") binds (jolt-inc i) n) nm)))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt-not (let* ((j (jolt-inc i))) (let loop7245 ((j j)) (if (jolt-n< j n) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.passes.inline" "local-escapes?") (jolt-nth (jolt-nth binds j) 1) nm)) #t (loop7245 (jolt-inc j))) #f)))))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt-not (jolt-invoke (var-deref "jolt.passes.inline" "local-escapes?") body nm)))) (if (jolt-truthy? and__25__auto) (let* ((or__26__auto ismap)) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((_a$7250 (var-deref "jolt.passes.inline" "lookups-all-fields?")) (_a$7251 (jolt-conj (let* ((_a$7247 (var-deref "clojure.core" "mapv")) (_a$7248 (lambda (bb) (let fnrec7246 ((bb bb)) (jolt-nth bb 1)))) (_a$7249 (jolt-invoke (var-deref "clojure.core" "subvec") binds (jolt-inc i) n))) (jolt-invoke _a$7247 _a$7248 _a$7249)) body)) (_a$7252 nm) (_a$7253 (jolt-get rs (keyword #f "fields")))) (jolt-invoke _a$7250 _a$7251 _a$7252 _a$7253)))) and__25__auto)) and__25__auto)) and__25__auto)) and__25__auto))) (let* ((head (jolt-invoke (var-deref "clojure.core" "subvec") binds 0 i)) (tail (let* ((_a$7257 (var-deref "clojure.core" "mapv")) (_a$7258 (lambda (bb) (let fnrec7254 ((bb bb)) (let* ((_o$7255 (jolt-nth bb 0)) (_o$7256 (jolt-invoke (var-deref "jolt.passes.inline" "subst-lookup") (jolt-nth bb 1) nm init))) (jolt-vector _o$7255 _o$7256))))) (_a$7259 (jolt-invoke (var-deref "clojure.core" "subvec") binds (jolt-inc i) n))) (jolt-invoke _a$7257 _a$7258 _a$7259))) (newbinds (jolt-reduce jolt-conj head tail)) (newbody (jolt-invoke (var-deref "jolt.passes.inline" "subst-lookup") body nm init))) (begin (jolt-invoke (var-deref "jolt.passes.inline" "mark!")) (if (jolt= 0 (jolt-count newbinds)) newbody (jolt-assoc node (keyword #f "bindings") newbinds (keyword #f "body") newbody)))) (loop7244 (jolt-inc i)))) node)))))))) elim-let-structs) (let* ((_o$7260 (keyword #f "private")) (_o$7261 #t) (_o$7262 (keyword #f "doc")) (_o$7263 "(b) Drop the first non-escaping let binding whose init is a foldable struct\n source \x2014; a pure const-key map literal or a pure record ctor \x2014; substituting its\n field reads into the remaining bindings and body. Fixpoint re-runs us for the\n rest, so one elimination per call keeps it simple. For a record every lookup\n of the binding must hit a declared field, else we keep the allocation.")) (jolt-hash-map _o$7260 _o$7261 _o$7262 _o$7263)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.inline" "scalar-replace" (letrec ((scalar-replace (lambda (node) (let fnrec7264 ((node node)) (let* ((op (jolt-get node (keyword #f "op")))) (if (jolt= op (keyword #f "invoke")) (jolt-invoke (var-deref "jolt.passes.inline" "fold-kw-literal") (jolt-invoke (var-deref "jolt.ir" "map-ir-children") scalar-replace node)) (if (jolt= op (keyword #f "let")) (jolt-invoke (var-deref "jolt.passes.inline" "elim-let-structs") (jolt-invoke (var-deref "jolt.ir" "map-ir-children") scalar-replace node)) (if (jolt-truthy? (keyword #f "else")) (jolt-invoke (var-deref "jolt.ir" "map-ir-children") scalar-replace node) jolt-nil)))))))) scalar-replace) (let* ((_o$7265 (keyword #f "doc")) (_o$7266 "Bottom-up: scalar-replace children, then apply (a) at invokes / (b) at lets.")) (jolt-hash-map _o$7265 _o$7266)))) -(guard (e (#t #f)) - (def-var! "jolt.passes.types.lattice" "velem" (letrec ((velem (lambda (t) (let fnrec6492 ((t t)) (jolt-get t (keyword #f "vec")))))) velem))) -(guard (e (#t #f)) - (def-var! "jolt.passes.types.lattice" "selem" (letrec ((selem (lambda (t) (let fnrec6493 ((t t)) (jolt-get t (keyword #f "set")))))) selem))) -(guard (e (#t #f)) - (def-var! "jolt.passes.types.lattice" "sfields" (letrec ((sfields (lambda (t) (let fnrec6494 ((t t)) (jolt-get t (keyword #f "struct")))))) sfields))) -(guard (e (#t #f)) - (def-var! "jolt.passes.types.lattice" "vec-type?" (letrec ((vec-type? (lambda (t) (let fnrec6495 ((t t)) (jolt-some? (jolt-invoke (var-deref "jolt.passes.types.lattice" "velem") t)))))) vec-type?))) -(guard (e (#t #f)) - (def-var! "jolt.passes.types.lattice" "set-type?" (letrec ((set-type? (lambda (t) (let fnrec6496 ((t t)) (jolt-some? (jolt-invoke (var-deref "jolt.passes.types.lattice" "selem") t)))))) set-type?))) -(guard (e (#t #f)) - (def-var! "jolt.passes.types.lattice" "struct-type?" (letrec ((struct-type? (lambda (t) (let fnrec6497 ((t t)) (jolt-some? (jolt-invoke (var-deref "jolt.passes.types.lattice" "sfields") t)))))) struct-type?))) -(guard (e (#t #f)) - (def-var! "jolt.passes.types.lattice" "mk-vec" (letrec ((mk-vec (lambda (t) (let fnrec6498 ((t t)) (let* ((_o$6499 (keyword #f "vec")) (_o$6500 (if (jolt-truthy? t) t (keyword #f "any")))) (jolt-hash-map _o$6499 _o$6500)))))) mk-vec))) -(guard (e (#t #f)) - (def-var! "jolt.passes.types.lattice" "mk-set" (letrec ((mk-set (lambda (t) (let fnrec6501 ((t t)) (let* ((_o$6502 (keyword #f "set")) (_o$6503 (if (jolt-truthy? t) t (keyword #f "any")))) (jolt-hash-map _o$6502 _o$6503)))))) mk-set))) -(guard (e (#t #f)) - (def-var! "jolt.passes.types.lattice" "mk-struct" (letrec ((mk-struct (lambda (fs) (let fnrec6504 ((fs fs)) (let* ((_o$6505 (keyword #f "struct")) (_o$6506 fs)) (jolt-hash-map _o$6505 _o$6506)))))) mk-struct))) -(guard (e (#t #f)) - (def-var! "jolt.passes.types.lattice" "union-cap" 4)) -(guard (e (#t #f)) - (def-var! "jolt.passes.types.lattice" "scalar-t?" (letrec ((scalar-t? (lambda (t) (let fnrec6507 ((t t)) (let* ((or__26__auto (jolt= t (keyword #f "num")))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt= t (keyword #f "str")))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt= t (keyword #f "kw")))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt= t (keyword #f "truthy")))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt= t (keyword #f "phm")))))))))))))) scalar-t?))) -(guard (e (#t #f)) - (def-var! "jolt.passes.types.lattice" "union-type?" (letrec ((union-type? (lambda (t) (let fnrec6508 ((t t)) (jolt-some? (jolt-get t (keyword #f "union"))))))) union-type?))) -(guard (e (#t #f)) - (def-var! "jolt.passes.types.lattice" "umembers" (letrec ((umembers (lambda (t) (let fnrec6509 ((t t)) (jolt-get t (keyword #f "union")))))) umembers))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types.lattice" "union-of" (letrec ((union-of (lambda (ts) (let fnrec6510 ((ts ts)) (let* ((flat (let* ((_a$6512 (lambda (acc t) (let fnrec6511 ((acc acc) (t t)) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.passes.types.lattice" "union-type?") t)) (jolt-reduce jolt-conj acc (jolt-invoke (var-deref "jolt.passes.types.lattice" "umembers") t)) (jolt-conj acc t))))) (_a$6513 (jolt-hash-set)) (_a$6514 ts)) (jolt-reduce _a$6512 _a$6513 _a$6514)))) (if (jolt-not (jolt-invoke (var-deref "clojure.core" "every?") (var-deref "jolt.passes.types.lattice" "scalar-t?") flat)) (keyword #f "any") (if (jolt= 0 (jolt-count flat)) (keyword #f "any") (if (jolt= 1 (jolt-count flat)) (jolt-first flat) (if (jolt-n> (jolt-count flat) (var-deref "jolt.passes.types.lattice" "union-cap")) (keyword #f "any") (if (jolt-truthy? (keyword #f "else")) (let* ((_o$6515 (keyword #f "union")) (_o$6516 flat)) (jolt-hash-map _o$6515 _o$6516)) jolt-nil)))))))))) union-of) (let* ((_o$6517 (keyword #f "doc")) (_o$6518 "Normalize a seq of member types into a lattice value: flatten nested unions,\n keep only scalars (any non-scalar member collapses the whole thing to :any,\n the conservative top), then return the lone member if one, {:union #{...}}\n for 2..cap distinct scalars, or :any past the cap.")) (jolt-hash-map _o$6517 _o$6518)))) -(guard (e (#t #f)) - (declare-var! "jolt.passes.types.lattice" "join-t")) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types.lattice" "merge-fields" (letrec ((merge-fields (lambda (fa fb) (let fnrec6519 ((fa fa) (fb fb)) (let* ((m1 (let* ((_a$6524 (lambda (m k) (let fnrec6520 ((m m) (k k)) (jolt-assoc m k (let* ((_a$6521 (var-deref "jolt.passes.types.lattice" "join-t")) (_a$6522 (jolt-get fa k (keyword #f "any"))) (_a$6523 (jolt-get fb k (keyword #f "any")))) (jolt-invoke _a$6521 _a$6522 _a$6523)))))) (_a$6525 (jolt-hash-map)) (_a$6526 (jolt-keys fa))) (jolt-reduce _a$6524 _a$6525 _a$6526)))) (let* ((_a$6531 (lambda (m k) (let fnrec6527 ((m m) (k k)) (if (jolt-truthy? (jolt-get m k)) m (jolt-assoc m k (let* ((_a$6528 (var-deref "jolt.passes.types.lattice" "join-t")) (_a$6529 (jolt-get fa k (keyword #f "any"))) (_a$6530 (jolt-get fb k (keyword #f "any")))) (jolt-invoke _a$6528 _a$6529 _a$6530))))))) (_a$6532 m1) (_a$6533 (jolt-keys fb))) (jolt-reduce _a$6531 _a$6532 _a$6533))))))) merge-fields) (let* ((_o$6534 (keyword #f "doc")) (_o$6535 "Per-field join of two field maps (a key in only one side joins with :any).")) (jolt-hash-map _o$6534 _o$6535)))) -(guard (e (#t #f)) - (def-var! "jolt.passes.types.lattice" "join-t" (letrec ((join-t (lambda (a b) (let fnrec6536 ((a a) (b b)) (if (jolt= a b) a (if (jolt-nil? a) b (if (jolt-nil? b) a (if (let* ((or__26__auto (jolt= a (keyword #f "nil")))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt= b (keyword #f "nil")))) (let* ((o (if (jolt= a (keyword #f "nil")) b a))) (if (jolt= o (keyword #f "nil")) (keyword #f "nil") (if (jolt-truthy? (jolt-invoke (var-deref "jolt.passes.types.lattice" "struct-type?") o)) (jolt-assoc o (keyword #f "nilable") #t) (if (jolt-truthy? (keyword #f "else")) (keyword #f "any") jolt-nil)))) (if (let* ((or__26__auto (jolt= a (keyword #f "double")))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt= b (keyword #f "double")))) (let* ((_a$6537 (if (jolt= a (keyword #f "double")) (keyword #f "num") a)) (_a$6538 (if (jolt= b (keyword #f "double")) (keyword #f "num") b))) (join-t _a$6537 _a$6538)) (if (jolt-truthy? (let* ((and__25__auto (jolt-invoke (var-deref "jolt.passes.types.lattice" "struct-type?") a))) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "jolt.passes.types.lattice" "struct-type?") b) and__25__auto))) (let* ((merged (jolt-invoke (var-deref "jolt.passes.types.lattice" "mk-struct") (let* ((_a$6539 (var-deref "jolt.passes.types.lattice" "merge-fields")) (_a$6540 (jolt-invoke (var-deref "jolt.passes.types.lattice" "sfields") a)) (_a$6541 (jolt-invoke (var-deref "jolt.passes.types.lattice" "sfields") b))) (jolt-invoke _a$6539 _a$6540 _a$6541)))) (merged (if (jolt-truthy? (let* ((and__25__auto (jolt-get a (keyword #f "shape")))) (if (jolt-truthy? and__25__auto) (let* ((_a$6542 (jolt-get a (keyword #f "shape"))) (_a$6543 (jolt-get b (keyword #f "shape")))) (jolt= _a$6542 _a$6543)) and__25__auto))) (jolt-assoc merged (keyword #f "shape") (jolt-get a (keyword #f "shape"))) merged)) (merged (if (jolt-truthy? (let* ((and__25__auto (jolt-get a (keyword #f "type")))) (if (jolt-truthy? and__25__auto) (let* ((_a$6544 (jolt-get a (keyword #f "type"))) (_a$6545 (jolt-get b (keyword #f "type")))) (jolt= _a$6544 _a$6545)) and__25__auto))) (jolt-assoc merged (keyword #f "type") (jolt-get a (keyword #f "type"))) merged)) (merged (if (jolt-truthy? (let* ((or__26__auto (jolt-get a (keyword #f "nilable")))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-get b (keyword #f "nilable"))))) (jolt-assoc merged (keyword #f "nilable") #t) merged))) merged) (if (jolt-truthy? (let* ((and__25__auto (jolt-invoke (var-deref "jolt.passes.types.lattice" "vec-type?") a))) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "jolt.passes.types.lattice" "vec-type?") b) and__25__auto))) (jolt-invoke (var-deref "jolt.passes.types.lattice" "mk-vec") (let* ((_a$6546 (jolt-invoke (var-deref "jolt.passes.types.lattice" "velem") a)) (_a$6547 (jolt-invoke (var-deref "jolt.passes.types.lattice" "velem") b))) (join-t _a$6546 _a$6547))) (if (jolt-truthy? (let* ((and__25__auto (jolt-invoke (var-deref "jolt.passes.types.lattice" "set-type?") a))) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "jolt.passes.types.lattice" "set-type?") b) and__25__auto))) (jolt-invoke (var-deref "jolt.passes.types.lattice" "mk-set") (let* ((_a$6548 (jolt-invoke (var-deref "jolt.passes.types.lattice" "selem") a)) (_a$6549 (jolt-invoke (var-deref "jolt.passes.types.lattice" "selem") b))) (join-t _a$6548 _a$6549))) (if (jolt-truthy? (keyword #f "else")) (let* ((ma (if (jolt-truthy? (jolt-invoke (var-deref "jolt.passes.types.lattice" "union-type?") a)) (jolt-invoke (var-deref "jolt.passes.types.lattice" "umembers") a) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.passes.types.lattice" "scalar-t?") a)) (jolt-hash-set a) (if (jolt-truthy? (keyword #f "else")) jolt-nil jolt-nil)))) (mb (if (jolt-truthy? (jolt-invoke (var-deref "jolt.passes.types.lattice" "union-type?") b)) (jolt-invoke (var-deref "jolt.passes.types.lattice" "umembers") b) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.passes.types.lattice" "scalar-t?") b)) (jolt-hash-set b) (if (jolt-truthy? (keyword #f "else")) jolt-nil jolt-nil))))) (if (jolt-truthy? (let* ((and__25__auto ma)) (if (jolt-truthy? and__25__auto) mb and__25__auto))) (jolt-invoke (var-deref "jolt.passes.types.lattice" "union-of") (jolt-reduce jolt-conj ma mb)) (keyword #f "any"))) jolt-nil))))))))))))) join-t))) -(guard (e (#t #f)) - (def-var! "jolt.passes.types.lattice" "join" (letrec ((join (lambda (a b) (let fnrec6550 ((a a) (b b)) (jolt-invoke (var-deref "jolt.passes.types.lattice" "join-t") a b))))) join))) -(guard (e (#t #f)) - (def-var! "jolt.passes.types.lattice" "type-depth" 4)) -(guard (e (#t #f)) - (def-var! "jolt.passes.types.lattice" "cap" (letrec ((cap (lambda (t d) (let fnrec6551 ((t t) (d d)) (if (jolt-n<= d 0) (if (jolt-truthy? (let* ((or__26__auto (jolt-invoke (var-deref "jolt.passes.types.lattice" "struct-type?") t))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt-invoke (var-deref "jolt.passes.types.lattice" "vec-type?") t))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-invoke (var-deref "jolt.passes.types.lattice" "set-type?") t)))))) (keyword #f "any") t) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.passes.types.lattice" "struct-type?") t)) (let* ((capped (jolt-invoke (var-deref "jolt.passes.types.lattice" "mk-struct") (let* ((_a$6555 (lambda (m k) (let fnrec6552 ((m m) (k k)) (jolt-assoc m k (let* ((_a$6553 (jolt-get (jolt-invoke (var-deref "jolt.passes.types.lattice" "sfields") t) k)) (_a$6554 (jolt-dec d))) (cap _a$6553 _a$6554)))))) (_a$6556 (jolt-hash-map)) (_a$6557 (jolt-keys (jolt-invoke (var-deref "jolt.passes.types.lattice" "sfields") t)))) (jolt-reduce _a$6555 _a$6556 _a$6557)))) (capped (if (jolt-truthy? (jolt-get t (keyword #f "shape"))) (jolt-assoc capped (keyword #f "shape") (jolt-get t (keyword #f "shape"))) capped)) (capped (if (jolt-truthy? (jolt-get t (keyword #f "type"))) (jolt-assoc capped (keyword #f "type") (jolt-get t (keyword #f "type"))) capped))) capped) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.passes.types.lattice" "vec-type?") t)) (jolt-invoke (var-deref "jolt.passes.types.lattice" "mk-vec") (let* ((_a$6558 (jolt-invoke (var-deref "jolt.passes.types.lattice" "velem") t)) (_a$6559 (jolt-dec d))) (cap _a$6558 _a$6559))) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.passes.types.lattice" "set-type?") t)) (jolt-invoke (var-deref "jolt.passes.types.lattice" "mk-set") (let* ((_a$6560 (jolt-invoke (var-deref "jolt.passes.types.lattice" "selem") t)) (_a$6561 (jolt-dec d))) (cap _a$6560 _a$6561))) (if (jolt-truthy? (keyword #f "else")) t jolt-nil))))))))) cap))) -(guard (e (#t #f)) - (def-var! "jolt.passes.types.lattice" "struct-safe?" (letrec ((struct-safe? (lambda (t) (let fnrec6562 ((t t)) (jolt-invoke (var-deref "jolt.passes.types.lattice" "struct-type?") t))))) struct-safe?))) -(guard (e (#t #f)) - (def-var! "jolt.passes.types.lattice" "field-type" (letrec ((field-type (lambda (t k) (let fnrec6563 ((t t) (k k)) (if (jolt-truthy? (let* ((and__25__auto (jolt-invoke (var-deref "jolt.passes.types.lattice" "struct-type?") t))) (if (jolt-truthy? and__25__auto) (jolt-not (jolt-get t (keyword #f "nilable"))) and__25__auto))) (jolt-get (jolt-invoke (var-deref "jolt.passes.types.lattice" "sfields") t) k (keyword #f "any")) (keyword #f "any")))))) field-type))) -(guard (e (#t #f)) - (def-var! "jolt.passes.types.lattice" "nilable?" (letrec ((nilable? (lambda (t) (let fnrec6564 ((t t)) (let* ((and__25__auto (jolt-invoke (var-deref "clojure.core" "map?") t))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt-get t (keyword #f "nilable")))) (if (jolt-truthy? and__25__auto) #t and__25__auto)) and__25__auto)))))) nilable?))) -(guard (e (#t #f)) - (def-var! "jolt.passes.types.lattice" "strip-nilable" (letrec ((strip-nilable (lambda (t) (let fnrec6565 ((t t)) (if (jolt-truthy? (let* ((and__25__auto (jolt-invoke (var-deref "clojure.core" "map?") t))) (if (jolt-truthy? and__25__auto) (jolt-get t (keyword #f "nilable")) and__25__auto))) (jolt-dissoc t (keyword #f "nilable")) t))))) strip-nilable))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types.lattice" "shape-order" (letrec ((shape-order (lambda (ks) (let fnrec6566 ((ks ks)) (jolt-invoke (var-deref "clojure.core" "vec") (jolt-invoke (var-deref "clojure.core" "sort") (lambda (a b) (let fnrec6567 ((a a) (b b)) (let* ((_a$6568 (var-deref "clojure.core" "compare")) (_a$6569 (jolt-invoke (var-deref "clojure.core" "str") a)) (_a$6570 (jolt-invoke (var-deref "clojure.core" "str") b))) (jolt-invoke _a$6568 _a$6569 _a$6570)))) ks)))))) shape-order) (let* ((_o$6571 (keyword #f "doc")) (_o$6572 "Canonical key order for a shape: keys sorted by their string form, so two\n literals with the same keys in any order intern to the same shape.")) (jolt-hash-map _o$6571 _o$6572)))) -(guard (e (#t #f)) - (def-var! "jolt.passes.types.lattice" "type-shape" (letrec ((type-shape (lambda (t) (let fnrec6573 ((t t)) (jolt-get t (keyword #f "shape")))))) type-shape))) -(guard (e (#t #f)) - (def-var! "jolt.passes.types.lattice" "mark-struct" (letrec ((mark-struct (lambda (node t) (let fnrec6574 ((node node) (t t)) (let* ((n (jolt-assoc node (keyword #f "hint") (keyword #f "struct")))) (if (jolt-truthy? (jolt-get t (keyword #f "shape"))) (jolt-assoc n (keyword #f "shape") (jolt-get t (keyword #f "shape"))) n)))))) mark-struct))) -(guard (e (#t #f)) - (def-var! "jolt.passes.types.lattice" "truthy-type?" (letrec ((truthy-type? (lambda (t) (let fnrec6575 ((t t)) (let* ((or__26__auto (jolt= t (keyword #f "num")))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt= t (keyword #f "double")))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt= t (keyword #f "str")))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt= t (keyword #f "kw")))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt= t (keyword #f "truthy")))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt= t (keyword #f "phm")))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (let* ((and__25__auto (jolt-invoke (var-deref "jolt.passes.types.lattice" "struct-type?") t))) (if (jolt-truthy? and__25__auto) (jolt-not (jolt-get t (keyword #f "nilable"))) and__25__auto)))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt-invoke (var-deref "jolt.passes.types.lattice" "vec-type?") t))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-invoke (var-deref "jolt.passes.types.lattice" "set-type?") t))))))))))))))))))))) truthy-type?))) -(guard (e (#t #f)) - (def-var! "jolt.passes.types.lattice" "num-ret-fns" (let* ((_o$6576 "+") (_o$6577 "-") (_o$6578 "*") (_o$6579 "/") (_o$6580 "inc") (_o$6581 "dec") (_o$6582 "mod") (_o$6583 "rem") (_o$6584 "quot") (_o$6585 "min") (_o$6586 "max") (_o$6587 "abs") (_o$6588 "bit-and") (_o$6589 "bit-or") (_o$6590 "bit-xor") (_o$6591 "count")) (jolt-hash-set _o$6576 _o$6577 _o$6578 _o$6579 _o$6580 _o$6581 _o$6582 _o$6583 _o$6584 _o$6585 _o$6586 _o$6587 _o$6588 _o$6589 _o$6590 _o$6591)))) -(guard (e (#t #f)) - (def-var! "jolt.passes.types.lattice" "vector-ret-fns" (let* ((_o$6592 "vec") (_o$6593 "vector") (_o$6594 "mapv") (_o$6595 "filterv") (_o$6596 "subvec")) (jolt-hash-set _o$6592 _o$6593 _o$6594 _o$6595 _o$6596)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types.check" "not-number?" (letrec ((not-number? (lambda (t) (let fnrec6597 ((t t)) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.passes.types.lattice" "union-type?") t)) (jolt-invoke (var-deref "clojure.core" "every?") not-number? (jolt-invoke (var-deref "jolt.passes.types.lattice" "umembers") t)) (let* ((or__26__auto (jolt= t (keyword #f "str")))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt= t (keyword #f "kw")))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt= t (keyword #f "phm")))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt-invoke (var-deref "jolt.passes.types.lattice" "struct-type?") t))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt-invoke (var-deref "jolt.passes.types.lattice" "vec-type?") t))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-invoke (var-deref "jolt.passes.types.lattice" "set-type?") t)))))))))))))))) not-number?) (let* ((_o$6598 (keyword #f "private")) (_o$6599 #t)) (jolt-hash-map _o$6598 _o$6599)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types.check" "not-seqable?" (letrec ((not-seqable? (lambda (t) (let fnrec6600 ((t t)) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.passes.types.lattice" "union-type?") t)) (jolt-invoke (var-deref "clojure.core" "every?") not-seqable? (jolt-invoke (var-deref "jolt.passes.types.lattice" "umembers") t)) (let* ((or__26__auto (jolt= t (keyword #f "num")))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt= t (keyword #f "kw"))))))))) not-seqable?) (let* ((_o$6601 (keyword #f "private")) (_o$6602 #t)) (jolt-hash-map _o$6601 _o$6602)))) -(guard (e (#t #f)) - (def-var! "jolt.passes.types.check" "not-callable?" (letrec ((not-callable? (lambda (t) (let fnrec6603 ((t t)) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.passes.types.lattice" "union-type?") t)) (jolt-invoke (var-deref "clojure.core" "every?") not-callable? (jolt-invoke (var-deref "jolt.passes.types.lattice" "umembers") t)) (let* ((or__26__auto (jolt= t (keyword #f "num")))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt= t (keyword #f "str"))))))))) not-callable?))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types.check" "num-ops" (let* ((_o$6604 "+") (_o$6605 "-") (_o$6606 "*") (_o$6607 "/") (_o$6608 "inc") (_o$6609 "dec") (_o$6610 "mod") (_o$6611 "rem") (_o$6612 "quot") (_o$6613 "min") (_o$6614 "max") (_o$6615 "abs") (_o$6616 "bit-and") (_o$6617 "bit-or") (_o$6618 "bit-xor") (_o$6619 "bit-not") (_o$6620 "bit-shift-left") (_o$6621 "bit-shift-right")) (jolt-hash-set _o$6604 _o$6605 _o$6606 _o$6607 _o$6608 _o$6609 _o$6610 _o$6611 _o$6612 _o$6613 _o$6614 _o$6615 _o$6616 _o$6617 _o$6618 _o$6619 _o$6620 _o$6621)) (let* ((_o$6622 (keyword #f "private")) (_o$6623 #t)) (jolt-hash-map _o$6622 _o$6623)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types.check" "seq-ops" (let* ((_o$6624 "count") (_o$6625 "first") (_o$6626 "rest") (_o$6627 "next") (_o$6628 "seq") (_o$6629 "nth")) (jolt-hash-set _o$6624 _o$6625 _o$6626 _o$6627 _o$6628 _o$6629)) (let* ((_o$6630 (keyword #f "private")) (_o$6631 #t)) (jolt-hash-map _o$6630 _o$6631)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types.check" "type-name" (letrec ((type-name (lambda (t) (let fnrec6632 ((t t)) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.passes.types.lattice" "union-type?") t)) (let* ((_a$6634 (lambda (s m) (let fnrec6633 ((s s) (m m)) (if (jolt= s "") (type-name m) (jolt-invoke (var-deref "clojure.core" "str") s " or " (type-name m)))))) (_a$6635 "") (_a$6636 (jolt-invoke (var-deref "jolt.passes.types.lattice" "umembers") t))) (jolt-reduce _a$6634 _a$6635 _a$6636)) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.passes.types.lattice" "struct-type?") t)) "a map" (if (jolt-truthy? (jolt-invoke (var-deref "jolt.passes.types.lattice" "vec-type?") t)) "a vector" (if (jolt-truthy? (jolt-invoke (var-deref "jolt.passes.types.lattice" "set-type?") t)) "a set" (if (jolt= t (keyword #f "str")) "a string" (if (jolt= t (keyword #f "kw")) "a keyword" (if (jolt= t (keyword #f "num")) "a number" (if (jolt= t (keyword #f "phm")) "a map" (if (jolt-truthy? (keyword #f "else")) (jolt-invoke (var-deref "clojure.core" "str") t) jolt-nil))))))))))))) type-name) (let* ((_o$6637 (keyword #f "doc")) (_o$6638 "Render an inferred type for an error message.")) (jolt-hash-map _o$6637 _o$6638)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types.check" "check-invoke" (letrec ((check-invoke (lambda (cn args arg-types pos env) (let fnrec6639 ((cn cn) (args args) (arg-types arg-types) (pos pos) (env env)) (if (jolt-contains? (var-deref "jolt.passes.types.check" "num-ops") cn) (let* ((_a$6662 (lambda (_ i) (let fnrec6640 ((_ _) (i i)) (begin (let* ((t (jolt-nth arg-types i))) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.passes.types.check" "not-number?") t)) (let* ((_a$6658 (var-deref "clojure.core" "swap!")) (_a$6659 (jolt-get env (keyword #f "diags"))) (_a$6660 jolt-conj) (_a$6661 (let* ((_o$6648 (keyword #f "op")) (_o$6649 cn) (_o$6650 (keyword #f "argpos")) (_o$6651 i) (_o$6652 (keyword #f "type")) (_o$6653 (jolt-invoke (var-deref "jolt.passes.types.check" "type-name") t)) (_o$6654 (keyword #f "pos")) (_o$6655 pos) (_o$6656 (keyword #f "msg")) (_o$6657 (let* ((_a$6641 (var-deref "clojure.core" "str")) (_a$6642 "`") (_a$6643 cn) (_a$6644 "` requires a number, but argument ") (_a$6645 (jolt-inc i)) (_a$6646 " is ") (_a$6647 (jolt-invoke (var-deref "jolt.passes.types.check" "type-name") t))) (jolt-invoke _a$6641 _a$6642 _a$6643 _a$6644 _a$6645 _a$6646 _a$6647)))) (jolt-hash-map _o$6648 _o$6649 _o$6650 _o$6651 _o$6652 _o$6653 _o$6654 _o$6655 _o$6656 _o$6657)))) (jolt-invoke _a$6658 _a$6659 _a$6660 _a$6661)) jolt-nil)) jolt-nil)))) (_a$6663 jolt-nil) (_a$6664 (jolt-range (jolt-count args)))) (jolt-reduce _a$6662 _a$6663 _a$6664)) (if (let* ((and__25__auto (jolt-contains? (var-deref "jolt.passes.types.check" "seq-ops") cn))) (if (jolt-truthy? and__25__auto) (jolt-n> (jolt-count args) 0) and__25__auto)) (let* ((t (jolt-nth arg-types 0))) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.passes.types.check" "not-seqable?") t)) (let* ((_a$6682 (var-deref "clojure.core" "swap!")) (_a$6683 (jolt-get env (keyword #f "diags"))) (_a$6684 jolt-conj) (_a$6685 (let* ((_o$6672 (keyword #f "op")) (_o$6673 cn) (_o$6674 (keyword #f "argpos")) (_o$6675 0) (_o$6676 (keyword #f "type")) (_o$6677 (jolt-invoke (var-deref "jolt.passes.types.check" "type-name") t)) (_o$6678 (keyword #f "pos")) (_o$6679 pos) (_o$6680 (keyword #f "msg")) (_o$6681 (let* ((_a$6665 (var-deref "clojure.core" "str")) (_a$6666 "`") (_a$6667 cn) (_a$6668 "` requires ") (_a$6669 (if (jolt= cn "count") "a countable collection" "a seqable")) (_a$6670 ", but argument 1 is ") (_a$6671 (jolt-invoke (var-deref "jolt.passes.types.check" "type-name") t))) (jolt-invoke _a$6665 _a$6666 _a$6667 _a$6668 _a$6669 _a$6670 _a$6671)))) (jolt-hash-map _o$6672 _o$6673 _o$6674 _o$6675 _o$6676 _o$6677 _o$6678 _o$6679 _o$6680 _o$6681)))) (jolt-invoke _a$6682 _a$6683 _a$6684 _a$6685)) jolt-nil)) (if (jolt-truthy? (keyword #f "else")) jolt-nil jolt-nil))))))) check-invoke) (let* ((_o$6686 (keyword #f "doc")) (_o$6687 "If node is a core-op call whose argument type is provably in the error domain,\n conj a diagnostic into env's diags cell. arg-types is the vector of inferred\n argument types; pos is the call form's source offset, carried into each\n diagnostic.")) (jolt-hash-map _o$6686 _o$6687)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types.check" "register-user-fn!" (letrec ((register-user-fn! (lambda (node env) (let fnrec6688 ((node node) (env env)) (let* ((init (jolt-get node (keyword #f "init"))) (m (jolt-get node (keyword #f "meta"))) (redefable (let* ((and__25__auto m)) (if (jolt-truthy? and__25__auto) (let* ((or__26__auto (jolt-get m (keyword #f "redef")))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-get m (keyword #f "dynamic")))) and__25__auto)))) (if (let* ((and__25__auto (jolt-not redefable))) (if (jolt-truthy? and__25__auto) (jolt= (keyword #f "fn") (jolt-get init (keyword #f "op"))) and__25__auto)) (let* ((arities (jolt-get init (keyword #f "arities")))) (if (jolt= 1 (jolt-count arities)) (let* ((ar (jolt-first arities))) (if (jolt-not (jolt-get ar (keyword #f "rest"))) (let* ((_a$6699 (var-deref "clojure.core" "swap!")) (_a$6700 (jolt-get env (keyword #f "user-sigs"))) (_a$6701 jolt-assoc) (_a$6702 (let* ((_a$6689 (var-deref "clojure.core" "str")) (_a$6690 (jolt-get node (keyword #f "ns"))) (_a$6691 "/") (_a$6692 (jolt-get node (keyword #f "name")))) (jolt-invoke _a$6689 _a$6690 _a$6691 _a$6692))) (_a$6703 (let* ((_o$6693 (keyword #f "name")) (_o$6694 (jolt-get node (keyword #f "name"))) (_o$6695 (keyword #f "params")) (_o$6696 (jolt-get ar (keyword #f "params"))) (_o$6697 (keyword #f "body")) (_o$6698 (jolt-get ar (keyword #f "body")))) (jolt-hash-map _o$6693 _o$6694 _o$6695 _o$6696 _o$6697 _o$6698)))) (jolt-invoke _a$6699 _a$6700 _a$6701 _a$6702 _a$6703)) jolt-nil)) jolt-nil)) jolt-nil)))))) register-user-fn!) (let* ((_o$6704 (keyword #f "doc")) (_o$6705 "Record a (def name (fn [params] body)) \x2014; single fixed arity, not redefinable \x2014;\n for later user-fn call checking. Redefinable/dynamic and multi/variadic fns are\n skipped (their body is not a stable requirement).")) (jolt-hash-map _o$6704 _o$6705)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types" "config-box" (jolt-invoke (var-deref "clojure.core" "atom") (let* ((_o$5648 (keyword #f "rtenv")) (_o$5649 (jolt-hash-map)) (_o$5650 (keyword #f "vtypes")) (_o$5651 (jolt-hash-map)) (_o$5652 (keyword #f "record-shapes")) (_o$5653 (jolt-hash-map)) (_o$5654 (keyword #f "protocol-methods")) (_o$5655 (jolt-hash-map)) (_o$5656 (keyword #f "map-shapes?")) (_o$5657 #f)) (jolt-hash-map _o$5648 _o$5649 _o$5650 _o$5651 _o$5652 _o$5653 _o$5654 _o$5655 _o$5656 _o$5657))) (let* ((_o$5658 (keyword #f "private")) (_o$5659 #t)) (jolt-hash-map _o$5658 _o$5659)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types" "escapes-box" (jolt-invoke (var-deref "clojure.core" "atom") (jolt-hash-set)) (let* ((_o$5660 (keyword #f "private")) (_o$5661 #t)) (jolt-hash-map _o$5660 _o$5661)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types" "user-sig-box" (jolt-invoke (var-deref "clojure.core" "atom") (jolt-hash-map)) (let* ((_o$5662 (keyword #f "private")) (_o$5663 #t)) (jolt-hash-map _o$5662 _o$5663)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types" "last-diags-box" (jolt-invoke (var-deref "clojure.core" "atom") (jolt-vector)) (let* ((_o$5664 (keyword #f "private")) (_o$5665 #t)) (jolt-hash-map _o$5664 _o$5665)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types" "check-mode-box" (jolt-invoke (var-deref "clojure.core" "atom") (let* ((_o$5666 (keyword #f "on")) (_o$5667 #f) (_o$5668 (keyword #f "strict")) (_o$5669 #f)) (jolt-hash-map _o$5666 _o$5667 _o$5668 _o$5669))) (let* ((_o$5670 (keyword #f "private")) (_o$5671 #t)) (jolt-hash-map _o$5670 _o$5671)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types" "pm-rets-box" (jolt-invoke (var-deref "clojure.core" "atom") (jolt-hash-map)) (let* ((_o$5672 (keyword #f "private")) (_o$5673 #t)) (jolt-hash-map _o$5672 _o$5673)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types" "mk-env" (letrec ((mk-env (lambda (checking? strict?) (let fnrec5674 ((checking? checking?) (strict? strict?)) (let* ((c (jolt-invoke (var-deref "clojure.core" "deref") (var-deref "jolt.passes.types" "config-box")))) (let* ((_o$5675 (keyword #f "rtenv")) (_o$5676 (jolt-get c (keyword #f "rtenv"))) (_o$5677 (keyword #f "vtypes")) (_o$5678 (jolt-get c (keyword #f "vtypes"))) (_o$5679 (keyword #f "record-shapes")) (_o$5680 (jolt-get c (keyword #f "record-shapes"))) (_o$5681 (keyword #f "protocol-methods")) (_o$5682 (jolt-get c (keyword #f "protocol-methods"))) (_o$5683 (keyword #f "map-shapes?")) (_o$5684 (jolt-get c (keyword #f "map-shapes?"))) (_o$5685 (keyword #f "checking?")) (_o$5686 checking?) (_o$5687 (keyword #f "strict?")) (_o$5688 strict?) (_o$5689 (keyword #f "diags")) (_o$5690 (jolt-invoke (var-deref "clojure.core" "atom") (jolt-vector))) (_o$5691 (keyword #f "calls")) (_o$5692 (jolt-invoke (var-deref "clojure.core" "atom") (jolt-vector))) (_o$5693 (keyword #f "checking-set")) (_o$5694 (jolt-invoke (var-deref "clojure.core" "atom") (jolt-hash-set))) (_o$5695 (keyword #f "diag-memo")) (_o$5696 (jolt-invoke (var-deref "clojure.core" "atom") (jolt-hash-map))) (_o$5697 (keyword #f "escapes")) (_o$5698 (var-deref "jolt.passes.types" "escapes-box")) (_o$5699 (keyword #f "user-sigs")) (_o$5700 (var-deref "jolt.passes.types" "user-sig-box"))) (jolt-hash-map _o$5675 _o$5676 _o$5677 _o$5678 _o$5679 _o$5680 _o$5681 _o$5682 _o$5683 _o$5684 _o$5685 _o$5686 _o$5687 _o$5688 _o$5689 _o$5690 _o$5691 _o$5692 _o$5693 _o$5694 _o$5695 _o$5696 _o$5697 _o$5698 _o$5699 _o$5700))))))) mk-env) (let* ((_o$5701 (keyword #f "private")) (_o$5702 #t)) (jolt-hash-map _o$5701 _o$5702)))) -(guard (e (#t #f)) - (declare-var! "jolt.passes.types" "record-type-from-entry")) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types" "field-type-from-tag" (letrec ((field-type-from-tag (lambda (tag depth shapes) (let fnrec5703 ((tag tag) (depth depth) (shapes shapes)) (if (let* ((or__26__auto (jolt-nil? tag))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-n<= depth 0))) (keyword #f "any") (if (jolt= tag "num") (keyword #f "num") (if (jolt= tag "double") (keyword #f "double") (if (jolt-truthy? (keyword #f "else")) (let* ((e (jolt-get shapes tag))) (if (jolt-truthy? e) (jolt-invoke (var-deref "jolt.passes.types" "record-type-from-entry") e depth shapes) (keyword #f "any"))) jolt-nil)))))))) field-type-from-tag) (let* ((_o$5704 (keyword #f "private")) (_o$5705 #t)) (jolt-hash-map _o$5704 _o$5705)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types" "record-type-from-entry" (letrec ((record-type-from-entry (lambda (rs depth shapes) (let fnrec5706 ((rs rs) (depth depth) (shapes shapes)) (let* ((fields (jolt-get rs (keyword #f "fields"))) (tags (jolt-get rs (keyword #f "tags"))) (fmap (let* ((_a$5715 (lambda (m i) (let fnrec5707 ((m m) (i i)) (let* ((_a$5712 m) (_a$5713 (jolt-nth fields i)) (_a$5714 (let* ((_a$5708 (var-deref "jolt.passes.types" "field-type-from-tag")) (_a$5709 (if (jolt-truthy? tags) (jolt-nth tags i) jolt-nil)) (_a$5710 (jolt-dec depth)) (_a$5711 shapes)) (jolt-invoke _a$5708 _a$5709 _a$5710 _a$5711)))) (jolt-assoc _a$5712 _a$5713 _a$5714))))) (_a$5716 (jolt-hash-map)) (_a$5717 (jolt-range (jolt-count fields)))) (jolt-reduce _a$5715 _a$5716 _a$5717)))) (let* ((_a$5718 (jolt-invoke (var-deref "jolt.passes.types.lattice" "mk-struct") fmap)) (_a$5719 (keyword #f "shape")) (_a$5720 (jolt-invoke (var-deref "clojure.core" "vec") fields)) (_a$5721 (keyword #f "type")) (_a$5722 (jolt-get rs (keyword #f "type")))) (jolt-assoc _a$5718 _a$5719 _a$5720 _a$5721 _a$5722))))))) record-type-from-entry) (let* ((_o$5723 (keyword #f "private")) (_o$5724 #t)) (jolt-hash-map _o$5723 _o$5724)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types" "elem-fns" (let* ((_o$5725 "rand-nth") (_o$5726 "first") (_o$5727 "peek") (_o$5728 "last") (_o$5729 "nth") (_o$5730 "fnext") (_o$5731 "second")) (jolt-hash-set _o$5725 _o$5726 _o$5727 _o$5728 _o$5729 _o$5730 _o$5731)) (let* ((_o$5732 (keyword #f "private")) (_o$5733 #t)) (jolt-hash-map _o$5732 _o$5733)))) -(guard (e (#t #f)) - (declare-var! "jolt.passes.types" "check-user-call")) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types" "var-key" (letrec ((var-key (lambda (fnode) (let fnrec5734 ((fnode fnode)) (let* ((_a$5735 (var-deref "clojure.core" "str")) (_a$5736 (jolt-get fnode (keyword #f "ns"))) (_a$5737 "/") (_a$5738 (jolt-get fnode (keyword #f "name")))) (jolt-invoke _a$5735 _a$5736 _a$5737 _a$5738)))))) var-key) (let* ((_o$5739 (keyword #f "private")) (_o$5740 #t)) (jolt-hash-map _o$5739 _o$5740)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types" "call-ret-type" (letrec ((call-ret-type (lambda (fnode env) (let fnrec5741 ((fnode fnode) (env env)) (let* ((op (jolt-get fnode (keyword #f "op"))) (shapes (jolt-get env (keyword #f "record-shapes")))) (if (jolt= op (keyword #f "var")) (let* ((rs (jolt-get shapes (jolt-invoke (var-deref "jolt.passes.types" "var-key") fnode)))) (if (jolt-truthy? rs) (jolt-invoke (var-deref "jolt.passes.types" "record-type-from-entry") rs (var-deref "jolt.passes.types.lattice" "type-depth") shapes) (let* ((r (let* ((_a$5742 (jolt-get env (keyword #f "rtenv"))) (_a$5743 (jolt-invoke (var-deref "jolt.passes.types" "var-key") fnode))) (jolt-get _a$5742 _a$5743)))) (if (jolt-truthy? r) r (let* ((pm (let* ((_a$5744 (jolt-get env (keyword #f "protocol-methods"))) (_a$5745 (jolt-invoke (var-deref "jolt.passes.types" "var-key") fnode))) (jolt-get _a$5744 _a$5745))) (pmr (if (jolt-truthy? pm) (let* ((_a$5750 (jolt-invoke (var-deref "clojure.core" "deref") (var-deref "jolt.passes.types" "pm-rets-box"))) (_a$5751 (let* ((_a$5746 (var-deref "clojure.core" "str")) (_a$5747 (jolt-nth pm 0)) (_a$5748 "/") (_a$5749 (jolt-nth pm 1))) (jolt-invoke _a$5746 _a$5747 _a$5748 _a$5749)))) (jolt-get _a$5750 _a$5751)) jolt-nil))) (if (jolt-truthy? (let* ((and__25__auto pmr)) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "clojure.core" "not=") pmr (keyword #f "any")) and__25__auto))) pmr (let* ((nm (let* ((and__25__auto (jolt= "clojure.core" (jolt-get fnode (keyword #f "ns"))))) (if (jolt-truthy? and__25__auto) (jolt-get fnode (keyword #f "name")) and__25__auto)))) (if (jolt-nil? nm) (keyword #f "any") (if (jolt-contains? (var-deref "jolt.passes.types.lattice" "num-ret-fns") nm) (keyword #f "num") (if (jolt-contains? (var-deref "jolt.passes.types.lattice" "vector-ret-fns") nm) (jolt-invoke (var-deref "jolt.passes.types.lattice" "mk-vec") (keyword #f "any")) (if (jolt-truthy? (keyword #f "else")) (keyword #f "any") jolt-nil))))))))))) (if (jolt= op (keyword #f "host")) (let* ((nm (jolt-get fnode (keyword #f "name")))) (if (jolt-contains? (var-deref "jolt.passes.types.lattice" "num-ret-fns") nm) (keyword #f "num") (if (jolt-contains? (var-deref "jolt.passes.types.lattice" "vector-ret-fns") nm) (jolt-invoke (var-deref "jolt.passes.types.lattice" "mk-vec") (keyword #f "any")) (if (jolt-truthy? (keyword #f "else")) (keyword #f "any") jolt-nil)))) (if (jolt-truthy? (keyword #f "else")) (keyword #f "any") jolt-nil)))))))) call-ret-type) (let* ((_o$5752 (keyword #f "private")) (_o$5753 #t)) (jolt-hash-map _o$5752 _o$5753)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types" "fold-preds" (let* ((_o$5754 "number?") (_o$5755 "string?") (_o$5756 "keyword?") (_o$5757 "record?") (_o$5758 "nil?") (_o$5759 "some?")) (jolt-hash-set _o$5754 _o$5755 _o$5756 _o$5757 _o$5758 _o$5759)) (let* ((_o$5760 (keyword #f "private")) (_o$5761 #t)) (jolt-hash-map _o$5760 _o$5761)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types" "record-t?" (letrec ((record-t? (lambda (t) (let fnrec5762 ((t t)) (let* ((and__25__auto (jolt-invoke (var-deref "jolt.passes.types.lattice" "struct-type?") t))) (if (jolt-truthy? and__25__auto) (jolt-some? (jolt-get t (keyword #f "type"))) and__25__auto)))))) record-t?) (let* ((_o$5763 (keyword #f "private")) (_o$5764 #t)) (jolt-hash-map _o$5763 _o$5764)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types" "pred-on" (letrec ((pred-on (lambda (pname t) (let fnrec5765 ((pname pname) (t t)) (if (let* ((or__26__auto (jolt= t (keyword #f "any")))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt= t (keyword #f "truthy")))) jolt-nil (if (jolt-truthy? (jolt-invoke (var-deref "jolt.passes.types.lattice" "nilable?") t)) jolt-nil (if (jolt-truthy? (jolt-invoke (var-deref "jolt.passes.types.lattice" "union-type?") t)) (let* ((vs (let* ((_a$5767 (lambda (m) (let fnrec5766 ((m m)) (pred-on pname m)))) (_a$5768 (jolt-invoke (var-deref "jolt.passes.types.lattice" "umembers") t))) (jolt-map _a$5767 _a$5768)))) (if (jolt-truthy? (let* ((and__25__auto (jolt-seq vs))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt-not (jolt-nil? (jolt-first vs))))) (if (jolt-truthy? and__25__auto) (jolt-apply jolt= vs) and__25__auto)) and__25__auto))) (jolt-first vs) jolt-nil)) (if (jolt-truthy? (keyword #f "else")) (let* ((G__138 pname)) (if (jolt= G__138 "number?") (let* ((or__26__auto (jolt= t (keyword #f "num")))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt= t (keyword #f "double")))) (if (jolt= G__138 "string?") (jolt= t (keyword #f "str")) (if (jolt= G__138 "keyword?") (jolt= t (keyword #f "kw")) (if (jolt= G__138 "record?") (jolt-invoke (var-deref "jolt.passes.types" "record-t?") t) (if (jolt= G__138 "nil?") #f (if (jolt= G__138 "some?") #t jolt-nil))))))) jolt-nil)))))))) pred-on) (let* ((_o$5769 (keyword #f "private")) (_o$5770 #t)) (jolt-hash-map _o$5769 _o$5770)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types" "pure-node?" (letrec ((pure-node? (lambda (n) (let fnrec5771 ((n n)) (let* ((op (jolt-get n (keyword #f "op")))) (let* ((or__26__auto (jolt= op (keyword #f "const")))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt= op (keyword #f "local"))))))))) pure-node?) (let* ((_o$5772 (keyword #f "private")) (_o$5773 #t)) (jolt-hash-map _o$5772 _o$5773)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types" "test-local" (letrec ((test-local (lambda (test pred-name) (let fnrec5774 ((test test) (pred-name pred-name)) (if (jolt= (keyword #f "invoke") (jolt-get test (keyword #f "op"))) (let* ((f (jolt-get test (keyword #f "fn"))) (args (jolt-get test (keyword #f "args")))) (if (let* ((and__25__auto (jolt= (keyword #f "var") (jolt-get f (keyword #f "op"))))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt= "clojure.core" (jolt-get f (keyword #f "ns"))))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt= pred-name (jolt-get f (keyword #f "name"))))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt= 1 (jolt-count args)))) (if (jolt-truthy? and__25__auto) (jolt= (keyword #f "local") (jolt-get (jolt-nth args 0) (keyword #f "op"))) and__25__auto)) and__25__auto)) and__25__auto)) and__25__auto)) (jolt-get (jolt-nth args 0) (keyword #f "name")) jolt-nil)) jolt-nil))))) test-local) (let* ((_o$5775 (keyword #f "private")) (_o$5776 #t)) (jolt-hash-map _o$5775 _o$5776)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types" "narrow-nonnil" (letrec ((narrow-nonnil (lambda (tenv nm) (let fnrec5777 ((tenv tenv) (nm nm)) (let* ((t (jolt-get tenv nm))) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.passes.types.lattice" "nilable?") t)) (jolt-assoc tenv nm (jolt-invoke (var-deref "jolt.passes.types.lattice" "strip-nilable") t)) tenv)))))) narrow-nonnil) (let* ((_o$5778 (keyword #f "private")) (_o$5779 #t)) (jolt-hash-map _o$5778 _o$5779)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types" "if-narrow" (letrec ((if-narrow (lambda (test tenv) (let fnrec5780 ((test test) (tenv tenv)) (let* ((somev (jolt-invoke (var-deref "jolt.passes.types" "test-local") test "some?")) (nilv (jolt-invoke (var-deref "jolt.passes.types" "test-local") test "nil?"))) (if (jolt= (keyword #f "local") (jolt-get test (keyword #f "op"))) (let* ((_o$5781 (jolt-invoke (var-deref "jolt.passes.types" "narrow-nonnil") tenv (jolt-get test (keyword #f "name")))) (_o$5782 tenv)) (jolt-vector _o$5781 _o$5782)) (if (jolt-truthy? somev) (let* ((_o$5783 (jolt-invoke (var-deref "jolt.passes.types" "narrow-nonnil") tenv somev)) (_o$5784 tenv)) (jolt-vector _o$5783 _o$5784)) (if (jolt-truthy? nilv) (let* ((_o$5785 tenv) (_o$5786 (jolt-invoke (var-deref "jolt.passes.types" "narrow-nonnil") tenv nilv))) (jolt-vector _o$5785 _o$5786)) (if (jolt-truthy? (keyword #f "else")) (let* ((_o$5787 tenv) (_o$5788 tenv)) (jolt-vector _o$5787 _o$5788)) jolt-nil))))))))) if-narrow) (let* ((_o$5789 (keyword #f "private")) (_o$5790 #t)) (jolt-hash-map _o$5789 _o$5790)))) -(guard (e (#t #f)) - (declare-var! "jolt.passes.types" "infer")) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types" "ty" (letrec ((ty (lambda (r) (let fnrec5791 ((r r)) (jolt-nth r 0))))) ty) (let* ((_o$5792 (keyword #f "private")) (_o$5793 #t)) (jolt-hash-map _o$5792 _o$5793)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types" "nd" (letrec ((nd (lambda (r) (let fnrec5794 ((r r)) (jolt-nth r 1))))) nd) (let* ((_o$5795 (keyword #f "private")) (_o$5796 #t)) (jolt-hash-map _o$5795 _o$5796)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types" "self-rec-argtys" (letrec ((self-rec-argtys (lambda (args ares self-params) (let fnrec5797 ((args args) (ares ares) (self-params self-params)) (let* ((_a$5801 (var-deref "clojure.core" "mapv")) (_a$5802 (lambda (i) (let fnrec5798 ((i i)) (let* ((a (jolt-nth args i))) (if (jolt-truthy? (let* ((and__25__auto self-params)) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt-n< i (jolt-count self-params)))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt= (keyword #f "local") (jolt-get a (keyword #f "op"))))) (if (jolt-truthy? and__25__auto) (let* ((_a$5799 (jolt-get a (keyword #f "name"))) (_a$5800 (jolt-nth self-params i))) (jolt= _a$5799 _a$5800)) and__25__auto)) and__25__auto)) and__25__auto))) jolt-nil (jolt-invoke (var-deref "jolt.passes.types" "ty") (jolt-nth ares i))))))) (_a$5803 (jolt-range (jolt-count ares)))) (jolt-invoke _a$5801 _a$5802 _a$5803)))))) self-rec-argtys) (let* ((_o$5804 (keyword #f "private")) (_o$5805 #t)) (jolt-hash-map _o$5804 _o$5805)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types" "dbl-arith-ops" (let* ((_o$5806 "+") (_o$5807 "-") (_o$5808 "*") (_o$5809 "/") (_o$5810 "min") (_o$5811 "max") (_o$5812 "inc") (_o$5813 "dec")) (jolt-hash-set _o$5806 _o$5807 _o$5808 _o$5809 _o$5810 _o$5811 _o$5812 _o$5813)) (let* ((_o$5814 (keyword #f "private")) (_o$5815 #t)) (jolt-hash-map _o$5814 _o$5815)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types" "int-lit-node?" (letrec ((int-lit-node? (lambda (n) (let fnrec5816 ((n n)) (let* ((and__25__auto (jolt= (keyword #f "const") (jolt-get n (keyword #f "op"))))) (if (jolt-truthy? and__25__auto) (let* ((v (jolt-get n (keyword #f "val")))) (let* ((and__25__auto (jolt-invoke (var-deref "clojure.core" "number?") v))) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "clojure.core" "integer?") v) and__25__auto))) and__25__auto)))))) int-lit-node?) (let* ((_o$5817 (keyword #f "private")) (_o$5818 #t)) (jolt-hash-map _o$5817 _o$5818)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types" "dbl-arith?" (letrec ((dbl-arith? (lambda (ares argnodes) (let fnrec5819 ((ares ares) (argnodes argnodes)) (let* ((and__25__auto (jolt-pos? (jolt-count ares)))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (let* ((_a$5821 (var-deref "clojure.core" "every?")) (_a$5822 (lambda (i) (let fnrec5820 ((i i)) (let* ((or__26__auto (jolt= (keyword #f "double") (jolt-invoke (var-deref "jolt.passes.types" "ty") (jolt-nth ares i))))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-invoke (var-deref "jolt.passes.types" "int-lit-node?") (jolt-nth argnodes i))))))) (_a$5823 (jolt-range (jolt-count ares)))) (jolt-invoke _a$5821 _a$5822 _a$5823)))) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "clojure.core" "some") (lambda (r) (let fnrec5824 ((r r)) (jolt= (keyword #f "double") (jolt-invoke (var-deref "jolt.passes.types" "ty") r)))) ares) and__25__auto)) and__25__auto)))))) dbl-arith?) (let* ((_o$5825 (keyword #f "private")) (_o$5826 #t)) (jolt-hash-map _o$5825 _o$5826)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types" "hof-table" (let* ((_o$5843 "map") (_o$5844 (let* ((_o$5827 (keyword #f "epos")) (_o$5828 0)) (jolt-hash-map _o$5827 _o$5828))) (_o$5845 "mapv") (_o$5846 (let* ((_o$5829 (keyword #f "epos")) (_o$5830 0)) (jolt-hash-map _o$5829 _o$5830))) (_o$5847 "filter") (_o$5848 (let* ((_o$5831 (keyword #f "epos")) (_o$5832 0)) (jolt-hash-map _o$5831 _o$5832))) (_o$5849 "filterv") (_o$5850 (let* ((_o$5833 (keyword #f "epos")) (_o$5834 0)) (jolt-hash-map _o$5833 _o$5834))) (_o$5851 "keep") (_o$5852 (let* ((_o$5835 (keyword #f "epos")) (_o$5836 0)) (jolt-hash-map _o$5835 _o$5836))) (_o$5853 "remove") (_o$5854 (let* ((_o$5837 (keyword #f "epos")) (_o$5838 0)) (jolt-hash-map _o$5837 _o$5838))) (_o$5855 "run!") (_o$5856 (let* ((_o$5839 (keyword #f "epos")) (_o$5840 0)) (jolt-hash-map _o$5839 _o$5840))) (_o$5857 "mapcat") (_o$5858 (let* ((_o$5841 (keyword #f "epos")) (_o$5842 0)) (jolt-hash-map _o$5841 _o$5842)))) (jolt-hash-map _o$5843 _o$5844 _o$5845 _o$5846 _o$5847 _o$5848 _o$5849 _o$5850 _o$5851 _o$5852 _o$5853 _o$5854 _o$5855 _o$5856 _o$5857 _o$5858)) (let* ((_o$5859 (keyword #f "private")) (_o$5860 #t)) (jolt-hash-map _o$5859 _o$5860)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types" "infer-fn-seeded" (letrec ((infer-fn-seeded (lambda (node seeds tenv env) (let fnrec5861 ((node node) (seeds seeds) (tenv tenv) (env env)) (let* ((res (let* ((_a$5872 (var-deref "clojure.core" "mapv")) (_a$5873 (lambda (a) (let fnrec5862 ((a a)) (let* ((params (jolt-get a (keyword #f "params"))) (pe (let* ((_a$5867 (lambda (e i) (let fnrec5863 ((e e) (i i)) (let* ((_a$5864 e) (_a$5865 (jolt-nth params i)) (_a$5866 (let* ((s (jolt-get seeds i))) (if (jolt-truthy? s) s (keyword #f "any"))))) (jolt-assoc _a$5864 _a$5865 _a$5866))))) (_a$5868 tenv) (_a$5869 (jolt-range (jolt-count params)))) (jolt-reduce _a$5867 _a$5868 _a$5869))) (pe (if (jolt-truthy? (jolt-get a (keyword #f "rest"))) (jolt-assoc pe (jolt-get a (keyword #f "rest")) (keyword #f "any")) pe)) (br (jolt-invoke (var-deref "jolt.passes.types" "infer") (jolt-get a (keyword #f "body")) pe env))) (let* ((_o$5870 (jolt-invoke (var-deref "jolt.passes.types" "ty") br)) (_o$5871 (jolt-assoc a (keyword #f "body") (jolt-invoke (var-deref "jolt.passes.types" "nd") br)))) (jolt-vector _o$5870 _o$5871)))))) (_a$5874 (jolt-get node (keyword #f "arities")))) (jolt-invoke _a$5872 _a$5873 _a$5874))) (rets (jolt-invoke (var-deref "clojure.core" "mapv") (lambda (r) (let fnrec5875 ((r r)) (jolt-invoke (var-deref "jolt.passes.types" "ty") r))) res)) (ret (if (jolt-empty? rets) (keyword #f "any") (let* ((_a$5876 (var-deref "jolt.passes.types.lattice" "join")) (_a$5877 (jolt-first rets)) (_a$5878 (jolt-rest rets))) (jolt-reduce _a$5876 _a$5877 _a$5878))))) (let* ((_o$5880 ret) (_o$5881 (jolt-assoc node (keyword #f "arities") (jolt-invoke (var-deref "clojure.core" "mapv") (lambda (r) (let fnrec5879 ((r r)) (jolt-invoke (var-deref "jolt.passes.types" "nd") r))) res)))) (jolt-vector _o$5880 _o$5881))))))) infer-fn-seeded) (let* ((_o$5882 (keyword #f "private")) (_o$5883 #t) (_o$5884 (keyword #f "doc")) (_o$5885 "Infer a fn-literal passed to a HOF, seeding the given params to element/accum\n types (seeds: param-index -> type), other params :any, captured locals from\n tenv. Returns [ret-type node'] \x2014; ret is the lub of arity tail types, used to\n type the HOF result (e.g. reduce's accumulator, mapv's element).")) (jolt-hash-map _o$5882 _o$5883 _o$5884 _o$5885)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types" "infer-pred-fold" (letrec ((infer-pred-fold (lambda (node fnode cn args tenv env) (let fnrec5886 ((node node) (fnode fnode) (cn cn) (args args) (tenv tenv) (env env)) (let* ((ar (jolt-invoke (var-deref "jolt.passes.types" "infer") (jolt-nth args 0) tenv env)) (v (jolt-invoke (var-deref "jolt.passes.types" "pred-on") cn (jolt-invoke (var-deref "jolt.passes.types" "ty") ar)))) (if (jolt-truthy? (let* ((and__25__auto (jolt-not (jolt-nil? v)))) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "jolt.passes.types" "pure-node?") (jolt-invoke (var-deref "jolt.passes.types" "nd") ar)) and__25__auto))) (let* ((_o$5891 (keyword #f "any")) (_o$5892 (let* ((_o$5887 (keyword #f "op")) (_o$5888 (keyword #f "const")) (_o$5889 (keyword #f "val")) (_o$5890 v)) (jolt-hash-map _o$5887 _o$5888 _o$5889 _o$5890)))) (jolt-vector _o$5891 _o$5892)) (let* ((_o$5893 (jolt-invoke (var-deref "jolt.passes.types" "call-ret-type") fnode env)) (_o$5894 (jolt-assoc node (keyword #f "args") (jolt-vector (jolt-invoke (var-deref "jolt.passes.types" "nd") ar))))) (jolt-vector _o$5893 _o$5894)))))))) infer-pred-fold) (let* ((_o$5895 (keyword #f "private")) (_o$5896 #t) (_o$5897 (keyword #f "doc")) (_o$5898 "A type predicate over a single side-effect-free arg whose type PROVES the answer\n folds to a boolean constant \x2014; eliminating the call, and (once const-fold runs\n after inference) collapsing any `if` it gates. Falls back to the normal call path\n when the answer isn't provable or the arg is impure.")) (jolt-hash-map _o$5895 _o$5896 _o$5897 _o$5898)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types" "infer-kw-lookup" (letrec ((infer-kw-lookup (lambda (node fnode args n tenv env) (let fnrec5899 ((node node) (fnode fnode) (args args) (n n) (tenv tenv) (env env)) (let* ((mr (jolt-invoke (var-deref "jolt.passes.types" "infer") (jolt-nth args 0) tenv env)) (mt (jolt-invoke (var-deref "jolt.passes.types" "ty") mr)) (msub (if (jolt-truthy? (jolt-invoke (var-deref "jolt.passes.types.lattice" "struct-safe?") mt)) (jolt-invoke (var-deref "jolt.passes.types.lattice" "mark-struct") (jolt-invoke (var-deref "jolt.passes.types" "nd") mr) mt) (jolt-invoke (var-deref "jolt.passes.types" "nd") mr))) (ft (jolt-invoke (var-deref "jolt.passes.types.lattice" "field-type") mt (jolt-get fnode (keyword #f "val")))) (dr (if (jolt= n 2) (jolt-invoke (var-deref "jolt.passes.types" "infer") (jolt-nth args 1) tenv env) jolt-nil)) (rt (if (jolt-truthy? dr) (jolt-invoke (var-deref "jolt.passes.types.lattice" "join") ft (jolt-invoke (var-deref "jolt.passes.types" "ty") dr)) ft)) (node_PRIME_ (jolt-assoc node (keyword #f "args") (if (jolt-truthy? dr) (let* ((_o$5900 msub) (_o$5901 (jolt-invoke (var-deref "jolt.passes.types" "nd") dr))) (jolt-vector _o$5900 _o$5901)) (jolt-vector msub))))) (let* ((_o$5902 rt) (_o$5903 (if (jolt= rt (keyword #f "double")) (jolt-assoc node_PRIME_ (keyword #f "num-read") (keyword #f "double")) node_PRIME_))) (jolt-vector _o$5902 _o$5903))))))) infer-kw-lookup) (let* ((_o$5904 (keyword #f "private")) (_o$5905 #t) (_o$5906 (keyword #f "doc")) (_o$5907 "(:k m) / (:k m default): the result is m's field type, and if m is a struct the\n subject is tagged so the back end drops the guard \x2014; this types nested access end\n to end (RFC 0005).")) (jolt-hash-map _o$5904 _o$5905 _o$5906 _o$5907)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types" "infer-get-lookup" (letrec ((infer-get-lookup (lambda (node args n tenv env) (let fnrec5908 ((node node) (args args) (n n) (tenv tenv) (env env)) (let* ((mr (jolt-invoke (var-deref "jolt.passes.types" "infer") (jolt-nth args 0) tenv env)) (mt (jolt-invoke (var-deref "jolt.passes.types" "ty") mr)) (msub (if (jolt-truthy? (jolt-invoke (var-deref "jolt.passes.types.lattice" "struct-safe?") mt)) (jolt-invoke (var-deref "jolt.passes.types.lattice" "mark-struct") (jolt-invoke (var-deref "jolt.passes.types" "nd") mr) mt) (jolt-invoke (var-deref "jolt.passes.types" "nd") mr))) (kr (jolt-invoke (var-deref "jolt.passes.types" "infer") (jolt-nth args 1) tenv env)) (ft (jolt-invoke (var-deref "jolt.passes.types.lattice" "field-type") mt (jolt-get (jolt-nth args 1) (keyword #f "val")))) (dr (if (jolt= n 3) (jolt-invoke (var-deref "jolt.passes.types" "infer") (jolt-nth args 2) tenv env) jolt-nil)) (rt (if (jolt-truthy? dr) (jolt-invoke (var-deref "jolt.passes.types.lattice" "join") ft (jolt-invoke (var-deref "jolt.passes.types" "ty") dr)) ft)) (node_PRIME_ (jolt-assoc node (keyword #f "args") (if (jolt-truthy? dr) (let* ((_o$5909 msub) (_o$5910 (jolt-invoke (var-deref "jolt.passes.types" "nd") kr)) (_o$5911 (jolt-invoke (var-deref "jolt.passes.types" "nd") dr))) (jolt-vector _o$5909 _o$5910 _o$5911)) (let* ((_o$5912 msub) (_o$5913 (jolt-invoke (var-deref "jolt.passes.types" "nd") kr))) (jolt-vector _o$5912 _o$5913)))))) (let* ((_o$5914 rt) (_o$5915 (if (jolt= rt (keyword #f "double")) (jolt-assoc node_PRIME_ (keyword #f "num-read") (keyword #f "double")) node_PRIME_))) (jolt-vector _o$5914 _o$5915))))))) infer-get-lookup) (let* ((_o$5916 (keyword #f "private")) (_o$5917 #t) (_o$5918 (keyword #f "doc")) (_o$5919 "(get m :k [default]): the keyword-lookup result type, when the key is a constant\n keyword.")) (jolt-hash-map _o$5916 _o$5917 _o$5918 _o$5919)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types" "infer-reduce-hof" (letrec ((infer-reduce-hof (lambda (node args n tenv env) (let fnrec5920 ((node node) (args args) (n n) (tenv tenv) (env env)) (let* ((three (jolt-n>= n 3)) (coll-r (jolt-invoke (var-deref "jolt.passes.types" "infer") (jolt-nth args (if (jolt-truthy? three) 2 1)) tenv env)) (init-r (if (jolt-truthy? three) (jolt-invoke (var-deref "jolt.passes.types" "infer") (jolt-nth args 1) tenv env) jolt-nil)) (et (let* ((ct (jolt-invoke (var-deref "jolt.passes.types" "ty") coll-r))) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.passes.types.lattice" "vec-type?") ct)) (jolt-invoke (var-deref "jolt.passes.types.lattice" "velem") ct) (keyword #f "any")))) (init-t (if (jolt-truthy? init-r) (jolt-invoke (var-deref "jolt.passes.types" "ty") init-r) (keyword #f "any"))) (fn-r (let* ((_a$5925 (var-deref "jolt.passes.types" "infer-fn-seeded")) (_a$5926 (jolt-nth args 0)) (_a$5927 (let* ((_o$5921 0) (_o$5922 init-t) (_o$5923 1) (_o$5924 et)) (jolt-hash-map _o$5921 _o$5922 _o$5923 _o$5924))) (_a$5928 tenv) (_a$5929 env)) (jolt-invoke _a$5925 _a$5926 _a$5927 _a$5928 _a$5929)))) (let* ((_o$5935 (jolt-invoke (var-deref "jolt.passes.types.lattice" "join") init-t (jolt-invoke (var-deref "jolt.passes.types" "ty") fn-r))) (_o$5936 (jolt-assoc node (keyword #f "args") (if (jolt-truthy? three) (let* ((_o$5930 (jolt-invoke (var-deref "jolt.passes.types" "nd") fn-r)) (_o$5931 (jolt-invoke (var-deref "jolt.passes.types" "nd") init-r)) (_o$5932 (jolt-invoke (var-deref "jolt.passes.types" "nd") coll-r))) (jolt-vector _o$5930 _o$5931 _o$5932)) (let* ((_o$5933 (jolt-invoke (var-deref "jolt.passes.types" "nd") fn-r)) (_o$5934 (jolt-invoke (var-deref "jolt.passes.types" "nd") coll-r))) (jolt-vector _o$5933 _o$5934)))))) (jolt-vector _o$5935 _o$5936))))))) infer-reduce-hof) (let* ((_o$5937 (keyword #f "private")) (_o$5938 #t) (_o$5939 (keyword #f "doc")) (_o$5940 "reduce over a typed vector with a fn-literal: seed the closure's accumulator\n (param 0) to the init type and its element (param 1) to the vector's element\n type, so its body \x2014; and any calls it makes \x2014; see those types.")) (jolt-hash-map _o$5937 _o$5938 _o$5939 _o$5940)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types" "infer-seq-hof" (letrec ((infer-seq-hof (lambda (node cn args tenv env) (let fnrec5941 ((node node) (cn cn) (args args) (tenv tenv) (env env)) (let* ((coll-r (jolt-invoke (var-deref "jolt.passes.types" "infer") (jolt-nth args 1) tenv env)) (et (let* ((ct (jolt-invoke (var-deref "jolt.passes.types" "ty") coll-r))) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.passes.types.lattice" "vec-type?") ct)) (jolt-invoke (var-deref "jolt.passes.types.lattice" "velem") ct) (keyword #f "any")))) (fn-r (let* ((_a$5944 (var-deref "jolt.passes.types" "infer-fn-seeded")) (_a$5945 (jolt-nth args 0)) (_a$5946 (let* ((_o$5942 (jolt-get (jolt-get (var-deref "jolt.passes.types" "hof-table") cn) (keyword #f "epos"))) (_o$5943 et)) (jolt-hash-map _o$5942 _o$5943))) (_a$5947 tenv) (_a$5948 env)) (jolt-invoke _a$5944 _a$5945 _a$5946 _a$5947 _a$5948))) (rt (if (jolt= cn "mapv") (jolt-invoke (var-deref "jolt.passes.types.lattice" "mk-vec") (jolt-invoke (var-deref "jolt.passes.types" "ty") fn-r)) (if (jolt= cn "filterv") (jolt-invoke (var-deref "jolt.passes.types.lattice" "mk-vec") et) (if (jolt-truthy? (keyword #f "else")) (keyword #f "any") jolt-nil))))) (let* ((_o$5951 rt) (_o$5952 (jolt-assoc node (keyword #f "args") (let* ((_o$5949 (jolt-invoke (var-deref "jolt.passes.types" "nd") fn-r)) (_o$5950 (jolt-invoke (var-deref "jolt.passes.types" "nd") coll-r))) (jolt-vector _o$5949 _o$5950))))) (jolt-vector _o$5951 _o$5952))))))) infer-seq-hof) (let* ((_o$5953 (keyword #f "private")) (_o$5954 #t) (_o$5955 (keyword #f "doc")) (_o$5956 "map/mapv/filter/... over a typed vector with a fn-literal: seed the fn's element\n param; mapv/filterv produce a typed vector.")) (jolt-hash-map _o$5953 _o$5954 _o$5955 _o$5956)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types" "infer-conj-into" (letrec ((infer-conj-into (lambda (node fnode cn args n tenv env) (let fnrec5957 ((node node) (fnode fnode) (cn cn) (args args) (n n) (tenv tenv) (env env)) (let* ((ares (jolt-invoke (var-deref "clojure.core" "mapv") (lambda (a) (let fnrec5958 ((a a)) (jolt-invoke (var-deref "jolt.passes.types" "infer") a tenv env))) args)) (base (jolt-invoke (var-deref "jolt.passes.types" "ty") (jolt-nth ares 0))) (rest-ts (let* ((_a$5960 (var-deref "clojure.core" "mapv")) (_a$5961 (lambda (r) (let fnrec5959 ((r r)) (jolt-invoke (var-deref "jolt.passes.types" "ty") r)))) (_a$5962 (jolt-rest ares))) (jolt-invoke _a$5960 _a$5961 _a$5962))) (rt (if (jolt-truthy? (let* ((and__25__auto (jolt= cn "conj"))) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "jolt.passes.types.lattice" "vec-type?") base) and__25__auto))) (jolt-invoke (var-deref "jolt.passes.types.lattice" "mk-vec") (jolt-reduce (var-deref "jolt.passes.types.lattice" "join") (jolt-invoke (var-deref "jolt.passes.types.lattice" "velem") base) rest-ts)) (if (jolt-truthy? (let* ((and__25__auto (jolt= cn "into"))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt-invoke (var-deref "jolt.passes.types.lattice" "vec-type?") base))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt= 2 n))) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "jolt.passes.types.lattice" "vec-type?") (jolt-nth rest-ts 0)) and__25__auto)) and__25__auto)) and__25__auto))) (jolt-invoke (var-deref "jolt.passes.types.lattice" "mk-vec") (let* ((_a$5963 (var-deref "jolt.passes.types.lattice" "join")) (_a$5964 (jolt-invoke (var-deref "jolt.passes.types.lattice" "velem") base)) (_a$5965 (jolt-invoke (var-deref "jolt.passes.types.lattice" "velem") (jolt-nth rest-ts 0)))) (jolt-invoke _a$5963 _a$5964 _a$5965))) (if (jolt-truthy? (keyword #f "else")) (jolt-invoke (var-deref "jolt.passes.types" "call-ret-type") fnode env) jolt-nil))))) (let* ((_o$5967 rt) (_o$5968 (jolt-assoc node (keyword #f "args") (jolt-invoke (var-deref "clojure.core" "mapv") (lambda (r) (let fnrec5966 ((r r)) (jolt-invoke (var-deref "jolt.passes.types" "nd") r))) ares)))) (jolt-vector _o$5967 _o$5968))))))) infer-conj-into) (let* ((_o$5969 (keyword #f "private")) (_o$5970 #t) (_o$5971 (keyword #f "doc")) (_o$5972 "conj/into: track the element type of a vector being grown.")) (jolt-hash-map _o$5969 _o$5970 _o$5971 _o$5972)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types" "infer-call" (letrec ((infer-call (lambda (node fnode iscall-var cn args n tenv env) (let fnrec5973 ((node node) (fnode fnode) (iscall-var iscall-var) (cn cn) (args args) (n n) (tenv tenv) (env env)) (let* ((fr (if (jolt-not iscall-var) (jolt-invoke (var-deref "jolt.passes.types" "infer") fnode tenv env) jolt-nil)) (fnode_PRIME_ (if (jolt-truthy? iscall-var) fnode (jolt-invoke (var-deref "jolt.passes.types" "nd") fr))) (callee-t (if (jolt-truthy? iscall-var) (let* ((_a$5974 (jolt-get env (keyword #f "vtypes"))) (_a$5975 (jolt-invoke (var-deref "jolt.passes.types" "var-key") fnode))) (jolt-get _a$5974 _a$5975)) (jolt-invoke (var-deref "jolt.passes.types" "ty") fr))) (ares (jolt-invoke (var-deref "clojure.core" "mapv") (lambda (a) (let fnrec5976 ((a a)) (jolt-invoke (var-deref "jolt.passes.types" "infer") a tenv env))) args))) (begin (if (jolt-truthy? iscall-var) (let* ((_a$5982 (var-deref "clojure.core" "swap!")) (_a$5983 (jolt-get env (keyword #f "calls"))) (_a$5984 jolt-conj) (_a$5985 (let* ((_o$5980 (jolt-invoke (var-deref "jolt.passes.types" "var-key") fnode)) (_o$5981 (if (let* ((_a$5977 (jolt-invoke (var-deref "jolt.passes.types" "var-key") fnode)) (_a$5978 (jolt-get env (keyword #f "self-key")))) (jolt= _a$5977 _a$5978)) (jolt-invoke (var-deref "jolt.passes.types" "self-rec-argtys") args ares (jolt-get env (keyword #f "self-params"))) (jolt-invoke (var-deref "clojure.core" "mapv") (lambda (r) (let fnrec5979 ((r r)) (jolt-invoke (var-deref "jolt.passes.types" "ty") r))) ares)))) (jolt-vector _o$5980 _o$5981)))) (jolt-invoke _a$5982 _a$5983 _a$5984 _a$5985)) jolt-nil) (if (jolt-truthy? (let* ((and__25__auto (jolt= (keyword #f "local") (jolt-get fnode (keyword #f "op"))))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt-get env (keyword #f "self-key")))) (if (jolt-truthy? and__25__auto) (let* ((_a$5986 (jolt-get fnode (keyword #f "name"))) (_a$5987 (jolt-get env (keyword #f "self-name")))) (jolt= _a$5986 _a$5987)) and__25__auto)) and__25__auto))) (let* ((_a$5990 (var-deref "clojure.core" "swap!")) (_a$5991 (jolt-get env (keyword #f "calls"))) (_a$5992 jolt-conj) (_a$5993 (let* ((_o$5988 (jolt-get env (keyword #f "self-key"))) (_o$5989 (jolt-invoke (var-deref "jolt.passes.types" "self-rec-argtys") args ares (jolt-get env (keyword #f "self-params"))))) (jolt-vector _o$5988 _o$5989)))) (jolt-invoke _a$5990 _a$5991 _a$5992 _a$5993)) jolt-nil) (if (jolt-truthy? (jolt-get env (keyword #f "checking?"))) (let* ((ats (jolt-invoke (var-deref "clojure.core" "mapv") (lambda (r) (let fnrec5994 ((r r)) (jolt-invoke (var-deref "jolt.passes.types" "ty") r))) ares)) (pos (jolt-get node (keyword #f "pos")))) (begin (if (jolt-truthy? cn) (jolt-invoke (var-deref "jolt.passes.types.check" "check-invoke") cn args ats pos env) jolt-nil) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.passes.types.check" "not-callable?") callee-t)) (let* ((_a$6003 (var-deref "clojure.core" "swap!")) (_a$6004 (jolt-get env (keyword #f "diags"))) (_a$6005 jolt-conj) (_a$6006 (let* ((_o$5995 (keyword #f "op")) (_o$5996 (keyword #f "call")) (_o$5997 (keyword #f "type")) (_o$5998 (jolt-invoke (var-deref "jolt.passes.types.check" "type-name") callee-t)) (_o$5999 (keyword #f "pos")) (_o$6000 pos) (_o$6001 (keyword #f "msg")) (_o$6002 (jolt-invoke (var-deref "clojure.core" "str") "cannot call " (jolt-invoke (var-deref "jolt.passes.types.check" "type-name") callee-t) " as a function"))) (jolt-hash-map _o$5995 _o$5996 _o$5997 _o$5998 _o$5999 _o$6000 _o$6001 _o$6002)))) (jolt-invoke _a$6003 _a$6004 _a$6005 _a$6006)) jolt-nil) (if (jolt-truthy? (let* ((and__25__auto (jolt-get env (keyword #f "strict?")))) (if (jolt-truthy? and__25__auto) iscall-var and__25__auto))) (let* ((k (jolt-invoke (var-deref "jolt.passes.types" "var-key") fnode)) (usig (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (jolt-get env (keyword #f "user-sigs"))) k))) (if (jolt-truthy? usig) (jolt-invoke (var-deref "jolt.passes.types" "check-user-call") k usig ats pos env) jolt-nil)) jolt-nil))) jolt-nil) (let* ((pm (let* ((and__25__auto iscall-var)) (if (jolt-truthy? and__25__auto) (let* ((_a$6007 (jolt-get env (keyword #f "protocol-methods"))) (_a$6008 (jolt-invoke (var-deref "jolt.passes.types" "var-key") fnode))) (jolt-get _a$6007 _a$6008)) and__25__auto))) (rtype (if (jolt-truthy? (let* ((and__25__auto pm)) (if (jolt-truthy? and__25__auto) (jolt-pos? n) and__25__auto))) (jolt-get (jolt-invoke (var-deref "jolt.passes.types" "ty") (jolt-nth ares 0)) (keyword #f "type")) jolt-nil)) (base (jolt-assoc node (keyword #f "fn") fnode_PRIME_ (keyword #f "args") (jolt-invoke (var-deref "clojure.core" "mapv") (lambda (r) (let fnrec6009 ((r r)) (jolt-invoke (var-deref "jolt.passes.types" "nd") r))) ares)))) (let* ((_o$6017 (if (jolt= cn "range") (jolt-invoke (var-deref "jolt.passes.types.lattice" "mk-vec") (keyword #f "num")) (if (jolt-truthy? (let* ((and__25__auto cn)) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt-contains? (var-deref "jolt.passes.types" "elem-fns") cn))) (if (jolt-truthy? and__25__auto) (jolt-n> n 0) and__25__auto)) and__25__auto))) (let* ((a0 (jolt-invoke (var-deref "jolt.passes.types" "ty") (jolt-nth ares 0)))) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.passes.types.lattice" "vec-type?") a0)) (jolt-invoke (var-deref "jolt.passes.types.lattice" "velem") a0) (keyword #f "any"))) (if (jolt-truthy? (let* ((and__25__auto cn)) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt-contains? (var-deref "jolt.passes.types" "dbl-arith-ops") cn))) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "jolt.passes.types" "dbl-arith?") ares args) and__25__auto)) and__25__auto))) (keyword #f "double") (if (jolt-truthy? (keyword #f "else")) (jolt-invoke (var-deref "jolt.passes.types" "call-ret-type") fnode env) jolt-nil))))) (_o$6018 (if (jolt-truthy? rtype) (let* ((_a$6010 base) (_a$6011 (keyword #f "devirt-type")) (_a$6012 rtype) (_a$6013 (keyword #f "devirt-proto")) (_a$6014 (jolt-nth pm 0)) (_a$6015 (keyword #f "devirt-method")) (_a$6016 (jolt-nth pm 1))) (jolt-assoc _a$6010 _a$6011 _a$6012 _a$6013 _a$6014 _a$6015 _a$6016)) base))) (jolt-vector _o$6017 _o$6018))))))))) infer-call) (let* ((_o$6019 (keyword #f "private")) (_o$6020 #t) (_o$6021 (keyword #f "doc")) (_o$6022 "Everything else: type the args, collect the call (var callee) for whole-program\n inference, run the success-type check, and use the declared/estimated return type.\n range produces a numeric vector; an element-returning fn over a typed vector\n yields the element type. A protocol-method call whose receiver (arg 0) is a known\n record type is annotated [type-tag proto method] for devirtualization \x2014; the back\n end looks up the impl at emit time and calls it directly, skipping the registry\n dispatch (~19x cheaper).")) (jolt-hash-map _o$6019 _o$6020 _o$6021 _o$6022)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types" "infer-invoke" (letrec ((infer-invoke (lambda (node tenv env) (let fnrec6023 ((node node) (tenv tenv) (env env)) (let* ((fnode (jolt-get node (keyword #f "fn"))) (iscall-var (jolt= (keyword #f "var") (jolt-get fnode (keyword #f "op")))) (cn (if (jolt-truthy? (let* ((and__25__auto iscall-var)) (if (jolt-truthy? and__25__auto) (jolt= "clojure.core" (jolt-get fnode (keyword #f "ns"))) and__25__auto))) (jolt-get fnode (keyword #f "name")) jolt-nil)) (args (jolt-get node (keyword #f "args"))) (n (jolt-count args))) (if (jolt-truthy? (let* ((and__25__auto iscall-var)) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt-contains? (var-deref "jolt.passes.types" "fold-preds") cn))) (if (jolt-truthy? and__25__auto) (jolt= n 1) and__25__auto)) and__25__auto))) (jolt-invoke (var-deref "jolt.passes.types" "infer-pred-fold") node fnode cn args tenv env) (if (jolt-truthy? (let* ((and__25__auto (jolt-invoke (var-deref "jolt.passes.fold" "kw-callee?") fnode))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt-n>= n 1))) (if (jolt-truthy? and__25__auto) (jolt-n<= n 2) and__25__auto)) and__25__auto))) (jolt-invoke (var-deref "jolt.passes.types" "infer-kw-lookup") node fnode args n tenv env) (if (jolt-truthy? (let* ((and__25__auto (jolt-invoke (var-deref "jolt.passes.fold" "get-callee?") fnode))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt-n>= n 2))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt= (keyword #f "const") (jolt-get (jolt-nth args 1) (keyword #f "op"))))) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "clojure.core" "keyword?") (jolt-get (jolt-nth args 1) (keyword #f "val"))) and__25__auto)) and__25__auto)) and__25__auto))) (jolt-invoke (var-deref "jolt.passes.types" "infer-get-lookup") node args n tenv env) (if (let* ((and__25__auto (jolt= cn "reduce"))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt-n>= n 2))) (if (jolt-truthy? and__25__auto) (jolt= (keyword #f "fn") (jolt-get (jolt-nth args 0) (keyword #f "op"))) and__25__auto)) and__25__auto)) (jolt-invoke (var-deref "jolt.passes.types" "infer-reduce-hof") node args n tenv env) (if (jolt-truthy? (let* ((and__25__auto cn)) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt-get (var-deref "jolt.passes.types" "hof-table") cn))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt-n>= n 2))) (if (jolt-truthy? and__25__auto) (jolt= (keyword #f "fn") (jolt-get (jolt-nth args 0) (keyword #f "op"))) and__25__auto)) and__25__auto)) and__25__auto))) (jolt-invoke (var-deref "jolt.passes.types" "infer-seq-hof") node cn args tenv env) (if (let* ((and__25__auto (let* ((or__26__auto (jolt= cn "conj"))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt= cn "into"))))) (if (jolt-truthy? and__25__auto) (jolt-n>= n 1) and__25__auto)) (jolt-invoke (var-deref "jolt.passes.types" "infer-conj-into") node fnode cn args n tenv env) (if (jolt-truthy? (keyword #f "else")) (jolt-invoke (var-deref "jolt.passes.types" "infer-call") node fnode iscall-var cn args n tenv env) jolt-nil)))))))))))) infer-invoke) (let* ((_o$6024 (keyword #f "private")) (_o$6025 #t) (_o$6026 (keyword #f "doc")) (_o$6027 "Split the callee/args once and dispatch by callee shape to a pattern helper.")) (jolt-hash-map _o$6024 _o$6025 _o$6026 _o$6027)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types" "infer" (letrec ((infer (lambda (node tenv env) (let fnrec6028 ((node node) (tenv tenv) (env env)) (let* ((op (jolt-get node (keyword #f "op")))) (if (jolt= op (keyword #f "const")) (let* ((_o$6029 (let* ((v (jolt-get node (keyword #f "val")))) (if (jolt-truthy? (let* ((and__25__auto (jolt-invoke (var-deref "clojure.core" "number?") v))) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "clojure.core" "float?") v) and__25__auto))) (keyword #f "double") (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "number?") v)) (keyword #f "num") (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "string?") v)) (keyword #f "str") (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "keyword?") v)) (keyword #f "kw") (if (jolt-nil? v) (keyword #f "nil") (if (jolt= #f v) (keyword #f "any") (if (jolt-truthy? (keyword #f "else")) (keyword #f "truthy") jolt-nil))))))))) (_o$6030 node)) (jolt-vector _o$6029 _o$6030)) (if (jolt= op (keyword #f "local")) (let* ((t (jolt-get tenv (jolt-get node (keyword #f "name"))))) (let* ((_o$6031 (if (jolt-truthy? t) t (keyword #f "any"))) (_o$6032 (if (jolt-truthy? (jolt-invoke (var-deref "jolt.passes.types.lattice" "struct-safe?") t)) (let* ((n (jolt-assoc node (keyword #f "hint") (keyword #f "struct")))) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.passes.types.lattice" "type-shape") t)) (jolt-assoc n (keyword #f "shape") (jolt-invoke (var-deref "jolt.passes.types.lattice" "type-shape") t)) n)) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.passes.types.lattice" "vec-type?") t)) (jolt-assoc node (keyword #f "hint") (keyword #f "vector")) (if (jolt-truthy? (keyword #f "else")) node jolt-nil))))) (jolt-vector _o$6031 _o$6032))) (if (jolt= op (keyword #f "map")) (let* ((pairs (jolt-get node (keyword #f "pairs"))) (res (jolt-invoke (var-deref "clojure.core" "mapv") (lambda (pr) (let fnrec6033 ((pr pr)) (let* ((kr (infer (jolt-nth pr 0) tenv env)) (vr (infer (jolt-nth pr 1) tenv env))) (let* ((_o$6034 (jolt-nth kr 1)) (_o$6035 (jolt-nth vr 1)) (_o$6036 (jolt-nth vr 0)) (_o$6037 (jolt-get (jolt-nth pr 0) (keyword #f "val")))) (jolt-vector _o$6034 _o$6035 _o$6036 _o$6037))))) pairs)) (struct? (let* ((and__25__auto (jolt-n> (jolt-count res) 0))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt-invoke (var-deref "clojure.core" "every?") (lambda (pr) (let fnrec6038 ((pr pr)) (jolt-invoke (var-deref "jolt.passes.fold" "scalar-const?") (jolt-nth pr 0)))) pairs))) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "clojure.core" "every?") (lambda (r) (let fnrec6039 ((r r)) (jolt-invoke (var-deref "jolt.passes.types.lattice" "truthy-type?") (jolt-nth r 2)))) res) and__25__auto)) and__25__auto))) (base (if (jolt-truthy? struct?) (jolt-invoke (var-deref "jolt.passes.types.lattice" "cap") (jolt-invoke (var-deref "jolt.passes.types.lattice" "mk-struct") (let* ((_a$6044 (lambda (m r) (let fnrec6040 ((m m) (r r)) (let* ((_a$6041 m) (_a$6042 (jolt-nth r 3)) (_a$6043 (jolt-nth r 2))) (jolt-assoc _a$6041 _a$6042 _a$6043))))) (_a$6045 (jolt-hash-map)) (_a$6046 res)) (jolt-reduce _a$6044 _a$6045 _a$6046))) (var-deref "jolt.passes.types.lattice" "type-depth")) jolt-nil)) (shp (if (jolt-truthy? (let* ((and__25__auto (jolt-get env (keyword #f "map-shapes?")))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto base)) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "jolt.passes.types.lattice" "struct-type?") base) and__25__auto)) and__25__auto))) (jolt-invoke (var-deref "jolt.passes.types.lattice" "shape-order") (jolt-keys (jolt-invoke (var-deref "jolt.passes.types.lattice" "sfields") base))) jolt-nil)) (t (if (jolt-truthy? base) (if (jolt-truthy? shp) (jolt-assoc base (keyword #f "shape") shp) base) (keyword #f "any"))) (node_PRIME_ (jolt-assoc node (keyword #f "pairs") (jolt-invoke (var-deref "clojure.core" "mapv") (lambda (r) (let fnrec6047 ((r r)) (let* ((_o$6048 (jolt-nth r 0)) (_o$6049 (jolt-nth r 1))) (jolt-vector _o$6048 _o$6049)))) res)))) (let* ((_o$6050 t) (_o$6051 (if (jolt-truthy? shp) (jolt-assoc node_PRIME_ (keyword #f "shape") shp) node_PRIME_))) (jolt-vector _o$6050 _o$6051))) (if (jolt= op (keyword #f "vector")) (let* ((irs (let* ((_a$6053 (var-deref "clojure.core" "mapv")) (_a$6054 (lambda (x) (let fnrec6052 ((x x)) (infer x tenv env)))) (_a$6055 (jolt-get node (keyword #f "items")))) (jolt-invoke _a$6053 _a$6054 _a$6055))) (ets (jolt-invoke (var-deref "clojure.core" "mapv") (lambda (r) (let fnrec6056 ((r r)) (jolt-nth r 0))) irs)) (el (if (jolt-empty? ets) (keyword #f "any") (let* ((_a$6057 (var-deref "jolt.passes.types.lattice" "join")) (_a$6058 (jolt-first ets)) (_a$6059 (jolt-rest ets))) (jolt-reduce _a$6057 _a$6058 _a$6059))))) (let* ((_o$6061 (jolt-invoke (var-deref "jolt.passes.types.lattice" "cap") (jolt-invoke (var-deref "jolt.passes.types.lattice" "mk-vec") el) (var-deref "jolt.passes.types.lattice" "type-depth"))) (_o$6062 (jolt-assoc node (keyword #f "items") (jolt-invoke (var-deref "clojure.core" "mapv") (lambda (r) (let fnrec6060 ((r r)) (jolt-nth r 1))) irs)))) (jolt-vector _o$6061 _o$6062))) (if (jolt= op (keyword #f "set")) (let* ((irs (let* ((_a$6064 (var-deref "clojure.core" "mapv")) (_a$6065 (lambda (x) (let fnrec6063 ((x x)) (infer x tenv env)))) (_a$6066 (jolt-get node (keyword #f "items")))) (jolt-invoke _a$6064 _a$6065 _a$6066))) (ets (jolt-invoke (var-deref "clojure.core" "mapv") (lambda (r) (let fnrec6067 ((r r)) (jolt-nth r 0))) irs)) (el (if (jolt-empty? ets) (keyword #f "any") (let* ((_a$6068 (var-deref "jolt.passes.types.lattice" "join")) (_a$6069 (jolt-first ets)) (_a$6070 (jolt-rest ets))) (jolt-reduce _a$6068 _a$6069 _a$6070))))) (let* ((_o$6072 (jolt-invoke (var-deref "jolt.passes.types.lattice" "cap") (jolt-invoke (var-deref "jolt.passes.types.lattice" "mk-set") el) (var-deref "jolt.passes.types.lattice" "type-depth"))) (_o$6073 (jolt-assoc node (keyword #f "items") (jolt-invoke (var-deref "clojure.core" "mapv") (lambda (r) (let fnrec6071 ((r r)) (jolt-nth r 1))) irs)))) (jolt-vector _o$6072 _o$6073))) (if (jolt= op (keyword #f "if")) (let* ((test (jolt-get node (keyword #f "test"))) (tr (infer test tenv env)) (nr (jolt-invoke (var-deref "jolt.passes.types" "if-narrow") test tenv)) (thn (let* ((_a$6074 (jolt-get node (keyword #f "then"))) (_a$6075 (jolt-nth nr 0)) (_a$6076 env)) (infer _a$6074 _a$6075 _a$6076))) (els (let* ((_a$6077 (jolt-get node (keyword #f "else"))) (_a$6078 (jolt-nth nr 1)) (_a$6079 env)) (infer _a$6077 _a$6078 _a$6079)))) (let* ((_o$6090 (let* ((_a$6080 (var-deref "jolt.passes.types.lattice" "join")) (_a$6081 (jolt-nth thn 0)) (_a$6082 (jolt-nth els 0))) (jolt-invoke _a$6080 _a$6081 _a$6082))) (_o$6091 (let* ((_a$6083 node) (_a$6084 (keyword #f "test")) (_a$6085 (jolt-nth tr 1)) (_a$6086 (keyword #f "then")) (_a$6087 (jolt-nth thn 1)) (_a$6088 (keyword #f "else")) (_a$6089 (jolt-nth els 1))) (jolt-assoc _a$6083 _a$6084 _a$6085 _a$6086 _a$6087 _a$6088 _a$6089)))) (jolt-vector _o$6090 _o$6091))) (if (jolt= op (keyword #f "do")) (let* ((stmts (let* ((_a$6093 (var-deref "clojure.core" "mapv")) (_a$6094 (lambda (s) (let fnrec6092 ((s s)) (jolt-nth (infer s tenv env) 1)))) (_a$6095 (jolt-get node (keyword #f "statements")))) (jolt-invoke _a$6093 _a$6094 _a$6095))) (r (infer (jolt-get node (keyword #f "ret")) tenv env))) (let* ((_o$6096 (jolt-nth r 0)) (_o$6097 (jolt-assoc node (keyword #f "statements") stmts (keyword #f "ret") (jolt-nth r 1)))) (jolt-vector _o$6096 _o$6097))) (if (jolt= op (keyword #f "throw")) (let* ((_o$6098 (keyword #f "any")) (_o$6099 (jolt-assoc node (keyword #f "expr") (jolt-nth (infer (jolt-get node (keyword #f "expr")) tenv env) 1)))) (jolt-vector _o$6098 _o$6099)) (if (jolt= op (keyword #f "var")) (begin (let* ((_a$6100 (var-deref "clojure.core" "swap!")) (_a$6101 (jolt-get env (keyword #f "escapes"))) (_a$6102 jolt-conj) (_a$6103 (jolt-invoke (var-deref "jolt.passes.types" "var-key") node))) (jolt-invoke _a$6100 _a$6101 _a$6102 _a$6103)) (let* ((_o$6106 (let* ((vt (let* ((_a$6104 (jolt-get env (keyword #f "vtypes"))) (_a$6105 (jolt-invoke (var-deref "jolt.passes.types" "var-key") node))) (jolt-get _a$6104 _a$6105)))) (if (jolt-truthy? vt) vt (keyword #f "any")))) (_o$6107 node)) (jolt-vector _o$6106 _o$6107))) (if (jolt= op (keyword #f "invoke")) (jolt-invoke (var-deref "jolt.passes.types" "infer-invoke") node tenv env) (if (jolt= op (keyword #f "let")) (let* ((res (let* ((_a$6118 (lambda (acc b) (let fnrec6108 ((acc acc) (b b)) (let* ((te (jolt-nth acc 0)) (binds (jolt-nth acc 1)) (ir (infer (jolt-nth b 1) te env))) (let* ((_o$6114 (let* ((_a$6109 te) (_a$6110 (jolt-nth b 0)) (_a$6111 (jolt-nth ir 0))) (jolt-assoc _a$6109 _a$6110 _a$6111))) (_o$6115 (jolt-conj binds (let* ((_o$6112 (jolt-nth b 0)) (_o$6113 (jolt-nth ir 1))) (jolt-vector _o$6112 _o$6113))))) (jolt-vector _o$6114 _o$6115)))))) (_a$6119 (let* ((_o$6116 tenv) (_o$6117 (jolt-vector))) (jolt-vector _o$6116 _o$6117))) (_a$6120 (jolt-get node (keyword #f "bindings")))) (jolt-reduce _a$6118 _a$6119 _a$6120))) (br (let* ((_a$6121 (jolt-get node (keyword #f "body"))) (_a$6122 (jolt-nth res 0)) (_a$6123 env)) (infer _a$6121 _a$6122 _a$6123)))) (let* ((_o$6129 (jolt-nth br 0)) (_o$6130 (let* ((_a$6124 node) (_a$6125 (keyword #f "bindings")) (_a$6126 (jolt-nth res 1)) (_a$6127 (keyword #f "body")) (_a$6128 (jolt-nth br 1))) (jolt-assoc _a$6124 _a$6125 _a$6126 _a$6127 _a$6128)))) (jolt-vector _o$6129 _o$6130))) (if (jolt= op (keyword #f "loop")) (let* ((lenv (jolt-assoc env (keyword #f "in-loop?") #t))) (let* ((_o$6142 (keyword #f "any")) (_o$6143 (let* ((_a$6137 node) (_a$6138 (keyword #f "bindings")) (_a$6139 (let* ((_a$6134 (var-deref "clojure.core" "mapv")) (_a$6135 (lambda (b) (let fnrec6131 ((b b)) (let* ((_o$6132 (jolt-nth b 0)) (_o$6133 (jolt-nth (infer (jolt-nth b 1) tenv env) 1))) (jolt-vector _o$6132 _o$6133))))) (_a$6136 (jolt-get node (keyword #f "bindings")))) (jolt-invoke _a$6134 _a$6135 _a$6136))) (_a$6140 (keyword #f "body")) (_a$6141 (jolt-nth (infer (jolt-get node (keyword #f "body")) tenv lenv) 1))) (jolt-assoc _a$6137 _a$6138 _a$6139 _a$6140 _a$6141)))) (jolt-vector _o$6142 _o$6143))) (if (jolt= op (keyword #f "recur")) (let* ((ares (let* ((_a$6145 (var-deref "clojure.core" "mapv")) (_a$6146 (lambda (a) (let fnrec6144 ((a a)) (infer a tenv env)))) (_a$6147 (jolt-get node (keyword #f "args")))) (jolt-invoke _a$6145 _a$6146 _a$6147)))) (begin (if (jolt-truthy? (let* ((and__25__auto (jolt-not (jolt-get env (keyword #f "in-loop?"))))) (if (jolt-truthy? and__25__auto) (jolt-get env (keyword #f "self-key")) and__25__auto))) (let* ((_a$6154 (var-deref "clojure.core" "swap!")) (_a$6155 (jolt-get env (keyword #f "calls"))) (_a$6156 jolt-conj) (_a$6157 (let* ((_o$6152 (jolt-get env (keyword #f "self-key"))) (_o$6153 (let* ((_a$6148 (var-deref "jolt.passes.types" "self-rec-argtys")) (_a$6149 (jolt-get node (keyword #f "args"))) (_a$6150 ares) (_a$6151 (jolt-get env (keyword #f "self-params")))) (jolt-invoke _a$6148 _a$6149 _a$6150 _a$6151)))) (jolt-vector _o$6152 _o$6153)))) (jolt-invoke _a$6154 _a$6155 _a$6156 _a$6157)) jolt-nil) (let* ((_o$6159 (keyword #f "any")) (_o$6160 (jolt-assoc node (keyword #f "args") (jolt-invoke (var-deref "clojure.core" "mapv") (lambda (r) (let fnrec6158 ((r r)) (jolt-invoke (var-deref "jolt.passes.types" "nd") r))) ares)))) (jolt-vector _o$6159 _o$6160)))) (if (jolt= op (keyword #f "fn")) (let* ((fenv (jolt-assoc env (keyword #f "self-name") jolt-nil (keyword #f "self-key") jolt-nil (keyword #f "self-params") jolt-nil (keyword #f "in-loop?") #f))) (let* ((_o$6176 (keyword #f "any")) (_o$6177 (jolt-assoc node (keyword #f "arities") (let* ((_a$6173 (var-deref "clojure.core" "mapv")) (_a$6174 (lambda (a) (let fnrec6161 ((a a)) (let* ((shapes (jolt-get env (keyword #f "record-shapes"))) (phm (let* ((_a$6166 (lambda (m pr) (let fnrec6162 ((m m) (pr pr)) (let* ((_a$6163 m) (_a$6164 (jolt-nth pr 0)) (_a$6165 (jolt-nth pr 1))) (jolt-assoc _a$6163 _a$6164 _a$6165))))) (_a$6167 (jolt-hash-map)) (_a$6168 (jolt-get a (keyword #f "phints")))) (jolt-reduce _a$6166 _a$6167 _a$6168))) (pe (let* ((_a$6170 (lambda (e p) (let fnrec6169 ((e e) (p p)) (jolt-assoc e p (let* ((ent (jolt-get shapes (jolt-get phm p)))) (if (jolt-truthy? ent) (jolt-invoke (var-deref "jolt.passes.types" "record-type-from-entry") ent (var-deref "jolt.passes.types.lattice" "type-depth") shapes) (keyword #f "any"))))))) (_a$6171 tenv) (_a$6172 (jolt-get a (keyword #f "params")))) (jolt-reduce _a$6170 _a$6171 _a$6172))) (pe (if (jolt-truthy? (jolt-get a (keyword #f "rest"))) (jolt-assoc pe (jolt-get a (keyword #f "rest")) (keyword #f "any")) pe))) (jolt-assoc a (keyword #f "body") (jolt-nth (infer (jolt-get a (keyword #f "body")) pe fenv) 1)))))) (_a$6175 (jolt-get node (keyword #f "arities")))) (jolt-invoke _a$6173 _a$6174 _a$6175))))) (jolt-vector _o$6176 _o$6177))) (if (jolt= op (keyword #f "def")) (begin (if (jolt-truthy? (jolt-get env (keyword #f "checking?"))) (jolt-invoke (var-deref "jolt.passes.types.check" "register-user-fn!") node env) jolt-nil) (let* ((_o$6178 (keyword #f "any")) (_o$6179 (jolt-assoc node (keyword #f "init") (jolt-nth (infer (jolt-get node (keyword #f "init")) tenv env) 1)))) (jolt-vector _o$6178 _o$6179))) (if (jolt= op (keyword #f "try")) (let* ((_o$6187 (keyword #f "any")) (_o$6188 (let* ((_a$6180 node) (_a$6181 (keyword #f "body")) (_a$6182 (jolt-nth (infer (jolt-get node (keyword #f "body")) tenv env) 1)) (_a$6183 (keyword #f "catch-body")) (_a$6184 (if (jolt-truthy? (jolt-get node (keyword #f "catch-body"))) (jolt-nth (infer (jolt-get node (keyword #f "catch-body")) tenv env) 1) jolt-nil)) (_a$6185 (keyword #f "finally")) (_a$6186 (if (jolt-truthy? (jolt-get node (keyword #f "finally"))) (jolt-nth (infer (jolt-get node (keyword #f "finally")) tenv env) 1) jolt-nil))) (jolt-assoc _a$6180 _a$6181 _a$6182 _a$6183 _a$6184 _a$6185 _a$6186)))) (jolt-vector _o$6187 _o$6188)) (if (jolt-truthy? (keyword #f "else")) (let* ((_o$6189 (keyword #f "any")) (_o$6190 node)) (jolt-vector _o$6189 _o$6190)) jolt-nil)))))))))))))))))))))) infer) (let* ((_o$6191 (keyword #f "private")) (_o$6192 #t) (_o$6193 (keyword #f "doc")) (_o$6194 "Returns [type node'] \x2014; the inferred type of node and node with struct-safe\n :local references annotated :hint :struct. tenv maps in-scope local names to\n inferred types; env carries the inference config and this run's accumulators.")) (jolt-hash-map _o$6191 _o$6192 _o$6193 _o$6194)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types" "infer-top" (letrec ((infer-top (lambda (node env) (let fnrec6195 ((node node) (env env)) (jolt-nth (jolt-invoke (var-deref "jolt.passes.types" "infer") node (jolt-hash-map) env) 1))))) infer-top) (let* ((_o$6196 (keyword #f "private")) (_o$6197 #t)) (jolt-hash-map _o$6196 _o$6197)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types" "all-any-env" (letrec ((all-any-env (lambda (params) (let fnrec6198 ((params params)) (let* ((_a$6200 (lambda (e p) (let fnrec6199 ((e e) (p p)) (jolt-assoc e p (keyword #f "any"))))) (_a$6201 (jolt-hash-map)) (_a$6202 params)) (jolt-reduce _a$6200 _a$6201 _a$6202)))))) all-any-env) (let* ((_o$6203 (keyword #f "private")) (_o$6204 #t) (_o$6205 (keyword #f "doc")) (_o$6206 "tenv binding every param name to :any (the all-ambiguous baseline).")) (jolt-hash-map _o$6203 _o$6204 _o$6205 _o$6206)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types" "isolated-diag-count" (letrec ((isolated-diag-count (lambda (body tenv env) (let fnrec6207 ((body body) (tenv tenv) (env env)) (let* ((sub (jolt-assoc env (keyword #f "diags") (jolt-invoke (var-deref "clojure.core" "atom") (jolt-vector))))) (begin (jolt-invoke (var-deref "jolt.passes.types" "infer") body tenv sub) (jolt-count (jolt-invoke (var-deref "clojure.core" "deref") (jolt-get sub (keyword #f "diags")))))))))) isolated-diag-count) (let* ((_o$6208 (keyword #f "private")) (_o$6209 #t) (_o$6210 (keyword #f "doc")) (_o$6211 "Count of diagnostics typing body under tenv produces. Runs under a SUB-ENV\n with its own diags cell, so this probe never leaks into the real report (the\n shared calls/escapes/guard cells are intentionally still threaded \x2014; they are\n not read here). Runs the same checking inference as check-form.")) (jolt-hash-map _o$6208 _o$6209 _o$6210 _o$6211)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types" "check-user-call" (letrec ((check-user-call (lambda (key sig arg-types pos env) (let fnrec6212 ((key key) (sig sig) (arg-types arg-types) (pos pos) (env env)) (let* ((cset (jolt-get env (keyword #f "checking-set")))) (if (jolt-not (jolt-contains? (jolt-invoke (var-deref "clojure.core" "deref") cset) key)) (let* ((prev (jolt-invoke (var-deref "clojure.core" "deref") cset))) (begin (jolt-invoke (var-deref "clojure.core" "reset!") cset (jolt-conj prev key)) (let* ((params (jolt-get sig (keyword #f "params"))) (body (jolt-get sig (keyword #f "body"))) (npar (jolt-count params)) (nargs (jolt-count arg-types)) (memo (jolt-get env (keyword #f "diag-memo")))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "not=") npar nargs)) (let* ((_a$6221 (var-deref "clojure.core" "swap!")) (_a$6222 (jolt-get env (keyword #f "diags"))) (_a$6223 jolt-conj) (_a$6224 (let* ((_o$6213 (keyword #f "op")) (_o$6214 (keyword #f "user-call")) (_o$6215 (keyword #f "type")) (_o$6216 (keyword #f "arity")) (_o$6217 (keyword #f "pos")) (_o$6218 pos) (_o$6219 (keyword #f "msg")) (_o$6220 (jolt-invoke (var-deref "clojure.core" "str") "wrong number of args (" nargs ") passed to `" (jolt-get sig (keyword #f "name")) "` (expected " npar ")"))) (jolt-hash-map _o$6213 _o$6214 _o$6215 _o$6216 _o$6217 _o$6218 _o$6219 _o$6220)))) (jolt-invoke _a$6221 _a$6222 _a$6223 _a$6224)) (let* ((base-env (jolt-invoke (var-deref "jolt.passes.types" "all-any-env") params)) (base (let* ((bk (let* ((_o$6225 (keyword #f "base")) (_o$6226 key)) (jolt-vector _o$6225 _o$6226)))) (if (jolt-contains? (jolt-invoke (var-deref "clojure.core" "deref") memo) bk) (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") memo) bk) (let* ((b (jolt-invoke (var-deref "jolt.passes.types" "isolated-diag-count") body base-env env))) (begin (jolt-invoke (var-deref "clojure.core" "swap!") memo jolt-assoc bk b) b)))))) (let* ((_a$6254 (lambda (_ i) (let fnrec6227 ((_ _) (i i)) (begin (let* ((at (jolt-nth arg-types i))) (if (jolt-truthy? (let* ((and__25__auto (jolt-invoke (var-deref "clojure.core" "not=") at (keyword #f "any")))) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "clojure.core" "not=") at (keyword #f "truthy")) and__25__auto))) (let* ((mk (let* ((_o$6228 (keyword #f "arg")) (_o$6229 key) (_o$6230 i) (_o$6231 at)) (jolt-vector _o$6228 _o$6229 _o$6230 _o$6231))) (rejects (if (jolt-contains? (jolt-invoke (var-deref "clojure.core" "deref") memo) mk) (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") memo) mk) (let* ((r (jolt-n> (jolt-invoke (var-deref "jolt.passes.types" "isolated-diag-count") body (jolt-assoc base-env (jolt-nth params i) at) env) base))) (begin (jolt-invoke (var-deref "clojure.core" "swap!") memo jolt-assoc mk r) r))))) (if (jolt-truthy? rejects) (let* ((_a$6250 (var-deref "clojure.core" "swap!")) (_a$6251 (jolt-get env (keyword #f "diags"))) (_a$6252 jolt-conj) (_a$6253 (let* ((_o$6240 (keyword #f "op")) (_o$6241 (keyword #f "user-call")) (_o$6242 (keyword #f "argpos")) (_o$6243 i) (_o$6244 (keyword #f "type")) (_o$6245 (jolt-invoke (var-deref "jolt.passes.types.check" "type-name") at)) (_o$6246 (keyword #f "pos")) (_o$6247 pos) (_o$6248 (keyword #f "msg")) (_o$6249 (let* ((_a$6232 (var-deref "clojure.core" "str")) (_a$6233 "argument ") (_a$6234 (jolt-inc i)) (_a$6235 " to `") (_a$6236 (jolt-get sig (keyword #f "name"))) (_a$6237 "` is ") (_a$6238 (jolt-invoke (var-deref "jolt.passes.types.check" "type-name") at)) (_a$6239 ", which its body provably rejects")) (jolt-invoke _a$6232 _a$6233 _a$6234 _a$6235 _a$6236 _a$6237 _a$6238 _a$6239)))) (jolt-hash-map _o$6240 _o$6241 _o$6242 _o$6243 _o$6244 _o$6245 _o$6246 _o$6247 _o$6248 _o$6249)))) (jolt-invoke _a$6250 _a$6251 _a$6252 _a$6253)) jolt-nil)) jolt-nil)) jolt-nil)))) (_a$6255 jolt-nil) (_a$6256 (jolt-range npar))) (jolt-reduce _a$6254 _a$6255 _a$6256))))) (jolt-invoke (var-deref "clojure.core" "reset!") cset prev))) jolt-nil)))))) check-user-call) (let* ((_o$6257 (keyword #f "private")) (_o$6258 #t) (_o$6259 (keyword #f "doc")) (_o$6260 "Strict mode: report a call to a registered user fn that provably throws \x2014;\n either a WRONG ARITY (the registered fn has one fixed arity, so a different\n arg count always throws) or an argument whose concrete type the body\n rejects. For the latter, re-check the body with ONLY that parameter bound to\n its arg type (others :any); a diagnostic the all-:any body did not already\n have means the argument alone is provably wrong. Monotonic \x2014; binding a\n concrete type can only ADD error-domain hits \x2014; so no false positive.\n Cycle-guarded (env's checking-set) so mutually recursive fns terminate.")) (jolt-hash-map _o$6257 _o$6258 _o$6259 _o$6260)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types" "set-rtenv!" (letrec ((set-rtenv! (lambda (m) (let fnrec6261 ((m m)) (jolt-invoke (var-deref "clojure.core" "swap!") (var-deref "jolt.passes.types" "config-box") jolt-assoc (keyword #f "rtenv") (let* ((or__26__auto m)) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-hash-map)))))))) set-rtenv!) (let* ((_o$6262 (keyword #f "doc")) (_o$6263 "Install the current return-type estimates (a map \"ns/name\" -> type) used to\n type call results during the fixpoint.")) (jolt-hash-map _o$6262 _o$6263)))) -(guard (e (#t #f)) - (def-var! "jolt.passes.types" "set-record-shapes!" (letrec ((set-record-shapes! (lambda (m) (let fnrec6264 ((m m)) (jolt-invoke (var-deref "clojure.core" "swap!") (var-deref "jolt.passes.types" "config-box") jolt-assoc (keyword #f "record-shapes") (let* ((or__26__auto m)) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-hash-map)))))))) set-record-shapes!))) -(guard (e (#t #f)) - (def-var! "jolt.passes.types" "set-protocol-methods!" (letrec ((set-protocol-methods! (lambda (m) (let fnrec6265 ((m m)) (jolt-invoke (var-deref "clojure.core" "swap!") (var-deref "jolt.passes.types" "config-box") jolt-assoc (keyword #f "protocol-methods") (let* ((or__26__auto m)) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-hash-map)))))))) set-protocol-methods!))) -(guard (e (#t #f)) - (def-var! "jolt.passes.types" "set-map-shapes!" (letrec ((set-map-shapes! (lambda (b) (let fnrec6266 ((b b)) (jolt-invoke (var-deref "clojure.core" "swap!") (var-deref "jolt.passes.types" "config-box") jolt-assoc (keyword #f "map-shapes?") (jolt-invoke (var-deref "clojure.core" "boolean") b)))))) set-map-shapes!))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types" "set-vtypes!" (letrec ((set-vtypes! (lambda (m) (let fnrec6267 ((m m)) (jolt-invoke (var-deref "clojure.core" "swap!") (var-deref "jolt.passes.types" "config-box") jolt-assoc (keyword #f "vtypes") (let* ((or__26__auto m)) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-hash-map)))))))) set-vtypes!) (let* ((_o$6268 (keyword #f "doc")) (_o$6269 "Install var VALUE types (a map \"ns/name\" -> type): fn vars are :truthy\n (non-nil), def vars carry their inferred init type.")) (jolt-hash-map _o$6268 _o$6269)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types" "join-types" (letrec ((join-types (lambda (a b) (let fnrec6270 ((a a) (b b)) (jolt-invoke (var-deref "jolt.passes.types.lattice" "join-t") a b))))) join-types) (let* ((_o$6271 (keyword #f "doc")) (_o$6272 "Public structural join (lub), used by the orchestrator's fixpoint so param/\n return types join field-wise/element-wise instead of collapsing to :any.")) (jolt-hash-map _o$6271 _o$6272)))) -(guard (e (#t #f)) - (def-var! "jolt.passes.types" "reset-escapes!" (letrec ((reset-escapes! (lambda () (let fnrec6273 () (jolt-invoke (var-deref "clojure.core" "reset!") (var-deref "jolt.passes.types" "escapes-box") (jolt-hash-set)))))) reset-escapes!))) -(guard (e (#t #f)) - (def-var! "jolt.passes.types" "collected-escapes" (letrec ((collected-escapes (lambda () (let fnrec6274 () (jolt-invoke (var-deref "clojure.core" "vec") (jolt-invoke (var-deref "clojure.core" "deref") (var-deref "jolt.passes.types" "escapes-box"))))))) collected-escapes))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types" "check-form" (letrec ((check-form (case-lambda ((node) (let fnrec6275 ((node node)) (check-form node #f))) ((node strict?) (let fnrec6276 ((node node) (strict? strict?)) (let* ((env (jolt-invoke (var-deref "jolt.passes.types" "mk-env") #t strict?))) (begin (jolt-invoke (var-deref "jolt.passes.types" "infer") node (jolt-hash-map) env) (jolt-invoke (var-deref "clojure.core" "vec") (jolt-invoke (var-deref "clojure.core" "deref") (jolt-get env (keyword #f "diags"))))))))))) check-form) (let* ((_o$6277 (keyword #f "doc")) (_o$6278 "Success-type check a single analyzed form (RFC 0006). Returns a vector of\n diagnostics [{:op :argpos :type :msg} ...] for provably-wrong calls; empty\n when nothing is provably wrong. Runs independently of specialization so it is\n usable in normal builds (the decoupled checking path).\n\n With strict? true, also reports calls to registered user functions whose\n concrete argument types provably make the body throw (opt-in,\n closed-world). user-sig-box accumulates registered defs across forms, so a\n def must precede its call \x2014; the same ordering RFC 0005 already assumes.")) (jolt-hash-map _o$6277 _o$6278)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types" "infer-body" (letrec ((infer-body (case-lambda ((body tenv) (let fnrec6279 ((body body) (tenv tenv)) (infer-body body tenv jolt-nil jolt-nil jolt-nil))) ((body tenv self-name self-key) (let fnrec6280 ((body body) (tenv tenv) (self-name self-name) (self-key self-key)) (infer-body body tenv self-name self-key jolt-nil))) ((body tenv self-name self-key self-params) (let fnrec6281 ((body body) (tenv tenv) (self-name self-name) (self-key self-key) (self-params self-params)) (let* ((env (jolt-assoc (jolt-invoke (var-deref "jolt.passes.types" "mk-env") #f #f) (keyword #f "self-name") self-name (keyword #f "self-key") self-key (keyword #f "self-params") self-params)) (r (jolt-invoke (var-deref "jolt.passes.types" "infer") body tenv env))) (let* ((_o$6282 (jolt-nth r 0)) (_o$6283 (jolt-nth r 1)) (_o$6284 (jolt-invoke (var-deref "clojure.core" "deref") (jolt-get env (keyword #f "calls"))))) (jolt-vector _o$6282 _o$6283 _o$6284)))))))) infer-body) (let* ((_o$6285 (keyword #f "doc")) (_o$6286 "Type `body` under tenv (local-name -> type). Returns [ret-type node' calls],\n where calls is the [[\"ns/name\" [arg-types...]] ...] this body invokes (for\n propagating into callee param types). Also accumulates escapes (read with\n collected-escapes after a full sweep). With self-name/self-key, a recursive\n self-call or fn-level recur in `body` is collected under self-key too, so a\n self-recursive fn's params are constrained by its recursion, not just callers.")) (jolt-hash-map _o$6285 _o$6286)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types" "impl-reg-ret" (letrec ((impl-reg-ret (lambda (node) (let fnrec6287 ((node node)) (if (jolt= (keyword #f "invoke") (jolt-get node (keyword #f "op"))) (let* ((f (jolt-get node (keyword #f "fn"))) (args (jolt-get node (keyword #f "args")))) (if (let* ((and__25__auto (jolt= (keyword #f "var") (jolt-get f (keyword #f "op"))))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (let* ((or__26__auto (jolt= "register-inline-method" (jolt-get f (keyword #f "name"))))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt= "register-method" (jolt-get f (keyword #f "name"))))))) (if (jolt-truthy? and__25__auto) (jolt= 4 (jolt-count args)) and__25__auto)) and__25__auto)) (let* ((proto (jolt-get (jolt-nth args 1) (keyword #f "val"))) (method (jolt-get (jolt-nth args 2) (keyword #f "val"))) (fnn (jolt-nth args 3))) (if (jolt-truthy? (let* ((and__25__auto (jolt-invoke (var-deref "clojure.core" "string?") proto))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt-invoke (var-deref "clojure.core" "string?") method))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt= (keyword #f "fn") (jolt-get fnn (keyword #f "op"))))) (if (jolt-truthy? and__25__auto) (jolt-seq (jolt-get fnn (keyword #f "arities"))) and__25__auto)) and__25__auto)) and__25__auto))) (let* ((_o$6291 (jolt-invoke (var-deref "clojure.core" "str") proto "/" method)) (_o$6292 (jolt-nth (let* ((_a$6288 (var-deref "jolt.passes.types" "infer-body")) (_a$6289 (jolt-get (jolt-first (jolt-get fnn (keyword #f "arities"))) (keyword #f "body"))) (_a$6290 (jolt-hash-map))) (jolt-invoke _a$6288 _a$6289 _a$6290)) 0))) (jolt-vector _o$6291 _o$6292)) jolt-nil)) jolt-nil)) jolt-nil))))) impl-reg-ret) (let* ((_o$6293 (keyword #f "private")) (_o$6294 #t)) (jolt-hash-map _o$6293 _o$6294)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types" "walk-pm-rets" (letrec ((walk-pm-rets (lambda (node acc) (let fnrec6295 ((node node) (acc acc)) (let* ((kr (jolt-invoke (var-deref "jolt.passes.types" "impl-reg-ret") node)) (acc (if (jolt-truthy? kr) (let* ((_a$6297 (var-deref "clojure.core" "update")) (_a$6298 acc) (_a$6299 (jolt-nth kr 0)) (_a$6300 (lambda (t) (let fnrec6296 ((t t)) (if (jolt-truthy? t) (jolt-invoke (var-deref "jolt.passes.types.lattice" "join") t (jolt-nth kr 1)) (jolt-nth kr 1)))))) (jolt-invoke _a$6297 _a$6298 _a$6299 _a$6300)) acc))) (jolt-invoke (var-deref "jolt.ir" "reduce-ir-children") (lambda (a c) (let fnrec6301 ((a a) (c c)) (walk-pm-rets c a))) acc node)))))) walk-pm-rets) (let* ((_o$6302 (keyword #f "private")) (_o$6303 #t)) (jolt-hash-map _o$6302 _o$6303)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types" "collect-pm-rets!" (letrec ((collect-pm-rets! (lambda (nodes) (let fnrec6304 ((nodes nodes)) (jolt-invoke (var-deref "clojure.core" "reset!") (var-deref "jolt.passes.types" "pm-rets-box") (let* ((_a$6306 (lambda (acc n) (let fnrec6305 ((acc acc) (n n)) (jolt-invoke (var-deref "jolt.passes.types" "walk-pm-rets") n acc)))) (_a$6307 (jolt-hash-map)) (_a$6308 nodes)) (jolt-reduce _a$6306 _a$6307 _a$6308))))))) collect-pm-rets!) (let* ((_o$6309 (keyword #f "doc")) (_o$6310 "Scan the unit's nodes for protocol-method impl registrations and stash each\n method's joined impl-return type (record-shapes must already be installed).")) (jolt-hash-map _o$6309 _o$6310)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types" "reinfer-def" (letrec ((reinfer-def (lambda (def-node ptmap) (let fnrec6311 ((def-node def-node) (ptmap ptmap)) (let* ((fnode (jolt-get def-node (keyword #f "init"))) (env (jolt-invoke (var-deref "jolt.passes.types" "mk-env") #f #f)) (shapes (jolt-get env (keyword #f "record-shapes")))) (if (jolt= (keyword #f "fn") (jolt-get fnode (keyword #f "op"))) (jolt-assoc def-node (keyword #f "init") (jolt-assoc fnode (keyword #f "arities") (let* ((_a$6317 (var-deref "clojure.core" "mapv")) (_a$6318 (lambda (a) (let fnrec6312 ((a a)) (let* ((pt (let* ((_a$6314 (lambda (m pr) (let fnrec6313 ((m m) (pr pr)) (let* ((nm (jolt-nth pr 0)) (e (jolt-get shapes (jolt-nth pr 1)))) (if (jolt-truthy? (let* ((and__25__auto e)) (if (jolt-truthy? and__25__auto) (jolt-not (jolt-contains? m nm)) and__25__auto))) (jolt-assoc m nm (jolt-invoke (var-deref "jolt.passes.types" "record-type-from-entry") e (var-deref "jolt.passes.types.lattice" "type-depth") shapes)) m))))) (_a$6315 ptmap) (_a$6316 (jolt-get a (keyword #f "phints")))) (jolt-reduce _a$6314 _a$6315 _a$6316)))) (jolt-assoc a (keyword #f "body") (jolt-nth (jolt-invoke (var-deref "jolt.passes.types" "infer") (jolt-get a (keyword #f "body")) pt env) 1)))))) (_a$6319 (jolt-get fnode (keyword #f "arities")))) (jolt-invoke _a$6317 _a$6318 _a$6319)))) def-node)))))) reinfer-def) (let* ((_o$6320 (keyword #f "doc")) (_o$6321 "Re-run inference on a stashed :def's fn arity bodies with param types seeded\n (ptmap: param-name -> type), returning the def with annotated bodies. The back\n end emits the result directly (no further passes), so the param-typed lookups\n keep their specialization. Used by the inter-procedural recompile.")) (jolt-hash-map _o$6320 _o$6321)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types" "phint-seed" (letrec ((phint-seed (lambda (params phints) (let fnrec6322 ((params params) (phints phints)) (let* ((shapes (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (var-deref "jolt.passes.types" "config-box")) (keyword #f "record-shapes"))) (m (let* ((_a$6327 (lambda (acc pr) (let fnrec6323 ((acc acc) (pr pr)) (let* ((_a$6324 acc) (_a$6325 (jolt-nth pr 0)) (_a$6326 (jolt-nth pr 1))) (jolt-assoc _a$6324 _a$6325 _a$6326))))) (_a$6328 (jolt-hash-map)) (_a$6329 phints)) (jolt-reduce _a$6327 _a$6328 _a$6329)))) (jolt-invoke (var-deref "clojure.core" "mapv") (lambda (nm) (let fnrec6330 ((nm nm)) (let* ((ck (jolt-get m nm)) (e (let* ((and__25__auto ck)) (if (jolt-truthy? and__25__auto) (jolt-get shapes ck) and__25__auto)))) (if (jolt-truthy? e) (jolt-invoke (var-deref "jolt.passes.types" "record-type-from-entry") e (var-deref "jolt.passes.types.lattice" "type-depth") shapes) jolt-nil)))) params)))))) phint-seed) (let* ((_o$6331 (keyword #f "doc")) (_o$6332 "Positional declared-hint type seeds for a fn arity. Given the param-name\n vector and the arity's :phints (a seq of [name ctor-key] pairs), return a\n vector parallel to params whose slot i is the resolved record TYPE of that\n param's ^Record hint (via the record-shapes registry), or nil. The\n whole-program fixpoint seeds these as a param-type FLOOR so a declared hint\n propagates to a fn's callees DURING inference \x2014; not only at the final re-emit\n (reinfer-def). Without it a hinted param with no callers stays :any through the\n fixpoint, so a field read off it (e.g. (:origin ^Ray r)) never tells a shared\n callee its arg is a Vec3.")) (jolt-hash-map _o$6331 _o$6332)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types" "wp-seeds-box" (jolt-invoke (var-deref "clojure.core" "atom") (jolt-hash-map)) (let* ((_o$6333 (keyword #f "private")) (_o$6334 #t)) (jolt-hash-map _o$6333 _o$6334)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types" "param-seeds-for" (letrec ((param-seeds-for (lambda (k) (let fnrec6335 ((k k)) (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (var-deref "jolt.passes.types" "wp-seeds-box")) k))))) param-seeds-for) (let* ((_o$6336 (keyword #f "doc")) (_o$6337 "The param-name -> type seed map a top-level def should be reinferred with, or\n nil. Set by wp-infer!, read by run-passes during the final per-def emit.")) (jolt-hash-map _o$6336 _o$6337)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types" "wp-num-seeds-box" (jolt-invoke (var-deref "clojure.core" "atom") (jolt-hash-map)) (let* ((_o$6338 (keyword #f "private")) (_o$6339 #t)) (jolt-hash-map _o$6338 _o$6339)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types" "param-num-seeds-for" (letrec ((param-num-seeds-for (lambda (k) (let fnrec6340 ((k k)) (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (var-deref "jolt.passes.types" "wp-num-seeds-box")) k))))) param-num-seeds-for) (let* ((_o$6341 (keyword #f "doc")) (_o$6342 "The param-name -> :double seed map for a def's hintless flonum params, or nil.")) (jolt-hash-map _o$6341 _o$6342)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types" "wp-specializable" (letrec ((wp-specializable (lambda (nodes) (let fnrec6343 ((nodes nodes)) (let* ((_a$6358 (lambda (m d) (let fnrec6344 ((m m) (d d)) (let* ((f (jolt-get d (keyword #f "init")))) (if (let* ((and__25__auto (jolt= (keyword #f "def") (jolt-get d (keyword #f "op"))))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt= (keyword #f "fn") (jolt-get f (keyword #f "op"))))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt= 1 (jolt-count (jolt-get f (keyword #f "arities")))))) (if (jolt-truthy? and__25__auto) (jolt-not (jolt-get (jolt-first (jolt-get f (keyword #f "arities"))) (keyword #f "rest"))) and__25__auto)) and__25__auto)) and__25__auto)) (let* ((a (jolt-first (jolt-get f (keyword #f "arities"))))) (let* ((_a$6355 m) (_a$6356 (let* ((_a$6345 (var-deref "clojure.core" "str")) (_a$6346 (jolt-get d (keyword #f "ns"))) (_a$6347 "/") (_a$6348 (jolt-get d (keyword #f "name")))) (jolt-invoke _a$6345 _a$6346 _a$6347 _a$6348))) (_a$6357 (let* ((_o$6349 (keyword #f "name")) (_o$6350 (jolt-get d (keyword #f "name"))) (_o$6351 (keyword #f "params")) (_o$6352 (jolt-get a (keyword #f "params"))) (_o$6353 (keyword #f "body")) (_o$6354 (jolt-get a (keyword #f "body")))) (jolt-hash-map _o$6349 _o$6350 _o$6351 _o$6352 _o$6353 _o$6354)))) (jolt-assoc _a$6355 _a$6356 _a$6357))) m))))) (_a$6359 (jolt-hash-map)) (_a$6360 nodes)) (jolt-reduce _a$6358 _a$6359 _a$6360)))))) wp-specializable) (let* ((_o$6361 (keyword #f "private")) (_o$6362 #t)) (jolt-hash-map _o$6361 _o$6362)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types" "wp-empty-ptypes" (letrec ((wp-empty-ptypes (lambda (spec ks) (let fnrec6363 ((spec spec) (ks ks)) (let* ((_a$6365 (lambda (m k) (let fnrec6364 ((m m) (k k)) (jolt-assoc m k (jolt-invoke (var-deref "clojure.core" "vec") (jolt-invoke (var-deref "clojure.core" "repeat") (jolt-count (jolt-get (jolt-get spec k) (keyword #f "params"))) jolt-nil)))))) (_a$6366 (jolt-hash-map)) (_a$6367 ks)) (jolt-reduce _a$6365 _a$6366 _a$6367)))))) wp-empty-ptypes) (let* ((_o$6368 (keyword #f "private")) (_o$6369 #t)) (jolt-hash-map _o$6368 _o$6369)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types" "wp-accum" (letrec ((wp-accum (lambda (pt spec calls) (let fnrec6370 ((pt pt) (spec spec) (calls calls)) (jolt-reduce (lambda (pt2 c) (let fnrec6371 ((pt2 pt2) (c c)) (let* ((callee (jolt-nth c 0)) (args (jolt-nth c 1))) (if (jolt-contains? spec callee) (let* ((cur (jolt-get pt2 callee))) (jolt-assoc pt2 callee (jolt-invoke (var-deref "clojure.core" "vec") (jolt-invoke (var-deref "clojure.core" "map-indexed") (lambda (i t) (let fnrec6372 ((i i) (t t)) (if (jolt-n< i (jolt-count args)) (jolt-invoke (var-deref "jolt.passes.types.lattice" "join") t (jolt-nth args i)) t))) cur)))) pt2)))) pt calls))))) wp-accum) (let* ((_o$6373 (keyword #f "private")) (_o$6374 #t)) (jolt-hash-map _o$6373 _o$6374)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types" "wp-pass" (letrec ((wp-pass (lambda (nodes spec ks ptypes) (let fnrec6375 ((nodes nodes) (spec spec) (ks ks) (ptypes ptypes)) (let* ((_a$6406 (lambda (acc node) (let fnrec6376 ((acc acc) (node node)) (let* ((k (if (jolt= (keyword #f "def") (jolt-get node (keyword #f "op"))) (let* ((_a$6377 (var-deref "clojure.core" "str")) (_a$6378 (jolt-get node (keyword #f "ns"))) (_a$6379 "/") (_a$6380 (jolt-get node (keyword #f "name")))) (jolt-invoke _a$6377 _a$6378 _a$6379 _a$6380)) jolt-nil)) (s (let* ((and__25__auto k)) (if (jolt-truthy? and__25__auto) (jolt-get spec k) and__25__auto)))) (if (jolt-truthy? s) (let* ((r (let* ((_a$6384 (var-deref "jolt.passes.types" "infer-body")) (_a$6385 (jolt-get s (keyword #f "body"))) (_a$6386 (let* ((_a$6381 (var-deref "clojure.core" "zipmap")) (_a$6382 (jolt-get s (keyword #f "params"))) (_a$6383 (jolt-get ptypes k))) (jolt-invoke _a$6381 _a$6382 _a$6383))) (_a$6387 (jolt-get s (keyword #f "name"))) (_a$6388 k) (_a$6389 (jolt-get s (keyword #f "params")))) (jolt-invoke _a$6384 _a$6385 _a$6386 _a$6387 _a$6388 _a$6389)))) (let* ((_a$6396 (var-deref "clojure.core" "update")) (_a$6397 (let* ((_a$6392 (var-deref "clojure.core" "assoc-in")) (_a$6393 acc) (_a$6394 (let* ((_o$6390 (keyword #f "rets")) (_o$6391 k)) (jolt-vector _o$6390 _o$6391))) (_a$6395 (jolt-nth r 0))) (jolt-invoke _a$6392 _a$6393 _a$6394 _a$6395))) (_a$6398 (keyword #f "ptypes")) (_a$6399 (var-deref "jolt.passes.types" "wp-accum")) (_a$6400 spec) (_a$6401 (jolt-nth r 2))) (jolt-invoke _a$6396 _a$6397 _a$6398 _a$6399 _a$6400 _a$6401))) (jolt-invoke (var-deref "clojure.core" "update") acc (keyword #f "ptypes") (var-deref "jolt.passes.types" "wp-accum") spec (jolt-nth (jolt-invoke (var-deref "jolt.passes.types" "infer-body") node (jolt-hash-map)) 2))))))) (_a$6407 (let* ((_o$6402 (keyword #f "rets")) (_o$6403 (jolt-hash-map)) (_o$6404 (keyword #f "ptypes")) (_o$6405 (jolt-invoke (var-deref "jolt.passes.types" "wp-empty-ptypes") spec ks))) (jolt-hash-map _o$6402 _o$6403 _o$6404 _o$6405))) (_a$6408 nodes)) (jolt-reduce _a$6406 _a$6407 _a$6408)))))) wp-pass) (let* ((_o$6409 (keyword #f "private")) (_o$6410 #t)) (jolt-hash-map _o$6409 _o$6410)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types" "wp-infer!" (letrec ((wp-infer! (lambda (nodes) (let fnrec6411 ((nodes nodes)) (begin (jolt-invoke (var-deref "jolt.passes.types" "collect-pm-rets!") nodes) (let* ((spec (jolt-invoke (var-deref "jolt.passes.types" "wp-specializable") nodes)) (ks (jolt-keys spec))) (let* ((iter 0) (ptypes (jolt-invoke (var-deref "jolt.passes.types" "wp-empty-ptypes") spec ks)) (rets (jolt-hash-map))) (let loop6412 ((iter iter) (ptypes ptypes) (rets rets)) (begin (jolt-invoke (var-deref "jolt.passes.types" "set-rtenv!") (let* ((_a$6414 (lambda (m k) (let fnrec6413 ((m m) (k k)) (let* ((v (jolt-get rets k))) (if (jolt-some? v) (jolt-assoc m k v) m))))) (_a$6415 (jolt-hash-map)) (_a$6416 ks)) (jolt-reduce _a$6414 _a$6415 _a$6416))) (jolt-invoke (var-deref "jolt.passes.types" "reset-escapes!")) (let* ((pass (jolt-invoke (var-deref "jolt.passes.types" "wp-pass") nodes spec ks ptypes)) (escaped (jolt-invoke (var-deref "clojure.core" "set") (jolt-invoke (var-deref "jolt.passes.types" "collected-escapes")))) (new-ptypes (let* ((_a$6418 (lambda (m k) (let fnrec6417 ((m m) (k k)) (if (jolt-contains? escaped k) (jolt-assoc m k (jolt-invoke (var-deref "clojure.core" "vec") (jolt-invoke (var-deref "clojure.core" "repeat") (jolt-count (jolt-get m k)) (keyword #f "any")))) m)))) (_a$6419 (jolt-get pass (keyword #f "ptypes"))) (_a$6420 ks)) (jolt-reduce _a$6418 _a$6419 _a$6420))) (new-rets (jolt-get pass (keyword #f "rets"))) (converged? (let* ((and__25__auto (jolt= new-ptypes ptypes))) (if (jolt-truthy? and__25__auto) (jolt= new-rets rets) and__25__auto)))) (if (jolt-truthy? (let* ((or__26__auto converged?)) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-n>= iter 16)))) (let* ((seed-ptypes (if (jolt-truthy? converged?) new-ptypes (jolt-reduce (lambda (m k) (let fnrec6421 ((m m) (k k)) (jolt-assoc m k (jolt-invoke (var-deref "clojure.core" "vec") (jolt-invoke (var-deref "clojure.core" "repeat") (jolt-count (jolt-get m k)) (keyword #f "any")))))) new-ptypes ks))) (pick (lambda (keep?) (let fnrec6422 ((keep? keep?)) (let* ((_a$6431 (lambda (m k) (let fnrec6423 ((m m) (k k)) (let* ((s (jolt-get spec k)) (pm (let* ((_a$6428 (lambda (pm pr) (let fnrec6424 ((pm pm) (pr pr)) (let* ((nm (jolt-nth pr 0)) (t (jolt-nth pr 1))) (if (jolt-truthy? (let* ((and__25__auto t)) (if (jolt-truthy? and__25__auto) (jolt-invoke keep? t) and__25__auto))) (jolt-assoc pm nm t) pm))))) (_a$6429 (jolt-hash-map)) (_a$6430 (let* ((_a$6425 jolt-vector) (_a$6426 (jolt-get s (keyword #f "params"))) (_a$6427 (jolt-get seed-ptypes k))) (jolt-map _a$6425 _a$6426 _a$6427)))) (jolt-reduce _a$6428 _a$6429 _a$6430)))) (if (jolt-truthy? (jolt-seq pm)) (jolt-assoc m k pm) m))))) (_a$6432 (jolt-hash-map)) (_a$6433 ks)) (jolt-reduce _a$6431 _a$6432 _a$6433)))))) (begin (jolt-invoke (var-deref "clojure.core" "reset!") (var-deref "jolt.passes.types" "wp-seeds-box") (jolt-invoke pick (lambda (t) (let fnrec6434 ((t t)) (let* ((and__25__auto (jolt-invoke (var-deref "clojure.core" "not=") t (keyword #f "any")))) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "clojure.core" "not=") t (keyword #f "double")) and__25__auto)))))) (jolt-invoke (var-deref "clojure.core" "reset!") (var-deref "jolt.passes.types" "wp-num-seeds-box") (jolt-invoke pick (lambda (t) (let fnrec6435 ((t t)) (jolt= t (keyword #f "double")))))))) (loop6412 (jolt-inc iter) new-ptypes new-rets)))))))))))) wp-infer!) (let* ((_o$6436 (keyword #f "doc")) (_o$6437 "Run the closed-world param-type fixpoint over the unit's analyzed top-level\n nodes and stash the resulting per-def seed maps (read via param-seeds-for).\n record-shapes / protocol-methods must already be installed. Idempotent \x2014; resets\n the seed box; called once per build before per-form emit.")) (jolt-hash-map _o$6436 _o$6437)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types" "set-check-mode!" (letrec ((set-check-mode! (lambda (on strict?) (let fnrec6438 ((on on) (strict? strict?)) (jolt-invoke (var-deref "clojure.core" "reset!") (var-deref "jolt.passes.types" "check-mode-box") (let* ((_o$6439 (keyword #f "on")) (_o$6440 (if (jolt-truthy? on) #t #f)) (_o$6441 (keyword #f "strict")) (_o$6442 (if (jolt-truthy? strict?) #t #f))) (jolt-hash-map _o$6439 _o$6440 _o$6441 _o$6442))))))) set-check-mode!) (let* ((_o$6443 (keyword #f "doc")) (_o$6444 "Enable/disable checking during the next run-passes inference (direct-link).")) (jolt-hash-map _o$6443 _o$6444)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types" "take-diags!" (letrec ((take-diags! (lambda () (let fnrec6445 () (let* ((d (jolt-invoke (var-deref "clojure.core" "deref") (var-deref "jolt.passes.types" "last-diags-box")))) (begin (jolt-invoke (var-deref "clojure.core" "reset!") (var-deref "jolt.passes.types" "last-diags-box") (jolt-vector)) d)))))) take-diags!) (let* ((_o$6446 (keyword #f "doc")) (_o$6447 "Diagnostics accumulated by the last checking run-passes; clears the buffer.")) (jolt-hash-map _o$6446 _o$6447)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes.types" "run-inference" (letrec ((run-inference (lambda (opt) (let fnrec6448 ((opt opt)) (if (jolt-truthy? (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (var-deref "jolt.passes.types" "check-mode-box")) (keyword #f "on"))) (let* ((env (jolt-invoke (var-deref "jolt.passes.types" "mk-env") #t (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (var-deref "jolt.passes.types" "check-mode-box")) (keyword #f "strict")))) (r (jolt-invoke (var-deref "jolt.passes.types" "infer-top") opt env))) (begin (jolt-invoke (var-deref "clojure.core" "reset!") (var-deref "jolt.passes.types" "last-diags-box") (jolt-invoke (var-deref "clojure.core" "deref") (jolt-get env (keyword #f "diags")))) r)) (jolt-invoke (var-deref "jolt.passes.types" "infer-top") opt (jolt-invoke (var-deref "jolt.passes.types" "mk-env") #f #f))))))) run-inference) (let* ((_o$6449 (keyword #f "doc")) (_o$6450 "Type-infer the optimized node (the inference walk specializes struct-safe\n lookups). When check mode is on (set-check-mode!), the same walk also emits\n success-type diagnostics, stashed for take-diags! to drain afterward. Pulled\n out of run-passes so the checking state stays private to this namespace.")) (jolt-hash-map _o$6449 _o$6450)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes" "inline-fixpoint-cap" 8 (let* ((_o$6451 (keyword #f "private")) (_o$6452 #t)) (jolt-hash-map _o$6451 _o$6452)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes" "inline-eligible?" (letrec ((inline-eligible? (lambda (node) (let fnrec6453 ((node node)) (let* ((and__25__auto (jolt= (keyword #f "def") (jolt-get node (keyword #f "op"))))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt-get node (keyword #f "init")))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt= (keyword #f "fn") (jolt-get (jolt-get node (keyword #f "init")) (keyword #f "op"))))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt= 1 (jolt-count (jolt-get (jolt-get node (keyword #f "init")) (keyword #f "arities")))))) (if (jolt-truthy? and__25__auto) (jolt-not (jolt-get (jolt-first (jolt-get (jolt-get node (keyword #f "init")) (keyword #f "arities"))) (keyword #f "rest"))) and__25__auto)) and__25__auto)) and__25__auto)) and__25__auto)))))) inline-eligible?) (let* ((_o$6454 (keyword #f "private")) (_o$6455 #t)) (jolt-hash-map _o$6454 _o$6455)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes" "stash-of" (letrec ((stash-of (lambda (node) (let fnrec6456 ((node node)) (let* ((a (jolt-first (jolt-get (jolt-get node (keyword #f "init")) (keyword #f "arities"))))) (let* ((_o$6457 (keyword #f "params")) (_o$6458 (jolt-get a (keyword #f "params"))) (_o$6459 (keyword #f "body")) (_o$6460 (jolt-get a (keyword #f "body"))) (_o$6461 (keyword #f "nhints")) (_o$6462 (jolt-get a (keyword #f "nhints"))) (_o$6463 (keyword #f "ret")) (_o$6464 (jolt-get a (keyword #f "ret-nhint")))) (jolt-hash-map _o$6457 _o$6458 _o$6459 _o$6460 _o$6461 _o$6462 _o$6463 _o$6464))))))) stash-of) (let* ((_o$6465 (keyword #f "private")) (_o$6466 #t)) (jolt-hash-map _o$6465 _o$6466)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes" "inject-wp-nhints" (letrec ((inject-wp-nhints (lambda (node) (let fnrec6467 ((node node)) (let* ((seeds (if (jolt= (keyword #f "def") (jolt-get node (keyword #f "op"))) (jolt-invoke (var-deref "jolt.passes.types" "param-num-seeds-for") (let* ((_a$6468 (var-deref "clojure.core" "str")) (_a$6469 (jolt-get node (keyword #f "ns"))) (_a$6470 "/") (_a$6471 (jolt-get node (keyword #f "name")))) (jolt-invoke _a$6468 _a$6469 _a$6470 _a$6471))) jolt-nil)) (f (jolt-get node (keyword #f "init")))) (if (jolt-truthy? (let* ((and__25__auto seeds)) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt= (keyword #f "fn") (jolt-get f (keyword #f "op"))))) (if (jolt-truthy? and__25__auto) (jolt= 1 (jolt-count (jolt-get f (keyword #f "arities")))) and__25__auto)) and__25__auto))) (let* ((a (jolt-first (jolt-get f (keyword #f "arities")))) (have (let* ((_a$6472 (jolt-hash-set)) (_a$6473 (jolt-map jolt-first (jolt-get a (keyword #f "nhints"))))) (jolt-into _a$6472 _a$6473))) (add (jolt-invoke (var-deref "clojure.core" "mapcat") (lambda (G__139) (let fnrec6474 ((G__139 G__139)) (let* ((G__140 G__139) (p (jolt-nth G__140 0 jolt-nil)) (k (jolt-nth G__140 1 jolt-nil))) (if (jolt-not (jolt-invoke have p)) (jolt-list (let* ((_o$6475 p) (_o$6476 k)) (jolt-vector _o$6475 _o$6476))) (jolt-vector))))) seeds))) (jolt-assoc node (keyword #f "init") (jolt-assoc f (keyword #f "arities") (jolt-vector (jolt-assoc a (keyword #f "nhints") (jolt-invoke (var-deref "clojure.core" "vec") (jolt-concat (jolt-get a (keyword #f "nhints")) add))))))) node)))))) inject-wp-nhints) (let* ((_o$6477 (keyword #f "doc")) (_o$6478 "Merge the whole-program :double param seeds into a def's arity :nhints as\n synthetic ^double hints, so the numeric pass unboxes a hintless fn whose callers\n all pass flonums (the entry coercion exact->inexact is a no-op on a proven\n flonum). Only un-hinted params are added \x2014; an explicit hint wins. A no-op unless\n the closed-world fixpoint typed a param :double (param-num-seeds-for).")) (jolt-hash-map _o$6477 _o$6478)))) -(guard (e (#t #f)) - (def-var-with-meta! "jolt.passes" "run-passes" (letrec ((run-passes (lambda (node ctx) (let fnrec6479 ((node node) (ctx ctx)) (begin (if (jolt-truthy? (let* ((and__25__auto (jolt-invoke (var-deref "jolt.host" "inline-enabled?") ctx))) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "jolt.passes" "inline-eligible?") node) and__25__auto))) (let* ((_a$6480 (var-deref "jolt.host" "stash-inline!")) (_a$6481 ctx) (_a$6482 (jolt-get node (keyword #f "ns"))) (_a$6483 (jolt-get node (keyword #f "name"))) (_a$6484 (jolt-invoke (var-deref "jolt.passes" "stash-of") node))) (jolt-invoke _a$6480 _a$6481 _a$6482 _a$6483 _a$6484)) jolt-nil) (jolt-invoke (var-deref "jolt.passes.numeric" "annotate") (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "inline-enabled?") ctx)) (let* ((_ (jolt-invoke (var-deref "jolt.passes.inline" "set-rec-shapes!") (jolt-invoke (var-deref "jolt.host" "record-shapes") ctx))) (_ (jolt-invoke (var-deref "jolt.passes.types" "set-record-shapes!") (jolt-invoke (var-deref "jolt.host" "record-shapes") ctx))) (_ (jolt-invoke (var-deref "jolt.passes.types" "set-protocol-methods!") (jolt-invoke (var-deref "jolt.host" "protocol-methods") ctx))) (opt (let* ((i 0) (n (jolt-invoke (var-deref "jolt.passes.fold" "const-fold") node))) (let loop6485 ((i i) (n n)) (begin (jolt-invoke (var-deref "clojure.core" "reset!") (var-deref "jolt.passes.inline" "dirty") #f) (let* ((n2 (jolt-invoke (var-deref "jolt.passes.fold" "const-fold") (jolt-invoke (var-deref "jolt.passes.inline" "scalar-replace") (jolt-invoke (var-deref "jolt.passes.inline" "flatten-lets") (jolt-invoke (var-deref "jolt.passes.inline" "inline-node") n ctx)))))) (if (jolt-truthy? (let* ((and__25__auto (jolt-invoke (var-deref "clojure.core" "deref") (var-deref "jolt.passes.inline" "dirty")))) (if (jolt-truthy? and__25__auto) (jolt-n< i (var-deref "jolt.passes" "inline-fixpoint-cap")) and__25__auto))) (loop6485 (jolt-inc i) n2) n2)))))) (seeds (if (jolt= (keyword #f "def") (jolt-get opt (keyword #f "op"))) (jolt-invoke (var-deref "jolt.passes.types" "param-seeds-for") (let* ((_a$6486 (var-deref "clojure.core" "str")) (_a$6487 (jolt-get opt (keyword #f "ns"))) (_a$6488 "/") (_a$6489 (jolt-get opt (keyword #f "name")))) (jolt-invoke _a$6486 _a$6487 _a$6488 _a$6489))) jolt-nil))) (jolt-invoke (var-deref "jolt.passes" "inject-wp-nhints") (jolt-invoke (var-deref "jolt.passes.fold" "const-fold") (if (jolt-truthy? seeds) (jolt-invoke (var-deref "jolt.passes.types" "reinfer-def") opt seeds) (jolt-invoke (var-deref "jolt.passes.types" "run-inference") opt))))) (jolt-invoke (var-deref "jolt.passes.fold" "const-fold") node)))))))) run-passes) (let* ((_o$6490 (keyword #f "doc")) (_o$6491 "All passes, in order. The back end applies this to every analyzed form. When\n inlining is enabled for the unit (user code under direct-linking),\n run inline + flatten + scalar-replace + const-fold to a capped fixpoint \x2014;\n inlining exposes map literals to lookups, scalar-replace collapses them, which\n may expose more \x2014; then a collection-type inference pass (optionally\n also emitting success diagnostics) that auto-drops the lookup guard where the\n type is proven. Otherwise (core + bootstrap) just const-fold, as before.\n\n numeric/annotate runs last in both branches (hint-directed fl*/fx* arithmetic);\n it benefits open builds too, so it is not gated on inlining.")) (jolt-hash-map _o$6490 _o$6491)))) \ No newline at end of file diff --git a/host/chez/seed/prelude.ss b/host/chez/seed/prelude.ss deleted file mode 100644 index 1c9f784..0000000 --- a/host/chez/seed/prelude.ss +++ /dev/null @@ -1,1514 +0,0 @@ -(guard (e (#t #f)) - (def-var! "clojure.core" "zero?" (letrec ((zero? (lambda (x) (let fnrec5041 ((x x)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "number?") x)) (jolt= x 0) (jolt-throw (jolt-invoke (var-deref "clojure.core" "str") "zero? requires a number, got: " x))))))) zero?))) -(guard (e (#t #f)) - (def-var! "clojure.core" "pos?" (letrec ((pos? (lambda (x) (let fnrec5042 ((x x)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "number?") x)) (jolt-n> x 0) (jolt-throw (jolt-invoke (var-deref "clojure.core" "str") "pos? requires a number, got: " x))))))) pos?))) -(guard (e (#t #f)) - (def-var! "clojure.core" "every?" (letrec ((every? (lambda (pred coll) (let fnrec5043 ((pred pred) (coll coll)) (if (jolt-nil? (jolt-seq coll)) #t (if (jolt-truthy? (jolt-invoke pred (jolt-first coll))) (fnrec5043 pred (jolt-next coll)) #f)))))) every?))) -(guard (e (#t #f)) - (def-var! "clojure.core" "empty?" (letrec ((empty? (lambda (coll) (let fnrec5044 ((coll coll)) (if (jolt-nil? coll) #t (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "vector?") coll)) (jolt-zero? (jolt-count coll)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "map?") coll)) (jolt-zero? (jolt-count coll)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "set?") coll)) (jolt-zero? (jolt-count coll)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "string?") coll)) (jolt-zero? (jolt-count coll)) (jolt-nil? (jolt-seq coll))))))))))) empty?))) -(guard (e (#t #f)) - (def-var! "clojure.core" "keys" (letrec ((keys (lambda (m) (let fnrec5045 ((m m)) (let* ((s (jolt-seq m))) (if (jolt-truthy? s) (jolt-map (lambda (e) (let fnrec5046 ((e e)) (jolt-nth e 0))) s) jolt-nil)))))) keys))) -(guard (e (#t #f)) - (def-var! "clojure.core" "vals" (letrec ((vals (lambda (m) (let fnrec5047 ((m m)) (let* ((s (jolt-seq m))) (if (jolt-truthy? s) (jolt-map (lambda (e) (let fnrec5048 ((e e)) (jolt-nth e 1))) s) jolt-nil)))))) vals))) -(guard (e (#t #f)) - (def-var! "clojure.core" "when" - (lambda (test . body) (let fnrec5049 ((test test) (body (list->cseq body))) (let* ((_a$5050 (var-deref "clojure.core" "__sqcat")) (_a$5051 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "if"))) (_a$5052 (jolt-invoke (var-deref "clojure.core" "__sq1") test)) (_a$5053 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqcat") (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "do")) body)))) (jolt-invoke _a$5050 _a$5051 _a$5052 _a$5053))))) - (mark-macro! "clojure.core" "when")) -(guard (e (#t #f)) - (def-var! "clojure.core" "when-not" - (lambda (test . body) (let fnrec5054 ((test test) (body (list->cseq body))) (let* ((_a$5058 (var-deref "clojure.core" "__sqcat")) (_a$5059 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "if"))) (_a$5060 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$5055 (var-deref "clojure.core" "__sqcat")) (_a$5056 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "not"))) (_a$5057 (jolt-invoke (var-deref "clojure.core" "__sq1") test))) (jolt-invoke _a$5055 _a$5056 _a$5057)))) (_a$5061 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqcat") (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "do")) body)))) (jolt-invoke _a$5058 _a$5059 _a$5060 _a$5061))))) - (mark-macro! "clojure.core" "when-not")) -(guard (e (#t #f)) - (def-var! "clojure.core" "and" - (lambda exprs (let fnrec5062 ((exprs (list->cseq exprs))) (if (jolt-empty? exprs) #t (if (jolt-empty? (jolt-rest exprs)) (jolt-first exprs) (let* ((_a$5074 (var-deref "clojure.core" "__sqcat")) (_a$5075 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "let*"))) (_a$5076 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$5063 (var-deref "clojure.core" "__sqvec")) (_a$5064 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "and__25__auto"))) (_a$5065 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-first exprs)))) (jolt-invoke _a$5063 _a$5064 _a$5065)))) (_a$5077 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$5069 (var-deref "clojure.core" "__sqcat")) (_a$5070 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "if"))) (_a$5071 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "and__25__auto"))) (_a$5072 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$5066 (var-deref "clojure.core" "__sqcat")) (_a$5067 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "and"))) (_a$5068 (jolt-rest exprs))) (jolt-invoke _a$5066 _a$5067 _a$5068)))) (_a$5073 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "and__25__auto")))) (jolt-invoke _a$5069 _a$5070 _a$5071 _a$5072 _a$5073))))) (jolt-invoke _a$5074 _a$5075 _a$5076 _a$5077))))))) - (mark-macro! "clojure.core" "and")) -(guard (e (#t #f)) - (def-var! "clojure.core" "or" - (lambda exprs (let fnrec5078 ((exprs (list->cseq exprs))) (if (jolt-empty? exprs) jolt-nil (if (jolt-empty? (jolt-rest exprs)) (jolt-first exprs) (let* ((_a$5090 (var-deref "clojure.core" "__sqcat")) (_a$5091 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "let*"))) (_a$5092 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$5079 (var-deref "clojure.core" "__sqvec")) (_a$5080 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "or__26__auto"))) (_a$5081 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-first exprs)))) (jolt-invoke _a$5079 _a$5080 _a$5081)))) (_a$5093 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$5085 (var-deref "clojure.core" "__sqcat")) (_a$5086 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "if"))) (_a$5087 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "or__26__auto"))) (_a$5088 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "or__26__auto"))) (_a$5089 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$5082 (var-deref "clojure.core" "__sqcat")) (_a$5083 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "or"))) (_a$5084 (jolt-rest exprs))) (jolt-invoke _a$5082 _a$5083 _a$5084))))) (jolt-invoke _a$5085 _a$5086 _a$5087 _a$5088 _a$5089))))) (jolt-invoke _a$5090 _a$5091 _a$5092 _a$5093))))))) - (mark-macro! "clojure.core" "or")) -(guard (e (#t #f)) - (def-var! "clojure.core" "cond" - (lambda clauses (let fnrec5094 ((clauses (list->cseq clauses))) (if (jolt-empty? clauses) jolt-nil (let* ((_a$5098 (var-deref "clojure.core" "__sqcat")) (_a$5099 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "if"))) (_a$5100 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-first clauses))) (_a$5101 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-nth clauses 1))) (_a$5102 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$5095 (var-deref "clojure.core" "__sqcat")) (_a$5096 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "cond"))) (_a$5097 (jolt-drop 2 clauses))) (jolt-invoke _a$5095 _a$5096 _a$5097))))) (jolt-invoke _a$5098 _a$5099 _a$5100 _a$5101 _a$5102)))))) - (mark-macro! "clojure.core" "cond")) -(guard (e (#t #f)) - (def-var! "clojure.core" "ns" - (lambda (nm . clauses) (let fnrec5103 ((nm nm) (clauses (list->cseq clauses))) (let* ((nm (if (jolt-truthy? (let* ((and__25__auto (jolt-invoke (var-deref "clojure.core" "seq?") nm))) (if (jolt-truthy? and__25__auto) (jolt= (jolt-symbol #f "with-meta") (jolt-first nm)) and__25__auto))) (jolt-invoke (var-deref "clojure.core" "second") nm) nm)) (calls (let* ((_a$5133 (lambda (acc clause) (let fnrec5104 ((acc acc) (clause clause)) (if (jolt-truthy? (let* ((or__26__auto (jolt-invoke (var-deref "clojure.core" "seq?") clause))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-invoke (var-deref "clojure.core" "vector?") clause)))) (let* ((head (jolt-first clause)) (args (jolt-rest clause))) (if (jolt= head (keyword #f "require")) (jolt-conj acc (let* ((_a$5109 (var-deref "clojure.core" "__sqcat")) (_a$5110 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "require"))) (_a$5111 (jolt-map (lambda (s) (let fnrec5105 ((s s)) (let* ((_a$5106 (var-deref "clojure.core" "__sqcat")) (_a$5107 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "quote"))) (_a$5108 (jolt-invoke (var-deref "clojure.core" "__sq1") s))) (jolt-invoke _a$5106 _a$5107 _a$5108)))) args))) (jolt-invoke _a$5109 _a$5110 _a$5111))) (if (jolt= head (keyword #f "use")) (jolt-conj acc (let* ((_a$5116 (var-deref "clojure.core" "__sqcat")) (_a$5117 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "use"))) (_a$5118 (jolt-map (lambda (s) (let fnrec5112 ((s s)) (let* ((_a$5113 (var-deref "clojure.core" "__sqcat")) (_a$5114 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "quote"))) (_a$5115 (jolt-invoke (var-deref "clojure.core" "__sq1") s))) (jolt-invoke _a$5113 _a$5114 _a$5115)))) args))) (jolt-invoke _a$5116 _a$5117 _a$5118))) (if (jolt= head (keyword #f "import")) (jolt-conj acc (let* ((_a$5123 (var-deref "clojure.core" "__sqcat")) (_a$5124 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "import"))) (_a$5125 (jolt-map (lambda (s) (let fnrec5119 ((s s)) (let* ((_a$5120 (var-deref "clojure.core" "__sqcat")) (_a$5121 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "quote"))) (_a$5122 (jolt-invoke (var-deref "clojure.core" "__sq1") s))) (jolt-invoke _a$5120 _a$5121 _a$5122)))) args))) (jolt-invoke _a$5123 _a$5124 _a$5125))) (if (jolt= head (keyword #f "refer-clojure")) (jolt-conj acc (let* ((_a$5130 (var-deref "clojure.core" "__sqcat")) (_a$5131 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "refer-clojure"))) (_a$5132 (jolt-map (lambda (s) (let fnrec5126 ((s s)) (let* ((_a$5127 (var-deref "clojure.core" "__sqcat")) (_a$5128 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "quote"))) (_a$5129 (jolt-invoke (var-deref "clojure.core" "__sq1") s))) (jolt-invoke _a$5127 _a$5128 _a$5129)))) args))) (jolt-invoke _a$5130 _a$5131 _a$5132))) (if (jolt-truthy? (keyword #f "else")) acc jolt-nil)))))) acc)))) (_a$5134 (jolt-vector)) (_a$5135 clauses)) (jolt-reduce _a$5133 _a$5134 _a$5135)))) (let* ((_a$5142 (var-deref "clojure.core" "__sqcat")) (_a$5143 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "do"))) (_a$5144 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$5139 (var-deref "clojure.core" "__sqcat")) (_a$5140 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "in-ns"))) (_a$5141 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$5136 (var-deref "clojure.core" "__sqcat")) (_a$5137 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "quote"))) (_a$5138 (jolt-invoke (var-deref "clojure.core" "__sq1") nm))) (jolt-invoke _a$5136 _a$5137 _a$5138))))) (jolt-invoke _a$5139 _a$5140 _a$5141)))) (_a$5145 calls)) (jolt-invoke _a$5142 _a$5143 _a$5144 _a$5145)))))) - (mark-macro! "clojure.core" "ns")) -(guard (e (#t #f)) - (def-var! "clojure.core" "->" - (lambda (x . forms) (let fnrec5146 ((x x) (forms (list->cseq forms))) (if (jolt-empty? forms) x (let* ((form (jolt-first forms)) (threaded (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "seq?") form)) (let* ((_a$5147 (var-deref "clojure.core" "__sqcat")) (_a$5148 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-first form))) (_a$5149 (jolt-invoke (var-deref "clojure.core" "__sq1") x)) (_a$5150 (jolt-rest form))) (jolt-invoke _a$5147 _a$5148 _a$5149 _a$5150)) (let* ((_a$5151 (var-deref "clojure.core" "__sqcat")) (_a$5152 (jolt-invoke (var-deref "clojure.core" "__sq1") form)) (_a$5153 (jolt-invoke (var-deref "clojure.core" "__sq1") x))) (jolt-invoke _a$5151 _a$5152 _a$5153))))) (let* ((_a$5154 (var-deref "clojure.core" "__sqcat")) (_a$5155 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "->"))) (_a$5156 (jolt-invoke (var-deref "clojure.core" "__sq1") threaded)) (_a$5157 (jolt-rest forms))) (jolt-invoke _a$5154 _a$5155 _a$5156 _a$5157))))))) - (mark-macro! "clojure.core" "->")) -(guard (e (#t #f)) - (def-var! "clojure.core" "->>" - (lambda (x . forms) (let fnrec5158 ((x x) (forms (list->cseq forms))) (if (jolt-empty? forms) x (let* ((form (jolt-first forms)) (threaded (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "seq?") form)) (let* ((_a$5159 (var-deref "clojure.core" "__sqcat")) (_a$5160 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-first form))) (_a$5161 (jolt-rest form)) (_a$5162 (jolt-invoke (var-deref "clojure.core" "__sq1") x))) (jolt-invoke _a$5159 _a$5160 _a$5161 _a$5162)) (let* ((_a$5163 (var-deref "clojure.core" "__sqcat")) (_a$5164 (jolt-invoke (var-deref "clojure.core" "__sq1") form)) (_a$5165 (jolt-invoke (var-deref "clojure.core" "__sq1") x))) (jolt-invoke _a$5163 _a$5164 _a$5165))))) (let* ((_a$5166 (var-deref "clojure.core" "__sqcat")) (_a$5167 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "->>"))) (_a$5168 (jolt-invoke (var-deref "clojure.core" "__sq1") threaded)) (_a$5169 (jolt-rest forms))) (jolt-invoke _a$5166 _a$5167 _a$5168 _a$5169))))))) - (mark-macro! "clojure.core" "->>")) -(guard (e (#t #f)) - (def-var! "clojure.core" "declare" - (lambda syms (let fnrec5170 ((syms (list->cseq syms))) (let* ((_a$5175 (var-deref "clojure.core" "__sqcat")) (_a$5176 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "do"))) (_a$5177 (jolt-map (lambda (s) (let fnrec5171 ((s s)) (let* ((_a$5172 (var-deref "clojure.core" "__sqcat")) (_a$5173 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "def"))) (_a$5174 (jolt-invoke (var-deref "clojure.core" "__sq1") s))) (jolt-invoke _a$5172 _a$5173 _a$5174)))) syms))) (jolt-invoke _a$5175 _a$5176 _a$5177))))) - (mark-macro! "clojure.core" "declare")) -(guard (e (#t #f)) - (def-var! "clojure.core" "letfn" - (lambda (fnspecs . body) (let fnrec5178 ((fnspecs fnspecs) (body (list->cseq body))) (jolt-cons (jolt-symbol #f "letfn*") (jolt-cons (let* ((_a$5182 (lambda (acc s) (let fnrec5179 ((acc acc) (s s)) (let* ((_a$5180 (jolt-conj acc (jolt-first s))) (_a$5181 (jolt-cons (jolt-symbol #f "fn") s))) (jolt-conj _a$5180 _a$5181))))) (_a$5183 (jolt-vector)) (_a$5184 fnspecs)) (jolt-reduce _a$5182 _a$5183 _a$5184)) body))))) - (mark-macro! "clojure.core" "letfn")) -(guard (e (#t #f)) - (def-var! "clojure.core" "destructure" (letrec ((destructure (lambda (bindings) (let fnrec5185 ((bindings bindings)) (let* ((find-or (lambda (or-map nm) (let fnrec5186 ((or-map or-map) (nm nm)) (let* ((_a$5192 (lambda (acc k) (let fnrec5187 ((acc acc) (k k)) (if (jolt-truthy? (let* ((and__25__auto (jolt-invoke (var-deref "clojure.core" "symbol?") k))) (if (jolt-truthy? and__25__auto) (jolt= nm (jolt-invoke (var-deref "clojure.core" "name") k)) and__25__auto))) (let* ((_o$5188 #t) (_o$5189 (jolt-get or-map k))) (jolt-vector _o$5188 _o$5189)) acc)))) (_a$5193 (let* ((_o$5190 #f) (_o$5191 jolt-nil)) (jolt-vector _o$5190 _o$5191))) (_a$5194 (if (jolt-truthy? or-map) (jolt-keys or-map) (jolt-vector)))) (jolt-reduce _a$5192 _a$5193 _a$5194))))) (amp? (lambda (x) (let fnrec5195 ((x x)) (let* ((and__25__auto (jolt-invoke (var-deref "clojure.core" "symbol?") x))) (if (jolt-truthy? and__25__auto) (jolt= "&" (jolt-invoke (var-deref "clojure.core" "name") x)) and__25__auto))))) (classify (lambda (names) (let fnrec5196 ((names names)) (jolt-nth (let* ((_a$5208 (lambda (st x) (let fnrec5197 ((st st) (x x)) (if (jolt-truthy? (jolt-invoke amp? x)) (let* ((_o$5198 (jolt-nth st 0)) (_o$5199 #f)) (jolt-vector _o$5198 _o$5199)) (let* ((_o$5204 (let* ((_a$5202 (jolt-nth st 0)) (_a$5203 (let* ((_o$5200 x) (_o$5201 (jolt-nth st 1))) (jolt-vector _o$5200 _o$5201)))) (jolt-conj _a$5202 _a$5203))) (_o$5205 (jolt-nth st 1))) (jolt-vector _o$5204 _o$5205)))))) (_a$5209 (let* ((_o$5206 (jolt-vector)) (_o$5207 #t)) (jolt-vector _o$5206 _o$5207))) (_a$5210 names)) (jolt-reduce _a$5208 _a$5209 _a$5210)) 0)))) (proc (letrec ((proc (lambda (pat init acc) (let fnrec5211 ((pat pat) (init init) (acc acc)) (if (jolt-truthy? (jolt-invoke amp? pat)) (jolt-throw (host-new "IllegalArgumentException" "Can't use & as a local binding")) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "symbol?") pat)) (jolt-conj (jolt-conj acc pat) init) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "vector?") pat)) (let* ((g (jolt-invoke (var-deref "clojure.core" "symbol") (jolt-invoke (var-deref "clojure.core" "str") (jolt-invoke (var-deref "clojure.core" "gensym"))))) (n (jolt-count pat)) (vloop (letrec ((vloop (lambda (i idx a) (let fnrec5212 ((i i) (idx idx) (a a)) (if (jolt-n< i n) (let* ((elem (jolt-nth pat i))) (if (jolt-truthy? (jolt-invoke amp? elem)) (let* ((_a$5220 (jolt-n+ i 2)) (_a$5221 idx) (_a$5222 (let* ((_a$5217 (jolt-nth pat (jolt-inc i))) (_a$5218 (let* ((_a$5213 (var-deref "clojure.core" "__sqcat")) (_a$5214 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "nthnext"))) (_a$5215 (jolt-invoke (var-deref "clojure.core" "__sq1") g)) (_a$5216 (jolt-invoke (var-deref "clojure.core" "__sq1") idx))) (jolt-invoke _a$5213 _a$5214 _a$5215 _a$5216))) (_a$5219 a)) (proc _a$5217 _a$5218 _a$5219)))) (vloop _a$5220 _a$5221 _a$5222)) (if (jolt= elem (keyword #f "as")) (let* ((_a$5223 (jolt-n+ i 2)) (_a$5224 idx) (_a$5225 (proc (jolt-nth pat (jolt-inc i)) g a))) (vloop _a$5223 _a$5224 _a$5225)) (if (jolt-truthy? (keyword #f "else")) (let* ((_a$5231 (jolt-inc i)) (_a$5232 (jolt-inc idx)) (_a$5233 (proc elem (let* ((_a$5226 (var-deref "clojure.core" "__sqcat")) (_a$5227 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "nth"))) (_a$5228 (jolt-invoke (var-deref "clojure.core" "__sq1") g)) (_a$5229 (jolt-invoke (var-deref "clojure.core" "__sq1") idx)) (_a$5230 (jolt-invoke (var-deref "clojure.core" "__sq1") jolt-nil))) (jolt-invoke _a$5226 _a$5227 _a$5228 _a$5229 _a$5230)) a))) (vloop _a$5231 _a$5232 _a$5233)) jolt-nil)))) a))))) vloop))) (jolt-invoke vloop 0 0 (jolt-conj (jolt-conj acc g) init))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "map?") pat)) (let* ((g (jolt-invoke (var-deref "clojure.core" "symbol") (jolt-invoke (var-deref "clojure.core" "str") (jolt-invoke (var-deref "clojure.core" "gensym"))))) (gm (jolt-invoke (var-deref "clojure.core" "symbol") (jolt-invoke (var-deref "clojure.core" "str") (jolt-invoke (var-deref "clojure.core" "gensym"))))) (coerce (let* ((_a$5266 (var-deref "clojure.core" "__sqcat")) (_a$5267 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "if"))) (_a$5268 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$5234 (var-deref "clojure.core" "__sqcat")) (_a$5235 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "sequential?"))) (_a$5236 (jolt-invoke (var-deref "clojure.core" "__sq1") g))) (jolt-invoke _a$5234 _a$5235 _a$5236)))) (_a$5269 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$5261 (var-deref "clojure.core" "__sqcat")) (_a$5262 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "if"))) (_a$5263 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$5240 (var-deref "clojure.core" "__sqcat")) (_a$5241 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "odd?"))) (_a$5242 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$5237 (var-deref "clojure.core" "__sqcat")) (_a$5238 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "count"))) (_a$5239 (jolt-invoke (var-deref "clojure.core" "__sq1") g))) (jolt-invoke _a$5237 _a$5238 _a$5239))))) (jolt-invoke _a$5240 _a$5241 _a$5242)))) (_a$5264 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$5253 (var-deref "clojure.core" "__sqcat")) (_a$5254 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "merge"))) (_a$5255 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$5246 (var-deref "clojure.core" "__sqcat")) (_a$5247 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "apply"))) (_a$5248 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "hash-map"))) (_a$5249 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$5243 (var-deref "clojure.core" "__sqcat")) (_a$5244 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "butlast"))) (_a$5245 (jolt-invoke (var-deref "clojure.core" "__sq1") g))) (jolt-invoke _a$5243 _a$5244 _a$5245))))) (jolt-invoke _a$5246 _a$5247 _a$5248 _a$5249)))) (_a$5256 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$5250 (var-deref "clojure.core" "__sqcat")) (_a$5251 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "last"))) (_a$5252 (jolt-invoke (var-deref "clojure.core" "__sq1") g))) (jolt-invoke _a$5250 _a$5251 _a$5252))))) (jolt-invoke _a$5253 _a$5254 _a$5255 _a$5256)))) (_a$5265 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$5257 (var-deref "clojure.core" "__sqcat")) (_a$5258 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "apply"))) (_a$5259 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "hash-map"))) (_a$5260 (jolt-invoke (var-deref "clojure.core" "__sq1") g))) (jolt-invoke _a$5257 _a$5258 _a$5259 _a$5260))))) (jolt-invoke _a$5261 _a$5262 _a$5263 _a$5264 _a$5265)))) (_a$5270 (jolt-invoke (var-deref "clojure.core" "__sq1") g))) (jolt-invoke _a$5266 _a$5267 _a$5268 _a$5269 _a$5270))) (or-map (jolt-get pat (keyword #f "or"))) (as-sym (jolt-get pat (keyword #f "as"))) (bound (jolt-conj (jolt-conj (jolt-conj (jolt-conj acc g) init) gm) coerce)) (base (if (jolt-truthy? as-sym) (jolt-conj (jolt-conj bound as-sym) gm) bound)) (group (letrec ((group (lambda (a names kind dnsp checked?) (let fnrec5271 ((a a) (names names) (kind kind) (dnsp dnsp) (checked? checked?)) (if (jolt-truthy? names) (let* ((_a$5289 (lambda (aa pair) (let fnrec5272 ((aa aa) (pair pair)) (let* ((s (jolt-nth pair 0)) (bind? (jolt-nth pair 1)) (local (jolt-invoke (var-deref "clojure.core" "name") s)) (nsp (let* ((or__26__auto (jolt-invoke (var-deref "clojure.core" "namespace") s))) (if (jolt-truthy? or__26__auto) or__26__auto dnsp))) (keyform (if (jolt= kind (keyword #f "kw")) (jolt-invoke (var-deref "clojure.core" "keyword") (if (jolt-truthy? nsp) (jolt-invoke (var-deref "clojure.core" "str") nsp "/" local) local)) (if (jolt= kind (keyword #f "str")) local (if (jolt-truthy? (keyword #f "else")) (let* ((_a$5273 (var-deref "clojure.core" "__sqcat")) (_a$5274 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "quote"))) (_a$5275 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "symbol") nsp local)))) (jolt-invoke _a$5273 _a$5274 _a$5275)) jolt-nil)))) (fo (jolt-invoke find-or or-map local)) (lookup (if (jolt-truthy? checked?) (let* ((_a$5276 (var-deref "clojure.core" "__sqcat")) (_a$5277 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "req!"))) (_a$5278 (jolt-invoke (var-deref "clojure.core" "__sq1") gm)) (_a$5279 (jolt-invoke (var-deref "clojure.core" "__sq1") keyform))) (jolt-invoke _a$5276 _a$5277 _a$5278 _a$5279)) (if (jolt-truthy? (jolt-nth fo 0)) (let* ((_a$5280 (var-deref "clojure.core" "__sqcat")) (_a$5281 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "get"))) (_a$5282 (jolt-invoke (var-deref "clojure.core" "__sq1") gm)) (_a$5283 (jolt-invoke (var-deref "clojure.core" "__sq1") keyform)) (_a$5284 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-nth fo 1)))) (jolt-invoke _a$5280 _a$5281 _a$5282 _a$5283 _a$5284)) (if (jolt-truthy? (keyword #f "else")) (let* ((_a$5285 (var-deref "clojure.core" "__sqcat")) (_a$5286 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "get"))) (_a$5287 (jolt-invoke (var-deref "clojure.core" "__sq1") gm)) (_a$5288 (jolt-invoke (var-deref "clojure.core" "__sq1") keyform))) (jolt-invoke _a$5285 _a$5286 _a$5287 _a$5288)) jolt-nil))))) (if (jolt-truthy? bind?) (jolt-conj (jolt-conj aa (jolt-invoke (var-deref "clojure.core" "symbol") local)) lookup) (if (jolt-truthy? checked?) (jolt-conj (jolt-conj aa (jolt-invoke (var-deref "clojure.core" "symbol") (jolt-invoke (var-deref "clojure.core" "str") (jolt-invoke (var-deref "clojure.core" "gensym"))))) lookup) (if (jolt-truthy? (keyword #f "else")) aa jolt-nil))))))) (_a$5290 a) (_a$5291 (jolt-invoke classify names))) (jolt-reduce _a$5289 _a$5290 _a$5291)) a))))) group)) (g1 (jolt-invoke group base (jolt-get pat (keyword #f "keys")) (keyword #f "kw") jolt-nil #f)) (g2 (jolt-invoke group g1 (jolt-get pat (keyword #f "strs")) (keyword #f "str") jolt-nil #f)) (g3 (jolt-invoke group g2 (jolt-get pat (keyword #f "syms")) (keyword #f "sym") jolt-nil #f)) (g4 (jolt-invoke group g3 (jolt-get pat (keyword #f "keys!")) (keyword #f "kw") jolt-nil #t)) (g5 (jolt-invoke group g4 (jolt-get pat (keyword #f "strs!")) (keyword #f "str") jolt-nil #t)) (g6 (jolt-invoke group g5 (jolt-get pat (keyword #f "syms!")) (keyword #f "sym") jolt-nil #t))) (let* ((_a$5304 (lambda (a k) (let fnrec5292 ((a a) (k k)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "keyword?") k)) (let* ((kn (jolt-invoke (var-deref "clojure.core" "name") k)) (kns (jolt-invoke (var-deref "clojure.core" "namespace") k))) (if (jolt-truthy? (let* ((and__25__auto kns)) (if (jolt-truthy? and__25__auto) (jolt= kn "keys") and__25__auto))) (jolt-invoke group a (jolt-get pat k) (keyword #f "kw") kns #f) (if (jolt-truthy? (let* ((and__25__auto kns)) (if (jolt-truthy? and__25__auto) (jolt= kn "strs") and__25__auto))) (jolt-invoke group a (jolt-get pat k) (keyword #f "str") kns #f) (if (jolt-truthy? (let* ((and__25__auto kns)) (if (jolt-truthy? and__25__auto) (jolt= kn "syms") and__25__auto))) (jolt-invoke group a (jolt-get pat k) (keyword #f "sym") kns #f) (if (jolt-truthy? (let* ((and__25__auto kns)) (if (jolt-truthy? and__25__auto) (jolt= kn "keys!") and__25__auto))) (jolt-invoke group a (jolt-get pat k) (keyword #f "kw") kns #t) (if (jolt-truthy? (let* ((and__25__auto kns)) (if (jolt-truthy? and__25__auto) (jolt= kn "strs!") and__25__auto))) (jolt-invoke group a (jolt-get pat k) (keyword #f "str") kns #t) (if (jolt-truthy? (let* ((and__25__auto kns)) (if (jolt-truthy? and__25__auto) (jolt= kn "syms!") and__25__auto))) (jolt-invoke group a (jolt-get pat k) (keyword #f "sym") kns #t) (if (jolt-truthy? (keyword #f "else")) a jolt-nil)))))))) (let* ((fo (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "symbol?") k)) (jolt-invoke find-or or-map (jolt-invoke (var-deref "clojure.core" "name") k)) (let* ((_o$5293 #f) (_o$5294 jolt-nil)) (jolt-vector _o$5293 _o$5294))))) (proc k (if (jolt-truthy? (jolt-nth fo 0)) (let* ((_a$5295 (var-deref "clojure.core" "__sqcat")) (_a$5296 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "get"))) (_a$5297 (jolt-invoke (var-deref "clojure.core" "__sq1") gm)) (_a$5298 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-get pat k))) (_a$5299 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-nth fo 1)))) (jolt-invoke _a$5295 _a$5296 _a$5297 _a$5298 _a$5299)) (let* ((_a$5300 (var-deref "clojure.core" "__sqcat")) (_a$5301 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "get"))) (_a$5302 (jolt-invoke (var-deref "clojure.core" "__sq1") gm)) (_a$5303 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-get pat k)))) (jolt-invoke _a$5300 _a$5301 _a$5302 _a$5303))) a)))))) (_a$5305 g6) (_a$5306 (jolt-keys pat))) (jolt-reduce _a$5304 _a$5305 _a$5306))) (if (jolt-truthy? (keyword #f "else")) (jolt-throw (jolt-invoke (var-deref "clojure.core" "str") "unsupported destructuring pattern: " (jolt-invoke (var-deref "clojure.core" "pr-str") pat))) jolt-nil))))))))) proc)) (ploop (letrec ((ploop (lambda (i acc) (let fnrec5307 ((i i) (acc acc)) (if (jolt-n< i (jolt-count bindings)) (let* ((_a$5312 (jolt-n+ i 2)) (_a$5313 (let* ((_a$5308 proc) (_a$5309 (jolt-nth bindings i)) (_a$5310 (jolt-nth bindings (jolt-inc i))) (_a$5311 acc)) (jolt-invoke _a$5308 _a$5309 _a$5310 _a$5311)))) (ploop _a$5312 _a$5313)) acc))))) ploop))) (jolt-invoke ploop 0 (jolt-vector))))))) destructure))) -(guard (e (#t #f)) - (def-var! "clojure.core" "let" - (lambda (bindings . body) (let fnrec5314 ((bindings bindings) (body (list->cseq body))) (let* ((_a$5315 (var-deref "clojure.core" "__sqcat")) (_a$5316 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "let*"))) (_a$5317 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqvec") (jolt-invoke (var-deref "clojure.core" "destructure") bindings)))) (_a$5318 body)) (jolt-invoke _a$5315 _a$5316 _a$5317 _a$5318))))) - (mark-macro! "clojure.core" "let")) -(guard (e (#t #f)) - (def-var! "clojure.core" "loop" - (lambda (bindings . body) (let fnrec5319 ((bindings bindings) (body (list->cseq body))) (let* ((d (jolt-invoke (var-deref "clojure.core" "destructure") bindings))) (if (jolt= d bindings) (let* ((_a$5320 (var-deref "clojure.core" "__sqcat")) (_a$5321 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "loop*"))) (_a$5322 (jolt-invoke (var-deref "clojure.core" "__sq1") bindings)) (_a$5323 body)) (jolt-invoke _a$5320 _a$5321 _a$5322 _a$5323)) (let* ((bs (jolt-invoke (var-deref "clojure.core" "take-nth") 2 bindings)) (vs (jolt-invoke (var-deref "clojure.core" "take-nth") 2 (jolt-drop 1 bindings))) (gs (jolt-map (lambda (b) (let fnrec5324 ((b b)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "symbol?") b)) b (jolt-invoke (var-deref "clojure.core" "symbol") (jolt-invoke (var-deref "clojure.core" "str") (jolt-invoke (var-deref "clojure.core" "gensym"))))))) bs)) (outer (let* ((_a$5326 (lambda (acc t) (let fnrec5325 ((acc acc) (t t)) (let* ((b (jolt-nth t 0)) (v (jolt-nth t 1)) (g (jolt-nth t 2))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "symbol?") b)) (jolt-conj (jolt-conj acc g) v) (jolt-conj (jolt-conj (jolt-conj (jolt-conj acc g) v) b) g)))))) (_a$5327 (jolt-vector)) (_a$5328 (jolt-map jolt-vector bs vs gs))) (jolt-reduce _a$5326 _a$5327 _a$5328))) (inner (let* ((_a$5332 (lambda (acc t) (let fnrec5329 ((acc acc) (t t)) (let* ((_a$5330 (jolt-conj acc (jolt-nth t 0))) (_a$5331 (jolt-nth t 1))) (jolt-conj _a$5330 _a$5331))))) (_a$5333 (jolt-vector)) (_a$5334 (jolt-map jolt-vector bs gs))) (jolt-reduce _a$5332 _a$5333 _a$5334))) (loopv (let* ((_a$5336 (lambda (acc g) (let fnrec5335 ((acc acc) (g g)) (jolt-conj (jolt-conj acc g) g)))) (_a$5337 (jolt-vector)) (_a$5338 gs)) (jolt-reduce _a$5336 _a$5337 _a$5338)))) (let* ((_a$5347 (var-deref "clojure.core" "__sqcat")) (_a$5348 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "let"))) (_a$5349 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqvec") outer))) (_a$5350 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$5343 (var-deref "clojure.core" "__sqcat")) (_a$5344 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "loop*"))) (_a$5345 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqvec") loopv))) (_a$5346 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$5339 (var-deref "clojure.core" "__sqcat")) (_a$5340 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "let"))) (_a$5341 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqvec") inner))) (_a$5342 body)) (jolt-invoke _a$5339 _a$5340 _a$5341 _a$5342))))) (jolt-invoke _a$5343 _a$5344 _a$5345 _a$5346))))) (jolt-invoke _a$5347 _a$5348 _a$5349 _a$5350)))))))) - (mark-macro! "clojure.core" "loop")) -(guard (e (#t #f)) - (def-var! "clojure.core" "fn" - (lambda raw (let fnrec5351 ((raw (list->cseq raw))) (let* ((nm (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "symbol?") (jolt-first raw))) (jolt-first raw) jolt-nil)) (aftn (if (jolt-truthy? nm) (jolt-next raw) raw)) (unhint (lambda (x) (let fnrec5352 ((x x)) (if (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "seq?") x)) (jolt= (jolt-symbol #f "with-meta") (jolt-first x)) #f) (jolt-nth x 1) x)))) (wrap-conds (lambda (body) (let fnrec5353 ((body body)) (if (jolt-truthy? (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "map?") (jolt-first body))) (jolt-next body) #f)) (let* ((conds (jolt-first body)) (real (jolt-next body)) (mka (lambda (cs) (let fnrec5354 ((cs cs)) (jolt-map (lambda (c) (let fnrec5355 ((c c)) (let* ((_a$5356 (var-deref "clojure.core" "__sqcat")) (_a$5357 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "assert"))) (_a$5358 (jolt-invoke (var-deref "clojure.core" "__sq1") c))) (jolt-invoke _a$5356 _a$5357 _a$5358)))) cs))))) (let* ((_a$5367 (var-deref "clojure.core" "__sqcat")) (_a$5368 (jolt-invoke mka (jolt-get conds (keyword #f "pre")))) (_a$5369 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$5362 (var-deref "clojure.core" "__sqcat")) (_a$5363 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "let"))) (_a$5364 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$5359 (var-deref "clojure.core" "__sqvec")) (_a$5360 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "%"))) (_a$5361 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqcat") (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "do")) real)))) (jolt-invoke _a$5359 _a$5360 _a$5361)))) (_a$5365 (jolt-invoke mka (jolt-get conds (keyword #f "post")))) (_a$5366 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "%")))) (jolt-invoke _a$5362 _a$5363 _a$5364 _a$5365 _a$5366))))) (jolt-invoke _a$5367 _a$5368 _a$5369))) body)))) (md (letrec ((go (lambda (ps nps lets) (let fnrec5370 ((ps ps) (nps nps) (lets lets)) (if (jolt-truthy? (jolt-seq ps)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "symbol?") (jolt-first ps))) (let* ((_a$5371 (jolt-next ps)) (_a$5372 (jolt-conj nps (jolt-first ps))) (_a$5373 lets)) (go _a$5371 _a$5372 _a$5373)) (let* ((g (jolt-invoke (var-deref "clojure.core" "symbol") (jolt-invoke (var-deref "clojure.core" "str") (jolt-invoke (var-deref "clojure.core" "gensym")))))) (let* ((_a$5374 (jolt-next ps)) (_a$5375 (jolt-conj nps g)) (_a$5376 (jolt-conj (jolt-conj lets (jolt-first ps)) g))) (go _a$5374 _a$5375 _a$5376)))) (let* ((_o$5377 nps) (_o$5378 lets)) (jolt-vector _o$5377 _o$5378))))))) go)) (mk (lambda (sig) (let fnrec5379 ((sig sig)) (let* ((ps (jolt-invoke unhint (jolt-first sig))) (hinted (jolt-not (jolt= ps (jolt-first sig)))) (r (let* ((_a$5380 md) (_a$5381 (jolt-seq ps)) (_a$5382 (jolt-vector)) (_a$5383 (jolt-vector))) (jolt-invoke _a$5380 _a$5381 _a$5382 _a$5383))) (raw-body (jolt-rest sig)) (body (jolt-invoke wrap-conds raw-body)) (conds? (jolt-not (jolt= body raw-body)))) (if (if (jolt-empty? (jolt-nth r 1)) (if (jolt-not hinted) (jolt-not conds?) #f) #f) sig (let* ((pv (jolt-invoke (var-deref "clojure.core" "__sqvec") (jolt-nth r 0))) (lv (jolt-invoke (var-deref "clojure.core" "__sqvec") (jolt-nth r 1)))) (if (jolt-empty? (jolt-nth r 1)) (jolt-invoke (var-deref "clojure.core" "__sqcat") (jolt-invoke (var-deref "clojure.core" "__sq1") pv) body) (let* ((_a$5388 (var-deref "clojure.core" "__sqcat")) (_a$5389 (jolt-invoke (var-deref "clojure.core" "__sq1") pv)) (_a$5390 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$5384 (var-deref "clojure.core" "__sqcat")) (_a$5385 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "let"))) (_a$5386 (jolt-invoke (var-deref "clojure.core" "__sq1") lv)) (_a$5387 body)) (jolt-invoke _a$5384 _a$5385 _a$5386 _a$5387))))) (jolt-invoke _a$5388 _a$5389 _a$5390)))))))))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "vector?") (jolt-invoke unhint (jolt-first aftn)))) (let* ((a (jolt-invoke mk aftn))) (if (jolt-truthy? nm) (let* ((_a$5391 (var-deref "clojure.core" "__sqcat")) (_a$5392 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "fn*"))) (_a$5393 (jolt-invoke (var-deref "clojure.core" "__sq1") nm)) (_a$5394 a)) (jolt-invoke _a$5391 _a$5392 _a$5393 _a$5394)) (jolt-invoke (var-deref "clojure.core" "__sqcat") (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "fn*")) a))) (let* ((as (jolt-invoke (var-deref "clojure.core" "vec") (jolt-map mk aftn)))) (if (jolt-truthy? nm) (let* ((_a$5395 (var-deref "clojure.core" "__sqcat")) (_a$5396 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "fn*"))) (_a$5397 (jolt-invoke (var-deref "clojure.core" "__sq1") nm)) (_a$5398 as)) (jolt-invoke _a$5395 _a$5396 _a$5397 _a$5398)) (jolt-invoke (var-deref "clojure.core" "__sqcat") (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "fn*")) as)))))))) - (mark-macro! "clojure.core" "fn")) -(guard (e (#t #f)) - (def-var! "clojure.core" "defn" - (lambda (fn-name . body) (let fnrec5399 ((fn-name fn-name) (body (list->cseq body))) (let* ((docstring (if (jolt-truthy? (let* ((and__25__auto (jolt-seq body))) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "clojure.core" "string?") (jolt-first body)) and__25__auto))) (jolt-first body) jolt-nil)) (body (if (jolt-truthy? docstring) (jolt-rest body) body)) (attr-map (if (jolt-truthy? (let* ((and__25__auto (jolt-seq body))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt-next body))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt-invoke (var-deref "clojure.core" "map?") (jolt-first body)))) (if (jolt-truthy? and__25__auto) (jolt-not (jolt-invoke (var-deref "clojure.core" "symbol?") (jolt-first body))) and__25__auto)) and__25__auto)) and__25__auto))) (jolt-first body) jolt-nil)) (body (if (jolt-truthy? attr-map) (jolt-rest body) body)) (fn-only-name (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "symbol?") fn-name)) fn-name (jolt-first (jolt-rest fn-name)))) (name-meta (jolt-invoke (var-deref "clojure.core" "meta") fn-only-name)) (m1 (if (jolt-truthy? attr-map) (if (jolt-truthy? name-meta) (jolt-conj name-meta attr-map) attr-map) name-meta)) (meta-map (if (jolt-truthy? docstring) (jolt-assoc (if (jolt-truthy? m1) m1 (jolt-hash-map)) (keyword #f "doc") docstring) m1))) (if (jolt-truthy? meta-map) (let* ((_a$5404 (var-deref "clojure.core" "__sqcat")) (_a$5405 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "def"))) (_a$5406 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "with-meta") fn-only-name meta-map))) (_a$5407 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$5400 (var-deref "clojure.core" "__sqcat")) (_a$5401 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "fn"))) (_a$5402 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "with-meta") fn-only-name jolt-nil))) (_a$5403 body)) (jolt-invoke _a$5400 _a$5401 _a$5402 _a$5403))))) (jolt-invoke _a$5404 _a$5405 _a$5406 _a$5407)) (let* ((_a$5412 (var-deref "clojure.core" "__sqcat")) (_a$5413 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "def"))) (_a$5414 (jolt-invoke (var-deref "clojure.core" "__sq1") fn-only-name)) (_a$5415 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$5408 (var-deref "clojure.core" "__sqcat")) (_a$5409 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "fn"))) (_a$5410 (jolt-invoke (var-deref "clojure.core" "__sq1") fn-only-name)) (_a$5411 body)) (jolt-invoke _a$5408 _a$5409 _a$5410 _a$5411))))) (jolt-invoke _a$5412 _a$5413 _a$5414 _a$5415))))))) - (mark-macro! "clojure.core" "defn")) -(guard (e (#t #f)) - (def-var! "clojure.core" "defn-" - (lambda (fn-name . body) (let fnrec5416 ((fn-name fn-name) (body (list->cseq body))) (let* ((_a$5417 (var-deref "clojure.core" "__sqcat")) (_a$5418 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "defn"))) (_a$5419 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "with-meta") fn-name (jolt-assoc (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "meta") fn-name)) (jolt-invoke (var-deref "clojure.core" "meta") fn-name) (jolt-hash-map)) (keyword #f "private") #t)))) (_a$5420 body)) (jolt-invoke _a$5417 _a$5418 _a$5419 _a$5420))))) - (mark-macro! "clojure.core" "defn-")) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "fresh-sym" (letrec ((fresh-sym (lambda () (let fnrec5421 () (jolt-invoke (var-deref "clojure.core" "symbol") (jolt-invoke (var-deref "clojure.core" "str") (jolt-invoke (var-deref "clojure.core" "gensym")))))))) fresh-sym) (let* ((_o$5422 (keyword #f "private")) (_o$5423 #t)) (jolt-hash-map _o$5422 _o$5423)))) -(guard (e (#t #f)) - (def-var! "clojure.core" "cond->" - (lambda (expr . clauses) (let fnrec5424 ((expr expr) (clauses (list->cseq clauses))) (let* ((step (letrec ((step (lambda (prev cls) (let fnrec5425 ((prev prev) (cls cls)) (if (jolt-empty? cls) prev (let* ((t (jolt-first cls)) (f (jolt-nth cls 1)) (gn (jolt-invoke (var-deref "clojure.core" "fresh-sym"))) (call (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "seq?") f)) (let* ((_a$5426 (var-deref "clojure.core" "__sqcat")) (_a$5427 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-first f))) (_a$5428 (jolt-invoke (var-deref "clojure.core" "__sq1") prev)) (_a$5429 (jolt-rest f))) (jolt-invoke _a$5426 _a$5427 _a$5428 _a$5429)) (let* ((_a$5430 (var-deref "clojure.core" "__sqcat")) (_a$5431 (jolt-invoke (var-deref "clojure.core" "__sq1") f)) (_a$5432 (jolt-invoke (var-deref "clojure.core" "__sq1") prev))) (jolt-invoke _a$5430 _a$5431 _a$5432))))) (let* ((_a$5441 (var-deref "clojure.core" "__sqcat")) (_a$5442 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "let*"))) (_a$5443 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$5438 (var-deref "clojure.core" "__sqvec")) (_a$5439 (jolt-invoke (var-deref "clojure.core" "__sq1") gn)) (_a$5440 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$5433 (var-deref "clojure.core" "__sqcat")) (_a$5434 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "if"))) (_a$5435 (jolt-invoke (var-deref "clojure.core" "__sq1") t)) (_a$5436 (jolt-invoke (var-deref "clojure.core" "__sq1") call)) (_a$5437 (jolt-invoke (var-deref "clojure.core" "__sq1") prev))) (jolt-invoke _a$5433 _a$5434 _a$5435 _a$5436 _a$5437))))) (jolt-invoke _a$5438 _a$5439 _a$5440)))) (_a$5444 (jolt-invoke (var-deref "clojure.core" "__sq1") (step gn (jolt-drop 2 cls))))) (jolt-invoke _a$5441 _a$5442 _a$5443 _a$5444)))))))) step)) (g0 (jolt-invoke (var-deref "clojure.core" "fresh-sym")))) (let* ((_a$5448 (var-deref "clojure.core" "__sqcat")) (_a$5449 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "let*"))) (_a$5450 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$5445 (var-deref "clojure.core" "__sqvec")) (_a$5446 (jolt-invoke (var-deref "clojure.core" "__sq1") g0)) (_a$5447 (jolt-invoke (var-deref "clojure.core" "__sq1") expr))) (jolt-invoke _a$5445 _a$5446 _a$5447)))) (_a$5451 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke step g0 clauses)))) (jolt-invoke _a$5448 _a$5449 _a$5450 _a$5451)))))) - (mark-macro! "clojure.core" "cond->")) -(guard (e (#t #f)) - (def-var! "clojure.core" "case" - (lambda (expr . clauses) (let fnrec5452 ((expr expr) (clauses (list->cseq clauses))) (let* ((g (jolt-invoke (var-deref "clojure.core" "fresh-sym"))) (mk-const (lambda (c) (let fnrec5453 ((c c)) (if (jolt-truthy? (let* ((or__26__auto (jolt-invoke (var-deref "clojure.core" "symbol?") c))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-invoke (var-deref "clojure.core" "seq?") c)))) (let* ((_a$5454 (var-deref "clojure.core" "__sqcat")) (_a$5455 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "quote"))) (_a$5456 (jolt-invoke (var-deref "clojure.core" "__sq1") c))) (jolt-invoke _a$5454 _a$5455 _a$5456)) c)))) (mk-test (lambda (c) (let fnrec5457 ((c c)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "seq?") c)) (let* ((_a$5463 (var-deref "clojure.core" "__sqcat")) (_a$5464 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "or"))) (_a$5465 (jolt-map (lambda (v) (let fnrec5458 ((v v)) (let* ((_a$5459 (var-deref "clojure.core" "__sqcat")) (_a$5460 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "="))) (_a$5461 (jolt-invoke (var-deref "clojure.core" "__sq1") g)) (_a$5462 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke mk-const v)))) (jolt-invoke _a$5459 _a$5460 _a$5461 _a$5462)))) c))) (jolt-invoke _a$5463 _a$5464 _a$5465)) (let* ((_a$5466 (var-deref "clojure.core" "__sqcat")) (_a$5467 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "="))) (_a$5468 (jolt-invoke (var-deref "clojure.core" "__sq1") g)) (_a$5469 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke mk-const c)))) (jolt-invoke _a$5466 _a$5467 _a$5468 _a$5469)))))) (collect (letrec ((collect (lambda (cls acc) (let fnrec5470 ((cls cls) (acc acc)) (if (let* ((or__26__auto (jolt-empty? cls))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-empty? (jolt-rest cls)))) acc (let* ((t (jolt-first cls)) (acc (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "seq?") t)) (jolt-reduce jolt-conj acc t) (jolt-conj acc t)))) (collect (jolt-drop 2 cls) acc))))))) collect)) (first-dup (letrec ((fd (lambda (items seen) (let fnrec5471 ((items items) (seen seen)) (if (jolt-empty? items) jolt-nil (let* ((x (jolt-first items))) (if (jolt-truthy? (jolt-reduce (lambda (f s) (let fnrec5472 ((f f) (s s)) (let* ((or__26__auto f)) (if (jolt-truthy? or__26__auto) or__26__auto (jolt= s x))))) #f seen)) (jolt-vector x) (let* ((_a$5473 (jolt-rest items)) (_a$5474 (jolt-conj seen x))) (fd _a$5473 _a$5474))))))))) fd)) (dup (let* ((_a$5475 first-dup) (_a$5476 (jolt-invoke collect clauses (jolt-vector))) (_a$5477 (jolt-vector))) (jolt-invoke _a$5475 _a$5476 _a$5477))) (build (letrec ((build (lambda (cls) (let fnrec5478 ((cls cls)) (if (jolt-empty? cls) (let* ((_a$5487 (var-deref "clojure.core" "__sqcat")) (_a$5488 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "throw"))) (_a$5489 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$5483 (var-deref "clojure.core" "__sqcat")) (_a$5484 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "ex-info"))) (_a$5485 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$5479 (var-deref "clojure.core" "__sqcat")) (_a$5480 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "str"))) (_a$5481 (jolt-invoke (var-deref "clojure.core" "__sq1") "No matching clause: ")) (_a$5482 (jolt-invoke (var-deref "clojure.core" "__sq1") g))) (jolt-invoke _a$5479 _a$5480 _a$5481 _a$5482)))) (_a$5486 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqmap"))))) (jolt-invoke _a$5483 _a$5484 _a$5485 _a$5486))))) (jolt-invoke _a$5487 _a$5488 _a$5489)) (if (jolt-empty? (jolt-rest cls)) (jolt-first cls) (let* ((_a$5490 (var-deref "clojure.core" "__sqcat")) (_a$5491 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "if"))) (_a$5492 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke mk-test (jolt-first cls)))) (_a$5493 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-nth cls 1))) (_a$5494 (jolt-invoke (var-deref "clojure.core" "__sq1") (build (jolt-drop 2 cls))))) (jolt-invoke _a$5490 _a$5491 _a$5492 _a$5493 _a$5494)))))))) build))) (if (jolt-truthy? dup) (jolt-throw (jolt-invoke (var-deref "clojure.core" "str") "Duplicate case test constant: " (jolt-first dup))) (let* ((_a$5498 (var-deref "clojure.core" "__sqcat")) (_a$5499 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "let*"))) (_a$5500 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$5495 (var-deref "clojure.core" "__sqvec")) (_a$5496 (jolt-invoke (var-deref "clojure.core" "__sq1") g)) (_a$5497 (jolt-invoke (var-deref "clojure.core" "__sq1") expr))) (jolt-invoke _a$5495 _a$5496 _a$5497)))) (_a$5501 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke build clauses)))) (jolt-invoke _a$5498 _a$5499 _a$5500 _a$5501))))))) - (mark-macro! "clojure.core" "case")) -(guard (e (#t #f)) - (def-var! "clojure.core" "for" - (lambda (bindings body) (let fnrec5502 ((bindings bindings) (body body)) (let* ((scan (letrec ((scan (lambda (bvec i bind coll mods) (let fnrec5503 ((bvec bvec) (i i) (bind bind) (coll coll) (mods mods)) (if (jolt-truthy? (let* ((and__25__auto (jolt-n< i (jolt-count bvec)))) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "clojure.core" "keyword?") (jolt-nth bvec i)) and__25__auto))) (let* ((k (jolt-nth bvec i)) (v (jolt-nth bvec (jolt-inc i)))) (if (jolt= k (keyword #f "when")) (let* ((_a$5506 bvec) (_a$5507 (jolt-n+ i 2)) (_a$5508 bind) (_a$5509 coll) (_a$5510 (jolt-conj mods (let* ((_o$5504 (keyword #f "when")) (_o$5505 v)) (jolt-vector _o$5504 _o$5505))))) (scan _a$5506 _a$5507 _a$5508 _a$5509 _a$5510)) (if (jolt= k (keyword #f "let")) (let* ((_a$5513 bvec) (_a$5514 (jolt-n+ i 2)) (_a$5515 bind) (_a$5516 coll) (_a$5517 (jolt-conj mods (let* ((_o$5511 (keyword #f "let")) (_o$5512 v)) (jolt-vector _o$5511 _o$5512))))) (scan _a$5513 _a$5514 _a$5515 _a$5516 _a$5517)) (if (jolt= k (keyword #f "while")) (let* ((_a$5526 bvec) (_a$5527 (jolt-n+ i 2)) (_a$5528 bind) (_a$5529 (let* ((_a$5522 (var-deref "clojure.core" "__sqcat")) (_a$5523 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "take-while"))) (_a$5524 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$5518 (var-deref "clojure.core" "__sqcat")) (_a$5519 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "fn"))) (_a$5520 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqvec") (jolt-invoke (var-deref "clojure.core" "__sq1") bind)))) (_a$5521 (jolt-invoke (var-deref "clojure.core" "__sq1") v))) (jolt-invoke _a$5518 _a$5519 _a$5520 _a$5521)))) (_a$5525 (jolt-invoke (var-deref "clojure.core" "__sq1") coll))) (jolt-invoke _a$5522 _a$5523 _a$5524 _a$5525))) (_a$5530 mods)) (scan _a$5526 _a$5527 _a$5528 _a$5529 _a$5530)) (if (jolt-truthy? (keyword #f "else")) (scan bvec (jolt-inc i) bind coll mods) jolt-nil))))) (let* ((_o$5531 i) (_o$5532 bind) (_o$5533 coll) (_o$5534 mods)) (jolt-vector _o$5531 _o$5532 _o$5533 _o$5534))))))) scan)) (parse-groups (letrec ((parse-groups (lambda (bvec i groups) (let fnrec5535 ((bvec bvec) (i i) (groups groups)) (if (jolt-n>= i (jolt-count bvec)) groups (let* ((r (let* ((_a$5536 scan) (_a$5537 bvec) (_a$5538 (jolt-n+ i 2)) (_a$5539 (jolt-nth bvec i)) (_a$5540 (jolt-nth bvec (jolt-inc i))) (_a$5541 (jolt-vector))) (jolt-invoke _a$5536 _a$5537 _a$5538 _a$5539 _a$5540 _a$5541)))) (let* ((_a$5545 bvec) (_a$5546 (jolt-nth r 0)) (_a$5547 (jolt-conj groups (let* ((_o$5542 (jolt-nth r 1)) (_o$5543 (jolt-nth r 2)) (_o$5544 (jolt-nth r 3))) (jolt-vector _o$5542 _o$5543 _o$5544))))) (parse-groups _a$5545 _a$5546 _a$5547)))))))) parse-groups)) (wrap-mods (letrec ((wrap-mods (lambda (mods inner) (let fnrec5548 ((mods mods) (inner inner)) (if (jolt-empty? mods) inner (let* ((m (jolt-first mods)) (sub (wrap-mods (jolt-rest mods) inner))) (if (jolt= (jolt-first m) (keyword #f "when")) (let* ((_a$5549 (var-deref "clojure.core" "__sqcat")) (_a$5550 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "if"))) (_a$5551 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-nth m 1))) (_a$5552 (jolt-invoke (var-deref "clojure.core" "__sq1") sub)) (_a$5553 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqvec"))))) (jolt-invoke _a$5549 _a$5550 _a$5551 _a$5552 _a$5553)) (let* ((_a$5554 (var-deref "clojure.core" "__sqcat")) (_a$5555 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "let"))) (_a$5556 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-nth m 1))) (_a$5557 (jolt-invoke (var-deref "clojure.core" "__sq1") sub))) (jolt-invoke _a$5554 _a$5555 _a$5556 _a$5557))))))))) wrap-mods)) (build (letrec ((build (lambda (idx groups) (let fnrec5558 ((idx idx) (groups groups)) (let* ((g (jolt-nth groups idx)) (my-bind (jolt-nth g 0)) (my-coll (jolt-nth g 1)) (my-mods (jolt-nth g 2)) (is-last (jolt= idx (jolt-dec (jolt-count groups))))) (if (jolt-truthy? (let* ((and__25__auto is-last)) (if (jolt-truthy? and__25__auto) (jolt-empty? my-mods) and__25__auto))) (let* ((_a$5563 (var-deref "clojure.core" "__sqcat")) (_a$5564 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "map"))) (_a$5565 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$5559 (var-deref "clojure.core" "__sqcat")) (_a$5560 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "fn"))) (_a$5561 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqvec") (jolt-invoke (var-deref "clojure.core" "__sq1") my-bind)))) (_a$5562 (jolt-invoke (var-deref "clojure.core" "__sq1") body))) (jolt-invoke _a$5559 _a$5560 _a$5561 _a$5562)))) (_a$5566 (jolt-invoke (var-deref "clojure.core" "__sq1") my-coll))) (jolt-invoke _a$5563 _a$5564 _a$5565 _a$5566)) (let* ((base (if (jolt-truthy? is-last) (let* ((_a$5567 (var-deref "clojure.core" "__sqcat")) (_a$5568 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "list"))) (_a$5569 (jolt-invoke (var-deref "clojure.core" "__sq1") body))) (jolt-invoke _a$5567 _a$5568 _a$5569)) (build (jolt-inc idx) groups)))) (let* ((_a$5574 (var-deref "clojure.core" "__sqcat")) (_a$5575 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "mapcat"))) (_a$5576 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$5570 (var-deref "clojure.core" "__sqcat")) (_a$5571 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "fn"))) (_a$5572 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqvec") (jolt-invoke (var-deref "clojure.core" "__sq1") my-bind)))) (_a$5573 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke wrap-mods my-mods base)))) (jolt-invoke _a$5570 _a$5571 _a$5572 _a$5573)))) (_a$5577 (jolt-invoke (var-deref "clojure.core" "__sq1") my-coll))) (jolt-invoke _a$5574 _a$5575 _a$5576 _a$5577))))))))) build))) (if (jolt-n>= (jolt-count bindings) 2) (jolt-invoke build 0 (jolt-invoke parse-groups bindings 0 (jolt-vector))) body))))) - (mark-macro! "clojure.core" "for")) -(guard (e (#t #f)) - (def-var! "clojure.core" "doseq" - (lambda (bindings . body) (let fnrec5578 ((bindings bindings) (body (list->cseq body))) (let* ((_a$5590 (var-deref "clojure.core" "__sqcat")) (_a$5591 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "do"))) (_a$5592 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$5587 (var-deref "clojure.core" "__sqcat")) (_a$5588 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "count"))) (_a$5589 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$5583 (var-deref "clojure.core" "__sqcat")) (_a$5584 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "for"))) (_a$5585 (jolt-invoke (var-deref "clojure.core" "__sq1") bindings)) (_a$5586 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$5579 (var-deref "clojure.core" "__sqcat")) (_a$5580 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "do"))) (_a$5581 body) (_a$5582 (jolt-invoke (var-deref "clojure.core" "__sq1") jolt-nil))) (jolt-invoke _a$5579 _a$5580 _a$5581 _a$5582))))) (jolt-invoke _a$5583 _a$5584 _a$5585 _a$5586))))) (jolt-invoke _a$5587 _a$5588 _a$5589)))) (_a$5593 (jolt-invoke (var-deref "clojure.core" "__sq1") jolt-nil))) (jolt-invoke _a$5590 _a$5591 _a$5592 _a$5593))))) - (mark-macro! "clojure.core" "doseq")) -(guard (e (#t #f)) - (def-var! "clojure.core" "when-let" - (lambda (bindings . body) (let fnrec5594 ((bindings bindings) (body (list->cseq body))) (begin (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "not=") 2 (jolt-count bindings))) (jolt-throw (host-new "IllegalArgumentException" "when-let requires exactly 2 forms in binding vector")) jolt-nil) (let* ((form (jolt-invoke bindings 0)) (tst (jolt-invoke bindings 1))) (let* ((_a$5610 (var-deref "clojure.core" "__sqcat")) (_a$5611 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "let"))) (_a$5612 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$5595 (var-deref "clojure.core" "__sqvec")) (_a$5596 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "temp__27__auto"))) (_a$5597 (jolt-invoke (var-deref "clojure.core" "__sq1") tst))) (jolt-invoke _a$5595 _a$5596 _a$5597)))) (_a$5613 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$5605 (var-deref "clojure.core" "__sqcat")) (_a$5606 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "if"))) (_a$5607 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "temp__27__auto"))) (_a$5608 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$5601 (var-deref "clojure.core" "__sqcat")) (_a$5602 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "let"))) (_a$5603 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$5598 (var-deref "clojure.core" "__sqvec")) (_a$5599 (jolt-invoke (var-deref "clojure.core" "__sq1") form)) (_a$5600 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "temp__27__auto")))) (jolt-invoke _a$5598 _a$5599 _a$5600)))) (_a$5604 body)) (jolt-invoke _a$5601 _a$5602 _a$5603 _a$5604)))) (_a$5609 (jolt-invoke (var-deref "clojure.core" "__sq1") jolt-nil))) (jolt-invoke _a$5605 _a$5606 _a$5607 _a$5608 _a$5609))))) (jolt-invoke _a$5610 _a$5611 _a$5612 _a$5613))))))) - (mark-macro! "clojure.core" "when-let")) -(guard (e (#t #f)) - (def-var! "clojure.core" "lazy-seq" - (lambda body (let fnrec5614 ((body (list->cseq body))) (let* ((_a$5622 (var-deref "clojure.core" "__sqcat")) (_a$5623 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "make-lazy-seq"))) (_a$5624 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$5618 (var-deref "clojure.core" "__sqcat")) (_a$5619 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "fn*"))) (_a$5620 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqvec")))) (_a$5621 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$5615 (var-deref "clojure.core" "__sqcat")) (_a$5616 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "coll->cells"))) (_a$5617 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqcat") (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "do")) body)))) (jolt-invoke _a$5615 _a$5616 _a$5617))))) (jolt-invoke _a$5618 _a$5619 _a$5620 _a$5621))))) (jolt-invoke _a$5622 _a$5623 _a$5624))))) - (mark-macro! "clojure.core" "lazy-seq")) -(guard (e (#t #f)) - (def-var! "clojure.core" "lazy-cat" - (lambda colls (let fnrec5625 ((colls (list->cseq colls))) (let* ((_a$5630 (var-deref "clojure.core" "__sqcat")) (_a$5631 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "concat"))) (_a$5632 (jolt-map (lambda (c) (let fnrec5626 ((c c)) (let* ((_a$5627 (var-deref "clojure.core" "__sqcat")) (_a$5628 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "lazy-seq"))) (_a$5629 (jolt-invoke (var-deref "clojure.core" "__sq1") c))) (jolt-invoke _a$5627 _a$5628 _a$5629)))) colls))) (jolt-invoke _a$5630 _a$5631 _a$5632))))) - (mark-macro! "clojure.core" "lazy-cat")) -(guard (e (#t #f)) - (def-var! "clojure.core" "not=" (letrec ((not= (case-lambda ((x) (let fnrec5633 ((x x)) #f)) ((x y) (let fnrec5634 ((x x) (y y)) (jolt-not (jolt= x y)))) ((x y . more) (let fnrec5635 ((x x) (y y) (more (list->cseq more))) (jolt-not (jolt-apply jolt= x y more))))))) not=))) -(guard (e (#t #f)) - (def-var! "clojure.core" "unreduced" (letrec ((unreduced (lambda (x) (let fnrec5636 ((x x)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "reduced?") x)) (jolt-invoke (var-deref "clojure.core" "deref") x) x))))) unreduced))) -(guard (e (#t #f)) - (def-var! "clojure.core" "second" (letrec ((second (lambda (coll) (let fnrec5637 ((coll coll)) (jolt-first (jolt-next coll)))))) second))) -(guard (e (#t #f)) - (def-var! "clojure.core" "peek" (letrec ((peek (lambda (coll) (let fnrec5638 ((coll coll)) (if (jolt-nil? coll) jolt-nil (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "vector?") coll)) (if (jolt-zero? (jolt-count coll)) jolt-nil (jolt-nth coll (jolt-dec (jolt-count coll)))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "seq?") coll)) (jolt-first coll) (if (jolt-truthy? (keyword #f "else")) (jolt-throw (jolt-invoke (var-deref "clojure.core" "str") "peek not supported on: " coll)) jolt-nil)))))))) peek))) -(guard (e (#t #f)) - (def-var! "clojure.core" "subvec" (letrec ((subvec (case-lambda ((v start) (let fnrec5639 ((v v) (start start)) (subvec v start (jolt-count v)))) ((v start end) (let fnrec5640 ((v v) (start start) (end end)) (begin (if (jolt-not (jolt-invoke (var-deref "clojure.core" "vector?") v)) (jolt-throw (jolt-invoke (var-deref "clojure.core" "str") "subvec requires a vector")) jolt-nil) (let* ((coerce (lambda (x) (let fnrec5641 ((x x)) (if (jolt-not (jolt-invoke (var-deref "clojure.core" "number?") x)) (jolt-throw (jolt-invoke (var-deref "clojure.core" "str") "subvec index must be a number")) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "not=") x x)) 0 (if (jolt-truthy? (keyword #f "else")) (jolt-invoke (var-deref "clojure.core" "long") x) jolt-nil)))))) (s (jolt-invoke coerce start)) (e (jolt-invoke coerce end))) (begin (if (let* ((or__26__auto (jolt-n< s 0))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt-n< e s))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-n< (jolt-count v) e))))) (jolt-throw (jolt-invoke (var-deref "clojure.core" "str") "subvec index out of range: " s " " e)) jolt-nil) (let* ((i s) (acc (jolt-vector))) (let loop5642 ((i i) (acc acc)) (if (jolt-n< i e) (let* ((_a$5643 (jolt-inc i)) (_a$5644 (jolt-conj acc (jolt-nth v i)))) (loop5642 _a$5643 _a$5644)) acc))))))))))) subvec))) -(guard (e (#t #f)) - (def-var! "clojure.core" "mapv" (letrec ((mapv (lambda (f . colls) (let fnrec5645 ((f f) (colls (list->cseq colls))) (jolt-invoke (var-deref "clojure.core" "vec") (jolt-apply jolt-map f colls)))))) mapv))) -(guard (e (#t #f)) - (def-var! "clojure.core" "update" (letrec ((update (lambda (m k f . args) (let fnrec5646 ((m m) (k k) (f f) (args (list->cseq args))) (jolt-assoc m k (jolt-apply f (jolt-get m k) args)))))) update))) -(guard (e (#t #f)) - (def-var! "clojure.core" "set" (letrec ((set (lambda (coll) (let fnrec5647 ((coll coll)) (if (jolt-nil? coll) (jolt-hash-set) (jolt-apply jolt-hash-set (jolt-seq coll))))))) set))) -(guard (e (#t #f)) - (def-var! "clojure.core" "vreset!" (letrec ((vreset! (lambda (vol newval) (let fnrec4727 ((vol vol) (newval newval)) (begin (jolt-invoke (var-deref "jolt.host" "ref-put!") vol (keyword #f "val") newval) newval))))) vreset!))) -(guard (e (#t #f)) - (def-var! "clojure.core" "vswap!" (letrec ((vswap! (lambda (vol f . args) (let fnrec4728 ((vol vol) (f f) (args (list->cseq args))) (jolt-invoke (var-deref "clojure.core" "vreset!") vol (jolt-apply f (jolt-get vol (keyword #f "val")) args)))))) vswap!))) -(guard (e (#t #f)) - (def-var! "clojure.core" "ffirst" (letrec ((ffirst (lambda (coll) (let fnrec4729 ((coll coll)) (jolt-first (jolt-first coll)))))) ffirst))) -(guard (e (#t #f)) - (def-var! "clojure.core" "nfirst" (letrec ((nfirst (lambda (coll) (let fnrec4730 ((coll coll)) (jolt-next (jolt-first coll)))))) nfirst))) -(guard (e (#t #f)) - (def-var! "clojure.core" "fnext" (letrec ((fnext (lambda (coll) (let fnrec4731 ((coll coll)) (jolt-first (jolt-next coll)))))) fnext))) -(guard (e (#t #f)) - (def-var! "clojure.core" "nnext" (letrec ((nnext (lambda (coll) (let fnrec4732 ((coll coll)) (jolt-next (jolt-next coll)))))) nnext))) -(guard (e (#t #f)) - (def-var! "clojure.core" "last" (letrec ((last (lambda (s) (let fnrec4733 ((s s)) (if (jolt-truthy? (jolt-next s)) (fnrec4733 (jolt-next s)) (jolt-first s)))))) last))) -(guard (e (#t #f)) - (def-var! "clojure.core" "butlast" (letrec ((butlast (lambda (s) (let fnrec4734 ((s s)) (let* ((ret (jolt-vector)) (s s)) (let loop4735 ((ret ret) (s s)) (if (jolt-truthy? (jolt-next s)) (let* ((_a$4736 (jolt-conj ret (jolt-first s))) (_a$4737 (jolt-next s))) (loop4735 _a$4736 _a$4737)) (jolt-seq ret)))))))) butlast))) -(guard (e (#t #f)) - (def-var! "clojure.core" "partition-by" (letrec ((partition-by (case-lambda ((f) (let fnrec4738 ((f f)) (lambda (rf) (let fnrec4739 ((rf rf)) (let* ((buf (jolt-invoke (var-deref "clojure.core" "volatile!") (jolt-vector))) (pv (jolt-invoke (var-deref "clojure.core" "volatile!") jolt-nil)) (started (jolt-invoke (var-deref "clojure.core" "volatile!") #f))) (case-lambda (() (let fnrec4740 () (jolt-invoke rf))) ((result) (let fnrec4741 ((result result)) (let* ((b (jolt-invoke (var-deref "clojure.core" "deref") buf)) (result (if (jolt-zero? (jolt-count b)) result (begin (jolt-invoke (var-deref "clojure.core" "vreset!") buf (jolt-vector)) (jolt-invoke (var-deref "clojure.core" "unreduced") (jolt-invoke rf result b)))))) (jolt-invoke rf result)))) ((result input) (let fnrec4742 ((result result) (input input)) (let* ((val (jolt-invoke f input))) (if (let* ((or__26__auto (jolt-not (jolt-invoke (var-deref "clojure.core" "deref") started)))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt= val (jolt-invoke (var-deref "clojure.core" "deref") pv)))) (begin (jolt-invoke (var-deref "clojure.core" "vreset!") started #t) (jolt-invoke (var-deref "clojure.core" "vreset!") pv val) (jolt-invoke (var-deref "clojure.core" "vswap!") buf jolt-conj input) result) (let* ((b (jolt-invoke (var-deref "clojure.core" "deref") buf))) (begin (jolt-invoke (var-deref "clojure.core" "vreset!") buf (jolt-vector)) (jolt-invoke (var-deref "clojure.core" "vreset!") pv val) (let* ((ret (jolt-invoke rf result b))) (begin (if (jolt-not (jolt-invoke (var-deref "clojure.core" "reduced?") ret)) (jolt-invoke (var-deref "clojure.core" "vswap!") buf jolt-conj input) jolt-nil) ret)))))))))))))) ((f coll) (let fnrec4743 ((f f) (coll coll)) (let* ((step (letrec ((step (lambda (s) (let fnrec4744 ((s s)) (jolt-invoke (var-deref "clojure.core" "make-lazy-seq") (lambda () (let fnrec4745 () (jolt-invoke (var-deref "clojure.core" "coll->cells") (let* ((s (jolt-seq s))) (if (jolt-truthy? s) (let* ((fst (jolt-first s)) (fv (jolt-invoke f fst)) (run (jolt-cons fst (let* ((_a$4747 (var-deref "clojure.core" "take-while")) (_a$4748 (lambda (x) (let fnrec4746 ((x x)) (jolt= fv (jolt-invoke f x))))) (_a$4749 (jolt-rest s))) (jolt-invoke _a$4747 _a$4748 _a$4749))))) (jolt-cons run (step (jolt-invoke (var-deref "clojure.core" "make-lazy-seq") (lambda () (let fnrec4750 () (jolt-invoke (var-deref "clojure.core" "coll->cells") (jolt-drop (jolt-count run) s)))))))) jolt-nil)))))))))) step))) (jolt-invoke step coll))))))) partition-by))) -(guard (e (#t #f)) - (def-var! "clojure.core" "some?" (letrec ((some? (lambda (x) (let fnrec4751 ((x x)) (jolt-not (jolt-nil? x)))))) some?))) -(guard (e (#t #f)) - (def-var! "clojure.core" "identity" (letrec ((identity (lambda (x) (let fnrec4752 ((x x)) x)))) identity))) -(guard (e (#t #f)) - (def-var! "clojure.core" "constantly" (letrec ((constantly (lambda (x) (let fnrec4753 ((x x)) (lambda args (let fnrec4754 ((args (list->cseq args))) x)))))) constantly))) -(guard (e (#t #f)) - (def-var! "clojure.core" "neg?" (letrec ((neg? (lambda (x) (let fnrec4755 ((x x)) (jolt-n< x 0))))) neg?))) -(guard (e (#t #f)) - (def-var! "clojure.core" "bit-and" (letrec ((bit-and (case-lambda ((x y) (let fnrec4756 ((x x) (y y)) (jolt-invoke (var-deref "clojure.core" "__bit-and") x y))) ((x y . more) (let fnrec4757 ((x x) (y y) (more (list->cseq more))) (jolt-reduce (var-deref "clojure.core" "__bit-and") (jolt-invoke (var-deref "clojure.core" "__bit-and") x y) more)))))) bit-and))) -(guard (e (#t #f)) - (def-var! "clojure.core" "bit-or" (letrec ((bit-or (case-lambda ((x y) (let fnrec4758 ((x x) (y y)) (jolt-invoke (var-deref "clojure.core" "__bit-or") x y))) ((x y . more) (let fnrec4759 ((x x) (y y) (more (list->cseq more))) (jolt-reduce (var-deref "clojure.core" "__bit-or") (jolt-invoke (var-deref "clojure.core" "__bit-or") x y) more)))))) bit-or))) -(guard (e (#t #f)) - (def-var! "clojure.core" "bit-xor" (letrec ((bit-xor (case-lambda ((x y) (let fnrec4760 ((x x) (y y)) (jolt-invoke (var-deref "clojure.core" "__bit-xor") x y))) ((x y . more) (let fnrec4761 ((x x) (y y) (more (list->cseq more))) (jolt-reduce (var-deref "clojure.core" "__bit-xor") (jolt-invoke (var-deref "clojure.core" "__bit-xor") x y) more)))))) bit-xor))) -(guard (e (#t #f)) - (def-var! "clojure.core" "bit-and-not" (letrec ((bit-and-not (case-lambda ((x y) (let fnrec4762 ((x x) (y y)) (jolt-invoke (var-deref "clojure.core" "__bit-and-not") x y))) ((x y . more) (let fnrec4763 ((x x) (y y) (more (list->cseq more))) (jolt-reduce (var-deref "clojure.core" "__bit-and-not") (jolt-invoke (var-deref "clojure.core" "__bit-and-not") x y) more)))))) bit-and-not))) -(guard (e (#t #f)) - (def-var! "clojure.core" "pr-str" (letrec ((pr-str (lambda xs (let fnrec4764 ((xs (list->cseq xs))) (let* ((out "") (s (jolt-seq xs)) (first? #t)) (let loop4765 ((out out) (s s) (first? first?)) (if (jolt-truthy? s) (let* ((_a$4770 (let* ((_a$4766 (var-deref "clojure.core" "str")) (_a$4767 out) (_a$4768 (if (jolt-truthy? first?) "" " ")) (_a$4769 (jolt-invoke (var-deref "clojure.core" "__pr-str1") (jolt-first s)))) (jolt-invoke _a$4766 _a$4767 _a$4768 _a$4769))) (_a$4771 (jolt-next s)) (_a$4772 #f)) (loop4765 _a$4770 _a$4771 _a$4772)) out))))))) pr-str))) -(guard (e (#t #f)) - (def-var! "clojure.core" "pr" (letrec ((pr (lambda xs (let fnrec4773 ((xs (list->cseq xs))) (begin (jolt-invoke (var-deref "clojure.core" "__write") (jolt-apply (var-deref "clojure.core" "pr-str") xs)) jolt-nil))))) pr))) -(guard (e (#t #f)) - (def-var! "clojure.core" "prn" (letrec ((prn (lambda xs (let fnrec4774 ((xs (list->cseq xs))) (begin (jolt-apply (var-deref "clojure.core" "pr") xs) (jolt-invoke (var-deref "clojure.core" "__write") "\n") jolt-nil))))) prn))) -(guard (e (#t #f)) - (def-var! "clojure.core" "print" (letrec ((print (lambda xs (let fnrec4775 ((xs (list->cseq xs))) (begin (jolt-invoke (var-deref "clojure.core" "__write") (let* ((out "") (s (jolt-seq xs)) (first? #t)) (let loop4776 ((out out) (s s) (first? first?)) (if (jolt-truthy? s) (let* ((x (jolt-first s)) (r (jolt-invoke (var-deref "clojure.core" "__print1") x))) (let* ((_a$4777 (jolt-invoke (var-deref "clojure.core" "str") out (if (jolt-truthy? first?) "" " ") r)) (_a$4778 (jolt-next s)) (_a$4779 #f)) (loop4776 _a$4777 _a$4778 _a$4779))) out)))) jolt-nil))))) print))) -(guard (e (#t #f)) - (def-var! "clojure.core" "println" (letrec ((println (lambda xs (let fnrec4780 ((xs (list->cseq xs))) (begin (jolt-apply (var-deref "clojure.core" "print") xs) (jolt-invoke (var-deref "clojure.core" "__write") "\n") jolt-nil))))) println))) -(guard (e (#t #f)) - (def-var! "clojure.core" "frequencies" (letrec ((frequencies (lambda (coll) (let fnrec4781 ((coll coll)) (jolt-invoke (var-deref "clojure.core" "persistent!") (let* ((_a$4783 (lambda (counts x) (let fnrec4782 ((counts counts) (x x)) (jolt-invoke (var-deref "clojure.core" "assoc!") counts x (jolt-inc (jolt-get counts x 0)))))) (_a$4784 (jolt-invoke (var-deref "clojure.core" "transient") (jolt-hash-map))) (_a$4785 coll)) (jolt-reduce _a$4783 _a$4784 _a$4785))))))) frequencies))) -(guard (e (#t #f)) - (def-var! "clojure.core" "group-by" (letrec ((group-by (lambda (f coll) (let fnrec4786 ((f f) (coll coll)) (let* ((tm (jolt-invoke (var-deref "clojure.core" "transient") (jolt-hash-map))) (ks (let* ((_a$4788 (lambda (ks x) (let fnrec4787 ((ks ks) (x x)) (let* ((k (jolt-invoke f x)) (b (jolt-get tm k))) (if (jolt-nil? b) (begin (jolt-invoke (var-deref "clojure.core" "assoc!") tm k (jolt-vector x)) (jolt-invoke (var-deref "clojure.core" "conj!") ks k)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "vector?") b)) (begin (jolt-invoke (var-deref "clojure.core" "assoc!") tm k (jolt-invoke (var-deref "clojure.core" "conj!") (jolt-invoke (var-deref "clojure.core" "transient") b) x)) ks) (begin (jolt-invoke (var-deref "clojure.core" "conj!") b x) ks))))))) (_a$4789 (jolt-invoke (var-deref "clojure.core" "transient") (jolt-vector))) (_a$4790 coll)) (jolt-reduce _a$4788 _a$4789 _a$4790)))) (begin (let* ((_a$4792 (lambda (_ k) (let fnrec4791 ((_ _) (k k)) (let* ((b (jolt-get tm k))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "vector?") b)) jolt-nil (jolt-invoke (var-deref "clojure.core" "assoc!") tm k (jolt-invoke (var-deref "clojure.core" "persistent!") b))))))) (_a$4793 jolt-nil) (_a$4794 (jolt-invoke (var-deref "clojure.core" "persistent!") ks))) (jolt-reduce _a$4792 _a$4793 _a$4794)) (jolt-invoke (var-deref "clojure.core" "persistent!") tm))))))) group-by))) -(guard (e (#t #f)) - (def-var! "clojure.core" "not-empty" (letrec ((not-empty (lambda (coll) (let fnrec4795 ((coll coll)) (if (let* ((or__26__auto (jolt-nil? coll))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-zero? (jolt-count coll)))) jolt-nil coll))))) not-empty))) -(guard (e (#t #f)) - (def-var! "clojure.core" "filterv" (letrec ((filterv (lambda (pred coll) (let fnrec4796 ((pred pred) (coll coll)) (jolt-invoke (var-deref "clojure.core" "vec") (jolt-filter pred coll)))))) filterv))) -(guard (e (#t #f)) - (def-var! "clojure.core" "max-key" (letrec ((max-key (case-lambda ((k x) (let fnrec4797 ((k k) (x x)) x)) ((k x y) (let fnrec4798 ((k k) (x x) (y y)) (if (let* ((_a$4799 (jolt-invoke k x)) (_a$4800 (jolt-invoke k y))) (jolt-n> _a$4799 _a$4800)) x y))) ((k x y . more) (let fnrec4801 ((k k) (x x) (y y) (more (list->cseq more))) (let* ((kx (jolt-invoke k x)) (ky (jolt-invoke k y)) (v (if (jolt-n> kx ky) x y)) (kv (if (jolt-n> kx ky) kx ky))) (let* ((v v) (kv kv) (more more)) (let loop4802 ((v v) (kv kv) (more more)) (if (jolt-truthy? (jolt-seq more)) (let* ((w (jolt-first more)) (kw (jolt-invoke k w))) (if (jolt-n>= kw kv) (loop4802 w kw (jolt-next more)) (loop4802 v kv (jolt-next more)))) v))))))))) max-key))) -(guard (e (#t #f)) - (def-var! "clojure.core" "min-key" (letrec ((min-key (case-lambda ((k x) (let fnrec4803 ((k k) (x x)) x)) ((k x y) (let fnrec4804 ((k k) (x x) (y y)) (if (let* ((_a$4805 (jolt-invoke k x)) (_a$4806 (jolt-invoke k y))) (jolt-n< _a$4805 _a$4806)) x y))) ((k x y . more) (let fnrec4807 ((k k) (x x) (y y) (more (list->cseq more))) (let* ((kx (jolt-invoke k x)) (ky (jolt-invoke k y)) (v (if (jolt-n< kx ky) x y)) (kv (if (jolt-n< kx ky) kx ky))) (let* ((v v) (kv kv) (more more)) (let loop4808 ((v v) (kv kv) (more more)) (if (jolt-truthy? (jolt-seq more)) (let* ((w (jolt-first more)) (kw (jolt-invoke k w))) (if (jolt-n<= kw kv) (loop4808 w kw (jolt-next more)) (loop4808 v kv (jolt-next more)))) v))))))))) min-key))) -(guard (e (#t #f)) - (def-var! "clojure.core" "juxt" (letrec ((juxt (lambda fs (let fnrec4809 ((fs (list->cseq fs))) (lambda args (let fnrec4810 ((args (list->cseq args))) (jolt-invoke (var-deref "clojure.core" "mapv") (lambda (f) (let fnrec4811 ((f f)) (jolt-apply f args))) fs))))))) juxt))) -(guard (e (#t #f)) - (def-var! "clojure.core" "every-pred" (letrec ((every-pred (lambda preds (let fnrec4812 ((preds (list->cseq preds))) (lambda xs (let fnrec4813 ((xs (list->cseq xs))) (jolt-invoke (var-deref "clojure.core" "every?") (lambda (p) (let fnrec4814 ((p p)) (jolt-invoke (var-deref "clojure.core" "every?") p xs))) preds))))))) every-pred))) -(guard (e (#t #f)) - (def-var! "clojure.core" "some" (letrec ((some (lambda (pred coll) (let fnrec4815 ((pred pred) (coll coll)) (let* ((temp__27__auto (jolt-seq coll))) (if (jolt-truthy? temp__27__auto) (let* ((s temp__27__auto)) (let* ((or__26__auto (jolt-invoke pred (jolt-first s)))) (if (jolt-truthy? or__26__auto) or__26__auto (fnrec4815 pred (jolt-next s))))) jolt-nil)))))) some))) -(guard (e (#t #f)) - (def-var! "clojure.core" "some-fn" (letrec ((some-fn (case-lambda ((p) (let fnrec4816 ((p p)) (letrec ((sp1 (case-lambda (() (let fnrec4817 () jolt-nil)) ((x) (let fnrec4818 ((x x)) (jolt-invoke p x))) ((x y) (let fnrec4819 ((x x) (y y)) (let* ((or__26__auto (jolt-invoke p x))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-invoke p y))))) ((x y z) (let fnrec4820 ((x x) (y y) (z z)) (let* ((or__26__auto (jolt-invoke p x))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt-invoke p y))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-invoke p z))))))) ((x y z . args) (let fnrec4821 ((x x) (y y) (z z) (args (list->cseq args))) (let* ((or__26__auto (sp1 x y z))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-invoke (var-deref "clojure.core" "some") p args)))))))) sp1))) ((p1 p2) (let fnrec4822 ((p1 p1) (p2 p2)) (letrec ((sp2 (case-lambda (() (let fnrec4823 () jolt-nil)) ((x) (let fnrec4824 ((x x)) (let* ((or__26__auto (jolt-invoke p1 x))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-invoke p2 x))))) ((x y) (let fnrec4825 ((x x) (y y)) (let* ((or__26__auto (jolt-invoke p1 x))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt-invoke p1 y))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt-invoke p2 x))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-invoke p2 y))))))))) ((x y z) (let fnrec4826 ((x x) (y y) (z z)) (let* ((or__26__auto (jolt-invoke p1 x))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt-invoke p1 y))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt-invoke p1 z))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt-invoke p2 x))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt-invoke p2 y))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-invoke p2 z))))))))))))) ((x y z . args) (let fnrec4827 ((x x) (y y) (z z) (args (list->cseq args))) (let* ((or__26__auto (sp2 x y z))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-invoke (var-deref "clojure.core" "some") (lambda (q) (let fnrec4828 ((q q)) (let* ((or__26__auto (jolt-invoke p1 q))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-invoke p2 q))))) args)))))))) sp2))) ((p1 p2 p3) (let fnrec4829 ((p1 p1) (p2 p2) (p3 p3)) (letrec ((sp3 (case-lambda (() (let fnrec4830 () jolt-nil)) ((x) (let fnrec4831 ((x x)) (let* ((or__26__auto (jolt-invoke p1 x))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt-invoke p2 x))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-invoke p3 x))))))) ((x y) (let fnrec4832 ((x x) (y y)) (let* ((or__26__auto (jolt-invoke p1 x))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt-invoke p2 x))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt-invoke p3 x))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt-invoke p1 y))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt-invoke p2 y))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-invoke p3 y))))))))))))) ((x y z) (let fnrec4833 ((x x) (y y) (z z)) (let* ((or__26__auto (jolt-invoke p1 x))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt-invoke p2 x))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt-invoke p3 x))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt-invoke p1 y))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt-invoke p2 y))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt-invoke p3 y))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt-invoke p1 z))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt-invoke p2 z))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-invoke p3 z))))))))))))))))))) ((x y z . args) (let fnrec4834 ((x x) (y y) (z z) (args (list->cseq args))) (let* ((or__26__auto (sp3 x y z))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-invoke (var-deref "clojure.core" "some") (lambda (q) (let fnrec4835 ((q q)) (let* ((or__26__auto (jolt-invoke p1 q))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt-invoke p2 q))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-invoke p3 q))))))) args)))))))) sp3))) ((p1 p2 p3 . ps) (let fnrec4836 ((p1 p1) (p2 p2) (p3 p3) (ps (list->cseq ps))) (let* ((ps (jolt-cons p1 (jolt-cons p2 (jolt-cons p3 ps))))) (letrec ((spn (case-lambda (() (let fnrec4837 () jolt-nil)) ((x) (let fnrec4838 ((x x)) (jolt-invoke (var-deref "clojure.core" "some") (lambda (p) (let fnrec4839 ((p p)) (jolt-invoke p x))) ps))) ((x y) (let fnrec4840 ((x x) (y y)) (let* ((or__26__auto (spn x))) (if (jolt-truthy? or__26__auto) or__26__auto (spn y))))) ((x y z) (let fnrec4841 ((x x) (y y) (z z)) (let* ((or__26__auto (spn x))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (spn y))) (if (jolt-truthy? or__26__auto) or__26__auto (spn z))))))) ((x y z . args) (let fnrec4842 ((x x) (y y) (z z) (args (list->cseq args))) (let* ((or__26__auto (spn x y z))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-invoke (var-deref "clojure.core" "some") (lambda (p) (let fnrec4843 ((p p)) (jolt-invoke (var-deref "clojure.core" "some") p args))) ps)))))))) spn))))))) some-fn))) -(guard (e (#t #f)) - (def-var! "clojure.core" "not-any?" (letrec ((not-any? (lambda (pred coll) (let fnrec4844 ((pred pred) (coll coll)) (jolt-not (jolt-invoke (var-deref "clojure.core" "some") pred coll)))))) not-any?))) -(guard (e (#t #f)) - (def-var! "clojure.core" "not-every?" (letrec ((not-every? (lambda (pred coll) (let fnrec4845 ((pred pred) (coll coll)) (jolt-not (jolt-invoke (var-deref "clojure.core" "every?") pred coll)))))) not-every?))) -(guard (e (#t #f)) - (def-var! "clojure.core" "split-at" (letrec ((split-at (lambda (n coll) (let fnrec4846 ((n n) (coll coll)) (let* ((_o$4847 (jolt-take n coll)) (_o$4848 (jolt-drop n coll))) (jolt-vector _o$4847 _o$4848)))))) split-at))) -(guard (e (#t #f)) - (def-var! "clojure.core" "split-with" (letrec ((split-with (lambda (pred coll) (let fnrec4849 ((pred pred) (coll coll)) (let* ((_o$4850 (jolt-invoke (var-deref "clojure.core" "take-while") pred coll)) (_o$4851 (jolt-invoke (var-deref "clojure.core" "drop-while") pred coll))) (jolt-vector _o$4850 _o$4851)))))) split-with))) -(guard (e (#t #f)) - (def-var! "clojure.core" "qualified-keyword?" (letrec ((qualified-keyword? (lambda (x) (let fnrec4852 ((x x)) (let* ((and__25__auto (jolt-invoke (var-deref "clojure.core" "keyword?") x))) (if (jolt-truthy? and__25__auto) (jolt-some? (jolt-invoke (var-deref "clojure.core" "namespace") x)) and__25__auto)))))) qualified-keyword?))) -(guard (e (#t #f)) - (def-var! "clojure.core" "simple-keyword?" (letrec ((simple-keyword? (lambda (x) (let fnrec4853 ((x x)) (let* ((and__25__auto (jolt-invoke (var-deref "clojure.core" "keyword?") x))) (if (jolt-truthy? and__25__auto) (jolt-nil? (jolt-invoke (var-deref "clojure.core" "namespace") x)) and__25__auto)))))) simple-keyword?))) -(guard (e (#t #f)) - (def-var! "clojure.core" "qualified-symbol?" (letrec ((qualified-symbol? (lambda (x) (let fnrec4854 ((x x)) (let* ((and__25__auto (jolt-invoke (var-deref "clojure.core" "symbol?") x))) (if (jolt-truthy? and__25__auto) (jolt-some? (jolt-invoke (var-deref "clojure.core" "namespace") x)) and__25__auto)))))) qualified-symbol?))) -(guard (e (#t #f)) - (def-var! "clojure.core" "simple-symbol?" (letrec ((simple-symbol? (lambda (x) (let fnrec4855 ((x x)) (let* ((and__25__auto (jolt-invoke (var-deref "clojure.core" "symbol?") x))) (if (jolt-truthy? and__25__auto) (jolt-nil? (jolt-invoke (var-deref "clojure.core" "namespace") x)) and__25__auto)))))) simple-symbol?))) -(guard (e (#t #f)) - (def-var! "clojure.core" "ident?" (letrec ((ident? (lambda (x) (let fnrec4856 ((x x)) (let* ((or__26__auto (jolt-invoke (var-deref "clojure.core" "keyword?") x))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-invoke (var-deref "clojure.core" "symbol?") x))))))) ident?))) -(guard (e (#t #f)) - (def-var! "clojure.core" "qualified-ident?" (letrec ((qualified-ident? (lambda (x) (let fnrec4857 ((x x)) (let* ((or__26__auto (jolt-invoke (var-deref "clojure.core" "qualified-symbol?") x))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-invoke (var-deref "clojure.core" "qualified-keyword?") x))))))) qualified-ident?))) -(guard (e (#t #f)) - (def-var! "clojure.core" "simple-ident?" (letrec ((simple-ident? (lambda (x) (let fnrec4858 ((x x)) (let* ((or__26__auto (jolt-invoke (var-deref "clojure.core" "simple-symbol?") x))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-invoke (var-deref "clojure.core" "simple-keyword?") x))))))) simple-ident?))) -(guard (e (#t #f)) - (def-var! "clojure.core" "ratio?" (letrec ((ratio? (lambda (x) (let fnrec4859 ((x x)) (let* ((and__25__auto (jolt-invoke (var-deref "clojure.core" "number?") x))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt-invoke (var-deref "jolt.host" "exact?") x))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt-invoke (var-deref "jolt.host" "rational-type?") x))) (if (jolt-truthy? and__25__auto) (jolt-not (jolt-invoke (var-deref "clojure.core" "integer?") x)) and__25__auto)) and__25__auto)) and__25__auto)))))) ratio?))) -(guard (e (#t #f)) - (def-var! "clojure.core" "rational?" (letrec ((rational? (lambda (x) (let fnrec4860 ((x x)) (let* ((or__26__auto (let* ((and__25__auto (jolt-invoke (var-deref "clojure.core" "number?") x))) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "jolt.host" "exact?") x) and__25__auto)))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-invoke (var-deref "clojure.core" "decimal?") x))))))) rational?))) -(guard (e (#t #f)) - (def-var! "clojure.core" "class?" (letrec ((class? (lambda (x) (let fnrec4861 ((x x)) #f)))) class?))) -(guard (e (#t #f)) - (def-var! "clojure.core" "list?" (letrec ((list? (lambda (x) (let fnrec4862 ((x x)) (let* ((or__26__auto (let* ((and__25__auto (jolt-invoke (var-deref "jolt.host" "cseq?") x))) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "jolt.host" "cseq-list?") x) and__25__auto)))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-invoke (var-deref "jolt.host" "empty-list?") x))))))) list?))) -(guard (e (#t #f)) - (def-var! "clojure.core" "nat-int?" (letrec ((nat-int? (lambda (x) (let fnrec4863 ((x x)) (let* ((and__25__auto (jolt-invoke (var-deref "clojure.core" "int?") x))) (if (jolt-truthy? and__25__auto) (jolt-n>= x 0) and__25__auto)))))) nat-int?))) -(guard (e (#t #f)) - (def-var! "clojure.core" "neg-int?" (letrec ((neg-int? (lambda (x) (let fnrec4864 ((x x)) (let* ((and__25__auto (jolt-invoke (var-deref "clojure.core" "int?") x))) (if (jolt-truthy? and__25__auto) (jolt-neg? x) and__25__auto)))))) neg-int?))) -(guard (e (#t #f)) - (def-var! "clojure.core" "pos-int?" (letrec ((pos-int? (lambda (x) (let fnrec4865 ((x x)) (let* ((and__25__auto (jolt-invoke (var-deref "clojure.core" "int?") x))) (if (jolt-truthy? and__25__auto) (jolt-pos? x) and__25__auto)))))) pos-int?))) -(guard (e (#t #f)) - (def-var! "clojure.core" "replicate" (letrec ((replicate (lambda (n x) (let fnrec4866 ((n n) (x x)) (let* ((_a$4868 (lambda (_) (let fnrec4867 ((_ _)) x))) (_a$4869 (jolt-range n))) (jolt-map _a$4868 _a$4869)))))) replicate))) -(guard (e (#t #f)) - (def-var! "clojure.core" "take-last" (letrec ((take-last (lambda (n coll) (let fnrec4870 ((n n) (coll coll)) (let* ((c (jolt-invoke (var-deref "clojure.core" "vec") coll)) (len (jolt-count c))) (if (jolt-pos? len) (jolt-seq (jolt-invoke (var-deref "clojure.core" "subvec") c (jolt-n-max 0 (jolt-n- len n)))) jolt-nil)))))) take-last))) -(guard (e (#t #f)) - (def-var! "clojure.core" "drop-last" (letrec ((drop-last (case-lambda ((coll) (let fnrec4871 ((coll coll)) (drop-last 1 coll))) ((n coll) (let fnrec4872 ((n n) (coll coll)) (let* ((_a$4874 (lambda (x _) (let fnrec4873 ((x x) (_ _)) x))) (_a$4875 coll) (_a$4876 (jolt-drop n coll))) (jolt-map _a$4874 _a$4875 _a$4876))))))) drop-last))) -(guard (e (#t #f)) - (def-var! "clojure.core" "distinct?" (letrec ((distinct? (case-lambda ((x) (let fnrec4877 ((x x)) #t)) ((x y) (let fnrec4878 ((x x) (y y)) (jolt-not (jolt= x y)))) ((x y . more) (let fnrec4879 ((x x) (y y) (more (list->cseq more))) (if (jolt-not (jolt= x y)) (let* ((s (let* ((_o$4881 x) (_o$4882 y)) (jolt-hash-set _o$4881 _o$4882))) (xs more)) (let loop4880 ((s s) (xs xs)) (if (jolt-truthy? xs) (let* ((x (jolt-first xs))) (if (jolt-contains? s x) #f (let* ((_a$4883 (jolt-conj s x)) (_a$4884 (jolt-next xs))) (loop4880 _a$4883 _a$4884)))) #t))) #f)))))) distinct?))) -(guard (e (#t #f)) - (def-var! "clojure.core" "replace" (letrec ((replace (lambda (smap coll) (let fnrec4885 ((smap smap) (coll coll)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "vector?") coll)) (jolt-invoke (var-deref "clojure.core" "mapv") (lambda (x) (let fnrec4886 ((x x)) (jolt-get smap x x))) coll) (jolt-map (lambda (x) (let fnrec4887 ((x x)) (jolt-get smap x x))) coll)))))) replace))) -(guard (e (#t #f)) - (def-var! "clojure.core" "nthnext" (letrec ((nthnext (lambda (coll n) (let fnrec4888 ((coll coll) (n n)) (let* ((n n) (xs (jolt-seq coll))) (let loop4889 ((n n) (xs xs)) (if (jolt-truthy? (let* ((and__25__auto xs)) (if (jolt-truthy? and__25__auto) (jolt-pos? n) and__25__auto))) (let* ((_a$4890 (jolt-dec n)) (_a$4891 (jolt-next xs))) (loop4889 _a$4890 _a$4891)) xs))))))) nthnext))) -(guard (e (#t #f)) - (def-var! "clojure.core" "bounded-count" (letrec ((bounded-count (lambda (n coll) (let fnrec4892 ((n n) (coll coll)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "counted?") coll)) (jolt-count coll) (let* ((i 0) (s (jolt-seq coll))) (let loop4893 ((i i) (s s)) (if (jolt-truthy? (let* ((and__25__auto s)) (if (jolt-truthy? and__25__auto) (jolt-n< i n) and__25__auto))) (let* ((_a$4894 (jolt-inc i)) (_a$4895 (jolt-next s))) (loop4893 _a$4894 _a$4895)) i)))))))) bounded-count))) -(guard (e (#t #f)) - (def-var! "clojure.core" "run!" (letrec ((run! (lambda (proc coll) (let fnrec4896 ((proc proc) (coll coll)) (begin (jolt-reduce (lambda (_ x) (let fnrec4897 ((_ _) (x x)) (jolt-invoke proc x))) jolt-nil coll) jolt-nil))))) run!))) -(guard (e (#t #f)) - (def-var! "clojure.core" "completing" (letrec ((completing (case-lambda ((f) (let fnrec4898 ((f f)) (completing f jolt-identity))) ((f cf) (let fnrec4899 ((f f) (cf cf)) (case-lambda (() (let fnrec4900 () (jolt-invoke f))) ((x) (let fnrec4901 ((x x)) (jolt-invoke cf x))) ((x y) (let fnrec4902 ((x x) (y y)) (jolt-invoke f x y))))))))) completing))) -(guard (e (#t #f)) - (def-var! "clojure.core" "nthrest" (letrec ((nthrest (lambda (coll n) (let fnrec4903 ((coll coll) (n n)) (if (jolt-pos? n) (let* ((or__26__auto (let* ((n n) (xs coll)) (let loop4904 ((n n) (xs xs)) (let* ((s (let* ((and__25__auto (jolt-pos? n))) (if (jolt-truthy? and__25__auto) (jolt-seq xs) and__25__auto)))) (if (jolt-truthy? s) (let* ((_a$4905 (jolt-dec n)) (_a$4906 (jolt-rest s))) (loop4904 _a$4905 _a$4906)) (jolt-seq xs))))))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-list ))) coll))))) nthrest))) -(guard (e (#t #f)) - (def-var! "clojure.core" "abs" (letrec ((abs (lambda (x) (let fnrec4907 ((x x)) (if (jolt-neg? x) (jolt-n- 0 x) x))))) abs))) -(guard (e (#t #f)) - (def-var! "clojure.core" "NaN?" (letrec ((NaN? (lambda (x) (let fnrec4908 ((x x)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "number?") x)) (jolt-not (jolt= x x)) (jolt-throw (jolt-invoke (var-deref "clojure.core" "str") "NaN? requires a number"))))))) NaN?))) -(guard (e (#t #f)) - (def-var! "clojure.core" "object?" (letrec ((object? (lambda (x) (let fnrec4909 ((x x)) #f)))) object?))) -(guard (e (#t #f)) - (def-var! "clojure.core" "undefined?" (letrec ((undefined? (lambda (x) (let fnrec4910 ((x x)) #f)))) undefined?))) -(guard (e (#t #f)) - (def-var! "clojure.core" "keyword-identical?" (letrec ((keyword-identical? (lambda (a b) (let fnrec4911 ((a a) (b b)) (jolt= a b))))) keyword-identical?))) -(guard (e (#t #f)) - (def-var! "clojure.core" "any?" (letrec ((any? (lambda (x) (let fnrec4912 ((x x)) #t)))) any?))) -(guard (e (#t #f)) - (def-var! "clojure.core" "printf" (letrec ((printf (lambda (fmt . args) (let fnrec4913 ((fmt fmt) (args (list->cseq args))) (jolt-invoke (var-deref "clojure.core" "print") (jolt-apply (var-deref "clojure.core" "format") fmt args)))))) printf))) -(guard (e (#t #f)) - (def-var! "clojure.core" "bound?" (letrec ((bound? (lambda vars (let fnrec4914 ((vars (list->cseq vars))) (jolt-invoke (var-deref "clojure.core" "every?") (lambda (v) (let fnrec4915 ((v v)) (jolt-some? (jolt-get v (keyword #f "root"))))) vars))))) bound?))) -(guard (e (#t #f)) - (def-var! "clojure.core" "with-bindings*" (letrec ((with-bindings* (lambda (binding-map f . args) (let fnrec4916 ((binding-map binding-map) (f f) (args (list->cseq args))) (begin (jolt-invoke (var-deref "clojure.core" "push-thread-bindings") binding-map) (dynamic-wind (lambda () #f) (lambda () (jolt-apply f args)) (lambda () (jolt-invoke (var-deref "clojure.core" "pop-thread-bindings"))))))))) with-bindings*))) -(guard (e (#t #f)) - (def-var! "clojure.core" "bound-fn*" (letrec ((bound-fn* (lambda (f) (let fnrec4917 ((f f)) (let* ((bs (jolt-invoke (var-deref "clojure.core" "get-thread-bindings")))) (lambda args (let fnrec4918 ((args (list->cseq args))) (jolt-apply (var-deref "clojure.core" "with-bindings*") bs f args)))))))) bound-fn*))) -(guard (e (#t #f)) - (def-var! "clojure.core" "thread-bound?" (letrec ((thread-bound? (lambda vars (let fnrec4919 ((vars (list->cseq vars))) (jolt-invoke (var-deref "clojure.core" "every?") (lambda (v) (let fnrec4920 ((v v)) (jolt-invoke (var-deref "clojure.core" "__thread-bound?") v))) vars))))) thread-bound?))) -(guard (e (#t #f)) - (def-var! "clojure.core" "key" (letrec ((key (lambda (e) (let fnrec4921 ((e e)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "map-entry?") e)) (jolt-nth e 0) (jolt-throw (jolt-ex-info "key requires a map entry" (jolt-hash-map)))))))) key))) -(guard (e (#t #f)) - (def-var! "clojure.core" "val" (letrec ((val (lambda (e) (let fnrec4922 ((e e)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "map-entry?") e)) (jolt-nth e 1) (jolt-throw (jolt-ex-info "val requires a map entry" (jolt-hash-map)))))))) val))) -(guard (e (#t #f)) - (def-var! "clojure.core" "make-hierarchy" (letrec ((make-hierarchy (lambda () (let fnrec4923 () (let* ((_o$4924 (keyword #f "parents")) (_o$4925 (jolt-hash-map)) (_o$4926 (keyword #f "descendants")) (_o$4927 (jolt-hash-map)) (_o$4928 (keyword #f "ancestors")) (_o$4929 (jolt-hash-map))) (jolt-hash-map _o$4924 _o$4925 _o$4926 _o$4927 _o$4928 _o$4929)))))) make-hierarchy))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "global-hierarchy" (jolt-invoke (var-deref "clojure.core" "atom") (jolt-invoke (var-deref "clojure.core" "make-hierarchy"))) (let* ((_o$4930 (keyword #f "private")) (_o$4931 #t)) (jolt-hash-map _o$4930 _o$4931)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "hier-assert" (letrec ((hier-assert (lambda (ok form) (let fnrec4932 ((ok ok) (form form)) (if (jolt-not ok) (jolt-throw (host-new "AssertionError" (jolt-invoke (var-deref "clojure.core" "str") "Assert failed: " form))) jolt-nil))))) hier-assert) (let* ((_o$4933 (keyword #f "private")) (_o$4934 #t)) (jolt-hash-map _o$4933 _o$4934)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "class-tag?" (letrec ((class-tag? (lambda (tag) (let fnrec4935 ((tag tag)) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "class-value?") tag)) #t #f))))) class-tag?) (let* ((_o$4936 (keyword #f "private")) (_o$4937 #t)) (jolt-hash-map _o$4936 _o$4937)))) -(guard (e (#t #f)) - (def-var! "clojure.core" "isa?" (letrec ((isa? (case-lambda ((child parent) (let fnrec4938 ((child child) (parent parent)) (isa? (jolt-invoke (var-deref "clojure.core" "deref") (var-deref "clojure.core" "global-hierarchy")) child parent))) ((h child parent) (let fnrec4939 ((h h) (child child) (parent parent)) (let* ((or__26__auto (jolt= child parent))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt-invoke (var-deref "jolt.host" "class-isa?") child parent))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt-contains? (let* ((_a$4940 (jolt-get h (keyword #f "ancestors"))) (_a$4941 child) (_a$4942 (jolt-hash-set))) (jolt-get _a$4940 _a$4941 _a$4942)) parent))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (let* ((and__25__auto (jolt-invoke (var-deref "clojure.core" "class-tag?") child))) (if (jolt-truthy? and__25__auto) (let* ((_a$4947 (var-deref "clojure.core" "some")) (_a$4948 (lambda (s) (let fnrec4943 ((s s)) (jolt-contains? (let* ((_a$4944 (jolt-get h (keyword #f "ancestors"))) (_a$4945 s) (_a$4946 (jolt-hash-set))) (jolt-get _a$4944 _a$4945 _a$4946)) parent)))) (_a$4949 (jolt-invoke (var-deref "jolt.host" "class-supers") child))) (jolt-invoke _a$4947 _a$4948 _a$4949)) and__25__auto)))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((and__25__auto (jolt-invoke (var-deref "clojure.core" "vector?") parent))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt-invoke (var-deref "clojure.core" "vector?") child))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (let* ((_a$4950 (jolt-count parent)) (_a$4951 (jolt-count child))) (jolt= _a$4950 _a$4951)))) (if (jolt-truthy? and__25__auto) (let* ((ret #t) (i 0)) (let loop4952 ((ret ret) (i i)) (if (let* ((or__26__auto (jolt-not ret))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt= i (jolt-count parent)))) ret (let* ((_a$4956 (let* ((_a$4953 h) (_a$4954 (jolt-nth child i)) (_a$4955 (jolt-nth parent i))) (isa? _a$4953 _a$4954 _a$4955))) (_a$4957 (jolt-inc i))) (loop4952 _a$4956 _a$4957))))) and__25__auto)) and__25__auto)) and__25__auto))))))))))))))) isa?))) -(guard (e (#t #f)) - (def-var! "clojure.core" "parents" (letrec ((parents (case-lambda ((tag) (let fnrec4958 ((tag tag)) (parents (jolt-invoke (var-deref "clojure.core" "deref") (var-deref "clojure.core" "global-hierarchy")) tag))) ((h tag) (let fnrec4959 ((h h) (tag tag)) (jolt-invoke (var-deref "clojure.core" "not-empty") (let* ((tp (jolt-get (jolt-get h (keyword #f "parents")) tag))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "class-tag?") tag)) (jolt-into (jolt-invoke (var-deref "clojure.core" "set") (jolt-invoke (var-deref "jolt.host" "class-bases") tag)) tp) tp)))))))) parents))) -(guard (e (#t #f)) - (def-var! "clojure.core" "ancestors" (letrec ((ancestors (case-lambda ((tag) (let fnrec4960 ((tag tag)) (ancestors (jolt-invoke (var-deref "clojure.core" "deref") (var-deref "clojure.core" "global-hierarchy")) tag))) ((h tag) (let fnrec4961 ((h h) (tag tag)) (jolt-invoke (var-deref "clojure.core" "not-empty") (let* ((ta (jolt-get (jolt-get h (keyword #f "ancestors")) tag))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "class-tag?") tag)) (let* ((superclasses (jolt-invoke (var-deref "clojure.core" "set") (jolt-invoke (var-deref "jolt.host" "class-supers") tag)))) (jolt-reduce jolt-into superclasses (jolt-cons ta (jolt-map (lambda (s) (let fnrec4962 ((s s)) (jolt-get (jolt-get h (keyword #f "ancestors")) s))) superclasses)))) ta)))))))) ancestors))) -(guard (e (#t #f)) - (def-var! "clojure.core" "descendants" (letrec ((descendants (case-lambda ((tag) (let fnrec4963 ((tag tag)) (descendants (jolt-invoke (var-deref "clojure.core" "deref") (var-deref "clojure.core" "global-hierarchy")) tag))) ((h tag) (let fnrec4964 ((h h) (tag tag)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "class-tag?") tag)) (jolt-throw (host-new "UnsupportedOperationException" "Can't get descendants of classes")) (jolt-invoke (var-deref "clojure.core" "not-empty") (jolt-get (jolt-get h (keyword #f "descendants")) tag)))))))) descendants))) -(guard (e (#t #f)) - (def-var! "clojure.core" "derive" (letrec ((derive (case-lambda ((tag parent) (let fnrec4965 ((tag tag) (parent parent)) (begin (jolt-invoke (var-deref "clojure.core" "hier-assert") (jolt-invoke (var-deref "clojure.core" "namespace") parent) "(namespace parent)") (jolt-invoke (var-deref "clojure.core" "hier-assert") (let* ((or__26__auto (jolt-invoke (var-deref "clojure.core" "class-tag?") tag))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((and__25__auto (let* ((or__26__auto (jolt-invoke (var-deref "clojure.core" "keyword?") tag))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-invoke (var-deref "clojure.core" "symbol?") tag))))) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "clojure.core" "namespace") tag) and__25__auto)))) "(or (class? tag) (and (instance? clojure.lang.Named tag) (namespace tag)))") (jolt-invoke (var-deref "clojure.core" "swap!") (var-deref "clojure.core" "global-hierarchy") derive tag parent) jolt-nil))) ((h tag parent) (let fnrec4966 ((h h) (tag tag) (parent parent)) (begin (jolt-invoke (var-deref "clojure.core" "hier-assert") (jolt-invoke (var-deref "clojure.core" "not=") tag parent) "(not= tag parent)") (jolt-invoke (var-deref "clojure.core" "hier-assert") (let* ((or__26__auto (jolt-invoke (var-deref "clojure.core" "class-tag?") tag))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt-invoke (var-deref "clojure.core" "keyword?") tag))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-invoke (var-deref "clojure.core" "symbol?") tag))))) "(or (class? tag) (instance? clojure.lang.Named tag))") (jolt-invoke (var-deref "clojure.core" "hier-assert") (let* ((or__26__auto (jolt-invoke (var-deref "clojure.core" "keyword?") parent))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-invoke (var-deref "clojure.core" "symbol?") parent))) "(instance? clojure.lang.Named parent)") (let* ((tp (jolt-get h (keyword #f "parents"))) (td (jolt-get h (keyword #f "descendants"))) (ta (jolt-get h (keyword #f "ancestors"))) (tf (lambda (m source sources target targets) (let fnrec4967 ((m m) (source source) (sources sources) (target target) (targets targets)) (let* ((_a$4972 (lambda (ret k) (let fnrec4968 ((ret ret) (k k)) (jolt-assoc ret k (let* ((_a$4969 jolt-conj) (_a$4970 (jolt-get targets k (jolt-hash-set))) (_a$4971 (jolt-cons target (jolt-invoke targets target)))) (jolt-reduce _a$4969 _a$4970 _a$4971)))))) (_a$4973 m) (_a$4974 (jolt-cons source (jolt-invoke sources source)))) (jolt-reduce _a$4972 _a$4973 _a$4974)))))) (let* ((or__26__auto (if (jolt-not (jolt-contains? (jolt-invoke tp tag) parent)) (begin (if (jolt-contains? (jolt-invoke ta tag) parent) (jolt-throw (host-new "Exception" (jolt-invoke (var-deref "clojure.core" "str") tag " already has " parent " as ancestor"))) jolt-nil) (if (jolt-contains? (jolt-invoke ta parent) tag) (jolt-throw (host-new "Exception" (jolt-invoke (var-deref "clojure.core" "str") "Cyclic derivation: " parent " has " tag " as ancestor"))) jolt-nil) (let* ((_o$4975 (keyword #f "parents")) (_o$4976 (jolt-assoc tp tag (jolt-conj (jolt-get tp tag (jolt-hash-set)) parent))) (_o$4977 (keyword #f "ancestors")) (_o$4978 (jolt-invoke tf ta tag td parent ta)) (_o$4979 (keyword #f "descendants")) (_o$4980 (jolt-invoke tf td parent ta tag td))) (jolt-hash-map _o$4975 _o$4976 _o$4977 _o$4978 _o$4979 _o$4980))) jolt-nil))) (if (jolt-truthy? or__26__auto) or__26__auto h))))))))) derive))) -(guard (e (#t #f)) - (def-var! "clojure.core" "underive" (letrec ((underive (case-lambda ((tag parent) (let fnrec4981 ((tag tag) (parent parent)) (begin (jolt-invoke (var-deref "clojure.core" "swap!") (var-deref "clojure.core" "global-hierarchy") underive tag parent) jolt-nil))) ((h tag parent) (let fnrec4982 ((h h) (tag tag) (parent parent)) (let* ((parent-map (jolt-get h (keyword #f "parents"))) (childs-parents (if (jolt-truthy? (jolt-invoke parent-map tag)) (jolt-invoke (var-deref "clojure.core" "disj") (jolt-invoke parent-map tag) parent) (jolt-hash-set))) (new-parents (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "not-empty") childs-parents)) (jolt-assoc parent-map tag childs-parents) (jolt-dissoc parent-map tag))) (deriv-seq (let* ((_a$4989 (var-deref "clojure.core" "mapcat")) (_a$4990 (lambda (e) (let fnrec4983 ((e e)) (let* ((_a$4987 (jolt-invoke (var-deref "clojure.core" "key") e)) (_a$4988 (let* ((_a$4984 (var-deref "clojure.core" "interpose")) (_a$4985 (jolt-invoke (var-deref "clojure.core" "key") e)) (_a$4986 (jolt-invoke (var-deref "clojure.core" "val") e))) (jolt-invoke _a$4984 _a$4985 _a$4986)))) (jolt-cons _a$4987 _a$4988))))) (_a$4991 (jolt-seq new-parents))) (jolt-invoke _a$4989 _a$4990 _a$4991)))) (if (jolt-contains? (jolt-invoke parent-map tag) parent) (let* ((_a$4993 (lambda (p G__136) (let fnrec4992 ((p p) (G__136 G__136)) (let* ((G__137 G__136) (t (jolt-nth G__137 0 jolt-nil)) (pr (jolt-nth G__137 1 jolt-nil))) (jolt-invoke (var-deref "clojure.core" "derive") p t pr))))) (_a$4994 (jolt-invoke (var-deref "clojure.core" "make-hierarchy"))) (_a$4995 (jolt-invoke (var-deref "clojure.core" "partition") 2 deriv-seq))) (jolt-reduce _a$4993 _a$4994 _a$4995)) h))))))) underive))) -(guard (e (#t #f)) - (def-var! "clojure.core" "sequential?" (letrec ((sequential? (lambda (x) (let fnrec4996 ((x x)) (let* ((or__26__auto (jolt-invoke (var-deref "clojure.core" "vector?") x))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-invoke (var-deref "clojure.core" "seq?") x))))))) sequential?))) -(guard (e (#t #f)) - (def-var! "clojure.core" "associative?" (letrec ((associative? (lambda (x) (let fnrec4997 ((x x)) (let* ((or__26__auto (jolt-invoke (var-deref "clojure.core" "map?") x))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-invoke (var-deref "clojure.core" "vector?") x))))))) associative?))) -(guard (e (#t #f)) - (def-var! "clojure.core" "counted?" (letrec ((counted? (lambda (x) (let fnrec4998 ((x x)) (let* ((or__26__auto (jolt-invoke (var-deref "clojure.core" "vector?") x))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt-invoke (var-deref "clojure.core" "map?") x))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt-invoke (var-deref "clojure.core" "set?") x))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-invoke (var-deref "clojure.core" "list?") x))))))))))) counted?))) -(guard (e (#t #f)) - (def-var! "clojure.core" "indexed?" (letrec ((indexed? (lambda (x) (let fnrec4999 ((x x)) (jolt-invoke (var-deref "clojure.core" "vector?") x))))) indexed?))) -(guard (e (#t #f)) - (declare-var! "clojure.core" "sorted?")) -(guard (e (#t #f)) - (def-var! "clojure.core" "reversible?" (letrec ((reversible? (lambda (x) (let fnrec5000 ((x x)) (let* ((or__26__auto (jolt-invoke (var-deref "clojure.core" "vector?") x))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-invoke (var-deref "clojure.core" "sorted?") x))))))) reversible?))) -(guard (e (#t #f)) - (def-var! "clojure.core" "seqable?" (letrec ((seqable? (lambda (x) (let fnrec5001 ((x x)) (if (jolt-truthy? (let* ((or__26__auto (jolt-nil? x))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt-invoke (var-deref "clojure.core" "coll?") x))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt-invoke (var-deref "clojure.core" "string?") x))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-invoke (var-deref "jolt.host" "array-value?") x)))))))) #t #f))))) seqable?))) -(guard (e (#t #f)) - (def-var! "clojure.core" "boolean?" (letrec ((boolean? (lambda (x) (let fnrec5002 ((x x)) (let* ((or__26__auto (jolt-invoke (var-deref "clojure.core" "true?") x))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-invoke (var-deref "clojure.core" "false?") x))))))) boolean?))) -(guard (e (#t #f)) - (def-var! "clojure.core" "double?" (letrec ((double? (lambda (x) (let fnrec5003 ((x x)) (let* ((and__25__auto (jolt-invoke (var-deref "clojure.core" "number?") x))) (if (jolt-truthy? and__25__auto) (jolt-not (jolt-invoke (var-deref "clojure.core" "integer?") x)) and__25__auto)))))) double?))) -(guard (e (#t #f)) - (def-var! "clojure.core" "float?" (letrec ((float? (lambda (x) (let fnrec5004 ((x x)) (jolt-invoke (var-deref "clojure.core" "double?") x))))) float?))) -(guard (e (#t #f)) - (def-var! "clojure.core" "infinite?" (letrec ((infinite? (lambda (x) (let fnrec5005 ((x x)) (let* ((and__25__auto (jolt-invoke (var-deref "clojure.core" "number?") x))) (if (jolt-truthy? and__25__auto) (let* ((or__26__auto (jolt= x +inf.0))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt= x -inf.0))) and__25__auto)))))) infinite?))) -(guard (e (#t #f)) - (def-var! "clojure.core" "atom?" (letrec ((atom? (lambda (x) (let fnrec5006 ((x x)) (jolt= (jolt-get x (keyword "jolt" "type")) (keyword "jolt" "atom")))))) atom?))) -(guard (e (#t #f)) - (def-var! "clojure.core" "volatile?" (letrec ((volatile? (lambda (x) (let fnrec5007 ((x x)) (jolt= (jolt-get x (keyword "jolt" "type")) (keyword "jolt" "volatile")))))) volatile?))) -(guard (e (#t #f)) - (def-var! "clojure.core" "reader-conditional?" (letrec ((reader-conditional? (lambda (x) (let fnrec5008 ((x x)) (jolt= (jolt-get x (keyword "jolt" "type")) (keyword "jolt" "reader-conditional")))))) reader-conditional?))) -(guard (e (#t #f)) - (def-var! "clojure.core" "tagged-literal?" (letrec ((tagged-literal? (lambda (x) (let fnrec5009 ((x x)) (jolt= (jolt-get x (keyword "jolt" "type")) (keyword "jolt" "tagged-literal")))))) tagged-literal?))) -(guard (e (#t #f)) - (def-var! "clojure.core" "record?" (letrec ((record? (lambda (x) (let fnrec5010 ((x x)) (jolt-some? (jolt-get x (keyword "jolt" "deftype"))))))) record?))) -(guard (e (#t #f)) - (def-var! "clojure.core" "uuid?" (letrec ((uuid? (lambda (x) (let fnrec5011 ((x x)) (jolt= (jolt-get x (keyword "jolt" "type")) (keyword "jolt" "uuid")))))) uuid?))) -(guard (e (#t #f)) - (def-var! "clojure.core" "inst?" (letrec ((inst? (lambda (x) (let fnrec5012 ((x x)) (jolt= (jolt-get x (keyword "jolt" "type")) (keyword "jolt" "inst")))))) inst?))) -(guard (e (#t #f)) - (def-var! "clojure.core" "char?" (letrec ((char? (lambda (x) (let fnrec5013 ((x x)) (jolt= (jolt-get x (keyword "jolt" "type")) (keyword "jolt" "char")))))) char?))) -(guard (e (#t #f)) - (def-var! "clojure.core" "realized?" (letrec ((realized? (lambda (x) (let fnrec5014 ((x x)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "delay?") x)) (jolt-invoke (var-deref "clojure.core" "boolean") (jolt-get x (keyword #f "realized"))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "future?") x)) (jolt-invoke (var-deref "clojure.core" "boolean") (jolt-get x (keyword #f "cached"))) (if (jolt= (keyword "jolt" "lazy-seq") (jolt-get x (keyword "jolt" "type"))) (jolt-invoke (var-deref "clojure.core" "boolean") (jolt-get x (keyword #f "realized"))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "atom?") x)) #t (if (jolt-truthy? (keyword #f "else")) (jolt-throw (jolt-invoke (var-deref "clojure.core" "str") "realized? not supported on: " (jolt-invoke (var-deref "clojure.core" "class") x))) jolt-nil))))))))) realized?))) -(guard (e (#t #f)) - (def-var! "clojure.core" "force" (letrec ((force (lambda (x) (let fnrec5015 ((x x)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "delay?") x)) (jolt-invoke (var-deref "clojure.core" "deref") x) x))))) force))) -(guard (e (#t #f)) - (def-var! "clojure.core" "pop" (letrec ((pop (lambda (coll) (let fnrec5016 ((coll coll)) (if (jolt-nil? coll) jolt-nil (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "vector?") coll)) (if (jolt-zero? (jolt-count coll)) (jolt-throw "Can't pop empty vector") (jolt-invoke (var-deref "clojure.core" "subvec") coll 0 (jolt-dec (jolt-count coll)))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "seq?") coll)) (if (jolt-nil? (jolt-seq coll)) (jolt-throw "Can't pop empty list") (jolt-rest coll)) (if (jolt-truthy? (keyword #f "else")) (jolt-throw (jolt-invoke (var-deref "clojure.core" "str") "pop not supported on: " coll)) jolt-nil)))))))) pop))) -(guard (e (#t #f)) - (def-var! "clojure.core" "dorun" (letrec ((dorun (case-lambda ((coll) (let fnrec5017 ((coll coll)) (let* ((s (jolt-seq coll))) (let loop5018 ((s s)) (if (jolt-truthy? s) (loop5018 (jolt-next s)) jolt-nil))))) ((n coll) (let fnrec5019 ((n n) (coll coll)) (let* ((n n) (s (jolt-seq coll))) (let loop5020 ((n n) (s s)) (if (jolt-truthy? (let* ((and__25__auto s)) (if (jolt-truthy? and__25__auto) (jolt-pos? n) and__25__auto))) (let* ((_a$5021 (jolt-dec n)) (_a$5022 (jolt-next s))) (loop5020 _a$5021 _a$5022)) jolt-nil)))))))) dorun))) -(guard (e (#t #f)) - (def-var! "clojure.core" "doall" (letrec ((doall (case-lambda ((coll) (let fnrec5023 ((coll coll)) (begin (jolt-invoke (var-deref "clojure.core" "dorun") coll) coll))) ((n coll) (let fnrec5024 ((n n) (coll coll)) (begin (jolt-invoke (var-deref "clojure.core" "dorun") n coll) coll)))))) doall))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "spread" (letrec ((spread (lambda (arglist) (let fnrec5025 ((arglist arglist)) (if (jolt-nil? arglist) jolt-nil (if (jolt-nil? (jolt-next arglist)) (jolt-seq (jolt-first arglist)) (if (jolt-truthy? (keyword #f "else")) (let* ((_a$5026 (jolt-first arglist)) (_a$5027 (spread (jolt-next arglist)))) (jolt-cons _a$5026 _a$5027)) jolt-nil))))))) spread) (let* ((_o$5028 (keyword #f "private")) (_o$5029 #t)) (jolt-hash-map _o$5028 _o$5029)))) -(guard (e (#t #f)) - (def-var! "clojure.core" "list*" (letrec ((list* (case-lambda ((args) (let fnrec5030 ((args args)) (jolt-seq args))) ((a args) (let fnrec5031 ((a a) (args args)) (jolt-cons a args))) ((a b args) (let fnrec5032 ((a a) (b b) (args args)) (jolt-cons a (jolt-cons b args)))) ((a b c args) (let fnrec5033 ((a a) (b b) (c c) (args args)) (jolt-cons a (jolt-cons b (jolt-cons c args))))) ((a b c d . more) (let fnrec5034 ((a a) (b b) (c c) (d d) (more (list->cseq more))) (jolt-cons a (jolt-cons b (jolt-cons c (jolt-cons d (jolt-invoke (var-deref "clojure.core" "spread") more)))))))))) list*))) -(guard (e (#t #f)) - (def-var! "clojure.core" "print-str" (letrec ((print-str (lambda xs (let fnrec5035 ((xs (list->cseq xs))) (jolt-invoke (var-deref "clojure.core" "__with-out-str") (lambda () (let fnrec5036 () (jolt-apply (var-deref "clojure.core" "print") xs)))))))) print-str))) -(guard (e (#t #f)) - (def-var! "clojure.core" "println-str" (letrec ((println-str (lambda xs (let fnrec5037 ((xs (list->cseq xs))) (jolt-invoke (var-deref "clojure.core" "__with-out-str") (lambda () (let fnrec5038 () (jolt-apply (var-deref "clojure.core" "println") xs)))))))) println-str))) -(guard (e (#t #f)) - (def-var! "clojure.core" "prn-str" (letrec ((prn-str (lambda xs (let fnrec5039 ((xs (list->cseq xs))) (jolt-invoke (var-deref "clojure.core" "__with-out-str") (lambda () (let fnrec5040 () (jolt-apply (var-deref "clojure.core" "prn") xs)))))))) prn-str))) -(guard (e (#t #f)) - (def-var! "clojure.core" "rand-int" (letrec ((rand-int (lambda (n) (let fnrec4319 ((n n)) (jolt-invoke (var-deref "clojure.core" "int") (jolt-invoke (var-deref "clojure.core" "rand") n)))))) rand-int))) -(guard (e (#t #f)) - (def-var! "clojure.core" "shuffle" (letrec ((shuffle (lambda (coll) (let fnrec4320 ((coll coll)) (begin (if (jolt-truthy? (let* ((or__26__auto (jolt-not (jolt-invoke (var-deref "clojure.core" "coll?") coll)))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-invoke (var-deref "clojure.core" "map?") coll)))) (jolt-throw (let* ((_a$4321 (jolt-invoke (var-deref "clojure.core" "str") "shuffle requires a collection, got: " coll)) (_a$4322 (jolt-hash-map))) (jolt-ex-info _a$4321 _a$4322))) jolt-nil) (let* ((v (jolt-invoke (var-deref "clojure.core" "vec") coll)) (i (jolt-dec (jolt-count v)))) (let loop4323 ((v v) (i i)) (if (jolt-pos? i) (let* ((j (jolt-invoke (var-deref "clojure.core" "rand-int") (jolt-inc i))) (t (jolt-nth v i))) (let* ((_a$4324 (jolt-assoc (jolt-assoc v i (jolt-nth v j)) j t)) (_a$4325 (jolt-dec i))) (loop4323 _a$4324 _a$4325))) v)))))))) shuffle))) -(guard (e (#t #f)) - (def-var! "clojure.core" "sort-by" (letrec ((sort-by (case-lambda ((keyfn coll) (let fnrec4326 ((keyfn keyfn) (coll coll)) (sort-by keyfn (var-deref "clojure.core" "compare") coll))) ((keyfn comp coll) (let fnrec4327 ((keyfn keyfn) (comp comp) (coll coll)) (begin (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "coll?") comp)) (jolt-throw (host-new "ClassCastException" (jolt-invoke (var-deref "clojure.core" "str") (jolt-invoke (var-deref "clojure.core" "class") comp) " cannot be cast to java.util.Comparator"))) jolt-nil) (jolt-invoke (var-deref "clojure.core" "sort") (lambda (x y) (let fnrec4328 ((x x) (y y)) (let* ((_a$4329 comp) (_a$4330 (jolt-invoke keyfn x)) (_a$4331 (jolt-invoke keyfn y))) (jolt-invoke _a$4329 _a$4330 _a$4331)))) coll))))))) sort-by))) -(guard (e (#t #f)) - (def-var! "clojure.core" "parse-uuid" (letrec ((parse-uuid (lambda (s) (let fnrec4332 ((s s)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "string?") s)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "re-matches") (jolt-regex "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}") s)) (jolt-invoke (var-deref "clojure.core" "__make-uuid") s) jolt-nil) (jolt-throw (jolt-invoke (var-deref "clojure.core" "str") "parse-uuid requires a string, got: " s))))))) parse-uuid))) -(guard (e (#t #f)) - (def-var! "clojure.core" "random-uuid" (letrec ((random-uuid (lambda () (let fnrec4333 () (let* ((hx4 (lambda () (let fnrec4334 () (jolt-invoke (var-deref "clojure.core" "format") "%04x" (jolt-invoke (var-deref "clojure.core" "rand-int") 65536))))) (hx3 (lambda () (let fnrec4335 () (jolt-invoke (var-deref "clojure.core" "format") "%03x" (jolt-invoke (var-deref "clojure.core" "rand-int") 4096)))))) (jolt-invoke (var-deref "clojure.core" "parse-uuid") (let* ((_a$4336 (var-deref "clojure.core" "str")) (_a$4337 (jolt-invoke hx4)) (_a$4338 (jolt-invoke hx4)) (_a$4339 "-") (_a$4340 (jolt-invoke hx4)) (_a$4341 "-4") (_a$4342 (jolt-invoke hx3)) (_a$4343 "-") (_a$4344 (jolt-invoke (var-deref "clojure.core" "format") "%x" (jolt-n+ 8 (jolt-invoke (var-deref "clojure.core" "rand-int") 4)))) (_a$4345 (jolt-invoke hx3)) (_a$4346 "-") (_a$4347 (jolt-invoke hx4)) (_a$4348 (jolt-invoke hx4)) (_a$4349 (jolt-invoke hx4))) (jolt-invoke _a$4336 _a$4337 _a$4338 _a$4339 _a$4340 _a$4341 _a$4342 _a$4343 _a$4344 _a$4345 _a$4346 _a$4347 _a$4348 _a$4349)))))))) random-uuid))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "char-escape-strings" (let* ((_o$4350 (integer->char 10)) (_o$4351 "\\n") (_o$4352 (integer->char 9)) (_o$4353 "\\t") (_o$4354 (integer->char 13)) (_o$4355 "\\r") (_o$4356 (integer->char 12)) (_o$4357 "\\f") (_o$4358 (integer->char 8)) (_o$4359 "\\b") (_o$4360 (integer->char 34)) (_o$4361 "\\\"") (_o$4362 (integer->char 92)) (_o$4363 "\\\\")) (jolt-hash-map _o$4350 _o$4351 _o$4352 _o$4353 _o$4354 _o$4355 _o$4356 _o$4357 _o$4358 _o$4359 _o$4360 _o$4361 _o$4362 _o$4363)) (let* ((_o$4364 (keyword #f "private")) (_o$4365 #t)) (jolt-hash-map _o$4364 _o$4365)))) -(guard (e (#t #f)) - (def-var! "clojure.core" "char-escape-string" (letrec ((char-escape-string (lambda (c) (let fnrec4366 ((c c)) (jolt-get (var-deref "clojure.core" "char-escape-strings") c))))) char-escape-string))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "char-name-strings" (let* ((_o$4367 (integer->char 10)) (_o$4368 "newline") (_o$4369 (integer->char 9)) (_o$4370 "tab") (_o$4371 (integer->char 13)) (_o$4372 "return") (_o$4373 (integer->char 12)) (_o$4374 "formfeed") (_o$4375 (integer->char 8)) (_o$4376 "backspace") (_o$4377 (integer->char 32)) (_o$4378 "space")) (jolt-hash-map _o$4367 _o$4368 _o$4369 _o$4370 _o$4371 _o$4372 _o$4373 _o$4374 _o$4375 _o$4376 _o$4377 _o$4378)) (let* ((_o$4379 (keyword #f "private")) (_o$4380 #t)) (jolt-hash-map _o$4379 _o$4380)))) -(guard (e (#t #f)) - (def-var! "clojure.core" "char-name-string" (letrec ((char-name-string (lambda (c) (let fnrec4381 ((c c)) (jolt-get (var-deref "clojure.core" "char-name-strings") c))))) char-name-string))) -(guard (e (#t #f)) - (def-var! "clojure.core" "rand-nth" (letrec ((rand-nth (lambda (coll) (let fnrec4382 ((coll coll)) (jolt-nth coll (jolt-invoke (var-deref "clojure.core" "rand-int") (jolt-count coll))))))) rand-nth))) -(guard (e (#t #f)) - (def-var! "clojure.core" "random-sample" (letrec ((random-sample (case-lambda ((prob) (let fnrec4383 ((prob prob)) (jolt-invoke jolt-filter (lambda (_) (let fnrec4384 ((_ _)) (jolt-n< (jolt-invoke (var-deref "clojure.core" "rand")) prob)))))) ((prob coll) (let fnrec4385 ((prob prob) (coll coll)) (jolt-filter (lambda (_) (let fnrec4386 ((_ _)) (jolt-n< (jolt-invoke (var-deref "clojure.core" "rand")) prob))) coll)))))) random-sample))) -(guard (e (#t #f)) - (def-var! "clojure.core" "comparator" (letrec ((comparator (lambda (pred) (let fnrec4387 ((pred pred)) (lambda (a b) (let fnrec4388 ((a a) (b b)) (if (jolt-truthy? (jolt-invoke pred a b)) -1 (if (jolt-truthy? (jolt-invoke pred b a)) 1 (if (jolt-truthy? (keyword #f "else")) 0 jolt-nil))))))))) comparator))) -(guard (e (#t #f)) - (def-var! "clojure.core" "reductions" (letrec ((reductions (case-lambda ((f coll) (let fnrec4389 ((f f) (coll coll)) (jolt-invoke (var-deref "clojure.core" "make-lazy-seq") (lambda () (let fnrec4390 () (jolt-invoke (var-deref "clojure.core" "coll->cells") (let* ((s (jolt-seq coll))) (if (jolt-truthy? s) (let* ((_a$4391 f) (_a$4392 (jolt-first s)) (_a$4393 (jolt-rest s))) (reductions _a$4391 _a$4392 _a$4393)) (jolt-list (jolt-invoke f)))))))))) ((f init coll) (let fnrec4394 ((f f) (init init) (coll coll)) (jolt-cons init (jolt-invoke (var-deref "clojure.core" "make-lazy-seq") (lambda () (let fnrec4395 () (jolt-invoke (var-deref "clojure.core" "coll->cells") (let* ((temp__27__auto (jolt-seq coll))) (if (jolt-truthy? temp__27__auto) (let* ((s temp__27__auto)) (let* ((_a$4396 f) (_a$4397 (jolt-invoke f init (jolt-first s))) (_a$4398 (jolt-rest s))) (reductions _a$4396 _a$4397 _a$4398))) jolt-nil)))))))))))) reductions))) -(guard (e (#t #f)) - (def-var! "clojure.core" "tree-seq" (letrec ((tree-seq (lambda (branch? children root) (let fnrec4399 ((branch? branch?) (children children) (root root)) (let* ((walk (letrec ((walk (lambda (node) (let fnrec4400 ((node node)) (jolt-invoke (var-deref "clojure.core" "make-lazy-seq") (lambda () (let fnrec4401 () (jolt-invoke (var-deref "clojure.core" "coll->cells") (jolt-cons node (if (jolt-truthy? (jolt-invoke branch? node)) (jolt-invoke (var-deref "clojure.core" "mapcat") walk (jolt-invoke children node)) jolt-nil)))))))))) walk))) (jolt-invoke walk root)))))) tree-seq))) -(guard (e (#t #f)) - (def-var! "clojure.core" "file-seq" (letrec ((file-seq (lambda (root) (let fnrec4402 ((root root)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "__file?") root)) (let* ((_a$4405 (var-deref "clojure.core" "tree-seq")) (_a$4406 (lambda (f) (let fnrec4403 ((f f)) (jolt-host-call "isDirectory" f)))) (_a$4407 (lambda (f) (let fnrec4404 ((f f)) (jolt-seq (jolt-host-call "listFiles" f))))) (_a$4408 root)) (jolt-invoke _a$4405 _a$4406 _a$4407 _a$4408)) (jolt-invoke (var-deref "clojure.core" "tree-seq") (var-deref "clojure.core" "__dir?") (var-deref "clojure.core" "__list-dir") root)))))) file-seq))) -(guard (e (#t #f)) - (def-var! "clojure.core" "flatten" (letrec ((flatten (lambda (coll) (let fnrec4409 ((coll coll)) (let* ((_a$4410 (jolt-invoke (var-deref "clojure.core" "complement") (var-deref "clojure.core" "sequential?"))) (_a$4411 (jolt-rest (jolt-invoke (var-deref "clojure.core" "tree-seq") (var-deref "clojure.core" "sequential?") jolt-seq coll)))) (jolt-filter _a$4410 _a$4411)))))) flatten))) -(guard (e (#t #f)) - (def-var! "clojure.core" "xml-seq" (letrec ((xml-seq (lambda (root) (let fnrec4412 ((root root)) (let* ((_a$4413 (var-deref "clojure.core" "tree-seq")) (_a$4414 (jolt-invoke (var-deref "clojure.core" "complement") (var-deref "clojure.core" "string?"))) (_a$4415 (jolt-invoke (var-deref "clojure.core" "comp") jolt-seq (keyword #f "content"))) (_a$4416 root)) (jolt-invoke _a$4413 _a$4414 _a$4415 _a$4416)))))) xml-seq))) -(guard (e (#t #f)) - (def-var! "clojure.core" "interleave" (letrec ((interleave (case-lambda (() (let fnrec4417 () (jolt-list ))) ((c1) (let fnrec4418 ((c1 c1)) (jolt-invoke (var-deref "clojure.core" "make-lazy-seq") (lambda () (let fnrec4419 () (jolt-invoke (var-deref "clojure.core" "coll->cells") c1)))))) ((c1 c2) (let fnrec4420 ((c1 c1) (c2 c2)) (jolt-invoke (var-deref "clojure.core" "make-lazy-seq") (lambda () (let fnrec4421 () (jolt-invoke (var-deref "clojure.core" "coll->cells") (let* ((s1 (jolt-seq c1)) (s2 (jolt-seq c2))) (if (jolt-truthy? (let* ((and__25__auto s1)) (if (jolt-truthy? and__25__auto) s2 and__25__auto))) (let* ((_a$4426 (jolt-first s1)) (_a$4427 (let* ((_a$4424 (jolt-first s2)) (_a$4425 (let* ((_a$4422 (jolt-rest s1)) (_a$4423 (jolt-rest s2))) (interleave _a$4422 _a$4423)))) (jolt-cons _a$4424 _a$4425)))) (jolt-cons _a$4426 _a$4427)) jolt-nil)))))))) ((c1 c2 . cs) (let fnrec4428 ((c1 c1) (c2 c2) (cs (list->cseq cs))) (jolt-invoke (var-deref "clojure.core" "make-lazy-seq") (lambda () (let fnrec4429 () (jolt-invoke (var-deref "clojure.core" "coll->cells") (let* ((ss (jolt-map jolt-seq (jolt-invoke (var-deref "clojure.core" "list*") c1 c2 cs)))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "every?") jolt-identity ss)) (let* ((_a$4430 (jolt-map jolt-first ss)) (_a$4431 (jolt-apply interleave (jolt-map jolt-rest ss)))) (jolt-concat _a$4430 _a$4431)) jolt-nil))))))))))) interleave))) -(guard (e (#t #f)) - (def-var! "clojure.core" "dedupe" (letrec ((dedupe (case-lambda (() (let fnrec4432 () (lambda (rf) (let fnrec4433 ((rf rf)) (let* ((pv (jolt-invoke (var-deref "clojure.core" "volatile!") (let* ((_o$4434 #f) (_o$4435 jolt-nil)) (jolt-vector _o$4434 _o$4435))))) (case-lambda (() (let fnrec4436 () (jolt-invoke rf))) ((result) (let fnrec4437 ((result result)) (jolt-invoke rf result))) ((result input) (let fnrec4438 ((result result) (input input)) (let* ((G__132 (jolt-invoke (var-deref "clojure.core" "deref") pv)) (seen (jolt-nth G__132 0 jolt-nil)) (prior (jolt-nth G__132 1 jolt-nil))) (begin (jolt-invoke (var-deref "clojure.core" "vreset!") pv (let* ((_o$4439 #t) (_o$4440 input)) (jolt-vector _o$4439 _o$4440))) (if (jolt-truthy? (let* ((and__25__auto seen)) (if (jolt-truthy? and__25__auto) (jolt= prior input) and__25__auto))) result (jolt-invoke rf result input)))))))))))) ((coll) (let fnrec4441 ((coll coll)) (let* ((step (letrec ((step (lambda (s prev) (let fnrec4442 ((s s) (prev prev)) (jolt-invoke (var-deref "clojure.core" "make-lazy-seq") (lambda () (let fnrec4443 () (let* ((s (jolt-seq s))) (if (jolt-truthy? s) (let* ((x (jolt-first s))) (if (jolt= x prev) (jolt-invoke (var-deref "clojure.core" "coll->cells") (step (jolt-rest s) prev)) (jolt-invoke (var-deref "clojure.core" "coll->cells") (jolt-cons x (step (jolt-rest s) x))))) jolt-nil))))))))) step))) (jolt-invoke (var-deref "clojure.core" "make-lazy-seq") (lambda () (let fnrec4444 () (let* ((s (jolt-seq coll))) (if (jolt-truthy? s) (jolt-invoke (var-deref "clojure.core" "coll->cells") (let* ((_a$4448 (jolt-first s)) (_a$4449 (let* ((_a$4445 step) (_a$4446 (jolt-rest s)) (_a$4447 (jolt-first s))) (jolt-invoke _a$4445 _a$4446 _a$4447)))) (jolt-cons _a$4448 _a$4449))) jolt-nil))))))))))) dedupe))) -(guard (e (#t #f)) - (def-var! "clojure.core" "seq-to-map-for-destructuring" (letrec ((seq-to-map-for-destructuring (lambda (s) (let fnrec4450 ((s s)) (if (jolt-truthy? (jolt-next s)) (let* ((m (jolt-hash-map)) (xs (jolt-seq s))) (let loop4451 ((m m) (xs xs)) (if (jolt-truthy? xs) (if (jolt-truthy? (jolt-next xs)) (let* ((_a$4455 (let* ((_a$4452 m) (_a$4453 (jolt-first xs)) (_a$4454 (jolt-invoke (var-deref "clojure.core" "second") xs))) (jolt-assoc _a$4452 _a$4453 _a$4454))) (_a$4456 (jolt-invoke (var-deref "clojure.core" "nnext") xs))) (loop4451 _a$4455 _a$4456)) (jolt-throw (jolt-invoke (var-deref "clojure.core" "str") "No value supplied for key: " (jolt-first xs)))) m))) (if (jolt-truthy? (jolt-seq s)) (jolt-first s) (jolt-hash-map))))))) seq-to-map-for-destructuring))) -(guard (e (#t #f)) - (def-var! "clojure.core" "vary-meta" (letrec ((vary-meta (lambda (obj f . args) (let fnrec4457 ((obj obj) (f f) (args (list->cseq args))) (jolt-invoke (var-deref "clojure.core" "with-meta") obj (jolt-apply f (jolt-invoke (var-deref "clojure.core" "meta") obj) args)))))) vary-meta))) -(guard (e (#t #f)) - (def-var! "clojure.core" "namespace-munge" (letrec ((namespace-munge (lambda (s) (let fnrec4458 ((s s)) (jolt-apply (var-deref "clojure.core" "str") (let* ((_a$4460 (lambda (c) (let fnrec4459 ((c c)) (if (jolt= c (integer->char 45)) (integer->char 95) c)))) (_a$4461 (jolt-seq (jolt-invoke (var-deref "clojure.core" "str") s)))) (jolt-map _a$4460 _a$4461))))))) namespace-munge))) -(guard (e (#t #f)) - (def-var! "clojure.core" "reduce-kv" (letrec ((reduce-kv (lambda (f init coll) (let fnrec4462 ((f f) (init init) (coll coll)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "vector?") coll)) (let* ((_a$4464 (lambda (acc i) (let fnrec4463 ((acc acc) (i i)) (jolt-invoke f acc i (jolt-nth coll i))))) (_a$4465 init) (_a$4466 (jolt-range (jolt-count coll)))) (jolt-reduce _a$4464 _a$4465 _a$4466)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "map?") coll)) (let* ((_a$4468 (lambda (acc k) (let fnrec4467 ((acc acc) (k k)) (jolt-invoke f acc k (jolt-get coll k))))) (_a$4469 init) (_a$4470 (jolt-keys coll))) (jolt-reduce _a$4468 _a$4469 _a$4470)) (if (jolt-nil? coll) init (if (jolt-truthy? (keyword #f "else")) (jolt-throw (jolt-invoke (var-deref "clojure.core" "str") "reduce-kv not supported on: " coll)) jolt-nil)))))))) reduce-kv))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "ex-info-val?" (letrec ((ex-info-val? (lambda (x) (let fnrec4471 ((x x)) (jolt= (jolt-get x (keyword "jolt" "type")) (keyword "jolt" "ex-info")))))) ex-info-val?) (let* ((_o$4472 (keyword #f "private")) (_o$4473 #t)) (jolt-hash-map _o$4472 _o$4473)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "ex-unwrap" (letrec ((ex-unwrap (lambda (e) (let fnrec4474 ((e e)) (if (jolt= (jolt-get e (keyword "jolt" "type")) (keyword "jolt" "exception")) (jolt-get e (keyword #f "value")) e))))) ex-unwrap) (let* ((_o$4475 (keyword #f "private")) (_o$4476 #t)) (jolt-hash-map _o$4475 _o$4476)))) -(guard (e (#t #f)) - (def-var! "clojure.core" "ex-data" (letrec ((ex-data (lambda (e) (let fnrec4477 ((e e)) (let* ((e (jolt-invoke (var-deref "clojure.core" "ex-unwrap") e))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "ex-info-val?") e)) (jolt-get e (keyword #f "data")) jolt-nil)))))) ex-data))) -(guard (e (#t #f)) - (def-var! "clojure.core" "ex-message" (letrec ((ex-message (lambda (e) (let fnrec4478 ((e e)) (let* ((e (jolt-invoke (var-deref "clojure.core" "ex-unwrap") e))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "ex-info-val?") e)) (jolt-get e (keyword #f "message")) (if (jolt-truthy? (keyword #f "else")) jolt-nil jolt-nil))))))) ex-message))) -(guard (e (#t #f)) - (def-var! "clojure.core" "ex-cause" (letrec ((ex-cause (lambda (e) (let fnrec4479 ((e e)) (let* ((e (jolt-invoke (var-deref "clojure.core" "ex-unwrap") e))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "ex-info-val?") e)) (jolt-get e (keyword #f "cause")) jolt-nil)))))) ex-cause))) -(guard (e (#t #f)) - (def-var! "clojure.core" "inst-ms" (letrec ((inst-ms (lambda (x) (let fnrec4480 ((x x)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "inst?") x)) (jolt-get x (keyword #f "ms")) (jolt-throw (jolt-invoke (var-deref "clojure.core" "str") "inst-ms requires an inst, got: " x))))))) inst-ms))) -(guard (e (#t #f)) - (def-var! "clojure.core" "update-keys" (letrec ((update-keys (lambda (m f) (let fnrec4481 ((m m) (f f)) (let* ((_a$4483 (var-deref "clojure.core" "reduce-kv")) (_a$4484 (lambda (acc k v) (let fnrec4482 ((acc acc) (k k) (v v)) (jolt-assoc acc (jolt-invoke f k) v)))) (_a$4485 (jolt-hash-map)) (_a$4486 m)) (jolt-invoke _a$4483 _a$4484 _a$4485 _a$4486)))))) update-keys))) -(guard (e (#t #f)) - (def-var! "clojure.core" "update-vals" (letrec ((update-vals (lambda (m f) (let fnrec4487 ((m m) (f f)) (let* ((_a$4489 (var-deref "clojure.core" "reduce-kv")) (_a$4490 (lambda (acc k v) (let fnrec4488 ((acc acc) (k k) (v v)) (jolt-assoc acc k (jolt-invoke f v))))) (_a$4491 (jolt-hash-map)) (_a$4492 m)) (jolt-invoke _a$4489 _a$4490 _a$4491 _a$4492)))))) update-vals))) -(guard (e (#t #f)) - (def-var! "clojure.core" "partitionv" (letrec ((partitionv (case-lambda ((n coll) (let fnrec4493 ((n n) (coll coll)) (jolt-map (var-deref "clojure.core" "vec") (jolt-invoke (var-deref "clojure.core" "partition") n coll)))) ((n step coll) (let fnrec4494 ((n n) (step step) (coll coll)) (jolt-map (var-deref "clojure.core" "vec") (jolt-invoke (var-deref "clojure.core" "partition") n step coll)))) ((n step pad coll) (let fnrec4495 ((n n) (step step) (pad pad) (coll coll)) (jolt-map (var-deref "clojure.core" "vec") (jolt-invoke (var-deref "clojure.core" "partition") n step pad coll))))))) partitionv))) -(guard (e (#t #f)) - (declare-var! "clojure.core" "partition-all")) -(guard (e (#t #f)) - (def-var! "clojure.core" "partitionv-all" (letrec ((partitionv-all (case-lambda ((n coll) (let fnrec4496 ((n n) (coll coll)) (jolt-map (var-deref "clojure.core" "vec") (jolt-invoke (var-deref "clojure.core" "partition-all") n coll)))) ((n step coll) (let fnrec4497 ((n n) (step step) (coll coll)) (jolt-map (var-deref "clojure.core" "vec") (jolt-invoke (var-deref "clojure.core" "partition-all") n step coll))))))) partitionv-all))) -(guard (e (#t #f)) - (def-var! "clojure.core" "splitv-at" (letrec ((splitv-at (lambda (n coll) (let fnrec4498 ((n n) (coll coll)) (let* ((_o$4499 (jolt-invoke (var-deref "clojure.core" "vec") (jolt-take n coll))) (_o$4500 (jolt-drop n coll))) (jolt-vector _o$4499 _o$4500)))))) splitv-at))) -(guard (e (#t #f)) - (def-var! "clojure.core" "with-redefs-fn" (letrec ((with-redefs-fn (lambda (binding-map func) (let fnrec4501 ((binding-map binding-map) (func func)) (let* ((vars (jolt-invoke (var-deref "clojure.core" "vec") (jolt-keys binding-map))) (saved (jolt-invoke (var-deref "clojure.core" "mapv") (var-deref "clojure.core" "var-get") vars))) (begin (begin (jolt-count (jolt-map (lambda (v) (let fnrec4502 ((v v)) (begin (jolt-invoke (var-deref "clojure.core" "var-set") v (jolt-get binding-map v)) jolt-nil))) vars)) jolt-nil) (dynamic-wind (lambda () #f) (lambda () (jolt-invoke func)) (lambda () (let* ((i 0)) (let loop4503 ((i i)) (if (jolt-n< i (jolt-count vars)) (begin (let* ((_a$4504 (var-deref "clojure.core" "var-set")) (_a$4505 (jolt-nth vars i)) (_a$4506 (jolt-nth saved i))) (jolt-invoke _a$4504 _a$4505 _a$4506)) (loop4503 (jolt-inc i))) jolt-nil))))))))))) with-redefs-fn))) -(guard (e (#t #f)) - (def-var! "clojure.core" "chunked-seq?" (letrec ((chunked-seq? (lambda (x) (let fnrec4507 ((x x)) #f)))) chunked-seq?))) -(guard (e (#t #f)) - (def-var! "clojure.core" "swap-vals!" (letrec ((swap-vals! (lambda (a f . args) (let fnrec4508 ((a a) (f f) (args (list->cseq args))) (let* ((old (jolt-invoke (var-deref "clojure.core" "deref") a))) (let* ((_o$4509 old) (_o$4510 (jolt-apply (var-deref "clojure.core" "swap!") a f args))) (jolt-vector _o$4509 _o$4510))))))) swap-vals!))) -(guard (e (#t #f)) - (def-var! "clojure.core" "reset-vals!" (letrec ((reset-vals! (lambda (a newval) (let fnrec4511 ((a a) (newval newval)) (let* ((old (jolt-invoke (var-deref "clojure.core" "deref") a))) (begin (jolt-invoke (var-deref "clojure.core" "reset!") a newval) (let* ((_o$4512 old) (_o$4513 newval)) (jolt-vector _o$4512 _o$4513)))))))) reset-vals!))) -(guard (e (#t #f)) - (def-var! "clojure.core" "compare-and-set!" (letrec ((compare-and-set! (lambda (a oldval newval) (let fnrec4514 ((a a) (oldval oldval) (newval newval)) (if (jolt= oldval (jolt-invoke (var-deref "clojure.core" "deref") a)) (begin (jolt-invoke (var-deref "clojure.core" "reset!") a newval) #t) #f))))) compare-and-set!))) -(guard (e (#t #f)) - (def-var! "clojure.core" "get-validator" (letrec ((get-validator (lambda (a) (let fnrec4515 ((a a)) (jolt-get a (keyword #f "validator")))))) get-validator))) -(guard (e (#t #f)) - (def-var! "clojure.core" "add-watch" (letrec ((add-watch (lambda (a key f) (let fnrec4516 ((a a) (key key) (f f)) (begin (jolt-invoke (var-deref "jolt.host" "ref-put!") (jolt-get a (keyword #f "watches")) key f) a))))) add-watch))) -(guard (e (#t #f)) - (def-var! "clojure.core" "remove-watch" (letrec ((remove-watch (lambda (a key) (let fnrec4517 ((a a) (key key)) (begin (jolt-invoke (var-deref "jolt.host" "ref-put!") (jolt-get a (keyword #f "watches")) key jolt-nil) a))))) remove-watch))) -(guard (e (#t #f)) - (def-var! "clojure.core" "set-validator!" (letrec ((set-validator! (lambda (a f) (let fnrec4518 ((a a) (f f)) (begin (jolt-invoke (var-deref "jolt.host" "ref-put!") a (keyword #f "validator") f) jolt-nil))))) set-validator!))) -(guard (e (#t #f)) - (def-var! "clojure.core" "future-done?" (letrec ((future-done? (lambda (x) (let fnrec4519 ((x x)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "future?") x)) (jolt-invoke (var-deref "clojure.core" "boolean") (jolt-get x (keyword #f "cached"))) (jolt-throw "future-done? requires a future")))))) future-done?))) -(guard (e (#t #f)) - (def-var! "clojure.core" "future-cancelled?" (letrec ((future-cancelled? (lambda (x) (let fnrec4520 ((x x)) (let* ((and__25__auto (jolt-invoke (var-deref "clojure.core" "future?") x))) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "clojure.core" "boolean") (jolt-get x (keyword #f "cancelled"))) and__25__auto)))))) future-cancelled?))) -(guard (e (#t #f)) - (def-var! "clojure.core" "ns-name" (letrec ((ns-name (lambda (ns) (let fnrec4521 ((ns ns)) (let* ((nm (jolt-get ns (keyword #f "name")))) (if (jolt-truthy? nm) (jolt-invoke (var-deref "clojure.core" "symbol") (jolt-invoke (var-deref "clojure.core" "str") nm)) jolt-nil)))))) ns-name))) -(guard (e (#t #f)) - (def-var! "clojure.core" "aget" (letrec ((aget (lambda (arr . idxs) (let fnrec4522 ((arr arr) (idxs (list->cseq idxs))) (jolt-reduce (lambda (v i) (let fnrec4523 ((v v) (i i)) (jolt-nth v i))) arr idxs))))) aget))) -(guard (e (#t #f)) - (def-var! "clojure.core" "alength" (letrec ((alength (lambda (arr) (let fnrec4524 ((arr arr)) (jolt-count arr))))) alength))) -(guard (e (#t #f)) - (def-var! "clojure.core" "aset" (letrec ((aset (lambda (arr . idxs+val) (let fnrec4525 ((arr arr) (idxs+val (list->cseq idxs+val))) (let* ((n (jolt-count idxs+val)) (val (jolt-nth idxs+val (jolt-dec n))) (target (let* ((_a$4527 (lambda (t k) (let fnrec4526 ((t t) (k k)) (jolt-nth t k)))) (_a$4528 arr) (_a$4529 (jolt-take (jolt-n- n 2) idxs+val))) (jolt-reduce _a$4527 _a$4528 _a$4529)))) (begin (jolt-invoke (var-deref "jolt.host" "ref-put!") target (jolt-nth idxs+val (jolt-n- n 2)) val) val)))))) aset))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "complement" (letrec ((complement (lambda (f) (let fnrec4530 ((f f)) (lambda args (let fnrec4531 ((args (list->cseq args))) (jolt-not (jolt-apply f args)))))))) complement) (let* ((_o$4532 (keyword #f "doc")) (_o$4533 "Takes a fn f and returns a fn that takes the same arguments as f, has the\n same effects, if any, and returns the opposite truth value.")) (jolt-hash-map _o$4532 _o$4533)))) -(guard (e (#t #f)) - (def-var! "clojure.core" "fnil" (letrec ((fnil (case-lambda ((f x) (let fnrec4534 ((f f) (x x)) (lambda (a . args) (let fnrec4535 ((a a) (args (list->cseq args))) (jolt-apply f (if (jolt-nil? a) x a) args))))) ((f x y) (let fnrec4536 ((f f) (x x) (y y)) (lambda (a b . args) (let fnrec4537 ((a a) (b b) (args (list->cseq args))) (let* ((_a$4538 f) (_a$4539 (if (jolt-nil? a) x a)) (_a$4540 (if (jolt-nil? b) y b)) (_a$4541 args)) (jolt-apply _a$4538 _a$4539 _a$4540 _a$4541)))))) ((f x y z) (let fnrec4542 ((f f) (x x) (y y) (z z)) (lambda (a b c . args) (let fnrec4543 ((a a) (b b) (c c) (args (list->cseq args))) (let* ((_a$4544 f) (_a$4545 (if (jolt-nil? a) x a)) (_a$4546 (if (jolt-nil? b) y b)) (_a$4547 (if (jolt-nil? c) z c)) (_a$4548 args)) (jolt-apply _a$4544 _a$4545 _a$4546 _a$4547 _a$4548))))))))) fnil))) -(guard (e (#t #f)) - (def-var! "clojure.core" "clojure-version" (letrec ((clojure-version (lambda () (let fnrec4549 () "1.11.0-jolt")))) clojure-version))) -(guard (e (#t #f)) - (def-var! "clojure.core" "supers" (letrec ((supers (lambda (x) (let fnrec4550 ((x x)) (let* ((s (jolt-invoke (var-deref "jolt.host" "class-supers") x))) (if (jolt-truthy? s) (jolt-invoke (var-deref "clojure.core" "set") s) (jolt-hash-set))))))) supers))) -(guard (e (#t #f)) - (def-var! "clojure.core" "munge" (letrec ((munge (lambda (s) (let fnrec4551 ((s s)) (let* ((m (jolt-invoke (var-deref "clojure.core" "str-replace-all") "-" "_" (jolt-invoke (var-deref "clojure.core" "str") s)))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "symbol?") s)) (jolt-invoke (var-deref "clojure.core" "symbol") m) m)))))) munge))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "test" (letrec ((test (lambda (v) (let fnrec4552 ((v v)) (let* ((t (jolt-get (jolt-invoke (var-deref "clojure.core" "meta") v) (keyword #f "test")))) (if (jolt-truthy? t) (begin (jolt-invoke t) (keyword #f "ok")) (keyword #f "no-test"))))))) test) (let* ((_o$4553 (keyword #f "doc")) (_o$4554 "Calls the :test fn from v's metadata; :ok if it runs, :no-test if absent.")) (jolt-hash-map _o$4553 _o$4554)))) -(guard (e (#t #f)) - (def-var! "clojure.core" "find" (letrec ((find (lambda (m k) (let fnrec4555 ((m m) (k k)) (if (jolt-contains? m k) (jolt-first (let* ((_o$4556 k) (_o$4557 (jolt-get m k))) (jolt-hash-map _o$4556 _o$4557))) jolt-nil))))) find))) -(guard (e (#t #f)) - (def-var! "clojure.core" "true?" (letrec ((true? (lambda (x) (let fnrec4558 ((x x)) (jolt= #t x))))) true?))) -(guard (e (#t #f)) - (def-var! "clojure.core" "false?" (letrec ((false? (lambda (x) (let fnrec4559 ((x x)) (jolt= #f x))))) false?))) -(guard (e (#t #f)) - (def-var! "clojure.core" "select-keys" (letrec ((select-keys (lambda (map keyseq) (let fnrec4560 ((map map) (keyseq keyseq)) (let* ((_a$4562 (lambda (m k) (let fnrec4561 ((m m) (k k)) (if (jolt-contains? map k) (jolt-assoc m k (jolt-get map k)) m)))) (_a$4563 (jolt-hash-map)) (_a$4564 keyseq)) (jolt-reduce _a$4562 _a$4563 _a$4564)))))) select-keys))) -(guard (e (#t #f)) - (def-var! "clojure.core" "zipmap" (letrec ((zipmap (lambda (keys vals) (let fnrec4565 ((keys keys) (vals vals)) (let* ((m (jolt-hash-map)) (ks (jolt-seq keys)) (vs (jolt-seq vals))) (let loop4566 ((m m) (ks ks) (vs vs)) (if (jolt-truthy? (let* ((and__25__auto ks)) (if (jolt-truthy? and__25__auto) vs and__25__auto))) (let* ((_a$4570 (let* ((_a$4567 m) (_a$4568 (jolt-first ks)) (_a$4569 (jolt-first vs))) (jolt-assoc _a$4567 _a$4568 _a$4569))) (_a$4571 (jolt-next ks)) (_a$4572 (jolt-next vs))) (loop4566 _a$4570 _a$4571 _a$4572)) m))))))) zipmap))) -(guard (e (#t #f)) - (def-var! "clojure.core" "create-struct" (letrec ((create-struct (lambda keys (let fnrec4573 ((keys (list->cseq keys))) (jolt-invoke (var-deref "clojure.core" "vec") keys))))) create-struct))) -(guard (e (#t #f)) - (def-var! "clojure.core" "struct-map" (letrec ((struct-map (lambda (basis . inits) (let fnrec4574 ((basis basis) (inits (list->cseq inits))) (let* ((base (let* ((m (jolt-hash-map)) (ks (jolt-seq basis))) (let loop4575 ((m m) (ks ks)) (if (jolt-truthy? ks) (let* ((_a$4576 (jolt-assoc m (jolt-first ks) jolt-nil)) (_a$4577 (jolt-next ks))) (loop4575 _a$4576 _a$4577)) m))))) (let* ((m base) (kvs (jolt-seq inits))) (let loop4578 ((m m) (kvs kvs)) (if (jolt-truthy? kvs) (let* ((_a$4582 (let* ((_a$4579 m) (_a$4580 (jolt-first kvs)) (_a$4581 (jolt-first (jolt-next kvs)))) (jolt-assoc _a$4579 _a$4580 _a$4581))) (_a$4583 (jolt-next (jolt-next kvs)))) (loop4578 _a$4582 _a$4583)) m)))))))) struct-map))) -(guard (e (#t #f)) - (def-var! "clojure.core" "struct" (letrec ((struct (lambda (basis . vals) (let fnrec4584 ((basis basis) (vals (list->cseq vals))) (let* ((m (jolt-invoke (var-deref "clojure.core" "struct-map") basis)) (ks (jolt-seq basis)) (vs (jolt-seq vals))) (let loop4585 ((m m) (ks ks) (vs vs)) (if (jolt-truthy? (let* ((and__25__auto ks)) (if (jolt-truthy? and__25__auto) vs and__25__auto))) (let* ((_a$4589 (let* ((_a$4586 m) (_a$4587 (jolt-first ks)) (_a$4588 (jolt-first vs))) (jolt-assoc _a$4586 _a$4587 _a$4588))) (_a$4590 (jolt-next ks)) (_a$4591 (jolt-next vs))) (loop4585 _a$4589 _a$4590 _a$4591)) m))))))) struct))) -(guard (e (#t #f)) - (def-var! "clojure.core" "accessor" (letrec ((accessor (lambda (basis key) (let fnrec4592 ((basis basis) (key key)) (lambda (m) (let fnrec4593 ((m m)) (jolt-get m key))))))) accessor))) -(guard (e (#t #f)) - (def-var! "clojure.core" "merge" (letrec ((merge (lambda maps (let fnrec4594 ((maps (list->cseq maps))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "some") jolt-identity maps)) (jolt-reduce (lambda (acc m) (let fnrec4595 ((acc acc) (m m)) (if (jolt-nil? m) acc (jolt-conj (let* ((or__26__auto acc)) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-hash-map))) m)))) maps) jolt-nil))))) merge))) -(guard (e (#t #f)) - (def-var! "clojure.core" "merge-with" (letrec ((merge-with (lambda (f . maps) (let fnrec4596 ((f f) (maps (list->cseq maps))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "some") jolt-identity maps)) (let* ((merge-entry (lambda (m e) (let fnrec4597 ((m m) (e e)) (let* ((k (jolt-invoke (var-deref "clojure.core" "key") e)) (v (jolt-invoke (var-deref "clojure.core" "val") e))) (if (jolt-contains? m k) (jolt-assoc m k (jolt-invoke f (jolt-get m k) v)) (jolt-assoc m k v)))))) (merge2 (lambda (m1 m2) (let fnrec4598 ((m1 m1) (m2 m2)) (let* ((_a$4599 merge-entry) (_a$4600 (let* ((or__26__auto m1)) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-hash-map)))) (_a$4601 (jolt-seq m2))) (jolt-reduce _a$4599 _a$4600 _a$4601)))))) (jolt-reduce merge2 maps)) jolt-nil))))) merge-with))) -(guard (e (#t #f)) - (def-var! "clojure.core" "get-in" (letrec ((get-in (case-lambda ((m ks) (let fnrec4602 ((m m) (ks ks)) (jolt-reduce jolt-get m ks))) ((m ks not-found) (let fnrec4603 ((m m) (ks ks) (not-found not-found)) (let* ((sentinel (jolt-hash-map-fn ))) (let* ((m m) (ks (jolt-seq ks))) (let loop4604 ((m m) (ks ks)) (if (jolt-truthy? ks) (let* ((nxt (jolt-get m (jolt-first ks) sentinel))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "identical?") sentinel nxt)) not-found (loop4604 nxt (jolt-next ks)))) m))))))))) get-in))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "req!" (letrec ((req! (lambda (m k) (let fnrec4605 ((m m) (k k)) (let* ((sentinel (jolt-hash-map-fn )) (v (jolt-get m k sentinel))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "identical?") sentinel v)) (jolt-throw (host-new "IllegalArgumentException" (jolt-invoke (var-deref "clojure.core" "str") "Expected key: " k))) v)))))) req!) (let* ((_o$4606 (keyword #f "added")) (_o$4607 "1.13") (_o$4608 (keyword #f "doc")) (_o$4609 "Returns the value mapped to key k in map m, like `get`, but throws\n IllegalArgumentException when k is not present. Unlike `get`, does not nil-pun:\n a key present with a nil value returns nil, an absent key throws. The primitive\n behind checked-keys destructuring (:keys! / :syms! / :strs!).")) (jolt-hash-map _o$4606 _o$4607 _o$4608 _o$4609)))) -(guard (e (#t #f)) - (def-var! "clojure.core" "memoize" (letrec ((memoize (lambda (f) (let fnrec4610 ((f f)) (let* ((mem (jolt-invoke (var-deref "clojure.core" "atom") (jolt-hash-map-fn )))) (lambda args (let fnrec4611 ((args (list->cseq args))) (let* ((e (jolt-invoke (var-deref "clojure.core" "find") (jolt-invoke (var-deref "clojure.core" "deref") mem) args))) (if (jolt-truthy? e) (jolt-invoke (var-deref "clojure.core" "val") e) (let* ((ret (jolt-apply f args))) (begin (jolt-invoke (var-deref "clojure.core" "swap!") mem jolt-assoc args ret) ret))))))))))) memoize))) -(guard (e (#t #f)) - (def-var! "clojure.core" "partial" (letrec ((partial (case-lambda ((f) (let fnrec4612 ((f f)) f)) ((f a) (let fnrec4613 ((f f) (a a)) (lambda args (let fnrec4614 ((args (list->cseq args))) (jolt-apply f a args))))) ((f a b) (let fnrec4615 ((f f) (a a) (b b)) (lambda args (let fnrec4616 ((args (list->cseq args))) (jolt-apply f a b args))))) ((f a b c) (let fnrec4617 ((f f) (a a) (b b) (c c)) (lambda args (let fnrec4618 ((args (list->cseq args))) (jolt-apply f a b c args))))) ((f a b c . more) (let fnrec4619 ((f f) (a a) (b b) (c c) (more (list->cseq more))) (lambda args (let fnrec4620 ((args (list->cseq args))) (jolt-apply f a b c (jolt-concat more args))))))))) partial))) -(guard (e (#t #f)) - (def-var! "clojure.core" "trampoline" (letrec ((trampoline (case-lambda ((f) (let fnrec4621 ((f f)) (let* ((ret (jolt-invoke f))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "fn?") ret)) (trampoline ret) ret)))) ((f . args) (let fnrec4622 ((f f) (args (list->cseq args))) (trampoline (lambda () (let fnrec4623 () (jolt-apply f args))))))))) trampoline))) -(guard (e (#t #f)) - (def-var! "clojure.core" "max" (letrec ((max (case-lambda ((x) (let fnrec4624 ((x x)) x)) ((x y) (let fnrec4625 ((x x) (y y)) (if (jolt-n> x y) x y))) ((x y . more) (let fnrec4626 ((x x) (y y) (more (list->cseq more))) (jolt-reduce max (max x y) more)))))) max))) -(guard (e (#t #f)) - (def-var! "clojure.core" "min" (letrec ((min (case-lambda ((x) (let fnrec4627 ((x x)) x)) ((x y) (let fnrec4628 ((x x) (y y)) (if (jolt-n< x y) x y))) ((x y . more) (let fnrec4629 ((x x) (y y) (more (list->cseq more))) (jolt-reduce min (min x y) more)))))) min))) -(guard (e (#t #f)) - (def-var! "clojure.core" "reverse" (letrec ((reverse (lambda (coll) (let fnrec4630 ((coll coll)) (jolt-reduce jolt-conj (jolt-list ) coll))))) reverse))) -(guard (e (#t #f)) - (def-var! "clojure.core" "empty" (letrec ((empty (lambda (coll) (let fnrec4631 ((coll coll)) (if (jolt-nil? coll) jolt-nil (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "jrec-method?") coll "empty")) (record-method-dispatch coll "empty" (jolt-vector)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "record?") coll)) (jolt-throw (host-new "UnsupportedOperationException" (jolt-invoke (var-deref "clojure.core" "str") "Can't create empty: " (record-method-dispatch (jolt-invoke (var-deref "clojure.core" "class") coll) "getName" (jolt-vector))))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "sorted?") coll)) (jolt-invoke (jolt-get (jolt-invoke (var-deref "jolt.host" "ref-get") coll (keyword #f "ops")) (keyword #f "empty")) coll) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "map?") coll)) (let* ((_a$4632 (var-deref "clojure.core" "with-meta")) (_a$4633 (jolt-hash-map)) (_a$4634 (jolt-invoke (var-deref "clojure.core" "meta") coll))) (jolt-invoke _a$4632 _a$4633 _a$4634)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "set?") coll)) (let* ((_a$4635 (var-deref "clojure.core" "with-meta")) (_a$4636 (jolt-hash-set)) (_a$4637 (jolt-invoke (var-deref "clojure.core" "meta") coll))) (jolt-invoke _a$4635 _a$4636 _a$4637)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "vector?") coll)) (let* ((_a$4638 (var-deref "clojure.core" "with-meta")) (_a$4639 (jolt-vector)) (_a$4640 (jolt-invoke (var-deref "clojure.core" "meta") coll))) (jolt-invoke _a$4638 _a$4639 _a$4640)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "coll?") coll)) (jolt-invoke (var-deref "clojure.core" "with-meta") (jolt-list ) (jolt-invoke (var-deref "clojure.core" "meta") coll)) (if (jolt-truthy? (keyword #f "else")) jolt-nil jolt-nil))))))))))))) empty))) -(guard (e (#t #f)) - (def-var! "clojure.core" "assoc-in" (letrec ((assoc-in (lambda (m G__133 v) (let fnrec4641 ((m m) (G__133 G__133) (v v)) (let* ((G__134 G__133) (k (jolt-nth G__134 0 jolt-nil)) (ks (jolt-invoke (var-deref "clojure.core" "nthnext") G__134 1))) (if (jolt-truthy? ks) (jolt-assoc m k (assoc-in (jolt-get m k) ks v)) (jolt-assoc m k v))))))) assoc-in))) -(guard (e (#t #f)) - (def-var! "clojure.core" "update-in" (letrec ((update-in (lambda (m ks f . args) (let fnrec4642 ((m m) (ks ks) (f f) (args (list->cseq args))) (let* ((up (letrec ((up (lambda (m ks f args) (let fnrec4643 ((m m) (ks ks) (f f) (args args)) (let* ((G__135 ks) (k (jolt-nth G__135 0 jolt-nil)) (ks (jolt-invoke (var-deref "clojure.core" "nthnext") G__135 1))) (if (jolt-truthy? ks) (jolt-assoc m k (up (jolt-get m k) ks f args)) (jolt-assoc m k (jolt-apply f (jolt-get m k) args)))))))) up))) (jolt-invoke up m ks f args)))))) update-in))) -(guard (e (#t #f)) - (def-var! "clojure.core" "find-keyword" (letrec ((find-keyword (case-lambda ((nm) (let fnrec4644 ((nm nm)) (jolt-invoke (var-deref "clojure.core" "keyword") nm))) ((ns nm) (let fnrec4645 ((ns ns) (nm nm)) (jolt-invoke (var-deref "clojure.core" "keyword") ns nm)))))) find-keyword))) -(guard (e (#t #f)) - (def-var! "clojure.core" "inst-ms*" (letrec ((inst-ms* (lambda (i) (let fnrec4646 ((i i)) (jolt-invoke (var-deref "clojure.core" "inst-ms") i))))) inst-ms*))) -(guard (e (#t #f)) - (def-var! "clojure.core" "comp" (letrec ((comp (case-lambda (() (let fnrec4647 () jolt-identity)) ((f) (let fnrec4648 ((f f)) f)) ((f g) (let fnrec4649 ((f f) (g g)) (case-lambda (() (let fnrec4650 () (jolt-invoke f (jolt-invoke g)))) ((x) (let fnrec4651 ((x x)) (jolt-invoke f (jolt-invoke g x)))) ((x y) (let fnrec4652 ((x x) (y y)) (jolt-invoke f (jolt-invoke g x y)))) ((x y z) (let fnrec4653 ((x x) (y y) (z z)) (jolt-invoke f (jolt-invoke g x y z)))) ((x y z . args) (let fnrec4654 ((x x) (y y) (z z) (args (list->cseq args))) (jolt-invoke f (jolt-apply g x y z args))))))) ((f g . fs) (let fnrec4655 ((f f) (g g) (fs (list->cseq fs))) (jolt-reduce comp (comp f g) fs)))))) comp))) -(guard (e (#t #f)) - (def-var! "clojure.core" "ifn?" (letrec ((ifn? (lambda (x) (let fnrec4656 ((x x)) (if (jolt-truthy? (let* ((or__26__auto (jolt-invoke (var-deref "clojure.core" "fn?") x))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt-invoke (var-deref "clojure.core" "keyword?") x))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt-invoke (var-deref "clojure.core" "symbol?") x))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt-invoke (var-deref "clojure.core" "map?") x))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt-invoke (var-deref "clojure.core" "set?") x))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt-invoke (var-deref "clojure.core" "vector?") x))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt-invoke (var-deref "clojure.core" "var?") x))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt-invoke (var-deref "jolt.host" "callable-host?") x))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-invoke (var-deref "jolt.host" "jrec-method?") x "invoke")))))))))))))))))) #t #f))))) ifn?))) -(guard (e (#t #f)) - (def-var! "clojure.core" "+'" jolt-add)) -(guard (e (#t #f)) - (def-var! "clojure.core" "-'" jolt-sub)) -(guard (e (#t #f)) - (def-var! "clojure.core" "*'" jolt-mul)) -(guard (e (#t #f)) - (def-var! "clojure.core" "inc'" jolt-inc)) -(guard (e (#t #f)) - (def-var! "clojure.core" "dec'" jolt-dec)) -(guard (e (#t #f)) - (def-var! "clojure.core" "int?" (letrec ((int? (lambda (x) (let fnrec4657 ((x x)) (jolt-invoke (var-deref "clojure.core" "integer?") x))))) int?))) -(guard (e (#t #f)) - (def-var! "clojure.core" "num" (letrec ((num (lambda (x) (let fnrec4658 ((x x)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "number?") x)) x (jolt-throw (jolt-invoke (var-deref "clojure.core" "str") "num requires a number, got: " x))))))) num))) -(guard (e (#t #f)) - (def-var! "clojure.core" "==" (letrec ((== (case-lambda ((x) (let fnrec4659 ((x x)) #t)) ((x y) (let fnrec4660 ((x x) (y y)) (if (jolt-truthy? (let* ((and__25__auto (jolt-invoke (var-deref "clojure.core" "number?") x))) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "clojure.core" "number?") y) and__25__auto))) (jolt= x y) (jolt-throw (jolt-invoke (var-deref "clojure.core" "str") "Cannot cast to number: " (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "number?") x)) y x)))))) ((x y . more) (let fnrec4661 ((x x) (y y) (more (list->cseq more))) (if (jolt-truthy? (== x y)) (jolt-apply == y more) #f)))))) ==))) -(guard (e (#t #f)) - (def-var! "clojure.core" "ensure-reduced" (letrec ((ensure-reduced (lambda (x) (let fnrec4662 ((x x)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "reduced?") x)) x (jolt-invoke (var-deref "clojure.core" "reduced") x)))))) ensure-reduced))) -(guard (e (#t #f)) - (def-var! "clojure.core" "halt-when" (letrec ((halt-when (case-lambda ((pred) (let fnrec4663 ((pred pred)) (halt-when pred jolt-nil))) ((pred retf) (let fnrec4664 ((pred pred) (retf retf)) (lambda (rf) (let fnrec4665 ((rf rf)) (case-lambda (() (let fnrec4666 () (jolt-invoke rf))) ((result) (let fnrec4667 ((result result)) (if (jolt-truthy? (let* ((and__25__auto (jolt-invoke (var-deref "clojure.core" "map?") result))) (if (jolt-truthy? and__25__auto) (jolt-contains? result (keyword "clojure.core" "halt")) and__25__auto))) (jolt-get result (keyword "clojure.core" "halt")) (jolt-invoke rf result)))) ((result input) (let fnrec4668 ((result result) (input input)) (if (jolt-truthy? (jolt-invoke pred input)) (jolt-invoke (var-deref "clojure.core" "reduced") (jolt-hash-map-fn (keyword "clojure.core" "halt") (if (jolt-truthy? retf) (jolt-invoke retf (jolt-invoke rf result) input) input))) (jolt-invoke rf result input)))))))))))) halt-when))) -(guard (e (#t #f)) - (def-var! "clojure.core" "parse-boolean" (letrec ((parse-boolean (lambda (s) (let fnrec4669 ((s s)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "string?") s)) (if (jolt= s "true") #t (if (jolt= s "false") #f (if (jolt-truthy? (keyword #f "else")) jolt-nil jolt-nil))) (jolt-throw (jolt-invoke (var-deref "clojure.core" "str") "parse-boolean requires a string, got: " s))))))) parse-boolean))) -(guard (e (#t #f)) - (def-var! "clojure.core" "newline" (letrec ((newline (lambda () (let fnrec4670 () (begin (jolt-invoke (var-deref "clojure.core" "print") "\n") jolt-nil))))) newline))) -(guard (e (#t #f)) - (def-var! "clojure.core" "seque" (letrec ((seque (case-lambda ((s) (let fnrec4671 ((s s)) s)) ((n-or-q s) (let fnrec4672 ((n-or-q n-or-q) (s s)) s))))) seque))) -(guard (e (#t #f)) - (def-var! "clojure.core" "array-seq" (letrec ((array-seq (lambda (arr . _) (let fnrec4673 ((arr arr) (_ (list->cseq _))) (jolt-seq arr))))) array-seq))) -(guard (e (#t #f)) - (def-var! "clojure.core" "to-array-2d" (letrec ((to-array-2d (lambda (coll) (let fnrec4674 ((coll coll)) (jolt-invoke (var-deref "clojure.core" "to-array") (jolt-map (var-deref "clojure.core" "to-array") coll)))))) to-array-2d))) -(guard (e (#t #f)) - (def-var! "clojure.core" "unchecked-byte" (letrec ((unchecked-byte (lambda (x) (let fnrec4675 ((x x)) (let* ((b (bitwise-and (jolt-invoke (var-deref "clojure.core" "unchecked-long") x) 255))) (if (jolt-n< b 128) b (jolt-n- b 256))))))) unchecked-byte))) -(guard (e (#t #f)) - (def-var! "clojure.core" "unchecked-short" (letrec ((unchecked-short (lambda (x) (let fnrec4676 ((x x)) (let* ((s (bitwise-and (jolt-invoke (var-deref "clojure.core" "unchecked-long") x) 65535))) (if (jolt-n< s 32768) s (jolt-n- s 65536))))))) unchecked-short))) -(guard (e (#t #f)) - (def-var! "clojure.core" "unchecked-char" (letrec ((unchecked-char (lambda (x) (let fnrec4677 ((x x)) (jolt-invoke (var-deref "clojure.core" "char") (bitwise-and (jolt-invoke (var-deref "clojure.core" "unchecked-long") x) 65535)))))) unchecked-char))) -(guard (e (#t #f)) - (def-var! "clojure.core" "unchecked-float" (letrec ((unchecked-float (lambda (x) (let fnrec4678 ((x x)) (jolt-invoke (var-deref "clojure.core" "double") x))))) unchecked-float))) -(guard (e (#t #f)) - (def-var! "clojure.core" "unchecked-double" (letrec ((unchecked-double (lambda (x) (let fnrec4679 ((x x)) (jolt-invoke (var-deref "clojure.core" "double") x))))) unchecked-double))) -(guard (e (#t #f)) - (def-var! "clojure.core" "transduce" (letrec ((transduce (case-lambda ((xform f coll) (let fnrec4680 ((xform xform) (f f) (coll coll)) (transduce xform f (jolt-invoke f) coll))) ((xform f init coll) (let fnrec4681 ((xform xform) (f f) (init init) (coll coll)) (let* ((xf (jolt-invoke xform f))) (jolt-invoke xf (jolt-reduce xf init coll)))))))) transduce))) -(guard (e (#t #f)) - (def-var! "clojure.core" "eduction" (letrec ((eduction (lambda args (let fnrec4682 ((args (list->cseq args))) (let* ((coll (jolt-last args)) (xforms (jolt-invoke (var-deref "clojure.core" "butlast") args))) (if (jolt-truthy? xforms) (jolt-invoke (var-deref "clojure.core" "sequence") (jolt-apply (var-deref "clojure.core" "comp") xforms) coll) (jolt-invoke (var-deref "clojure.core" "sequence") coll))))))) eduction))) -(guard (e (#t #f)) - (def-var! "clojure.core" "->Eduction" (letrec ((->Eduction (lambda (xform coll) (let fnrec4683 ((xform xform) (coll coll)) (jolt-invoke (var-deref "clojure.core" "sequence") xform coll))))) ->Eduction))) -(guard (e (#t #f)) - (def-var! "clojure.core" "enumeration-seq" (letrec ((enumeration-seq (lambda (e) (let fnrec4684 ((e e)) (if (jolt-truthy? (let* ((or__26__auto (jolt-nil? e))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt-invoke (var-deref "clojure.core" "seq?") e))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-invoke (var-deref "clojure.core" "sequential?") e)))))) (jolt-seq e) (jolt-invoke (var-deref "clojure.core" "make-lazy-seq") (lambda () (let fnrec4685 () (jolt-invoke (var-deref "clojure.core" "coll->cells") (if (jolt-truthy? (record-method-dispatch e "hasMoreElements" (jolt-vector))) (let* ((_a$4686 (record-method-dispatch e "nextElement" (jolt-vector))) (_a$4687 (enumeration-seq e))) (jolt-cons _a$4686 _a$4687)) jolt-nil)))))))))) enumeration-seq))) -(guard (e (#t #f)) - (def-var! "clojure.core" "iterator-seq" (letrec ((iterator-seq (lambda (i) (let fnrec4688 ((i i)) (jolt-seq i))))) iterator-seq))) -(guard (e (#t #f)) - (def-var! "clojure.core" "promise" (letrec ((promise (lambda () (let fnrec4689 () (jolt-invoke (var-deref "clojure.core" "atom") jolt-nil))))) promise))) -(guard (e (#t #f)) - (def-var! "clojure.core" "deliver" (letrec ((deliver (lambda (p v) (let fnrec4690 ((p p) (v v)) (begin (jolt-invoke (var-deref "clojure.core" "reset!") p v) p))))) deliver))) -(guard (e (#t #f)) - (def-var! "clojure.core" "bean" (letrec ((bean (lambda (x) (let fnrec4691 ((x x)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "map?") x)) x (jolt-hash-map)))))) bean))) -(guard (e (#t #f)) - (def-var! "clojure.core" "uri?" (letrec ((uri? (lambda (x) (let fnrec4692 ((x x)) #f)))) uri?))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "special-syms" (let* ((_o$4693 (jolt-symbol #f "if")) (_o$4694 (jolt-symbol #f "do")) (_o$4695 (jolt-symbol #f "let*")) (_o$4696 (jolt-symbol #f "fn*")) (_o$4697 (jolt-symbol #f "quote")) (_o$4698 (jolt-symbol #f "var")) (_o$4699 (jolt-symbol #f "def")) (_o$4700 (jolt-symbol #f "loop*")) (_o$4701 (jolt-symbol #f "recur")) (_o$4702 (jolt-symbol #f "throw")) (_o$4703 (jolt-symbol #f "try")) (_o$4704 (jolt-symbol #f "catch")) (_o$4705 (jolt-symbol #f "finally")) (_o$4706 (jolt-symbol #f "new")) (_o$4707 (jolt-symbol #f "set!")) (_o$4708 (jolt-symbol #f ".")) (_o$4709 (jolt-symbol #f "monitor-enter")) (_o$4710 (jolt-symbol #f "monitor-exit")) (_o$4711 (jolt-symbol #f "&")) (_o$4712 (jolt-symbol #f "case*")) (_o$4713 (jolt-symbol #f "deftype*")) (_o$4714 (jolt-symbol #f "letfn*")) (_o$4715 (jolt-symbol #f "reify*"))) (jolt-hash-set _o$4693 _o$4694 _o$4695 _o$4696 _o$4697 _o$4698 _o$4699 _o$4700 _o$4701 _o$4702 _o$4703 _o$4704 _o$4705 _o$4706 _o$4707 _o$4708 _o$4709 _o$4710 _o$4711 _o$4712 _o$4713 _o$4714 _o$4715)) (let* ((_o$4716 (keyword #f "private")) (_o$4717 #t)) (jolt-hash-map _o$4716 _o$4717)))) -(guard (e (#t #f)) - (def-var! "clojure.core" "special-symbol?" (letrec ((special-symbol? (lambda (s) (let fnrec4718 ((s s)) (jolt-contains? (var-deref "clojure.core" "special-syms") s))))) special-symbol?))) -(guard (e (#t #f)) - (def-var! "clojure.core" "proxy-mappings" (letrec ((proxy-mappings (lambda (p) (let fnrec4719 ((p p)) (jolt-hash-map))))) proxy-mappings))) -(guard (e (#t #f)) - (def-var! "clojure.core" "proxy-call-with-super" (letrec ((proxy-call-with-super (lambda (f p meth) (let fnrec4720 ((f f) (p p) (meth meth)) (jolt-invoke f))))) proxy-call-with-super))) -(guard (e (#t #f)) - (def-var! "clojure.core" "init-proxy" (letrec ((init-proxy (lambda (p mappings) (let fnrec4721 ((p p) (mappings mappings)) p)))) init-proxy))) -(guard (e (#t #f)) - (def-var! "clojure.core" "update-proxy" (letrec ((update-proxy (lambda (p mappings) (let fnrec4722 ((p p) (mappings mappings)) p)))) update-proxy))) -(guard (e (#t #f)) - (def-var! "clojure.core" "proxy-super" (letrec ((proxy-super (lambda args (let fnrec4723 ((args (list->cseq args))) (jolt-throw "proxy-super: JVM proxies are not supported in Jolt"))))) proxy-super))) -(guard (e (#t #f)) - (def-var! "clojure.core" "construct-proxy" (letrec ((construct-proxy (lambda (c . args) (let fnrec4724 ((c c) (args (list->cseq args))) (jolt-throw "construct-proxy: not supported in Jolt"))))) construct-proxy))) -(guard (e (#t #f)) - (def-var! "clojure.core" "get-proxy-class" (letrec ((get-proxy-class (lambda interfaces (let fnrec4725 ((interfaces (list->cseq interfaces))) (jolt-throw "get-proxy-class: not supported in Jolt"))))) get-proxy-class))) -(guard (e (#t #f)) - (def-var! "clojure.core" "requiring-resolve" (letrec ((requiring-resolve (lambda (sym) (let fnrec4726 ((sym sym)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "qualified-symbol?") sym)) (let* ((or__26__auto (jolt-invoke (var-deref "clojure.core" "resolve") sym))) (if (jolt-truthy? or__26__auto) or__26__auto (begin (jolt-invoke (var-deref "clojure.core" "require") (jolt-invoke (var-deref "clojure.core" "symbol") (jolt-invoke (var-deref "clojure.core" "namespace") sym))) (jolt-invoke (var-deref "clojure.core" "resolve") sym)))) (jolt-throw (host-new "IllegalArgumentException" (jolt-invoke (var-deref "clojure.core" "str") "Not a qualified symbol: " sym)))))))) requiring-resolve))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "sfield" (letrec ((sfield (lambda (sc k) (let fnrec2750 ((sc sc) (k k)) (jolt-invoke (var-deref "jolt.host" "ref-get") sc k))))) sfield) (let* ((_o$2751 (keyword #f "private")) (_o$2752 #t)) (jolt-hash-map _o$2751 _o$2752)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "fn->cmp" (letrec ((fn->cmp (lambda (f) (let fnrec2753 ((f f)) (lambda (a b) (let fnrec2754 ((a a) (b b)) (let* ((r (jolt-invoke f a b))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "number?") r)) r (if (jolt-truthy? r) -1 (if (jolt-truthy? (jolt-invoke f b a)) 1 0)))))))))) fn->cmp) (let* ((_o$2755 (keyword #f "private")) (_o$2756 #t)) (jolt-hash-map _o$2755 _o$2756)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "the-cmp" (letrec ((the-cmp (lambda (sc) (let fnrec2757 ((sc sc)) (let* ((or__26__auto (jolt-invoke (var-deref "clojure.core" "sfield") sc (keyword #f "cmp")))) (if (jolt-truthy? or__26__auto) or__26__auto (var-deref "clojure.core" "compare"))))))) the-cmp) (let* ((_o$2758 (keyword #f "private")) (_o$2759 #t)) (jolt-hash-map _o$2758 _o$2759)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "nd-key" (letrec ((nd-key (lambda (n) (let fnrec2760 ((n n)) (jolt-nth n 1))))) nd-key) (let* ((_o$2761 (keyword #f "private")) (_o$2762 #t)) (jolt-hash-map _o$2761 _o$2762)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "nd-val" (letrec ((nd-val (lambda (n) (let fnrec2763 ((n n)) (jolt-nth n 2))))) nd-val) (let* ((_o$2764 (keyword #f "private")) (_o$2765 #t)) (jolt-hash-map _o$2764 _o$2765)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "nd-left" (letrec ((nd-left (lambda (n) (let fnrec2766 ((n n)) (jolt-nth n 3))))) nd-left) (let* ((_o$2767 (keyword #f "private")) (_o$2768 #t)) (jolt-hash-map _o$2767 _o$2768)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "nd-right" (letrec ((nd-right (lambda (n) (let fnrec2769 ((n n)) (jolt-nth n 4))))) nd-right) (let* ((_o$2770 (keyword #f "private")) (_o$2771 #t)) (jolt-hash-map _o$2770 _o$2771)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "red?" (letrec ((red? (lambda (n) (let fnrec2772 ((n n)) (let* ((and__25__auto n)) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "clojure.core" "identical?") (keyword #f "red") (jolt-nth n 0)) and__25__auto)))))) red?) (let* ((_o$2773 (keyword #f "private")) (_o$2774 #t)) (jolt-hash-map _o$2773 _o$2774)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "black?" (letrec ((black? (lambda (n) (let fnrec2775 ((n n)) (let* ((and__25__auto n)) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "clojure.core" "identical?") (keyword #f "black") (jolt-nth n 0)) and__25__auto)))))) black?) (let* ((_o$2776 (keyword #f "private")) (_o$2777 #t)) (jolt-hash-map _o$2776 _o$2777)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "mk-red" (letrec ((mk-red (lambda (k v l r) (let fnrec2778 ((k k) (v v) (l l) (r r)) (let* ((_o$2779 (keyword #f "red")) (_o$2780 k) (_o$2781 v) (_o$2782 l) (_o$2783 r)) (jolt-vector _o$2779 _o$2780 _o$2781 _o$2782 _o$2783)))))) mk-red) (let* ((_o$2784 (keyword #f "private")) (_o$2785 #t)) (jolt-hash-map _o$2784 _o$2785)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "mk-black" (letrec ((mk-black (lambda (k v l r) (let fnrec2786 ((k k) (v v) (l l) (r r)) (let* ((_o$2787 (keyword #f "black")) (_o$2788 k) (_o$2789 v) (_o$2790 l) (_o$2791 r)) (jolt-vector _o$2787 _o$2788 _o$2789 _o$2790 _o$2791)))))) mk-black) (let* ((_o$2792 (keyword #f "private")) (_o$2793 #t)) (jolt-hash-map _o$2792 _o$2793)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "blacken" (letrec ((blacken (lambda (n) (let fnrec2794 ((n n)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "red?") n)) (let* ((_o$2795 (keyword #f "black")) (_o$2796 (jolt-invoke (var-deref "clojure.core" "nd-key") n)) (_o$2797 (jolt-invoke (var-deref "clojure.core" "nd-val") n)) (_o$2798 (jolt-invoke (var-deref "clojure.core" "nd-left") n)) (_o$2799 (jolt-invoke (var-deref "clojure.core" "nd-right") n))) (jolt-vector _o$2795 _o$2796 _o$2797 _o$2798 _o$2799)) n))))) blacken) (let* ((_o$2800 (keyword #f "private")) (_o$2801 #t)) (jolt-hash-map _o$2800 _o$2801)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "redden" (letrec ((redden (lambda (n) (let fnrec2802 ((n n)) (let* ((_o$2803 (keyword #f "red")) (_o$2804 (jolt-invoke (var-deref "clojure.core" "nd-key") n)) (_o$2805 (jolt-invoke (var-deref "clojure.core" "nd-val") n)) (_o$2806 (jolt-invoke (var-deref "clojure.core" "nd-left") n)) (_o$2807 (jolt-invoke (var-deref "clojure.core" "nd-right") n))) (jolt-vector _o$2803 _o$2804 _o$2805 _o$2806 _o$2807)))))) redden) (let* ((_o$2808 (keyword #f "private")) (_o$2809 #t)) (jolt-hash-map _o$2808 _o$2809)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "replace-node" (letrec ((replace-node (lambda (n k v l r) (let fnrec2810 ((n n) (k k) (v v) (l l) (r r)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "red?") n)) (jolt-invoke (var-deref "clojure.core" "mk-red") k v l r) (jolt-invoke (var-deref "clojure.core" "mk-black") k v l r)))))) replace-node) (let* ((_o$2811 (keyword #f "private")) (_o$2812 #t)) (jolt-hash-map _o$2811 _o$2812)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "ins-balance-left" (letrec ((ins-balance-left (lambda (ins parent) (let fnrec2813 ((ins ins) (parent parent)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "red?") ins)) (let* ((l (jolt-invoke (var-deref "clojure.core" "nd-left") ins)) (r (jolt-invoke (var-deref "clojure.core" "nd-right") ins))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "red?") l)) (let* ((_a$2819 (var-deref "clojure.core" "mk-red")) (_a$2820 (jolt-invoke (var-deref "clojure.core" "nd-key") ins)) (_a$2821 (jolt-invoke (var-deref "clojure.core" "nd-val") ins)) (_a$2822 (jolt-invoke (var-deref "clojure.core" "blacken") l)) (_a$2823 (let* ((_a$2814 (var-deref "clojure.core" "mk-black")) (_a$2815 (jolt-invoke (var-deref "clojure.core" "nd-key") parent)) (_a$2816 (jolt-invoke (var-deref "clojure.core" "nd-val") parent)) (_a$2817 r) (_a$2818 (jolt-invoke (var-deref "clojure.core" "nd-right") parent))) (jolt-invoke _a$2814 _a$2815 _a$2816 _a$2817 _a$2818)))) (jolt-invoke _a$2819 _a$2820 _a$2821 _a$2822 _a$2823)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "red?") r)) (let* ((_a$2834 (var-deref "clojure.core" "mk-red")) (_a$2835 (jolt-invoke (var-deref "clojure.core" "nd-key") r)) (_a$2836 (jolt-invoke (var-deref "clojure.core" "nd-val") r)) (_a$2837 (let* ((_a$2824 (var-deref "clojure.core" "mk-black")) (_a$2825 (jolt-invoke (var-deref "clojure.core" "nd-key") ins)) (_a$2826 (jolt-invoke (var-deref "clojure.core" "nd-val") ins)) (_a$2827 l) (_a$2828 (jolt-invoke (var-deref "clojure.core" "nd-left") r))) (jolt-invoke _a$2824 _a$2825 _a$2826 _a$2827 _a$2828))) (_a$2838 (let* ((_a$2829 (var-deref "clojure.core" "mk-black")) (_a$2830 (jolt-invoke (var-deref "clojure.core" "nd-key") parent)) (_a$2831 (jolt-invoke (var-deref "clojure.core" "nd-val") parent)) (_a$2832 (jolt-invoke (var-deref "clojure.core" "nd-right") r)) (_a$2833 (jolt-invoke (var-deref "clojure.core" "nd-right") parent))) (jolt-invoke _a$2829 _a$2830 _a$2831 _a$2832 _a$2833)))) (jolt-invoke _a$2834 _a$2835 _a$2836 _a$2837 _a$2838)) (if (jolt-truthy? (keyword #f "else")) (let* ((_a$2839 (var-deref "clojure.core" "mk-black")) (_a$2840 (jolt-invoke (var-deref "clojure.core" "nd-key") parent)) (_a$2841 (jolt-invoke (var-deref "clojure.core" "nd-val") parent)) (_a$2842 ins) (_a$2843 (jolt-invoke (var-deref "clojure.core" "nd-right") parent))) (jolt-invoke _a$2839 _a$2840 _a$2841 _a$2842 _a$2843)) jolt-nil)))) (let* ((_a$2844 (var-deref "clojure.core" "mk-black")) (_a$2845 (jolt-invoke (var-deref "clojure.core" "nd-key") parent)) (_a$2846 (jolt-invoke (var-deref "clojure.core" "nd-val") parent)) (_a$2847 ins) (_a$2848 (jolt-invoke (var-deref "clojure.core" "nd-right") parent))) (jolt-invoke _a$2844 _a$2845 _a$2846 _a$2847 _a$2848))))))) ins-balance-left) (let* ((_o$2849 (keyword #f "private")) (_o$2850 #t)) (jolt-hash-map _o$2849 _o$2850)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "ins-balance-right" (letrec ((ins-balance-right (lambda (ins parent) (let fnrec2851 ((ins ins) (parent parent)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "red?") ins)) (let* ((l (jolt-invoke (var-deref "clojure.core" "nd-left") ins)) (r (jolt-invoke (var-deref "clojure.core" "nd-right") ins))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "red?") r)) (let* ((_a$2857 (var-deref "clojure.core" "mk-red")) (_a$2858 (jolt-invoke (var-deref "clojure.core" "nd-key") ins)) (_a$2859 (jolt-invoke (var-deref "clojure.core" "nd-val") ins)) (_a$2860 (let* ((_a$2852 (var-deref "clojure.core" "mk-black")) (_a$2853 (jolt-invoke (var-deref "clojure.core" "nd-key") parent)) (_a$2854 (jolt-invoke (var-deref "clojure.core" "nd-val") parent)) (_a$2855 (jolt-invoke (var-deref "clojure.core" "nd-left") parent)) (_a$2856 l)) (jolt-invoke _a$2852 _a$2853 _a$2854 _a$2855 _a$2856))) (_a$2861 (jolt-invoke (var-deref "clojure.core" "blacken") r))) (jolt-invoke _a$2857 _a$2858 _a$2859 _a$2860 _a$2861)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "red?") l)) (let* ((_a$2872 (var-deref "clojure.core" "mk-red")) (_a$2873 (jolt-invoke (var-deref "clojure.core" "nd-key") l)) (_a$2874 (jolt-invoke (var-deref "clojure.core" "nd-val") l)) (_a$2875 (let* ((_a$2862 (var-deref "clojure.core" "mk-black")) (_a$2863 (jolt-invoke (var-deref "clojure.core" "nd-key") parent)) (_a$2864 (jolt-invoke (var-deref "clojure.core" "nd-val") parent)) (_a$2865 (jolt-invoke (var-deref "clojure.core" "nd-left") parent)) (_a$2866 (jolt-invoke (var-deref "clojure.core" "nd-left") l))) (jolt-invoke _a$2862 _a$2863 _a$2864 _a$2865 _a$2866))) (_a$2876 (let* ((_a$2867 (var-deref "clojure.core" "mk-black")) (_a$2868 (jolt-invoke (var-deref "clojure.core" "nd-key") ins)) (_a$2869 (jolt-invoke (var-deref "clojure.core" "nd-val") ins)) (_a$2870 (jolt-invoke (var-deref "clojure.core" "nd-right") l)) (_a$2871 r)) (jolt-invoke _a$2867 _a$2868 _a$2869 _a$2870 _a$2871)))) (jolt-invoke _a$2872 _a$2873 _a$2874 _a$2875 _a$2876)) (if (jolt-truthy? (keyword #f "else")) (let* ((_a$2877 (var-deref "clojure.core" "mk-black")) (_a$2878 (jolt-invoke (var-deref "clojure.core" "nd-key") parent)) (_a$2879 (jolt-invoke (var-deref "clojure.core" "nd-val") parent)) (_a$2880 (jolt-invoke (var-deref "clojure.core" "nd-left") parent)) (_a$2881 ins)) (jolt-invoke _a$2877 _a$2878 _a$2879 _a$2880 _a$2881)) jolt-nil)))) (let* ((_a$2882 (var-deref "clojure.core" "mk-black")) (_a$2883 (jolt-invoke (var-deref "clojure.core" "nd-key") parent)) (_a$2884 (jolt-invoke (var-deref "clojure.core" "nd-val") parent)) (_a$2885 (jolt-invoke (var-deref "clojure.core" "nd-left") parent)) (_a$2886 ins)) (jolt-invoke _a$2882 _a$2883 _a$2884 _a$2885 _a$2886))))))) ins-balance-right) (let* ((_o$2887 (keyword #f "private")) (_o$2888 #t)) (jolt-hash-map _o$2887 _o$2888)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "add-left" (letrec ((add-left (lambda (parent ins) (let fnrec2889 ((parent parent) (ins ins)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "red?") parent)) (let* ((_a$2890 (var-deref "clojure.core" "mk-red")) (_a$2891 (jolt-invoke (var-deref "clojure.core" "nd-key") parent)) (_a$2892 (jolt-invoke (var-deref "clojure.core" "nd-val") parent)) (_a$2893 ins) (_a$2894 (jolt-invoke (var-deref "clojure.core" "nd-right") parent))) (jolt-invoke _a$2890 _a$2891 _a$2892 _a$2893 _a$2894)) (jolt-invoke (var-deref "clojure.core" "ins-balance-left") ins parent)))))) add-left) (let* ((_o$2895 (keyword #f "private")) (_o$2896 #t)) (jolt-hash-map _o$2895 _o$2896)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "add-right" (letrec ((add-right (lambda (parent ins) (let fnrec2897 ((parent parent) (ins ins)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "red?") parent)) (let* ((_a$2898 (var-deref "clojure.core" "mk-red")) (_a$2899 (jolt-invoke (var-deref "clojure.core" "nd-key") parent)) (_a$2900 (jolt-invoke (var-deref "clojure.core" "nd-val") parent)) (_a$2901 (jolt-invoke (var-deref "clojure.core" "nd-left") parent)) (_a$2902 ins)) (jolt-invoke _a$2898 _a$2899 _a$2900 _a$2901 _a$2902)) (jolt-invoke (var-deref "clojure.core" "ins-balance-right") ins parent)))))) add-right) (let* ((_o$2903 (keyword #f "private")) (_o$2904 #t)) (jolt-hash-map _o$2903 _o$2904)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "tree-ins" (letrec ((tree-ins (lambda (cmp tree k v) (let fnrec2905 ((cmp cmp) (tree tree) (k k) (v v)) (if (jolt-nil? tree) (jolt-invoke (var-deref "clojure.core" "mk-red") k v jolt-nil jolt-nil) (if (jolt-neg? (jolt-invoke cmp k (jolt-invoke (var-deref "clojure.core" "nd-key") tree))) (jolt-invoke (var-deref "clojure.core" "add-left") tree (tree-ins cmp (jolt-invoke (var-deref "clojure.core" "nd-left") tree) k v)) (jolt-invoke (var-deref "clojure.core" "add-right") tree (tree-ins cmp (jolt-invoke (var-deref "clojure.core" "nd-right") tree) k v)))))))) tree-ins) (let* ((_o$2906 (keyword #f "private")) (_o$2907 #t)) (jolt-hash-map _o$2906 _o$2907)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "tree-replace" (letrec ((tree-replace (lambda (cmp tree k v) (let fnrec2908 ((cmp cmp) (tree tree) (k k) (v v)) (let* ((c (jolt-invoke cmp k (jolt-invoke (var-deref "clojure.core" "nd-key") tree)))) (if (jolt-zero? c) (let* ((_a$2909 (var-deref "clojure.core" "replace-node")) (_a$2910 tree) (_a$2911 (jolt-invoke (var-deref "clojure.core" "nd-key") tree)) (_a$2912 v) (_a$2913 (jolt-invoke (var-deref "clojure.core" "nd-left") tree)) (_a$2914 (jolt-invoke (var-deref "clojure.core" "nd-right") tree))) (jolt-invoke _a$2909 _a$2910 _a$2911 _a$2912 _a$2913 _a$2914)) (if (jolt-neg? c) (let* ((_a$2915 (var-deref "clojure.core" "replace-node")) (_a$2916 tree) (_a$2917 (jolt-invoke (var-deref "clojure.core" "nd-key") tree)) (_a$2918 (jolt-invoke (var-deref "clojure.core" "nd-val") tree)) (_a$2919 (tree-replace cmp (jolt-invoke (var-deref "clojure.core" "nd-left") tree) k v)) (_a$2920 (jolt-invoke (var-deref "clojure.core" "nd-right") tree))) (jolt-invoke _a$2915 _a$2916 _a$2917 _a$2918 _a$2919 _a$2920)) (if (jolt-truthy? (keyword #f "else")) (let* ((_a$2921 (var-deref "clojure.core" "replace-node")) (_a$2922 tree) (_a$2923 (jolt-invoke (var-deref "clojure.core" "nd-key") tree)) (_a$2924 (jolt-invoke (var-deref "clojure.core" "nd-val") tree)) (_a$2925 (jolt-invoke (var-deref "clojure.core" "nd-left") tree)) (_a$2926 (tree-replace cmp (jolt-invoke (var-deref "clojure.core" "nd-right") tree) k v))) (jolt-invoke _a$2921 _a$2922 _a$2923 _a$2924 _a$2925 _a$2926)) jolt-nil)))))))) tree-replace) (let* ((_o$2927 (keyword #f "private")) (_o$2928 #t)) (jolt-hash-map _o$2927 _o$2928)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "tree-lookup" (letrec ((tree-lookup (lambda (tree cmp k) (let fnrec2929 ((tree tree) (cmp cmp) (k k)) (let* ((t tree)) (let loop2930 ((t t)) (if (jolt-nil? t) jolt-nil (let* ((c (jolt-invoke cmp k (jolt-invoke (var-deref "clojure.core" "nd-key") t)))) (if (jolt-zero? c) t (if (jolt-neg? c) (loop2930 (jolt-invoke (var-deref "clojure.core" "nd-left") t)) (if (jolt-truthy? (keyword #f "else")) (loop2930 (jolt-invoke (var-deref "clojure.core" "nd-right") t)) jolt-nil))))))))))) tree-lookup) (let* ((_o$2931 (keyword #f "private")) (_o$2932 #t)) (jolt-hash-map _o$2931 _o$2932)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "balance-left" (letrec ((balance-left (lambda (k v ins right) (let fnrec2933 ((k k) (v v) (ins ins) (right right)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "red?") ins)) (let* ((il (jolt-invoke (var-deref "clojure.core" "nd-left") ins)) (ir (jolt-invoke (var-deref "clojure.core" "nd-right") ins))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "red?") il)) (let* ((_a$2934 (var-deref "clojure.core" "mk-red")) (_a$2935 (jolt-invoke (var-deref "clojure.core" "nd-key") ins)) (_a$2936 (jolt-invoke (var-deref "clojure.core" "nd-val") ins)) (_a$2937 (jolt-invoke (var-deref "clojure.core" "blacken") il)) (_a$2938 (jolt-invoke (var-deref "clojure.core" "mk-black") k v ir right))) (jolt-invoke _a$2934 _a$2935 _a$2936 _a$2937 _a$2938)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "red?") ir)) (let* ((_a$2944 (var-deref "clojure.core" "mk-red")) (_a$2945 (jolt-invoke (var-deref "clojure.core" "nd-key") ir)) (_a$2946 (jolt-invoke (var-deref "clojure.core" "nd-val") ir)) (_a$2947 (let* ((_a$2939 (var-deref "clojure.core" "mk-black")) (_a$2940 (jolt-invoke (var-deref "clojure.core" "nd-key") ins)) (_a$2941 (jolt-invoke (var-deref "clojure.core" "nd-val") ins)) (_a$2942 il) (_a$2943 (jolt-invoke (var-deref "clojure.core" "nd-left") ir))) (jolt-invoke _a$2939 _a$2940 _a$2941 _a$2942 _a$2943))) (_a$2948 (jolt-invoke (var-deref "clojure.core" "mk-black") k v (jolt-invoke (var-deref "clojure.core" "nd-right") ir) right))) (jolt-invoke _a$2944 _a$2945 _a$2946 _a$2947 _a$2948)) (if (jolt-truthy? (keyword #f "else")) (jolt-invoke (var-deref "clojure.core" "mk-black") k v ins right) jolt-nil)))) (jolt-invoke (var-deref "clojure.core" "mk-black") k v ins right)))))) balance-left) (let* ((_o$2949 (keyword #f "private")) (_o$2950 #t)) (jolt-hash-map _o$2949 _o$2950)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "balance-right" (letrec ((balance-right (lambda (k v left ins) (let fnrec2951 ((k k) (v v) (left left) (ins ins)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "red?") ins)) (let* ((il (jolt-invoke (var-deref "clojure.core" "nd-left") ins)) (ir (jolt-invoke (var-deref "clojure.core" "nd-right") ins))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "red?") ir)) (let* ((_a$2952 (var-deref "clojure.core" "mk-red")) (_a$2953 (jolt-invoke (var-deref "clojure.core" "nd-key") ins)) (_a$2954 (jolt-invoke (var-deref "clojure.core" "nd-val") ins)) (_a$2955 (jolt-invoke (var-deref "clojure.core" "mk-black") k v left il)) (_a$2956 (jolt-invoke (var-deref "clojure.core" "blacken") ir))) (jolt-invoke _a$2952 _a$2953 _a$2954 _a$2955 _a$2956)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "red?") il)) (let* ((_a$2962 (var-deref "clojure.core" "mk-red")) (_a$2963 (jolt-invoke (var-deref "clojure.core" "nd-key") il)) (_a$2964 (jolt-invoke (var-deref "clojure.core" "nd-val") il)) (_a$2965 (jolt-invoke (var-deref "clojure.core" "mk-black") k v left (jolt-invoke (var-deref "clojure.core" "nd-left") il))) (_a$2966 (let* ((_a$2957 (var-deref "clojure.core" "mk-black")) (_a$2958 (jolt-invoke (var-deref "clojure.core" "nd-key") ins)) (_a$2959 (jolt-invoke (var-deref "clojure.core" "nd-val") ins)) (_a$2960 (jolt-invoke (var-deref "clojure.core" "nd-right") il)) (_a$2961 ir)) (jolt-invoke _a$2957 _a$2958 _a$2959 _a$2960 _a$2961)))) (jolt-invoke _a$2962 _a$2963 _a$2964 _a$2965 _a$2966)) (if (jolt-truthy? (keyword #f "else")) (jolt-invoke (var-deref "clojure.core" "mk-black") k v left ins) jolt-nil)))) (jolt-invoke (var-deref "clojure.core" "mk-black") k v left ins)))))) balance-right) (let* ((_o$2967 (keyword #f "private")) (_o$2968 #t)) (jolt-hash-map _o$2967 _o$2968)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "balance-left-del" (letrec ((balance-left-del (lambda (k v del right) (let fnrec2969 ((k k) (v v) (del del) (right right)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "red?") del)) (jolt-invoke (var-deref "clojure.core" "mk-red") k v (jolt-invoke (var-deref "clojure.core" "blacken") del) right) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "black?") right)) (jolt-invoke (var-deref "clojure.core" "balance-right") k v del (jolt-invoke (var-deref "clojure.core" "redden") right)) (if (jolt-truthy? (let* ((and__25__auto (jolt-invoke (var-deref "clojure.core" "red?") right))) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "clojure.core" "black?") (jolt-invoke (var-deref "clojure.core" "nd-left") right)) and__25__auto))) (let* ((_a$2975 (var-deref "clojure.core" "mk-red")) (_a$2976 (jolt-invoke (var-deref "clojure.core" "nd-key") (jolt-invoke (var-deref "clojure.core" "nd-left") right))) (_a$2977 (jolt-invoke (var-deref "clojure.core" "nd-val") (jolt-invoke (var-deref "clojure.core" "nd-left") right))) (_a$2978 (jolt-invoke (var-deref "clojure.core" "mk-black") k v del (jolt-invoke (var-deref "clojure.core" "nd-left") (jolt-invoke (var-deref "clojure.core" "nd-left") right)))) (_a$2979 (let* ((_a$2970 (var-deref "clojure.core" "balance-right")) (_a$2971 (jolt-invoke (var-deref "clojure.core" "nd-key") right)) (_a$2972 (jolt-invoke (var-deref "clojure.core" "nd-val") right)) (_a$2973 (jolt-invoke (var-deref "clojure.core" "nd-right") (jolt-invoke (var-deref "clojure.core" "nd-left") right))) (_a$2974 (jolt-invoke (var-deref "clojure.core" "redden") (jolt-invoke (var-deref "clojure.core" "nd-right") right)))) (jolt-invoke _a$2970 _a$2971 _a$2972 _a$2973 _a$2974)))) (jolt-invoke _a$2975 _a$2976 _a$2977 _a$2978 _a$2979)) (if (jolt-truthy? (keyword #f "else")) (jolt-throw (jolt-ex-info "red-black tree invariant violation" (jolt-hash-map))) jolt-nil)))))))) balance-left-del) (let* ((_o$2980 (keyword #f "private")) (_o$2981 #t)) (jolt-hash-map _o$2980 _o$2981)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "balance-right-del" (letrec ((balance-right-del (lambda (k v left del) (let fnrec2982 ((k k) (v v) (left left) (del del)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "red?") del)) (jolt-invoke (var-deref "clojure.core" "mk-red") k v left (jolt-invoke (var-deref "clojure.core" "blacken") del)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "black?") left)) (jolt-invoke (var-deref "clojure.core" "balance-left") k v (jolt-invoke (var-deref "clojure.core" "redden") left) del) (if (jolt-truthy? (let* ((and__25__auto (jolt-invoke (var-deref "clojure.core" "red?") left))) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "clojure.core" "black?") (jolt-invoke (var-deref "clojure.core" "nd-right") left)) and__25__auto))) (let* ((_a$2988 (var-deref "clojure.core" "mk-red")) (_a$2989 (jolt-invoke (var-deref "clojure.core" "nd-key") (jolt-invoke (var-deref "clojure.core" "nd-right") left))) (_a$2990 (jolt-invoke (var-deref "clojure.core" "nd-val") (jolt-invoke (var-deref "clojure.core" "nd-right") left))) (_a$2991 (let* ((_a$2983 (var-deref "clojure.core" "balance-left")) (_a$2984 (jolt-invoke (var-deref "clojure.core" "nd-key") left)) (_a$2985 (jolt-invoke (var-deref "clojure.core" "nd-val") left)) (_a$2986 (jolt-invoke (var-deref "clojure.core" "redden") (jolt-invoke (var-deref "clojure.core" "nd-left") left))) (_a$2987 (jolt-invoke (var-deref "clojure.core" "nd-left") (jolt-invoke (var-deref "clojure.core" "nd-right") left)))) (jolt-invoke _a$2983 _a$2984 _a$2985 _a$2986 _a$2987))) (_a$2992 (jolt-invoke (var-deref "clojure.core" "mk-black") k v (jolt-invoke (var-deref "clojure.core" "nd-right") (jolt-invoke (var-deref "clojure.core" "nd-right") left)) del))) (jolt-invoke _a$2988 _a$2989 _a$2990 _a$2991 _a$2992)) (if (jolt-truthy? (keyword #f "else")) (jolt-throw (jolt-ex-info "red-black tree invariant violation" (jolt-hash-map))) jolt-nil)))))))) balance-right-del) (let* ((_o$2993 (keyword #f "private")) (_o$2994 #t)) (jolt-hash-map _o$2993 _o$2994)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "tree-append" (letrec ((tree-append (lambda (left right) (let fnrec2995 ((left left) (right right)) (if (jolt-nil? left) right (if (jolt-nil? right) left (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "red?") left)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "red?") right)) (let* ((app (let* ((_a$2996 (jolt-invoke (var-deref "clojure.core" "nd-right") left)) (_a$2997 (jolt-invoke (var-deref "clojure.core" "nd-left") right))) (tree-append _a$2996 _a$2997)))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "red?") app)) (let* ((_a$3008 (var-deref "clojure.core" "mk-red")) (_a$3009 (jolt-invoke (var-deref "clojure.core" "nd-key") app)) (_a$3010 (jolt-invoke (var-deref "clojure.core" "nd-val") app)) (_a$3011 (let* ((_a$2998 (var-deref "clojure.core" "mk-red")) (_a$2999 (jolt-invoke (var-deref "clojure.core" "nd-key") left)) (_a$3000 (jolt-invoke (var-deref "clojure.core" "nd-val") left)) (_a$3001 (jolt-invoke (var-deref "clojure.core" "nd-left") left)) (_a$3002 (jolt-invoke (var-deref "clojure.core" "nd-left") app))) (jolt-invoke _a$2998 _a$2999 _a$3000 _a$3001 _a$3002))) (_a$3012 (let* ((_a$3003 (var-deref "clojure.core" "mk-red")) (_a$3004 (jolt-invoke (var-deref "clojure.core" "nd-key") right)) (_a$3005 (jolt-invoke (var-deref "clojure.core" "nd-val") right)) (_a$3006 (jolt-invoke (var-deref "clojure.core" "nd-right") app)) (_a$3007 (jolt-invoke (var-deref "clojure.core" "nd-right") right))) (jolt-invoke _a$3003 _a$3004 _a$3005 _a$3006 _a$3007)))) (jolt-invoke _a$3008 _a$3009 _a$3010 _a$3011 _a$3012)) (let* ((_a$3018 (var-deref "clojure.core" "mk-red")) (_a$3019 (jolt-invoke (var-deref "clojure.core" "nd-key") left)) (_a$3020 (jolt-invoke (var-deref "clojure.core" "nd-val") left)) (_a$3021 (jolt-invoke (var-deref "clojure.core" "nd-left") left)) (_a$3022 (let* ((_a$3013 (var-deref "clojure.core" "mk-red")) (_a$3014 (jolt-invoke (var-deref "clojure.core" "nd-key") right)) (_a$3015 (jolt-invoke (var-deref "clojure.core" "nd-val") right)) (_a$3016 app) (_a$3017 (jolt-invoke (var-deref "clojure.core" "nd-right") right))) (jolt-invoke _a$3013 _a$3014 _a$3015 _a$3016 _a$3017)))) (jolt-invoke _a$3018 _a$3019 _a$3020 _a$3021 _a$3022)))) (let* ((_a$3023 (var-deref "clojure.core" "mk-red")) (_a$3024 (jolt-invoke (var-deref "clojure.core" "nd-key") left)) (_a$3025 (jolt-invoke (var-deref "clojure.core" "nd-val") left)) (_a$3026 (jolt-invoke (var-deref "clojure.core" "nd-left") left)) (_a$3027 (tree-append (jolt-invoke (var-deref "clojure.core" "nd-right") left) right))) (jolt-invoke _a$3023 _a$3024 _a$3025 _a$3026 _a$3027))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "red?") right)) (let* ((_a$3028 (var-deref "clojure.core" "mk-red")) (_a$3029 (jolt-invoke (var-deref "clojure.core" "nd-key") right)) (_a$3030 (jolt-invoke (var-deref "clojure.core" "nd-val") right)) (_a$3031 (tree-append left (jolt-invoke (var-deref "clojure.core" "nd-left") right))) (_a$3032 (jolt-invoke (var-deref "clojure.core" "nd-right") right))) (jolt-invoke _a$3028 _a$3029 _a$3030 _a$3031 _a$3032)) (if (jolt-truthy? (keyword #f "else")) (let* ((app (let* ((_a$3033 (jolt-invoke (var-deref "clojure.core" "nd-right") left)) (_a$3034 (jolt-invoke (var-deref "clojure.core" "nd-left") right))) (tree-append _a$3033 _a$3034)))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "red?") app)) (let* ((_a$3045 (var-deref "clojure.core" "mk-red")) (_a$3046 (jolt-invoke (var-deref "clojure.core" "nd-key") app)) (_a$3047 (jolt-invoke (var-deref "clojure.core" "nd-val") app)) (_a$3048 (let* ((_a$3035 (var-deref "clojure.core" "mk-black")) (_a$3036 (jolt-invoke (var-deref "clojure.core" "nd-key") left)) (_a$3037 (jolt-invoke (var-deref "clojure.core" "nd-val") left)) (_a$3038 (jolt-invoke (var-deref "clojure.core" "nd-left") left)) (_a$3039 (jolt-invoke (var-deref "clojure.core" "nd-left") app))) (jolt-invoke _a$3035 _a$3036 _a$3037 _a$3038 _a$3039))) (_a$3049 (let* ((_a$3040 (var-deref "clojure.core" "mk-black")) (_a$3041 (jolt-invoke (var-deref "clojure.core" "nd-key") right)) (_a$3042 (jolt-invoke (var-deref "clojure.core" "nd-val") right)) (_a$3043 (jolt-invoke (var-deref "clojure.core" "nd-right") app)) (_a$3044 (jolt-invoke (var-deref "clojure.core" "nd-right") right))) (jolt-invoke _a$3040 _a$3041 _a$3042 _a$3043 _a$3044)))) (jolt-invoke _a$3045 _a$3046 _a$3047 _a$3048 _a$3049)) (let* ((_a$3055 (var-deref "clojure.core" "balance-left-del")) (_a$3056 (jolt-invoke (var-deref "clojure.core" "nd-key") left)) (_a$3057 (jolt-invoke (var-deref "clojure.core" "nd-val") left)) (_a$3058 (jolt-invoke (var-deref "clojure.core" "nd-left") left)) (_a$3059 (let* ((_a$3050 (var-deref "clojure.core" "mk-black")) (_a$3051 (jolt-invoke (var-deref "clojure.core" "nd-key") right)) (_a$3052 (jolt-invoke (var-deref "clojure.core" "nd-val") right)) (_a$3053 app) (_a$3054 (jolt-invoke (var-deref "clojure.core" "nd-right") right))) (jolt-invoke _a$3050 _a$3051 _a$3052 _a$3053 _a$3054)))) (jolt-invoke _a$3055 _a$3056 _a$3057 _a$3058 _a$3059)))) jolt-nil))))))))) tree-append) (let* ((_o$3060 (keyword #f "private")) (_o$3061 #t)) (jolt-hash-map _o$3060 _o$3061)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "tree-del" (letrec ((tree-del (lambda (cmp tree k) (let fnrec3062 ((cmp cmp) (tree tree) (k k)) (let* ((c (jolt-invoke cmp k (jolt-invoke (var-deref "clojure.core" "nd-key") tree)))) (if (jolt-zero? c) (let* ((_a$3063 (var-deref "clojure.core" "tree-append")) (_a$3064 (jolt-invoke (var-deref "clojure.core" "nd-left") tree)) (_a$3065 (jolt-invoke (var-deref "clojure.core" "nd-right") tree))) (jolt-invoke _a$3063 _a$3064 _a$3065)) (if (jolt-neg? c) (let* ((del (tree-del cmp (jolt-invoke (var-deref "clojure.core" "nd-left") tree) k))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "black?") (jolt-invoke (var-deref "clojure.core" "nd-left") tree))) (let* ((_a$3066 (var-deref "clojure.core" "balance-left-del")) (_a$3067 (jolt-invoke (var-deref "clojure.core" "nd-key") tree)) (_a$3068 (jolt-invoke (var-deref "clojure.core" "nd-val") tree)) (_a$3069 del) (_a$3070 (jolt-invoke (var-deref "clojure.core" "nd-right") tree))) (jolt-invoke _a$3066 _a$3067 _a$3068 _a$3069 _a$3070)) (let* ((_a$3071 (var-deref "clojure.core" "mk-red")) (_a$3072 (jolt-invoke (var-deref "clojure.core" "nd-key") tree)) (_a$3073 (jolt-invoke (var-deref "clojure.core" "nd-val") tree)) (_a$3074 del) (_a$3075 (jolt-invoke (var-deref "clojure.core" "nd-right") tree))) (jolt-invoke _a$3071 _a$3072 _a$3073 _a$3074 _a$3075)))) (if (jolt-truthy? (keyword #f "else")) (let* ((del (tree-del cmp (jolt-invoke (var-deref "clojure.core" "nd-right") tree) k))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "black?") (jolt-invoke (var-deref "clojure.core" "nd-right") tree))) (let* ((_a$3076 (var-deref "clojure.core" "balance-right-del")) (_a$3077 (jolt-invoke (var-deref "clojure.core" "nd-key") tree)) (_a$3078 (jolt-invoke (var-deref "clojure.core" "nd-val") tree)) (_a$3079 (jolt-invoke (var-deref "clojure.core" "nd-left") tree)) (_a$3080 del)) (jolt-invoke _a$3076 _a$3077 _a$3078 _a$3079 _a$3080)) (let* ((_a$3081 (var-deref "clojure.core" "mk-red")) (_a$3082 (jolt-invoke (var-deref "clojure.core" "nd-key") tree)) (_a$3083 (jolt-invoke (var-deref "clojure.core" "nd-val") tree)) (_a$3084 (jolt-invoke (var-deref "clojure.core" "nd-left") tree)) (_a$3085 del)) (jolt-invoke _a$3081 _a$3082 _a$3083 _a$3084 _a$3085)))) jolt-nil)))))))) tree-del) (let* ((_o$3086 (keyword #f "private")) (_o$3087 #t)) (jolt-hash-map _o$3086 _o$3087)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "tree-collect" (letrec ((tree-collect (lambda (t proj acc) (let fnrec3088 ((t t) (proj proj) (acc acc)) (if (jolt-nil? t) acc (let* ((_a$3091 (jolt-invoke (var-deref "clojure.core" "nd-right") t)) (_a$3092 proj) (_a$3093 (let* ((_a$3089 (tree-collect (jolt-invoke (var-deref "clojure.core" "nd-left") t) proj acc)) (_a$3090 (jolt-invoke proj t))) (jolt-conj _a$3089 _a$3090)))) (tree-collect _a$3091 _a$3092 _a$3093))))))) tree-collect) (let* ((_o$3094 (keyword #f "private")) (_o$3095 #t)) (jolt-hash-map _o$3094 _o$3095)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "make-sorted" (letrec ((make-sorted (lambda (tag tree cnt cmp ops) (let fnrec3096 ((tag tag) (tree tree) (cnt cnt) (cmp cmp) (ops ops)) (jolt-invoke (var-deref "jolt.host" "ref-put!") (jolt-invoke (var-deref "jolt.host" "ref-put!") (jolt-invoke (var-deref "jolt.host" "ref-put!") (jolt-invoke (var-deref "jolt.host" "ref-put!") (jolt-invoke (var-deref "jolt.host" "tagged-table") tag) (keyword #f "tree") tree) (keyword #f "cnt") cnt) (keyword #f "cmp") cmp) (keyword #f "ops") ops))))) make-sorted) (let* ((_o$3097 (keyword #f "private")) (_o$3098 #t)) (jolt-hash-map _o$3097 _o$3098)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "sc-entries" (letrec ((sc-entries (lambda (sc proj) (let fnrec3099 ((sc sc) (proj proj)) (let* ((_a$3100 (var-deref "clojure.core" "tree-collect")) (_a$3101 (jolt-invoke (var-deref "clojure.core" "sfield") sc (keyword #f "tree"))) (_a$3102 proj) (_a$3103 (jolt-vector))) (jolt-invoke _a$3100 _a$3101 _a$3102 _a$3103)))))) sc-entries) (let* ((_o$3104 (keyword #f "private")) (_o$3105 #t)) (jolt-hash-map _o$3104 _o$3105)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "map-entry" (letrec ((map-entry (lambda (t) (let fnrec3106 ((t t)) (let* ((_a$3107 (var-deref "jolt.host" "map-entry")) (_a$3108 (jolt-invoke (var-deref "clojure.core" "nd-key") t)) (_a$3109 (jolt-invoke (var-deref "clojure.core" "nd-val") t))) (jolt-invoke _a$3107 _a$3108 _a$3109)))))) map-entry) (let* ((_o$3110 (keyword #f "private")) (_o$3111 #t)) (jolt-hash-map _o$3110 _o$3111)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "sm-get" (letrec ((sm-get (lambda (sm k not-found) (let fnrec3112 ((sm sm) (k k) (not-found not-found)) (let* ((n (let* ((_a$3113 (var-deref "clojure.core" "tree-lookup")) (_a$3114 (jolt-invoke (var-deref "clojure.core" "sfield") sm (keyword #f "tree"))) (_a$3115 (jolt-invoke (var-deref "clojure.core" "the-cmp") sm)) (_a$3116 k)) (jolt-invoke _a$3113 _a$3114 _a$3115 _a$3116)))) (if (jolt-nil? n) not-found (jolt-invoke (var-deref "clojure.core" "nd-val") n))))))) sm-get) (let* ((_o$3117 (keyword #f "private")) (_o$3118 #t)) (jolt-hash-map _o$3117 _o$3118)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "sm-assoc-1" (letrec ((sm-assoc-1 (lambda (sm k v) (let fnrec3119 ((sm sm) (k k) (v v)) (let* ((cmp (jolt-invoke (var-deref "clojure.core" "the-cmp") sm)) (tree (jolt-invoke (var-deref "clojure.core" "sfield") sm (keyword #f "tree"))) (node (jolt-invoke (var-deref "clojure.core" "tree-lookup") tree cmp k))) (if (jolt-truthy? (let* ((and__25__auto node)) (if (jolt-truthy? and__25__auto) (jolt= v (jolt-invoke (var-deref "clojure.core" "nd-val") node)) and__25__auto))) sm (if (jolt-truthy? node) (let* ((_a$3120 (var-deref "clojure.core" "make-sorted")) (_a$3121 (keyword "jolt" "sorted-map")) (_a$3122 (jolt-invoke (var-deref "clojure.core" "tree-replace") cmp tree k v)) (_a$3123 (jolt-invoke (var-deref "clojure.core" "sfield") sm (keyword #f "cnt"))) (_a$3124 (jolt-invoke (var-deref "clojure.core" "sfield") sm (keyword #f "cmp"))) (_a$3125 (jolt-invoke (var-deref "clojure.core" "sfield") sm (keyword #f "ops")))) (jolt-invoke _a$3120 _a$3121 _a$3122 _a$3123 _a$3124 _a$3125)) (if (jolt-truthy? (keyword #f "else")) (let* ((_a$3126 (var-deref "clojure.core" "make-sorted")) (_a$3127 (keyword "jolt" "sorted-map")) (_a$3128 (jolt-invoke (var-deref "clojure.core" "blacken") (jolt-invoke (var-deref "clojure.core" "tree-ins") cmp tree k v))) (_a$3129 (jolt-inc (jolt-invoke (var-deref "clojure.core" "sfield") sm (keyword #f "cnt")))) (_a$3130 (jolt-invoke (var-deref "clojure.core" "sfield") sm (keyword #f "cmp"))) (_a$3131 (jolt-invoke (var-deref "clojure.core" "sfield") sm (keyword #f "ops")))) (jolt-invoke _a$3126 _a$3127 _a$3128 _a$3129 _a$3130 _a$3131)) jolt-nil)))))))) sm-assoc-1) (let* ((_o$3132 (keyword #f "private")) (_o$3133 #t)) (jolt-hash-map _o$3132 _o$3133)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "sm-assoc-many" (letrec ((sm-assoc-many (lambda (sm kvs) (let fnrec3134 ((sm sm) (kvs kvs)) (let* ((n (jolt-count kvs))) (begin (if (jolt-odd? n) (jolt-throw (jolt-ex-info "sorted-map assoc expects an even number of key/values" (let* ((_o$3135 (keyword #f "count")) (_o$3136 n)) (jolt-hash-map _o$3135 _o$3136)))) jolt-nil) (let* ((m sm) (i 0)) (let loop3137 ((m m) (i i)) (if (jolt-n< i n) (let* ((_a$3142 (let* ((_a$3138 (var-deref "clojure.core" "sm-assoc-1")) (_a$3139 m) (_a$3140 (jolt-nth kvs i)) (_a$3141 (jolt-nth kvs (jolt-inc i)))) (jolt-invoke _a$3138 _a$3139 _a$3140 _a$3141))) (_a$3143 (jolt-n+ i 2))) (loop3137 _a$3142 _a$3143)) m))))))))) sm-assoc-many) (let* ((_o$3144 (keyword #f "private")) (_o$3145 #t)) (jolt-hash-map _o$3144 _o$3145)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "sm-dissoc-1" (letrec ((sm-dissoc-1 (lambda (sm k) (let fnrec3146 ((sm sm) (k k)) (let* ((cmp (jolt-invoke (var-deref "clojure.core" "the-cmp") sm)) (tree (jolt-invoke (var-deref "clojure.core" "sfield") sm (keyword #f "tree")))) (if (jolt-nil? (jolt-invoke (var-deref "clojure.core" "tree-lookup") tree cmp k)) sm (let* ((t (jolt-invoke (var-deref "clojure.core" "tree-del") cmp tree k))) (let* ((_a$3147 (var-deref "clojure.core" "make-sorted")) (_a$3148 (keyword "jolt" "sorted-map")) (_a$3149 (if (jolt-truthy? t) (jolt-invoke (var-deref "clojure.core" "blacken") t) jolt-nil)) (_a$3150 (jolt-dec (jolt-invoke (var-deref "clojure.core" "sfield") sm (keyword #f "cnt")))) (_a$3151 (jolt-invoke (var-deref "clojure.core" "sfield") sm (keyword #f "cmp"))) (_a$3152 (jolt-invoke (var-deref "clojure.core" "sfield") sm (keyword #f "ops")))) (jolt-invoke _a$3147 _a$3148 _a$3149 _a$3150 _a$3151 _a$3152))))))))) sm-dissoc-1) (let* ((_o$3153 (keyword #f "private")) (_o$3154 #t)) (jolt-hash-map _o$3153 _o$3154)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "sm-dissoc-many" (letrec ((sm-dissoc-many (lambda (sm ks) (let fnrec3155 ((sm sm) (ks ks)) (jolt-reduce (var-deref "clojure.core" "sm-dissoc-1") sm ks))))) sm-dissoc-many) (let* ((_o$3156 (keyword #f "private")) (_o$3157 #t)) (jolt-hash-map _o$3156 _o$3157)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "sm-conj-1" (letrec ((sm-conj-1 (lambda (sm x) (let fnrec3158 ((sm sm) (x x)) (if (jolt-nil? x) sm (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "map?") x)) (let* ((_a$3164 (lambda (m e) (let fnrec3159 ((m m) (e e)) (let* ((_a$3160 (var-deref "clojure.core" "sm-assoc-1")) (_a$3161 m) (_a$3162 (jolt-first e)) (_a$3163 (jolt-invoke (var-deref "clojure.core" "second") e))) (jolt-invoke _a$3160 _a$3161 _a$3162 _a$3163))))) (_a$3165 sm) (_a$3166 (jolt-seq x))) (jolt-reduce _a$3164 _a$3165 _a$3166)) (if (jolt-truthy? (let* ((and__25__auto (jolt-invoke (var-deref "clojure.core" "vector?") x))) (if (jolt-truthy? and__25__auto) (jolt= 2 (jolt-count x)) and__25__auto))) (let* ((_a$3167 (var-deref "clojure.core" "sm-assoc-1")) (_a$3168 sm) (_a$3169 (jolt-nth x 0)) (_a$3170 (jolt-nth x 1))) (jolt-invoke _a$3167 _a$3168 _a$3169 _a$3170)) (if (jolt-truthy? (keyword #f "else")) (jolt-throw (jolt-ex-info "conj on a sorted-map requires a [key value] pair or a map" (jolt-hash-map))) jolt-nil)))))))) sm-conj-1) (let* ((_o$3171 (keyword #f "private")) (_o$3172 #t)) (jolt-hash-map _o$3171 _o$3172)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "sm-conj-many" (letrec ((sm-conj-many (lambda (sm xs) (let fnrec3173 ((sm sm) (xs xs)) (jolt-reduce (var-deref "clojure.core" "sm-conj-1") sm xs))))) sm-conj-many) (let* ((_o$3174 (keyword #f "private")) (_o$3175 #t)) (jolt-hash-map _o$3174 _o$3175)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "ss-get" (letrec ((ss-get (lambda (ss x not-found) (let fnrec3176 ((ss ss) (x x) (not-found not-found)) (let* ((n (let* ((_a$3177 (var-deref "clojure.core" "tree-lookup")) (_a$3178 (jolt-invoke (var-deref "clojure.core" "sfield") ss (keyword #f "tree"))) (_a$3179 (jolt-invoke (var-deref "clojure.core" "the-cmp") ss)) (_a$3180 x)) (jolt-invoke _a$3177 _a$3178 _a$3179 _a$3180)))) (if (jolt-nil? n) not-found (jolt-invoke (var-deref "clojure.core" "nd-key") n))))))) ss-get) (let* ((_o$3181 (keyword #f "private")) (_o$3182 #t)) (jolt-hash-map _o$3181 _o$3182)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "ss-conj-1" (letrec ((ss-conj-1 (lambda (ss x) (let fnrec3183 ((ss ss) (x x)) (let* ((cmp (jolt-invoke (var-deref "clojure.core" "the-cmp") ss)) (tree (jolt-invoke (var-deref "clojure.core" "sfield") ss (keyword #f "tree")))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "tree-lookup") tree cmp x)) ss (let* ((_a$3184 (var-deref "clojure.core" "make-sorted")) (_a$3185 (keyword "jolt" "sorted-set")) (_a$3186 (jolt-invoke (var-deref "clojure.core" "blacken") (jolt-invoke (var-deref "clojure.core" "tree-ins") cmp tree x jolt-nil))) (_a$3187 (jolt-inc (jolt-invoke (var-deref "clojure.core" "sfield") ss (keyword #f "cnt")))) (_a$3188 (jolt-invoke (var-deref "clojure.core" "sfield") ss (keyword #f "cmp"))) (_a$3189 (jolt-invoke (var-deref "clojure.core" "sfield") ss (keyword #f "ops")))) (jolt-invoke _a$3184 _a$3185 _a$3186 _a$3187 _a$3188 _a$3189)))))))) ss-conj-1) (let* ((_o$3190 (keyword #f "private")) (_o$3191 #t)) (jolt-hash-map _o$3190 _o$3191)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "ss-conj-many" (letrec ((ss-conj-many (lambda (ss xs) (let fnrec3192 ((ss ss) (xs xs)) (jolt-reduce (var-deref "clojure.core" "ss-conj-1") ss xs))))) ss-conj-many) (let* ((_o$3193 (keyword #f "private")) (_o$3194 #t)) (jolt-hash-map _o$3193 _o$3194)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "ss-disj-1" (letrec ((ss-disj-1 (lambda (ss x) (let fnrec3195 ((ss ss) (x x)) (let* ((cmp (jolt-invoke (var-deref "clojure.core" "the-cmp") ss)) (tree (jolt-invoke (var-deref "clojure.core" "sfield") ss (keyword #f "tree")))) (if (jolt-nil? (jolt-invoke (var-deref "clojure.core" "tree-lookup") tree cmp x)) ss (let* ((t (jolt-invoke (var-deref "clojure.core" "tree-del") cmp tree x))) (let* ((_a$3196 (var-deref "clojure.core" "make-sorted")) (_a$3197 (keyword "jolt" "sorted-set")) (_a$3198 (if (jolt-truthy? t) (jolt-invoke (var-deref "clojure.core" "blacken") t) jolt-nil)) (_a$3199 (jolt-dec (jolt-invoke (var-deref "clojure.core" "sfield") ss (keyword #f "cnt")))) (_a$3200 (jolt-invoke (var-deref "clojure.core" "sfield") ss (keyword #f "cmp"))) (_a$3201 (jolt-invoke (var-deref "clojure.core" "sfield") ss (keyword #f "ops")))) (jolt-invoke _a$3196 _a$3197 _a$3198 _a$3199 _a$3200 _a$3201))))))))) ss-disj-1) (let* ((_o$3202 (keyword #f "private")) (_o$3203 #t)) (jolt-hash-map _o$3202 _o$3203)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "ss-disj-many" (letrec ((ss-disj-many (lambda (ss xs) (let fnrec3204 ((ss ss) (xs xs)) (jolt-reduce (var-deref "clojure.core" "ss-disj-1") ss xs))))) ss-disj-many) (let* ((_o$3205 (keyword #f "private")) (_o$3206 #t)) (jolt-hash-map _o$3205 _o$3206)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "sm-ops" (let* ((_o$3224 (keyword #f "count")) (_o$3225 (lambda (sm) (let fnrec3207 ((sm sm)) (jolt-invoke (var-deref "clojure.core" "sfield") sm (keyword #f "cnt"))))) (_o$3226 (keyword #f "entries")) (_o$3227 (lambda (sm) (let fnrec3208 ((sm sm)) (jolt-invoke (var-deref "clojure.core" "sc-entries") sm (var-deref "clojure.core" "map-entry"))))) (_o$3228 (keyword #f "seq")) (_o$3229 (lambda (sm) (let fnrec3209 ((sm sm)) (jolt-seq (jolt-invoke (var-deref "clojure.core" "sc-entries") sm (var-deref "clojure.core" "map-entry")))))) (_o$3230 (keyword #f "rseq")) (_o$3231 (lambda (sm) (let fnrec3210 ((sm sm)) (jolt-seq (jolt-invoke (var-deref "clojure.core" "vec") (jolt-reverse (jolt-invoke (var-deref "clojure.core" "sc-entries") sm (var-deref "clojure.core" "map-entry")))))))) (_o$3232 (keyword #f "first")) (_o$3233 (lambda (sm) (let fnrec3211 ((sm sm)) (jolt-first (jolt-invoke (var-deref "clojure.core" "sc-entries") sm (var-deref "clojure.core" "map-entry")))))) (_o$3234 (keyword #f "get")) (_o$3235 (var-deref "clojure.core" "sm-get")) (_o$3236 (keyword #f "contains")) (_o$3237 (lambda (sm k) (let fnrec3212 ((sm sm) (k k)) (jolt-not (jolt-nil? (let* ((_a$3213 (var-deref "clojure.core" "tree-lookup")) (_a$3214 (jolt-invoke (var-deref "clojure.core" "sfield") sm (keyword #f "tree"))) (_a$3215 (jolt-invoke (var-deref "clojure.core" "the-cmp") sm)) (_a$3216 k)) (jolt-invoke _a$3213 _a$3214 _a$3215 _a$3216))))))) (_o$3238 (keyword #f "assoc")) (_o$3239 (var-deref "clojure.core" "sm-assoc-many")) (_o$3240 (keyword #f "dissoc")) (_o$3241 (var-deref "clojure.core" "sm-dissoc-many")) (_o$3242 (keyword #f "conj")) (_o$3243 (var-deref "clojure.core" "sm-conj-many")) (_o$3244 (keyword #f "empty")) (_o$3245 (lambda (sm) (let fnrec3217 ((sm sm)) (let* ((_a$3218 (var-deref "clojure.core" "make-sorted")) (_a$3219 (keyword "jolt" "sorted-map")) (_a$3220 jolt-nil) (_a$3221 0) (_a$3222 (jolt-invoke (var-deref "clojure.core" "sfield") sm (keyword #f "cmp"))) (_a$3223 (jolt-invoke (var-deref "clojure.core" "sfield") sm (keyword #f "ops")))) (jolt-invoke _a$3218 _a$3219 _a$3220 _a$3221 _a$3222 _a$3223)))))) (jolt-hash-map _o$3224 _o$3225 _o$3226 _o$3227 _o$3228 _o$3229 _o$3230 _o$3231 _o$3232 _o$3233 _o$3234 _o$3235 _o$3236 _o$3237 _o$3238 _o$3239 _o$3240 _o$3241 _o$3242 _o$3243 _o$3244 _o$3245)) (let* ((_o$3246 (keyword #f "private")) (_o$3247 #t)) (jolt-hash-map _o$3246 _o$3247)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "ss-ops" (let* ((_o$3265 (keyword #f "count")) (_o$3266 (lambda (ss) (let fnrec3248 ((ss ss)) (jolt-invoke (var-deref "clojure.core" "sfield") ss (keyword #f "cnt"))))) (_o$3267 (keyword #f "entries")) (_o$3268 (lambda (ss) (let fnrec3249 ((ss ss)) (jolt-invoke (var-deref "clojure.core" "sc-entries") ss (var-deref "clojure.core" "nd-key"))))) (_o$3269 (keyword #f "seq")) (_o$3270 (lambda (ss) (let fnrec3250 ((ss ss)) (jolt-seq (jolt-invoke (var-deref "clojure.core" "sc-entries") ss (var-deref "clojure.core" "nd-key")))))) (_o$3271 (keyword #f "rseq")) (_o$3272 (lambda (ss) (let fnrec3251 ((ss ss)) (jolt-seq (jolt-invoke (var-deref "clojure.core" "vec") (jolt-reverse (jolt-invoke (var-deref "clojure.core" "sc-entries") ss (var-deref "clojure.core" "nd-key")))))))) (_o$3273 (keyword #f "first")) (_o$3274 (lambda (ss) (let fnrec3252 ((ss ss)) (jolt-first (jolt-invoke (var-deref "clojure.core" "sc-entries") ss (var-deref "clojure.core" "nd-key")))))) (_o$3275 (keyword #f "get")) (_o$3276 (var-deref "clojure.core" "ss-get")) (_o$3277 (keyword #f "contains")) (_o$3278 (lambda (ss x) (let fnrec3253 ((ss ss) (x x)) (jolt-not (jolt-nil? (let* ((_a$3254 (var-deref "clojure.core" "tree-lookup")) (_a$3255 (jolt-invoke (var-deref "clojure.core" "sfield") ss (keyword #f "tree"))) (_a$3256 (jolt-invoke (var-deref "clojure.core" "the-cmp") ss)) (_a$3257 x)) (jolt-invoke _a$3254 _a$3255 _a$3256 _a$3257))))))) (_o$3279 (keyword #f "conj")) (_o$3280 (var-deref "clojure.core" "ss-conj-many")) (_o$3281 (keyword #f "disj")) (_o$3282 (var-deref "clojure.core" "ss-disj-many")) (_o$3283 (keyword #f "empty")) (_o$3284 (lambda (ss) (let fnrec3258 ((ss ss)) (let* ((_a$3259 (var-deref "clojure.core" "make-sorted")) (_a$3260 (keyword "jolt" "sorted-set")) (_a$3261 jolt-nil) (_a$3262 0) (_a$3263 (jolt-invoke (var-deref "clojure.core" "sfield") ss (keyword #f "cmp"))) (_a$3264 (jolt-invoke (var-deref "clojure.core" "sfield") ss (keyword #f "ops")))) (jolt-invoke _a$3259 _a$3260 _a$3261 _a$3262 _a$3263 _a$3264)))))) (jolt-hash-map _o$3265 _o$3266 _o$3267 _o$3268 _o$3269 _o$3270 _o$3271 _o$3272 _o$3273 _o$3274 _o$3275 _o$3276 _o$3277 _o$3278 _o$3279 _o$3280 _o$3281 _o$3282 _o$3283 _o$3284)) (let* ((_o$3285 (keyword #f "private")) (_o$3286 #t)) (jolt-hash-map _o$3285 _o$3286)))) -(guard (e (#t #f)) - (def-var! "clojure.core" "sorted-map" (letrec ((sorted-map (lambda kvs (let fnrec3287 ((kvs (list->cseq kvs))) (let* ((_a$3288 (var-deref "clojure.core" "sm-assoc-many")) (_a$3289 (jolt-invoke (var-deref "clojure.core" "make-sorted") (keyword "jolt" "sorted-map") jolt-nil 0 jolt-nil (var-deref "clojure.core" "sm-ops"))) (_a$3290 (jolt-invoke (var-deref "clojure.core" "vec") kvs))) (jolt-invoke _a$3288 _a$3289 _a$3290)))))) sorted-map))) -(guard (e (#t #f)) - (def-var! "clojure.core" "sorted-map-by" (letrec ((sorted-map-by (lambda (comparator . kvs) (let fnrec3291 ((comparator comparator) (kvs (list->cseq kvs))) (let* ((_a$3292 (var-deref "clojure.core" "sm-assoc-many")) (_a$3293 (jolt-invoke (var-deref "clojure.core" "make-sorted") (keyword "jolt" "sorted-map") jolt-nil 0 (jolt-invoke (var-deref "clojure.core" "fn->cmp") comparator) (var-deref "clojure.core" "sm-ops"))) (_a$3294 (jolt-invoke (var-deref "clojure.core" "vec") kvs))) (jolt-invoke _a$3292 _a$3293 _a$3294)))))) sorted-map-by))) -(guard (e (#t #f)) - (def-var! "clojure.core" "sorted-set" (letrec ((sorted-set (lambda xs (let fnrec3295 ((xs (list->cseq xs))) (let* ((_a$3296 (var-deref "clojure.core" "ss-conj-many")) (_a$3297 (jolt-invoke (var-deref "clojure.core" "make-sorted") (keyword "jolt" "sorted-set") jolt-nil 0 jolt-nil (var-deref "clojure.core" "ss-ops"))) (_a$3298 (jolt-invoke (var-deref "clojure.core" "vec") xs))) (jolt-invoke _a$3296 _a$3297 _a$3298)))))) sorted-set))) -(guard (e (#t #f)) - (def-var! "clojure.core" "sorted-set-by" (letrec ((sorted-set-by (lambda (comparator . xs) (let fnrec3299 ((comparator comparator) (xs (list->cseq xs))) (let* ((_a$3300 (var-deref "clojure.core" "ss-conj-many")) (_a$3301 (jolt-invoke (var-deref "clojure.core" "make-sorted") (keyword "jolt" "sorted-set") jolt-nil 0 (jolt-invoke (var-deref "clojure.core" "fn->cmp") comparator) (var-deref "clojure.core" "ss-ops"))) (_a$3302 (jolt-invoke (var-deref "clojure.core" "vec") xs))) (jolt-invoke _a$3300 _a$3301 _a$3302)))))) sorted-set-by))) -(guard (e (#t #f)) - (def-var! "clojure.core" "sorted-map?" (letrec ((sorted-map? (lambda (x) (let fnrec3303 ((x x)) (jolt= (keyword "jolt" "sorted-map") (jolt-invoke (var-deref "clojure.core" "sfield") x (keyword "jolt" "type"))))))) sorted-map?))) -(guard (e (#t #f)) - (def-var! "clojure.core" "sorted-set?" (letrec ((sorted-set? (lambda (x) (let fnrec3304 ((x x)) (jolt= (keyword "jolt" "sorted-set") (jolt-invoke (var-deref "clojure.core" "sfield") x (keyword "jolt" "type"))))))) sorted-set?))) -(guard (e (#t #f)) - (def-var! "clojure.core" "sorted?" (letrec ((sorted? (lambda (x) (let fnrec3305 ((x x)) (let* ((or__26__auto (jolt-invoke (var-deref "clojure.core" "sorted-map?") x))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-invoke (var-deref "clojure.core" "sorted-set?") x))))))) sorted?))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "sc-keyf" (letrec ((sc-keyf (lambda (sc) (let fnrec3306 ((sc sc)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "sorted-map?") sc)) jolt-first jolt-identity))))) sc-keyf) (let* ((_o$3307 (keyword #f "private")) (_o$3308 #t)) (jolt-hash-map _o$3307 _o$3308)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "sc-proj" (letrec ((sc-proj (lambda (sc) (let fnrec3309 ((sc sc)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "sorted-map?") sc)) (var-deref "clojure.core" "map-entry") (var-deref "clojure.core" "nd-key")))))) sc-proj) (let* ((_o$3310 (keyword #f "private")) (_o$3311 #t)) (jolt-hash-map _o$3310 _o$3311)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "sub-filter" (letrec ((sub-filter (lambda (sc tests) (let fnrec3312 ((sc sc) (tests tests)) (let* ((cmp (jolt-invoke (var-deref "clojure.core" "the-cmp") sc)) (keyf (jolt-invoke (var-deref "clojure.core" "sc-keyf") sc))) (let* ((_a$3315 (var-deref "clojure.core" "filterv")) (_a$3316 (lambda (e) (let fnrec3313 ((e e)) (jolt-invoke (var-deref "clojure.core" "every?") (lambda (G__119) (let fnrec3314 ((G__119 G__119)) (let* ((G__120 G__119) (test (jolt-nth G__120 0 jolt-nil)) (k (jolt-nth G__120 1 jolt-nil))) (jolt-invoke test (jolt-invoke cmp (jolt-invoke keyf e) k) 0)))) tests)))) (_a$3317 (jolt-invoke (var-deref "clojure.core" "sc-entries") sc (jolt-invoke (var-deref "clojure.core" "sc-proj") sc)))) (jolt-invoke _a$3315 _a$3316 _a$3317))))))) sub-filter) (let* ((_o$3318 (keyword #f "private")) (_o$3319 #t)) (jolt-hash-map _o$3318 _o$3319)))) -(guard (e (#t #f)) - (def-var! "clojure.core" "subseq" (letrec ((subseq (case-lambda ((sc test k) (let fnrec3320 ((sc sc) (test test) (k k)) (jolt-seq (jolt-invoke (var-deref "clojure.core" "sub-filter") sc (jolt-vector (let* ((_o$3321 test) (_o$3322 k)) (jolt-vector _o$3321 _o$3322))))))) ((sc start-test start-k end-test end-k) (let fnrec3323 ((sc sc) (start-test start-test) (start-k start-k) (end-test end-test) (end-k end-k)) (jolt-seq (jolt-invoke (var-deref "clojure.core" "sub-filter") sc (let* ((_o$3328 (let* ((_o$3324 start-test) (_o$3325 start-k)) (jolt-vector _o$3324 _o$3325))) (_o$3329 (let* ((_o$3326 end-test) (_o$3327 end-k)) (jolt-vector _o$3326 _o$3327)))) (jolt-vector _o$3328 _o$3329))))))))) subseq))) -(guard (e (#t #f)) - (def-var! "clojure.core" "rsubseq" (letrec ((rsubseq (case-lambda ((sc test k) (let fnrec3330 ((sc sc) (test test) (k k)) (jolt-seq (jolt-invoke (var-deref "clojure.core" "vec") (jolt-reverse (jolt-invoke (var-deref "clojure.core" "sub-filter") sc (jolt-vector (let* ((_o$3331 test) (_o$3332 k)) (jolt-vector _o$3331 _o$3332))))))))) ((sc start-test start-k end-test end-k) (let fnrec3333 ((sc sc) (start-test start-test) (start-k start-k) (end-test end-test) (end-k end-k)) (jolt-seq (jolt-invoke (var-deref "clojure.core" "vec") (jolt-reverse (jolt-invoke (var-deref "clojure.core" "sub-filter") sc (let* ((_o$3338 (let* ((_o$3334 start-test) (_o$3335 start-k)) (jolt-vector _o$3334 _o$3335))) (_o$3339 (let* ((_o$3336 end-test) (_o$3337 end-k)) (jolt-vector _o$3336 _o$3337)))) (jolt-vector _o$3338 _o$3339))))))))))) rsubseq))) -(guard (e (#t #f)) - (def-var! "clojure.core" "comment" - (lambda body (let fnrec3340 ((body (list->cseq body))) jolt-nil))) - (mark-macro! "clojure.core" "comment")) -(guard (e (#t #f)) - (def-var! "clojure.core" "with-out-str" - (lambda body (let fnrec3341 ((body (list->cseq body))) (let* ((_a$3346 (var-deref "clojure.core" "__sqcat")) (_a$3347 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "__with-out-str"))) (_a$3348 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3342 (var-deref "clojure.core" "__sqcat")) (_a$3343 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "fn*"))) (_a$3344 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqvec")))) (_a$3345 body)) (jolt-invoke _a$3342 _a$3343 _a$3344 _a$3345))))) (jolt-invoke _a$3346 _a$3347 _a$3348))))) - (mark-macro! "clojure.core" "with-out-str")) -(guard (e (#t #f)) - (def-var! "clojure.core" "defmulti" - (lambda (name . args) (let fnrec3349 ((name name) (args (list->cseq args))) (let* ((args (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "string?") (jolt-first args))) (jolt-rest args) args)) (args (if (jolt-truthy? (let* ((and__25__auto (jolt-invoke (var-deref "clojure.core" "map?") (jolt-first args)))) (if (jolt-truthy? and__25__auto) (jolt-not (jolt-invoke (var-deref "clojure.core" "symbol?") (jolt-first args))) and__25__auto))) (jolt-rest args) args)) (dispatch (jolt-first args)) (opts (jolt-rest args)) (qname (let* ((_a$3350 (var-deref "clojure.core" "symbol")) (_a$3351 (jolt-invoke (var-deref "clojure.core" "str") (jolt-invoke (var-deref "clojure.core" "ns-name") (var-deref "clojure.core" "*ns*")))) (_a$3352 (jolt-invoke (var-deref "clojure.core" "name") name))) (jolt-invoke _a$3350 _a$3351 _a$3352)))) (let* ((_a$3356 (var-deref "clojure.core" "__sqcat")) (_a$3357 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "defmulti-setup"))) (_a$3358 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3353 (var-deref "clojure.core" "__sqcat")) (_a$3354 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "quote"))) (_a$3355 (jolt-invoke (var-deref "clojure.core" "__sq1") qname))) (jolt-invoke _a$3353 _a$3354 _a$3355)))) (_a$3359 (jolt-invoke (var-deref "clojure.core" "__sq1") dispatch)) (_a$3360 opts)) (jolt-invoke _a$3356 _a$3357 _a$3358 _a$3359 _a$3360)))))) - (mark-macro! "clojure.core" "defmulti")) -(guard (e (#t #f)) - (def-var! "clojure.core" "defmethod" - (lambda (mm dispatch-val . fn-tail) (let fnrec3361 ((mm mm) (dispatch-val dispatch-val) (fn-tail (list->cseq fn-tail))) (let* ((_a$3365 (var-deref "clojure.core" "__sqcat")) (_a$3366 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "defmethod-setup"))) (_a$3367 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3362 (var-deref "clojure.core" "__sqcat")) (_a$3363 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "quote"))) (_a$3364 (jolt-invoke (var-deref "clojure.core" "__sq1") mm))) (jolt-invoke _a$3362 _a$3363 _a$3364)))) (_a$3368 (jolt-invoke (var-deref "clojure.core" "__sq1") dispatch-val)) (_a$3369 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqcat") (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "fn")) fn-tail))) (_a$3370 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "str") (jolt-invoke (var-deref "clojure.core" "ns-name") (var-deref "clojure.core" "*ns*")))))) (jolt-invoke _a$3365 _a$3366 _a$3367 _a$3368 _a$3369 _a$3370))))) - (mark-macro! "clojure.core" "defmethod")) -(guard (e (#t #f)) - (def-var! "clojure.core" "prefer-method" - (lambda (mm dval-a dval-b) (let fnrec3371 ((mm mm) (dval-a dval-a) (dval-b dval-b)) (let* ((_a$3375 (var-deref "clojure.core" "__sqcat")) (_a$3376 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "prefer-method-setup"))) (_a$3377 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3372 (var-deref "clojure.core" "__sqcat")) (_a$3373 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "quote"))) (_a$3374 (jolt-invoke (var-deref "clojure.core" "__sq1") mm))) (jolt-invoke _a$3372 _a$3373 _a$3374)))) (_a$3378 (jolt-invoke (var-deref "clojure.core" "__sq1") dval-a)) (_a$3379 (jolt-invoke (var-deref "clojure.core" "__sq1") dval-b))) (jolt-invoke _a$3375 _a$3376 _a$3377 _a$3378 _a$3379))))) - (mark-macro! "clojure.core" "prefer-method")) -(guard (e (#t #f)) - (def-var! "clojure.core" "remove-method" - (lambda (mm dval) (let fnrec3380 ((mm mm) (dval dval)) (let* ((_a$3384 (var-deref "clojure.core" "__sqcat")) (_a$3385 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "remove-method-setup"))) (_a$3386 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3381 (var-deref "clojure.core" "__sqcat")) (_a$3382 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "quote"))) (_a$3383 (jolt-invoke (var-deref "clojure.core" "__sq1") mm))) (jolt-invoke _a$3381 _a$3382 _a$3383)))) (_a$3387 (jolt-invoke (var-deref "clojure.core" "__sq1") dval))) (jolt-invoke _a$3384 _a$3385 _a$3386 _a$3387))))) - (mark-macro! "clojure.core" "remove-method")) -(guard (e (#t #f)) - (def-var! "clojure.core" "remove-all-methods" - (lambda (mm) (let fnrec3388 ((mm mm)) (let* ((_a$3392 (var-deref "clojure.core" "__sqcat")) (_a$3393 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "remove-all-methods-setup"))) (_a$3394 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3389 (var-deref "clojure.core" "__sqcat")) (_a$3390 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "quote"))) (_a$3391 (jolt-invoke (var-deref "clojure.core" "__sq1") mm))) (jolt-invoke _a$3389 _a$3390 _a$3391))))) (jolt-invoke _a$3392 _a$3393 _a$3394))))) - (mark-macro! "clojure.core" "remove-all-methods")) -(guard (e (#t #f)) - (def-var! "clojure.core" "get-method" - (lambda (mm dval) (let fnrec3395 ((mm mm) (dval dval)) (let* ((_a$3396 (var-deref "clojure.core" "__sqcat")) (_a$3397 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "get-method-setup"))) (_a$3398 (jolt-invoke (var-deref "clojure.core" "__sq1") mm)) (_a$3399 (jolt-invoke (var-deref "clojure.core" "__sq1") dval))) (jolt-invoke _a$3396 _a$3397 _a$3398 _a$3399))))) - (mark-macro! "clojure.core" "get-method")) -(guard (e (#t #f)) - (def-var! "clojure.core" "methods" - (lambda (mm) (let fnrec3400 ((mm mm)) (let* ((_a$3401 (var-deref "clojure.core" "__sqcat")) (_a$3402 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "methods-setup"))) (_a$3403 (jolt-invoke (var-deref "clojure.core" "__sq1") mm))) (jolt-invoke _a$3401 _a$3402 _a$3403))))) - (mark-macro! "clojure.core" "methods")) -(guard (e (#t #f)) - (def-var! "clojure.core" "prefers" - (lambda (mm) (let fnrec3404 ((mm mm)) (let* ((_a$3408 (var-deref "clojure.core" "__sqcat")) (_a$3409 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "prefers-setup"))) (_a$3410 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3405 (var-deref "clojure.core" "__sqcat")) (_a$3406 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "quote"))) (_a$3407 (jolt-invoke (var-deref "clojure.core" "__sq1") mm))) (jolt-invoke _a$3405 _a$3406 _a$3407))))) (jolt-invoke _a$3408 _a$3409 _a$3410))))) - (mark-macro! "clojure.core" "prefers")) -(guard (e (#t #f)) - (def-var! "clojure.core" "instance?" - (lambda (t x) (let fnrec3411 ((t t) (x x)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "seq?") t)) (let* ((_a$3412 (var-deref "clojure.core" "__sqcat")) (_a$3413 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "instance-check"))) (_a$3414 (jolt-invoke (var-deref "clojure.core" "__sq1") t)) (_a$3415 (jolt-invoke (var-deref "clojure.core" "__sq1") x))) (jolt-invoke _a$3412 _a$3413 _a$3414 _a$3415)) (let* ((_a$3419 (var-deref "clojure.core" "__sqcat")) (_a$3420 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "instance-check"))) (_a$3421 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3416 (var-deref "clojure.core" "__sqcat")) (_a$3417 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "quote"))) (_a$3418 (jolt-invoke (var-deref "clojure.core" "__sq1") t))) (jolt-invoke _a$3416 _a$3417 _a$3418)))) (_a$3422 (jolt-invoke (var-deref "clojure.core" "__sq1") x))) (jolt-invoke _a$3419 _a$3420 _a$3421 _a$3422)))))) - (mark-macro! "clojure.core" "instance?")) -(guard (e (#t #f)) - (def-var! "clojure.core" "locking" - (lambda (x . body) (let fnrec3423 ((x x) (body (list->cseq body))) (let* ((_a$3428 (var-deref "clojure.core" "__sqcat")) (_a$3429 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "jolt.host" "with-monitor"))) (_a$3430 (jolt-invoke (var-deref "clojure.core" "__sq1") x)) (_a$3431 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3424 (var-deref "clojure.core" "__sqcat")) (_a$3425 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "fn*"))) (_a$3426 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqvec")))) (_a$3427 body)) (jolt-invoke _a$3424 _a$3425 _a$3426 _a$3427))))) (jolt-invoke _a$3428 _a$3429 _a$3430 _a$3431))))) - (mark-macro! "clojure.core" "locking")) -(guard (e (#t #f)) - (def-var! "clojure.core" "time" - (lambda (expr) (let fnrec3432 ((expr expr)) (let* ((_a$3450 (var-deref "clojure.core" "__sqcat")) (_a$3451 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "let"))) (_a$3452 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3433 (var-deref "clojure.core" "__sqvec")) (_a$3434 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "start__13__auto"))) (_a$3435 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqcat") (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "current-time-ms"))))) (_a$3436 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "ret__14__auto"))) (_a$3437 (jolt-invoke (var-deref "clojure.core" "__sq1") expr))) (jolt-invoke _a$3433 _a$3434 _a$3435 _a$3436 _a$3437)))) (_a$3453 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3447 (var-deref "clojure.core" "__sqcat")) (_a$3448 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "println"))) (_a$3449 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3442 (var-deref "clojure.core" "__sqcat")) (_a$3443 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "str"))) (_a$3444 (jolt-invoke (var-deref "clojure.core" "__sq1") "Elapsed time: ")) (_a$3445 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3438 (var-deref "clojure.core" "__sqcat")) (_a$3439 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "-"))) (_a$3440 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqcat") (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "current-time-ms"))))) (_a$3441 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "start__13__auto")))) (jolt-invoke _a$3438 _a$3439 _a$3440 _a$3441)))) (_a$3446 (jolt-invoke (var-deref "clojure.core" "__sq1") " msecs"))) (jolt-invoke _a$3442 _a$3443 _a$3444 _a$3445 _a$3446))))) (jolt-invoke _a$3447 _a$3448 _a$3449)))) (_a$3454 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "ret__14__auto")))) (jolt-invoke _a$3450 _a$3451 _a$3452 _a$3453 _a$3454))))) - (mark-macro! "clojure.core" "time")) -(guard (e (#t #f)) - (def-var! "clojure.core" "with-redefs" - (lambda (bindings . body) (let fnrec3455 ((bindings bindings) (body (list->cseq body))) (let* ((pairs (let* ((_a$3462 (lambda (acc p) (let fnrec3456 ((acc acc) (p p)) (let* ((_a$3460 (jolt-conj acc (let* ((_a$3457 (var-deref "clojure.core" "__sqcat")) (_a$3458 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "var"))) (_a$3459 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-first p)))) (jolt-invoke _a$3457 _a$3458 _a$3459)))) (_a$3461 (jolt-invoke (var-deref "clojure.core" "second") p))) (jolt-conj _a$3460 _a$3461))))) (_a$3463 (jolt-vector)) (_a$3464 (jolt-invoke (var-deref "clojure.core" "partition") 2 bindings))) (jolt-reduce _a$3462 _a$3463 _a$3464)))) (let* ((_a$3469 (var-deref "clojure.core" "__sqcat")) (_a$3470 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "with-redefs-fn"))) (_a$3471 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqcat") (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "hash-map")) pairs))) (_a$3472 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3465 (var-deref "clojure.core" "__sqcat")) (_a$3466 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "fn"))) (_a$3467 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqvec")))) (_a$3468 body)) (jolt-invoke _a$3465 _a$3466 _a$3467 _a$3468))))) (jolt-invoke _a$3469 _a$3470 _a$3471 _a$3472)))))) - (mark-macro! "clojure.core" "with-redefs")) -(guard (e (#t #f)) - (def-var! "clojure.core" "with-local-vars" - (lambda (bindings . body) (let fnrec3473 ((bindings bindings) (body (list->cseq body))) (let* ((binds (let* ((_a$3480 (lambda (acc p) (let fnrec3474 ((acc acc) (p p)) (let* ((_a$3478 (jolt-conj acc (jolt-first p))) (_a$3479 (let* ((_a$3475 (var-deref "clojure.core" "__sqcat")) (_a$3476 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "__local-var"))) (_a$3477 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "second") p)))) (jolt-invoke _a$3475 _a$3476 _a$3477)))) (jolt-conj _a$3478 _a$3479))))) (_a$3481 (jolt-vector)) (_a$3482 (jolt-invoke (var-deref "clojure.core" "partition") 2 bindings))) (jolt-reduce _a$3480 _a$3481 _a$3482)))) (let* ((_a$3483 (var-deref "clojure.core" "__sqcat")) (_a$3484 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "let"))) (_a$3485 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqvec") binds))) (_a$3486 body)) (jolt-invoke _a$3483 _a$3484 _a$3485 _a$3486)))))) - (mark-macro! "clojure.core" "with-local-vars")) -(guard (e (#t #f)) - (def-var! "clojure.core" "with-open" - (lambda (bindings . body) (let fnrec3487 ((bindings bindings) (body (list->cseq body))) (if (jolt-zero? (jolt-count bindings)) (jolt-invoke (var-deref "clojure.core" "__sqcat") (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "do")) body) (let* ((_a$3505 (var-deref "clojure.core" "__sqcat")) (_a$3506 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "let"))) (_a$3507 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3488 (var-deref "clojure.core" "__sqvec")) (_a$3489 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-first bindings))) (_a$3490 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "second") bindings)))) (jolt-invoke _a$3488 _a$3489 _a$3490)))) (_a$3508 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3501 (var-deref "clojure.core" "__sqcat")) (_a$3502 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "try"))) (_a$3503 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3491 (var-deref "clojure.core" "__sqcat")) (_a$3492 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "with-open"))) (_a$3493 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "vec") (jolt-drop 2 bindings)))) (_a$3494 body)) (jolt-invoke _a$3491 _a$3492 _a$3493 _a$3494)))) (_a$3504 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3498 (var-deref "clojure.core" "__sqcat")) (_a$3499 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "finally"))) (_a$3500 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3495 (var-deref "clojure.core" "__sqcat")) (_a$3496 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "__close"))) (_a$3497 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-first bindings)))) (jolt-invoke _a$3495 _a$3496 _a$3497))))) (jolt-invoke _a$3498 _a$3499 _a$3500))))) (jolt-invoke _a$3501 _a$3502 _a$3503 _a$3504))))) (jolt-invoke _a$3505 _a$3506 _a$3507 _a$3508)))))) - (mark-macro! "clojure.core" "with-open")) -(guard (e (#t #f)) - (def-var! "clojure.core" "with-precision" - (lambda (precision . exprs) (let fnrec3509 ((precision precision) (exprs (list->cseq exprs))) (let* ((G__121 (if (jolt= (keyword #f "rounding") (jolt-first exprs)) (let* ((_o$3510 (jolt-invoke (var-deref "clojure.core" "second") exprs)) (_o$3511 (jolt-drop 2 exprs))) (jolt-vector _o$3510 _o$3511)) (let* ((_o$3512 (jolt-symbol #f "HALF_UP")) (_o$3513 exprs)) (jolt-vector _o$3512 _o$3513)))) (rounding (jolt-nth G__121 0 jolt-nil)) (body (jolt-nth G__121 1 jolt-nil))) (let* ((_a$3520 (var-deref "clojure.core" "__sqcat")) (_a$3521 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "binding"))) (_a$3522 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3517 (var-deref "clojure.core" "__sqvec")) (_a$3518 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "*math-context*"))) (_a$3519 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqmap") (keyword #f "precision") precision (keyword #f "rounding") (let* ((_a$3514 (var-deref "clojure.core" "__sqcat")) (_a$3515 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "quote"))) (_a$3516 (jolt-invoke (var-deref "clojure.core" "__sq1") rounding))) (jolt-invoke _a$3514 _a$3515 _a$3516)))))) (jolt-invoke _a$3517 _a$3518 _a$3519)))) (_a$3523 body)) (jolt-invoke _a$3520 _a$3521 _a$3522 _a$3523)))))) - (mark-macro! "clojure.core" "with-precision")) -(guard (e (#t #f)) - (def-var! "clojure.core" "with-bindings" - (lambda (binding-map . body) (let fnrec3524 ((binding-map binding-map) (body (list->cseq body))) (let* ((_a$3529 (var-deref "clojure.core" "__sqcat")) (_a$3530 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "with-bindings*"))) (_a$3531 (jolt-invoke (var-deref "clojure.core" "__sq1") binding-map)) (_a$3532 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3525 (var-deref "clojure.core" "__sqcat")) (_a$3526 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "fn"))) (_a$3527 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqvec")))) (_a$3528 body)) (jolt-invoke _a$3525 _a$3526 _a$3527 _a$3528))))) (jolt-invoke _a$3529 _a$3530 _a$3531 _a$3532))))) - (mark-macro! "clojure.core" "with-bindings")) -(guard (e (#t #f)) - (def-var! "clojure.core" "bound-fn" - (lambda fntail (let fnrec3533 ((fntail (list->cseq fntail))) (let* ((_a$3534 (var-deref "clojure.core" "__sqcat")) (_a$3535 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "bound-fn*"))) (_a$3536 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqcat") (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "fn")) fntail)))) (jolt-invoke _a$3534 _a$3535 _a$3536))))) - (mark-macro! "clojure.core" "bound-fn")) -(guard (e (#t #f)) - (def-var! "clojure.core" "defonce" - (lambda (name expr) (let fnrec3537 ((name name) (expr expr)) (let* ((_a$3563 (var-deref "clojure.core" "__sqcat")) (_a$3564 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "let"))) (_a$3565 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3544 (var-deref "clojure.core" "__sqvec")) (_a$3545 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "v__15__auto"))) (_a$3546 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3541 (var-deref "clojure.core" "__sqcat")) (_a$3542 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "resolve"))) (_a$3543 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3538 (var-deref "clojure.core" "__sqcat")) (_a$3539 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "quote"))) (_a$3540 (jolt-invoke (var-deref "clojure.core" "__sq1") name))) (jolt-invoke _a$3538 _a$3539 _a$3540))))) (jolt-invoke _a$3541 _a$3542 _a$3543))))) (jolt-invoke _a$3544 _a$3545 _a$3546)))) (_a$3566 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3558 (var-deref "clojure.core" "__sqcat")) (_a$3559 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "if"))) (_a$3560 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3550 (var-deref "clojure.core" "__sqcat")) (_a$3551 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "and"))) (_a$3552 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "v__15__auto"))) (_a$3553 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3547 (var-deref "clojure.core" "__sqcat")) (_a$3548 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "bound?"))) (_a$3549 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "v__15__auto")))) (jolt-invoke _a$3547 _a$3548 _a$3549))))) (jolt-invoke _a$3550 _a$3551 _a$3552 _a$3553)))) (_a$3561 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "v__15__auto"))) (_a$3562 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3554 (var-deref "clojure.core" "__sqcat")) (_a$3555 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "def"))) (_a$3556 (jolt-invoke (var-deref "clojure.core" "__sq1") name)) (_a$3557 (jolt-invoke (var-deref "clojure.core" "__sq1") expr))) (jolt-invoke _a$3554 _a$3555 _a$3556 _a$3557))))) (jolt-invoke _a$3558 _a$3559 _a$3560 _a$3561 _a$3562))))) (jolt-invoke _a$3563 _a$3564 _a$3565 _a$3566))))) - (mark-macro! "clojure.core" "defonce")) -(guard (e (#t #f)) - (def-var! "clojure.core" "if-not" - (lambda (test then . G__122) (let fnrec3567 ((test test) (then then) (G__122 (list->cseq G__122))) (let* ((G__123 G__122) (_else (jolt-nth G__123 0 jolt-nil))) (let* ((_a$3571 (var-deref "clojure.core" "__sqcat")) (_a$3572 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "if"))) (_a$3573 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3568 (var-deref "clojure.core" "__sqcat")) (_a$3569 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "not"))) (_a$3570 (jolt-invoke (var-deref "clojure.core" "__sq1") test))) (jolt-invoke _a$3568 _a$3569 _a$3570)))) (_a$3574 (jolt-invoke (var-deref "clojure.core" "__sq1") then)) (_a$3575 (jolt-invoke (var-deref "clojure.core" "__sq1") _else))) (jolt-invoke _a$3571 _a$3572 _a$3573 _a$3574 _a$3575)))))) - (mark-macro! "clojure.core" "if-not")) -(guard (e (#t #f)) - (def-var! "clojure.core" "if-let" - (lambda (bindings then . G__124) (let fnrec3576 ((bindings bindings) (then then) (G__124 (list->cseq G__124))) (let* ((G__125 G__124) (_else (jolt-nth G__125 0 jolt-nil))) (let* ((form (jolt-invoke bindings 0)) (tst (jolt-invoke bindings 1))) (let* ((_a$3592 (var-deref "clojure.core" "__sqcat")) (_a$3593 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "let"))) (_a$3594 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3577 (var-deref "clojure.core" "__sqvec")) (_a$3578 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "temp__16__auto"))) (_a$3579 (jolt-invoke (var-deref "clojure.core" "__sq1") tst))) (jolt-invoke _a$3577 _a$3578 _a$3579)))) (_a$3595 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3587 (var-deref "clojure.core" "__sqcat")) (_a$3588 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "if"))) (_a$3589 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "temp__16__auto"))) (_a$3590 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3583 (var-deref "clojure.core" "__sqcat")) (_a$3584 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "let"))) (_a$3585 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3580 (var-deref "clojure.core" "__sqvec")) (_a$3581 (jolt-invoke (var-deref "clojure.core" "__sq1") form)) (_a$3582 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "temp__16__auto")))) (jolt-invoke _a$3580 _a$3581 _a$3582)))) (_a$3586 (jolt-invoke (var-deref "clojure.core" "__sq1") then))) (jolt-invoke _a$3583 _a$3584 _a$3585 _a$3586)))) (_a$3591 (jolt-invoke (var-deref "clojure.core" "__sq1") _else))) (jolt-invoke _a$3587 _a$3588 _a$3589 _a$3590 _a$3591))))) (jolt-invoke _a$3592 _a$3593 _a$3594 _a$3595))))))) - (mark-macro! "clojure.core" "if-let")) -(guard (e (#t #f)) - (def-var! "clojure.core" "if-some" - (lambda (bindings then . G__126) (let fnrec3596 ((bindings bindings) (then then) (G__126 (list->cseq G__126))) (let* ((G__127 G__126) (_else (jolt-nth G__127 0 jolt-nil))) (let* ((form (jolt-invoke bindings 0)) (tst (jolt-invoke bindings 1))) (let* ((_a$3615 (var-deref "clojure.core" "__sqcat")) (_a$3616 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "let"))) (_a$3617 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3597 (var-deref "clojure.core" "__sqvec")) (_a$3598 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "temp__17__auto"))) (_a$3599 (jolt-invoke (var-deref "clojure.core" "__sq1") tst))) (jolt-invoke _a$3597 _a$3598 _a$3599)))) (_a$3618 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3610 (var-deref "clojure.core" "__sqcat")) (_a$3611 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "if"))) (_a$3612 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3600 (var-deref "clojure.core" "__sqcat")) (_a$3601 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "some?"))) (_a$3602 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "temp__17__auto")))) (jolt-invoke _a$3600 _a$3601 _a$3602)))) (_a$3613 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3606 (var-deref "clojure.core" "__sqcat")) (_a$3607 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "let"))) (_a$3608 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3603 (var-deref "clojure.core" "__sqvec")) (_a$3604 (jolt-invoke (var-deref "clojure.core" "__sq1") form)) (_a$3605 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "temp__17__auto")))) (jolt-invoke _a$3603 _a$3604 _a$3605)))) (_a$3609 (jolt-invoke (var-deref "clojure.core" "__sq1") then))) (jolt-invoke _a$3606 _a$3607 _a$3608 _a$3609)))) (_a$3614 (jolt-invoke (var-deref "clojure.core" "__sq1") _else))) (jolt-invoke _a$3610 _a$3611 _a$3612 _a$3613 _a$3614))))) (jolt-invoke _a$3615 _a$3616 _a$3617 _a$3618))))))) - (mark-macro! "clojure.core" "if-some")) -(guard (e (#t #f)) - (def-var! "clojure.core" "when-some" - (lambda (bindings . body) (let fnrec3619 ((bindings bindings) (body (list->cseq body))) (let* ((form (jolt-invoke bindings 0)) (tst (jolt-invoke bindings 1))) (let* ((_a$3638 (var-deref "clojure.core" "__sqcat")) (_a$3639 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "let"))) (_a$3640 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3620 (var-deref "clojure.core" "__sqvec")) (_a$3621 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "temp__18__auto"))) (_a$3622 (jolt-invoke (var-deref "clojure.core" "__sq1") tst))) (jolt-invoke _a$3620 _a$3621 _a$3622)))) (_a$3641 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3633 (var-deref "clojure.core" "__sqcat")) (_a$3634 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "if"))) (_a$3635 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3623 (var-deref "clojure.core" "__sqcat")) (_a$3624 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "some?"))) (_a$3625 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "temp__18__auto")))) (jolt-invoke _a$3623 _a$3624 _a$3625)))) (_a$3636 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3629 (var-deref "clojure.core" "__sqcat")) (_a$3630 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "let"))) (_a$3631 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3626 (var-deref "clojure.core" "__sqvec")) (_a$3627 (jolt-invoke (var-deref "clojure.core" "__sq1") form)) (_a$3628 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "temp__18__auto")))) (jolt-invoke _a$3626 _a$3627 _a$3628)))) (_a$3632 body)) (jolt-invoke _a$3629 _a$3630 _a$3631 _a$3632)))) (_a$3637 (jolt-invoke (var-deref "clojure.core" "__sq1") jolt-nil))) (jolt-invoke _a$3633 _a$3634 _a$3635 _a$3636 _a$3637))))) (jolt-invoke _a$3638 _a$3639 _a$3640 _a$3641)))))) - (mark-macro! "clojure.core" "when-some")) -(guard (e (#t #f)) - (def-var! "clojure.core" "while" - (lambda (test . body) (let fnrec3642 ((test test) (body (list->cseq body))) (let* ((_a$3648 (var-deref "clojure.core" "__sqcat")) (_a$3649 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "loop"))) (_a$3650 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqvec")))) (_a$3651 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3643 (var-deref "clojure.core" "__sqcat")) (_a$3644 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "when"))) (_a$3645 (jolt-invoke (var-deref "clojure.core" "__sq1") test)) (_a$3646 body) (_a$3647 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqcat") (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "recur")))))) (jolt-invoke _a$3643 _a$3644 _a$3645 _a$3646 _a$3647))))) (jolt-invoke _a$3648 _a$3649 _a$3650 _a$3651))))) - (mark-macro! "clojure.core" "while")) -(guard (e (#t #f)) - (def-var! "clojure.core" "dotimes" - (lambda (bindings . body) (let fnrec3652 ((bindings bindings) (body (list->cseq body))) (let* ((i (jolt-invoke bindings 0)) (n (jolt-invoke bindings 1))) (let* ((_a$3678 (var-deref "clojure.core" "__sqcat")) (_a$3679 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "let"))) (_a$3680 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3653 (var-deref "clojure.core" "__sqvec")) (_a$3654 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "n__19__auto"))) (_a$3655 (jolt-invoke (var-deref "clojure.core" "__sq1") n))) (jolt-invoke _a$3653 _a$3654 _a$3655)))) (_a$3681 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3674 (var-deref "clojure.core" "__sqcat")) (_a$3675 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "loop"))) (_a$3676 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3656 (var-deref "clojure.core" "__sqvec")) (_a$3657 (jolt-invoke (var-deref "clojure.core" "__sq1") i)) (_a$3658 (jolt-invoke (var-deref "clojure.core" "__sq1") 0))) (jolt-invoke _a$3656 _a$3657 _a$3658)))) (_a$3677 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3669 (var-deref "clojure.core" "__sqcat")) (_a$3670 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "when"))) (_a$3671 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3659 (var-deref "clojure.core" "__sqcat")) (_a$3660 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "<"))) (_a$3661 (jolt-invoke (var-deref "clojure.core" "__sq1") i)) (_a$3662 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "n__19__auto")))) (jolt-invoke _a$3659 _a$3660 _a$3661 _a$3662)))) (_a$3672 body) (_a$3673 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3666 (var-deref "clojure.core" "__sqcat")) (_a$3667 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "recur"))) (_a$3668 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3663 (var-deref "clojure.core" "__sqcat")) (_a$3664 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "inc"))) (_a$3665 (jolt-invoke (var-deref "clojure.core" "__sq1") i))) (jolt-invoke _a$3663 _a$3664 _a$3665))))) (jolt-invoke _a$3666 _a$3667 _a$3668))))) (jolt-invoke _a$3669 _a$3670 _a$3671 _a$3672 _a$3673))))) (jolt-invoke _a$3674 _a$3675 _a$3676 _a$3677))))) (jolt-invoke _a$3678 _a$3679 _a$3680 _a$3681)))))) - (mark-macro! "clojure.core" "dotimes")) -(guard (e (#t #f)) - (def-var! "clojure.core" "when-first" - (lambda (bindings . body) (let fnrec3682 ((bindings bindings) (body (list->cseq body))) (let* ((x (jolt-invoke bindings 0)) (coll (jolt-invoke bindings 1))) (let* ((_a$3689 (var-deref "clojure.core" "__sqcat")) (_a$3690 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "when-let"))) (_a$3691 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3686 (var-deref "clojure.core" "__sqvec")) (_a$3687 (jolt-invoke (var-deref "clojure.core" "__sq1") x)) (_a$3688 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3683 (var-deref "clojure.core" "__sqcat")) (_a$3684 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "first"))) (_a$3685 (jolt-invoke (var-deref "clojure.core" "__sq1") coll))) (jolt-invoke _a$3683 _a$3684 _a$3685))))) (jolt-invoke _a$3686 _a$3687 _a$3688)))) (_a$3692 body)) (jolt-invoke _a$3689 _a$3690 _a$3691 _a$3692)))))) - (mark-macro! "clojure.core" "when-first")) -(guard (e (#t #f)) - (def-var! "clojure.core" "doto" - (lambda (x . forms) (let fnrec3693 ((x x) (forms (list->cseq forms))) (let* ((g (jolt-invoke (var-deref "clojure.core" "fresh-sym"))) (steps (jolt-map (lambda (f) (let fnrec3694 ((f f)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "seq?") f)) (let* ((_a$3695 jolt-list) (_a$3696 (jolt-first f)) (_a$3697 g) (_a$3698 (jolt-rest f))) (jolt-apply _a$3695 _a$3696 _a$3697 _a$3698)) (jolt-list f g)))) forms))) (let* ((_a$3702 (var-deref "clojure.core" "__sqcat")) (_a$3703 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "let"))) (_a$3704 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3699 (var-deref "clojure.core" "__sqvec")) (_a$3700 (jolt-invoke (var-deref "clojure.core" "__sq1") g)) (_a$3701 (jolt-invoke (var-deref "clojure.core" "__sq1") x))) (jolt-invoke _a$3699 _a$3700 _a$3701)))) (_a$3705 steps) (_a$3706 (jolt-invoke (var-deref "clojure.core" "__sq1") g))) (jolt-invoke _a$3702 _a$3703 _a$3704 _a$3705 _a$3706)))))) - (mark-macro! "clojure.core" "doto")) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "thread-binds" (letrec ((thread-binds (lambda (g steps) (let fnrec3707 ((g g) (steps steps)) (let* ((_a$3709 (lambda (acc s) (let fnrec3708 ((acc acc) (s s)) (jolt-conj (jolt-conj acc g) s)))) (_a$3710 (jolt-vector)) (_a$3711 (jolt-invoke (var-deref "clojure.core" "butlast") steps))) (jolt-reduce _a$3709 _a$3710 _a$3711)))))) thread-binds) (let* ((_o$3712 (keyword #f "private")) (_o$3713 #t)) (jolt-hash-map _o$3712 _o$3713)))) -(guard (e (#t #f)) - (def-var! "clojure.core" "as->" - (lambda (expr name . forms) (let fnrec3714 ((expr expr) (name name) (forms (list->cseq forms))) (let* ((pairs (let* ((_a$3716 (lambda (acc f) (let fnrec3715 ((acc acc) (f f)) (jolt-conj (jolt-conj acc name) f)))) (_a$3717 (jolt-vector)) (_a$3718 (jolt-invoke (var-deref "clojure.core" "butlast") forms))) (jolt-reduce _a$3716 _a$3717 _a$3718)))) (let* ((_a$3723 (var-deref "clojure.core" "__sqcat")) (_a$3724 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "let"))) (_a$3725 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3719 (var-deref "clojure.core" "__sqvec")) (_a$3720 (jolt-invoke (var-deref "clojure.core" "__sq1") name)) (_a$3721 (jolt-invoke (var-deref "clojure.core" "__sq1") expr)) (_a$3722 pairs)) (jolt-invoke _a$3719 _a$3720 _a$3721 _a$3722)))) (_a$3726 (jolt-invoke (var-deref "clojure.core" "__sq1") (if (jolt-empty? forms) name (jolt-last forms))))) (jolt-invoke _a$3723 _a$3724 _a$3725 _a$3726)))))) - (mark-macro! "clojure.core" "as->")) -(guard (e (#t #f)) - (def-var! "clojure.core" "some->" - (lambda (expr . forms) (let fnrec3727 ((expr expr) (forms (list->cseq forms))) (let* ((g (jolt-invoke (var-deref "clojure.core" "fresh-sym"))) (steps (jolt-map (lambda (f) (let fnrec3728 ((f f)) (let* ((_a$3736 (var-deref "clojure.core" "__sqcat")) (_a$3737 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "if"))) (_a$3738 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3729 (var-deref "clojure.core" "__sqcat")) (_a$3730 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "nil?"))) (_a$3731 (jolt-invoke (var-deref "clojure.core" "__sq1") g))) (jolt-invoke _a$3729 _a$3730 _a$3731)))) (_a$3739 (jolt-invoke (var-deref "clojure.core" "__sq1") jolt-nil)) (_a$3740 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3732 (var-deref "clojure.core" "__sqcat")) (_a$3733 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "->"))) (_a$3734 (jolt-invoke (var-deref "clojure.core" "__sq1") g)) (_a$3735 (jolt-invoke (var-deref "clojure.core" "__sq1") f))) (jolt-invoke _a$3732 _a$3733 _a$3734 _a$3735))))) (jolt-invoke _a$3736 _a$3737 _a$3738 _a$3739 _a$3740)))) forms))) (let* ((_a$3745 (var-deref "clojure.core" "__sqcat")) (_a$3746 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "let"))) (_a$3747 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3741 (var-deref "clojure.core" "__sqvec")) (_a$3742 (jolt-invoke (var-deref "clojure.core" "__sq1") g)) (_a$3743 (jolt-invoke (var-deref "clojure.core" "__sq1") expr)) (_a$3744 (jolt-invoke (var-deref "clojure.core" "thread-binds") g steps))) (jolt-invoke _a$3741 _a$3742 _a$3743 _a$3744)))) (_a$3748 (jolt-invoke (var-deref "clojure.core" "__sq1") (if (jolt-empty? steps) g (jolt-last steps))))) (jolt-invoke _a$3745 _a$3746 _a$3747 _a$3748)))))) - (mark-macro! "clojure.core" "some->")) -(guard (e (#t #f)) - (def-var! "clojure.core" "some->>" - (lambda (expr . forms) (let fnrec3749 ((expr expr) (forms (list->cseq forms))) (let* ((g (jolt-invoke (var-deref "clojure.core" "fresh-sym"))) (steps (jolt-map (lambda (f) (let fnrec3750 ((f f)) (let* ((_a$3758 (var-deref "clojure.core" "__sqcat")) (_a$3759 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "if"))) (_a$3760 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3751 (var-deref "clojure.core" "__sqcat")) (_a$3752 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "nil?"))) (_a$3753 (jolt-invoke (var-deref "clojure.core" "__sq1") g))) (jolt-invoke _a$3751 _a$3752 _a$3753)))) (_a$3761 (jolt-invoke (var-deref "clojure.core" "__sq1") jolt-nil)) (_a$3762 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3754 (var-deref "clojure.core" "__sqcat")) (_a$3755 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "->>"))) (_a$3756 (jolt-invoke (var-deref "clojure.core" "__sq1") g)) (_a$3757 (jolt-invoke (var-deref "clojure.core" "__sq1") f))) (jolt-invoke _a$3754 _a$3755 _a$3756 _a$3757))))) (jolt-invoke _a$3758 _a$3759 _a$3760 _a$3761 _a$3762)))) forms))) (let* ((_a$3767 (var-deref "clojure.core" "__sqcat")) (_a$3768 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "let"))) (_a$3769 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3763 (var-deref "clojure.core" "__sqvec")) (_a$3764 (jolt-invoke (var-deref "clojure.core" "__sq1") g)) (_a$3765 (jolt-invoke (var-deref "clojure.core" "__sq1") expr)) (_a$3766 (jolt-invoke (var-deref "clojure.core" "thread-binds") g steps))) (jolt-invoke _a$3763 _a$3764 _a$3765 _a$3766)))) (_a$3770 (jolt-invoke (var-deref "clojure.core" "__sq1") (if (jolt-empty? steps) g (jolt-last steps))))) (jolt-invoke _a$3767 _a$3768 _a$3769 _a$3770)))))) - (mark-macro! "clojure.core" "some->>")) -(guard (e (#t #f)) - (def-var! "clojure.core" "cond->>" - (lambda (expr . clauses) (let fnrec3771 ((expr expr) (clauses (list->cseq clauses))) (let* ((g (jolt-invoke (var-deref "clojure.core" "fresh-sym"))) (steps (let* ((_a$3782 (lambda (pair) (let fnrec3772 ((pair pair)) (let* ((_a$3777 (var-deref "clojure.core" "__sqcat")) (_a$3778 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "if"))) (_a$3779 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-first pair))) (_a$3780 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3773 (var-deref "clojure.core" "__sqcat")) (_a$3774 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "->>"))) (_a$3775 (jolt-invoke (var-deref "clojure.core" "__sq1") g)) (_a$3776 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "second") pair)))) (jolt-invoke _a$3773 _a$3774 _a$3775 _a$3776)))) (_a$3781 (jolt-invoke (var-deref "clojure.core" "__sq1") g))) (jolt-invoke _a$3777 _a$3778 _a$3779 _a$3780 _a$3781))))) (_a$3783 (jolt-invoke (var-deref "clojure.core" "partition") 2 clauses))) (jolt-map _a$3782 _a$3783)))) (let* ((_a$3788 (var-deref "clojure.core" "__sqcat")) (_a$3789 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "let"))) (_a$3790 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3784 (var-deref "clojure.core" "__sqvec")) (_a$3785 (jolt-invoke (var-deref "clojure.core" "__sq1") g)) (_a$3786 (jolt-invoke (var-deref "clojure.core" "__sq1") expr)) (_a$3787 (jolt-invoke (var-deref "clojure.core" "thread-binds") g steps))) (jolt-invoke _a$3784 _a$3785 _a$3786 _a$3787)))) (_a$3791 (jolt-invoke (var-deref "clojure.core" "__sq1") (if (jolt-empty? steps) g (jolt-last steps))))) (jolt-invoke _a$3788 _a$3789 _a$3790 _a$3791)))))) - (mark-macro! "clojure.core" "cond->>")) -(guard (e (#t #f)) - (def-var! "clojure.core" "assert" - (lambda (x . G__128) (let fnrec3792 ((x x) (G__128 (list->cseq G__128))) (let* ((G__129 G__128) (message (jolt-nth G__129 0 jolt-nil))) (let* ((msg (if (jolt-truthy? message) (jolt-invoke (var-deref "clojure.core" "str") "Assert failed: " message "\n" (jolt-invoke (var-deref "clojure.core" "pr-str") x)) (jolt-invoke (var-deref "clojure.core" "str") "Assert failed: " (jolt-invoke (var-deref "clojure.core" "pr-str") x))))) (let* ((_a$3800 (var-deref "clojure.core" "__sqcat")) (_a$3801 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "when-not"))) (_a$3802 (jolt-invoke (var-deref "clojure.core" "__sq1") x)) (_a$3803 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3797 (var-deref "clojure.core" "__sqcat")) (_a$3798 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "throw"))) (_a$3799 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3793 (var-deref "clojure.core" "__sqcat")) (_a$3794 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "new"))) (_a$3795 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "AssertionError"))) (_a$3796 (jolt-invoke (var-deref "clojure.core" "__sq1") msg))) (jolt-invoke _a$3793 _a$3794 _a$3795 _a$3796))))) (jolt-invoke _a$3797 _a$3798 _a$3799))))) (jolt-invoke _a$3800 _a$3801 _a$3802 _a$3803))))))) - (mark-macro! "clojure.core" "assert")) -(guard (e (#t #f)) - (def-var! "clojure.core" "pvalues" - (lambda exprs (let fnrec3804 ((exprs (list->cseq exprs))) (let* ((_a$3810 (var-deref "clojure.core" "__sqcat")) (_a$3811 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "pcalls"))) (_a$3812 (jolt-map (lambda (e) (let fnrec3805 ((e e)) (let* ((_a$3806 (var-deref "clojure.core" "__sqcat")) (_a$3807 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "fn"))) (_a$3808 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqvec")))) (_a$3809 (jolt-invoke (var-deref "clojure.core" "__sq1") e))) (jolt-invoke _a$3806 _a$3807 _a$3808 _a$3809)))) exprs))) (jolt-invoke _a$3810 _a$3811 _a$3812))))) - (mark-macro! "clojure.core" "pvalues")) -(guard (e (#t #f)) - (def-var! "clojure.core" "delay" - (lambda body (let fnrec3813 ((body (list->cseq body))) (let* ((_a$3818 (var-deref "clojure.core" "__sqcat")) (_a$3819 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "make-delay"))) (_a$3820 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3814 (var-deref "clojure.core" "__sqcat")) (_a$3815 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "fn"))) (_a$3816 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqvec")))) (_a$3817 body)) (jolt-invoke _a$3814 _a$3815 _a$3816 _a$3817))))) (jolt-invoke _a$3818 _a$3819 _a$3820))))) - (mark-macro! "clojure.core" "delay")) -(guard (e (#t #f)) - (def-var! "clojure.core" "future" - (lambda body (let fnrec3821 ((body (list->cseq body))) (let* ((_a$3826 (var-deref "clojure.core" "__sqcat")) (_a$3827 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "future-call"))) (_a$3828 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3822 (var-deref "clojure.core" "__sqcat")) (_a$3823 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "fn"))) (_a$3824 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqvec")))) (_a$3825 body)) (jolt-invoke _a$3822 _a$3823 _a$3824 _a$3825))))) (jolt-invoke _a$3826 _a$3827 _a$3828))))) - (mark-macro! "clojure.core" "future")) -(guard (e (#t #f)) - (def-var! "clojure.core" "binding" - (lambda (bindings . body) (let fnrec3829 ((bindings bindings) (body (list->cseq body))) (let* ((pairs (let* ((_a$3836 (lambda (acc p) (let fnrec3830 ((acc acc) (p p)) (let* ((_a$3834 (jolt-conj acc (let* ((_a$3831 (var-deref "clojure.core" "__sqcat")) (_a$3832 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "var"))) (_a$3833 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-first p)))) (jolt-invoke _a$3831 _a$3832 _a$3833)))) (_a$3835 (jolt-invoke (var-deref "clojure.core" "second") p))) (jolt-conj _a$3834 _a$3835))))) (_a$3837 (jolt-vector)) (_a$3838 (jolt-invoke (var-deref "clojure.core" "partition") 2 bindings))) (jolt-reduce _a$3836 _a$3837 _a$3838)))) (let* ((_a$3852 (var-deref "clojure.core" "__sqcat")) (_a$3853 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "let*"))) (_a$3854 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3839 (var-deref "clojure.core" "__sqvec")) (_a$3840 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "frame__20__auto"))) (_a$3841 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqcat") (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "array-map")) pairs)))) (jolt-invoke _a$3839 _a$3840 _a$3841)))) (_a$3855 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3842 (var-deref "clojure.core" "__sqcat")) (_a$3843 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "push-thread-bindings"))) (_a$3844 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "frame__20__auto")))) (jolt-invoke _a$3842 _a$3843 _a$3844)))) (_a$3856 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3848 (var-deref "clojure.core" "__sqcat")) (_a$3849 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "try"))) (_a$3850 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqcat") (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "do")) body))) (_a$3851 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3845 (var-deref "clojure.core" "__sqcat")) (_a$3846 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "finally"))) (_a$3847 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqcat") (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "pop-thread-bindings")))))) (jolt-invoke _a$3845 _a$3846 _a$3847))))) (jolt-invoke _a$3848 _a$3849 _a$3850 _a$3851))))) (jolt-invoke _a$3852 _a$3853 _a$3854 _a$3855 _a$3856)))))) - (mark-macro! "clojure.core" "binding")) -(guard (e (#t #f)) - (def-var! "clojure.core" "condp" - (lambda (pred expr . clauses) (let fnrec3857 ((pred pred) (expr expr) (clauses (list->cseq clauses))) (let* ((gp (jolt-invoke (var-deref "clojure.core" "fresh-sym"))) (ge (jolt-invoke (var-deref "clojure.core" "fresh-sym"))) (emit (letrec ((emit (lambda (args) (let fnrec3858 ((args args)) (let* ((n (if (jolt= (keyword #f ">>") (jolt-invoke (var-deref "clojure.core" "second") args)) 3 2)) (clause (jolt-take n args)) (more (jolt-drop n args)) (cn (jolt-count clause))) (if (jolt= 0 cn) (let* ((_a$3867 (var-deref "clojure.core" "__sqcat")) (_a$3868 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "throw"))) (_a$3869 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3863 (var-deref "clojure.core" "__sqcat")) (_a$3864 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "ex-info"))) (_a$3865 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3859 (var-deref "clojure.core" "__sqcat")) (_a$3860 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "str"))) (_a$3861 (jolt-invoke (var-deref "clojure.core" "__sq1") "No matching clause: ")) (_a$3862 (jolt-invoke (var-deref "clojure.core" "__sq1") ge))) (jolt-invoke _a$3859 _a$3860 _a$3861 _a$3862)))) (_a$3866 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqmap"))))) (jolt-invoke _a$3863 _a$3864 _a$3865 _a$3866))))) (jolt-invoke _a$3867 _a$3868 _a$3869)) (if (jolt= 1 cn) (jolt-first clause) (if (jolt= 2 cn) (let* ((_a$3874 (var-deref "clojure.core" "__sqcat")) (_a$3875 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "if"))) (_a$3876 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3870 (var-deref "clojure.core" "__sqcat")) (_a$3871 (jolt-invoke (var-deref "clojure.core" "__sq1") gp)) (_a$3872 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-first clause))) (_a$3873 (jolt-invoke (var-deref "clojure.core" "__sq1") ge))) (jolt-invoke _a$3870 _a$3871 _a$3872 _a$3873)))) (_a$3877 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "second") clause))) (_a$3878 (jolt-invoke (var-deref "clojure.core" "__sq1") (emit more)))) (jolt-invoke _a$3874 _a$3875 _a$3876 _a$3877 _a$3878)) (if (jolt-truthy? (keyword #f "else")) (let* ((_a$3889 (var-deref "clojure.core" "__sqcat")) (_a$3890 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "if-let"))) (_a$3891 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3883 (var-deref "clojure.core" "__sqvec")) (_a$3884 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "p__21__auto"))) (_a$3885 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3879 (var-deref "clojure.core" "__sqcat")) (_a$3880 (jolt-invoke (var-deref "clojure.core" "__sq1") gp)) (_a$3881 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-first clause))) (_a$3882 (jolt-invoke (var-deref "clojure.core" "__sq1") ge))) (jolt-invoke _a$3879 _a$3880 _a$3881 _a$3882))))) (jolt-invoke _a$3883 _a$3884 _a$3885)))) (_a$3892 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3886 (var-deref "clojure.core" "__sqcat")) (_a$3887 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-nth clause 2))) (_a$3888 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "p__21__auto")))) (jolt-invoke _a$3886 _a$3887 _a$3888)))) (_a$3893 (jolt-invoke (var-deref "clojure.core" "__sq1") (emit more)))) (jolt-invoke _a$3889 _a$3890 _a$3891 _a$3892 _a$3893)) jolt-nil))))))))) emit))) (let* ((_a$3899 (var-deref "clojure.core" "__sqcat")) (_a$3900 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "let"))) (_a$3901 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3894 (var-deref "clojure.core" "__sqvec")) (_a$3895 (jolt-invoke (var-deref "clojure.core" "__sq1") gp)) (_a$3896 (jolt-invoke (var-deref "clojure.core" "__sq1") pred)) (_a$3897 (jolt-invoke (var-deref "clojure.core" "__sq1") ge)) (_a$3898 (jolt-invoke (var-deref "clojure.core" "__sq1") expr))) (jolt-invoke _a$3894 _a$3895 _a$3896 _a$3897 _a$3898)))) (_a$3902 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke emit clauses)))) (jolt-invoke _a$3899 _a$3900 _a$3901 _a$3902)))))) - (mark-macro! "clojure.core" "condp")) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "group-by-head" (letrec ((group-by-head (lambda (items) (let fnrec3903 ((items items)) (let* ((_a$3907 (lambda (acc x) (let fnrec3904 ((acc acc) (x x)) (if (jolt-truthy? (let* ((or__26__auto (jolt-invoke (var-deref "clojure.core" "symbol?") x))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-nil? x)))) (jolt-conj acc (jolt-vector x)) (let* ((_a$3905 (jolt-pop acc)) (_a$3906 (jolt-conj (jolt-peek acc) x))) (jolt-conj _a$3905 _a$3906)))))) (_a$3908 (jolt-vector)) (_a$3909 items)) (jolt-reduce _a$3907 _a$3908 _a$3909)))))) group-by-head) (let* ((_o$3910 (keyword #f "private")) (_o$3911 #t)) (jolt-hash-map _o$3910 _o$3911)))) -(guard (e (#t #f)) - (def-var! "clojure.core" "defstruct" - (lambda (name . keys) (let fnrec3912 ((name name) (keys (list->cseq keys))) (let* ((_a$3913 (var-deref "clojure.core" "__sqcat")) (_a$3914 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "def"))) (_a$3915 (jolt-invoke (var-deref "clojure.core" "__sq1") name)) (_a$3916 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqcat") (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "create-struct")) keys)))) (jolt-invoke _a$3913 _a$3914 _a$3915 _a$3916))))) - (mark-macro! "clojure.core" "defstruct")) -(guard (e (#t #f)) - (def-var! "clojure.core" "deftype" - (lambda (tname fields . body) (let fnrec3917 ((tname tname) (fields fields) (body (list->cseq body))) (let* ((unwrap (lambda (x) (let fnrec3918 ((x x)) (if (jolt-truthy? (let* ((and__25__auto (jolt-invoke (var-deref "clojure.core" "seq?") x))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt-invoke (var-deref "clojure.core" "symbol?") (jolt-first x)))) (if (jolt-truthy? and__25__auto) (jolt= "with-meta" (jolt-invoke (var-deref "clojure.core" "name") (jolt-first x))) and__25__auto)) and__25__auto))) (jolt-invoke (var-deref "clojure.core" "second") x) x)))) (tname (jolt-invoke unwrap tname)) (fields (jolt-map unwrap fields)) (arrow (jolt-invoke (var-deref "clojure.core" "symbol") (jolt-invoke (var-deref "clojure.core" "str") "->" (jolt-invoke (var-deref "clojure.core" "name") tname)))) (field-kws (jolt-map (lambda (f) (let fnrec3919 ((f f)) (jolt-invoke (var-deref "clojure.core" "keyword") (jolt-invoke (var-deref "clojure.core" "name") f)))) fields)) (field-tags (jolt-map (lambda (f) (let fnrec3920 ((f f)) (let* ((mt (jolt-invoke (var-deref "clojure.core" "meta") f))) (if (jolt-truthy? (let* ((and__25__auto mt)) (if (jolt-truthy? and__25__auto) (jolt-get mt (keyword #f "tag")) and__25__auto))) (jolt-invoke (var-deref "clojure.core" "name") (jolt-get mt (keyword #f "tag"))) (if (jolt-truthy? (let* ((and__25__auto mt)) (if (jolt-truthy? and__25__auto) (jolt-get mt (keyword #f "num")) and__25__auto))) "num" (if (jolt-truthy? (keyword #f "else")) jolt-nil jolt-nil)))))) fields)) (field-muts (jolt-map (lambda (f) (let fnrec3921 ((f f)) (let* ((mt (jolt-invoke (var-deref "clojure.core" "meta") f))) (if (jolt-truthy? (let* ((and__25__auto mt)) (if (jolt-truthy? and__25__auto) (let* ((or__26__auto (jolt-get mt (keyword #f "unsynchronized-mutable")))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-get mt (keyword #f "volatile-mutable")))) and__25__auto))) #t #f)))) fields)) (mutable-syms (jolt-map jolt-first (jolt-filter (var-deref "clojure.core" "second") (jolt-map jolt-vector fields field-muts)))) (mutable? (lambda (s) (let fnrec3922 ((s s)) (jolt-invoke (var-deref "clojure.core" "boolean") (jolt-invoke (var-deref "clojure.core" "some") (lambda (m) (let fnrec3923 ((m m)) (jolt= m s))) mutable-syms))))) (rewrite-body (letrec ((rw (lambda (inst shadowed form) (let fnrec3924 ((inst inst) (shadowed shadowed) (form form)) (if (jolt-truthy? (let* ((and__25__auto (jolt-invoke (var-deref "clojure.core" "seq?") form))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt-seq form))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt-invoke (var-deref "clojure.core" "symbol?") (jolt-first form)))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt= "set!" (jolt-invoke (var-deref "clojure.core" "name") (jolt-first form))))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt-invoke (var-deref "clojure.core" "symbol?") (jolt-invoke (var-deref "clojure.core" "second") form)))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt-invoke mutable? (jolt-invoke (var-deref "clojure.core" "second") form)))) (if (jolt-truthy? and__25__auto) (jolt-not (jolt-contains? shadowed (jolt-invoke (var-deref "clojure.core" "second") form))) and__25__auto)) and__25__auto)) and__25__auto)) and__25__auto)) and__25__auto)) and__25__auto))) (let* ((_a$3925 (jolt-symbol #f "set!")) (_a$3926 (jolt-list (jolt-invoke (var-deref "clojure.core" "symbol") (jolt-invoke (var-deref "clojure.core" "str") ".-" (jolt-invoke (var-deref "clojure.core" "name") (jolt-invoke (var-deref "clojure.core" "second") form)))) inst)) (_a$3927 (rw inst shadowed (jolt-nth form 2)))) (jolt-list _a$3925 _a$3926 _a$3927)) (if (jolt-truthy? (let* ((and__25__auto (jolt-invoke (var-deref "clojure.core" "seq?") form))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt-seq form))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt-invoke (var-deref "clojure.core" "symbol?") (jolt-first form)))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (let* ((_a$3936 (let* ((_o$3928 "let") (_o$3929 "let*") (_o$3930 "loop") (_o$3931 "binding") (_o$3932 "when-let") (_o$3933 "if-let") (_o$3934 "when-some") (_o$3935 "if-some")) (jolt-hash-set _o$3928 _o$3929 _o$3930 _o$3931 _o$3932 _o$3933 _o$3934 _o$3935))) (_a$3937 (jolt-invoke (var-deref "clojure.core" "name") (jolt-first form)))) (jolt-contains? _a$3936 _a$3937)))) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "clojure.core" "vector?") (jolt-invoke (var-deref "clojure.core" "second") form)) and__25__auto)) and__25__auto)) and__25__auto)) and__25__auto))) (let* ((bv (jolt-invoke (var-deref "clojure.core" "second") form)) (n (jolt-count bv)) (bv_PRIME_ (let* ((i 0) (acc (jolt-vector))) (let loop3938 ((i i) (acc acc)) (if (jolt-n< i n) (let* ((_a$3939 (jolt-n+ i 2)) (_a$3940 (let* ((a (jolt-conj acc (jolt-nth bv i)))) (if (jolt-n< (jolt-inc i) n) (jolt-conj a (rw inst shadowed (jolt-nth bv (jolt-inc i)))) a)))) (loop3938 _a$3939 _a$3940)) acc)))) (sh (let* ((i 0) (acc shadowed)) (let loop3941 ((i i) (acc acc)) (if (jolt-n< i n) (let* ((_a$3942 (jolt-n+ i 2)) (_a$3943 (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "symbol?") (jolt-nth bv i))) (jolt-conj acc (jolt-nth bv i)) acc))) (loop3941 _a$3942 _a$3943)) acc))))) (let* ((_a$3947 (jolt-first form)) (_a$3948 (jolt-cons bv_PRIME_ (let* ((_a$3945 (lambda (x) (let fnrec3944 ((x x)) (rw inst sh x)))) (_a$3946 (jolt-drop 2 form))) (jolt-map _a$3945 _a$3946))))) (jolt-cons _a$3947 _a$3948))) (if (jolt-truthy? (let* ((and__25__auto (jolt-invoke (var-deref "clojure.core" "seq?") form))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt-seq form))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt-invoke (var-deref "clojure.core" "symbol?") (jolt-first form)))) (if (jolt-truthy? and__25__auto) (let* ((_a$3951 (let* ((_o$3949 "fn") (_o$3950 "fn*")) (jolt-hash-set _o$3949 _o$3950))) (_a$3952 (jolt-invoke (var-deref "clojure.core" "name") (jolt-first form)))) (jolt-contains? _a$3951 _a$3952)) and__25__auto)) and__25__auto)) and__25__auto))) (let* ((head (jolt-first form)) (tail (jolt-rest form)) (named? (let* ((and__25__auto (jolt-seq tail))) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "clojure.core" "symbol?") (jolt-first tail)) and__25__auto))) (fname (if (jolt-truthy? named?) (jolt-first tail) jolt-nil)) (arts (if (jolt-truthy? named?) (jolt-rest tail) tail)) (psyms (lambda (pv) (let fnrec3953 ((pv pv)) (let* ((p (jolt-seq pv)) (acc shadowed)) (let loop3954 ((p p) (acc acc)) (if (jolt-truthy? p) (let* ((_a$3955 (jolt-next p)) (_a$3956 (if (jolt-truthy? (let* ((and__25__auto (jolt-invoke (var-deref "clojure.core" "symbol?") (jolt-first p)))) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "clojure.core" "not=") (jolt-invoke (var-deref "clojure.core" "name") (jolt-first p)) "&") and__25__auto))) (jolt-conj acc (jolt-first p)) acc))) (loop3954 _a$3955 _a$3956)) acc)))))) (do-art (lambda (ar) (let fnrec3957 ((ar ar)) (let* ((_a$3961 (jolt-first ar)) (_a$3962 (let* ((_a$3959 (lambda (x) (let fnrec3958 ((x x)) (rw inst (jolt-invoke psyms (jolt-first ar)) x)))) (_a$3960 (jolt-rest ar))) (jolt-map _a$3959 _a$3960)))) (jolt-cons _a$3961 _a$3962))))) (arts_PRIME_ (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "vector?") (jolt-first arts))) (jolt-invoke do-art arts) (jolt-map do-art arts)))) (let* ((_a$3963 (jolt-list head)) (_a$3964 (if (jolt-truthy? named?) (jolt-list fname) jolt-nil)) (_a$3965 arts_PRIME_)) (jolt-concat _a$3963 _a$3964 _a$3965))) (if (jolt-truthy? (let* ((and__25__auto (jolt-invoke (var-deref "clojure.core" "symbol?") form))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt-invoke mutable? form))) (if (jolt-truthy? and__25__auto) (jolt-not (jolt-contains? shadowed form)) and__25__auto)) and__25__auto))) (jolt-list (jolt-invoke (var-deref "clojure.core" "symbol") (jolt-invoke (var-deref "clojure.core" "str") ".-" (jolt-invoke (var-deref "clojure.core" "name") form))) inst) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "seq?") form)) (jolt-map (lambda (x) (let fnrec3966 ((x x)) (rw inst shadowed x))) form) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "vector?") form)) (jolt-invoke (var-deref "clojure.core" "mapv") (lambda (x) (let fnrec3967 ((x x)) (rw inst shadowed x))) form) (if (jolt-truthy? (keyword #f "else")) form jolt-nil))))))))))) rw)) (mk-clause (lambda (spec) (let fnrec3968 ((spec spec)) (let* ((argv (let* ((_a$3970 (var-deref "clojure.core" "mapv")) (_a$3971 (lambda (p) (let fnrec3969 ((p p)) (if (jolt= p (jolt-symbol #f "_")) (jolt-invoke (var-deref "clojure.core" "gensym") "_p") p)))) (_a$3972 (jolt-nth spec 1))) (jolt-invoke _a$3970 _a$3971 _a$3972))) (inst (jolt-first argv)) (pnames (jolt-invoke (var-deref "clojure.core" "set") (jolt-map (var-deref "clojure.core" "name") argv))) (binds (jolt-invoke (var-deref "clojure.core" "vec") (let* ((_a$3981 (var-deref "clojure.core" "mapcat")) (_a$3982 (lambda (f) (let fnrec3973 ((f f)) (let* ((_o$3978 f) (_o$3979 (let* ((_a$3974 (var-deref "clojure.core" "__sqcat")) (_a$3975 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "get"))) (_a$3976 (jolt-invoke (var-deref "clojure.core" "__sq1") inst)) (_a$3977 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "keyword") (jolt-invoke (var-deref "clojure.core" "name") f))))) (jolt-invoke _a$3974 _a$3975 _a$3976 _a$3977)))) (jolt-vector _o$3978 _o$3979))))) (_a$3983 (jolt-filter (lambda (f) (let fnrec3980 ((f f)) (let* ((and__25__auto (jolt-not (jolt-invoke mutable? f)))) (if (jolt-truthy? and__25__auto) (jolt-not (jolt-contains? pnames (jolt-invoke (var-deref "clojure.core" "name") f))) and__25__auto)))) fields))) (jolt-invoke _a$3981 _a$3982 _a$3983)))) (mbody (let* ((_a$3985 (lambda (bf) (let fnrec3984 ((bf bf)) (jolt-invoke rewrite-body inst (jolt-invoke (var-deref "clojure.core" "set") argv) bf)))) (_a$3986 (jolt-drop 2 spec))) (jolt-map _a$3985 _a$3986)))) (jolt-list argv (jolt-invoke (var-deref "clojure.core" "list*") (jolt-symbol #f "let") binds mbody)))))) (groups (jolt-invoke (var-deref "clojure.core" "group-by-head") body)) (by-name (let* ((_a$3990 (lambda (m spec) (let fnrec3987 ((m m) (spec spec)) (let* ((nm (jolt-invoke (var-deref "clojure.core" "name") (jolt-first spec)))) (jolt-assoc m nm (let* ((_a$3988 (jolt-get m nm (jolt-vector))) (_a$3989 (jolt-invoke mk-clause spec))) (jolt-conj _a$3988 _a$3989))))))) (_a$3991 (jolt-hash-map)) (_a$3992 (jolt-invoke (var-deref "clojure.core" "mapcat") jolt-rest groups))) (jolt-reduce _a$3990 _a$3991 _a$3992)))) (let* ((_a$4030 (var-deref "clojure.core" "__sqcat")) (_a$4031 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "do"))) (_a$4032 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$4002 (var-deref "clojure.core" "__sqcat")) (_a$4003 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "def"))) (_a$4004 (jolt-invoke (var-deref "clojure.core" "__sq1") tname)) (_a$4005 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3996 (var-deref "clojure.core" "__sqcat")) (_a$3997 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "make-deftype-ctor"))) (_a$3998 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$3993 (var-deref "clojure.core" "__sqcat")) (_a$3994 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "quote"))) (_a$3995 (jolt-invoke (var-deref "clojure.core" "__sq1") tname))) (jolt-invoke _a$3993 _a$3994 _a$3995)))) (_a$3999 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqvec") field-kws))) (_a$4000 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqvec") field-tags))) (_a$4001 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqvec") field-muts)))) (jolt-invoke _a$3996 _a$3997 _a$3998 _a$3999 _a$4000 _a$4001))))) (jolt-invoke _a$4002 _a$4003 _a$4004 _a$4005)))) (_a$4033 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$4006 (var-deref "clojure.core" "__sqcat")) (_a$4007 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "def"))) (_a$4008 (jolt-invoke (var-deref "clojure.core" "__sq1") arrow)) (_a$4009 (jolt-invoke (var-deref "clojure.core" "__sq1") tname))) (jolt-invoke _a$4006 _a$4007 _a$4008 _a$4009)))) (_a$4034 (jolt-invoke (var-deref "clojure.core" "mapcat") (lambda (g) (let fnrec4010 ((g g)) (let* ((proto (jolt-first g)) (names (jolt-invoke (var-deref "clojure.core" "distinct") (let* ((_a$4012 (lambda (spec) (let fnrec4011 ((spec spec)) (jolt-invoke (var-deref "clojure.core" "name") (jolt-first spec))))) (_a$4013 (jolt-rest g))) (jolt-map _a$4012 _a$4013))))) (let* ((_a$4028 (let* ((_a$4014 (var-deref "clojure.core" "__sqcat")) (_a$4015 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "register-inline-protocol!"))) (_a$4016 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "name") tname))) (_a$4017 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "name") proto)))) (jolt-invoke _a$4014 _a$4015 _a$4016 _a$4017))) (_a$4029 (jolt-map (lambda (nm) (let fnrec4018 ((nm nm)) (let* ((_a$4022 (var-deref "clojure.core" "__sqcat")) (_a$4023 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "register-inline-method"))) (_a$4024 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "name") tname))) (_a$4025 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "name") proto))) (_a$4026 (jolt-invoke (var-deref "clojure.core" "__sq1") nm)) (_a$4027 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$4019 (var-deref "clojure.core" "__sqcat")) (_a$4020 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "fn"))) (_a$4021 (jolt-get by-name nm))) (jolt-invoke _a$4019 _a$4020 _a$4021))))) (jolt-invoke _a$4022 _a$4023 _a$4024 _a$4025 _a$4026 _a$4027)))) names))) (jolt-cons _a$4028 _a$4029))))) groups)) (_a$4035 (jolt-invoke (var-deref "clojure.core" "__sq1") tname))) (jolt-invoke _a$4030 _a$4031 _a$4032 _a$4033 _a$4034 _a$4035)))))) - (mark-macro! "clojure.core" "deftype")) -(guard (e (#t #f)) - (def-var! "clojure.core" "defprotocol" - (lambda (pname . sigs) (let fnrec4036 ((pname pname) (sigs (list->cseq sigs))) (let* ((sigs (let* ((s sigs)) (let loop4037 ((s s)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "string?") (jolt-first s))) (loop4037 (jolt-rest s)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "keyword?") (jolt-first s))) (loop4037 (jolt-rest (jolt-rest s))) (if (jolt-truthy? (keyword #f "else")) s jolt-nil)))))) (methods (let* ((_a$4044 (lambda (m sig) (let fnrec4038 ((m m) (sig sig)) (let* ((_a$4041 m) (_a$4042 (jolt-invoke (var-deref "clojure.core" "keyword") (jolt-invoke (var-deref "clojure.core" "name") (jolt-first sig)))) (_a$4043 (let* ((_o$4039 (keyword #f "name")) (_o$4040 (jolt-invoke (var-deref "clojure.core" "name") (jolt-first sig)))) (jolt-hash-map _o$4039 _o$4040)))) (jolt-assoc _a$4041 _a$4042 _a$4043))))) (_a$4045 (jolt-hash-map)) (_a$4046 sigs)) (jolt-reduce _a$4044 _a$4045 _a$4046)))) (let* ((_a$4094 (var-deref "clojure.core" "__sqcat")) (_a$4095 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "do"))) (_a$4096 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$4051 (var-deref "clojure.core" "__sqcat")) (_a$4052 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "def"))) (_a$4053 (jolt-invoke (var-deref "clojure.core" "__sq1") pname)) (_a$4054 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$4047 (var-deref "clojure.core" "__sqcat")) (_a$4048 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "make-protocol"))) (_a$4049 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "name") pname))) (_a$4050 (jolt-invoke (var-deref "clojure.core" "__sq1") methods))) (jolt-invoke _a$4047 _a$4048 _a$4049 _a$4050))))) (jolt-invoke _a$4051 _a$4052 _a$4053 _a$4054)))) (_a$4097 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$4056 (var-deref "clojure.core" "__sqcat")) (_a$4057 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "register-protocol-methods!"))) (_a$4058 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "name") pname))) (_a$4059 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqvec") (jolt-map (lambda (s) (let fnrec4055 ((s s)) (jolt-invoke (var-deref "clojure.core" "name") (jolt-first s)))) sigs))))) (jolt-invoke _a$4056 _a$4057 _a$4058 _a$4059)))) (_a$4098 (jolt-map (lambda (sig) (let fnrec4060 ((sig sig)) (let* ((pn (jolt-invoke (var-deref "clojure.core" "name") pname)) (mn (jolt-invoke (var-deref "clojure.core" "name") (jolt-first sig))) (arglists (jolt-filter (var-deref "clojure.core" "vector?") (jolt-rest sig))) (clause (lambda (argv) (let fnrec4061 ((argv argv)) (let* ((ps (jolt-invoke (var-deref "clojure.core" "mapv") (lambda (_) (let fnrec4062 ((_ _)) (jolt-invoke (var-deref "clojure.core" "fresh-sym")))) argv)) (n (jolt-count ps)) (obj (jolt-first ps))) (if (jolt= n 1) (jolt-list ps (jolt-list (jolt-symbol #f "protocol-dispatch1") pn mn obj)) (if (jolt= n 2) (jolt-list ps (jolt-list (jolt-symbol #f "protocol-dispatch2") pn mn obj (jolt-nth ps 1))) (if (jolt= n 3) (jolt-list ps (let* ((_a$4063 (jolt-symbol #f "protocol-dispatch3")) (_a$4064 pn) (_a$4065 mn) (_a$4066 obj) (_a$4067 (jolt-nth ps 1)) (_a$4068 (jolt-nth ps 2))) (jolt-list _a$4063 _a$4064 _a$4065 _a$4066 _a$4067 _a$4068))) (if (jolt-truthy? (keyword #f "else")) (jolt-list ps (jolt-list (jolt-symbol #f "protocol-dispatch") pn mn obj (jolt-invoke (var-deref "clojure.core" "vec") (jolt-rest ps)))) jolt-nil))))))))) (if (jolt-truthy? (jolt-seq arglists)) (let* ((_a$4072 (var-deref "clojure.core" "__sqcat")) (_a$4073 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "def"))) (_a$4074 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-first sig))) (_a$4075 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$4069 (var-deref "clojure.core" "__sqcat")) (_a$4070 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "fn*"))) (_a$4071 (jolt-map clause arglists))) (jolt-invoke _a$4069 _a$4070 _a$4071))))) (jolt-invoke _a$4072 _a$4073 _a$4074 _a$4075)) (let* ((_a$4090 (var-deref "clojure.core" "__sqcat")) (_a$4091 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "def"))) (_a$4092 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-first sig))) (_a$4093 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$4086 (var-deref "clojure.core" "__sqcat")) (_a$4087 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "fn*"))) (_a$4088 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$4076 (var-deref "clojure.core" "__sqvec")) (_a$4077 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "this__23__auto"))) (_a$4078 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "&"))) (_a$4079 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "rest__22__auto")))) (jolt-invoke _a$4076 _a$4077 _a$4078 _a$4079)))) (_a$4089 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$4080 (var-deref "clojure.core" "__sqcat")) (_a$4081 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "protocol-dispatch"))) (_a$4082 (jolt-invoke (var-deref "clojure.core" "__sq1") pn)) (_a$4083 (jolt-invoke (var-deref "clojure.core" "__sq1") mn)) (_a$4084 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "this__23__auto"))) (_a$4085 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "rest__22__auto")))) (jolt-invoke _a$4080 _a$4081 _a$4082 _a$4083 _a$4084 _a$4085))))) (jolt-invoke _a$4086 _a$4087 _a$4088 _a$4089))))) (jolt-invoke _a$4090 _a$4091 _a$4092 _a$4093)))))) sigs))) (jolt-invoke _a$4094 _a$4095 _a$4096 _a$4097 _a$4098)))))) - (mark-macro! "clojure.core" "defprotocol")) -(guard (e (#t #f)) - (def-var! "clojure.core" ".." - (lambda (x form . more) (let fnrec4099 ((x x) (form form) (more (list->cseq more))) (let* ((step (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "seq?") form)) (let* ((_a$4100 (var-deref "clojure.core" "__sqcat")) (_a$4101 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "."))) (_a$4102 (jolt-invoke (var-deref "clojure.core" "__sq1") x)) (_a$4103 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-first form))) (_a$4104 (jolt-rest form))) (jolt-invoke _a$4100 _a$4101 _a$4102 _a$4103 _a$4104)) (let* ((_a$4105 (var-deref "clojure.core" "__sqcat")) (_a$4106 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "."))) (_a$4107 (jolt-invoke (var-deref "clojure.core" "__sq1") x)) (_a$4108 (jolt-invoke (var-deref "clojure.core" "__sq1") form))) (jolt-invoke _a$4105 _a$4106 _a$4107 _a$4108))))) (if (jolt-truthy? (jolt-seq more)) (let* ((_a$4109 (var-deref "clojure.core" "__sqcat")) (_a$4110 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" ".."))) (_a$4111 (jolt-invoke (var-deref "clojure.core" "__sq1") step)) (_a$4112 more)) (jolt-invoke _a$4109 _a$4110 _a$4111 _a$4112)) step))))) - (mark-macro! "clojure.core" "..")) -(guard (e (#t #f)) - (def-var! "clojure.core" "extends?" (letrec ((extends? (lambda (protocol atype) (let fnrec4113 ((protocol protocol) (atype atype)) (let* ((want (if (jolt-nil? atype) "nil" (jolt-invoke (var-deref "clojure.core" "name") atype))) (suffix? (lambda (long short) (let fnrec4114 ((long long) (short short)) (let* ((d (jolt-invoke (var-deref "clojure.core" "str") "." short))) (let* ((and__25__auto (let* ((_a$4115 (jolt-count long)) (_a$4116 (jolt-count d))) (jolt-n> _a$4115 _a$4116)))) (if (jolt-truthy? and__25__auto) (jolt= (jolt-invoke (var-deref "clojure.core" "subs") long (let* ((_a$4117 (jolt-count long)) (_a$4118 (jolt-count d))) (jolt-n- _a$4117 _a$4118))) d) and__25__auto))))))) (jolt-invoke (var-deref "clojure.core" "boolean") (let* ((_a$4120 (var-deref "clojure.core" "some")) (_a$4121 (lambda (t) (let fnrec4119 ((t t)) (let* ((tn (jolt-invoke (var-deref "clojure.core" "name") t))) (let* ((or__26__auto (jolt= tn want))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt-invoke suffix? tn want))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-invoke suffix? want tn))))))))) (_a$4122 (jolt-invoke (var-deref "clojure.core" "extenders") protocol))) (jolt-invoke _a$4120 _a$4121 _a$4122)))))))) extends?))) -(guard (e (#t #f)) - (def-var! "clojure.core" "type->name" (letrec ((type->name (lambda (t) (let fnrec4123 ((t t)) (if (jolt-nil? t) "nil" (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "string?") t)) t (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "symbol?") t)) (jolt-invoke (var-deref "clojure.core" "name") t) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "keyword?") t)) (jolt-invoke (var-deref "clojure.core" "name") t) (if (jolt-truthy? (keyword #f "else")) (record-method-dispatch t "getName" (jolt-vector)) jolt-nil))))))))) type->name))) -(guard (e (#t #f)) - (def-var! "clojure.core" "extend" (letrec ((extend (lambda (atype . proto+mmaps) (let fnrec4124 ((atype atype) (proto+mmaps (list->cseq proto+mmaps))) (let* ((tname (jolt-invoke (var-deref "clojure.core" "type->name") atype))) (let* ((s (jolt-seq proto+mmaps))) (let loop4125 ((s s)) (if (jolt-truthy? s) (begin (let* ((proto (jolt-first s)) (mmap (jolt-invoke (var-deref "clojure.core" "second") s)) (pname (jolt-invoke (var-deref "clojure.core" "name") (jolt-get proto (keyword #f "name"))))) (begin (jolt-count (jolt-map (lambda (G__130) (let fnrec4126 ((G__130 G__130)) (let* ((G__131 G__130) (k (jolt-nth G__131 0 jolt-nil)) (f (jolt-nth G__131 1 jolt-nil))) (begin (jolt-invoke (var-deref "clojure.core" "register-method") tname pname (jolt-invoke (var-deref "clojure.core" "name") k) f) jolt-nil)))) mmap)) jolt-nil)) (loop4125 (jolt-invoke (var-deref "clojure.core" "nnext") s))) jolt-nil)))))))) extend))) -(guard (e (#t #f)) - (def-var! "clojure.core" "extend-type" - (lambda (tsym . body) (let fnrec4127 ((tsym tsym) (body (list->cseq body))) (let* ((literal? (let* ((or__26__auto (jolt-nil? tsym))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-invoke (var-deref "clojure.core" "symbol?") tsym)))) (tn (jolt-invoke (var-deref "clojure.core" "gensym") "tname")) (tref (if (jolt-truthy? literal?) (if (jolt-nil? tsym) "nil" (jolt-invoke (var-deref "clojure.core" "name") tsym)) tn)) (emit (lambda () (let fnrec4128 () (let* ((items (jolt-seq body)) (proto jolt-nil) (forms (jolt-vector))) (let loop4129 ((items items) (proto proto) (forms forms)) (if (jolt-empty? items) forms (let* ((x (jolt-first items))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "symbol?") x)) (let* ((_a$4130 (jolt-rest items)) (_a$4131 (jolt-invoke (var-deref "clojure.core" "name") x)) (_a$4132 forms)) (loop4129 _a$4130 _a$4131 _a$4132)) (let* ((_a$4143 (jolt-rest items)) (_a$4144 proto) (_a$4145 (jolt-conj forms (let* ((_a$4137 (var-deref "clojure.core" "__sqcat")) (_a$4138 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "register-method"))) (_a$4139 (jolt-invoke (var-deref "clojure.core" "__sq1") tref)) (_a$4140 (jolt-invoke (var-deref "clojure.core" "__sq1") proto)) (_a$4141 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "name") (jolt-first x)))) (_a$4142 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$4133 (var-deref "clojure.core" "__sqcat")) (_a$4134 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "fn"))) (_a$4135 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-nth x 1))) (_a$4136 (jolt-drop 2 x))) (jolt-invoke _a$4133 _a$4134 _a$4135 _a$4136))))) (jolt-invoke _a$4137 _a$4138 _a$4139 _a$4140 _a$4141 _a$4142))))) (loop4129 _a$4143 _a$4144 _a$4145))))))))))) (if (jolt-truthy? literal?) (let* ((_a$4146 (var-deref "clojure.core" "__sqcat")) (_a$4147 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "do"))) (_a$4148 (jolt-invoke emit))) (jolt-invoke _a$4146 _a$4147 _a$4148)) (let* ((_a$4155 (var-deref "clojure.core" "__sqcat")) (_a$4156 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "let"))) (_a$4157 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$4152 (var-deref "clojure.core" "__sqvec")) (_a$4153 (jolt-invoke (var-deref "clojure.core" "__sq1") tn)) (_a$4154 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$4149 (var-deref "clojure.core" "__sqcat")) (_a$4150 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "type->name"))) (_a$4151 (jolt-invoke (var-deref "clojure.core" "__sq1") tsym))) (jolt-invoke _a$4149 _a$4150 _a$4151))))) (jolt-invoke _a$4152 _a$4153 _a$4154)))) (_a$4158 (jolt-invoke emit)) (_a$4159 (jolt-invoke (var-deref "clojure.core" "__sq1") jolt-nil))) (jolt-invoke _a$4155 _a$4156 _a$4157 _a$4158 _a$4159))))))) - (mark-macro! "clojure.core" "extend-type")) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "parse-extend-impls" (letrec ((parse-extend-impls (lambda (items) (let fnrec4160 ((items items)) (let* ((s (jolt-seq items)) (groups (jolt-vector))) (let loop4161 ((s s) (groups groups)) (if (jolt-empty? s) groups (let* ((after (jolt-rest s))) (let* ((_a$4164 (jolt-invoke (var-deref "clojure.core" "drop-while") (var-deref "clojure.core" "seq?") after)) (_a$4165 (jolt-conj groups (jolt-invoke (var-deref "clojure.core" "vec") (let* ((_a$4162 (jolt-first s)) (_a$4163 (jolt-invoke (var-deref "clojure.core" "take-while") (var-deref "clojure.core" "seq?") after))) (jolt-cons _a$4162 _a$4163)))))) (loop4161 _a$4164 _a$4165)))))))))) parse-extend-impls) (let* ((_o$4166 (keyword #f "private")) (_o$4167 #t)) (jolt-hash-map _o$4166 _o$4167)))) -(guard (e (#t #f)) - (def-var! "clojure.core" "extend-protocol" - (lambda (psym . type-impls) (let fnrec4168 ((psym psym) (type-impls (list->cseq type-impls))) (let* ((_a$4177 (var-deref "clojure.core" "__sqcat")) (_a$4178 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "do"))) (_a$4179 (let* ((_a$4175 (lambda (g) (let fnrec4169 ((g g)) (let* ((_a$4170 (var-deref "clojure.core" "__sqcat")) (_a$4171 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "extend-type"))) (_a$4172 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-first g))) (_a$4173 (jolt-invoke (var-deref "clojure.core" "__sq1") psym)) (_a$4174 (jolt-rest g))) (jolt-invoke _a$4170 _a$4171 _a$4172 _a$4173 _a$4174))))) (_a$4176 (jolt-invoke (var-deref "clojure.core" "parse-extend-impls") type-impls))) (jolt-map _a$4175 _a$4176)))) (jolt-invoke _a$4177 _a$4178 _a$4179))))) - (mark-macro! "clojure.core" "extend-protocol")) -(guard (e (#t #f)) - (def-var! "clojure.core" "proxy" - (lambda (supers ctor-args . methods) (let fnrec4180 ((supers supers) (ctor-args ctor-args) (methods (list->cseq methods))) (if (jolt-truthy? (let* ((and__25__auto (jolt-invoke (var-deref "clojure.core" "vector?") supers))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt= 1 (jolt-count supers)))) (if (jolt-truthy? and__25__auto) (let* ((s (jolt-invoke (var-deref "clojure.core" "name") (jolt-first supers)))) (let* ((or__26__auto (jolt= s "ThreadLocal"))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt= s "InheritableThreadLocal")))) and__25__auto)) and__25__auto))) (let* ((init (jolt-invoke (var-deref "clojure.core" "some") (lambda (m) (let fnrec4181 ((m m)) (if (jolt= "initialValue" (jolt-invoke (var-deref "clojure.core" "name") (jolt-first m))) m jolt-nil))) methods))) (let* ((_a$4186 (var-deref "clojure.core" "__sqcat")) (_a$4187 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "jolt.host" "make-thread-local"))) (_a$4188 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$4182 (var-deref "clojure.core" "__sqcat")) (_a$4183 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "fn"))) (_a$4184 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqvec")))) (_a$4185 (if (jolt-truthy? init) (jolt-invoke (var-deref "clojure.core" "nnext") init) jolt-nil))) (jolt-invoke _a$4182 _a$4183 _a$4184 _a$4185))))) (jolt-invoke _a$4186 _a$4187 _a$4188))) jolt-nil)))) - (mark-macro! "clojure.core" "proxy")) -(guard (e (#t #f)) - (def-var! "clojure.core" "definterface" - (lambda (name-sym . body) (let fnrec4189 ((name-sym name-sym) (body (list->cseq body))) (let* ((_a$4197 (var-deref "clojure.core" "__sqcat")) (_a$4198 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "do"))) (_a$4199 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$4190 (var-deref "clojure.core" "__sqcat")) (_a$4191 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "def"))) (_a$4192 (jolt-invoke (var-deref "clojure.core" "__sq1") name-sym)) (_a$4193 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqmap"))))) (jolt-invoke _a$4190 _a$4191 _a$4192 _a$4193)))) (_a$4200 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$4194 (var-deref "clojure.core" "__sqcat")) (_a$4195 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "quote"))) (_a$4196 (jolt-invoke (var-deref "clojure.core" "__sq1") name-sym))) (jolt-invoke _a$4194 _a$4195 _a$4196))))) (jolt-invoke _a$4197 _a$4198 _a$4199 _a$4200))))) - (mark-macro! "clojure.core" "definterface")) -(guard (e (#t #f)) - (def-var! "clojure.core" "reify" - (lambda forms (let fnrec4201 ((forms (list->cseq forms))) (let* ((items (jolt-seq forms)) (protos (jolt-vector)) (methods (jolt-hash-map)) (order (jolt-vector))) (let loop4202 ((items items) (protos protos) (methods methods) (order order)) (if (jolt-empty? items) (let* ((_a$4210 (var-deref "clojure.core" "__sqcat")) (_a$4211 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "make-reified"))) (_a$4212 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$4207 (lambda (m k) (let fnrec4203 ((m m) (k k)) (jolt-assoc m k (let* ((_a$4204 (var-deref "clojure.core" "__sqcat")) (_a$4205 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "fn"))) (_a$4206 (jolt-get methods k))) (jolt-invoke _a$4204 _a$4205 _a$4206)))))) (_a$4208 (jolt-hash-map)) (_a$4209 order)) (jolt-reduce _a$4207 _a$4208 _a$4209)))) (_a$4213 (jolt-invoke (var-deref "clojure.core" "vec") (jolt-map (var-deref "clojure.core" "name") protos)))) (jolt-invoke _a$4210 _a$4211 _a$4212 _a$4213)) (let* ((x (jolt-first items))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "symbol?") x)) (let* ((_a$4214 (jolt-rest items)) (_a$4215 (jolt-conj protos x)) (_a$4216 methods) (_a$4217 order)) (loop4202 _a$4214 _a$4215 _a$4216 _a$4217)) (let* ((k (jolt-invoke (var-deref "clojure.core" "keyword") (jolt-invoke (var-deref "clojure.core" "name") (jolt-first x)))) (clause (let* ((_a$4218 (var-deref "clojure.core" "__sqcat")) (_a$4219 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-nth x 1))) (_a$4220 (jolt-drop 2 x))) (jolt-invoke _a$4218 _a$4219 _a$4220)))) (let* ((_a$4221 (jolt-rest items)) (_a$4222 protos) (_a$4223 (jolt-assoc methods k (jolt-conj (jolt-get methods k (jolt-vector)) clause))) (_a$4224 (if (jolt-contains? methods k) order (jolt-conj order k)))) (loop4202 _a$4221 _a$4222 _a$4223 _a$4224))))))))))) - (mark-macro! "clojure.core" "reify")) -(guard (e (#t #f)) - (def-var! "clojure.core" "defrecord" - (lambda (name-sym fields . body) (let fnrec4225 ((name-sym name-sym) (fields fields) (body (list->cseq body))) (let* ((tn (jolt-invoke (var-deref "clojure.core" "name") name-sym)) (arrow (jolt-invoke (var-deref "clojure.core" "symbol") (jolt-invoke (var-deref "clojure.core" "str") "->" tn))) (mapf (jolt-invoke (var-deref "clojure.core" "symbol") (jolt-invoke (var-deref "clojure.core" "str") "map->" tn))) (m (jolt-invoke (var-deref "clojure.core" "fresh-sym"))) (mk-clause (lambda (spec) (let fnrec4226 ((spec spec)) (let* ((argv (let* ((_a$4228 (var-deref "clojure.core" "mapv")) (_a$4229 (lambda (p) (let fnrec4227 ((p p)) (if (jolt= p (jolt-symbol #f "_")) (jolt-invoke (var-deref "clojure.core" "gensym") "_p") p)))) (_a$4230 (jolt-nth spec 1))) (jolt-invoke _a$4228 _a$4229 _a$4230))) (inst (jolt-first argv)) (hinted (jolt-assoc argv 0 (jolt-invoke (var-deref "clojure.core" "vary-meta") inst jolt-assoc (keyword #f "tag") (jolt-invoke (var-deref "clojure.core" "name") name-sym)))) (pnames (jolt-invoke (var-deref "clojure.core" "set") (jolt-map (var-deref "clojure.core" "name") argv))) (binds (jolt-invoke (var-deref "clojure.core" "vec") (let* ((_a$4239 (var-deref "clojure.core" "mapcat")) (_a$4240 (lambda (f) (let fnrec4231 ((f f)) (let* ((_o$4236 f) (_o$4237 (let* ((_a$4232 (var-deref "clojure.core" "__sqcat")) (_a$4233 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "get"))) (_a$4234 (jolt-invoke (var-deref "clojure.core" "__sq1") inst)) (_a$4235 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "keyword") (jolt-invoke (var-deref "clojure.core" "name") f))))) (jolt-invoke _a$4232 _a$4233 _a$4234 _a$4235)))) (jolt-vector _o$4236 _o$4237))))) (_a$4241 (jolt-remove (lambda (f) (let fnrec4238 ((f f)) (jolt-contains? pnames (jolt-invoke (var-deref "clojure.core" "name") f)))) fields))) (jolt-invoke _a$4239 _a$4240 _a$4241))))) (jolt-list hinted (jolt-invoke (var-deref "clojure.core" "list*") (jolt-symbol #f "let") binds (jolt-drop 2 spec))))))) (groups (jolt-invoke (var-deref "clojure.core" "group-by-head") body)) (by-name (let* ((_a$4245 (lambda (m spec) (let fnrec4242 ((m m) (spec spec)) (let* ((nm (jolt-invoke (var-deref "clojure.core" "name") (jolt-first spec)))) (jolt-assoc m nm (let* ((_a$4243 (jolt-get m nm (jolt-vector))) (_a$4244 (jolt-invoke mk-clause spec))) (jolt-conj _a$4243 _a$4244))))))) (_a$4246 (jolt-hash-map)) (_a$4247 (jolt-invoke (var-deref "clojure.core" "mapcat") jolt-rest groups))) (jolt-reduce _a$4245 _a$4246 _a$4247)))) (let* ((_a$4304 (var-deref "clojure.core" "__sqcat")) (_a$4305 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "do"))) (_a$4306 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$4248 (var-deref "clojure.core" "__sqcat")) (_a$4249 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "deftype"))) (_a$4250 (jolt-invoke (var-deref "clojure.core" "__sq1") name-sym)) (_a$4251 (jolt-invoke (var-deref "clojure.core" "__sq1") fields))) (jolt-invoke _a$4248 _a$4249 _a$4250 _a$4251)))) (_a$4307 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$4255 (var-deref "clojure.core" "__sqcat")) (_a$4256 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "register-record-type!"))) (_a$4257 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$4252 (var-deref "clojure.core" "__sqcat")) (_a$4253 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "quote"))) (_a$4254 (jolt-invoke (var-deref "clojure.core" "__sq1") name-sym))) (jolt-invoke _a$4252 _a$4253 _a$4254))))) (jolt-invoke _a$4255 _a$4256 _a$4257)))) (_a$4308 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$4280 (var-deref "clojure.core" "__sqcat")) (_a$4281 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "def"))) (_a$4282 (jolt-invoke (var-deref "clojure.core" "__sq1") mapf)) (_a$4283 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$4276 (var-deref "clojure.core" "__sqcat")) (_a$4277 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "fn*"))) (_a$4278 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqvec") (jolt-invoke (var-deref "clojure.core" "__sq1") m)))) (_a$4279 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$4271 (var-deref "clojure.core" "__sqcat")) (_a$4272 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "reduce-kv"))) (_a$4273 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "assoc"))) (_a$4274 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$4263 (var-deref "clojure.core" "__sqcat")) (_a$4264 (jolt-invoke (var-deref "clojure.core" "__sq1") arrow)) (_a$4265 (jolt-map (lambda (f) (let fnrec4258 ((f f)) (let* ((_a$4259 (var-deref "clojure.core" "__sqcat")) (_a$4260 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "get"))) (_a$4261 (jolt-invoke (var-deref "clojure.core" "__sq1") m)) (_a$4262 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "keyword") (jolt-invoke (var-deref "clojure.core" "name") f))))) (jolt-invoke _a$4259 _a$4260 _a$4261 _a$4262)))) fields))) (jolt-invoke _a$4263 _a$4264 _a$4265)))) (_a$4275 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$4267 (var-deref "clojure.core" "__sqcat")) (_a$4268 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "dissoc"))) (_a$4269 (jolt-invoke (var-deref "clojure.core" "__sq1") m)) (_a$4270 (jolt-map (lambda (f) (let fnrec4266 ((f f)) (jolt-invoke (var-deref "clojure.core" "keyword") (jolt-invoke (var-deref "clojure.core" "name") f)))) fields))) (jolt-invoke _a$4267 _a$4268 _a$4269 _a$4270))))) (jolt-invoke _a$4271 _a$4272 _a$4273 _a$4274 _a$4275))))) (jolt-invoke _a$4276 _a$4277 _a$4278 _a$4279))))) (jolt-invoke _a$4280 _a$4281 _a$4282 _a$4283)))) (_a$4309 (jolt-invoke (var-deref "clojure.core" "mapcat") (lambda (g) (let fnrec4284 ((g g)) (let* ((proto (jolt-first g)) (names (jolt-invoke (var-deref "clojure.core" "distinct") (let* ((_a$4286 (lambda (spec) (let fnrec4285 ((spec spec)) (jolt-invoke (var-deref "clojure.core" "name") (jolt-first spec))))) (_a$4287 (jolt-rest g))) (jolt-map _a$4286 _a$4287))))) (let* ((_a$4302 (let* ((_a$4288 (var-deref "clojure.core" "__sqcat")) (_a$4289 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "register-inline-protocol!"))) (_a$4290 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "name") name-sym))) (_a$4291 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "name") proto)))) (jolt-invoke _a$4288 _a$4289 _a$4290 _a$4291))) (_a$4303 (jolt-map (lambda (nm) (let fnrec4292 ((nm nm)) (let* ((_a$4296 (var-deref "clojure.core" "__sqcat")) (_a$4297 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "register-inline-method"))) (_a$4298 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "name") name-sym))) (_a$4299 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "name") proto))) (_a$4300 (jolt-invoke (var-deref "clojure.core" "__sq1") nm)) (_a$4301 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$4293 (var-deref "clojure.core" "__sqcat")) (_a$4294 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "fn"))) (_a$4295 (jolt-get by-name nm))) (jolt-invoke _a$4293 _a$4294 _a$4295))))) (jolt-invoke _a$4296 _a$4297 _a$4298 _a$4299 _a$4300 _a$4301)))) names))) (jolt-cons _a$4302 _a$4303))))) groups))) (jolt-invoke _a$4304 _a$4305 _a$4306 _a$4307 _a$4308 _a$4309)))))) - (mark-macro! "clojure.core" "defrecord")) -(guard (e (#t #f)) - (def-var! "clojure.core" "memfn" - (lambda (method-name . args) (let fnrec4310 ((method-name method-name) (args (list->cseq args))) (let* ((_a$4315 (var-deref "clojure.core" "__sqcat")) (_a$4316 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "fn"))) (_a$4317 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqvec") (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "target__24__auto")) args))) (_a$4318 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$4311 (var-deref "clojure.core" "__sqcat")) (_a$4312 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "symbol") (jolt-invoke (var-deref "clojure.core" "str") "." (jolt-invoke (var-deref "clojure.core" "name") method-name))))) (_a$4313 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "target__24__auto"))) (_a$4314 args)) (jolt-invoke _a$4311 _a$4312 _a$4313 _a$4314))))) (jolt-invoke _a$4315 _a$4316 _a$4317 _a$4318))))) - (mark-macro! "clojure.core" "memfn")) -(guard (e (#t #f)) - (def-var! "clojure.core" "distinct" (letrec ((distinct (case-lambda (() (let fnrec2546 () (lambda (rf) (let fnrec2547 ((rf rf)) (let* ((seen (jolt-invoke (var-deref "clojure.core" "volatile!") (jolt-hash-set)))) (case-lambda (() (let fnrec2548 () (jolt-invoke rf))) ((result) (let fnrec2549 ((result result)) (jolt-invoke rf result))) ((result input) (let fnrec2550 ((result result) (input input)) (if (jolt-contains? (jolt-invoke (var-deref "clojure.core" "deref") seen) input) result (begin (jolt-invoke (var-deref "clojure.core" "vswap!") seen jolt-conj input) (jolt-invoke rf result input))))))))))) ((coll) (let fnrec2551 ((coll coll)) (let* ((step (letrec ((step (lambda (xs seen) (let fnrec2552 ((xs xs) (seen seen)) (jolt-invoke (var-deref "clojure.core" "make-lazy-seq") (lambda () (let fnrec2553 () (jolt-invoke (var-deref "clojure.core" "coll->cells") (jolt-invoke (lambda (G__112 seen) (let fnrec2554 ((G__112 G__112) (seen seen)) (let* ((G__113 G__112) (f (jolt-nth G__113 0 jolt-nil)) (xs G__113)) (let* ((temp__27__auto (jolt-seq xs))) (if (jolt-truthy? temp__27__auto) (let* ((s temp__27__auto)) (if (jolt-contains? seen f) (fnrec2554 (jolt-rest s) seen) (jolt-cons f (let* ((_a$2555 (jolt-rest s)) (_a$2556 (jolt-conj seen f))) (step _a$2555 _a$2556))))) jolt-nil))))) xs seen))))))))) step))) (jolt-invoke step coll (jolt-hash-set)))))))) distinct))) -(guard (e (#t #f)) - (def-var! "clojure.core" "keep" (letrec ((keep (case-lambda ((f) (let fnrec2557 ((f f)) (lambda (rf) (let fnrec2558 ((rf rf)) (case-lambda (() (let fnrec2559 () (jolt-invoke rf))) ((result) (let fnrec2560 ((result result)) (jolt-invoke rf result))) ((result input) (let fnrec2561 ((result result) (input input)) (let* ((v (jolt-invoke f input))) (if (jolt-nil? v) result (jolt-invoke rf result v)))))))))) ((f coll) (let fnrec2562 ((f f) (coll coll)) (jolt-invoke (var-deref "clojure.core" "make-lazy-seq") (lambda () (let fnrec2563 () (jolt-invoke (var-deref "clojure.core" "coll->cells") (let* ((temp__27__auto (jolt-seq coll))) (if (jolt-truthy? temp__27__auto) (let* ((s temp__27__auto)) (let* ((x (jolt-invoke f (jolt-first s)))) (if (jolt-nil? x) (keep f (jolt-rest s)) (jolt-cons x (keep f (jolt-rest s)))))) jolt-nil))))))))))) keep))) -(guard (e (#t #f)) - (def-var! "clojure.core" "keep-indexed" (letrec ((keep-indexed (case-lambda ((f) (let fnrec2564 ((f f)) (lambda (rf) (let fnrec2565 ((rf rf)) (let* ((ia (jolt-invoke (var-deref "clojure.core" "volatile!") -1))) (case-lambda (() (let fnrec2566 () (jolt-invoke rf))) ((result) (let fnrec2567 ((result result)) (jolt-invoke rf result))) ((result input) (let fnrec2568 ((result result) (input input)) (let* ((i (jolt-invoke (var-deref "clojure.core" "vswap!") ia jolt-inc)) (v (jolt-invoke f i input))) (if (jolt-nil? v) result (jolt-invoke rf result v))))))))))) ((f coll) (let fnrec2569 ((f f) (coll coll)) (letrec* ((keepi (letrec ((keepi (lambda (idx coll) (let fnrec2570 ((idx idx) (coll coll)) (jolt-invoke (var-deref "clojure.core" "make-lazy-seq") (lambda () (let fnrec2571 () (jolt-invoke (var-deref "clojure.core" "coll->cells") (let* ((temp__27__auto (jolt-seq coll))) (if (jolt-truthy? temp__27__auto) (let* ((s temp__27__auto)) (let* ((x (jolt-invoke f idx (jolt-first s)))) (if (jolt-nil? x) (let* ((_a$2572 (jolt-inc idx)) (_a$2573 (jolt-rest s))) (keepi _a$2572 _a$2573)) (jolt-cons x (let* ((_a$2574 (jolt-inc idx)) (_a$2575 (jolt-rest s))) (keepi _a$2574 _a$2575)))))) jolt-nil)))))))))) keepi))) (jolt-invoke keepi 0 coll))))))) keep-indexed))) -(guard (e (#t #f)) - (def-var! "clojure.core" "map-indexed" (letrec ((map-indexed (case-lambda ((f) (let fnrec2576 ((f f)) (lambda (rf) (let fnrec2577 ((rf rf)) (let* ((i (jolt-invoke (var-deref "clojure.core" "volatile!") -1))) (case-lambda (() (let fnrec2578 () (jolt-invoke rf))) ((result) (let fnrec2579 ((result result)) (jolt-invoke rf result))) ((result input) (let fnrec2580 ((result result) (input input)) (jolt-invoke rf result (jolt-invoke f (jolt-invoke (var-deref "clojure.core" "vswap!") i jolt-inc) input)))))))))) ((f coll) (let fnrec2581 ((f f) (coll coll)) (letrec* ((mapi (letrec ((mapi (lambda (idx coll) (let fnrec2582 ((idx idx) (coll coll)) (jolt-invoke (var-deref "clojure.core" "make-lazy-seq") (lambda () (let fnrec2583 () (jolt-invoke (var-deref "clojure.core" "coll->cells") (let* ((temp__27__auto (jolt-seq coll))) (if (jolt-truthy? temp__27__auto) (let* ((s temp__27__auto)) (let* ((_a$2586 (jolt-invoke f idx (jolt-first s))) (_a$2587 (let* ((_a$2584 (jolt-inc idx)) (_a$2585 (jolt-rest s))) (mapi _a$2584 _a$2585)))) (jolt-cons _a$2586 _a$2587))) jolt-nil)))))))))) mapi))) (jolt-invoke mapi 0 coll))))))) map-indexed))) -(guard (e (#t #f)) - (def-var! "clojure.core" "cycle" (letrec ((cycle (lambda (coll) (let fnrec2588 ((coll coll)) (if (jolt-truthy? (jolt-seq coll)) (jolt-invoke (var-deref "clojure.core" "make-lazy-seq") (lambda () (let fnrec2589 () (jolt-invoke (var-deref "clojure.core" "coll->cells") (jolt-concat coll (cycle coll)))))) (jolt-list )))))) cycle))) -(guard (e (#t #f)) - (def-var! "clojure.core" "repeatedly" (letrec ((repeatedly (case-lambda ((f) (let fnrec2590 ((f f)) (jolt-invoke (var-deref "clojure.core" "make-lazy-seq") (lambda () (let fnrec2591 () (jolt-invoke (var-deref "clojure.core" "coll->cells") (let* ((_a$2592 (jolt-invoke f)) (_a$2593 (repeatedly f))) (jolt-cons _a$2592 _a$2593)))))))) ((n f) (let fnrec2594 ((n n) (f f)) (jolt-take n (repeatedly f))))))) repeatedly))) -(guard (e (#t #f)) - (def-var! "clojure.core" "repeat" (letrec ((repeat (case-lambda ((x) (let fnrec2595 ((x x)) (jolt-invoke (var-deref "clojure.core" "make-lazy-seq") (lambda () (let fnrec2596 () (jolt-invoke (var-deref "clojure.core" "coll->cells") (jolt-cons x (repeat x)))))))) ((n x) (let fnrec2597 ((n n) (x x)) (jolt-take n (repeat x))))))) repeat))) -(guard (e (#t #f)) - (def-var! "clojure.core" "iterate" (letrec ((iterate (lambda (f x) (let fnrec2598 ((f f) (x x)) (jolt-cons x (jolt-invoke (var-deref "clojure.core" "make-lazy-seq") (lambda () (let fnrec2599 () (jolt-invoke (var-deref "clojure.core" "coll->cells") (iterate f (jolt-invoke f x))))))))))) iterate))) -(guard (e (#t #f)) - (def-var! "clojure.core" "partition-all" (letrec ((partition-all (case-lambda ((n) (let fnrec2600 ((n n)) (lambda (rf) (let fnrec2601 ((rf rf)) (let* ((a (jolt-invoke (var-deref "clojure.core" "volatile!") (jolt-vector)))) (case-lambda (() (let fnrec2602 () (jolt-invoke rf))) ((result) (let fnrec2603 ((result result)) (let* ((result (if (jolt-zero? (jolt-count (jolt-invoke (var-deref "clojure.core" "deref") a))) result (let* ((v (jolt-invoke (var-deref "clojure.core" "deref") a))) (begin (jolt-invoke (var-deref "clojure.core" "vreset!") a (jolt-vector)) (jolt-invoke (var-deref "clojure.core" "unreduced") (jolt-invoke rf result v))))))) (jolt-invoke rf result)))) ((result input) (let fnrec2604 ((result result) (input input)) (begin (jolt-invoke (var-deref "clojure.core" "vswap!") a jolt-conj input) (if (jolt= n (jolt-count (jolt-invoke (var-deref "clojure.core" "deref") a))) (let* ((v (jolt-invoke (var-deref "clojure.core" "deref") a))) (begin (jolt-invoke (var-deref "clojure.core" "vreset!") a (jolt-vector)) (jolt-invoke rf result v))) result)))))))))) ((n coll) (let fnrec2605 ((n n) (coll coll)) (letrec* ((go (letrec ((go (lambda (s) (let fnrec2606 ((s s)) (jolt-invoke (var-deref "clojure.core" "make-lazy-seq") (lambda () (let fnrec2607 () (jolt-invoke (var-deref "clojure.core" "coll->cells") (if (jolt-truthy? (jolt-seq s)) (let* ((i 0) (acc (jolt-list )) (cur s)) (let loop2608 ((i i) (acc acc) (cur cur)) (if (jolt-truthy? (let* ((and__25__auto (jolt-n< i n))) (if (jolt-truthy? and__25__auto) (jolt-seq cur) and__25__auto))) (let* ((_a$2609 (jolt-inc i)) (_a$2610 (jolt-cons (jolt-first cur) acc)) (_a$2611 (jolt-rest cur))) (loop2608 _a$2609 _a$2610 _a$2611)) (let* ((_a$2612 (jolt-reverse acc)) (_a$2613 (go cur))) (jolt-cons _a$2612 _a$2613))))) jolt-nil))))))))) go))) (jolt-invoke go coll)))) ((n step coll) (let fnrec2614 ((n n) (step step) (coll coll)) (letrec* ((go (letrec ((go (lambda (s) (let fnrec2615 ((s s)) (jolt-invoke (var-deref "clojure.core" "make-lazy-seq") (lambda () (let fnrec2616 () (jolt-invoke (var-deref "clojure.core" "coll->cells") (if (jolt-truthy? (jolt-seq s)) (let* ((_a$2617 (jolt-take n s)) (_a$2618 (go (jolt-invoke (var-deref "clojure.core" "nthrest") s step)))) (jolt-cons _a$2617 _a$2618)) jolt-nil))))))))) go))) (jolt-invoke go coll))))))) partition-all))) -(guard (e (#t #f)) - (def-var! "clojure.core" "interpose" (letrec ((interpose (case-lambda ((sep) (let fnrec2619 ((sep sep)) (lambda (rf) (let fnrec2620 ((rf rf)) (let* ((started (jolt-invoke (var-deref "clojure.core" "volatile!") #f))) (case-lambda (() (let fnrec2621 () (jolt-invoke rf))) ((result) (let fnrec2622 ((result result)) (jolt-invoke rf result))) ((result input) (let fnrec2623 ((result result) (input input)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "deref") started)) (let* ((sepr (jolt-invoke rf result sep))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "reduced?") sepr)) sepr (jolt-invoke rf sepr input))) (begin (jolt-invoke (var-deref "clojure.core" "vreset!") started #t) (jolt-invoke rf result input))))))))))) ((sep coll) (let fnrec2624 ((sep sep) (coll coll)) (jolt-drop 1 (jolt-invoke (var-deref "clojure.core" "interleave") (jolt-invoke (var-deref "clojure.core" "repeat") sep) coll))))))) interpose))) -(guard (e (#t #f)) - (def-var! "clojure.core" "take-nth" (letrec ((take-nth (case-lambda ((n) (let fnrec2625 ((n n)) (lambda (rf) (let fnrec2626 ((rf rf)) (let* ((iv (jolt-invoke (var-deref "clojure.core" "volatile!") -1))) (case-lambda (() (let fnrec2627 () (jolt-invoke rf))) ((result) (let fnrec2628 ((result result)) (jolt-invoke rf result))) ((result input) (let fnrec2629 ((result result) (input input)) (let* ((i (jolt-invoke (var-deref "clojure.core" "vswap!") iv jolt-inc))) (if (jolt-zero? (jolt-rem i n)) (jolt-invoke rf result input) result)))))))))) ((n coll) (let fnrec2630 ((n n) (coll coll)) (jolt-invoke (var-deref "clojure.core" "make-lazy-seq") (lambda () (let fnrec2631 () (jolt-invoke (var-deref "clojure.core" "coll->cells") (let* ((temp__27__auto (jolt-seq coll))) (if (jolt-truthy? temp__27__auto) (let* ((s temp__27__auto)) (let* ((_a$2632 (jolt-first s)) (_a$2633 (take-nth n (jolt-drop n s)))) (jolt-cons _a$2632 _a$2633))) jolt-nil))))))))))) take-nth))) -(guard (e (#t #f)) - (def-var! "clojure.core" "pmap" (letrec ((pmap (case-lambda ((f coll) (let fnrec2634 ((f f) (coll coll)) (jolt-map (var-deref "clojure.core" "deref") (jolt-invoke (var-deref "clojure.core" "doall") (jolt-map (lambda (x) (let fnrec2635 ((x x)) (jolt-invoke (var-deref "clojure.core" "future-call") (lambda () (let fnrec2636 () (jolt-invoke f x)))))) coll))))) ((f coll . colls) (let fnrec2637 ((f f) (coll coll) (colls (list->cseq colls))) (let* ((_a$2639 (lambda (xs) (let fnrec2638 ((xs xs)) (jolt-apply f xs)))) (_a$2640 (jolt-apply jolt-map jolt-vector coll colls))) (pmap _a$2639 _a$2640))))))) pmap))) -(guard (e (#t #f)) - (def-var! "clojure.core" "pcalls" (letrec ((pcalls (lambda fns (let fnrec2641 ((fns (list->cseq fns))) (jolt-invoke (var-deref "clojure.core" "pmap") (lambda (f) (let fnrec2642 ((f f)) (jolt-invoke f))) fns))))) pcalls))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "reader-eof" (keyword "jolt" "reader-eof") (let* ((_o$2643 (keyword #f "private")) (_o$2644 #t)) (jolt-hash-map _o$2643 _o$2644)))) -(guard (e (#t #f)) - (begin (def-var! "clojure.core" "IReader" (jolt-invoke (var-deref "clojure.core" "make-protocol") "IReader" (let* ((_o$2651 (keyword #f "-read-line")) (_o$2652 (let* ((_o$2645 (keyword #f "name")) (_o$2646 "-read-line")) (jolt-hash-map _o$2645 _o$2646))) (_o$2653 (keyword #f "-read-form")) (_o$2654 (let* ((_o$2647 (keyword #f "name")) (_o$2648 "-read-form")) (jolt-hash-map _o$2647 _o$2648))) (_o$2655 (keyword #f "-read+string")) (_o$2656 (let* ((_o$2649 (keyword #f "name")) (_o$2650 "-read+string")) (jolt-hash-map _o$2649 _o$2650)))) (jolt-hash-map _o$2651 _o$2652 _o$2653 _o$2654 _o$2655 _o$2656)))) (jolt-invoke (var-deref "clojure.core" "register-protocol-methods!") "IReader" (let* ((_o$2657 "-read-line") (_o$2658 "-read-form") (_o$2659 "-read+string")) (jolt-vector _o$2657 _o$2658 _o$2659))) (def-var! "clojure.core" "-read-line" (lambda (G__114) (let fnrec2660 ((G__114 G__114)) (protocol-dispatch1 "IReader" "-read-line" G__114)))) (def-var! "clojure.core" "-read-form" (lambda (G__115) (let fnrec2661 ((G__115 G__115)) (protocol-dispatch1 "IReader" "-read-form" G__115)))) (def-var! "clojure.core" "-read+string" (lambda (G__116 G__117 G__118) (let fnrec2662 ((G__116 G__116) (G__117 G__117) (G__118 G__118)) (protocol-dispatch3 "IReader" "-read+string" G__116 G__117 G__118)))))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "__string-reader" (letrec ((__string-reader (lambda (s) (let fnrec2663 ((s s)) (let* ((buf (jolt-invoke (var-deref "clojure.core" "atom") s))) (jolt-invoke (var-deref "clojure.core" "make-reified") (let* ((_o$2673 (keyword #f "-read-line")) (_o$2674 (lambda (_) (let fnrec2664 ((_ _)) (let* ((cur (jolt-invoke (var-deref "clojure.core" "deref") buf))) (if (jolt-pos? (jolt-count cur)) (let* ((i (jolt-invoke (var-deref "clojure.core" "str-find") "\n" cur))) (if (jolt-nil? i) (begin (jolt-invoke (var-deref "clojure.core" "reset!") buf "") cur) (begin (jolt-invoke (var-deref "clojure.core" "reset!") buf (jolt-invoke (var-deref "clojure.core" "subs") cur (jolt-inc i))) (jolt-invoke (var-deref "clojure.core" "subs") cur 0 i)))) jolt-nil))))) (_o$2675 (keyword #f "-read-form")) (_o$2676 (lambda (_) (let fnrec2665 ((_ _)) (let* ((r (jolt-invoke (var-deref "clojure.core" "__parse-next") (jolt-invoke (var-deref "clojure.core" "deref") buf)))) (if (jolt-nil? r) (var-deref "clojure.core" "reader-eof") (begin (jolt-invoke (var-deref "clojure.core" "reset!") buf (jolt-nth r 1)) (jolt-nth r 0))))))) (_o$2677 (keyword #f "-read+string")) (_o$2678 (lambda (_ eof-error? eof-value) (let fnrec2666 ((_ _) (eof-error? eof-error?) (eof-value eof-value)) (let* ((s (jolt-invoke (var-deref "clojure.core" "deref") buf)) (r (jolt-invoke (var-deref "clojure.core" "__parse-next") s))) (if (jolt-nil? r) (if (jolt-truthy? eof-error?) (jolt-throw (jolt-ex-info "EOF while reading" (jolt-hash-map))) (let* ((_o$2667 eof-value) (_o$2668 "")) (jolt-vector _o$2667 _o$2668))) (begin (jolt-invoke (var-deref "clojure.core" "reset!") buf (jolt-nth r 1)) (let* ((_o$2671 (jolt-nth r 0)) (_o$2672 (jolt-invoke (var-deref "clojure.core" "subs") s 0 (let* ((_a$2669 (jolt-count s)) (_a$2670 (jolt-count (jolt-nth r 1)))) (jolt-n- _a$2669 _a$2670))))) (jolt-vector _o$2671 _o$2672))))))))) (jolt-hash-map _o$2673 _o$2674 _o$2675 _o$2676 _o$2677 _o$2678)) "IReader")))))) __string-reader) (let* ((_o$2679 (keyword #f "doc")) (_o$2680 "A reader over string s (the with-in-str expansion calls this).")) (jolt-hash-map _o$2679 _o$2680)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "stdin-buf" (jolt-invoke (var-deref "clojure.core" "atom") "") (let* ((_o$2681 (keyword #f "private")) (_o$2682 #t)) (jolt-hash-map _o$2681 _o$2682)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "*in*" (jolt-invoke (var-deref "clojure.core" "make-reified") (let* ((_o$2696 (keyword #f "-read-line")) (_o$2697 (lambda (_) (let fnrec2683 ((_ _)) (let* ((cur (jolt-invoke (var-deref "clojure.core" "deref") (var-deref "clojure.core" "stdin-buf")))) (if (jolt-pos? (jolt-count cur)) (let* ((i (jolt-invoke (var-deref "clojure.core" "str-find") "\n" cur))) (if (jolt-nil? i) (begin (jolt-invoke (var-deref "clojure.core" "reset!") (var-deref "clojure.core" "stdin-buf") "") cur) (begin (jolt-invoke (var-deref "clojure.core" "reset!") (var-deref "clojure.core" "stdin-buf") (jolt-invoke (var-deref "clojure.core" "subs") cur (jolt-inc i))) (jolt-invoke (var-deref "clojure.core" "subs") cur 0 i)))) (jolt-invoke (var-deref "clojure.core" "__stdin-read-line"))))))) (_o$2698 (keyword #f "-read-form")) (_o$2699 (lambda (_) (let fnrec2684 ((_ _)) (let* () (let loop2685 () (let* ((r (jolt-invoke (var-deref "clojure.core" "__parse-next") (jolt-invoke (var-deref "clojure.core" "deref") (var-deref "clojure.core" "stdin-buf"))))) (if (jolt-nil? r) (let* ((line (jolt-invoke (var-deref "clojure.core" "__stdin-read-line")))) (if (jolt-nil? line) (var-deref "clojure.core" "reader-eof") (begin (jolt-invoke (var-deref "clojure.core" "swap!") (var-deref "clojure.core" "stdin-buf") (lambda (b) (let fnrec2686 ((b b)) (jolt-invoke (var-deref "clojure.core" "str") b line "\n")))) (loop2685 )))) (begin (jolt-invoke (var-deref "clojure.core" "reset!") (var-deref "clojure.core" "stdin-buf") (jolt-nth r 1)) (jolt-nth r 0))))))))) (_o$2700 (keyword #f "-read+string")) (_o$2701 (lambda (_ eof-error? eof-value) (let fnrec2687 ((_ _) (eof-error? eof-error?) (eof-value eof-value)) (let* () (let loop2688 () (let* ((s (jolt-invoke (var-deref "clojure.core" "deref") (var-deref "clojure.core" "stdin-buf"))) (r (jolt-invoke (var-deref "clojure.core" "__parse-next") s))) (if (jolt-nil? r) (let* ((line (jolt-invoke (var-deref "clojure.core" "__stdin-read-line")))) (if (jolt-nil? line) (if (jolt-truthy? eof-error?) (jolt-throw (jolt-ex-info "EOF while reading" (jolt-hash-map))) (let* ((_o$2689 eof-value) (_o$2690 "")) (jolt-vector _o$2689 _o$2690))) (begin (jolt-invoke (var-deref "clojure.core" "swap!") (var-deref "clojure.core" "stdin-buf") (lambda (b) (let fnrec2691 ((b b)) (jolt-invoke (var-deref "clojure.core" "str") b line "\n")))) (loop2688 )))) (begin (jolt-invoke (var-deref "clojure.core" "reset!") (var-deref "clojure.core" "stdin-buf") (jolt-nth r 1)) (let* ((_o$2694 (jolt-nth r 0)) (_o$2695 (jolt-invoke (var-deref "clojure.core" "subs") s 0 (let* ((_a$2692 (jolt-count s)) (_a$2693 (jolt-count (jolt-nth r 1)))) (jolt-n- _a$2692 _a$2693))))) (jolt-vector _o$2694 _o$2695))))))))))) (jolt-hash-map _o$2696 _o$2697 _o$2698 _o$2699 _o$2700 _o$2701)) "IReader") (let* ((_o$2702 (keyword #f "dynamic")) (_o$2703 #t)) (jolt-hash-map _o$2702 _o$2703)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "read-line" (letrec ((read-line (lambda () (let fnrec2704 () (jolt-invoke (var-deref "clojure.core" "-read-line") (var-deref "clojure.core" "*in*")))))) read-line) (let* ((_o$2705 (keyword #f "doc")) (_o$2706 "Reads the next line from the stream that is the current value of *in*.\n Returns nil at EOF.")) (jolt-hash-map _o$2705 _o$2706)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "read" (letrec ((read (case-lambda (() (let fnrec2707 () (read (var-deref "clojure.core" "*in*")))) ((stream) (let fnrec2708 ((stream stream)) (let* ((v (jolt-invoke (var-deref "clojure.core" "-read-form") stream))) (if (jolt= v (var-deref "clojure.core" "reader-eof")) (jolt-throw (jolt-ex-info "EOF while reading" (jolt-hash-map))) v)))) ((stream eof-error? eof-value) (let fnrec2709 ((stream stream) (eof-error? eof-error?) (eof-value eof-value)) (let* ((v (jolt-invoke (var-deref "clojure.core" "-read-form") stream))) (if (jolt= v (var-deref "clojure.core" "reader-eof")) (if (jolt-truthy? eof-error?) (jolt-throw (jolt-ex-info "EOF while reading" (jolt-hash-map))) eof-value) v))))))) read) (let* ((_o$2710 (keyword #f "doc")) (_o$2711 "Reads the next object from stream (defaults to *in*). At EOF, throws \x2014;\n or returns eof-value when eof-error? is false.")) (jolt-hash-map _o$2710 _o$2711)))) -(guard (e (#t #f)) - (def-var! "clojure.core" "with-in-str" - (lambda (s . body) (let fnrec2712 ((s s) (body (list->cseq body))) (let* ((_a$2719 (var-deref "clojure.core" "__sqcat")) (_a$2720 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "binding"))) (_a$2721 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$2716 (var-deref "clojure.core" "__sqvec")) (_a$2717 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "*in*"))) (_a$2718 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$2713 (var-deref "clojure.core" "__sqcat")) (_a$2714 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "__string-reader"))) (_a$2715 (jolt-invoke (var-deref "clojure.core" "__sq1") s))) (jolt-invoke _a$2713 _a$2714 _a$2715))))) (jolt-invoke _a$2716 _a$2717 _a$2718)))) (_a$2722 body)) (jolt-invoke _a$2719 _a$2720 _a$2721 _a$2722))))) - (mark-macro! "clojure.core" "with-in-str")) -(guard (e (#t #f)) - (def-var! "clojure.core" "read+string" (letrec ((read+string (case-lambda (() (let fnrec2723 () (read+string (var-deref "clojure.core" "*in*")))) ((stream) (let fnrec2724 ((stream stream)) (read+string stream #t jolt-nil))) ((stream eof-error? eof-value) (let fnrec2725 ((stream stream) (eof-error? eof-error?) (eof-value eof-value)) (jolt-invoke (var-deref "clojure.core" "-read+string") stream eof-error? eof-value)))))) read+string))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "line-seq" (letrec ((line-seq (lambda (rdr) (let fnrec2726 ((rdr rdr)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "string?") rdr)) (jolt-seq (jolt-invoke (var-deref "clojure.core" "str-split") "\n" rdr)) (jolt-invoke (var-deref "clojure.core" "make-lazy-seq") (lambda () (let fnrec2727 () (jolt-invoke (var-deref "clojure.core" "coll->cells") (let* ((line (jolt-invoke (var-deref "clojure.core" "-read-line") rdr))) (if (jolt-truthy? line) (jolt-cons line (line-seq rdr)) jolt-nil))))))))))) line-seq) (let* ((_o$2728 (keyword #f "doc")) (_o$2729 "Returns the lines of text from rdr as a lazy sequence of strings, as by\n read-line. (Jolt extension kept from the old kernel stub: a plain string\n splits into its lines.)")) (jolt-hash-map _o$2728 _o$2729)))) -(guard (e (#t #f)) - (jolt-invoke (var-deref "clojure.core" "defmulti-setup") (jolt-symbol "clojure.core" "print-method") (lambda (x writer) (let fnrec2730 ((x x) (writer writer)) (let* ((t (jolt-get (jolt-invoke (var-deref "clojure.core" "meta") x) (keyword #f "type")))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "keyword?") t)) t (jolt-invoke (var-deref "clojure.core" "__type-tag") x))))))) -(guard (e (#t #f)) - (jolt-invoke (var-deref "clojure.core" "defmethod-setup") (jolt-symbol #f "print-method") (keyword #f "default") (lambda (o w) (let fnrec2731 ((o o) (w w)) (begin (record-method-dispatch w "write" (jolt-vector (jolt-invoke (var-deref "clojure.core" "__pr-str1") o))) jolt-nil))) "clojure.core")) -(guard (e (#t #f)) - (jolt-invoke (var-deref "clojure.core" "defmulti-setup") (jolt-symbol "clojure.core" "print-dup") (lambda (x writer) (let fnrec2732 ((x x) (writer writer)) (let* ((t (jolt-get (jolt-invoke (var-deref "clojure.core" "meta") x) (keyword #f "type")))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "keyword?") t)) t (jolt-invoke (var-deref "clojure.core" "__type-tag") x))))))) -(guard (e (#t #f)) - (jolt-invoke (var-deref "clojure.core" "defmethod-setup") (jolt-symbol #f "print-dup") (keyword #f "default") (lambda (o w) (let fnrec2733 ((o o) (w w)) (jolt-invoke (var-deref "clojure.core" "print-method") o w))) "clojure.core")) -(guard (e (#t #f)) - (jolt-invoke (var-deref "clojure.core" "defmethod-setup") (jolt-symbol #f "print-method") (keyword "jolt" "uuid") (lambda (u w) (let fnrec2734 ((u u) (w w)) (begin (record-method-dispatch w "write" (jolt-vector (jolt-invoke (var-deref "clojure.core" "str") "#uuid \"" (jolt-get u (keyword #f "str")) "\""))) jolt-nil))) "clojure.core")) -(guard (e (#t #f)) - (jolt-invoke (var-deref "clojure.core" "defmethod-setup") (jolt-symbol #f "print-method") (keyword "jolt" "regex") (lambda (re w) (let fnrec2735 ((re re) (w w)) (begin (record-method-dispatch w "write" (jolt-vector (jolt-invoke (var-deref "clojure.core" "str") "#\"" (jolt-get re (keyword #f "source")) "\""))) jolt-nil))) "clojure.core")) -(guard (e (#t #f)) - (jolt-invoke (var-deref "clojure.core" "defmethod-setup") (jolt-symbol #f "print-method") (keyword "jolt" "transient") (lambda (t w) (let fnrec2736 ((t t) (w w)) (begin (record-method-dispatch w "write" (jolt-vector (jolt-invoke (var-deref "clojure.core" "str") "#"))) jolt-nil))) "clojure.core")) -(guard (e (#t #f)) - (jolt-invoke (var-deref "clojure.core" "defmethod-setup") (jolt-symbol #f "print-method") (keyword "jolt" "chan") (lambda (c w) (let fnrec2737 ((c c) (w w)) (begin (record-method-dispatch w "write" (jolt-vector "#")) jolt-nil))) "clojure.core")) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "agent" (letrec ((agent (lambda (state . _opts) (let fnrec2738 ((state state) (_opts (list->cseq _opts))) (jolt-invoke (var-deref "clojure.core" "atom") state))))) agent) (let* ((_o$2739 (keyword #f "doc")) (_o$2740 "Creates an agent (an atom on jolt \x2014; synchronous, no async dispatch).")) (jolt-hash-map _o$2739 _o$2740)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "send-off" (letrec ((send-off (lambda (a f . args) (let fnrec2741 ((a a) (f f) (args (list->cseq args))) (begin (jolt-apply (var-deref "clojure.core" "swap!") a f args) a))))) send-off) (let* ((_o$2742 (keyword #f "doc")) (_o$2743 "Apply (action state & args) to the agent's state immediately; return the agent.")) (jolt-hash-map _o$2742 _o$2743)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "send" (letrec ((send (lambda (a f . args) (let fnrec2744 ((a a) (f f) (args (list->cseq args))) (begin (jolt-apply (var-deref "clojure.core" "swap!") a f args) a))))) send) (let* ((_o$2745 (keyword #f "doc")) (_o$2746 "Like send-off on jolt (no separate thread pool).")) (jolt-hash-map _o$2745 _o$2746)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.core" "agent-error" (letrec ((agent-error (lambda (_a) (let fnrec2747 ((_a _a)) jolt-nil)))) agent-error) (let* ((_o$2748 (keyword #f "doc")) (_o$2749 "jolt agents never enter an error state.")) (jolt-hash-map _o$2748 _o$2749)))) -(guard (e (#t #f)) - (def-var! "clojure.string" "blank?" (letrec ((blank? (lambda (s) (let fnrec2442 ((s s)) (if (jolt-nil? s) #t (jolt= 0 (jolt-count (jolt-invoke (var-deref "clojure.core" "str-trim") s)))))))) blank?))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.string" "to-str" (letrec ((to-str (lambda (s) (let fnrec2443 ((s s)) (if (jolt-nil? s) (jolt-throw (host-new "NullPointerException" "s")) (record-method-dispatch s "toString" (jolt-vector))))))) to-str) (let* ((_o$2444 (keyword #f "private")) (_o$2445 #t)) (jolt-hash-map _o$2444 _o$2445)))) -(guard (e (#t #f)) - (def-var! "clojure.string" "capitalize" (letrec ((capitalize (lambda (s) (let fnrec2446 ((s s)) (let* ((s (jolt-invoke (var-deref "clojure.string" "to-str") s))) (if (jolt-n< 1 (jolt-count s)) (let* ((_a$2447 (var-deref "clojure.core" "str")) (_a$2448 (jolt-invoke (var-deref "clojure.core" "str-upper") (jolt-invoke (var-deref "clojure.core" "subs") s 0 1))) (_a$2449 (jolt-invoke (var-deref "clojure.core" "str-lower") (jolt-invoke (var-deref "clojure.core" "subs") s 1)))) (jolt-invoke _a$2447 _a$2448 _a$2449)) (jolt-invoke (var-deref "clojure.core" "str-upper") s))))))) capitalize))) -(guard (e (#t #f)) - (def-var! "clojure.string" "lower-case" (letrec ((lower-case (lambda (s) (let fnrec2450 ((s s)) (jolt-invoke (var-deref "clojure.core" "str-lower") (jolt-invoke (var-deref "clojure.string" "to-str") s)))))) lower-case))) -(guard (e (#t #f)) - (def-var! "clojure.string" "upper-case" (letrec ((upper-case (lambda (s) (let fnrec2451 ((s s)) (jolt-invoke (var-deref "clojure.core" "str-upper") (jolt-invoke (var-deref "clojure.string" "to-str") s)))))) upper-case))) -(guard (e (#t #f)) - (def-var! "clojure.string" "includes?" (letrec ((includes? (lambda (s substr) (let fnrec2452 ((s s) (substr substr)) (jolt-not (jolt-nil? (jolt-invoke (var-deref "clojure.core" "str-find") substr (jolt-invoke (var-deref "clojure.string" "to-str") s)))))))) includes?))) -(guard (e (#t #f)) - (def-var! "clojure.string" "join" (letrec ((join (case-lambda ((coll) (let fnrec2453 ((coll coll)) (jolt-invoke (var-deref "clojure.core" "str-join") coll))) ((separator coll) (let fnrec2454 ((separator separator) (coll coll)) (jolt-invoke (var-deref "clojure.core" "str-join") coll separator)))))) join))) -(guard (e (#t #f)) - (def-var! "clojure.string" "replace" (letrec ((replace (lambda (s match replacement) (let fnrec2455 ((s s) (match match) (replacement replacement)) (jolt-invoke (var-deref "clojure.core" "str-replace-all") match replacement (jolt-invoke (var-deref "clojure.string" "to-str") s)))))) replace))) -(guard (e (#t #f)) - (def-var! "clojure.string" "replace-first" (letrec ((replace-first (lambda (s match replacement) (let fnrec2456 ((s s) (match match) (replacement replacement)) (jolt-invoke (var-deref "clojure.core" "str-replace") match replacement (jolt-invoke (var-deref "clojure.string" "to-str") s)))))) replace-first))) -(guard (e (#t #f)) - (def-var! "clojure.string" "reverse" (letrec ((reverse (lambda (s) (let fnrec2457 ((s s)) (jolt-invoke (var-deref "clojure.core" "str-reverse-b") s))))) reverse))) -(guard (e (#t #f)) - (def-var! "clojure.string" "str-reverse" (letrec ((str-reverse (lambda (s) (let fnrec2458 ((s s)) (jolt-invoke (var-deref "clojure.core" "str-reverse-b") s))))) str-reverse))) -(guard (e (#t #f)) - (def-var! "clojure.string" "split" (letrec ((split (case-lambda ((s re) (let fnrec2459 ((s s) (re re)) (split s re 0))) ((s re limit) (let fnrec2460 ((s s) (re re) (limit limit)) (let* ((parts (jolt-invoke (var-deref "clojure.core" "vec") (jolt-invoke (var-deref "clojure.core" "str-split") re s (if (jolt-pos? limit) limit jolt-nil))))) (if (let* ((and__25__auto (jolt-zero? limit))) (if (jolt-truthy? and__25__auto) (jolt-n> (jolt-count parts) 1) and__25__auto)) (let* ((v parts)) (let loop2461 ((v v)) (if (jolt-truthy? (let* ((and__25__auto (jolt-seq v))) (if (jolt-truthy? and__25__auto) (jolt= "" (jolt-peek v)) and__25__auto))) (loop2461 (jolt-pop v)) v))) parts))))))) split))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.string" "split-lines" (letrec ((split-lines (lambda (s) (let fnrec2462 ((s s)) (jolt-invoke (var-deref "clojure.core" "vec") (jolt-invoke (var-deref "clojure.core" "str-split") (jolt-regex "\\r?\\n") s)))))) split-lines) (let* ((_o$2463 (keyword #f "doc")) (_o$2464 "Split s on \\n or \\r\\n, returning a vector of lines.")) (jolt-hash-map _o$2463 _o$2464)))) -(guard (e (#t #f)) - (def-var! "clojure.string" "starts-with?" (letrec ((starts-with? (lambda (s substr) (let fnrec2465 ((s s) (substr substr)) (begin (if (jolt-nil? substr) (jolt-throw (host-new "NullPointerException" "substr")) jolt-nil) (let* ((s (jolt-invoke (var-deref "clojure.string" "to-str") s)) (slen (jolt-count s)) (slen2 (jolt-count substr))) (let* ((and__25__auto (jolt-n>= slen slen2))) (if (jolt-truthy? and__25__auto) (jolt= (jolt-invoke (var-deref "clojure.core" "subs") s 0 slen2) substr) and__25__auto)))))))) starts-with?))) -(guard (e (#t #f)) - (def-var! "clojure.string" "ends-with?" (letrec ((ends-with? (lambda (s substr) (let fnrec2466 ((s s) (substr substr)) (begin (if (jolt-nil? substr) (jolt-throw (host-new "NullPointerException" "substr")) jolt-nil) (let* ((s (jolt-invoke (var-deref "clojure.string" "to-str") s)) (slen (jolt-count s)) (slen2 (jolt-count substr))) (let* ((and__25__auto (jolt-n>= slen slen2))) (if (jolt-truthy? and__25__auto) (jolt= (jolt-invoke (var-deref "clojure.core" "subs") s (jolt-n- slen slen2)) substr) and__25__auto)))))))) ends-with?))) -(guard (e (#t #f)) - (def-var! "clojure.string" "trim" (letrec ((trim (lambda (s) (let fnrec2467 ((s s)) (jolt-invoke (var-deref "clojure.core" "str-trim") s))))) trim))) -(guard (e (#t #f)) - (def-var! "clojure.string" "triml" (letrec ((triml (lambda (s) (let fnrec2468 ((s s)) (jolt-invoke (var-deref "clojure.core" "str-triml") s))))) triml))) -(guard (e (#t #f)) - (def-var! "clojure.string" "trimr" (letrec ((trimr (lambda (s) (let fnrec2469 ((s s)) (jolt-invoke (var-deref "clojure.core" "str-trimr") s))))) trimr))) -(guard (e (#t #f)) - (def-var! "clojure.string" "escape" (letrec ((escape (lambda (s cmap) (let fnrec2470 ((s s) (cmap cmap)) (begin (if (jolt-nil? s) (jolt-throw (host-new "NullPointerException" "s")) jolt-nil) (jolt-apply (var-deref "clojure.core" "str") (jolt-map (lambda (ch) (let fnrec2471 ((ch ch)) (let* ((temp__16__auto (jolt-invoke cmap ch))) (if (jolt-truthy? temp__16__auto) (let* ((rep temp__16__auto)) rep) (jolt-invoke (var-deref "clojure.core" "str") ch))))) s))))))) escape))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.string" "index-of" (letrec ((index-of (case-lambda ((s value) (let fnrec2472 ((s s) (value value)) (jolt-invoke (var-deref "clojure.core" "str-find") value (jolt-invoke (var-deref "clojure.string" "to-str") s)))) ((s value from) (let fnrec2473 ((s s) (value value) (from from)) (let* ((idx (jolt-invoke (var-deref "clojure.core" "str-find") value (jolt-invoke (var-deref "clojure.core" "subs") (jolt-invoke (var-deref "clojure.string" "to-str") s) from)))) (if (jolt-truthy? idx) (jolt-n+ from idx) jolt-nil))))))) index-of) (let* ((_o$2474 (keyword #f "doc")) (_o$2475 "0-based index of the first occurrence of value in s, or nil.")) (jolt-hash-map _o$2474 _o$2475)))) -(guard (e (#t #f)) - (def-var! "clojure.string" "last-index-of" (letrec ((last-index-of (case-lambda ((s value) (let fnrec2476 ((s s) (value value)) (let* ((r (jolt-invoke (var-deref "clojure.core" "str-reverse-b") s)) (sval (jolt-invoke (var-deref "clojure.core" "str-reverse-b") value)) (idx (jolt-invoke (var-deref "clojure.core" "str-find") sval r))) (if (jolt-truthy? idx) (let* ((_a$2477 (jolt-count s)) (_a$2478 (jolt-n+ idx (jolt-count value)))) (jolt-n- _a$2477 _a$2478)) jolt-nil)))) ((s value from) (let fnrec2479 ((s s) (value value) (from from)) (let* ((sub (jolt-invoke (var-deref "clojure.core" "subs") s 0 from)) (r (jolt-invoke (var-deref "clojure.core" "str-reverse-b") sub)) (sval (jolt-invoke (var-deref "clojure.core" "str-reverse-b") value)) (idx (jolt-invoke (var-deref "clojure.core" "str-find") sval r))) (if (jolt-truthy? idx) (jolt-n- from (jolt-n+ idx (jolt-count value))) jolt-nil))))))) last-index-of))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.string" "re-quote-replacement" (letrec ((re-quote-replacement (lambda (replacement) (let fnrec2480 ((replacement replacement)) (jolt-apply (var-deref "clojure.core" "str") (let* ((_a$2482 (lambda (ch) (let fnrec2481 ((ch ch)) (let* ((c (jolt-invoke (var-deref "clojure.core" "str") ch))) (if (let* ((or__26__auto (jolt= c "\\"))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt= c "$"))) (jolt-invoke (var-deref "clojure.core" "str") "\\" c) c))))) (_a$2483 (jolt-seq replacement))) (jolt-map _a$2482 _a$2483))))))) re-quote-replacement) (let* ((_o$2484 (keyword #f "doc")) (_o$2485 "Escape special characters (backslash and dollar) in a regex replacement\n string so it is used literally rather than interpreted.")) (jolt-hash-map _o$2484 _o$2485)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.string" "trim-newline" (letrec ((trim-newline (lambda (s) (let fnrec2486 ((s s)) (let* ((index (jolt-count s))) (let loop2487 ((index index)) (if (jolt-zero? index) "" (let* ((c (jolt-invoke (var-deref "clojure.core" "subs") s (jolt-dec index) index))) (if (let* ((or__26__auto (jolt= c "\n"))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt= c "\r"))) (loop2487 (jolt-dec index)) (jolt-invoke (var-deref "clojure.core" "subs") s 0 index)))))))))) trim-newline) (let* ((_o$2488 (keyword #f "doc")) (_o$2489 "Removes all trailing newline \\n or return \\r characters from\n string. Similar to Perl's chomp.")) (jolt-hash-map _o$2488 _o$2489)))) -(guard (e (#t #f)) - (def-var! "clojure.walk" "walk" (letrec ((walk (lambda (inner outer form) (let fnrec2490 ((inner inner) (outer outer) (form form)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "vector?") form)) (jolt-invoke outer (let* ((_a$2491 (var-deref "clojure.core" "with-meta")) (_a$2492 (jolt-invoke (var-deref "clojure.core" "vec") (jolt-map inner form))) (_a$2493 (jolt-invoke (var-deref "clojure.core" "meta") form))) (jolt-invoke _a$2491 _a$2492 _a$2493))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "record?") form)) (jolt-invoke outer (jolt-reduce (lambda (r x) (let fnrec2494 ((r r) (x x)) (jolt-conj r (jolt-invoke inner x)))) form form)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "map?") form)) (jolt-invoke outer (let* ((_a$2497 (var-deref "clojure.core" "with-meta")) (_a$2498 (let* ((_a$2495 (jolt-invoke (var-deref "clojure.core" "empty") form)) (_a$2496 (jolt-map inner form))) (jolt-into _a$2495 _a$2496))) (_a$2499 (jolt-invoke (var-deref "clojure.core" "meta") form))) (jolt-invoke _a$2497 _a$2498 _a$2499))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "list?") form)) (jolt-invoke outer (let* ((_a$2500 (var-deref "clojure.core" "with-meta")) (_a$2501 (jolt-apply jolt-list (jolt-map inner form))) (_a$2502 (jolt-invoke (var-deref "clojure.core" "meta") form))) (jolt-invoke _a$2500 _a$2501 _a$2502))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "seq?") form)) (jolt-invoke outer (let* ((_a$2503 (var-deref "clojure.core" "with-meta")) (_a$2504 (jolt-invoke (var-deref "clojure.core" "doall") (jolt-map inner form))) (_a$2505 (jolt-invoke (var-deref "clojure.core" "meta") form))) (jolt-invoke _a$2503 _a$2504 _a$2505))) (if (jolt-truthy? (keyword #f "else")) (jolt-invoke outer form) jolt-nil)))))))))) walk))) -(guard (e (#t #f)) - (def-var! "clojure.walk" "postwalk" (letrec ((postwalk (lambda (f form) (let fnrec2506 ((f f) (form form)) (jolt-invoke (var-deref "clojure.walk" "walk") (jolt-invoke (var-deref "clojure.core" "partial") postwalk f) f form))))) postwalk))) -(guard (e (#t #f)) - (def-var! "clojure.walk" "prewalk" (letrec ((prewalk (lambda (f form) (let fnrec2507 ((f f) (form form)) (let* ((_a$2508 (var-deref "clojure.walk" "walk")) (_a$2509 (jolt-invoke (var-deref "clojure.core" "partial") prewalk f)) (_a$2510 jolt-identity) (_a$2511 (jolt-invoke f form))) (jolt-invoke _a$2508 _a$2509 _a$2510 _a$2511)))))) prewalk))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.walk" "postwalk-demo" (letrec ((postwalk-demo (lambda (form) (let fnrec2512 ((form form)) (jolt-invoke (var-deref "clojure.walk" "postwalk") (lambda (x) (let fnrec2513 ((x x)) (begin (jolt-invoke (var-deref "clojure.core" "print") "Walked: ") (jolt-invoke (var-deref "clojure.core" "prn") x) x))) form))))) postwalk-demo) (let* ((_o$2514 (keyword #f "doc")) (_o$2515 "Demonstrates the behavior of postwalk by printing each form as it is walked.")) (jolt-hash-map _o$2514 _o$2515)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.walk" "prewalk-demo" (letrec ((prewalk-demo (lambda (form) (let fnrec2516 ((form form)) (jolt-invoke (var-deref "clojure.walk" "prewalk") (lambda (x) (let fnrec2517 ((x x)) (begin (jolt-invoke (var-deref "clojure.core" "print") "Walked: ") (jolt-invoke (var-deref "clojure.core" "prn") x) x))) form))))) prewalk-demo) (let* ((_o$2518 (keyword #f "doc")) (_o$2519 "Demonstrates the behavior of prewalk by printing each form as it is walked.")) (jolt-hash-map _o$2518 _o$2519)))) -(guard (e (#t #f)) - (def-var! "clojure.walk" "postwalk-replace" (letrec ((postwalk-replace (lambda (smap form) (let fnrec2520 ((smap smap) (form form)) (jolt-invoke (var-deref "clojure.walk" "postwalk") (lambda (x) (let fnrec2521 ((x x)) (if (jolt-contains? smap x) (jolt-get smap x) x))) form))))) postwalk-replace))) -(guard (e (#t #f)) - (def-var! "clojure.walk" "prewalk-replace" (letrec ((prewalk-replace (lambda (smap form) (let fnrec2522 ((smap smap) (form form)) (jolt-invoke (var-deref "clojure.walk" "prewalk") (lambda (x) (let fnrec2523 ((x x)) (if (jolt-contains? smap x) (jolt-get smap x) x))) form))))) prewalk-replace))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.walk" "macroexpand-all" (letrec ((macroexpand-all (lambda (form) (let fnrec2524 ((form form)) (jolt-invoke (var-deref "clojure.walk" "prewalk") (lambda (x) (let fnrec2525 ((x x)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "seq?") x)) (jolt-invoke (var-deref "clojure.core" "macroexpand") x) x))) form))))) macroexpand-all) (let* ((_o$2526 (keyword #f "doc")) (_o$2527 "Recursively performs all possible macroexpansions in form.")) (jolt-hash-map _o$2526 _o$2527)))) -(guard (e (#t #f)) - (def-var! "clojure.walk" "keywordize-keys" (letrec ((keywordize-keys (lambda (m) (let fnrec2528 ((m m)) (let* ((f (lambda (G__108) (let fnrec2529 ((G__108 G__108)) (let* ((G__109 G__108) (k (jolt-nth G__109 0 jolt-nil)) (v (jolt-nth G__109 1 jolt-nil))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "string?") k)) (let* ((_o$2530 (jolt-invoke (var-deref "clojure.core" "keyword") k)) (_o$2531 v)) (jolt-vector _o$2530 _o$2531)) (let* ((_o$2532 k) (_o$2533 v)) (jolt-vector _o$2532 _o$2533)))))))) (jolt-invoke (var-deref "clojure.walk" "postwalk") (lambda (x) (let fnrec2534 ((x x)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "map?") x)) (let* ((_a$2535 (jolt-hash-map)) (_a$2536 (jolt-map f x))) (jolt-into _a$2535 _a$2536)) x))) m)))))) keywordize-keys))) -(guard (e (#t #f)) - (def-var! "clojure.walk" "stringify-keys" (letrec ((stringify-keys (lambda (m) (let fnrec2537 ((m m)) (let* ((f (lambda (G__110) (let fnrec2538 ((G__110 G__110)) (let* ((G__111 G__110) (k (jolt-nth G__111 0 jolt-nil)) (v (jolt-nth G__111 1 jolt-nil))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "keyword?") k)) (let* ((_o$2539 (jolt-invoke (var-deref "clojure.core" "name") k)) (_o$2540 v)) (jolt-vector _o$2539 _o$2540)) (let* ((_o$2541 k) (_o$2542 v)) (jolt-vector _o$2541 _o$2542)))))))) (jolt-invoke (var-deref "clojure.walk" "postwalk") (lambda (x) (let fnrec2543 ((x x)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "map?") x)) (let* ((_a$2544 (jolt-hash-map)) (_a$2545 (jolt-map f x))) (jolt-into _a$2544 _a$2545)) x))) m)))))) stringify-keys))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.template" "apply-template" (letrec ((apply-template (lambda (argv expr _values) (let fnrec2375 ((argv argv) (expr expr) (_values _values)) (begin (if (jolt-not (jolt-invoke (var-deref "clojure.core" "vector?") argv)) (jolt-throw (host-new "AssertionError" "Assert failed: (vector? argv)")) jolt-nil) (if (jolt-not (jolt-invoke (var-deref "clojure.core" "every?") (var-deref "clojure.core" "symbol?") argv)) (jolt-throw (host-new "AssertionError" "Assert failed: (every? symbol? argv)")) jolt-nil) (jolt-invoke (var-deref "clojure.walk" "postwalk-replace") (jolt-invoke (var-deref "clojure.core" "zipmap") argv _values) expr)))))) apply-template) (let* ((_o$2376 (keyword #f "doc")) (_o$2377 "For use in macros. argv is an argument list, as in defn. expr is\n a quoted expression using the symbols in argv. values is a sequence\n of values to be used for the arguments.\n\n apply-template will recursively replace argument symbols in expr\n with their corresponding values, returning a modified expr.\n\n Example: (apply-template '[x] '(+ x x) '[2])\n ;=> (+ 2 2)")) (jolt-hash-map _o$2376 _o$2377)))) -(guard (e (#t #f)) - (def-var! "clojure.template" "do-template" - (lambda (argv expr . _values) (let fnrec2378 ((argv argv) (expr expr) (_values (list->cseq _values))) (let* ((c (jolt-count argv))) (let* ((_a$2382 (var-deref "clojure.core" "__sqcat")) (_a$2383 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "do"))) (_a$2384 (let* ((_a$2380 (lambda (a) (let fnrec2379 ((a a)) (jolt-invoke (var-deref "clojure.template" "apply-template") argv expr a)))) (_a$2381 (jolt-invoke (var-deref "clojure.core" "partition") c _values))) (jolt-map _a$2380 _a$2381)))) (jolt-invoke _a$2382 _a$2383 _a$2384)))))) - (mark-macro! "clojure.template" "do-template")) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.edn" "edn->value" (letrec ((edn->value (lambda (opts x) (let fnrec2385 ((opts opts) (x x)) (if (jolt= (keyword "jolt" "set") (jolt-get x (keyword "jolt" "type"))) (let* ((vs (let* ((_a$2387 (lambda (v) (let fnrec2386 ((v v)) (edn->value opts v)))) (_a$2388 (jolt-get x (keyword #f "value")))) (jolt-map _a$2387 _a$2388))) (st (jolt-invoke (var-deref "clojure.core" "set") vs))) (begin (if (let* ((_a$2389 (jolt-count st)) (_a$2390 (jolt-count vs))) (jolt-n< _a$2389 _a$2390)) (jolt-throw (host-new "IllegalArgumentException" (jolt-invoke (var-deref "clojure.core" "str") "Duplicate key: " (jolt-invoke (var-deref "clojure.core" "pr-str") (let* ((_a$2392 (var-deref "clojure.core" "some")) (_a$2393 (lambda (G__106) (let fnrec2391 ((G__106 G__106)) (let* ((G__107 G__106) (k (jolt-nth G__107 0 jolt-nil)) (n (jolt-nth G__107 1 jolt-nil))) (if (jolt-n< 1 n) k jolt-nil))))) (_a$2394 (jolt-invoke (var-deref "clojure.core" "frequencies") vs))) (jolt-invoke _a$2392 _a$2393 _a$2394)))))) jolt-nil) (jolt-invoke (var-deref "clojure.core" "with-meta") st (edn->value opts (jolt-invoke (var-deref "clojure.core" "meta") x))))) (if (jolt= (keyword "jolt" "tagged") (jolt-get x (keyword "jolt" "type"))) (let* ((tag (jolt-get x (keyword #f "tag"))) (v (edn->value opts (jolt-get x (keyword #f "form")))) (tag-sym (let* ((n (jolt-invoke (var-deref "clojure.core" "name") tag))) (jolt-invoke (var-deref "clojure.core" "symbol") (if (jolt= "#" (jolt-invoke (var-deref "clojure.core" "subs") n 0 1)) (jolt-invoke (var-deref "clojure.core" "subs") n 1) n)))) (custom (jolt-get (jolt-get opts (keyword #f "readers")) tag-sym))) (if (jolt-truthy? custom) (jolt-invoke custom v) (if (jolt-contains? (let* ((_o$2395 (jolt-symbol #f "inst")) (_o$2396 (jolt-symbol #f "uuid")) (_o$2397 (jolt-symbol #f "bigdec"))) (jolt-hash-set _o$2395 _o$2396 _o$2397)) tag-sym) (jolt-invoke (var-deref "clojure.core" "__read-tagged") tag v) (if (jolt-truthy? (jolt-get opts (keyword #f "default"))) (jolt-invoke (jolt-get opts (keyword #f "default")) tag-sym v) (if (jolt-truthy? (keyword #f "else")) (jolt-invoke (var-deref "clojure.core" "__read-tagged") tag v) jolt-nil))))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "map?") x)) (let* ((_a$2403 (var-deref "clojure.core" "with-meta")) (_a$2404 (let* ((_a$2401 (jolt-hash-map)) (_a$2402 (jolt-map (lambda (e) (let fnrec2398 ((e e)) (let* ((_o$2399 (edn->value opts (jolt-invoke (var-deref "clojure.core" "key") e))) (_o$2400 (edn->value opts (jolt-invoke (var-deref "clojure.core" "val") e)))) (jolt-vector _o$2399 _o$2400)))) x))) (jolt-into _a$2401 _a$2402))) (_a$2405 (edn->value opts (jolt-invoke (var-deref "clojure.core" "meta") x)))) (jolt-invoke _a$2403 _a$2404 _a$2405)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "vector?") x)) (let* ((_a$2407 (var-deref "clojure.core" "with-meta")) (_a$2408 (jolt-invoke (var-deref "clojure.core" "mapv") (lambda (v) (let fnrec2406 ((v v)) (edn->value opts v))) x)) (_a$2409 (edn->value opts (jolt-invoke (var-deref "clojure.core" "meta") x)))) (jolt-invoke _a$2407 _a$2408 _a$2409)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "set?") x)) (let* ((_a$2411 (var-deref "clojure.core" "with-meta")) (_a$2412 (jolt-invoke (var-deref "clojure.core" "set") (jolt-map (lambda (v) (let fnrec2410 ((v v)) (edn->value opts v))) x))) (_a$2413 (edn->value opts (jolt-invoke (var-deref "clojure.core" "meta") x)))) (jolt-invoke _a$2411 _a$2412 _a$2413)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "seq?") x)) (let* ((_a$2415 (var-deref "clojure.core" "with-meta")) (_a$2416 (jolt-apply jolt-list (jolt-map (lambda (v) (let fnrec2414 ((v v)) (edn->value opts v))) x))) (_a$2417 (edn->value opts (jolt-invoke (var-deref "clojure.core" "meta") x)))) (jolt-invoke _a$2415 _a$2416 _a$2417)) (if (jolt-truthy? (keyword #f "else")) x jolt-nil))))))))))) edn->value) (let* ((_o$2418 (keyword #f "private")) (_o$2419 #t)) (jolt-hash-map _o$2418 _o$2419)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.edn" "read-edn" (letrec ((read-edn (lambda (opts s) (let fnrec2420 ((opts opts) (s s)) (let* ((v (jolt-invoke (var-deref "clojure.core" "__read-form-edn") s (lambda (form) (let fnrec2421 ((form form)) (begin (jolt-invoke (var-deref "clojure.edn" "edn->value") opts form) jolt-nil)))))) (if (jolt= v (keyword "jolt" "reader-eof")) (if (jolt-contains? opts (keyword #f "eof")) (jolt-get opts (keyword #f "eof")) (jolt-throw (jolt-ex-info "EOF while reading" (jolt-hash-map)))) (jolt-invoke (var-deref "clojure.edn" "edn->value") opts v))))))) read-edn) (let* ((_o$2422 (keyword #f "private")) (_o$2423 #t)) (jolt-hash-map _o$2422 _o$2423)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.edn" "read-string" (letrec ((read-string (case-lambda ((s) (let fnrec2424 ((s s)) (jolt-invoke (var-deref "clojure.edn" "read-edn") (let* ((_o$2425 (keyword #f "eof")) (_o$2426 jolt-nil)) (jolt-hash-map _o$2425 _o$2426)) s))) ((opts s) (let fnrec2427 ((opts opts) (s s)) (jolt-invoke (var-deref "clojure.edn" "read-edn") opts s)))))) read-string) (let* ((_o$2428 (keyword #f "doc")) (_o$2429 "Reads one object from the string s. The no-opts arity returns nil at end of\n input; with an opts map, :eof sets the value returned at end of input and its\n absence makes end-of-input an error.")) (jolt-hash-map _o$2428 _o$2429)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.edn" "drain-reader" (letrec ((drain-reader (lambda (reader) (let fnrec2430 ((reader reader)) (let* ((acc (jolt-invoke (var-deref "clojure.core" "transient") (jolt-vector))) (c (record-method-dispatch reader "read" (jolt-vector)))) (let loop2431 ((acc acc) (c c)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "==") -1 c)) (jolt-apply (var-deref "clojure.core" "str") (jolt-map (var-deref "clojure.core" "char") (jolt-invoke (var-deref "clojure.core" "persistent!") acc))) (let* ((_a$2432 (jolt-invoke (var-deref "clojure.core" "conj!") acc c)) (_a$2433 (record-method-dispatch reader "read" (jolt-vector)))) (loop2431 _a$2432 _a$2433))))))))) drain-reader) (let* ((_o$2434 (keyword #f "private")) (_o$2435 #t) (_o$2436 (keyword #f "doc")) (_o$2437 "All remaining content of a reader as a string. Shim readers (StringReader,\n PushbackReader, io/reader results) expose char-wise .read; a raw file\n handle is read whole.")) (jolt-hash-map _o$2434 _o$2435 _o$2436 _o$2437)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.edn" "read" (letrec ((read (case-lambda ((reader) (let fnrec2438 ((reader reader)) (read (jolt-hash-map) reader))) ((opts reader) (let fnrec2439 ((opts opts) (reader reader)) (jolt-invoke (var-deref "clojure.edn" "read-edn") opts (jolt-invoke (var-deref "clojure.edn" "drain-reader") reader))))))) read) (let* ((_o$2440 (keyword #f "doc")) (_o$2441 "Reads one EDN object from reader (a PushbackReader or any jolt reader).\n Returns the :eof option value (default nil) at end of input.")) (jolt-hash-map _o$2440 _o$2441)))) -(guard (e (#t #f)) - (def-var! "clojure.set" "union" (letrec ((union (case-lambda (() (let fnrec1 () (jolt-hash-set))) ((s1) (let fnrec2 ((s1 s1)) s1)) ((s1 s2) (let fnrec3 ((s1 s1) (s2 s2)) (if (let* ((_a$4 (jolt-count s1)) (_a$5 (jolt-count s2))) (jolt-n< _a$4 _a$5)) (jolt-reduce jolt-conj s2 s1) (jolt-reduce jolt-conj s1 s2)))) ((s1 s2 . sets) (let fnrec6 ((s1 s1) (s2 s2) (sets (list->cseq sets))) (jolt-reduce union (union s1 s2) sets)))))) union))) -(guard (e (#t #f)) - (def-var! "clojure.set" "intersection" (letrec ((intersection (case-lambda ((s1) (let fnrec7 ((s1 s1)) s1)) ((s1 s2) (let fnrec8 ((s1 s1) (s2 s2)) (jolt-reduce (lambda (acc item) (let fnrec9 ((acc acc) (item item)) (if (jolt-contains? s2 item) acc (jolt-invoke (var-deref "clojure.core" "disj") acc item)))) s1 s1))) ((s1 s2 . sets) (let fnrec10 ((s1 s1) (s2 s2) (sets (list->cseq sets))) (jolt-reduce intersection (intersection s1 s2) sets)))))) intersection))) -(guard (e (#t #f)) - (def-var! "clojure.set" "difference" (letrec ((difference (case-lambda ((s1) (let fnrec11 ((s1 s1)) s1)) ((s1 s2) (let fnrec12 ((s1 s1) (s2 s2)) (jolt-reduce (var-deref "clojure.core" "disj") s1 s2))) ((s1 s2 . sets) (let fnrec13 ((s1 s1) (s2 s2) (sets (list->cseq sets))) (jolt-reduce difference (difference s1 s2) sets)))))) difference))) -(guard (e (#t #f)) - (def-var! "clojure.set" "select" (letrec ((select (lambda (pred s) (let fnrec14 ((pred pred) (s s)) (jolt-reduce (lambda (acc item) (let fnrec15 ((acc acc) (item item)) (if (jolt-truthy? (jolt-invoke pred item)) acc (jolt-invoke (var-deref "clojure.core" "disj") acc item)))) s s))))) select))) -(guard (e (#t #f)) - (def-var! "clojure.set" "project" (letrec ((project (lambda (xrel ks) (let fnrec16 ((xrel xrel) (ks ks)) (jolt-invoke (var-deref "clojure.core" "set") (jolt-map (lambda (p__1_) (let fnrec17 ((p__1_ p__1_)) (jolt-invoke (var-deref "clojure.core" "select-keys") p__1_ ks))) xrel)))))) project))) -(guard (e (#t #f)) - (def-var! "clojure.set" "rename-keys" (letrec ((rename-keys (lambda (map kmap) (let fnrec18 ((map map) (kmap kmap)) (let* ((_a$20 (lambda (m G__1) (let fnrec19 ((m m) (G__1 G__1)) (let* ((G__2 G__1) (old (jolt-nth G__2 0 jolt-nil)) (new (jolt-nth G__2 1 jolt-nil))) (if (jolt-contains? map old) (jolt-assoc m new (jolt-get map old)) m))))) (_a$21 (jolt-apply jolt-dissoc map (jolt-keys kmap))) (_a$22 kmap)) (jolt-reduce _a$20 _a$21 _a$22)))))) rename-keys))) -(guard (e (#t #f)) - (def-var! "clojure.set" "map-invert" (letrec ((map-invert (lambda (m) (let fnrec23 ((m m)) (let* ((_a$25 (lambda (acc G__3) (let fnrec24 ((acc acc) (G__3 G__3)) (let* ((G__4 G__3) (k (jolt-nth G__4 0 jolt-nil)) (v (jolt-nth G__4 1 jolt-nil))) (jolt-assoc acc v k))))) (_a$26 (jolt-hash-map)) (_a$27 m)) (jolt-reduce _a$25 _a$26 _a$27)))))) map-invert))) -(guard (e (#t #f)) - (def-var! "clojure.set" "rename" (letrec ((rename (lambda (xrel kmap) (let fnrec28 ((xrel xrel) (kmap kmap)) (jolt-invoke (var-deref "clojure.core" "set") (jolt-map (lambda (m) (let fnrec29 ((m m)) (let* ((_a$31 (lambda (acc G__5) (let fnrec30 ((acc acc) (G__5 G__5)) (let* ((G__6 G__5) (old (jolt-nth G__6 0 jolt-nil)) (new (jolt-nth G__6 1 jolt-nil))) (if (jolt-contains? m old) (jolt-assoc acc new (jolt-get m old)) acc))))) (_a$32 (jolt-apply jolt-dissoc m (jolt-keys kmap))) (_a$33 kmap)) (jolt-reduce _a$31 _a$32 _a$33)))) xrel)))))) rename))) -(guard (e (#t #f)) - (def-var! "clojure.set" "index" (letrec ((index (lambda (xrel ks) (let fnrec34 ((xrel xrel) (ks ks)) (let* ((_a$36 (lambda (m x) (let fnrec35 ((m m) (x x)) (let* ((ik (jolt-invoke (var-deref "clojure.core" "select-keys") x ks))) (jolt-assoc m ik (jolt-conj (jolt-get m ik (jolt-hash-set)) x)))))) (_a$37 (jolt-hash-map)) (_a$38 xrel)) (jolt-reduce _a$36 _a$37 _a$38)))))) index))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.set" "join" (letrec ((join (case-lambda ((xrel yrel) (let fnrec39 ((xrel xrel) (yrel yrel)) (if (jolt-truthy? (let* ((and__25__auto (jolt-seq xrel))) (if (jolt-truthy? and__25__auto) (jolt-seq yrel) and__25__auto))) (let* ((ks (let* ((_a$40 (var-deref "clojure.set" "intersection")) (_a$41 (jolt-invoke (var-deref "clojure.core" "set") (jolt-keys (jolt-first xrel)))) (_a$42 (jolt-invoke (var-deref "clojure.core" "set") (jolt-keys (jolt-first yrel))))) (jolt-invoke _a$40 _a$41 _a$42))) (G__7 (if (let* ((_a$43 (jolt-count xrel)) (_a$44 (jolt-count yrel))) (jolt-n<= _a$43 _a$44)) (let* ((_o$45 xrel) (_o$46 yrel)) (jolt-vector _o$45 _o$46)) (let* ((_o$47 yrel) (_o$48 xrel)) (jolt-vector _o$47 _o$48)))) (r (jolt-nth G__7 0 jolt-nil)) (s (jolt-nth G__7 1 jolt-nil)) (idx (jolt-invoke (var-deref "clojure.set" "index") r ks))) (let* ((_a$51 (lambda (ret x) (let fnrec49 ((ret ret) (x x)) (let* ((found (jolt-invoke idx (jolt-invoke (var-deref "clojure.core" "select-keys") x ks)))) (if (jolt-truthy? found) (jolt-reduce (lambda (acc y) (let fnrec50 ((acc acc) (y y)) (jolt-conj acc (jolt-invoke (var-deref "clojure.core" "merge") y x)))) ret found) ret))))) (_a$52 (jolt-hash-set)) (_a$53 s)) (jolt-reduce _a$51 _a$52 _a$53))) (jolt-hash-set)))) ((xrel yrel km) (let fnrec54 ((xrel xrel) (yrel yrel) (km km)) (let* ((G__8 (if (let* ((_a$55 (jolt-count xrel)) (_a$56 (jolt-count yrel))) (jolt-n<= _a$55 _a$56)) (let* ((_o$57 xrel) (_o$58 yrel) (_o$59 (jolt-invoke (var-deref "clojure.set" "map-invert") km))) (jolt-vector _o$57 _o$58 _o$59)) (let* ((_o$60 yrel) (_o$61 xrel) (_o$62 km)) (jolt-vector _o$60 _o$61 _o$62)))) (r (jolt-nth G__8 0 jolt-nil)) (s (jolt-nth G__8 1 jolt-nil)) (k (jolt-nth G__8 2 jolt-nil)) (idx (jolt-invoke (var-deref "clojure.set" "index") r (jolt-vals k)))) (let* ((_a$65 (lambda (ret x) (let fnrec63 ((ret ret) (x x)) (let* ((found (jolt-invoke idx (jolt-invoke (var-deref "clojure.set" "rename-keys") (jolt-invoke (var-deref "clojure.core" "select-keys") x (jolt-keys k)) k)))) (if (jolt-truthy? found) (jolt-reduce (lambda (acc y) (let fnrec64 ((acc acc) (y y)) (jolt-conj acc (jolt-invoke (var-deref "clojure.core" "merge") y x)))) ret found) ret))))) (_a$66 (jolt-hash-set)) (_a$67 s)) (jolt-reduce _a$65 _a$66 _a$67)))))))) join) (let* ((_o$68 (keyword #f "doc")) (_o$69 "When passed 2 rels, returns the rel corresponding to the natural join.\n When passed an additional keymap, joins on the corresponding keys.")) (jolt-hash-map _o$68 _o$69)))) -(guard (e (#t #f)) - (def-var! "clojure.set" "subset?" (letrec ((subset? (lambda (set1 set2) (let fnrec70 ((set1 set1) (set2 set2)) (let* ((and__25__auto (let* ((_a$71 (jolt-count set1)) (_a$72 (jolt-count set2))) (jolt-n<= _a$71 _a$72)))) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "clojure.core" "every?") (lambda (p__2_) (let fnrec73 ((p__2_ p__2_)) (jolt-contains? set2 p__2_))) set1) and__25__auto)))))) subset?))) -(guard (e (#t #f)) - (def-var! "clojure.set" "superset?" (letrec ((superset? (lambda (set1 set2) (let fnrec74 ((set1 set1) (set2 set2)) (let* ((and__25__auto (let* ((_a$75 (jolt-count set1)) (_a$76 (jolt-count set2))) (jolt-n>= _a$75 _a$76)))) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "clojure.core" "every?") (lambda (p__3_) (let fnrec77 ((p__3_ p__3_)) (jolt-contains? set1 p__3_))) set2) and__25__auto)))))) superset?))) -(guard (e (#t #f)) - (def-var! "clojure.pprint" "getf" - (lambda (sym) (let fnrec78 ((sym sym)) (let* ((_a$85 (var-deref "clojure.core" "__sqcat")) (_a$86 (jolt-invoke (var-deref "clojure.core" "__sq1") sym)) (_a$87 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$82 (var-deref "clojure.core" "__sqcat")) (_a$83 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "deref"))) (_a$84 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$79 (var-deref "clojure.core" "__sqcat")) (_a$80 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f ".-fields"))) (_a$81 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "this")))) (jolt-invoke _a$79 _a$80 _a$81))))) (jolt-invoke _a$82 _a$83 _a$84))))) (jolt-invoke _a$85 _a$86 _a$87))))) - (mark-macro! "clojure.pprint" "getf")) -(guard (e (#t #f)) - (def-var! "clojure.pprint" "setf" - (lambda (sym new-val) (let fnrec88 ((sym sym) (new-val new-val)) (let* ((_a$92 (var-deref "clojure.core" "__sqcat")) (_a$93 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "swap!"))) (_a$94 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$89 (var-deref "clojure.core" "__sqcat")) (_a$90 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f ".-fields"))) (_a$91 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "this")))) (jolt-invoke _a$89 _a$90 _a$91)))) (_a$95 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "assoc"))) (_a$96 (jolt-invoke (var-deref "clojure.core" "__sq1") sym)) (_a$97 (jolt-invoke (var-deref "clojure.core" "__sq1") new-val))) (jolt-invoke _a$92 _a$93 _a$94 _a$95 _a$96 _a$97))))) - (mark-macro! "clojure.pprint" "setf")) -(guard (e (#t #f)) - (def-var! "clojure.pprint" "deftype" - (lambda (type-name . fields) (let fnrec98 ((type-name type-name) (fields (list->cseq fields))) (let* ((name-str (jolt-invoke (var-deref "clojure.core" "name") type-name)) (fields (jolt-map (jolt-invoke (var-deref "clojure.core" "comp") (var-deref "clojure.core" "symbol") (var-deref "clojure.core" "name")) fields))) (let* ((_a$124 (var-deref "clojure.core" "__sqcat")) (_a$125 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "do"))) (_a$126 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$99 (var-deref "clojure.core" "__sqcat")) (_a$100 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "defrecord"))) (_a$101 (jolt-invoke (var-deref "clojure.core" "__sq1") type-name)) (_a$102 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqvec") (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "type-tag")) fields)))) (jolt-invoke _a$99 _a$100 _a$101 _a$102)))) (_a$127 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$107 (var-deref "clojure.core" "__sqcat")) (_a$108 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "defn-"))) (_a$109 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "symbol") (jolt-invoke (var-deref "clojure.core" "str") "make-" name-str)))) (_a$110 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "vec") fields))) (_a$111 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$103 (var-deref "clojure.core" "__sqcat")) (_a$104 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "symbol") (jolt-invoke (var-deref "clojure.core" "str") "->" type-name)))) (_a$105 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "keyword") name-str))) (_a$106 fields)) (jolt-invoke _a$103 _a$104 _a$105 _a$106))))) (jolt-invoke _a$107 _a$108 _a$109 _a$110 _a$111)))) (_a$128 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$119 (var-deref "clojure.core" "__sqcat")) (_a$120 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "defn-"))) (_a$121 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "symbol") (jolt-invoke (var-deref "clojure.core" "str") name-str "?")))) (_a$122 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqvec") (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "x__1__auto"))))) (_a$123 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$115 (var-deref "clojure.core" "__sqcat")) (_a$116 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "="))) (_a$117 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$112 (var-deref "clojure.core" "__sqcat")) (_a$113 (jolt-invoke (var-deref "clojure.core" "__sq1") (keyword #f "type-tag"))) (_a$114 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "x__1__auto")))) (jolt-invoke _a$112 _a$113 _a$114)))) (_a$118 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "keyword") name-str)))) (jolt-invoke _a$115 _a$116 _a$117 _a$118))))) (jolt-invoke _a$119 _a$120 _a$121 _a$122 _a$123))))) (jolt-invoke _a$124 _a$125 _a$126 _a$127 _a$128)))))) - (mark-macro! "clojure.pprint" "deftype")) -(guard (e (#t #f)) - (def-var! "clojure.pprint" "pprint-logical-block" - (lambda args (let fnrec129 ((args (list->cseq args))) (let* ((G__9 (let* ((body args) (acc (jolt-vector))) (let loop130 ((body body) (acc acc)) (if (jolt-truthy? (let* ((_a$134 (let* ((_o$131 (keyword #f "prefix")) (_o$132 (keyword #f "per-line-prefix")) (_o$133 (keyword #f "suffix"))) (jolt-hash-set _o$131 _o$132 _o$133))) (_a$135 (jolt-first body))) (jolt-get _a$134 _a$135))) (let* ((_a$136 (jolt-drop 2 body)) (_a$137 (jolt-concat acc (jolt-take 2 body)))) (loop130 _a$136 _a$137)) (let* ((_o$138 (jolt-apply jolt-hash-map-fn acc)) (_o$139 body)) (jolt-vector _o$138 _o$139)))))) (options (jolt-nth G__9 0 jolt-nil)) (body (jolt-nth G__9 1 jolt-nil))) (let* ((_a$172 (var-deref "clojure.core" "__sqcat")) (_a$173 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "do"))) (_a$174 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$167 (var-deref "clojure.core" "__sqcat")) (_a$168 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "if"))) (_a$169 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqcat") (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.pprint" "level-exceeded"))))) (_a$170 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$140 (var-deref "clojure.core" "__sqcat")) (_a$141 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.pprint" "-write"))) (_a$142 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "*out*"))) (_a$143 (jolt-invoke (var-deref "clojure.core" "__sq1") "#"))) (jolt-invoke _a$140 _a$141 _a$142 _a$143)))) (_a$171 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$161 (var-deref "clojure.core" "__sqcat")) (_a$162 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "binding"))) (_a$163 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$147 (var-deref "clojure.core" "__sqvec")) (_a$148 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.pprint" "*current-level*"))) (_a$149 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$144 (var-deref "clojure.core" "__sqcat")) (_a$145 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "inc"))) (_a$146 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.pprint" "*current-level*")))) (jolt-invoke _a$144 _a$145 _a$146)))) (_a$150 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.pprint" "*current-length*"))) (_a$151 (jolt-invoke (var-deref "clojure.core" "__sq1") 0))) (jolt-invoke _a$147 _a$148 _a$149 _a$150 _a$151)))) (_a$164 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$152 (var-deref "clojure.core" "__sqcat")) (_a$153 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.pprint" "start-block"))) (_a$154 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "*out*"))) (_a$155 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-get options (keyword #f "prefix")))) (_a$156 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-get options (keyword #f "per-line-prefix")))) (_a$157 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-get options (keyword #f "suffix"))))) (jolt-invoke _a$152 _a$153 _a$154 _a$155 _a$156 _a$157)))) (_a$165 body) (_a$166 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$158 (var-deref "clojure.core" "__sqcat")) (_a$159 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.pprint" "end-block"))) (_a$160 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "*out*")))) (jolt-invoke _a$158 _a$159 _a$160))))) (jolt-invoke _a$161 _a$162 _a$163 _a$164 _a$165 _a$166))))) (jolt-invoke _a$167 _a$168 _a$169 _a$170 _a$171)))) (_a$175 (jolt-invoke (var-deref "clojure.core" "__sq1") jolt-nil))) (jolt-invoke _a$172 _a$173 _a$174 _a$175)))))) - (mark-macro! "clojure.pprint" "pprint-logical-block")) -(guard (e (#t #f)) - (def-var! "clojure.pprint" "print-length-loop" - (lambda (bindings . body) (let fnrec176 ((bindings bindings) (body (list->cseq body))) (let* ((_a$177 (var-deref "clojure.core" "__sqcat")) (_a$178 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "loop"))) (_a$179 (jolt-invoke (var-deref "clojure.core" "__sq1") bindings)) (_a$180 body)) (jolt-invoke _a$177 _a$178 _a$179 _a$180))))) - (mark-macro! "clojure.pprint" "print-length-loop")) -(guard (e (#t #f)) - (def-var! "clojure.pprint" "formatter-out" - (lambda (format-in) (let fnrec181 ((format-in format-in)) (let* ((_a$219 (var-deref "clojure.core" "__sqcat")) (_a$220 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "let"))) (_a$221 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$193 (var-deref "clojure.core" "__sqvec")) (_a$194 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "format-in__5__auto"))) (_a$195 (jolt-invoke (var-deref "clojure.core" "__sq1") format-in)) (_a$196 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "cf__3__auto"))) (_a$197 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$188 (var-deref "clojure.core" "__sqcat")) (_a$189 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "if"))) (_a$190 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$182 (var-deref "clojure.core" "__sqcat")) (_a$183 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "string?"))) (_a$184 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "format-in__5__auto")))) (jolt-invoke _a$182 _a$183 _a$184)))) (_a$191 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$185 (var-deref "clojure.core" "__sqcat")) (_a$186 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.pprint" "cached-compile"))) (_a$187 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "format-in__5__auto")))) (jolt-invoke _a$185 _a$186 _a$187)))) (_a$192 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "format-in__5__auto")))) (jolt-invoke _a$188 _a$189 _a$190 _a$191 _a$192))))) (jolt-invoke _a$193 _a$194 _a$195 _a$196 _a$197)))) (_a$222 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$215 (var-deref "clojure.core" "__sqcat")) (_a$216 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "fn"))) (_a$217 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$198 (var-deref "clojure.core" "__sqvec")) (_a$199 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.pprint" "&"))) (_a$200 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "args__4__auto")))) (jolt-invoke _a$198 _a$199 _a$200)))) (_a$218 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$211 (var-deref "clojure.core" "__sqcat")) (_a$212 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "let"))) (_a$213 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$204 (var-deref "clojure.core" "__sqvec")) (_a$205 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "navigator__2__auto"))) (_a$206 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$201 (var-deref "clojure.core" "__sqcat")) (_a$202 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.pprint" "init-navigator"))) (_a$203 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "args__4__auto")))) (jolt-invoke _a$201 _a$202 _a$203))))) (jolt-invoke _a$204 _a$205 _a$206)))) (_a$214 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$207 (var-deref "clojure.core" "__sqcat")) (_a$208 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.pprint" "execute-format"))) (_a$209 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "cf__3__auto"))) (_a$210 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "navigator__2__auto")))) (jolt-invoke _a$207 _a$208 _a$209 _a$210))))) (jolt-invoke _a$211 _a$212 _a$213 _a$214))))) (jolt-invoke _a$215 _a$216 _a$217 _a$218))))) (jolt-invoke _a$219 _a$220 _a$221 _a$222))))) - (mark-macro! "clojure.pprint" "formatter-out")) -(guard (e (#t #f)) - (def-var! "clojure.pprint" "formatter" - (lambda (format-in) (let fnrec223 ((format-in format-in)) (let* ((_a$263 (var-deref "clojure.core" "__sqcat")) (_a$264 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "let"))) (_a$265 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$235 (var-deref "clojure.core" "__sqvec")) (_a$236 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "format-in__10__auto"))) (_a$237 (jolt-invoke (var-deref "clojure.core" "__sq1") format-in)) (_a$238 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "cf__6__auto"))) (_a$239 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$230 (var-deref "clojure.core" "__sqcat")) (_a$231 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "if"))) (_a$232 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$224 (var-deref "clojure.core" "__sqcat")) (_a$225 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "string?"))) (_a$226 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "format-in__10__auto")))) (jolt-invoke _a$224 _a$225 _a$226)))) (_a$233 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$227 (var-deref "clojure.core" "__sqcat")) (_a$228 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.pprint" "cached-compile"))) (_a$229 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "format-in__10__auto")))) (jolt-invoke _a$227 _a$228 _a$229)))) (_a$234 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "format-in__10__auto")))) (jolt-invoke _a$230 _a$231 _a$232 _a$233 _a$234))))) (jolt-invoke _a$235 _a$236 _a$237 _a$238 _a$239)))) (_a$266 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$259 (var-deref "clojure.core" "__sqcat")) (_a$260 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "fn"))) (_a$261 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$240 (var-deref "clojure.core" "__sqvec")) (_a$241 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "stream__8__auto"))) (_a$242 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.pprint" "&"))) (_a$243 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "args__9__auto")))) (jolt-invoke _a$240 _a$241 _a$242 _a$243)))) (_a$262 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$255 (var-deref "clojure.core" "__sqcat")) (_a$256 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "let"))) (_a$257 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$247 (var-deref "clojure.core" "__sqvec")) (_a$248 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "navigator__7__auto"))) (_a$249 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$244 (var-deref "clojure.core" "__sqcat")) (_a$245 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.pprint" "init-navigator"))) (_a$246 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "args__9__auto")))) (jolt-invoke _a$244 _a$245 _a$246))))) (jolt-invoke _a$247 _a$248 _a$249)))) (_a$258 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$250 (var-deref "clojure.core" "__sqcat")) (_a$251 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.pprint" "execute-format"))) (_a$252 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "stream__8__auto"))) (_a$253 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "cf__6__auto"))) (_a$254 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "navigator__7__auto")))) (jolt-invoke _a$250 _a$251 _a$252 _a$253 _a$254))))) (jolt-invoke _a$255 _a$256 _a$257 _a$258))))) (jolt-invoke _a$259 _a$260 _a$261 _a$262))))) (jolt-invoke _a$263 _a$264 _a$265 _a$266))))) - (mark-macro! "clojure.pprint" "formatter")) -(guard (e (#t #f)) - (def-var! "clojure.pprint" "with-pprint-dispatch" - (lambda (function . body) (let fnrec267 ((function function) (body (list->cseq body))) (let* ((_a$271 (var-deref "clojure.core" "__sqcat")) (_a$272 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "binding"))) (_a$273 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$268 (var-deref "clojure.core" "__sqvec")) (_a$269 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.pprint" "*print-pprint-dispatch*"))) (_a$270 (jolt-invoke (var-deref "clojure.core" "__sq1") function))) (jolt-invoke _a$268 _a$269 _a$270)))) (_a$274 body)) (jolt-invoke _a$271 _a$272 _a$273 _a$274))))) - (mark-macro! "clojure.pprint" "with-pprint-dispatch")) -(guard (e (#t #f)) - (def-var! "clojure.pprint" "pp" - (lambda () (let fnrec275 () jolt-nil))) - (mark-macro! "clojure.pprint" "pp")) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "print" (letrec ((print (lambda more (let fnrec276 ((more (list->cseq more))) (jolt-invoke (var-deref "clojure.pprint" "-write") (var-deref "clojure.core" "*out*") (jolt-apply (var-deref "clojure.core" "print-str") more)))))) print) (let* ((_o$277 (keyword #f "private")) (_o$278 #t)) (jolt-hash-map _o$277 _o$278)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "println" (letrec ((println (lambda more (let fnrec279 ((more (list->cseq more))) (begin (jolt-apply (var-deref "clojure.pprint" "print") more) (jolt-invoke (var-deref "clojure.pprint" "-write") (var-deref "clojure.core" "*out*") "\n")))))) println) (let* ((_o$280 (keyword #f "private")) (_o$281 #t)) (jolt-hash-map _o$280 _o$281)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "print-char" (letrec ((print-char (lambda (c) (let fnrec282 ((c c)) (jolt-invoke (var-deref "clojure.pprint" "-write") (var-deref "clojure.core" "*out*") (let* ((G__10 jolt=) (G__11 c)) (if (jolt-truthy? (jolt-invoke G__10 (integer->char 8) G__11)) "\\backspace" (if (jolt-truthy? (jolt-invoke G__10 (integer->char 32) G__11)) "\\space" (if (jolt-truthy? (jolt-invoke G__10 (integer->char 9) G__11)) "\\tab" (if (jolt-truthy? (jolt-invoke G__10 (integer->char 10) G__11)) "\\newline" (if (jolt-truthy? (jolt-invoke G__10 (integer->char 12) G__11)) "\\formfeed" (if (jolt-truthy? (jolt-invoke G__10 (integer->char 13) G__11)) "\\return" (if (jolt-truthy? (jolt-invoke G__10 (integer->char 34) G__11)) "\\\"" (if (jolt-truthy? (jolt-invoke G__10 (integer->char 92) G__11)) "\\\\" (jolt-invoke (var-deref "clojure.core" "str") "\\" c))))))))))))))) print-char) (let* ((_o$283 (keyword #f "private")) (_o$284 #t)) (jolt-hash-map _o$283 _o$284)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "pr" (letrec ((pr (lambda more (let fnrec285 ((more (list->cseq more))) (jolt-invoke (var-deref "clojure.pprint" "-write") (var-deref "clojure.core" "*out*") (jolt-apply (var-deref "clojure.core" "pr-str") more)))))) pr) (let* ((_o$286 (keyword #f "dynamic")) (_o$287 #t) (_o$288 (keyword #f "private")) (_o$289 #t)) (jolt-hash-map _o$286 _o$287 _o$288 _o$289)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "prn" (letrec ((prn (lambda more (let fnrec290 ((more (list->cseq more))) (begin (jolt-apply (var-deref "clojure.pprint" "pr") more) (jolt-invoke (var-deref "clojure.pprint" "-write") (var-deref "clojure.core" "*out*") "\n")))))) prn) (let* ((_o$291 (keyword #f "private")) (_o$292 #t)) (jolt-hash-map _o$291 _o$292)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "float?" (letrec ((float? (lambda (n) (let fnrec293 ((n n)) (let* ((and__25__auto (jolt-invoke (var-deref "clojure.core" "number?") n))) (if (jolt-truthy? and__25__auto) (jolt-not (jolt-invoke (var-deref "clojure.core" "integer?") n)) and__25__auto)))))) float?) (let* ((_o$294 (keyword #f "private")) (_o$295 #t)) (jolt-hash-map _o$294 _o$295)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "char-code" (letrec ((char-code (lambda (c) (let fnrec296 ((c c)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "number?") c)) c (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "char?") c)) (jolt-invoke (var-deref "clojure.core" "int") c) (if (jolt-truthy? (let* ((and__25__auto (jolt-invoke (var-deref "clojure.core" "string?") c))) (if (jolt-truthy? and__25__auto) (jolt= (jolt-count c) 1) and__25__auto))) (jolt-invoke (var-deref "clojure.core" "int") (record-method-dispatch c "charAt" (jolt-vector 0))) (if (jolt-truthy? (keyword #f "else")) (jolt-throw (host-new "Exception" "Argument to char must be a character or number")) jolt-nil)))))))) char-code) (let* ((_o$297 (keyword #f "private")) (_o$298 #t)) (jolt-hash-map _o$297 _o$298)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "map-passing-context" (letrec ((map-passing-context (lambda (func initial-context lis) (let fnrec299 ((func func) (initial-context initial-context) (lis lis)) (let* ((context initial-context) (lis lis) (acc (jolt-vector))) (let loop300 ((context context) (lis lis) (acc acc)) (if (jolt-empty? lis) (let* ((_o$301 acc) (_o$302 context)) (jolt-vector _o$301 _o$302)) (let* ((this (jolt-first lis)) (remainder (jolt-next lis)) (G__12 (jolt-apply func (let* ((_o$303 this) (_o$304 context)) (jolt-vector _o$303 _o$304)))) (result (jolt-nth G__12 0 jolt-nil)) (new-context (jolt-nth G__12 1 jolt-nil))) (loop300 new-context remainder (jolt-conj acc result)))))))))) map-passing-context) (let* ((_o$305 (keyword #f "private")) (_o$306 #t)) (jolt-hash-map _o$305 _o$306)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "consume" (letrec ((consume (lambda (func initial-context) (let fnrec307 ((func func) (initial-context initial-context)) (let* ((context initial-context) (acc (jolt-vector))) (let loop308 ((context context) (acc acc)) (let* ((G__13 (jolt-apply func (jolt-vector context))) (result (jolt-nth G__13 0 jolt-nil)) (new-context (jolt-nth G__13 1 jolt-nil))) (if (jolt-not result) (let* ((_o$309 acc) (_o$310 new-context)) (jolt-vector _o$309 _o$310)) (loop308 new-context (jolt-conj acc result)))))))))) consume) (let* ((_o$311 (keyword #f "private")) (_o$312 #t)) (jolt-hash-map _o$311 _o$312)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "unzip-map" (letrec ((unzip-map (lambda (m) (let fnrec313 ((m m)) (let* ((_o$324 (let* ((_a$317 (jolt-hash-map)) (_a$318 (jolt-map (lambda (G__14) (let fnrec314 ((G__14 G__14)) (let* ((G__15 G__14) (k (jolt-nth G__15 0 jolt-nil)) (G__16 (jolt-nth G__15 1 jolt-nil)) (v1 (jolt-nth G__16 0 jolt-nil)) (v2 (jolt-nth G__16 1 jolt-nil))) (let* ((_o$315 k) (_o$316 v1)) (jolt-vector _o$315 _o$316))))) m))) (jolt-into _a$317 _a$318))) (_o$325 (let* ((_a$322 (jolt-hash-map)) (_a$323 (jolt-map (lambda (G__17) (let fnrec319 ((G__17 G__17)) (let* ((G__18 G__17) (k (jolt-nth G__18 0 jolt-nil)) (G__19 (jolt-nth G__18 1 jolt-nil)) (v1 (jolt-nth G__19 0 jolt-nil)) (v2 (jolt-nth G__19 1 jolt-nil))) (let* ((_o$320 k) (_o$321 v2)) (jolt-vector _o$320 _o$321))))) m))) (jolt-into _a$322 _a$323)))) (jolt-vector _o$324 _o$325)))))) unzip-map) (let* ((_o$326 (keyword #f "private")) (_o$327 #t)) (jolt-hash-map _o$326 _o$327)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "tuple-map" (letrec ((tuple-map (lambda (m v1) (let fnrec328 ((m m) (v1 v1)) (let* ((_a$334 (jolt-hash-map)) (_a$335 (jolt-map (lambda (G__20) (let fnrec329 ((G__20 G__20)) (let* ((G__21 G__20) (k (jolt-nth G__21 0 jolt-nil)) (v (jolt-nth G__21 1 jolt-nil))) (let* ((_o$332 k) (_o$333 (let* ((_o$330 v) (_o$331 v1)) (jolt-vector _o$330 _o$331)))) (jolt-vector _o$332 _o$333))))) m))) (jolt-into _a$334 _a$335)))))) tuple-map) (let* ((_o$336 (keyword #f "private")) (_o$337 #t)) (jolt-hash-map _o$336 _o$337)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "rtrim" (letrec ((rtrim (lambda (s c) (let fnrec338 ((s s) (c c)) (let* ((len (jolt-count s))) (if (let* ((and__25__auto (jolt-pos? len))) (if (jolt-truthy? and__25__auto) (jolt= (jolt-nth s (jolt-dec (jolt-count s))) c) and__25__auto)) (let* ((n (jolt-dec len))) (let loop339 ((n n)) (if (jolt-neg? n) "" (if (jolt-not (jolt= (jolt-nth s n) c)) (jolt-invoke (var-deref "clojure.core" "subs") s 0 (jolt-inc n)) (if #t (loop339 (jolt-dec n)) jolt-nil))))) s)))))) rtrim) (let* ((_o$340 (keyword #f "private")) (_o$341 #t)) (jolt-hash-map _o$340 _o$341)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "ltrim" (letrec ((ltrim (lambda (s c) (let fnrec342 ((s s) (c c)) (let* ((len (jolt-count s))) (if (let* ((and__25__auto (jolt-pos? len))) (if (jolt-truthy? and__25__auto) (jolt= (jolt-nth s 0) c) and__25__auto)) (let* ((n 0)) (let loop343 ((n n)) (if (let* ((or__26__auto (jolt= n len))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-not (jolt= (jolt-nth s n) c)))) (jolt-invoke (var-deref "clojure.core" "subs") s n) (loop343 (jolt-inc n))))) s)))))) ltrim) (let* ((_o$344 (keyword #f "private")) (_o$345 #t)) (jolt-hash-map _o$344 _o$345)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "prefix-count" (letrec ((prefix-count (lambda (aseq val) (let fnrec346 ((aseq aseq) (val val)) (let* ((test (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "coll?") val)) (jolt-invoke (var-deref "clojure.core" "set") val) (jolt-hash-set val)))) (let* ((pos 0)) (let loop347 ((pos pos)) (if (let* ((or__26__auto (jolt= pos (jolt-count aseq)))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-not (jolt-invoke test (jolt-nth aseq pos))))) pos (loop347 (jolt-inc pos)))))))))) prefix-count) (let* ((_o$348 (keyword #f "private")) (_o$349 #t)) (jolt-hash-map _o$348 _o$349)))) -(guard (e (#t #f)) - (begin (def-var! "clojure.pprint" "IPrettyFlush" (jolt-invoke (var-deref "clojure.core" "make-protocol") "IPrettyFlush" (let* ((_o$352 (keyword #f "-ppflush")) (_o$353 (let* ((_o$350 (keyword #f "name")) (_o$351 "-ppflush")) (jolt-hash-map _o$350 _o$351)))) (jolt-hash-map _o$352 _o$353)))) (jolt-invoke (var-deref "clojure.core" "register-protocol-methods!") "IPrettyFlush" (jolt-vector "-ppflush")) (def-var! "clojure.pprint" "-ppflush" (lambda (G__22) (let fnrec354 ((G__22 G__22)) (protocol-dispatch1 "IPrettyFlush" "-ppflush" G__22)))))) -(guard (e (#t #f)) - (begin (def-var! "clojure.pprint" "IPrettyWriter" (jolt-invoke (var-deref "clojure.core" "make-protocol") "IPrettyWriter" (let* ((_o$359 (keyword #f "-write")) (_o$360 (let* ((_o$355 (keyword #f "name")) (_o$356 "-write")) (jolt-hash-map _o$355 _o$356))) (_o$361 (keyword #f "-pflush")) (_o$362 (let* ((_o$357 (keyword #f "name")) (_o$358 "-pflush")) (jolt-hash-map _o$357 _o$358)))) (jolt-hash-map _o$359 _o$360 _o$361 _o$362)))) (jolt-invoke (var-deref "clojure.core" "register-protocol-methods!") "IPrettyWriter" (let* ((_o$363 "-write") (_o$364 "-pflush")) (jolt-vector _o$363 _o$364))) (def-var! "clojure.pprint" "-write" (lambda (G__23 G__24) (let fnrec365 ((G__23 G__23) (G__24 G__24)) (protocol-dispatch2 "IPrettyWriter" "-write" G__23 G__24)))) (def-var! "clojure.pprint" "-pflush" (lambda (G__25) (let fnrec366 ((G__25 G__25)) (protocol-dispatch1 "IPrettyWriter" "-pflush" G__25)))))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "*default-page-width*" 72 (let* ((_o$367 (keyword #f "private")) (_o$368 #t) (_o$369 (keyword #f "dynamic")) (_o$370 #t)) (jolt-hash-map _o$367 _o$368 _o$369 _o$370)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "get-field" (letrec ((get-field (lambda (this sym) (let fnrec371 ((this this) (sym sym)) (jolt-invoke sym (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch this "-fields" (jolt-vector)))))))) get-field) (let* ((_o$372 (keyword #f "private")) (_o$373 #t)) (jolt-hash-map _o$372 _o$373)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "set-field" (letrec ((set-field (lambda (this sym new-val) (let fnrec374 ((this this) (sym sym) (new-val new-val)) (jolt-invoke (var-deref "clojure.core" "swap!") (record-method-dispatch this "-fields" (jolt-vector)) jolt-assoc sym new-val))))) set-field) (let* ((_o$375 (keyword #f "private")) (_o$376 #t)) (jolt-hash-map _o$375 _o$376)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "get-column" (letrec ((get-column (lambda (this) (let fnrec377 ((this this)) (jolt-invoke (var-deref "clojure.pprint" "get-field") this (keyword #f "cur")))))) get-column) (let* ((_o$378 (keyword #f "private")) (_o$379 #t)) (jolt-hash-map _o$378 _o$379)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "get-line" (letrec ((get-line (lambda (this) (let fnrec380 ((this this)) (jolt-invoke (var-deref "clojure.pprint" "get-field") this (keyword #f "line")))))) get-line) (let* ((_o$381 (keyword #f "private")) (_o$382 #t)) (jolt-hash-map _o$381 _o$382)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "get-max-column" (letrec ((get-max-column (lambda (this) (let fnrec383 ((this this)) (jolt-invoke (var-deref "clojure.pprint" "get-field") this (keyword #f "max")))))) get-max-column) (let* ((_o$384 (keyword #f "private")) (_o$385 #t)) (jolt-hash-map _o$384 _o$385)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "set-max-column" (letrec ((set-max-column (lambda (this new-max) (let fnrec386 ((this this) (new-max new-max)) (begin (jolt-invoke (var-deref "clojure.pprint" "set-field") this (keyword #f "max") new-max) jolt-nil))))) set-max-column) (let* ((_o$387 (keyword #f "private")) (_o$388 #t)) (jolt-hash-map _o$387 _o$388)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "get-writer" (letrec ((get-writer (lambda (this) (let fnrec389 ((this this)) (jolt-invoke (var-deref "clojure.pprint" "get-field") this (keyword #f "base")))))) get-writer) (let* ((_o$390 (keyword #f "private")) (_o$391 #t)) (jolt-hash-map _o$390 _o$391)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "c-write-char" (letrec ((c-write-char (lambda (this c) (let fnrec392 ((this this) (c c)) (begin (if (jolt= c (integer->char 10)) (begin (jolt-invoke (var-deref "clojure.pprint" "set-field") this (keyword #f "cur") 0) (jolt-invoke (var-deref "clojure.pprint" "set-field") this (keyword #f "line") (jolt-inc (jolt-invoke (var-deref "clojure.pprint" "get-field") this (keyword #f "line"))))) (jolt-invoke (var-deref "clojure.pprint" "set-field") this (keyword #f "cur") (jolt-inc (jolt-invoke (var-deref "clojure.pprint" "get-field") this (keyword #f "cur"))))) (jolt-invoke (var-deref "clojure.pprint" "-write") (jolt-invoke (var-deref "clojure.pprint" "get-field") this (keyword #f "base")) c)))))) c-write-char) (let* ((_o$393 (keyword #f "private")) (_o$394 #t)) (jolt-hash-map _o$393 _o$394)))) -(guard (e (#t #f)) - (begin (begin (def-var! "clojure.pprint" "StringBufferWriter" (let* ((_a$395 (var-deref "clojure.core" "make-deftype-ctor")) (_a$396 (jolt-symbol #f "StringBufferWriter")) (_a$397 (jolt-vector (keyword #f "sb"))) (_a$398 (jolt-vector jolt-nil)) (_a$399 (jolt-vector #f))) (jolt-invoke _a$395 _a$396 _a$397 _a$398 _a$399))) (def-var! "clojure.pprint" "->StringBufferWriter" (var-deref "clojure.pprint" "StringBufferWriter")) (var-deref "clojure.pprint" "StringBufferWriter")) (jolt-invoke (var-deref "clojure.core" "register-record-type!") (jolt-symbol #f "StringBufferWriter")) (def-var! "clojure.pprint" "map->StringBufferWriter" (lambda (G__26) (let fnrec400 ((G__26 G__26)) (let* ((_a$401 (var-deref "clojure.core" "reduce-kv")) (_a$402 jolt-assoc) (_a$403 (jolt-invoke (var-deref "clojure.pprint" "->StringBufferWriter") (jolt-get G__26 (keyword #f "sb")))) (_a$404 (jolt-dissoc G__26 (keyword #f "sb")))) (jolt-invoke _a$401 _a$402 _a$403 _a$404))))) (jolt-invoke (var-deref "clojure.core" "register-inline-protocol!") "StringBufferWriter" "IPrettyWriter") (jolt-invoke (var-deref "clojure.core" "register-inline-method") "StringBufferWriter" "IPrettyWriter" "-write" (lambda (_p27 x) (let fnrec405 ((_p27 _p27) (x x)) (let* ((sb (jolt-get _p27 (keyword #f "sb")))) (begin (record-method-dispatch sb "append" (jolt-vector (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "char?") x)) (jolt-invoke (var-deref "clojure.core" "str") x) x))) jolt-nil))))) (jolt-invoke (var-deref "clojure.core" "register-inline-method") "StringBufferWriter" "IPrettyWriter" "-pflush" (lambda (_p28) (let fnrec406 ((_p28 _p28)) (let* ((sb (jolt-get _p28 (keyword #f "sb")))) jolt-nil)))) (jolt-invoke (var-deref "clojure.core" "register-inline-protocol!") "StringBufferWriter" "IPrettyFlush") (jolt-invoke (var-deref "clojure.core" "register-inline-method") "StringBufferWriter" "IPrettyFlush" "-ppflush" (lambda (_p29) (let fnrec407 ((_p29 _p29)) (let* ((sb (jolt-get _p29 (keyword #f "sb")))) jolt-nil)))))) -(guard (e (#t #f)) - (begin (begin (def-var! "clojure.pprint" "ColumnWriter" (let* ((_a$408 (var-deref "clojure.core" "make-deftype-ctor")) (_a$409 (jolt-symbol #f "ColumnWriter")) (_a$410 (jolt-vector (keyword #f "fields"))) (_a$411 (jolt-vector jolt-nil)) (_a$412 (jolt-vector #f))) (jolt-invoke _a$408 _a$409 _a$410 _a$411 _a$412))) (def-var! "clojure.pprint" "->ColumnWriter" (var-deref "clojure.pprint" "ColumnWriter")) (var-deref "clojure.pprint" "ColumnWriter")) (jolt-invoke (var-deref "clojure.core" "register-record-type!") (jolt-symbol #f "ColumnWriter")) (def-var! "clojure.pprint" "map->ColumnWriter" (lambda (G__30) (let fnrec413 ((G__30 G__30)) (let* ((_a$414 (var-deref "clojure.core" "reduce-kv")) (_a$415 jolt-assoc) (_a$416 (jolt-invoke (var-deref "clojure.pprint" "->ColumnWriter") (jolt-get G__30 (keyword #f "fields")))) (_a$417 (jolt-dissoc G__30 (keyword #f "fields")))) (jolt-invoke _a$414 _a$415 _a$416 _a$417))))) (jolt-invoke (var-deref "clojure.core" "register-inline-protocol!") "ColumnWriter" "IPrettyWriter") (jolt-invoke (var-deref "clojure.core" "register-inline-method") "ColumnWriter" "IPrettyWriter" "-write" (lambda (this x) (let fnrec418 ((this this) (x x)) (let* ((fields (jolt-get this (keyword #f "fields")))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "string?") x)) (let* ((s x) (nl (record-method-dispatch s "lastIndexOf" (jolt-vector "\n")))) (begin (if (jolt-neg? nl) (jolt-invoke (var-deref "clojure.pprint" "set-field") this (keyword #f "cur") (let* ((_a$419 (jolt-invoke (var-deref "clojure.pprint" "get-field") this (keyword #f "cur"))) (_a$420 (jolt-count s))) (jolt-n+ _a$419 _a$420))) (begin (jolt-invoke (var-deref "clojure.pprint" "set-field") this (keyword #f "cur") (jolt-n- (jolt-count s) nl 1)) (jolt-invoke (var-deref "clojure.pprint" "set-field") this (keyword #f "line") (let* ((_a$422 (jolt-invoke (var-deref "clojure.pprint" "get-field") this (keyword #f "line"))) (_a$423 (jolt-count (jolt-filter (lambda (p__4_) (let fnrec421 ((p__4_ p__4_)) (jolt= p__4_ (integer->char 10)))) s)))) (jolt-n+ _a$422 _a$423))))) (jolt-invoke (var-deref "clojure.pprint" "-write") (jolt-invoke (var-deref "clojure.pprint" "get-field") this (keyword #f "base")) s))) (if (jolt-truthy? (let* ((or__26__auto (jolt-invoke (var-deref "clojure.core" "char?") x))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-invoke (var-deref "clojure.core" "number?") x)))) (jolt-invoke (var-deref "clojure.pprint" "c-write-char") this x) jolt-nil)))))) (jolt-invoke (var-deref "clojure.core" "register-inline-method") "ColumnWriter" "IPrettyWriter" "-pflush" (lambda (this) (let fnrec424 ((this this)) (let* ((fields (jolt-get this (keyword #f "fields")))) (jolt-invoke (var-deref "clojure.pprint" "-pflush") (jolt-invoke (var-deref "clojure.pprint" "get-field") this (keyword #f "base"))))))) (jolt-invoke (var-deref "clojure.core" "register-inline-protocol!") "ColumnWriter" "IPrettyFlush") (jolt-invoke (var-deref "clojure.core" "register-inline-method") "ColumnWriter" "IPrettyFlush" "-ppflush" (lambda (_p31) (let fnrec425 ((_p31 _p31)) (let* ((fields (jolt-get _p31 (keyword #f "fields")))) jolt-nil)))))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "column-writer" (letrec ((column-writer (case-lambda ((writer) (let fnrec426 ((writer writer)) (column-writer writer (var-deref "clojure.pprint" "*default-page-width*")))) ((writer max-columns) (let fnrec427 ((writer writer) (max-columns max-columns)) (jolt-invoke (var-deref "clojure.pprint" "->ColumnWriter") (jolt-invoke (var-deref "clojure.core" "atom") (let* ((_o$428 (keyword #f "max")) (_o$429 max-columns) (_o$430 (keyword #f "cur")) (_o$431 0) (_o$432 (keyword #f "line")) (_o$433 0) (_o$434 (keyword #f "base")) (_o$435 writer)) (jolt-hash-map _o$428 _o$429 _o$430 _o$431 _o$432 _o$433 _o$434 _o$435))))))))) column-writer) (let* ((_o$436 (keyword #f "private")) (_o$437 #t)) (jolt-hash-map _o$436 _o$437)))) -(guard (e (#t #f)) - (declare-var! "clojure.pprint" "get-miser-width")) -(guard (e (#t #f)) - (begin (begin (def-var! "clojure.pprint" "logical-block" (let* ((_a$468 (var-deref "clojure.core" "make-deftype-ctor")) (_a$469 (jolt-symbol #f "logical-block")) (_a$470 (let* ((_o$438 (keyword #f "parent")) (_o$439 (keyword #f "section")) (_o$440 (keyword #f "start-col")) (_o$441 (keyword #f "indent")) (_o$442 (keyword #f "done-nl")) (_o$443 (keyword #f "intra-block-nl")) (_o$444 (keyword #f "prefix")) (_o$445 (keyword #f "per-line-prefix")) (_o$446 (keyword #f "suffix")) (_o$447 (keyword #f "logical-block-callback"))) (jolt-vector _o$438 _o$439 _o$440 _o$441 _o$442 _o$443 _o$444 _o$445 _o$446 _o$447))) (_a$471 (let* ((_o$448 jolt-nil) (_o$449 jolt-nil) (_o$450 jolt-nil) (_o$451 jolt-nil) (_o$452 jolt-nil) (_o$453 jolt-nil) (_o$454 jolt-nil) (_o$455 jolt-nil) (_o$456 jolt-nil) (_o$457 jolt-nil)) (jolt-vector _o$448 _o$449 _o$450 _o$451 _o$452 _o$453 _o$454 _o$455 _o$456 _o$457))) (_a$472 (let* ((_o$458 #f) (_o$459 #f) (_o$460 #f) (_o$461 #f) (_o$462 #f) (_o$463 #f) (_o$464 #f) (_o$465 #f) (_o$466 #f) (_o$467 #f)) (jolt-vector _o$458 _o$459 _o$460 _o$461 _o$462 _o$463 _o$464 _o$465 _o$466 _o$467)))) (jolt-invoke _a$468 _a$469 _a$470 _a$471 _a$472))) (def-var! "clojure.pprint" "->logical-block" (var-deref "clojure.pprint" "logical-block")) (var-deref "clojure.pprint" "logical-block")) (jolt-invoke (var-deref "clojure.core" "register-record-type!") (jolt-symbol #f "logical-block")) (def-var! "clojure.pprint" "map->logical-block" (lambda (G__32) (let fnrec473 ((G__32 G__32)) (let* ((_a$485 (var-deref "clojure.core" "reduce-kv")) (_a$486 jolt-assoc) (_a$487 (let* ((_a$474 (var-deref "clojure.pprint" "->logical-block")) (_a$475 (jolt-get G__32 (keyword #f "parent"))) (_a$476 (jolt-get G__32 (keyword #f "section"))) (_a$477 (jolt-get G__32 (keyword #f "start-col"))) (_a$478 (jolt-get G__32 (keyword #f "indent"))) (_a$479 (jolt-get G__32 (keyword #f "done-nl"))) (_a$480 (jolt-get G__32 (keyword #f "intra-block-nl"))) (_a$481 (jolt-get G__32 (keyword #f "prefix"))) (_a$482 (jolt-get G__32 (keyword #f "per-line-prefix"))) (_a$483 (jolt-get G__32 (keyword #f "suffix"))) (_a$484 (jolt-get G__32 (keyword #f "logical-block-callback")))) (jolt-invoke _a$474 _a$475 _a$476 _a$477 _a$478 _a$479 _a$480 _a$481 _a$482 _a$483 _a$484))) (_a$488 (jolt-dissoc G__32 (keyword #f "parent") (keyword #f "section") (keyword #f "start-col") (keyword #f "indent") (keyword #f "done-nl") (keyword #f "intra-block-nl") (keyword #f "prefix") (keyword #f "per-line-prefix") (keyword #f "suffix") (keyword #f "logical-block-callback")))) (jolt-invoke _a$485 _a$486 _a$487 _a$488))))))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "ancestor?" (letrec ((ancestor? (lambda (parent child) (let fnrec489 ((parent parent) (child child)) (let* ((child (jolt-get child (keyword #f "parent")))) (let loop490 ((child child)) (if (jolt-nil? child) #f (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "identical?") parent child)) #t (if (jolt-truthy? (keyword #f "else")) (loop490 (jolt-get child (keyword #f "parent"))) jolt-nil))))))))) ancestor?) (let* ((_o$491 (keyword #f "private")) (_o$492 #t)) (jolt-hash-map _o$491 _o$492)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "buffer-length" (letrec ((buffer-length (lambda (l) (let fnrec493 ((l l)) (let* ((l (jolt-seq l))) (if (jolt-truthy? l) (let* ((_a$494 (jolt-get (jolt-last l) (keyword #f "end-pos"))) (_a$495 (jolt-get (jolt-first l) (keyword #f "start-pos")))) (jolt-n- _a$494 _a$495)) 0)))))) buffer-length) (let* ((_o$496 (keyword #f "private")) (_o$497 #t)) (jolt-hash-map _o$496 _o$497)))) -(guard (e (#t #f)) - (begin (begin (begin (def-var! "clojure.pprint" "buffer-blob" (let* ((_a$513 (var-deref "clojure.core" "make-deftype-ctor")) (_a$514 (jolt-symbol #f "buffer-blob")) (_a$515 (let* ((_o$498 (keyword #f "type-tag")) (_o$499 (keyword #f "data")) (_o$500 (keyword #f "trailing-white-space")) (_o$501 (keyword #f "start-pos")) (_o$502 (keyword #f "end-pos"))) (jolt-vector _o$498 _o$499 _o$500 _o$501 _o$502))) (_a$516 (let* ((_o$503 jolt-nil) (_o$504 jolt-nil) (_o$505 jolt-nil) (_o$506 jolt-nil) (_o$507 jolt-nil)) (jolt-vector _o$503 _o$504 _o$505 _o$506 _o$507))) (_a$517 (let* ((_o$508 #f) (_o$509 #f) (_o$510 #f) (_o$511 #f) (_o$512 #f)) (jolt-vector _o$508 _o$509 _o$510 _o$511 _o$512)))) (jolt-invoke _a$513 _a$514 _a$515 _a$516 _a$517))) (def-var! "clojure.pprint" "->buffer-blob" (var-deref "clojure.pprint" "buffer-blob")) (var-deref "clojure.pprint" "buffer-blob")) (jolt-invoke (var-deref "clojure.core" "register-record-type!") (jolt-symbol #f "buffer-blob")) (def-var! "clojure.pprint" "map->buffer-blob" (lambda (G__33) (let fnrec518 ((G__33 G__33)) (let* ((_a$525 (var-deref "clojure.core" "reduce-kv")) (_a$526 jolt-assoc) (_a$527 (let* ((_a$519 (var-deref "clojure.pprint" "->buffer-blob")) (_a$520 (jolt-get G__33 (keyword #f "type-tag"))) (_a$521 (jolt-get G__33 (keyword #f "data"))) (_a$522 (jolt-get G__33 (keyword #f "trailing-white-space"))) (_a$523 (jolt-get G__33 (keyword #f "start-pos"))) (_a$524 (jolt-get G__33 (keyword #f "end-pos")))) (jolt-invoke _a$519 _a$520 _a$521 _a$522 _a$523 _a$524))) (_a$528 (jolt-dissoc G__33 (keyword #f "type-tag") (keyword #f "data") (keyword #f "trailing-white-space") (keyword #f "start-pos") (keyword #f "end-pos")))) (jolt-invoke _a$525 _a$526 _a$527 _a$528)))))) (def-var-with-meta! "clojure.pprint" "make-buffer-blob" (letrec ((make-buffer-blob (lambda (data trailing-white-space start-pos end-pos) (let fnrec529 ((data data) (trailing-white-space trailing-white-space) (start-pos start-pos) (end-pos end-pos)) (jolt-invoke (var-deref "clojure.pprint" "->buffer-blob") (keyword #f "buffer-blob") data trailing-white-space start-pos end-pos))))) make-buffer-blob) (let* ((_o$530 (keyword #f "private")) (_o$531 #t)) (jolt-hash-map _o$530 _o$531))) (def-var-with-meta! "clojure.pprint" "buffer-blob?" (letrec ((buffer-blob? (lambda (x__1__auto) (let fnrec532 ((x__1__auto x__1__auto)) (jolt= (jolt-get x__1__auto (keyword #f "type-tag")) (keyword #f "buffer-blob")))))) buffer-blob?) (let* ((_o$533 (keyword #f "private")) (_o$534 #t)) (jolt-hash-map _o$533 _o$534))))) -(guard (e (#t #f)) - (begin (begin (begin (def-var! "clojure.pprint" "nl-t" (let* ((_a$550 (var-deref "clojure.core" "make-deftype-ctor")) (_a$551 (jolt-symbol #f "nl-t")) (_a$552 (let* ((_o$535 (keyword #f "type-tag")) (_o$536 (keyword #f "type")) (_o$537 (keyword #f "logical-block")) (_o$538 (keyword #f "start-pos")) (_o$539 (keyword #f "end-pos"))) (jolt-vector _o$535 _o$536 _o$537 _o$538 _o$539))) (_a$553 (let* ((_o$540 jolt-nil) (_o$541 jolt-nil) (_o$542 jolt-nil) (_o$543 jolt-nil) (_o$544 jolt-nil)) (jolt-vector _o$540 _o$541 _o$542 _o$543 _o$544))) (_a$554 (let* ((_o$545 #f) (_o$546 #f) (_o$547 #f) (_o$548 #f) (_o$549 #f)) (jolt-vector _o$545 _o$546 _o$547 _o$548 _o$549)))) (jolt-invoke _a$550 _a$551 _a$552 _a$553 _a$554))) (def-var! "clojure.pprint" "->nl-t" (var-deref "clojure.pprint" "nl-t")) (var-deref "clojure.pprint" "nl-t")) (jolt-invoke (var-deref "clojure.core" "register-record-type!") (jolt-symbol #f "nl-t")) (def-var! "clojure.pprint" "map->nl-t" (lambda (G__34) (let fnrec555 ((G__34 G__34)) (let* ((_a$562 (var-deref "clojure.core" "reduce-kv")) (_a$563 jolt-assoc) (_a$564 (let* ((_a$556 (var-deref "clojure.pprint" "->nl-t")) (_a$557 (jolt-get G__34 (keyword #f "type-tag"))) (_a$558 (jolt-get G__34 (keyword #f "type"))) (_a$559 (jolt-get G__34 (keyword #f "logical-block"))) (_a$560 (jolt-get G__34 (keyword #f "start-pos"))) (_a$561 (jolt-get G__34 (keyword #f "end-pos")))) (jolt-invoke _a$556 _a$557 _a$558 _a$559 _a$560 _a$561))) (_a$565 (jolt-dissoc G__34 (keyword #f "type-tag") (keyword #f "type") (keyword #f "logical-block") (keyword #f "start-pos") (keyword #f "end-pos")))) (jolt-invoke _a$562 _a$563 _a$564 _a$565)))))) (def-var-with-meta! "clojure.pprint" "make-nl-t" (letrec ((make-nl-t (lambda (type logical-block start-pos end-pos) (let fnrec566 ((type type) (logical-block logical-block) (start-pos start-pos) (end-pos end-pos)) (jolt-invoke (var-deref "clojure.pprint" "->nl-t") (keyword #f "nl-t") type logical-block start-pos end-pos))))) make-nl-t) (let* ((_o$567 (keyword #f "private")) (_o$568 #t)) (jolt-hash-map _o$567 _o$568))) (def-var-with-meta! "clojure.pprint" "nl-t?" (letrec ((nl-t? (lambda (x__1__auto) (let fnrec569 ((x__1__auto x__1__auto)) (jolt= (jolt-get x__1__auto (keyword #f "type-tag")) (keyword #f "nl-t")))))) nl-t?) (let* ((_o$570 (keyword #f "private")) (_o$571 #t)) (jolt-hash-map _o$570 _o$571))))) -(guard (e (#t #f)) - (begin (begin (begin (def-var! "clojure.pprint" "start-block-t" (let* ((_a$584 (var-deref "clojure.core" "make-deftype-ctor")) (_a$585 (jolt-symbol #f "start-block-t")) (_a$586 (let* ((_o$572 (keyword #f "type-tag")) (_o$573 (keyword #f "logical-block")) (_o$574 (keyword #f "start-pos")) (_o$575 (keyword #f "end-pos"))) (jolt-vector _o$572 _o$573 _o$574 _o$575))) (_a$587 (let* ((_o$576 jolt-nil) (_o$577 jolt-nil) (_o$578 jolt-nil) (_o$579 jolt-nil)) (jolt-vector _o$576 _o$577 _o$578 _o$579))) (_a$588 (let* ((_o$580 #f) (_o$581 #f) (_o$582 #f) (_o$583 #f)) (jolt-vector _o$580 _o$581 _o$582 _o$583)))) (jolt-invoke _a$584 _a$585 _a$586 _a$587 _a$588))) (def-var! "clojure.pprint" "->start-block-t" (var-deref "clojure.pprint" "start-block-t")) (var-deref "clojure.pprint" "start-block-t")) (jolt-invoke (var-deref "clojure.core" "register-record-type!") (jolt-symbol #f "start-block-t")) (def-var! "clojure.pprint" "map->start-block-t" (lambda (G__35) (let fnrec589 ((G__35 G__35)) (let* ((_a$595 (var-deref "clojure.core" "reduce-kv")) (_a$596 jolt-assoc) (_a$597 (let* ((_a$590 (var-deref "clojure.pprint" "->start-block-t")) (_a$591 (jolt-get G__35 (keyword #f "type-tag"))) (_a$592 (jolt-get G__35 (keyword #f "logical-block"))) (_a$593 (jolt-get G__35 (keyword #f "start-pos"))) (_a$594 (jolt-get G__35 (keyword #f "end-pos")))) (jolt-invoke _a$590 _a$591 _a$592 _a$593 _a$594))) (_a$598 (jolt-dissoc G__35 (keyword #f "type-tag") (keyword #f "logical-block") (keyword #f "start-pos") (keyword #f "end-pos")))) (jolt-invoke _a$595 _a$596 _a$597 _a$598)))))) (def-var-with-meta! "clojure.pprint" "make-start-block-t" (letrec ((make-start-block-t (lambda (logical-block start-pos end-pos) (let fnrec599 ((logical-block logical-block) (start-pos start-pos) (end-pos end-pos)) (jolt-invoke (var-deref "clojure.pprint" "->start-block-t") (keyword #f "start-block-t") logical-block start-pos end-pos))))) make-start-block-t) (let* ((_o$600 (keyword #f "private")) (_o$601 #t)) (jolt-hash-map _o$600 _o$601))) (def-var-with-meta! "clojure.pprint" "start-block-t?" (letrec ((start-block-t? (lambda (x__1__auto) (let fnrec602 ((x__1__auto x__1__auto)) (jolt= (jolt-get x__1__auto (keyword #f "type-tag")) (keyword #f "start-block-t")))))) start-block-t?) (let* ((_o$603 (keyword #f "private")) (_o$604 #t)) (jolt-hash-map _o$603 _o$604))))) -(guard (e (#t #f)) - (begin (begin (begin (def-var! "clojure.pprint" "end-block-t" (let* ((_a$617 (var-deref "clojure.core" "make-deftype-ctor")) (_a$618 (jolt-symbol #f "end-block-t")) (_a$619 (let* ((_o$605 (keyword #f "type-tag")) (_o$606 (keyword #f "logical-block")) (_o$607 (keyword #f "start-pos")) (_o$608 (keyword #f "end-pos"))) (jolt-vector _o$605 _o$606 _o$607 _o$608))) (_a$620 (let* ((_o$609 jolt-nil) (_o$610 jolt-nil) (_o$611 jolt-nil) (_o$612 jolt-nil)) (jolt-vector _o$609 _o$610 _o$611 _o$612))) (_a$621 (let* ((_o$613 #f) (_o$614 #f) (_o$615 #f) (_o$616 #f)) (jolt-vector _o$613 _o$614 _o$615 _o$616)))) (jolt-invoke _a$617 _a$618 _a$619 _a$620 _a$621))) (def-var! "clojure.pprint" "->end-block-t" (var-deref "clojure.pprint" "end-block-t")) (var-deref "clojure.pprint" "end-block-t")) (jolt-invoke (var-deref "clojure.core" "register-record-type!") (jolt-symbol #f "end-block-t")) (def-var! "clojure.pprint" "map->end-block-t" (lambda (G__36) (let fnrec622 ((G__36 G__36)) (let* ((_a$628 (var-deref "clojure.core" "reduce-kv")) (_a$629 jolt-assoc) (_a$630 (let* ((_a$623 (var-deref "clojure.pprint" "->end-block-t")) (_a$624 (jolt-get G__36 (keyword #f "type-tag"))) (_a$625 (jolt-get G__36 (keyword #f "logical-block"))) (_a$626 (jolt-get G__36 (keyword #f "start-pos"))) (_a$627 (jolt-get G__36 (keyword #f "end-pos")))) (jolt-invoke _a$623 _a$624 _a$625 _a$626 _a$627))) (_a$631 (jolt-dissoc G__36 (keyword #f "type-tag") (keyword #f "logical-block") (keyword #f "start-pos") (keyword #f "end-pos")))) (jolt-invoke _a$628 _a$629 _a$630 _a$631)))))) (def-var-with-meta! "clojure.pprint" "make-end-block-t" (letrec ((make-end-block-t (lambda (logical-block start-pos end-pos) (let fnrec632 ((logical-block logical-block) (start-pos start-pos) (end-pos end-pos)) (jolt-invoke (var-deref "clojure.pprint" "->end-block-t") (keyword #f "end-block-t") logical-block start-pos end-pos))))) make-end-block-t) (let* ((_o$633 (keyword #f "private")) (_o$634 #t)) (jolt-hash-map _o$633 _o$634))) (def-var-with-meta! "clojure.pprint" "end-block-t?" (letrec ((end-block-t? (lambda (x__1__auto) (let fnrec635 ((x__1__auto x__1__auto)) (jolt= (jolt-get x__1__auto (keyword #f "type-tag")) (keyword #f "end-block-t")))))) end-block-t?) (let* ((_o$636 (keyword #f "private")) (_o$637 #t)) (jolt-hash-map _o$636 _o$637))))) -(guard (e (#t #f)) - (begin (begin (begin (def-var! "clojure.pprint" "indent-t" (let* ((_a$656 (var-deref "clojure.core" "make-deftype-ctor")) (_a$657 (jolt-symbol #f "indent-t")) (_a$658 (let* ((_o$638 (keyword #f "type-tag")) (_o$639 (keyword #f "logical-block")) (_o$640 (keyword #f "relative-to")) (_o$641 (keyword #f "offset")) (_o$642 (keyword #f "start-pos")) (_o$643 (keyword #f "end-pos"))) (jolt-vector _o$638 _o$639 _o$640 _o$641 _o$642 _o$643))) (_a$659 (let* ((_o$644 jolt-nil) (_o$645 jolt-nil) (_o$646 jolt-nil) (_o$647 jolt-nil) (_o$648 jolt-nil) (_o$649 jolt-nil)) (jolt-vector _o$644 _o$645 _o$646 _o$647 _o$648 _o$649))) (_a$660 (let* ((_o$650 #f) (_o$651 #f) (_o$652 #f) (_o$653 #f) (_o$654 #f) (_o$655 #f)) (jolt-vector _o$650 _o$651 _o$652 _o$653 _o$654 _o$655)))) (jolt-invoke _a$656 _a$657 _a$658 _a$659 _a$660))) (def-var! "clojure.pprint" "->indent-t" (var-deref "clojure.pprint" "indent-t")) (var-deref "clojure.pprint" "indent-t")) (jolt-invoke (var-deref "clojure.core" "register-record-type!") (jolt-symbol #f "indent-t")) (def-var! "clojure.pprint" "map->indent-t" (lambda (G__37) (let fnrec661 ((G__37 G__37)) (let* ((_a$669 (var-deref "clojure.core" "reduce-kv")) (_a$670 jolt-assoc) (_a$671 (let* ((_a$662 (var-deref "clojure.pprint" "->indent-t")) (_a$663 (jolt-get G__37 (keyword #f "type-tag"))) (_a$664 (jolt-get G__37 (keyword #f "logical-block"))) (_a$665 (jolt-get G__37 (keyword #f "relative-to"))) (_a$666 (jolt-get G__37 (keyword #f "offset"))) (_a$667 (jolt-get G__37 (keyword #f "start-pos"))) (_a$668 (jolt-get G__37 (keyword #f "end-pos")))) (jolt-invoke _a$662 _a$663 _a$664 _a$665 _a$666 _a$667 _a$668))) (_a$672 (jolt-dissoc G__37 (keyword #f "type-tag") (keyword #f "logical-block") (keyword #f "relative-to") (keyword #f "offset") (keyword #f "start-pos") (keyword #f "end-pos")))) (jolt-invoke _a$669 _a$670 _a$671 _a$672)))))) (def-var-with-meta! "clojure.pprint" "make-indent-t" (letrec ((make-indent-t (lambda (logical-block relative-to offset start-pos end-pos) (let fnrec673 ((logical-block logical-block) (relative-to relative-to) (offset offset) (start-pos start-pos) (end-pos end-pos)) (jolt-invoke (var-deref "clojure.pprint" "->indent-t") (keyword #f "indent-t") logical-block relative-to offset start-pos end-pos))))) make-indent-t) (let* ((_o$674 (keyword #f "private")) (_o$675 #t)) (jolt-hash-map _o$674 _o$675))) (def-var-with-meta! "clojure.pprint" "indent-t?" (letrec ((indent-t? (lambda (x__1__auto) (let fnrec676 ((x__1__auto x__1__auto)) (jolt= (jolt-get x__1__auto (keyword #f "type-tag")) (keyword #f "indent-t")))))) indent-t?) (let* ((_o$677 (keyword #f "private")) (_o$678 #t)) (jolt-hash-map _o$677 _o$678))))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "pp-newline" (lambda () (let fnrec679 () "\n")) (let* ((_o$680 (keyword #f "private")) (_o$681 #t)) (jolt-hash-map _o$680 _o$681)))) -(guard (e (#t #f)) - (declare-var! "clojure.pprint" "emit-nl")) -(guard (e (#t #f)) - (jolt-invoke (var-deref "clojure.core" "defmulti-setup") (jolt-symbol "clojure.pprint" "write-token") (lambda (this token) (let fnrec682 ((this this) (token token)) (jolt-get token (keyword #f "type-tag")))))) -(guard (e (#t #f)) - (jolt-invoke (var-deref "clojure.core" "defmethod-setup") (jolt-symbol #f "write-token") (keyword #f "start-block-t") (lambda (this token) (let fnrec683 ((this this) (token token)) (begin (let* ((temp__27__auto (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch this "-fields" (jolt-vector))) (keyword #f "logical-block-callback")))) (if (jolt-truthy? temp__27__auto) (let* ((cb temp__27__auto)) (jolt-invoke cb (keyword #f "start"))) jolt-nil)) (let* ((lb (jolt-get token (keyword #f "logical-block")))) (begin (let* ((temp__27__auto (jolt-get lb (keyword #f "prefix")))) (if (jolt-truthy? temp__27__auto) (let* ((prefix temp__27__auto)) (jolt-invoke (var-deref "clojure.pprint" "-write") (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch this "-fields" (jolt-vector))) (keyword #f "base")) prefix)) jolt-nil)) (let* ((col (jolt-invoke (var-deref "clojure.pprint" "get-column") (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch this "-fields" (jolt-vector))) (keyword #f "base"))))) (begin (jolt-invoke (var-deref "clojure.core" "reset!") (jolt-get lb (keyword #f "start-col")) col) (jolt-invoke (var-deref "clojure.core" "reset!") (jolt-get lb (keyword #f "indent")) col)))))))) "clojure.pprint")) -(guard (e (#t #f)) - (jolt-invoke (var-deref "clojure.core" "defmethod-setup") (jolt-symbol #f "write-token") (keyword #f "end-block-t") (lambda (this token) (let fnrec684 ((this this) (token token)) (begin (let* ((temp__27__auto (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch this "-fields" (jolt-vector))) (keyword #f "logical-block-callback")))) (if (jolt-truthy? temp__27__auto) (let* ((cb temp__27__auto)) (jolt-invoke cb (keyword #f "end"))) jolt-nil)) (let* ((temp__27__auto (jolt-get (jolt-get token (keyword #f "logical-block")) (keyword #f "suffix")))) (if (jolt-truthy? temp__27__auto) (let* ((suffix temp__27__auto)) (jolt-invoke (var-deref "clojure.pprint" "-write") (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch this "-fields" (jolt-vector))) (keyword #f "base")) suffix)) jolt-nil))))) "clojure.pprint")) -(guard (e (#t #f)) - (jolt-invoke (var-deref "clojure.core" "defmethod-setup") (jolt-symbol #f "write-token") (keyword #f "indent-t") (lambda (this token) (let fnrec685 ((this this) (token token)) (let* ((lb (jolt-get token (keyword #f "logical-block")))) (let* ((_a$690 (var-deref "clojure.core" "reset!")) (_a$691 (jolt-get lb (keyword #f "indent"))) (_a$692 (let* ((_a$688 (jolt-get token (keyword #f "offset"))) (_a$689 (let* ((G__38 jolt=) (G__39 (jolt-get token (keyword #f "relative-to")))) (if (jolt-truthy? (jolt-invoke G__38 (keyword #f "block") G__39)) (jolt-invoke (var-deref "clojure.core" "deref") (jolt-get lb (keyword #f "start-col"))) (if (jolt-truthy? (jolt-invoke G__38 (keyword #f "current") G__39)) (jolt-invoke (var-deref "clojure.pprint" "get-column") (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch this "-fields" (jolt-vector))) (keyword #f "base"))) (jolt-throw (let* ((_a$686 (jolt-invoke (var-deref "clojure.core" "str") "No matching clause: " G__39)) (_a$687 (jolt-hash-map))) (jolt-ex-info _a$686 _a$687)))))))) (jolt-n+ _a$688 _a$689)))) (jolt-invoke _a$690 _a$691 _a$692))))) "clojure.pprint")) -(guard (e (#t #f)) - (jolt-invoke (var-deref "clojure.core" "defmethod-setup") (jolt-symbol #f "write-token") (keyword #f "buffer-blob") (lambda (this token) (let fnrec693 ((this this) (token token)) (let* ((_a$694 (var-deref "clojure.pprint" "-write")) (_a$695 (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch this "-fields" (jolt-vector))) (keyword #f "base"))) (_a$696 (jolt-get token (keyword #f "data")))) (jolt-invoke _a$694 _a$695 _a$696)))) "clojure.pprint")) -(guard (e (#t #f)) - (jolt-invoke (var-deref "clojure.core" "defmethod-setup") (jolt-symbol #f "write-token") (keyword #f "nl-t") (lambda (this token) (let fnrec697 ((this this) (token token)) (begin (if (jolt-truthy? (let* ((or__26__auto (jolt= (jolt-get token (keyword #f "type")) (keyword #f "mandatory")))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((and__25__auto (jolt-not (jolt= (jolt-get token (keyword #f "type")) (keyword #f "fill"))))) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "clojure.core" "deref") (jolt-get (jolt-get token (keyword #f "logical-block")) (keyword #f "done-nl"))) and__25__auto))))) (jolt-invoke (var-deref "clojure.pprint" "emit-nl") this token) (let* ((temp__16__auto (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch this "-fields" (jolt-vector))) (keyword #f "trailing-white-space")))) (if (jolt-truthy? temp__16__auto) (let* ((tws temp__16__auto)) (jolt-invoke (var-deref "clojure.pprint" "-write") (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch this "-fields" (jolt-vector))) (keyword #f "base")) tws)) jolt-nil))) (jolt-invoke (var-deref "clojure.core" "swap!") (record-method-dispatch this "-fields" (jolt-vector)) jolt-assoc (keyword #f "trailing-white-space") jolt-nil)))) "clojure.pprint")) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "write-tokens" (letrec ((write-tokens (lambda (this tokens force-trailing-whitespace) (let fnrec698 ((this this) (tokens tokens) (force-trailing-whitespace force-trailing-whitespace)) (begin (jolt-count (jolt-map (lambda (token) (let fnrec699 ((token token)) (begin (if (jolt-not (jolt= (jolt-get token (keyword #f "type-tag")) (keyword #f "nl-t"))) (let* ((temp__16__auto (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch this "-fields" (jolt-vector))) (keyword #f "trailing-white-space")))) (if (jolt-truthy? temp__16__auto) (let* ((tws temp__16__auto)) (jolt-invoke (var-deref "clojure.pprint" "-write") (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch this "-fields" (jolt-vector))) (keyword #f "base")) tws)) jolt-nil)) jolt-nil) (jolt-invoke (var-deref "clojure.pprint" "write-token") this token) (let* ((_a$700 (var-deref "clojure.core" "swap!")) (_a$701 (record-method-dispatch this "-fields" (jolt-vector))) (_a$702 jolt-assoc) (_a$703 (keyword #f "trailing-white-space")) (_a$704 (jolt-get token (keyword #f "trailing-white-space")))) (jolt-invoke _a$700 _a$701 _a$702 _a$703 _a$704)) (let* ((tws (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch this "-fields" (jolt-vector))) (keyword #f "trailing-white-space")))) (if (jolt-truthy? (let* ((and__25__auto force-trailing-whitespace)) (if (jolt-truthy? and__25__auto) tws and__25__auto))) (begin (jolt-invoke (var-deref "clojure.pprint" "-write") (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch this "-fields" (jolt-vector))) (keyword #f "base")) tws) (jolt-invoke (var-deref "clojure.core" "swap!") (record-method-dispatch this "-fields" (jolt-vector)) jolt-assoc (keyword #f "trailing-white-space") jolt-nil)) jolt-nil)) jolt-nil))) tokens)) jolt-nil))))) write-tokens) (let* ((_o$705 (keyword #f "private")) (_o$706 #t)) (jolt-hash-map _o$705 _o$706)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "tokens-fit?" (letrec ((tokens-fit? (lambda (this tokens) (let fnrec707 ((this this) (tokens tokens)) (let* ((maxcol (jolt-invoke (var-deref "clojure.pprint" "get-max-column") (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch this "-fields" (jolt-vector))) (keyword #f "base"))))) (let* ((or__26__auto (jolt-nil? maxcol))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-n< (let* ((_a$708 (jolt-invoke (var-deref "clojure.pprint" "get-column") (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch this "-fields" (jolt-vector))) (keyword #f "base")))) (_a$709 (jolt-invoke (var-deref "clojure.pprint" "buffer-length") tokens))) (jolt-n+ _a$708 _a$709)) maxcol)))))))) tokens-fit?) (let* ((_o$710 (keyword #f "private")) (_o$711 #t)) (jolt-hash-map _o$710 _o$711)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "linear-nl?" (letrec ((linear-nl? (lambda (this lb section) (let fnrec712 ((this this) (lb lb) (section section)) (let* ((or__26__auto (jolt-invoke (var-deref "clojure.core" "deref") (jolt-get lb (keyword #f "done-nl"))))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-not (jolt-invoke (var-deref "clojure.pprint" "tokens-fit?") this section)))))))) linear-nl?) (let* ((_o$713 (keyword #f "private")) (_o$714 #t)) (jolt-hash-map _o$713 _o$714)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "miser-nl?" (letrec ((miser-nl? (lambda (this lb section) (let fnrec715 ((this this) (lb lb) (section section)) (let* ((miser-width (jolt-invoke (var-deref "clojure.pprint" "get-miser-width") this)) (maxcol (jolt-invoke (var-deref "clojure.pprint" "get-max-column") (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch this "-fields" (jolt-vector))) (keyword #f "base"))))) (let* ((and__25__auto miser-width)) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto maxcol)) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (let* ((_a$716 (jolt-invoke (var-deref "clojure.core" "deref") (jolt-get lb (keyword #f "start-col")))) (_a$717 (jolt-n- maxcol miser-width))) (jolt-n>= _a$716 _a$717)))) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "clojure.pprint" "linear-nl?") this lb section) and__25__auto)) and__25__auto)) and__25__auto))))))) miser-nl?) (let* ((_o$718 (keyword #f "private")) (_o$719 #t)) (jolt-hash-map _o$718 _o$719)))) -(guard (e (#t #f)) - (jolt-invoke (var-deref "clojure.core" "defmulti-setup") (jolt-symbol "clojure.pprint" "emit-nl?") (lambda (t _r$__119 _r$__120 _) (let fnrec720 ((t t) (_r$__119 _r$__119) (_r$__120 _r$__120) (_ _)) (jolt-get t (keyword #f "type")))))) -(guard (e (#t #f)) - (jolt-invoke (var-deref "clojure.core" "defmethod-setup") (jolt-symbol #f "emit-nl?") (keyword #f "linear") (lambda (newl this section _) (let fnrec721 ((newl newl) (this this) (section section) (_ _)) (let* ((lb (jolt-get newl (keyword #f "logical-block")))) (jolt-invoke (var-deref "clojure.pprint" "linear-nl?") this lb section)))) "clojure.pprint")) -(guard (e (#t #f)) - (jolt-invoke (var-deref "clojure.core" "defmethod-setup") (jolt-symbol #f "emit-nl?") (keyword #f "miser") (lambda (newl this section _) (let fnrec722 ((newl newl) (this this) (section section) (_ _)) (let* ((lb (jolt-get newl (keyword #f "logical-block")))) (jolt-invoke (var-deref "clojure.pprint" "miser-nl?") this lb section)))) "clojure.pprint")) -(guard (e (#t #f)) - (jolt-invoke (var-deref "clojure.core" "defmethod-setup") (jolt-symbol #f "emit-nl?") (keyword #f "fill") (lambda (newl this section subsection) (let fnrec723 ((newl newl) (this this) (section section) (subsection subsection)) (let* ((lb (jolt-get newl (keyword #f "logical-block")))) (let* ((or__26__auto (jolt-invoke (var-deref "clojure.core" "deref") (jolt-get lb (keyword #f "intra-block-nl"))))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt-not (jolt-invoke (var-deref "clojure.pprint" "tokens-fit?") this subsection)))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-invoke (var-deref "clojure.pprint" "miser-nl?") this lb section)))))))) "clojure.pprint")) -(guard (e (#t #f)) - (jolt-invoke (var-deref "clojure.core" "defmethod-setup") (jolt-symbol #f "emit-nl?") (keyword #f "mandatory") (lambda (_r$__125 _r$__126 _r$__127 _) (let fnrec724 ((_r$__125 _r$__125) (_r$__126 _r$__126) (_r$__127 _r$__127) (_ _)) #t)) "clojure.pprint")) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "get-section" (letrec ((get-section (lambda (buffer) (let fnrec725 ((buffer buffer)) (let* ((nl (jolt-first buffer)) (lb (jolt-get nl (keyword #f "logical-block"))) (section (jolt-seq (let* ((_a$727 (var-deref "clojure.core" "take-while")) (_a$728 (lambda (p__5_) (let fnrec726 ((p__5_ p__5_)) (jolt-not (let* ((and__25__auto (jolt-invoke (var-deref "clojure.pprint" "nl-t?") p__5_))) (if (jolt-truthy? and__25__auto) (jolt-invoke (var-deref "clojure.pprint" "ancestor?") (jolt-get p__5_ (keyword #f "logical-block")) lb) and__25__auto)))))) (_a$729 (jolt-next buffer))) (jolt-invoke _a$727 _a$728 _a$729))))) (let* ((_o$730 section) (_o$731 (jolt-seq (jolt-drop (jolt-inc (jolt-count section)) buffer)))) (jolt-vector _o$730 _o$731))))))) get-section) (let* ((_o$732 (keyword #f "private")) (_o$733 #t)) (jolt-hash-map _o$732 _o$733)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "get-sub-section" (letrec ((get-sub-section (lambda (buffer) (let fnrec734 ((buffer buffer)) (let* ((nl (jolt-first buffer)) (lb (jolt-get nl (keyword #f "logical-block"))) (section (jolt-seq (let* ((_a$736 (var-deref "clojure.core" "take-while")) (_a$737 (lambda (p__6_) (let fnrec735 ((p__6_ p__6_)) (let* ((nl-lb (jolt-get p__6_ (keyword #f "logical-block")))) (jolt-not (let* ((and__25__auto (jolt-invoke (var-deref "clojure.pprint" "nl-t?") p__6_))) (if (jolt-truthy? and__25__auto) (let* ((or__26__auto (jolt= nl-lb lb))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-invoke (var-deref "clojure.pprint" "ancestor?") nl-lb lb))) and__25__auto))))))) (_a$738 (jolt-next buffer))) (jolt-invoke _a$736 _a$737 _a$738))))) section))))) get-sub-section) (let* ((_o$739 (keyword #f "private")) (_o$740 #t)) (jolt-hash-map _o$739 _o$740)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "update-nl-state" (letrec ((update-nl-state (lambda (lb) (let fnrec741 ((lb lb)) (begin (jolt-invoke (var-deref "clojure.core" "reset!") (jolt-get lb (keyword #f "intra-block-nl")) #t) (jolt-invoke (var-deref "clojure.core" "reset!") (jolt-get lb (keyword #f "done-nl")) #t) (let* ((lb (jolt-get lb (keyword #f "parent")))) (let loop742 ((lb lb)) (if (jolt-truthy? lb) (begin (jolt-invoke (var-deref "clojure.core" "reset!") (jolt-get lb (keyword #f "done-nl")) #t) (jolt-invoke (var-deref "clojure.core" "reset!") (jolt-get lb (keyword #f "intra-block-nl")) #t) (loop742 (jolt-get lb (keyword #f "parent")))) jolt-nil)))))))) update-nl-state) (let* ((_o$743 (keyword #f "private")) (_o$744 #t)) (jolt-hash-map _o$743 _o$744)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "emit-nl" (letrec ((emit-nl (lambda (this nl) (let fnrec745 ((this this) (nl nl)) (begin (let* ((_a$746 (var-deref "clojure.pprint" "-write")) (_a$747 (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch this "-fields" (jolt-vector))) (keyword #f "base"))) (_a$748 (jolt-invoke (var-deref "clojure.pprint" "pp-newline")))) (jolt-invoke _a$746 _a$747 _a$748)) (jolt-invoke (var-deref "clojure.core" "swap!") (record-method-dispatch this "-fields" (jolt-vector)) jolt-assoc (keyword #f "trailing-white-space") jolt-nil) (let* ((lb (jolt-get nl (keyword #f "logical-block"))) (prefix (jolt-get lb (keyword #f "per-line-prefix")))) (begin (if (jolt-truthy? prefix) (jolt-invoke (var-deref "clojure.pprint" "-write") (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch this "-fields" (jolt-vector))) (keyword #f "base")) prefix) jolt-nil) (let* ((istr (jolt-apply (var-deref "clojure.core" "str") (jolt-invoke (var-deref "clojure.core" "repeat") (let* ((_a$749 (jolt-invoke (var-deref "clojure.core" "deref") (jolt-get lb (keyword #f "indent")))) (_a$750 (jolt-count prefix))) (jolt-n- _a$749 _a$750)) (integer->char 32))))) (jolt-invoke (var-deref "clojure.pprint" "-write") (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch this "-fields" (jolt-vector))) (keyword #f "base")) istr)) (jolt-invoke (var-deref "clojure.pprint" "update-nl-state") lb)))))))) emit-nl) (let* ((_o$751 (keyword #f "private")) (_o$752 #t)) (jolt-hash-map _o$751 _o$752)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "split-at-newline" (letrec ((split-at-newline (lambda (tokens) (let fnrec753 ((tokens tokens)) (let* ((pre (jolt-seq (jolt-invoke (var-deref "clojure.core" "take-while") (lambda (p__7_) (let fnrec754 ((p__7_ p__7_)) (jolt-not (jolt-invoke (var-deref "clojure.pprint" "nl-t?") p__7_)))) tokens)))) (let* ((_o$755 pre) (_o$756 (jolt-seq (jolt-drop (jolt-count pre) tokens)))) (jolt-vector _o$755 _o$756))))))) split-at-newline) (let* ((_o$757 (keyword #f "private")) (_o$758 #t)) (jolt-hash-map _o$757 _o$758)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "write-token-string" (letrec ((write-token-string (lambda (this tokens) (let fnrec759 ((this this) (tokens tokens)) (let* ((G__40 (jolt-invoke (var-deref "clojure.pprint" "split-at-newline") tokens)) (a (jolt-nth G__40 0 jolt-nil)) (b (jolt-nth G__40 1 jolt-nil))) (begin (if (jolt-truthy? a) (jolt-invoke (var-deref "clojure.pprint" "write-tokens") this a #f) jolt-nil) (if (jolt-truthy? b) (let* ((G__41 (jolt-invoke (var-deref "clojure.pprint" "get-section") b)) (section (jolt-nth G__41 0 jolt-nil)) (remainder (jolt-nth G__41 1 jolt-nil)) (newl (jolt-first b))) (let* ((do-nl (jolt-invoke (var-deref "clojure.pprint" "emit-nl?") newl this section (jolt-invoke (var-deref "clojure.pprint" "get-sub-section") b))) (result (if (jolt-truthy? do-nl) (begin (jolt-invoke (var-deref "clojure.pprint" "emit-nl") this newl) (jolt-next b)) b)) (long-section (jolt-not (jolt-invoke (var-deref "clojure.pprint" "tokens-fit?") this result))) (result (if (jolt-truthy? long-section) (let* ((rem2 (write-token-string this section))) (if (jolt= rem2 section) (begin (jolt-invoke (var-deref "clojure.pprint" "write-tokens") this section #f) remainder) (let* ((_a$760 (jolt-vector)) (_a$761 (jolt-concat rem2 remainder))) (jolt-into _a$760 _a$761)))) result))) result)) jolt-nil))))))) write-token-string) (let* ((_o$762 (keyword #f "private")) (_o$763 #t)) (jolt-hash-map _o$762 _o$763)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "write-line" (letrec ((write-line (lambda (this) (let fnrec764 ((this this)) (let* ((buffer (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch this "-fields" (jolt-vector))) (keyword #f "buffer")))) (let loop765 ((buffer buffer)) (begin (let* ((_a$766 (var-deref "clojure.core" "swap!")) (_a$767 (record-method-dispatch this "-fields" (jolt-vector))) (_a$768 jolt-assoc) (_a$769 (keyword #f "buffer")) (_a$770 (jolt-into (jolt-vector) buffer))) (jolt-invoke _a$766 _a$767 _a$768 _a$769 _a$770)) (if (jolt-not (jolt-invoke (var-deref "clojure.pprint" "tokens-fit?") this buffer)) (let* ((new-buffer (jolt-invoke (var-deref "clojure.pprint" "write-token-string") this buffer))) (if (jolt-not (jolt-invoke (var-deref "clojure.core" "identical?") buffer new-buffer)) (loop765 new-buffer) jolt-nil)) jolt-nil)))))))) write-line) (let* ((_o$771 (keyword #f "private")) (_o$772 #t)) (jolt-hash-map _o$771 _o$772)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "add-to-buffer" (letrec ((add-to-buffer (lambda (this token) (let fnrec773 ((this this) (token token)) (begin (let* ((_a$774 (var-deref "clojure.core" "swap!")) (_a$775 (record-method-dispatch this "-fields" (jolt-vector))) (_a$776 jolt-assoc) (_a$777 (keyword #f "buffer")) (_a$778 (jolt-conj (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch this "-fields" (jolt-vector))) (keyword #f "buffer")) token))) (jolt-invoke _a$774 _a$775 _a$776 _a$777 _a$778)) (if (jolt-not (jolt-invoke (var-deref "clojure.pprint" "tokens-fit?") this (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch this "-fields" (jolt-vector))) (keyword #f "buffer")))) (jolt-invoke (var-deref "clojure.pprint" "write-line") this) jolt-nil)))))) add-to-buffer) (let* ((_o$779 (keyword #f "private")) (_o$780 #t)) (jolt-hash-map _o$779 _o$780)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "write-buffered-output" (letrec ((write-buffered-output (lambda (this) (let fnrec781 ((this this)) (begin (jolt-invoke (var-deref "clojure.pprint" "write-line") this) (let* ((temp__16__auto (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch this "-fields" (jolt-vector))) (keyword #f "buffer")))) (if (jolt-truthy? temp__16__auto) (let* ((buf temp__16__auto)) (begin (jolt-invoke (var-deref "clojure.pprint" "write-tokens") this buf #t) (let* ((_a$782 (var-deref "clojure.core" "swap!")) (_a$783 (record-method-dispatch this "-fields" (jolt-vector))) (_a$784 jolt-assoc) (_a$785 (keyword #f "buffer")) (_a$786 (jolt-vector))) (jolt-invoke _a$782 _a$783 _a$784 _a$785 _a$786)))) jolt-nil))))))) write-buffered-output) (let* ((_o$787 (keyword #f "private")) (_o$788 #t)) (jolt-hash-map _o$787 _o$788)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "write-white-space" (letrec ((write-white-space (lambda (this) (let fnrec789 ((this this)) (let* ((temp__27__auto (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch this "-fields" (jolt-vector))) (keyword #f "trailing-white-space")))) (if (jolt-truthy? temp__27__auto) (let* ((tws temp__27__auto)) (begin (jolt-invoke (var-deref "clojure.pprint" "-write") (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch this "-fields" (jolt-vector))) (keyword #f "base")) tws) (jolt-invoke (var-deref "clojure.core" "swap!") (record-method-dispatch this "-fields" (jolt-vector)) jolt-assoc (keyword #f "trailing-white-space") jolt-nil))) jolt-nil)))))) write-white-space) (let* ((_o$790 (keyword #f "private")) (_o$791 #t)) (jolt-hash-map _o$790 _o$791)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "write-initial-lines" (letrec ((write-initial-lines (lambda (this s) (let fnrec792 ((this this) (s s)) (let* ((lines (jolt-invoke (var-deref "clojure.string" "split") s (jolt-regex "\\n") -1))) (if (jolt= (jolt-count lines) 1) s (let* ((prefix (jolt-get (jolt-first (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch this "-fields" (jolt-vector))) (keyword #f "logical-blocks"))) (keyword #f "per-line-prefix"))) (l (jolt-first lines))) (begin (if (jolt= (keyword #f "buffering") (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch this "-fields" (jolt-vector))) (keyword #f "mode"))) (let* ((oldpos (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch this "-fields" (jolt-vector))) (keyword #f "pos"))) (newpos (jolt-n+ oldpos (jolt-count l)))) (begin (jolt-invoke (var-deref "clojure.core" "swap!") (record-method-dispatch this "-fields" (jolt-vector)) jolt-assoc (keyword #f "pos") newpos) (jolt-invoke (var-deref "clojure.pprint" "add-to-buffer") this (jolt-invoke (var-deref "clojure.pprint" "make-buffer-blob") l jolt-nil oldpos newpos)) (jolt-invoke (var-deref "clojure.pprint" "write-buffered-output") this))) (begin (jolt-invoke (var-deref "clojure.pprint" "write-white-space") this) (jolt-invoke (var-deref "clojure.pprint" "-write") (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch this "-fields" (jolt-vector))) (keyword #f "base")) l))) (jolt-invoke (var-deref "clojure.pprint" "-write") (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch this "-fields" (jolt-vector))) (keyword #f "base")) "\n") (begin (jolt-count (let* ((_a$797 (lambda (l) (let fnrec793 ((l l)) (begin (jolt-invoke (var-deref "clojure.pprint" "-write") (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch this "-fields" (jolt-vector))) (keyword #f "base")) l) (let* ((_a$794 (var-deref "clojure.pprint" "-write")) (_a$795 (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch this "-fields" (jolt-vector))) (keyword #f "base"))) (_a$796 (jolt-invoke (var-deref "clojure.pprint" "pp-newline")))) (jolt-invoke _a$794 _a$795 _a$796)) (if (jolt-truthy? prefix) (jolt-invoke (var-deref "clojure.pprint" "-write") (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch this "-fields" (jolt-vector))) (keyword #f "base")) prefix) jolt-nil) jolt-nil)))) (_a$798 (jolt-next (jolt-invoke (var-deref "clojure.core" "butlast") lines)))) (jolt-map _a$797 _a$798))) jolt-nil) (jolt-invoke (var-deref "clojure.core" "swap!") (record-method-dispatch this "-fields" (jolt-vector)) jolt-assoc (keyword #f "buffering") (keyword #f "writing")) (jolt-last lines))))))))) write-initial-lines) (let* ((_o$799 (keyword #f "private")) (_o$800 #t)) (jolt-hash-map _o$799 _o$800)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "p-write-char" (letrec ((p-write-char (lambda (this c) (let fnrec801 ((this this) (c c)) (if (jolt= (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch this "-fields" (jolt-vector))) (keyword #f "mode")) (keyword #f "writing")) (begin (jolt-invoke (var-deref "clojure.pprint" "write-white-space") this) (jolt-invoke (var-deref "clojure.pprint" "-write") (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch this "-fields" (jolt-vector))) (keyword #f "base")) c)) (if (jolt= c (integer->char 10)) (jolt-invoke (var-deref "clojure.pprint" "write-initial-lines") this "\n") (let* ((oldpos (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch this "-fields" (jolt-vector))) (keyword #f "pos"))) (newpos (jolt-inc oldpos))) (begin (jolt-invoke (var-deref "clojure.core" "swap!") (record-method-dispatch this "-fields" (jolt-vector)) jolt-assoc (keyword #f "pos") newpos) (jolt-invoke (var-deref "clojure.pprint" "add-to-buffer") this (jolt-invoke (var-deref "clojure.pprint" "make-buffer-blob") (jolt-invoke (var-deref "clojure.core" "str") c) jolt-nil oldpos newpos)))))))))) p-write-char) (let* ((_o$802 (keyword #f "private")) (_o$803 #t)) (jolt-hash-map _o$802 _o$803)))) -(guard (e (#t #f)) - (begin (begin (def-var! "clojure.pprint" "PrettyWriter" (let* ((_a$804 (var-deref "clojure.core" "make-deftype-ctor")) (_a$805 (jolt-symbol #f "PrettyWriter")) (_a$806 (jolt-vector (keyword #f "fields"))) (_a$807 (jolt-vector jolt-nil)) (_a$808 (jolt-vector #f))) (jolt-invoke _a$804 _a$805 _a$806 _a$807 _a$808))) (def-var! "clojure.pprint" "->PrettyWriter" (var-deref "clojure.pprint" "PrettyWriter")) (var-deref "clojure.pprint" "PrettyWriter")) (jolt-invoke (var-deref "clojure.core" "register-record-type!") (jolt-symbol #f "PrettyWriter")) (def-var! "clojure.pprint" "map->PrettyWriter" (lambda (G__42) (let fnrec809 ((G__42 G__42)) (let* ((_a$810 (var-deref "clojure.core" "reduce-kv")) (_a$811 jolt-assoc) (_a$812 (jolt-invoke (var-deref "clojure.pprint" "->PrettyWriter") (jolt-get G__42 (keyword #f "fields")))) (_a$813 (jolt-dissoc G__42 (keyword #f "fields")))) (jolt-invoke _a$810 _a$811 _a$812 _a$813))))) (jolt-invoke (var-deref "clojure.core" "register-inline-protocol!") "PrettyWriter" "IPrettyWriter") (jolt-invoke (var-deref "clojure.core" "register-inline-method") "PrettyWriter" "IPrettyWriter" "-write" (lambda (this x) (let fnrec814 ((this this) (x x)) (let* ((fields (jolt-get this (keyword #f "fields")))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "string?") x)) (let* ((s0 (jolt-invoke (var-deref "clojure.pprint" "write-initial-lines") this x)) (s (jolt-invoke (var-deref "clojure.string" "replace-first") s0 (jolt-regex "\\s+$") "")) (white-space (jolt-invoke (var-deref "clojure.core" "subs") s0 (jolt-count s))) (mode (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch this "-fields" (jolt-vector))) (keyword #f "mode")))) (if (jolt= mode (keyword #f "writing")) (begin (jolt-invoke (var-deref "clojure.pprint" "write-white-space") this) (jolt-invoke (var-deref "clojure.pprint" "-write") (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch this "-fields" (jolt-vector))) (keyword #f "base")) s) (jolt-invoke (var-deref "clojure.core" "swap!") (record-method-dispatch this "-fields" (jolt-vector)) jolt-assoc (keyword #f "trailing-white-space") white-space)) (let* ((oldpos (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch this "-fields" (jolt-vector))) (keyword #f "pos"))) (newpos (jolt-n+ oldpos (jolt-count s0)))) (begin (jolt-invoke (var-deref "clojure.core" "swap!") (record-method-dispatch this "-fields" (jolt-vector)) jolt-assoc (keyword #f "pos") newpos) (jolt-invoke (var-deref "clojure.pprint" "add-to-buffer") this (jolt-invoke (var-deref "clojure.pprint" "make-buffer-blob") s white-space oldpos newpos)))))) (if (jolt-truthy? (let* ((or__26__auto (jolt-invoke (var-deref "clojure.core" "char?") x))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-invoke (var-deref "clojure.core" "number?") x)))) (jolt-invoke (var-deref "clojure.pprint" "p-write-char") this x) jolt-nil)))))) (jolt-invoke (var-deref "clojure.core" "register-inline-method") "PrettyWriter" "IPrettyWriter" "-pflush" (lambda (this) (let fnrec815 ((this this)) (let* ((fields (jolt-get this (keyword #f "fields")))) (begin (jolt-invoke (var-deref "clojure.pprint" "-ppflush") this) (jolt-invoke (var-deref "clojure.pprint" "-pflush") (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch this "-fields" (jolt-vector))) (keyword #f "base")))))))) (jolt-invoke (var-deref "clojure.core" "register-inline-protocol!") "PrettyWriter" "IPrettyFlush") (jolt-invoke (var-deref "clojure.core" "register-inline-method") "PrettyWriter" "IPrettyFlush" "-ppflush" (lambda (this) (let fnrec816 ((this this)) (let* ((fields (jolt-get this (keyword #f "fields")))) (if (jolt= (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch this "-fields" (jolt-vector))) (keyword #f "mode")) (keyword #f "buffering")) (begin (jolt-invoke (var-deref "clojure.pprint" "write-tokens") this (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch this "-fields" (jolt-vector))) (keyword #f "buffer")) #t) (let* ((_a$817 (var-deref "clojure.core" "swap!")) (_a$818 (record-method-dispatch this "-fields" (jolt-vector))) (_a$819 jolt-assoc) (_a$820 (keyword #f "buffer")) (_a$821 (jolt-vector))) (jolt-invoke _a$817 _a$818 _a$819 _a$820 _a$821))) (jolt-invoke (var-deref "clojure.pprint" "write-white-space") this)))))))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "pretty-writer" (letrec ((pretty-writer (lambda (writer max-columns miser-width) (let fnrec822 ((writer writer) (max-columns max-columns) (miser-width miser-width)) (let* ((lb (let* ((_a$823 (var-deref "clojure.pprint" "->logical-block")) (_a$824 jolt-nil) (_a$825 jolt-nil) (_a$826 (jolt-invoke (var-deref "clojure.core" "atom") 0)) (_a$827 (jolt-invoke (var-deref "clojure.core" "atom") 0)) (_a$828 (jolt-invoke (var-deref "clojure.core" "atom") #f)) (_a$829 (jolt-invoke (var-deref "clojure.core" "atom") #f)) (_a$830 jolt-nil) (_a$831 jolt-nil) (_a$832 jolt-nil) (_a$833 jolt-nil)) (jolt-invoke _a$823 _a$824 _a$825 _a$826 _a$827 _a$828 _a$829 _a$830 _a$831 _a$832 _a$833)))) (jolt-invoke (var-deref "clojure.pprint" "->PrettyWriter") (jolt-invoke (var-deref "clojure.core" "atom") (let* ((_o$834 (keyword #f "pretty-writer")) (_o$835 #t) (_o$836 (keyword #f "base")) (_o$837 (jolt-invoke (var-deref "clojure.pprint" "column-writer") writer max-columns)) (_o$838 (keyword #f "logical-blocks")) (_o$839 lb) (_o$840 (keyword #f "sections")) (_o$841 jolt-nil) (_o$842 (keyword #f "mode")) (_o$843 (keyword #f "writing")) (_o$844 (keyword #f "buffer")) (_o$845 (jolt-vector)) (_o$846 (keyword #f "buffer-block")) (_o$847 lb) (_o$848 (keyword #f "buffer-level")) (_o$849 1) (_o$850 (keyword #f "miser-width")) (_o$851 miser-width) (_o$852 (keyword #f "trailing-white-space")) (_o$853 jolt-nil) (_o$854 (keyword #f "pos")) (_o$855 0)) (jolt-hash-map _o$834 _o$835 _o$836 _o$837 _o$838 _o$839 _o$840 _o$841 _o$842 _o$843 _o$844 _o$845 _o$846 _o$847 _o$848 _o$849 _o$850 _o$851 _o$852 _o$853 _o$854 _o$855))))))))) pretty-writer) (let* ((_o$856 (keyword #f "private")) (_o$857 #t)) (jolt-hash-map _o$856 _o$857)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "start-block" (letrec ((start-block (lambda (this prefix per-line-prefix suffix) (let fnrec858 ((this this) (prefix prefix) (per-line-prefix per-line-prefix) (suffix suffix)) (let* ((lb (let* ((_a$859 (var-deref "clojure.pprint" "->logical-block")) (_a$860 (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch this "-fields" (jolt-vector))) (keyword #f "logical-blocks"))) (_a$861 jolt-nil) (_a$862 (jolt-invoke (var-deref "clojure.core" "atom") 0)) (_a$863 (jolt-invoke (var-deref "clojure.core" "atom") 0)) (_a$864 (jolt-invoke (var-deref "clojure.core" "atom") #f)) (_a$865 (jolt-invoke (var-deref "clojure.core" "atom") #f)) (_a$866 prefix) (_a$867 per-line-prefix) (_a$868 suffix) (_a$869 jolt-nil)) (jolt-invoke _a$859 _a$860 _a$861 _a$862 _a$863 _a$864 _a$865 _a$866 _a$867 _a$868 _a$869)))) (begin (jolt-invoke (var-deref "clojure.core" "swap!") (record-method-dispatch this "-fields" (jolt-vector)) jolt-assoc (keyword #f "logical-blocks") lb) (if (jolt= (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch this "-fields" (jolt-vector))) (keyword #f "mode")) (keyword #f "writing")) (begin (jolt-invoke (var-deref "clojure.pprint" "write-white-space") this) (let* ((temp__27__auto (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch this "-fields" (jolt-vector))) (keyword #f "logical-block-callback")))) (if (jolt-truthy? temp__27__auto) (let* ((cb temp__27__auto)) (jolt-invoke cb (keyword #f "start"))) jolt-nil)) (if (jolt-truthy? prefix) (jolt-invoke (var-deref "clojure.pprint" "-write") (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch this "-fields" (jolt-vector))) (keyword #f "base")) prefix) jolt-nil) (let* ((col (jolt-invoke (var-deref "clojure.pprint" "get-column") (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch this "-fields" (jolt-vector))) (keyword #f "base"))))) (begin (jolt-invoke (var-deref "clojure.core" "reset!") (jolt-get lb (keyword #f "start-col")) col) (jolt-invoke (var-deref "clojure.core" "reset!") (jolt-get lb (keyword #f "indent")) col)))) (let* ((oldpos (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch this "-fields" (jolt-vector))) (keyword #f "pos"))) (newpos (jolt-n+ oldpos (if (jolt-truthy? prefix) (jolt-count prefix) 0)))) (begin (jolt-invoke (var-deref "clojure.core" "swap!") (record-method-dispatch this "-fields" (jolt-vector)) jolt-assoc (keyword #f "pos") newpos) (jolt-invoke (var-deref "clojure.pprint" "add-to-buffer") this (jolt-invoke (var-deref "clojure.pprint" "make-start-block-t") lb oldpos newpos))))))))))) start-block) (let* ((_o$870 (keyword #f "private")) (_o$871 #t)) (jolt-hash-map _o$870 _o$871)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "end-block" (letrec ((end-block (lambda (this) (let fnrec872 ((this this)) (let* ((lb (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch this "-fields" (jolt-vector))) (keyword #f "logical-blocks"))) (suffix (jolt-get lb (keyword #f "suffix")))) (begin (if (jolt= (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch this "-fields" (jolt-vector))) (keyword #f "mode")) (keyword #f "writing")) (begin (jolt-invoke (var-deref "clojure.pprint" "write-white-space") this) (if (jolt-truthy? suffix) (jolt-invoke (var-deref "clojure.pprint" "-write") (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch this "-fields" (jolt-vector))) (keyword #f "base")) suffix) jolt-nil) (let* ((temp__27__auto (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch this "-fields" (jolt-vector))) (keyword #f "logical-block-callback")))) (if (jolt-truthy? temp__27__auto) (let* ((cb temp__27__auto)) (jolt-invoke cb (keyword #f "end"))) jolt-nil))) (let* ((oldpos (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch this "-fields" (jolt-vector))) (keyword #f "pos"))) (newpos (jolt-n+ oldpos (if (jolt-truthy? suffix) (jolt-count suffix) 0)))) (begin (jolt-invoke (var-deref "clojure.core" "swap!") (record-method-dispatch this "-fields" (jolt-vector)) jolt-assoc (keyword #f "pos") newpos) (jolt-invoke (var-deref "clojure.pprint" "add-to-buffer") this (jolt-invoke (var-deref "clojure.pprint" "make-end-block-t") lb oldpos newpos))))) (let* ((_a$873 (var-deref "clojure.core" "swap!")) (_a$874 (record-method-dispatch this "-fields" (jolt-vector))) (_a$875 jolt-assoc) (_a$876 (keyword #f "logical-blocks")) (_a$877 (jolt-get lb (keyword #f "parent")))) (jolt-invoke _a$873 _a$874 _a$875 _a$876 _a$877)))))))) end-block) (let* ((_o$878 (keyword #f "private")) (_o$879 #t)) (jolt-hash-map _o$878 _o$879)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "nl" (letrec ((nl (lambda (this type) (let fnrec880 ((this this) (type type)) (begin (jolt-invoke (var-deref "clojure.core" "swap!") (record-method-dispatch this "-fields" (jolt-vector)) jolt-assoc (keyword #f "mode") (keyword #f "buffering")) (let* ((pos (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch this "-fields" (jolt-vector))) (keyword #f "pos")))) (jolt-invoke (var-deref "clojure.pprint" "add-to-buffer") this (jolt-invoke (var-deref "clojure.pprint" "make-nl-t") type (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch this "-fields" (jolt-vector))) (keyword #f "logical-blocks")) pos pos)))))))) nl) (let* ((_o$881 (keyword #f "private")) (_o$882 #t)) (jolt-hash-map _o$881 _o$882)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "indent" (letrec ((indent (lambda (this relative-to offset) (let fnrec883 ((this this) (relative-to relative-to) (offset offset)) (let* ((lb (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch this "-fields" (jolt-vector))) (keyword #f "logical-blocks")))) (if (jolt= (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch this "-fields" (jolt-vector))) (keyword #f "mode")) (keyword #f "writing")) (begin (jolt-invoke (var-deref "clojure.pprint" "write-white-space") this) (let* ((_a$886 (var-deref "clojure.core" "reset!")) (_a$887 (jolt-get lb (keyword #f "indent"))) (_a$888 (jolt-n+ offset (let* ((G__43 jolt=) (G__44 relative-to)) (if (jolt-truthy? (jolt-invoke G__43 (keyword #f "block") G__44)) (jolt-invoke (var-deref "clojure.core" "deref") (jolt-get lb (keyword #f "start-col"))) (if (jolt-truthy? (jolt-invoke G__43 (keyword #f "current") G__44)) (jolt-invoke (var-deref "clojure.pprint" "get-column") (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch this "-fields" (jolt-vector))) (keyword #f "base"))) (jolt-throw (let* ((_a$884 (jolt-invoke (var-deref "clojure.core" "str") "No matching clause: " G__44)) (_a$885 (jolt-hash-map))) (jolt-ex-info _a$884 _a$885))))))))) (jolt-invoke _a$886 _a$887 _a$888))) (let* ((pos (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch this "-fields" (jolt-vector))) (keyword #f "pos")))) (jolt-invoke (var-deref "clojure.pprint" "add-to-buffer") this (jolt-invoke (var-deref "clojure.pprint" "make-indent-t") lb relative-to offset pos pos))))))))) indent) (let* ((_o$889 (keyword #f "private")) (_o$890 #t)) (jolt-hash-map _o$889 _o$890)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "get-miser-width" (letrec ((get-miser-width (lambda (this) (let fnrec891 ((this this)) (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch this "-fields" (jolt-vector))) (keyword #f "miser-width")))))) get-miser-width) (let* ((_o$892 (keyword #f "private")) (_o$893 #t)) (jolt-hash-map _o$892 _o$893)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "*print-pretty*" #t (let* ((_o$894 (keyword #f "dynamic")) (_o$895 #t)) (jolt-hash-map _o$894 _o$895)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "*print-pprint-dispatch*" jolt-nil (let* ((_o$896 (keyword #f "dynamic")) (_o$897 #t)) (jolt-hash-map _o$896 _o$897)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "*print-right-margin*" 72 (let* ((_o$898 (keyword #f "dynamic")) (_o$899 #t)) (jolt-hash-map _o$898 _o$899)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "*print-miser-width*" 40 (let* ((_o$900 (keyword #f "dynamic")) (_o$901 #t)) (jolt-hash-map _o$900 _o$901)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "*print-lines*" jolt-nil (let* ((_o$902 (keyword #f "private")) (_o$903 #t) (_o$904 (keyword #f "dynamic")) (_o$905 #t)) (jolt-hash-map _o$902 _o$903 _o$904 _o$905)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "*print-circle*" jolt-nil (let* ((_o$906 (keyword #f "private")) (_o$907 #t) (_o$908 (keyword #f "dynamic")) (_o$909 #t)) (jolt-hash-map _o$906 _o$907 _o$908 _o$909)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "*print-shared*" jolt-nil (let* ((_o$910 (keyword #f "private")) (_o$911 #t) (_o$912 (keyword #f "dynamic")) (_o$913 #t)) (jolt-hash-map _o$910 _o$911 _o$912 _o$913)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "*print-suppress-namespaces*" jolt-nil (let* ((_o$914 (keyword #f "dynamic")) (_o$915 #t)) (jolt-hash-map _o$914 _o$915)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "*print-radix*" jolt-nil (let* ((_o$916 (keyword #f "dynamic")) (_o$917 #t)) (jolt-hash-map _o$916 _o$917)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "*print-base*" 10 (let* ((_o$918 (keyword #f "dynamic")) (_o$919 #t)) (jolt-hash-map _o$918 _o$919)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "*current-level*" 0 (let* ((_o$920 (keyword #f "private")) (_o$921 #t) (_o$922 (keyword #f "dynamic")) (_o$923 #t)) (jolt-hash-map _o$920 _o$921 _o$922 _o$923)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "*current-length*" jolt-nil (let* ((_o$924 (keyword #f "private")) (_o$925 #t) (_o$926 (keyword #f "dynamic")) (_o$927 #t)) (jolt-hash-map _o$924 _o$925 _o$926 _o$927)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "*print-length*" jolt-nil (let* ((_o$928 (keyword #f "dynamic")) (_o$929 #t)) (jolt-hash-map _o$928 _o$929)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "*print-level*" jolt-nil (let* ((_o$930 (keyword #f "dynamic")) (_o$931 #t)) (jolt-hash-map _o$930 _o$931)))) -(guard (e (#t #f)) - (declare-var! "clojure.pprint" "format-simple-number")) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "pretty-writer?" (letrec ((pretty-writer? (lambda (x) (let fnrec932 ((x x)) (let* ((and__25__auto (jolt-invoke (var-deref "clojure.core" "instance-check") (jolt-symbol #f "PrettyWriter") x))) (if (jolt-truthy? and__25__auto) (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch x "-fields" (jolt-vector))) (keyword #f "pretty-writer")) and__25__auto)))))) pretty-writer?) (let* ((_o$933 (keyword #f "private")) (_o$934 #t)) (jolt-hash-map _o$933 _o$934)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "make-pretty-writer" (letrec ((make-pretty-writer (lambda (base-writer right-margin miser-width) (let fnrec935 ((base-writer base-writer) (right-margin right-margin) (miser-width miser-width)) (jolt-invoke (var-deref "clojure.pprint" "pretty-writer") base-writer right-margin miser-width))))) make-pretty-writer) (let* ((_o$936 (keyword #f "private")) (_o$937 #t)) (jolt-hash-map _o$936 _o$937)))) -(guard (e (#t #f)) - (def-var! "clojure.pprint" "with-pretty-writer" - (lambda (base-writer . body) (let fnrec938 ((base-writer base-writer) (body (list->cseq body))) (let* ((_a$978 (var-deref "clojure.core" "__sqcat")) (_a$979 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "let"))) (_a$980 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$945 (var-deref "clojure.core" "__sqvec")) (_a$946 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "base-writer__11__auto"))) (_a$947 (jolt-invoke (var-deref "clojure.core" "__sq1") base-writer)) (_a$948 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "new-writer__12__auto"))) (_a$949 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$942 (var-deref "clojure.core" "__sqcat")) (_a$943 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "not"))) (_a$944 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$939 (var-deref "clojure.core" "__sqcat")) (_a$940 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.pprint" "pretty-writer?"))) (_a$941 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "base-writer__11__auto")))) (jolt-invoke _a$939 _a$940 _a$941))))) (jolt-invoke _a$942 _a$943 _a$944))))) (jolt-invoke _a$945 _a$946 _a$947 _a$948 _a$949)))) (_a$981 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$974 (var-deref "clojure.core" "__sqcat")) (_a$975 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "binding"))) (_a$976 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$960 (var-deref "clojure.core" "__sqvec")) (_a$961 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "*out*"))) (_a$962 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$955 (var-deref "clojure.core" "__sqcat")) (_a$956 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "if"))) (_a$957 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "new-writer__12__auto"))) (_a$958 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$950 (var-deref "clojure.core" "__sqcat")) (_a$951 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.pprint" "make-pretty-writer"))) (_a$952 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "base-writer__11__auto"))) (_a$953 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.pprint" "*print-right-margin*"))) (_a$954 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.pprint" "*print-miser-width*")))) (jolt-invoke _a$950 _a$951 _a$952 _a$953 _a$954)))) (_a$959 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "base-writer__11__auto")))) (jolt-invoke _a$955 _a$956 _a$957 _a$958 _a$959))))) (jolt-invoke _a$960 _a$961 _a$962)))) (_a$977 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$971 (var-deref "clojure.core" "__sqcat")) (_a$972 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "__with-pprint-routing"))) (_a$973 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$966 (var-deref "clojure.core" "__sqcat")) (_a$967 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "fn"))) (_a$968 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqvec")))) (_a$969 body) (_a$970 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$963 (var-deref "clojure.core" "__sqcat")) (_a$964 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.pprint" "-ppflush"))) (_a$965 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "*out*")))) (jolt-invoke _a$963 _a$964 _a$965))))) (jolt-invoke _a$966 _a$967 _a$968 _a$969 _a$970))))) (jolt-invoke _a$971 _a$972 _a$973))))) (jolt-invoke _a$974 _a$975 _a$976 _a$977))))) (jolt-invoke _a$978 _a$979 _a$980 _a$981))))) - (mark-macro! "clojure.pprint" "with-pretty-writer")) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "write-out" (letrec ((write-out (lambda (object) (let fnrec982 ((object object)) (let* ((length-reached (let* ((and__25__auto (var-deref "clojure.pprint" "*current-length*"))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (var-deref "clojure.pprint" "*print-length*"))) (if (jolt-truthy? and__25__auto) (jolt-n>= (var-deref "clojure.pprint" "*current-length*") (var-deref "clojure.pprint" "*print-length*")) and__25__auto)) and__25__auto)))) (begin (if (jolt-not (var-deref "clojure.pprint" "*print-pretty*")) (jolt-invoke (var-deref "clojure.pprint" "pr") object) (if (jolt-truthy? length-reached) (jolt-invoke (var-deref "clojure.pprint" "-write") (var-deref "clojure.core" "*out*") "...") (begin (if (jolt-truthy? (var-deref "clojure.pprint" "*current-length*")) (jolt-var-set (jolt-var "clojure.pprint" "*current-length*") (jolt-inc (var-deref "clojure.pprint" "*current-length*"))) jolt-nil) (jolt-invoke (var-deref "clojure.pprint" "*print-pprint-dispatch*") object)))) length-reached)))))) write-out) (let* ((_o$983 (keyword #f "doc")) (_o$984 "Write an object to *out* subject to the current bindings of the printer control\n variables. *out* must be a PrettyWriter when pretty printing is enabled.")) (jolt-hash-map _o$983 _o$984)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "write" (letrec ((write (lambda (object . kw-args) (let fnrec985 ((object object) (kw-args (list->cseq kw-args))) (let* ((options (let* ((_a$988 (var-deref "clojure.core" "merge")) (_a$989 (let* ((_o$986 (keyword #f "stream")) (_o$987 #t)) (jolt-hash-map _o$986 _o$987))) (_a$990 (jolt-apply jolt-hash-map-fn kw-args))) (jolt-invoke _a$988 _a$989 _a$990)))) (let* ((frame__20__auto (let* ((_a$991 (var-deref "clojure.core" "array-map")) (_a$992 (jolt-var "clojure.pprint" "*print-base*")) (_a$993 (jolt-get options (keyword #f "base") (var-deref "clojure.pprint" "*print-base*"))) (_a$994 (jolt-var "clojure.pprint" "*print-circle*")) (_a$995 (jolt-get options (keyword #f "circle") (var-deref "clojure.pprint" "*print-circle*"))) (_a$996 (jolt-var "clojure.pprint" "*print-length*")) (_a$997 (jolt-get options (keyword #f "length") (var-deref "clojure.pprint" "*print-length*"))) (_a$998 (jolt-var "clojure.pprint" "*print-level*")) (_a$999 (jolt-get options (keyword #f "level") (var-deref "clojure.pprint" "*print-level*"))) (_a$1000 (jolt-var "clojure.pprint" "*print-lines*")) (_a$1001 (jolt-get options (keyword #f "lines") (var-deref "clojure.pprint" "*print-lines*"))) (_a$1002 (jolt-var "clojure.pprint" "*print-miser-width*")) (_a$1003 (jolt-get options (keyword #f "miser-width") (var-deref "clojure.pprint" "*print-miser-width*"))) (_a$1004 (jolt-var "clojure.pprint" "*print-pprint-dispatch*")) (_a$1005 (jolt-get options (keyword #f "dispatch") (var-deref "clojure.pprint" "*print-pprint-dispatch*"))) (_a$1006 (jolt-var "clojure.pprint" "*print-pretty*")) (_a$1007 (jolt-get options (keyword #f "pretty") (var-deref "clojure.pprint" "*print-pretty*"))) (_a$1008 (jolt-var "clojure.pprint" "*print-radix*")) (_a$1009 (jolt-get options (keyword #f "radix") (var-deref "clojure.pprint" "*print-radix*"))) (_a$1010 (jolt-var "clojure.core" "*print-readably*")) (_a$1011 (jolt-get options (keyword #f "readably") (var-deref "clojure.core" "*print-readably*"))) (_a$1012 (jolt-var "clojure.pprint" "*print-right-margin*")) (_a$1013 (jolt-get options (keyword #f "right-margin") (var-deref "clojure.pprint" "*print-right-margin*"))) (_a$1014 (jolt-var "clojure.pprint" "*print-suppress-namespaces*")) (_a$1015 (jolt-get options (keyword #f "suppress-namespaces") (var-deref "clojure.pprint" "*print-suppress-namespaces*")))) (jolt-invoke _a$991 _a$992 _a$993 _a$994 _a$995 _a$996 _a$997 _a$998 _a$999 _a$1000 _a$1001 _a$1002 _a$1003 _a$1004 _a$1005 _a$1006 _a$1007 _a$1008 _a$1009 _a$1010 _a$1011 _a$1012 _a$1013 _a$1014 _a$1015)))) (begin (jolt-invoke (var-deref "clojure.core" "push-thread-bindings") frame__20__auto) (dynamic-wind (lambda () #f) (lambda () (let* ((sb (host-new "StringBuilder")) (optval (if (jolt-contains? options (keyword #f "stream")) (jolt-get options (keyword #f "stream")) #t)) (base-writer (if (jolt-truthy? (let* ((or__26__auto (jolt-invoke (var-deref "clojure.core" "true?") optval))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-nil? optval)))) (jolt-invoke (var-deref "clojure.pprint" "->StringBufferWriter") sb) optval))) (begin (if (jolt-truthy? (var-deref "clojure.pprint" "*print-pretty*")) (let* ((base-writer__11__auto base-writer) (new-writer__12__auto (jolt-not (jolt-invoke (var-deref "clojure.pprint" "pretty-writer?") base-writer__11__auto)))) (let* ((frame__20__auto (jolt-invoke (var-deref "clojure.core" "array-map") (jolt-var "clojure.core" "*out*") (if (jolt-truthy? new-writer__12__auto) (jolt-invoke (var-deref "clojure.pprint" "make-pretty-writer") base-writer__11__auto (var-deref "clojure.pprint" "*print-right-margin*") (var-deref "clojure.pprint" "*print-miser-width*")) base-writer__11__auto)))) (begin (jolt-invoke (var-deref "clojure.core" "push-thread-bindings") frame__20__auto) (dynamic-wind (lambda () #f) (lambda () (jolt-invoke (var-deref "clojure.core" "__with-pprint-routing") (lambda () (let fnrec1016 () (begin (jolt-invoke (var-deref "clojure.pprint" "write-out") object) (jolt-invoke (var-deref "clojure.pprint" "-ppflush") (var-deref "clojure.core" "*out*"))))))) (lambda () (jolt-invoke (var-deref "clojure.core" "pop-thread-bindings"))))))) (let* ((frame__20__auto (jolt-invoke (var-deref "clojure.core" "array-map") (jolt-var "clojure.core" "*out*") base-writer))) (begin (jolt-invoke (var-deref "clojure.core" "push-thread-bindings") frame__20__auto) (dynamic-wind (lambda () #f) (lambda () (jolt-invoke (var-deref "clojure.pprint" "pr") object)) (lambda () (jolt-invoke (var-deref "clojure.core" "pop-thread-bindings"))))))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "true?") optval)) (jolt-invoke (var-deref "clojure.core" "print") (jolt-invoke (var-deref "clojure.core" "str") sb)) jolt-nil) (if (jolt-nil? optval) (jolt-invoke (var-deref "clojure.core" "str") sb) jolt-nil)))) (lambda () (jolt-invoke (var-deref "clojure.core" "pop-thread-bindings"))))))))))) write) (let* ((_o$1017 (keyword #f "doc")) (_o$1018 "Write an object subject to the current bindings of the printer control\n variables. Returns the string result if :stream is nil, nil otherwise.")) (jolt-hash-map _o$1017 _o$1018)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "pprint" (letrec ((pprint (case-lambda ((object) (let fnrec1019 ((object object)) (let* ((sb (host-new "StringBuilder"))) (let* ((frame__20__auto (jolt-invoke (var-deref "clojure.core" "array-map") (jolt-var "clojure.core" "*out*") (jolt-invoke (var-deref "clojure.pprint" "->StringBufferWriter") sb)))) (begin (jolt-invoke (var-deref "clojure.core" "push-thread-bindings") frame__20__auto) (dynamic-wind (lambda () #f) (lambda () (begin (pprint object (var-deref "clojure.core" "*out*")) (jolt-invoke (var-deref "clojure.core" "print") (jolt-invoke (var-deref "clojure.core" "str") sb)))) (lambda () (jolt-invoke (var-deref "clojure.core" "pop-thread-bindings"))))))))) ((object writer) (let fnrec1020 ((object object) (writer writer)) (let* ((base-writer__11__auto writer) (new-writer__12__auto (jolt-not (jolt-invoke (var-deref "clojure.pprint" "pretty-writer?") base-writer__11__auto)))) (let* ((frame__20__auto (jolt-invoke (var-deref "clojure.core" "array-map") (jolt-var "clojure.core" "*out*") (if (jolt-truthy? new-writer__12__auto) (jolt-invoke (var-deref "clojure.pprint" "make-pretty-writer") base-writer__11__auto (var-deref "clojure.pprint" "*print-right-margin*") (var-deref "clojure.pprint" "*print-miser-width*")) base-writer__11__auto)))) (begin (jolt-invoke (var-deref "clojure.core" "push-thread-bindings") frame__20__auto) (dynamic-wind (lambda () #f) (lambda () (jolt-invoke (var-deref "clojure.core" "__with-pprint-routing") (lambda () (let fnrec1021 () (begin (let* ((frame__20__auto (jolt-invoke (var-deref "clojure.core" "array-map") (jolt-var "clojure.pprint" "*print-pretty*") #t))) (begin (jolt-invoke (var-deref "clojure.core" "push-thread-bindings") frame__20__auto) (dynamic-wind (lambda () #f) (lambda () (jolt-invoke (var-deref "clojure.pprint" "write-out") object)) (lambda () (jolt-invoke (var-deref "clojure.core" "pop-thread-bindings")))))) (if (jolt-not (jolt= 0 (jolt-invoke (var-deref "clojure.pprint" "get-column") (var-deref "clojure.core" "*out*")))) (jolt-invoke (var-deref "clojure.pprint" "-write") (var-deref "clojure.core" "*out*") "\n") jolt-nil) (jolt-invoke (var-deref "clojure.pprint" "-ppflush") (var-deref "clojure.core" "*out*"))))))) (lambda () (jolt-invoke (var-deref "clojure.core" "pop-thread-bindings")))))))))))) pprint) (let* ((_o$1022 (keyword #f "doc")) (_o$1023 "Pretty print object. With one arg, prints to *out* (captured by with-out-str).\n The 2-arg form writes to the supplied pretty-writer.")) (jolt-hash-map _o$1022 _o$1023)))) -(guard (e (#t #f)) - (def-var! "clojure.pprint" "set-pprint-dispatch" (letrec ((set-pprint-dispatch (lambda (function) (let fnrec1024 ((function function)) (begin (jolt-var-set (jolt-var "clojure.pprint" "*print-pprint-dispatch*") function) jolt-nil))))) set-pprint-dispatch))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "check-enumerated-arg" (letrec ((check-enumerated-arg (lambda (arg choices) (let fnrec1025 ((arg arg) (choices choices)) (if (jolt-not (jolt-invoke choices arg)) (jolt-throw (host-new "Exception" (jolt-invoke (var-deref "clojure.core" "str") "Bad argument: " arg ". It must be one of " choices))) jolt-nil))))) check-enumerated-arg) (let* ((_o$1026 (keyword #f "private")) (_o$1027 #t)) (jolt-hash-map _o$1026 _o$1027)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "level-exceeded" (letrec ((level-exceeded (lambda () (let fnrec1028 () (let* ((and__25__auto (var-deref "clojure.pprint" "*print-level*"))) (if (jolt-truthy? and__25__auto) (jolt-n>= (var-deref "clojure.pprint" "*current-level*") (var-deref "clojure.pprint" "*print-level*")) and__25__auto)))))) level-exceeded) (let* ((_o$1029 (keyword #f "private")) (_o$1030 #t)) (jolt-hash-map _o$1029 _o$1030)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "pprint-newline" (letrec ((pprint-newline (lambda (kind) (let fnrec1031 ((kind kind)) (begin (jolt-invoke (var-deref "clojure.pprint" "check-enumerated-arg") kind (let* ((_o$1032 (keyword #f "linear")) (_o$1033 (keyword #f "miser")) (_o$1034 (keyword #f "fill")) (_o$1035 (keyword #f "mandatory"))) (jolt-hash-set _o$1032 _o$1033 _o$1034 _o$1035))) (jolt-invoke (var-deref "clojure.pprint" "nl") (var-deref "clojure.core" "*out*") kind)))))) pprint-newline) (let* ((_o$1036 (keyword #f "doc")) (_o$1037 "Print a conditional newline (:linear :miser :fill or :mandatory) to *out*,\n which must be a pretty-printing writer.")) (jolt-hash-map _o$1036 _o$1037)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "pprint-indent" (letrec ((pprint-indent (lambda (relative-to n) (let fnrec1038 ((relative-to relative-to) (n n)) (begin (jolt-invoke (var-deref "clojure.pprint" "check-enumerated-arg") relative-to (let* ((_o$1039 (keyword #f "block")) (_o$1040 (keyword #f "current"))) (jolt-hash-set _o$1039 _o$1040))) (jolt-invoke (var-deref "clojure.pprint" "indent") (var-deref "clojure.core" "*out*") relative-to n)))))) pprint-indent) (let* ((_o$1041 (keyword #f "doc")) (_o$1042 "Create an indent at this point in the pretty-printing stream. relative-to is\n :block or :current; n is an offset.")) (jolt-hash-map _o$1041 _o$1042)))) -(guard (e (#t #f)) - (def-var! "clojure.pprint" "pprint-tab" (letrec ((pprint-tab (lambda (kind colnum colinc) (let fnrec1043 ((kind kind) (colnum colnum) (colinc colinc)) (begin (jolt-invoke (var-deref "clojure.pprint" "check-enumerated-arg") kind (let* ((_o$1044 (keyword #f "line")) (_o$1045 (keyword #f "section")) (_o$1046 (keyword #f "line-relative")) (_o$1047 (keyword #f "section-relative"))) (jolt-hash-set _o$1044 _o$1045 _o$1046 _o$1047))) (jolt-throw (host-new "Exception" "pprint-tab is not yet implemented"))))))) pprint-tab))) -(guard (e (#t #f)) - (declare-var! "clojure.pprint" "compile-format")) -(guard (e (#t #f)) - (declare-var! "clojure.pprint" "execute-format")) -(guard (e (#t #f)) - (declare-var! "clojure.pprint" "init-navigator")) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "cl-format" (letrec ((cl-format (lambda (writer format-in . args) (let fnrec1048 ((writer writer) (format-in format-in) (args (list->cseq args))) (let* ((compiled-format (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "string?") format-in)) (jolt-invoke (var-deref "clojure.pprint" "compile-format") format-in) format-in)) (navigator (jolt-invoke (var-deref "clojure.pprint" "init-navigator") args))) (jolt-invoke (var-deref "clojure.pprint" "execute-format") writer compiled-format navigator)))))) cl-format) (let* ((_o$1049 (keyword #f "doc")) (_o$1050 "A Common Lisp compatible format function. If writer is nil, returns the\n formatted string; if true, prints to *out*; otherwise writes to writer.")) (jolt-hash-map _o$1049 _o$1050)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "*format-str*" jolt-nil (let* ((_o$1051 (keyword #f "private")) (_o$1052 #t) (_o$1053 (keyword #f "dynamic")) (_o$1054 #t)) (jolt-hash-map _o$1051 _o$1052 _o$1053 _o$1054)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "format-error" (letrec ((format-error (lambda (message offset) (let fnrec1055 ((message message) (offset offset)) (let* ((full-message (jolt-invoke (var-deref "clojure.core" "str") message "\n" (var-deref "clojure.pprint" "*format-str*") "\n" (jolt-apply (var-deref "clojure.core" "str") (jolt-invoke (var-deref "clojure.core" "repeat") offset (integer->char 32))) "^" "\n"))) (jolt-throw (host-new "Exception" full-message))))))) format-error) (let* ((_o$1056 (keyword #f "private")) (_o$1057 #t)) (jolt-hash-map _o$1056 _o$1057)))) -(guard (e (#t #f)) - (begin (begin (def-var-with-meta! "clojure.pprint" "arg-navigator" (let* ((_a$1067 (var-deref "clojure.core" "make-deftype-ctor")) (_a$1068 (jolt-invoke (var-deref "clojure.core" "with-meta") (jolt-symbol/meta #f "arg-navigator" (jolt-hash-map (keyword #f "private") #t)) (jolt-hash-map (keyword #f "private") #t))) (_a$1069 (let* ((_o$1058 (keyword #f "seq")) (_o$1059 (keyword #f "rest")) (_o$1060 (keyword #f "pos"))) (jolt-vector _o$1058 _o$1059 _o$1060))) (_a$1070 (let* ((_o$1061 jolt-nil) (_o$1062 jolt-nil) (_o$1063 jolt-nil)) (jolt-vector _o$1061 _o$1062 _o$1063))) (_a$1071 (let* ((_o$1064 #f) (_o$1065 #f) (_o$1066 #f)) (jolt-vector _o$1064 _o$1065 _o$1066)))) (jolt-invoke _a$1067 _a$1068 _a$1069 _a$1070 _a$1071)) (let* ((_o$1072 (keyword #f "private")) (_o$1073 #t)) (jolt-hash-map _o$1072 _o$1073))) (def-var! "clojure.pprint" "->arg-navigator" (var-deref "clojure.pprint" "arg-navigator")) (var-deref "clojure.pprint" "arg-navigator")) (jolt-invoke (var-deref "clojure.core" "register-record-type!") (jolt-invoke (var-deref "clojure.core" "with-meta") (jolt-symbol/meta #f "arg-navigator" (jolt-hash-map (keyword #f "private") #t)) (jolt-hash-map (keyword #f "private") #t))) (def-var! "clojure.pprint" "map->arg-navigator" (lambda (G__45) (let fnrec1074 ((G__45 G__45)) (let* ((_a$1079 (var-deref "clojure.core" "reduce-kv")) (_a$1080 jolt-assoc) (_a$1081 (let* ((_a$1075 (var-deref "clojure.pprint" "->arg-navigator")) (_a$1076 (jolt-get G__45 (keyword #f "seq"))) (_a$1077 (jolt-get G__45 (keyword #f "rest"))) (_a$1078 (jolt-get G__45 (keyword #f "pos")))) (jolt-invoke _a$1075 _a$1076 _a$1077 _a$1078))) (_a$1082 (jolt-dissoc G__45 (keyword #f "seq") (keyword #f "rest") (keyword #f "pos")))) (jolt-invoke _a$1079 _a$1080 _a$1081 _a$1082))))))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "init-navigator" (letrec ((init-navigator (lambda (s) (let fnrec1083 ((s s)) (let* ((s (jolt-seq s))) (jolt-invoke (var-deref "clojure.pprint" "->arg-navigator") s s 0)))))) init-navigator) (let* ((_o$1084 (keyword #f "private")) (_o$1085 #t)) (jolt-hash-map _o$1084 _o$1085)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "next-arg" (letrec ((next-arg (lambda (navigator) (let fnrec1086 ((navigator navigator)) (let* ((rst (jolt-get navigator (keyword #f "rest")))) (if (jolt-truthy? rst) (let* ((_o$1091 (jolt-first rst)) (_o$1092 (let* ((_a$1087 (var-deref "clojure.pprint" "->arg-navigator")) (_a$1088 (jolt-get navigator (keyword #f "seq"))) (_a$1089 (jolt-next rst)) (_a$1090 (jolt-inc (jolt-get navigator (keyword #f "pos"))))) (jolt-invoke _a$1087 _a$1088 _a$1089 _a$1090)))) (jolt-vector _o$1091 _o$1092)) (jolt-throw (host-new "Exception" "Not enough arguments for format definition")))))))) next-arg) (let* ((_o$1093 (keyword #f "private")) (_o$1094 #t)) (jolt-hash-map _o$1093 _o$1094)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "next-arg-or-nil" (letrec ((next-arg-or-nil (lambda (navigator) (let fnrec1095 ((navigator navigator)) (let* ((rst (jolt-get navigator (keyword #f "rest")))) (if (jolt-truthy? rst) (let* ((_o$1100 (jolt-first rst)) (_o$1101 (let* ((_a$1096 (var-deref "clojure.pprint" "->arg-navigator")) (_a$1097 (jolt-get navigator (keyword #f "seq"))) (_a$1098 (jolt-next rst)) (_a$1099 (jolt-inc (jolt-get navigator (keyword #f "pos"))))) (jolt-invoke _a$1096 _a$1097 _a$1098 _a$1099)))) (jolt-vector _o$1100 _o$1101)) (let* ((_o$1102 jolt-nil) (_o$1103 navigator)) (jolt-vector _o$1102 _o$1103)))))))) next-arg-or-nil) (let* ((_o$1104 (keyword #f "private")) (_o$1105 #t)) (jolt-hash-map _o$1104 _o$1105)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "get-format-arg" (letrec ((get-format-arg (lambda (navigator) (let fnrec1106 ((navigator navigator)) (let* ((G__46 (jolt-invoke (var-deref "clojure.pprint" "next-arg") navigator)) (raw-format (jolt-nth G__46 0 jolt-nil)) (navigator (jolt-nth G__46 1 jolt-nil)) (compiled-format (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "string?") raw-format)) (jolt-invoke (var-deref "clojure.pprint" "compile-format") raw-format) raw-format))) (let* ((_o$1107 compiled-format) (_o$1108 navigator)) (jolt-vector _o$1107 _o$1108))))))) get-format-arg) (let* ((_o$1109 (keyword #f "private")) (_o$1110 #t)) (jolt-hash-map _o$1109 _o$1110)))) -(guard (e (#t #f)) - (declare-var! "clojure.pprint" "relative-reposition")) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "absolute-reposition" (letrec ((absolute-reposition (lambda (navigator position) (let fnrec1111 ((navigator navigator) (position position)) (if (jolt-n>= position (jolt-get navigator (keyword #f "pos"))) (jolt-invoke (var-deref "clojure.pprint" "relative-reposition") navigator (jolt-n- (jolt-get navigator (keyword #f "pos")) position)) (let* ((_a$1112 (var-deref "clojure.pprint" "->arg-navigator")) (_a$1113 (jolt-get navigator (keyword #f "seq"))) (_a$1114 (jolt-drop position (jolt-get navigator (keyword #f "seq")))) (_a$1115 position)) (jolt-invoke _a$1112 _a$1113 _a$1114 _a$1115))))))) absolute-reposition) (let* ((_o$1116 (keyword #f "private")) (_o$1117 #t)) (jolt-hash-map _o$1116 _o$1117)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "relative-reposition" (letrec ((relative-reposition (lambda (navigator position) (let fnrec1118 ((navigator navigator) (position position)) (let* ((newpos (jolt-n+ (jolt-get navigator (keyword #f "pos")) position))) (if (jolt-neg? position) (jolt-invoke (var-deref "clojure.pprint" "absolute-reposition") navigator newpos) (let* ((_a$1119 (var-deref "clojure.pprint" "->arg-navigator")) (_a$1120 (jolt-get navigator (keyword #f "seq"))) (_a$1121 (jolt-drop position (jolt-get navigator (keyword #f "rest")))) (_a$1122 newpos)) (jolt-invoke _a$1119 _a$1120 _a$1121 _a$1122)))))))) relative-reposition) (let* ((_o$1123 (keyword #f "private")) (_o$1124 #t)) (jolt-hash-map _o$1123 _o$1124)))) -(guard (e (#t #f)) - (begin (begin (def-var-with-meta! "clojure.pprint" "compiled-directive" (let* ((_a$1137 (var-deref "clojure.core" "make-deftype-ctor")) (_a$1138 (jolt-invoke (var-deref "clojure.core" "with-meta") (jolt-symbol/meta #f "compiled-directive" (jolt-hash-map (keyword #f "private") #t)) (jolt-hash-map (keyword #f "private") #t))) (_a$1139 (let* ((_o$1125 (keyword #f "func")) (_o$1126 (keyword #f "dirdef")) (_o$1127 (keyword #f "params")) (_o$1128 (keyword #f "offset"))) (jolt-vector _o$1125 _o$1126 _o$1127 _o$1128))) (_a$1140 (let* ((_o$1129 jolt-nil) (_o$1130 jolt-nil) (_o$1131 jolt-nil) (_o$1132 jolt-nil)) (jolt-vector _o$1129 _o$1130 _o$1131 _o$1132))) (_a$1141 (let* ((_o$1133 #f) (_o$1134 #f) (_o$1135 #f) (_o$1136 #f)) (jolt-vector _o$1133 _o$1134 _o$1135 _o$1136)))) (jolt-invoke _a$1137 _a$1138 _a$1139 _a$1140 _a$1141)) (let* ((_o$1142 (keyword #f "private")) (_o$1143 #t)) (jolt-hash-map _o$1142 _o$1143))) (def-var! "clojure.pprint" "->compiled-directive" (var-deref "clojure.pprint" "compiled-directive")) (var-deref "clojure.pprint" "compiled-directive")) (jolt-invoke (var-deref "clojure.core" "register-record-type!") (jolt-invoke (var-deref "clojure.core" "with-meta") (jolt-symbol/meta #f "compiled-directive" (jolt-hash-map (keyword #f "private") #t)) (jolt-hash-map (keyword #f "private") #t))) (def-var! "clojure.pprint" "map->compiled-directive" (lambda (G__47) (let fnrec1144 ((G__47 G__47)) (let* ((_a$1150 (var-deref "clojure.core" "reduce-kv")) (_a$1151 jolt-assoc) (_a$1152 (let* ((_a$1145 (var-deref "clojure.pprint" "->compiled-directive")) (_a$1146 (jolt-get G__47 (keyword #f "func"))) (_a$1147 (jolt-get G__47 (keyword #f "dirdef"))) (_a$1148 (jolt-get G__47 (keyword #f "params"))) (_a$1149 (jolt-get G__47 (keyword #f "offset")))) (jolt-invoke _a$1145 _a$1146 _a$1147 _a$1148 _a$1149))) (_a$1153 (jolt-dissoc G__47 (keyword #f "func") (keyword #f "dirdef") (keyword #f "params") (keyword #f "offset")))) (jolt-invoke _a$1150 _a$1151 _a$1152 _a$1153))))))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "realize-parameter" (letrec ((realize-parameter (lambda (G__48 navigator) (let fnrec1154 ((G__48 G__48) (navigator navigator)) (let* ((G__49 G__48) (param (jolt-nth G__49 0 jolt-nil)) (G__50 (jolt-nth G__49 1 jolt-nil)) (raw-val (jolt-nth G__50 0 jolt-nil)) (offset (jolt-nth G__50 1 jolt-nil))) (let* ((G__51 (if (jolt-contains? (let* ((_o$1155 (keyword #f "at")) (_o$1156 (keyword #f "colon"))) (jolt-hash-set _o$1155 _o$1156)) param) (let* ((_o$1157 raw-val) (_o$1158 navigator)) (jolt-vector _o$1157 _o$1158)) (if (jolt= raw-val (keyword #f "parameter-from-args")) (jolt-invoke (var-deref "clojure.pprint" "next-arg") navigator) (if (jolt= raw-val (keyword #f "remaining-arg-count")) (let* ((_o$1159 (jolt-count (jolt-get navigator (keyword #f "rest")))) (_o$1160 navigator)) (jolt-vector _o$1159 _o$1160)) (if #t (let* ((_o$1161 raw-val) (_o$1162 navigator)) (jolt-vector _o$1161 _o$1162)) jolt-nil))))) (real-param (jolt-nth G__51 0 jolt-nil)) (new-navigator (jolt-nth G__51 1 jolt-nil))) (let* ((_o$1167 (let* ((_o$1165 param) (_o$1166 (let* ((_o$1163 real-param) (_o$1164 offset)) (jolt-vector _o$1163 _o$1164)))) (jolt-vector _o$1165 _o$1166))) (_o$1168 new-navigator)) (jolt-vector _o$1167 _o$1168)))))))) realize-parameter) (let* ((_o$1169 (keyword #f "private")) (_o$1170 #t)) (jolt-hash-map _o$1169 _o$1170)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "realize-parameter-list" (letrec ((realize-parameter-list (lambda (parameter-map navigator) (let fnrec1171 ((parameter-map parameter-map) (navigator navigator)) (let* ((G__52 (jolt-invoke (var-deref "clojure.pprint" "map-passing-context") (var-deref "clojure.pprint" "realize-parameter") navigator parameter-map)) (pairs (jolt-nth G__52 0 jolt-nil)) (new-navigator (jolt-nth G__52 1 jolt-nil))) (let* ((_o$1172 (jolt-into (jolt-hash-map) pairs)) (_o$1173 new-navigator)) (jolt-vector _o$1172 _o$1173))))))) realize-parameter-list) (let* ((_o$1174 (keyword #f "private")) (_o$1175 #t)) (jolt-hash-map _o$1174 _o$1175)))) -(guard (e (#t #f)) - (declare-var! "clojure.pprint" "opt-base-str")) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "special-radix-markers" (let* ((_o$1176 2) (_o$1177 "#b") (_o$1178 8) (_o$1179 "#o") (_o$1180 16) (_o$1181 "#x")) (jolt-hash-map _o$1176 _o$1177 _o$1178 _o$1179 _o$1180 _o$1181)) (let* ((_o$1182 (keyword #f "private")) (_o$1183 #t)) (jolt-hash-map _o$1182 _o$1183)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "format-simple-number" (letrec ((format-simple-number (lambda (n) (let fnrec1184 ((n n)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "integer?") n)) (if (jolt= (var-deref "clojure.pprint" "*print-base*") 10) (jolt-invoke (var-deref "clojure.core" "str") n (if (jolt-truthy? (var-deref "clojure.pprint" "*print-radix*")) "." jolt-nil)) (let* ((_a$1185 (var-deref "clojure.core" "str")) (_a$1186 (if (jolt-truthy? (var-deref "clojure.pprint" "*print-radix*")) (let* ((or__26__auto (jolt-get (var-deref "clojure.pprint" "special-radix-markers") (var-deref "clojure.pprint" "*print-base*")))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-invoke (var-deref "clojure.core" "str") "#" (var-deref "clojure.pprint" "*print-base*") "r"))) jolt-nil)) (_a$1187 (jolt-invoke (var-deref "clojure.pprint" "opt-base-str") (var-deref "clojure.pprint" "*print-base*") n))) (jolt-invoke _a$1185 _a$1186 _a$1187))) (if (jolt-truthy? (keyword #f "else")) jolt-nil jolt-nil)))))) format-simple-number) (let* ((_o$1188 (keyword #f "private")) (_o$1189 #t)) (jolt-hash-map _o$1188 _o$1189)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "format-ascii" (letrec ((format-ascii (lambda (print-func params arg-navigator offsets) (let fnrec1190 ((print-func print-func) (params params) (arg-navigator arg-navigator) (offsets offsets)) (let* ((G__53 (jolt-invoke (var-deref "clojure.pprint" "next-arg") arg-navigator)) (arg (jolt-nth G__53 0 jolt-nil)) (arg-navigator (jolt-nth G__53 1 jolt-nil)) (base-output (let* ((or__26__auto (jolt-invoke (var-deref "clojure.pprint" "format-simple-number") arg))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-invoke print-func arg)))) (base-width (jolt-count base-output)) (min-width (jolt-n+ base-width (jolt-get params (keyword #f "minpad")))) (width (if (jolt-n>= min-width (jolt-get params (keyword #f "mincol"))) min-width (jolt-n+ min-width (let* ((_a$1193 (jolt-n+ (let* ((_a$1191 (jolt-n- (jolt-get params (keyword #f "mincol")) min-width 1)) (_a$1192 (jolt-get params (keyword #f "colinc")))) (jolt-quot _a$1191 _a$1192)) 1)) (_a$1194 (jolt-get params (keyword #f "colinc")))) (jolt-n* _a$1193 _a$1194))))) (chars (jolt-apply (var-deref "clojure.core" "str") (let* ((_a$1195 (var-deref "clojure.core" "repeat")) (_a$1196 (jolt-n- width base-width)) (_a$1197 (jolt-get params (keyword #f "padchar")))) (jolt-invoke _a$1195 _a$1196 _a$1197))))) (begin (if (jolt-truthy? (jolt-get params (keyword #f "at"))) (jolt-invoke (var-deref "clojure.pprint" "print") (jolt-invoke (var-deref "clojure.core" "str") chars base-output)) (jolt-invoke (var-deref "clojure.pprint" "print") (jolt-invoke (var-deref "clojure.core" "str") base-output chars))) arg-navigator)))))) format-ascii) (let* ((_o$1198 (keyword #f "private")) (_o$1199 #t)) (jolt-hash-map _o$1198 _o$1199)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "integral?" (letrec ((integral? (lambda (x) (let fnrec1200 ((x x)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "integer?") x)) #t (if (jolt-truthy? (jolt-invoke (var-deref "clojure.pprint" "float?") x)) (jolt= x (host-static-call "Math" "floor" x)) (if (jolt-truthy? (keyword #f "else")) #f jolt-nil))))))) integral?) (let* ((_o$1201 (keyword #f "private")) (_o$1202 #t)) (jolt-hash-map _o$1201 _o$1202)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "remainders" (letrec ((remainders (lambda (base val) (let fnrec1203 ((base base) (val val)) (jolt-reverse (jolt-first (jolt-invoke (var-deref "clojure.pprint" "consume") (lambda (p__8_) (let fnrec1204 ((p__8_ p__8_)) (if (jolt-pos? p__8_) (let* ((_o$1205 (jolt-rem p__8_ base)) (_o$1206 (jolt-quot p__8_ base))) (jolt-vector _o$1205 _o$1206)) (let* ((_o$1207 jolt-nil) (_o$1208 jolt-nil)) (jolt-vector _o$1207 _o$1208))))) val))))))) remainders) (let* ((_o$1209 (keyword #f "private")) (_o$1210 #t)) (jolt-hash-map _o$1209 _o$1210)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "base-str" (letrec ((base-str (lambda (base val) (let fnrec1211 ((base base) (val val)) (if (jolt-zero? val) "0" (jolt-apply (var-deref "clojure.core" "str") (let* ((_a$1215 (lambda (p__9_) (let fnrec1212 ((p__9_ p__9_)) (if (jolt-n< p__9_ 10) (jolt-invoke (var-deref "clojure.core" "char") (jolt-n+ (jolt-invoke (var-deref "clojure.pprint" "char-code") (integer->char 48)) p__9_)) (jolt-invoke (var-deref "clojure.core" "char") (let* ((_a$1213 (jolt-invoke (var-deref "clojure.pprint" "char-code") (integer->char 97))) (_a$1214 (jolt-n- p__9_ 10))) (jolt-n+ _a$1213 _a$1214))))))) (_a$1216 (jolt-invoke (var-deref "clojure.pprint" "remainders") base val))) (jolt-map _a$1215 _a$1216)))))))) base-str) (let* ((_o$1217 (keyword #f "private")) (_o$1218 #t)) (jolt-hash-map _o$1217 _o$1218)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "opt-base-str" (letrec ((opt-base-str (lambda (base val) (let fnrec1219 ((base base) (val val)) (jolt-invoke (var-deref "clojure.pprint" "base-str") base val))))) opt-base-str) (let* ((_o$1220 (keyword #f "private")) (_o$1221 #t)) (jolt-hash-map _o$1220 _o$1221)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "group-by*" (letrec ((group-by* (lambda (unit lis) (let fnrec1222 ((unit unit) (lis lis)) (jolt-reverse (jolt-first (let* ((_a$1226 (var-deref "clojure.pprint" "consume")) (_a$1227 (lambda (x) (let fnrec1223 ((x x)) (let* ((_o$1224 (jolt-seq (jolt-reverse (jolt-take unit x)))) (_o$1225 (jolt-seq (jolt-drop unit x)))) (jolt-vector _o$1224 _o$1225))))) (_a$1228 (jolt-reverse lis))) (jolt-invoke _a$1226 _a$1227 _a$1228)))))))) group-by*) (let* ((_o$1229 (keyword #f "private")) (_o$1230 #t)) (jolt-hash-map _o$1229 _o$1230)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "format-integer" (letrec ((format-integer (lambda (base params arg-navigator offsets) (let fnrec1231 ((base base) (params params) (arg-navigator arg-navigator) (offsets offsets)) (let* ((G__54 (jolt-invoke (var-deref "clojure.pprint" "next-arg") arg-navigator)) (arg (jolt-nth G__54 0 jolt-nil)) (arg-navigator (jolt-nth G__54 1 jolt-nil))) (begin (if (jolt-truthy? (jolt-invoke (var-deref "clojure.pprint" "integral?") arg)) (let* ((neg (jolt-neg? arg)) (pos-arg (if (jolt-truthy? neg) (jolt-n- arg) arg)) (raw-str (jolt-invoke (var-deref "clojure.pprint" "opt-base-str") base pos-arg)) (group-str (if (jolt-truthy? (jolt-get params (keyword #f "colon"))) (let* ((groups (let* ((_a$1233 (lambda (p__10_) (let fnrec1232 ((p__10_ p__10_)) (jolt-apply (var-deref "clojure.core" "str") p__10_)))) (_a$1234 (jolt-invoke (var-deref "clojure.pprint" "group-by*") (jolt-get params (keyword #f "commainterval")) raw-str))) (jolt-map _a$1233 _a$1234))) (commas (let* ((_a$1235 (var-deref "clojure.core" "repeat")) (_a$1236 (jolt-count groups)) (_a$1237 (jolt-get params (keyword #f "commachar")))) (jolt-invoke _a$1235 _a$1236 _a$1237)))) (jolt-apply (var-deref "clojure.core" "str") (jolt-next (jolt-invoke (var-deref "clojure.core" "interleave") commas groups)))) raw-str)) (signed-str (if (jolt-truthy? neg) (jolt-invoke (var-deref "clojure.core" "str") "-" group-str) (if (jolt-truthy? (jolt-get params (keyword #f "at"))) (jolt-invoke (var-deref "clojure.core" "str") "+" group-str) (if #t group-str jolt-nil)))) (padded-str (if (let* ((_a$1238 (jolt-count signed-str)) (_a$1239 (jolt-get params (keyword #f "mincol")))) (jolt-n< _a$1238 _a$1239)) (jolt-invoke (var-deref "clojure.core" "str") (jolt-apply (var-deref "clojure.core" "str") (let* ((_a$1242 (var-deref "clojure.core" "repeat")) (_a$1243 (let* ((_a$1240 (jolt-get params (keyword #f "mincol"))) (_a$1241 (jolt-count signed-str))) (jolt-n- _a$1240 _a$1241))) (_a$1244 (jolt-get params (keyword #f "padchar")))) (jolt-invoke _a$1242 _a$1243 _a$1244))) signed-str) signed-str))) (jolt-invoke (var-deref "clojure.pprint" "print") padded-str)) (let* ((_a$1255 (var-deref "clojure.pprint" "format-ascii")) (_a$1256 (var-deref "clojure.core" "print-str")) (_a$1257 (let* ((_o$1245 (keyword #f "mincol")) (_o$1246 (jolt-get params (keyword #f "mincol"))) (_o$1247 (keyword #f "colinc")) (_o$1248 1) (_o$1249 (keyword #f "minpad")) (_o$1250 0) (_o$1251 (keyword #f "padchar")) (_o$1252 (jolt-get params (keyword #f "padchar"))) (_o$1253 (keyword #f "at")) (_o$1254 #t)) (jolt-hash-map _o$1245 _o$1246 _o$1247 _o$1248 _o$1249 _o$1250 _o$1251 _o$1252 _o$1253 _o$1254))) (_a$1258 (jolt-invoke (var-deref "clojure.pprint" "init-navigator") (jolt-vector arg))) (_a$1259 jolt-nil)) (jolt-invoke _a$1255 _a$1256 _a$1257 _a$1258 _a$1259))) arg-navigator)))))) format-integer) (let* ((_o$1260 (keyword #f "private")) (_o$1261 #t)) (jolt-hash-map _o$1260 _o$1261)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "abort?" (letrec ((abort? (lambda (context) (let fnrec1262 ((context context)) (let* ((token (jolt-first context))) (let* ((or__26__auto (jolt= (keyword #f "up-arrow") token))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt= (keyword #f "colon-up-arrow") token)))))))) abort?) (let* ((_o$1263 (keyword #f "private")) (_o$1264 #t)) (jolt-hash-map _o$1263 _o$1264)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "execute-sub-format" (letrec ((execute-sub-format (lambda (format args base-args) (let fnrec1265 ((format format) (args args) (base-args base-args)) (jolt-invoke (var-deref "clojure.core" "second") (jolt-invoke (var-deref "clojure.pprint" "map-passing-context") (lambda (element context) (let fnrec1266 ((element element) (context context)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.pprint" "abort?") context)) (let* ((_o$1267 jolt-nil) (_o$1268 context)) (jolt-vector _o$1267 _o$1268)) (let* ((G__55 (jolt-invoke (var-deref "clojure.pprint" "realize-parameter-list") (jolt-get element (keyword #f "params")) context)) (params (jolt-nth G__55 0 jolt-nil)) (args (jolt-nth G__55 1 jolt-nil)) (G__56 (jolt-invoke (var-deref "clojure.pprint" "unzip-map") params)) (params (jolt-nth G__56 0 jolt-nil)) (offsets (jolt-nth G__56 1 jolt-nil)) (params (jolt-assoc params (keyword #f "base-args") base-args))) (let* ((_o$1274 jolt-nil) (_o$1275 (let* ((_a$1272 (jolt-get element (keyword #f "func"))) (_a$1273 (let* ((_o$1269 params) (_o$1270 args) (_o$1271 offsets)) (jolt-vector _o$1269 _o$1270 _o$1271)))) (jolt-apply _a$1272 _a$1273)))) (jolt-vector _o$1274 _o$1275)))))) args format)))))) execute-sub-format) (let* ((_o$1276 (keyword #f "private")) (_o$1277 #t)) (jolt-hash-map _o$1276 _o$1277)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "choice-conditional" (letrec ((choice-conditional (lambda (params arg-navigator offsets) (let fnrec1278 ((params params) (arg-navigator arg-navigator) (offsets offsets)) (let* ((arg (jolt-get params (keyword #f "selector"))) (G__57 (if (jolt-truthy? arg) (let* ((_o$1279 arg) (_o$1280 arg-navigator)) (jolt-vector _o$1279 _o$1280)) (jolt-invoke (var-deref "clojure.pprint" "next-arg") arg-navigator))) (arg (jolt-nth G__57 0 jolt-nil)) (navigator (jolt-nth G__57 1 jolt-nil)) (clauses (jolt-get params (keyword #f "clauses"))) (clause (if (let* ((or__26__auto (jolt-neg? arg))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-n>= arg (jolt-count clauses)))) (jolt-first (jolt-get params (keyword #f "else"))) (jolt-nth clauses arg)))) (if (jolt-truthy? clause) (jolt-invoke (var-deref "clojure.pprint" "execute-sub-format") clause navigator (jolt-get params (keyword #f "base-args"))) navigator)))))) choice-conditional) (let* ((_o$1281 (keyword #f "private")) (_o$1282 #t)) (jolt-hash-map _o$1281 _o$1282)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "boolean-conditional" (letrec ((boolean-conditional (lambda (params arg-navigator offsets) (let fnrec1283 ((params params) (arg-navigator arg-navigator) (offsets offsets)) (let* ((G__58 (jolt-invoke (var-deref "clojure.pprint" "next-arg") arg-navigator)) (arg (jolt-nth G__58 0 jolt-nil)) (navigator (jolt-nth G__58 1 jolt-nil)) (clauses (jolt-get params (keyword #f "clauses"))) (clause (if (jolt-truthy? arg) (jolt-invoke (var-deref "clojure.core" "second") clauses) (jolt-first clauses)))) (if (jolt-truthy? clause) (jolt-invoke (var-deref "clojure.pprint" "execute-sub-format") clause navigator (jolt-get params (keyword #f "base-args"))) navigator)))))) boolean-conditional) (let* ((_o$1284 (keyword #f "private")) (_o$1285 #t)) (jolt-hash-map _o$1284 _o$1285)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "check-arg-conditional" (letrec ((check-arg-conditional (lambda (params arg-navigator offsets) (let fnrec1286 ((params params) (arg-navigator arg-navigator) (offsets offsets)) (let* ((G__59 (jolt-invoke (var-deref "clojure.pprint" "next-arg") arg-navigator)) (arg (jolt-nth G__59 0 jolt-nil)) (navigator (jolt-nth G__59 1 jolt-nil)) (clauses (jolt-get params (keyword #f "clauses"))) (clause (if (jolt-truthy? arg) (jolt-first clauses) jolt-nil))) (if (jolt-truthy? arg) (if (jolt-truthy? clause) (jolt-invoke (var-deref "clojure.pprint" "execute-sub-format") clause arg-navigator (jolt-get params (keyword #f "base-args"))) arg-navigator) navigator)))))) check-arg-conditional) (let* ((_o$1287 (keyword #f "private")) (_o$1288 #t)) (jolt-hash-map _o$1287 _o$1288)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "iterate-sublist" (letrec ((iterate-sublist (lambda (params navigator offsets) (let fnrec1289 ((params params) (navigator navigator) (offsets offsets)) (let* ((max-count (jolt-get params (keyword #f "max-iterations"))) (param-clause (jolt-first (jolt-get params (keyword #f "clauses")))) (G__60 (if (jolt-empty? param-clause) (jolt-invoke (var-deref "clojure.pprint" "get-format-arg") navigator) (let* ((_o$1290 param-clause) (_o$1291 navigator)) (jolt-vector _o$1290 _o$1291)))) (clause (jolt-nth G__60 0 jolt-nil)) (navigator (jolt-nth G__60 1 jolt-nil)) (G__61 (jolt-invoke (var-deref "clojure.pprint" "next-arg") navigator)) (arg-list (jolt-nth G__61 0 jolt-nil)) (navigator (jolt-nth G__61 1 jolt-nil)) (args (jolt-invoke (var-deref "clojure.pprint" "init-navigator") arg-list))) (let* ((count 0) (args args) (last-pos -1)) (let loop1292 ((count count) (args args) (last-pos last-pos)) (begin (if (let* ((and__25__auto (jolt-not max-count))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt= (jolt-get args (keyword #f "pos")) last-pos))) (if (jolt-truthy? and__25__auto) (jolt-n> count 1) and__25__auto)) and__25__auto)) (jolt-throw (host-new "Exception" "~{ construct not consuming any arguments: Infinite loop!")) jolt-nil) (if (jolt-truthy? (let* ((or__26__auto (let* ((and__25__auto (jolt-empty? (jolt-get args (keyword #f "rest"))))) (if (jolt-truthy? and__25__auto) (let* ((or__26__auto (jolt-not (jolt-get (jolt-get params (keyword #f "right-params")) (keyword #f "colon"))))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-n> count 0))) and__25__auto)))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((and__25__auto max-count)) (if (jolt-truthy? and__25__auto) (jolt-n>= count max-count) and__25__auto))))) navigator (let* ((iter-result (jolt-invoke (var-deref "clojure.pprint" "execute-sub-format") clause args (jolt-get params (keyword #f "base-args"))))) (if (jolt= (keyword #f "up-arrow") (jolt-first iter-result)) navigator (let* ((_a$1293 (jolt-inc count)) (_a$1294 iter-result) (_a$1295 (jolt-get args (keyword #f "pos")))) (loop1292 _a$1293 _a$1294 _a$1295))))))))))))) iterate-sublist) (let* ((_o$1296 (keyword #f "private")) (_o$1297 #t)) (jolt-hash-map _o$1296 _o$1297)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "iterate-list-of-sublists" (letrec ((iterate-list-of-sublists (lambda (params navigator offsets) (let fnrec1298 ((params params) (navigator navigator) (offsets offsets)) (let* ((max-count (jolt-get params (keyword #f "max-iterations"))) (param-clause (jolt-first (jolt-get params (keyword #f "clauses")))) (G__62 (if (jolt-empty? param-clause) (jolt-invoke (var-deref "clojure.pprint" "get-format-arg") navigator) (let* ((_o$1299 param-clause) (_o$1300 navigator)) (jolt-vector _o$1299 _o$1300)))) (clause (jolt-nth G__62 0 jolt-nil)) (navigator (jolt-nth G__62 1 jolt-nil)) (G__63 (jolt-invoke (var-deref "clojure.pprint" "next-arg") navigator)) (arg-list (jolt-nth G__63 0 jolt-nil)) (navigator (jolt-nth G__63 1 jolt-nil))) (let* ((count 0) (arg-list arg-list)) (let loop1301 ((count count) (arg-list arg-list)) (if (jolt-truthy? (let* ((or__26__auto (let* ((and__25__auto (jolt-empty? arg-list))) (if (jolt-truthy? and__25__auto) (let* ((or__26__auto (jolt-not (jolt-get (jolt-get params (keyword #f "right-params")) (keyword #f "colon"))))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-n> count 0))) and__25__auto)))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((and__25__auto max-count)) (if (jolt-truthy? and__25__auto) (jolt-n>= count max-count) and__25__auto))))) navigator (let* ((iter-result (let* ((_a$1302 (var-deref "clojure.pprint" "execute-sub-format")) (_a$1303 clause) (_a$1304 (jolt-invoke (var-deref "clojure.pprint" "init-navigator") (jolt-first arg-list))) (_a$1305 (jolt-invoke (var-deref "clojure.pprint" "init-navigator") (jolt-next arg-list)))) (jolt-invoke _a$1302 _a$1303 _a$1304 _a$1305)))) (if (jolt= (keyword #f "colon-up-arrow") (jolt-first iter-result)) navigator (let* ((_a$1306 (jolt-inc count)) (_a$1307 (jolt-next arg-list))) (loop1301 _a$1306 _a$1307)))))))))))) iterate-list-of-sublists) (let* ((_o$1308 (keyword #f "private")) (_o$1309 #t)) (jolt-hash-map _o$1308 _o$1309)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "iterate-main-list" (letrec ((iterate-main-list (lambda (params navigator offsets) (let fnrec1310 ((params params) (navigator navigator) (offsets offsets)) (let* ((max-count (jolt-get params (keyword #f "max-iterations"))) (param-clause (jolt-first (jolt-get params (keyword #f "clauses")))) (G__64 (if (jolt-empty? param-clause) (jolt-invoke (var-deref "clojure.pprint" "get-format-arg") navigator) (let* ((_o$1311 param-clause) (_o$1312 navigator)) (jolt-vector _o$1311 _o$1312)))) (clause (jolt-nth G__64 0 jolt-nil)) (navigator (jolt-nth G__64 1 jolt-nil))) (let* ((count 0) (navigator navigator) (last-pos -1)) (let loop1313 ((count count) (navigator navigator) (last-pos last-pos)) (begin (if (let* ((and__25__auto (jolt-not max-count))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt= (jolt-get navigator (keyword #f "pos")) last-pos))) (if (jolt-truthy? and__25__auto) (jolt-n> count 1) and__25__auto)) and__25__auto)) (jolt-throw (host-new "Exception" "~@{ construct not consuming any arguments: Infinite loop!")) jolt-nil) (if (jolt-truthy? (let* ((or__26__auto (let* ((and__25__auto (jolt-empty? (jolt-get navigator (keyword #f "rest"))))) (if (jolt-truthy? and__25__auto) (let* ((or__26__auto (jolt-not (jolt-get (jolt-get params (keyword #f "right-params")) (keyword #f "colon"))))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-n> count 0))) and__25__auto)))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((and__25__auto max-count)) (if (jolt-truthy? and__25__auto) (jolt-n>= count max-count) and__25__auto))))) navigator (let* ((iter-result (jolt-invoke (var-deref "clojure.pprint" "execute-sub-format") clause navigator (jolt-get params (keyword #f "base-args"))))) (if (jolt= (keyword #f "up-arrow") (jolt-first iter-result)) (jolt-invoke (var-deref "clojure.core" "second") iter-result) (let* ((_a$1314 (jolt-inc count)) (_a$1315 iter-result) (_a$1316 (jolt-get navigator (keyword #f "pos")))) (loop1313 _a$1314 _a$1315 _a$1316))))))))))))) iterate-main-list) (let* ((_o$1317 (keyword #f "private")) (_o$1318 #t)) (jolt-hash-map _o$1317 _o$1318)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "iterate-main-sublists" (letrec ((iterate-main-sublists (lambda (params navigator offsets) (let fnrec1319 ((params params) (navigator navigator) (offsets offsets)) (let* ((max-count (jolt-get params (keyword #f "max-iterations"))) (param-clause (jolt-first (jolt-get params (keyword #f "clauses")))) (G__65 (if (jolt-empty? param-clause) (jolt-invoke (var-deref "clojure.pprint" "get-format-arg") navigator) (let* ((_o$1320 param-clause) (_o$1321 navigator)) (jolt-vector _o$1320 _o$1321)))) (clause (jolt-nth G__65 0 jolt-nil)) (navigator (jolt-nth G__65 1 jolt-nil))) (let* ((count 0) (navigator navigator)) (let loop1322 ((count count) (navigator navigator)) (if (jolt-truthy? (let* ((or__26__auto (let* ((and__25__auto (jolt-empty? (jolt-get navigator (keyword #f "rest"))))) (if (jolt-truthy? and__25__auto) (let* ((or__26__auto (jolt-not (jolt-get (jolt-get params (keyword #f "right-params")) (keyword #f "colon"))))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-n> count 0))) and__25__auto)))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((and__25__auto max-count)) (if (jolt-truthy? and__25__auto) (jolt-n>= count max-count) and__25__auto))))) navigator (let* ((G__66 (jolt-invoke (var-deref "clojure.pprint" "next-arg-or-nil") navigator)) (sublist (jolt-nth G__66 0 jolt-nil)) (navigator (jolt-nth G__66 1 jolt-nil)) (iter-result (jolt-invoke (var-deref "clojure.pprint" "execute-sub-format") clause (jolt-invoke (var-deref "clojure.pprint" "init-navigator") sublist) navigator))) (if (jolt= (keyword #f "colon-up-arrow") (jolt-first iter-result)) navigator (loop1322 (jolt-inc count) navigator))))))))))) iterate-main-sublists) (let* ((_o$1323 (keyword #f "private")) (_o$1324 #t)) (jolt-hash-map _o$1323 _o$1324)))) -(guard (e (#t #f)) - (declare-var! "clojure.pprint" "format-logical-block")) -(guard (e (#t #f)) - (declare-var! "clojure.pprint" "justify-clauses")) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "logical-block-or-justify" (letrec ((logical-block-or-justify (lambda (params navigator offsets) (let fnrec1325 ((params params) (navigator navigator) (offsets offsets)) (if (jolt-truthy? (jolt-get (jolt-get params (keyword #f "right-params")) (keyword #f "colon"))) (jolt-invoke (var-deref "clojure.pprint" "format-logical-block") params navigator offsets) (jolt-invoke (var-deref "clojure.pprint" "justify-clauses") params navigator offsets)))))) logical-block-or-justify) (let* ((_o$1326 (keyword #f "private")) (_o$1327 #t)) (jolt-hash-map _o$1326 _o$1327)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "render-clauses" (letrec ((render-clauses (lambda (clauses navigator base-navigator) (let fnrec1328 ((clauses clauses) (navigator navigator) (base-navigator base-navigator)) (let* ((clauses clauses) (acc (jolt-vector)) (navigator navigator)) (let loop1329 ((clauses clauses) (acc acc) (navigator navigator)) (if (jolt-empty? clauses) (let* ((_o$1330 acc) (_o$1331 navigator)) (jolt-vector _o$1330 _o$1331)) (let* ((clause (jolt-first clauses)) (G__67 (let* ((sb (host-new "StringBuilder"))) (let* ((frame__20__auto (jolt-invoke (var-deref "clojure.core" "array-map") (jolt-var "clojure.core" "*out*") (jolt-invoke (var-deref "clojure.pprint" "->StringBufferWriter") sb)))) (begin (jolt-invoke (var-deref "clojure.core" "push-thread-bindings") frame__20__auto) (dynamic-wind (lambda () #f) (lambda () (let* ((_o$1332 (jolt-invoke (var-deref "clojure.pprint" "execute-sub-format") clause navigator base-navigator)) (_o$1333 (jolt-invoke (var-deref "clojure.core" "str") sb))) (jolt-vector _o$1332 _o$1333))) (lambda () (jolt-invoke (var-deref "clojure.core" "pop-thread-bindings")))))))) (iter-result (jolt-nth G__67 0 jolt-nil)) (result-str (jolt-nth G__67 1 jolt-nil))) (if (jolt= (keyword #f "up-arrow") (jolt-first iter-result)) (let* ((_o$1334 acc) (_o$1335 (jolt-invoke (var-deref "clojure.core" "second") iter-result))) (jolt-vector _o$1334 _o$1335)) (let* ((_a$1336 (jolt-next clauses)) (_a$1337 (jolt-conj acc result-str)) (_a$1338 iter-result)) (loop1329 _a$1336 _a$1337 _a$1338))))))))))) render-clauses) (let* ((_o$1339 (keyword #f "private")) (_o$1340 #t)) (jolt-hash-map _o$1339 _o$1340)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "justify-clauses" (letrec ((justify-clauses (lambda (params navigator offsets) (let fnrec1341 ((params params) (navigator navigator) (offsets offsets)) (let* ((G__68 (let* ((temp__27__auto (jolt-get params (keyword #f "else")))) (if (jolt-truthy? temp__27__auto) (let* ((_else temp__27__auto)) (jolt-invoke (var-deref "clojure.pprint" "render-clauses") _else navigator (jolt-get params (keyword #f "base-args")))) jolt-nil))) (G__69 (jolt-nth G__68 0 jolt-nil)) (eol-str (jolt-nth G__69 0 jolt-nil)) (new-navigator (jolt-nth G__68 1 jolt-nil)) (navigator (let* ((or__26__auto new-navigator)) (if (jolt-truthy? or__26__auto) or__26__auto navigator))) (G__70 (let* ((temp__27__auto (jolt-get params (keyword #f "else-params")))) (if (jolt-truthy? temp__27__auto) (let* ((p temp__27__auto)) (jolt-invoke (var-deref "clojure.pprint" "realize-parameter-list") p navigator)) jolt-nil))) (else-params (jolt-nth G__70 0 jolt-nil)) (new-navigator (jolt-nth G__70 1 jolt-nil)) (navigator (let* ((or__26__auto new-navigator)) (if (jolt-truthy? or__26__auto) or__26__auto navigator))) (min-remaining (let* ((or__26__auto (jolt-first (jolt-get else-params (keyword #f "min-remaining"))))) (if (jolt-truthy? or__26__auto) or__26__auto 0))) (max-columns (let* ((or__26__auto (jolt-first (jolt-get else-params (keyword #f "max-columns"))))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-invoke (var-deref "clojure.pprint" "get-max-column") (var-deref "clojure.core" "*out*"))))) (clauses (jolt-get params (keyword #f "clauses"))) (G__71 (jolt-invoke (var-deref "clojure.pprint" "render-clauses") clauses navigator (jolt-get params (keyword #f "base-args")))) (strs (jolt-nth G__71 0 jolt-nil)) (navigator (jolt-nth G__71 1 jolt-nil)) (slots (jolt-n-max 1 (let* ((_a$1342 (jolt-dec (jolt-count strs))) (_a$1343 (if (jolt-truthy? (jolt-get params (keyword #f "colon"))) 1 0)) (_a$1344 (if (jolt-truthy? (jolt-get params (keyword #f "at"))) 1 0))) (jolt-n+ _a$1342 _a$1343 _a$1344)))) (chars (jolt-reduce jolt-add (jolt-map jolt-count strs))) (mincol (jolt-get params (keyword #f "mincol"))) (minpad (jolt-get params (keyword #f "minpad"))) (colinc (jolt-get params (keyword #f "colinc"))) (minout (jolt-n+ chars (jolt-n* slots minpad))) (result-columns (if (jolt-n<= minout mincol) mincol (jolt-n+ mincol (jolt-n* colinc (jolt-n+ 1 (jolt-quot (jolt-n- minout mincol 1) colinc)))))) (total-pad (jolt-n- result-columns chars)) (pad (jolt-n-max minpad (jolt-quot total-pad slots))) (extra-pad (jolt-n- total-pad (jolt-n* pad slots))) (pad-str (jolt-apply (var-deref "clojure.core" "str") (jolt-invoke (var-deref "clojure.core" "repeat") pad (jolt-get params (keyword #f "padchar")))))) (begin (if (jolt-truthy? (let* ((and__25__auto eol-str)) (if (jolt-truthy? and__25__auto) (jolt-n> (jolt-n+ (jolt-invoke (var-deref "clojure.pprint" "get-column") (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch (var-deref "clojure.core" "*out*") "-fields" (jolt-vector))) (keyword #f "base"))) min-remaining result-columns) max-columns) and__25__auto))) (jolt-invoke (var-deref "clojure.pprint" "print") eol-str) jolt-nil) (let* ((slots slots) (extra-pad extra-pad) (strs strs) (pad-only (let* ((or__26__auto (jolt-get params (keyword #f "colon")))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((and__25__auto (jolt= (jolt-count strs) 1))) (if (jolt-truthy? and__25__auto) (jolt-not (jolt-get params (keyword #f "at"))) and__25__auto)))))) (let loop1345 ((slots slots) (extra-pad extra-pad) (strs strs) (pad-only pad-only)) (if (jolt-truthy? (jolt-seq strs)) (begin (jolt-invoke (var-deref "clojure.pprint" "print") (let* ((_a$1346 (var-deref "clojure.core" "str")) (_a$1347 (if (jolt-not pad-only) (jolt-first strs) jolt-nil)) (_a$1348 (if (jolt-truthy? (let* ((or__26__auto pad-only)) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt-next strs))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-get params (keyword #f "at"))))))) pad-str jolt-nil)) (_a$1349 (if (jolt-pos? extra-pad) (jolt-get params (keyword #f "padchar")) jolt-nil))) (jolt-invoke _a$1346 _a$1347 _a$1348 _a$1349))) (let* ((_a$1350 (jolt-dec slots)) (_a$1351 (jolt-dec extra-pad)) (_a$1352 (if (jolt-truthy? pad-only) strs (jolt-next strs))) (_a$1353 #f)) (loop1345 _a$1350 _a$1351 _a$1352 _a$1353))) jolt-nil))) navigator)))))) justify-clauses) (let* ((_o$1354 (keyword #f "private")) (_o$1355 #t)) (jolt-hash-map _o$1354 _o$1355)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "get-pretty-writer" (letrec ((get-pretty-writer (lambda (writer) (let fnrec1356 ((writer writer)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.pprint" "pretty-writer?") writer)) writer (jolt-invoke (var-deref "clojure.pprint" "pretty-writer") writer (var-deref "clojure.pprint" "*print-right-margin*") (var-deref "clojure.pprint" "*print-miser-width*"))))))) get-pretty-writer) (let* ((_o$1357 (keyword #f "doc")) (_o$1358 "Returns writer wrapped in a pretty writer unless it already is one.")) (jolt-hash-map _o$1357 _o$1358)))) -(guard (e (#t #f)) - (def-var! "clojure.pprint" "fresh-line" (letrec ((fresh-line (lambda () (let fnrec1359 () (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "instance-check") (jolt-symbol #f "PrettyWriter") (var-deref "clojure.core" "*out*"))) (if (jolt-not (jolt= 0 (jolt-invoke (var-deref "clojure.pprint" "get-column") (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch (var-deref "clojure.core" "*out*") "-fields" (jolt-vector))) (keyword #f "base"))))) (jolt-invoke (var-deref "clojure.pprint" "prn")) jolt-nil) (jolt-invoke (var-deref "clojure.pprint" "prn"))))))) fresh-line))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "absolute-tabulation" (letrec ((absolute-tabulation (lambda (params navigator offsets) (let fnrec1360 ((params params) (navigator navigator) (offsets offsets)) (begin (let* ((colnum (jolt-get params (keyword #f "colnum"))) (colinc (jolt-get params (keyword #f "colinc"))) (current (jolt-invoke (var-deref "clojure.pprint" "get-column") (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch (var-deref "clojure.core" "*out*") "-fields" (jolt-vector))) (keyword #f "base")))) (space-count (if (jolt-n< current colnum) (jolt-n- colnum current) (if (jolt= colinc 0) 0 (if (jolt-truthy? (keyword #f "else")) (jolt-n- colinc (jolt-rem (jolt-n- current colnum) colinc)) jolt-nil))))) (jolt-invoke (var-deref "clojure.pprint" "print") (jolt-apply (var-deref "clojure.core" "str") (jolt-invoke (var-deref "clojure.core" "repeat") space-count (integer->char 32))))) navigator))))) absolute-tabulation) (let* ((_o$1361 (keyword #f "private")) (_o$1362 #t)) (jolt-hash-map _o$1361 _o$1362)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "relative-tabulation" (letrec ((relative-tabulation (lambda (params navigator offsets) (let fnrec1363 ((params params) (navigator navigator) (offsets offsets)) (begin (let* ((colrel (jolt-get params (keyword #f "colnum"))) (colinc (jolt-get params (keyword #f "colinc"))) (start-col (jolt-n+ colrel (jolt-invoke (var-deref "clojure.pprint" "get-column") (jolt-get (jolt-invoke (var-deref "clojure.core" "deref") (record-method-dispatch (var-deref "clojure.core" "*out*") "-fields" (jolt-vector))) (keyword #f "base"))))) (offset (if (jolt-pos? colinc) (jolt-rem start-col colinc) 0)) (space-count (jolt-n+ colrel (if (jolt= 0 offset) 0 (jolt-n- colinc offset))))) (jolt-invoke (var-deref "clojure.pprint" "print") (jolt-apply (var-deref "clojure.core" "str") (jolt-invoke (var-deref "clojure.core" "repeat") space-count (integer->char 32))))) navigator))))) relative-tabulation) (let* ((_o$1364 (keyword #f "private")) (_o$1365 #t)) (jolt-hash-map _o$1364 _o$1365)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "format-logical-block" (letrec ((format-logical-block (lambda (params navigator offsets) (let fnrec1366 ((params params) (navigator navigator) (offsets offsets)) (let* ((clauses (jolt-get params (keyword #f "clauses"))) (clause-count (jolt-count clauses)) (prefix (if (jolt-n> clause-count 1) (jolt-get (jolt-get (jolt-first (jolt-first clauses)) (keyword #f "params")) (keyword #f "string")) (if (jolt-truthy? (jolt-get params (keyword #f "colon"))) "(" jolt-nil))) (body (jolt-nth clauses (if (jolt-n> clause-count 1) 1 0))) (suffix (if (jolt-n> clause-count 2) (jolt-get (jolt-get (jolt-first (jolt-nth clauses 2)) (keyword #f "params")) (keyword #f "string")) (if (jolt-truthy? (jolt-get params (keyword #f "colon"))) ")" jolt-nil))) (G__72 (jolt-invoke (var-deref "clojure.pprint" "next-arg") navigator)) (arg (jolt-nth G__72 0 jolt-nil)) (navigator (jolt-nth G__72 1 jolt-nil))) (begin (begin (if (jolt-truthy? (jolt-invoke (var-deref "clojure.pprint" "level-exceeded"))) (jolt-invoke (var-deref "clojure.pprint" "-write") (var-deref "clojure.core" "*out*") "#") (let* ((frame__20__auto (jolt-invoke (var-deref "clojure.core" "array-map") (jolt-var "clojure.pprint" "*current-level*") (jolt-inc (var-deref "clojure.pprint" "*current-level*")) (jolt-var "clojure.pprint" "*current-length*") 0))) (begin (jolt-invoke (var-deref "clojure.core" "push-thread-bindings") frame__20__auto) (dynamic-wind (lambda () #f) (lambda () (begin (jolt-invoke (var-deref "clojure.pprint" "start-block") (var-deref "clojure.core" "*out*") prefix jolt-nil suffix) (let* ((_a$1367 (var-deref "clojure.pprint" "execute-sub-format")) (_a$1368 body) (_a$1369 (jolt-invoke (var-deref "clojure.pprint" "init-navigator") arg)) (_a$1370 (jolt-get params (keyword #f "base-args")))) (jolt-invoke _a$1367 _a$1368 _a$1369 _a$1370)) (jolt-invoke (var-deref "clojure.pprint" "end-block") (var-deref "clojure.core" "*out*")))) (lambda () (jolt-invoke (var-deref "clojure.core" "pop-thread-bindings"))))))) jolt-nil) navigator)))))) format-logical-block) (let* ((_o$1371 (keyword #f "private")) (_o$1372 #t)) (jolt-hash-map _o$1371 _o$1372)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "set-indent" (letrec ((set-indent (lambda (params navigator offsets) (let fnrec1373 ((params params) (navigator navigator) (offsets offsets)) (let* ((relative-to (if (jolt-truthy? (jolt-get params (keyword #f "colon"))) (keyword #f "current") (keyword #f "block")))) (begin (jolt-invoke (var-deref "clojure.pprint" "pprint-indent") relative-to (jolt-get params (keyword #f "n"))) navigator)))))) set-indent) (let* ((_o$1374 (keyword #f "private")) (_o$1375 #t)) (jolt-hash-map _o$1374 _o$1375)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "conditional-newline" (letrec ((conditional-newline (lambda (params navigator offsets) (let fnrec1376 ((params params) (navigator navigator) (offsets offsets)) (let* ((kind (if (jolt-truthy? (jolt-get params (keyword #f "colon"))) (if (jolt-truthy? (jolt-get params (keyword #f "at"))) (keyword #f "mandatory") (keyword #f "fill")) (if (jolt-truthy? (jolt-get params (keyword #f "at"))) (keyword #f "miser") (keyword #f "linear"))))) (begin (jolt-invoke (var-deref "clojure.pprint" "pprint-newline") kind) navigator)))))) conditional-newline) (let* ((_o$1377 (keyword #f "private")) (_o$1378 #t)) (jolt-hash-map _o$1377 _o$1378)))) -(guard (e (#t #f)) - (def-var! "clojure.pprint" "defdirectives" - (lambda directives (let fnrec1379 ((directives (list->cseq directives))) (let* ((process (lambda (G__73) (let fnrec1380 ((G__73 G__73)) (let* ((G__74 G__73) (char (jolt-nth G__74 0 jolt-nil)) (params (jolt-nth G__74 1 jolt-nil)) (flags (jolt-nth G__74 2 jolt-nil)) (bracket-info (jolt-nth G__74 3 jolt-nil)) (generator-fn (jolt-invoke (var-deref "clojure.core" "nthnext") G__74 4))) (let* ((_o$1391 char) (_o$1392 (let* ((_o$1381 (keyword #f "directive")) (_o$1382 char) (_o$1383 (keyword #f "params")) (_o$1384 (jolt-invoke (var-deref "clojure.core" "__sqcat") (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "array-map")) params)) (_o$1385 (keyword #f "flags")) (_o$1386 flags) (_o$1387 (keyword #f "bracket-info")) (_o$1388 bracket-info) (_o$1389 (keyword #f "generator-fn")) (_o$1390 (jolt-concat (jolt-list (jolt-symbol #f "fn") (jolt-vector (jolt-symbol #f "params") (jolt-symbol #f "offset"))) generator-fn))) (jolt-hash-map _o$1381 _o$1382 _o$1383 _o$1384 _o$1385 _o$1386 _o$1387 _o$1388 _o$1389 _o$1390)))) (jolt-vector _o$1391 _o$1392))))))) (let* ((_a$1396 (var-deref "clojure.core" "__sqcat")) (_a$1397 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "def"))) (_a$1398 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "directive-table"))) (_a$1399 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1393 (var-deref "clojure.core" "__sqcat")) (_a$1394 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "hash-map"))) (_a$1395 (jolt-invoke (var-deref "clojure.core" "mapcat") process directives))) (jolt-invoke _a$1393 _a$1394 _a$1395))))) (jolt-invoke _a$1396 _a$1397 _a$1398 _a$1399)))))) - (mark-macro! "clojure.pprint" "defdirectives")) -(guard (e (#t #f)) - (def-var! "clojure.pprint" "directive-table" (let* ((_a$1952 (integer->char 65)) (_a$1953 (let* ((_o$1422 (keyword #f "directive")) (_o$1423 (integer->char 65)) (_o$1424 (keyword #f "params")) (_o$1425 (let* ((_a$1408 (var-deref "clojure.core" "array-map")) (_a$1409 (keyword #f "mincol")) (_a$1410 (let* ((_o$1400 0) (_o$1401 (var-deref "clojure.core" "Long"))) (jolt-vector _o$1400 _o$1401))) (_a$1411 (keyword #f "colinc")) (_a$1412 (let* ((_o$1402 1) (_o$1403 (var-deref "clojure.core" "Long"))) (jolt-vector _o$1402 _o$1403))) (_a$1413 (keyword #f "minpad")) (_a$1414 (let* ((_o$1404 0) (_o$1405 (var-deref "clojure.core" "Long"))) (jolt-vector _o$1404 _o$1405))) (_a$1415 (keyword #f "padchar")) (_a$1416 (let* ((_o$1406 (integer->char 32)) (_o$1407 (var-deref "clojure.core" "Character"))) (jolt-vector _o$1406 _o$1407)))) (jolt-invoke _a$1408 _a$1409 _a$1410 _a$1411 _a$1412 _a$1413 _a$1414 _a$1415 _a$1416))) (_o$1426 (keyword #f "flags")) (_o$1427 (let* ((_o$1417 (keyword #f "at")) (_o$1418 (keyword #f "colon")) (_o$1419 (keyword #f "both"))) (jolt-hash-set _o$1417 _o$1418 _o$1419))) (_o$1428 (keyword #f "bracket-info")) (_o$1429 (jolt-hash-map)) (_o$1430 (keyword #f "generator-fn")) (_o$1431 (lambda (params offset) (let fnrec1420 ((params params) (offset offset)) (lambda (p__11_ p__12_ p__13_) (let fnrec1421 ((p__11_ p__11_) (p__12_ p__12_) (p__13_ p__13_)) (jolt-invoke (var-deref "clojure.pprint" "format-ascii") (var-deref "clojure.core" "print-str") p__11_ p__12_ p__13_))))))) (jolt-hash-map _o$1422 _o$1423 _o$1424 _o$1425 _o$1426 _o$1427 _o$1428 _o$1429 _o$1430 _o$1431))) (_a$1954 (integer->char 83)) (_a$1955 (let* ((_o$1454 (keyword #f "directive")) (_o$1455 (integer->char 83)) (_o$1456 (keyword #f "params")) (_o$1457 (let* ((_a$1440 (var-deref "clojure.core" "array-map")) (_a$1441 (keyword #f "mincol")) (_a$1442 (let* ((_o$1432 0) (_o$1433 (var-deref "clojure.core" "Long"))) (jolt-vector _o$1432 _o$1433))) (_a$1443 (keyword #f "colinc")) (_a$1444 (let* ((_o$1434 1) (_o$1435 (var-deref "clojure.core" "Long"))) (jolt-vector _o$1434 _o$1435))) (_a$1445 (keyword #f "minpad")) (_a$1446 (let* ((_o$1436 0) (_o$1437 (var-deref "clojure.core" "Long"))) (jolt-vector _o$1436 _o$1437))) (_a$1447 (keyword #f "padchar")) (_a$1448 (let* ((_o$1438 (integer->char 32)) (_o$1439 (var-deref "clojure.core" "Character"))) (jolt-vector _o$1438 _o$1439)))) (jolt-invoke _a$1440 _a$1441 _a$1442 _a$1443 _a$1444 _a$1445 _a$1446 _a$1447 _a$1448))) (_o$1458 (keyword #f "flags")) (_o$1459 (let* ((_o$1449 (keyword #f "at")) (_o$1450 (keyword #f "colon")) (_o$1451 (keyword #f "both"))) (jolt-hash-set _o$1449 _o$1450 _o$1451))) (_o$1460 (keyword #f "bracket-info")) (_o$1461 (jolt-hash-map)) (_o$1462 (keyword #f "generator-fn")) (_o$1463 (lambda (params offset) (let fnrec1452 ((params params) (offset offset)) (lambda (p__14_ p__15_ p__16_) (let fnrec1453 ((p__14_ p__14_) (p__15_ p__15_) (p__16_ p__16_)) (jolt-invoke (var-deref "clojure.pprint" "format-ascii") (var-deref "clojure.core" "pr-str") p__14_ p__15_ p__16_))))))) (jolt-hash-map _o$1454 _o$1455 _o$1456 _o$1457 _o$1458 _o$1459 _o$1460 _o$1461 _o$1462 _o$1463))) (_a$1956 (integer->char 68)) (_a$1957 (let* ((_o$1486 (keyword #f "directive")) (_o$1487 (integer->char 68)) (_o$1488 (keyword #f "params")) (_o$1489 (let* ((_a$1472 (var-deref "clojure.core" "array-map")) (_a$1473 (keyword #f "mincol")) (_a$1474 (let* ((_o$1464 0) (_o$1465 (var-deref "clojure.core" "Long"))) (jolt-vector _o$1464 _o$1465))) (_a$1475 (keyword #f "padchar")) (_a$1476 (let* ((_o$1466 (integer->char 32)) (_o$1467 (var-deref "clojure.core" "Character"))) (jolt-vector _o$1466 _o$1467))) (_a$1477 (keyword #f "commachar")) (_a$1478 (let* ((_o$1468 (integer->char 44)) (_o$1469 (var-deref "clojure.core" "Character"))) (jolt-vector _o$1468 _o$1469))) (_a$1479 (keyword #f "commainterval")) (_a$1480 (let* ((_o$1470 3) (_o$1471 (var-deref "clojure.core" "Long"))) (jolt-vector _o$1470 _o$1471)))) (jolt-invoke _a$1472 _a$1473 _a$1474 _a$1475 _a$1476 _a$1477 _a$1478 _a$1479 _a$1480))) (_o$1490 (keyword #f "flags")) (_o$1491 (let* ((_o$1481 (keyword #f "at")) (_o$1482 (keyword #f "colon")) (_o$1483 (keyword #f "both"))) (jolt-hash-set _o$1481 _o$1482 _o$1483))) (_o$1492 (keyword #f "bracket-info")) (_o$1493 (jolt-hash-map)) (_o$1494 (keyword #f "generator-fn")) (_o$1495 (lambda (params offset) (let fnrec1484 ((params params) (offset offset)) (lambda (p__17_ p__18_ p__19_) (let fnrec1485 ((p__17_ p__17_) (p__18_ p__18_) (p__19_ p__19_)) (jolt-invoke (var-deref "clojure.pprint" "format-integer") 10 p__17_ p__18_ p__19_))))))) (jolt-hash-map _o$1486 _o$1487 _o$1488 _o$1489 _o$1490 _o$1491 _o$1492 _o$1493 _o$1494 _o$1495))) (_a$1958 (integer->char 66)) (_a$1959 (let* ((_o$1518 (keyword #f "directive")) (_o$1519 (integer->char 66)) (_o$1520 (keyword #f "params")) (_o$1521 (let* ((_a$1504 (var-deref "clojure.core" "array-map")) (_a$1505 (keyword #f "mincol")) (_a$1506 (let* ((_o$1496 0) (_o$1497 (var-deref "clojure.core" "Long"))) (jolt-vector _o$1496 _o$1497))) (_a$1507 (keyword #f "padchar")) (_a$1508 (let* ((_o$1498 (integer->char 32)) (_o$1499 (var-deref "clojure.core" "Character"))) (jolt-vector _o$1498 _o$1499))) (_a$1509 (keyword #f "commachar")) (_a$1510 (let* ((_o$1500 (integer->char 44)) (_o$1501 (var-deref "clojure.core" "Character"))) (jolt-vector _o$1500 _o$1501))) (_a$1511 (keyword #f "commainterval")) (_a$1512 (let* ((_o$1502 3) (_o$1503 (var-deref "clojure.core" "Long"))) (jolt-vector _o$1502 _o$1503)))) (jolt-invoke _a$1504 _a$1505 _a$1506 _a$1507 _a$1508 _a$1509 _a$1510 _a$1511 _a$1512))) (_o$1522 (keyword #f "flags")) (_o$1523 (let* ((_o$1513 (keyword #f "at")) (_o$1514 (keyword #f "colon")) (_o$1515 (keyword #f "both"))) (jolt-hash-set _o$1513 _o$1514 _o$1515))) (_o$1524 (keyword #f "bracket-info")) (_o$1525 (jolt-hash-map)) (_o$1526 (keyword #f "generator-fn")) (_o$1527 (lambda (params offset) (let fnrec1516 ((params params) (offset offset)) (lambda (p__20_ p__21_ p__22_) (let fnrec1517 ((p__20_ p__20_) (p__21_ p__21_) (p__22_ p__22_)) (jolt-invoke (var-deref "clojure.pprint" "format-integer") 2 p__20_ p__21_ p__22_))))))) (jolt-hash-map _o$1518 _o$1519 _o$1520 _o$1521 _o$1522 _o$1523 _o$1524 _o$1525 _o$1526 _o$1527))) (_a$1960 (integer->char 79)) (_a$1961 (let* ((_o$1550 (keyword #f "directive")) (_o$1551 (integer->char 79)) (_o$1552 (keyword #f "params")) (_o$1553 (let* ((_a$1536 (var-deref "clojure.core" "array-map")) (_a$1537 (keyword #f "mincol")) (_a$1538 (let* ((_o$1528 0) (_o$1529 (var-deref "clojure.core" "Long"))) (jolt-vector _o$1528 _o$1529))) (_a$1539 (keyword #f "padchar")) (_a$1540 (let* ((_o$1530 (integer->char 32)) (_o$1531 (var-deref "clojure.core" "Character"))) (jolt-vector _o$1530 _o$1531))) (_a$1541 (keyword #f "commachar")) (_a$1542 (let* ((_o$1532 (integer->char 44)) (_o$1533 (var-deref "clojure.core" "Character"))) (jolt-vector _o$1532 _o$1533))) (_a$1543 (keyword #f "commainterval")) (_a$1544 (let* ((_o$1534 3) (_o$1535 (var-deref "clojure.core" "Long"))) (jolt-vector _o$1534 _o$1535)))) (jolt-invoke _a$1536 _a$1537 _a$1538 _a$1539 _a$1540 _a$1541 _a$1542 _a$1543 _a$1544))) (_o$1554 (keyword #f "flags")) (_o$1555 (let* ((_o$1545 (keyword #f "at")) (_o$1546 (keyword #f "colon")) (_o$1547 (keyword #f "both"))) (jolt-hash-set _o$1545 _o$1546 _o$1547))) (_o$1556 (keyword #f "bracket-info")) (_o$1557 (jolt-hash-map)) (_o$1558 (keyword #f "generator-fn")) (_o$1559 (lambda (params offset) (let fnrec1548 ((params params) (offset offset)) (lambda (p__23_ p__24_ p__25_) (let fnrec1549 ((p__23_ p__23_) (p__24_ p__24_) (p__25_ p__25_)) (jolt-invoke (var-deref "clojure.pprint" "format-integer") 8 p__23_ p__24_ p__25_))))))) (jolt-hash-map _o$1550 _o$1551 _o$1552 _o$1553 _o$1554 _o$1555 _o$1556 _o$1557 _o$1558 _o$1559))) (_a$1962 (integer->char 88)) (_a$1963 (let* ((_o$1582 (keyword #f "directive")) (_o$1583 (integer->char 88)) (_o$1584 (keyword #f "params")) (_o$1585 (let* ((_a$1568 (var-deref "clojure.core" "array-map")) (_a$1569 (keyword #f "mincol")) (_a$1570 (let* ((_o$1560 0) (_o$1561 (var-deref "clojure.core" "Long"))) (jolt-vector _o$1560 _o$1561))) (_a$1571 (keyword #f "padchar")) (_a$1572 (let* ((_o$1562 (integer->char 32)) (_o$1563 (var-deref "clojure.core" "Character"))) (jolt-vector _o$1562 _o$1563))) (_a$1573 (keyword #f "commachar")) (_a$1574 (let* ((_o$1564 (integer->char 44)) (_o$1565 (var-deref "clojure.core" "Character"))) (jolt-vector _o$1564 _o$1565))) (_a$1575 (keyword #f "commainterval")) (_a$1576 (let* ((_o$1566 3) (_o$1567 (var-deref "clojure.core" "Long"))) (jolt-vector _o$1566 _o$1567)))) (jolt-invoke _a$1568 _a$1569 _a$1570 _a$1571 _a$1572 _a$1573 _a$1574 _a$1575 _a$1576))) (_o$1586 (keyword #f "flags")) (_o$1587 (let* ((_o$1577 (keyword #f "at")) (_o$1578 (keyword #f "colon")) (_o$1579 (keyword #f "both"))) (jolt-hash-set _o$1577 _o$1578 _o$1579))) (_o$1588 (keyword #f "bracket-info")) (_o$1589 (jolt-hash-map)) (_o$1590 (keyword #f "generator-fn")) (_o$1591 (lambda (params offset) (let fnrec1580 ((params params) (offset offset)) (lambda (p__26_ p__27_ p__28_) (let fnrec1581 ((p__26_ p__26_) (p__27_ p__27_) (p__28_ p__28_)) (jolt-invoke (var-deref "clojure.pprint" "format-integer") 16 p__26_ p__27_ p__28_))))))) (jolt-hash-map _o$1582 _o$1583 _o$1584 _o$1585 _o$1586 _o$1587 _o$1588 _o$1589 _o$1590 _o$1591))) (_a$1964 (integer->char 37)) (_a$1965 (let* ((_o$1597 (keyword #f "directive")) (_o$1598 (integer->char 37)) (_o$1599 (keyword #f "params")) (_o$1600 (jolt-invoke (var-deref "clojure.core" "array-map") (keyword #f "count") (let* ((_o$1592 1) (_o$1593 (var-deref "clojure.core" "Long"))) (jolt-vector _o$1592 _o$1593)))) (_o$1601 (keyword #f "flags")) (_o$1602 (jolt-hash-set)) (_o$1603 (keyword #f "bracket-info")) (_o$1604 (jolt-hash-map)) (_o$1605 (keyword #f "generator-fn")) (_o$1606 (lambda (params offset) (let fnrec1594 ((params params) (offset offset)) (lambda (params arg-navigator offsets) (let fnrec1595 ((params params) (arg-navigator arg-navigator) (offsets offsets)) (begin (let* ((n__19__auto (jolt-get params (keyword #f "count")))) (let* ((i 0)) (let loop1596 ((i i)) (if (jolt-n< i n__19__auto) (begin (jolt-invoke (var-deref "clojure.pprint" "prn")) (loop1596 (jolt-inc i))) jolt-nil)))) arg-navigator))))))) (jolt-hash-map _o$1597 _o$1598 _o$1599 _o$1600 _o$1601 _o$1602 _o$1603 _o$1604 _o$1605 _o$1606))) (_a$1966 (integer->char 38)) (_a$1967 (let* ((_o$1612 (keyword #f "directive")) (_o$1613 (integer->char 38)) (_o$1614 (keyword #f "params")) (_o$1615 (jolt-invoke (var-deref "clojure.core" "array-map") (keyword #f "count") (let* ((_o$1607 1) (_o$1608 (var-deref "clojure.core" "Long"))) (jolt-vector _o$1607 _o$1608)))) (_o$1616 (keyword #f "flags")) (_o$1617 (jolt-hash-set (keyword #f "pretty"))) (_o$1618 (keyword #f "bracket-info")) (_o$1619 (jolt-hash-map)) (_o$1620 (keyword #f "generator-fn")) (_o$1621 (lambda (params offset) (let fnrec1609 ((params params) (offset offset)) (lambda (params arg-navigator offsets) (let fnrec1610 ((params params) (arg-navigator arg-navigator) (offsets offsets)) (begin (let* ((cnt (jolt-get params (keyword #f "count")))) (begin (if (jolt-pos? cnt) (jolt-invoke (var-deref "clojure.pprint" "fresh-line")) jolt-nil) (let* ((n__19__auto (jolt-dec cnt))) (let* ((i 0)) (let loop1611 ((i i)) (if (jolt-n< i n__19__auto) (begin (jolt-invoke (var-deref "clojure.pprint" "prn")) (loop1611 (jolt-inc i))) jolt-nil)))))) arg-navigator))))))) (jolt-hash-map _o$1612 _o$1613 _o$1614 _o$1615 _o$1616 _o$1617 _o$1618 _o$1619 _o$1620 _o$1621))) (_a$1968 (integer->char 124)) (_a$1969 (let* ((_o$1627 (keyword #f "directive")) (_o$1628 (integer->char 124)) (_o$1629 (keyword #f "params")) (_o$1630 (jolt-invoke (var-deref "clojure.core" "array-map") (keyword #f "count") (let* ((_o$1622 1) (_o$1623 (var-deref "clojure.core" "Long"))) (jolt-vector _o$1622 _o$1623)))) (_o$1631 (keyword #f "flags")) (_o$1632 (jolt-hash-set)) (_o$1633 (keyword #f "bracket-info")) (_o$1634 (jolt-hash-map)) (_o$1635 (keyword #f "generator-fn")) (_o$1636 (lambda (params offset) (let fnrec1624 ((params params) (offset offset)) (lambda (params arg-navigator offsets) (let fnrec1625 ((params params) (arg-navigator arg-navigator) (offsets offsets)) (begin (let* ((n__19__auto (jolt-get params (keyword #f "count")))) (let* ((i 0)) (let loop1626 ((i i)) (if (jolt-n< i n__19__auto) (begin (jolt-invoke (var-deref "clojure.pprint" "print") (integer->char 12)) (loop1626 (jolt-inc i))) jolt-nil)))) arg-navigator))))))) (jolt-hash-map _o$1627 _o$1628 _o$1629 _o$1630 _o$1631 _o$1632 _o$1633 _o$1634 _o$1635 _o$1636))) (_a$1970 (integer->char 126)) (_a$1971 (let* ((_o$1641 (keyword #f "directive")) (_o$1642 (integer->char 126)) (_o$1643 (keyword #f "params")) (_o$1644 (jolt-invoke (var-deref "clojure.core" "array-map") (keyword #f "n") (let* ((_o$1637 1) (_o$1638 (var-deref "clojure.core" "Long"))) (jolt-vector _o$1637 _o$1638)))) (_o$1645 (keyword #f "flags")) (_o$1646 (jolt-hash-set)) (_o$1647 (keyword #f "bracket-info")) (_o$1648 (jolt-hash-map)) (_o$1649 (keyword #f "generator-fn")) (_o$1650 (lambda (params offset) (let fnrec1639 ((params params) (offset offset)) (lambda (params arg-navigator offsets) (let fnrec1640 ((params params) (arg-navigator arg-navigator) (offsets offsets)) (let* ((n (jolt-get params (keyword #f "n")))) (begin (jolt-invoke (var-deref "clojure.pprint" "print") (jolt-apply (var-deref "clojure.core" "str") (jolt-invoke (var-deref "clojure.core" "repeat") n (integer->char 126)))) arg-navigator)))))))) (jolt-hash-map _o$1641 _o$1642 _o$1643 _o$1644 _o$1645 _o$1646 _o$1647 _o$1648 _o$1649 _o$1650))) (_a$1972 (integer->char 10)) (_a$1973 (let* ((_o$1655 (keyword #f "directive")) (_o$1656 (integer->char 10)) (_o$1657 (keyword #f "params")) (_o$1658 (jolt-invoke (var-deref "clojure.core" "array-map"))) (_o$1659 (keyword #f "flags")) (_o$1660 (let* ((_o$1651 (keyword #f "colon")) (_o$1652 (keyword #f "at"))) (jolt-hash-set _o$1651 _o$1652))) (_o$1661 (keyword #f "bracket-info")) (_o$1662 (jolt-hash-map)) (_o$1663 (keyword #f "generator-fn")) (_o$1664 (lambda (params offset) (let fnrec1653 ((params params) (offset offset)) (lambda (params arg-navigator offsets) (let fnrec1654 ((params params) (arg-navigator arg-navigator) (offsets offsets)) (begin (if (jolt-truthy? (jolt-get params (keyword #f "at"))) (jolt-invoke (var-deref "clojure.pprint" "prn")) jolt-nil) arg-navigator))))))) (jolt-hash-map _o$1655 _o$1656 _o$1657 _o$1658 _o$1659 _o$1660 _o$1661 _o$1662 _o$1663 _o$1664))) (_a$1974 (integer->char 84)) (_a$1975 (let* ((_o$1679 (keyword #f "directive")) (_o$1680 (integer->char 84)) (_o$1681 (keyword #f "params")) (_o$1682 (let* ((_a$1669 (var-deref "clojure.core" "array-map")) (_a$1670 (keyword #f "colnum")) (_a$1671 (let* ((_o$1665 1) (_o$1666 (var-deref "clojure.core" "Long"))) (jolt-vector _o$1665 _o$1666))) (_a$1672 (keyword #f "colinc")) (_a$1673 (let* ((_o$1667 1) (_o$1668 (var-deref "clojure.core" "Long"))) (jolt-vector _o$1667 _o$1668)))) (jolt-invoke _a$1669 _a$1670 _a$1671 _a$1672 _a$1673))) (_o$1683 (keyword #f "flags")) (_o$1684 (let* ((_o$1674 (keyword #f "at")) (_o$1675 (keyword #f "pretty"))) (jolt-hash-set _o$1674 _o$1675))) (_o$1685 (keyword #f "bracket-info")) (_o$1686 (jolt-hash-map)) (_o$1687 (keyword #f "generator-fn")) (_o$1688 (lambda (params offset) (let fnrec1676 ((params params) (offset offset)) (if (jolt-truthy? (jolt-get params (keyword #f "at"))) (lambda (p__29_ p__30_ p__31_) (let fnrec1677 ((p__29_ p__29_) (p__30_ p__30_) (p__31_ p__31_)) (jolt-invoke (var-deref "clojure.pprint" "relative-tabulation") p__29_ p__30_ p__31_))) (lambda (p__32_ p__33_ p__34_) (let fnrec1678 ((p__32_ p__32_) (p__33_ p__33_) (p__34_ p__34_)) (jolt-invoke (var-deref "clojure.pprint" "absolute-tabulation") p__32_ p__33_ p__34_)))))))) (jolt-hash-map _o$1679 _o$1680 _o$1681 _o$1682 _o$1683 _o$1684 _o$1685 _o$1686 _o$1687 _o$1688))) (_a$1976 (integer->char 42)) (_a$1977 (let* ((_o$1695 (keyword #f "directive")) (_o$1696 (integer->char 42)) (_o$1697 (keyword #f "params")) (_o$1698 (jolt-invoke (var-deref "clojure.core" "array-map") (keyword #f "n") (let* ((_o$1689 1) (_o$1690 (var-deref "clojure.core" "Long"))) (jolt-vector _o$1689 _o$1690)))) (_o$1699 (keyword #f "flags")) (_o$1700 (let* ((_o$1691 (keyword #f "colon")) (_o$1692 (keyword #f "at"))) (jolt-hash-set _o$1691 _o$1692))) (_o$1701 (keyword #f "bracket-info")) (_o$1702 (jolt-hash-map)) (_o$1703 (keyword #f "generator-fn")) (_o$1704 (lambda (params offset) (let fnrec1693 ((params params) (offset offset)) (lambda (params navigator offsets) (let fnrec1694 ((params params) (navigator navigator) (offsets offsets)) (let* ((n (jolt-get params (keyword #f "n")))) (if (jolt-truthy? (jolt-get params (keyword #f "at"))) (jolt-invoke (var-deref "clojure.pprint" "absolute-reposition") navigator n) (jolt-invoke (var-deref "clojure.pprint" "relative-reposition") navigator (if (jolt-truthy? (jolt-get params (keyword #f "colon"))) (jolt-n- n) n)))))))))) (jolt-hash-map _o$1695 _o$1696 _o$1697 _o$1698 _o$1699 _o$1700 _o$1701 _o$1702 _o$1703 _o$1704))) (_a$1978 (integer->char 63)) (_a$1979 (let* ((_o$1708 (keyword #f "directive")) (_o$1709 (integer->char 63)) (_o$1710 (keyword #f "params")) (_o$1711 (jolt-invoke (var-deref "clojure.core" "array-map"))) (_o$1712 (keyword #f "flags")) (_o$1713 (jolt-hash-set (keyword #f "at"))) (_o$1714 (keyword #f "bracket-info")) (_o$1715 (jolt-hash-map)) (_o$1716 (keyword #f "generator-fn")) (_o$1717 (lambda (params offset) (let fnrec1705 ((params params) (offset offset)) (if (jolt-truthy? (jolt-get params (keyword #f "at"))) (lambda (params navigator offsets) (let fnrec1706 ((params params) (navigator navigator) (offsets offsets)) (let* ((G__75 (jolt-invoke (var-deref "clojure.pprint" "get-format-arg") navigator)) (subformat (jolt-nth G__75 0 jolt-nil)) (navigator (jolt-nth G__75 1 jolt-nil))) (jolt-invoke (var-deref "clojure.pprint" "execute-sub-format") subformat navigator (jolt-get params (keyword #f "base-args")))))) (lambda (params navigator offsets) (let fnrec1707 ((params params) (navigator navigator) (offsets offsets)) (let* ((G__76 (jolt-invoke (var-deref "clojure.pprint" "get-format-arg") navigator)) (subformat (jolt-nth G__76 0 jolt-nil)) (navigator (jolt-nth G__76 1 jolt-nil)) (G__77 (jolt-invoke (var-deref "clojure.pprint" "next-arg") navigator)) (subargs (jolt-nth G__77 0 jolt-nil)) (navigator (jolt-nth G__77 1 jolt-nil)) (sub-navigator (jolt-invoke (var-deref "clojure.pprint" "init-navigator") subargs))) (begin (jolt-invoke (var-deref "clojure.pprint" "execute-sub-format") subformat sub-navigator (jolt-get params (keyword #f "base-args"))) navigator))))))))) (jolt-hash-map _o$1708 _o$1709 _o$1710 _o$1711 _o$1712 _o$1713 _o$1714 _o$1715 _o$1716 _o$1717))) (_a$1980 (integer->char 41)) (_a$1981 (let* ((_o$1719 (keyword #f "directive")) (_o$1720 (integer->char 41)) (_o$1721 (keyword #f "params")) (_o$1722 (jolt-invoke (var-deref "clojure.core" "array-map"))) (_o$1723 (keyword #f "flags")) (_o$1724 (jolt-hash-set)) (_o$1725 (keyword #f "bracket-info")) (_o$1726 (jolt-hash-map)) (_o$1727 (keyword #f "generator-fn")) (_o$1728 (lambda (params offset) (let fnrec1718 ((params params) (offset offset)) jolt-nil)))) (jolt-hash-map _o$1719 _o$1720 _o$1721 _o$1722 _o$1723 _o$1724 _o$1725 _o$1726 _o$1727 _o$1728))) (_a$1982 (integer->char 91)) (_a$1983 (let* ((_o$1740 (keyword #f "directive")) (_o$1741 (integer->char 91)) (_o$1742 (keyword #f "params")) (_o$1743 (jolt-invoke (var-deref "clojure.core" "array-map") (keyword #f "selector") (let* ((_o$1729 jolt-nil) (_o$1730 (var-deref "clojure.core" "Long"))) (jolt-vector _o$1729 _o$1730)))) (_o$1744 (keyword #f "flags")) (_o$1745 (let* ((_o$1731 (keyword #f "colon")) (_o$1732 (keyword #f "at"))) (jolt-hash-set _o$1731 _o$1732))) (_o$1746 (keyword #f "bracket-info")) (_o$1747 (let* ((_o$1733 (keyword #f "right")) (_o$1734 (integer->char 93)) (_o$1735 (keyword #f "allows-separator")) (_o$1736 #t) (_o$1737 (keyword #f "else")) (_o$1738 (keyword #f "last"))) (jolt-hash-map _o$1733 _o$1734 _o$1735 _o$1736 _o$1737 _o$1738))) (_o$1748 (keyword #f "generator-fn")) (_o$1749 (lambda (params offset) (let fnrec1739 ((params params) (offset offset)) (if (jolt-truthy? (jolt-get params (keyword #f "colon"))) (var-deref "clojure.pprint" "boolean-conditional") (if (jolt-truthy? (jolt-get params (keyword #f "at"))) (var-deref "clojure.pprint" "check-arg-conditional") (if #t (var-deref "clojure.pprint" "choice-conditional") jolt-nil))))))) (jolt-hash-map _o$1740 _o$1741 _o$1742 _o$1743 _o$1744 _o$1745 _o$1746 _o$1747 _o$1748 _o$1749))) (_a$1984 (integer->char 59)) (_a$1985 (let* ((_o$1762 (keyword #f "directive")) (_o$1763 (integer->char 59)) (_o$1764 (keyword #f "params")) (_o$1765 (let* ((_a$1754 (var-deref "clojure.core" "array-map")) (_a$1755 (keyword #f "min-remaining")) (_a$1756 (let* ((_o$1750 jolt-nil) (_o$1751 (var-deref "clojure.core" "Long"))) (jolt-vector _o$1750 _o$1751))) (_a$1757 (keyword #f "max-columns")) (_a$1758 (let* ((_o$1752 jolt-nil) (_o$1753 (var-deref "clojure.core" "Long"))) (jolt-vector _o$1752 _o$1753)))) (jolt-invoke _a$1754 _a$1755 _a$1756 _a$1757 _a$1758))) (_o$1766 (keyword #f "flags")) (_o$1767 (jolt-hash-set (keyword #f "colon"))) (_o$1768 (keyword #f "bracket-info")) (_o$1769 (let* ((_o$1759 (keyword #f "separator")) (_o$1760 #t)) (jolt-hash-map _o$1759 _o$1760))) (_o$1770 (keyword #f "generator-fn")) (_o$1771 (lambda (params offset) (let fnrec1761 ((params params) (offset offset)) jolt-nil)))) (jolt-hash-map _o$1762 _o$1763 _o$1764 _o$1765 _o$1766 _o$1767 _o$1768 _o$1769 _o$1770 _o$1771))) (_a$1986 (integer->char 93)) (_a$1987 (let* ((_o$1773 (keyword #f "directive")) (_o$1774 (integer->char 93)) (_o$1775 (keyword #f "params")) (_o$1776 (jolt-invoke (var-deref "clojure.core" "array-map"))) (_o$1777 (keyword #f "flags")) (_o$1778 (jolt-hash-set)) (_o$1779 (keyword #f "bracket-info")) (_o$1780 (jolt-hash-map)) (_o$1781 (keyword #f "generator-fn")) (_o$1782 (lambda (params offset) (let fnrec1772 ((params params) (offset offset)) jolt-nil)))) (jolt-hash-map _o$1773 _o$1774 _o$1775 _o$1776 _o$1777 _o$1778 _o$1779 _o$1780 _o$1781 _o$1782))) (_a$1988 (integer->char 123)) (_a$1989 (let* ((_o$1793 (keyword #f "directive")) (_o$1794 (integer->char 123)) (_o$1795 (keyword #f "params")) (_o$1796 (jolt-invoke (var-deref "clojure.core" "array-map") (keyword #f "max-iterations") (let* ((_o$1783 jolt-nil) (_o$1784 (var-deref "clojure.core" "Long"))) (jolt-vector _o$1783 _o$1784)))) (_o$1797 (keyword #f "flags")) (_o$1798 (let* ((_o$1785 (keyword #f "colon")) (_o$1786 (keyword #f "at")) (_o$1787 (keyword #f "both"))) (jolt-hash-set _o$1785 _o$1786 _o$1787))) (_o$1799 (keyword #f "bracket-info")) (_o$1800 (let* ((_o$1788 (keyword #f "right")) (_o$1789 (integer->char 125)) (_o$1790 (keyword #f "allows-separator")) (_o$1791 #f)) (jolt-hash-map _o$1788 _o$1789 _o$1790 _o$1791))) (_o$1801 (keyword #f "generator-fn")) (_o$1802 (lambda (params offset) (let fnrec1792 ((params params) (offset offset)) (if (jolt-truthy? (let* ((and__25__auto (jolt-get params (keyword #f "at")))) (if (jolt-truthy? and__25__auto) (jolt-get params (keyword #f "colon")) and__25__auto))) (var-deref "clojure.pprint" "iterate-main-sublists") (if (jolt-truthy? (jolt-get params (keyword #f "colon"))) (var-deref "clojure.pprint" "iterate-list-of-sublists") (if (jolt-truthy? (jolt-get params (keyword #f "at"))) (var-deref "clojure.pprint" "iterate-main-list") (if #t (var-deref "clojure.pprint" "iterate-sublist") jolt-nil)))))))) (jolt-hash-map _o$1793 _o$1794 _o$1795 _o$1796 _o$1797 _o$1798 _o$1799 _o$1800 _o$1801 _o$1802))) (_a$1990 (integer->char 125)) (_a$1991 (let* ((_o$1804 (keyword #f "directive")) (_o$1805 (integer->char 125)) (_o$1806 (keyword #f "params")) (_o$1807 (jolt-invoke (var-deref "clojure.core" "array-map"))) (_o$1808 (keyword #f "flags")) (_o$1809 (jolt-hash-set (keyword #f "colon"))) (_o$1810 (keyword #f "bracket-info")) (_o$1811 (jolt-hash-map)) (_o$1812 (keyword #f "generator-fn")) (_o$1813 (lambda (params offset) (let fnrec1803 ((params params) (offset offset)) jolt-nil)))) (jolt-hash-map _o$1804 _o$1805 _o$1806 _o$1807 _o$1808 _o$1809 _o$1810 _o$1811 _o$1812 _o$1813))) (_a$1992 (integer->char 60)) (_a$1993 (let* ((_o$1842 (keyword #f "directive")) (_o$1843 (integer->char 60)) (_o$1844 (keyword #f "params")) (_o$1845 (let* ((_a$1822 (var-deref "clojure.core" "array-map")) (_a$1823 (keyword #f "mincol")) (_a$1824 (let* ((_o$1814 0) (_o$1815 (var-deref "clojure.core" "Long"))) (jolt-vector _o$1814 _o$1815))) (_a$1825 (keyword #f "colinc")) (_a$1826 (let* ((_o$1816 1) (_o$1817 (var-deref "clojure.core" "Long"))) (jolt-vector _o$1816 _o$1817))) (_a$1827 (keyword #f "minpad")) (_a$1828 (let* ((_o$1818 0) (_o$1819 (var-deref "clojure.core" "Long"))) (jolt-vector _o$1818 _o$1819))) (_a$1829 (keyword #f "padchar")) (_a$1830 (let* ((_o$1820 (integer->char 32)) (_o$1821 (var-deref "clojure.core" "Character"))) (jolt-vector _o$1820 _o$1821)))) (jolt-invoke _a$1822 _a$1823 _a$1824 _a$1825 _a$1826 _a$1827 _a$1828 _a$1829 _a$1830))) (_o$1846 (keyword #f "flags")) (_o$1847 (let* ((_o$1831 (keyword #f "colon")) (_o$1832 (keyword #f "at")) (_o$1833 (keyword #f "both")) (_o$1834 (keyword #f "pretty"))) (jolt-hash-set _o$1831 _o$1832 _o$1833 _o$1834))) (_o$1848 (keyword #f "bracket-info")) (_o$1849 (let* ((_o$1835 (keyword #f "right")) (_o$1836 (integer->char 62)) (_o$1837 (keyword #f "allows-separator")) (_o$1838 #t) (_o$1839 (keyword #f "else")) (_o$1840 (keyword #f "first"))) (jolt-hash-map _o$1835 _o$1836 _o$1837 _o$1838 _o$1839 _o$1840))) (_o$1850 (keyword #f "generator-fn")) (_o$1851 (lambda (params offset) (let fnrec1841 ((params params) (offset offset)) (var-deref "clojure.pprint" "logical-block-or-justify"))))) (jolt-hash-map _o$1842 _o$1843 _o$1844 _o$1845 _o$1846 _o$1847 _o$1848 _o$1849 _o$1850 _o$1851))) (_a$1994 (integer->char 62)) (_a$1995 (let* ((_o$1853 (keyword #f "directive")) (_o$1854 (integer->char 62)) (_o$1855 (keyword #f "params")) (_o$1856 (jolt-invoke (var-deref "clojure.core" "array-map"))) (_o$1857 (keyword #f "flags")) (_o$1858 (jolt-hash-set (keyword #f "colon"))) (_o$1859 (keyword #f "bracket-info")) (_o$1860 (jolt-hash-map)) (_o$1861 (keyword #f "generator-fn")) (_o$1862 (lambda (params offset) (let fnrec1852 ((params params) (offset offset)) jolt-nil)))) (jolt-hash-map _o$1853 _o$1854 _o$1855 _o$1856 _o$1857 _o$1858 _o$1859 _o$1860 _o$1861 _o$1862))) (_a$1996 (integer->char 94)) (_a$1997 (let* ((_o$1886 (keyword #f "directive")) (_o$1887 (integer->char 94)) (_o$1888 (keyword #f "params")) (_o$1889 (let* ((_a$1869 (var-deref "clojure.core" "array-map")) (_a$1870 (keyword #f "arg1")) (_a$1871 (let* ((_o$1863 jolt-nil) (_o$1864 (var-deref "clojure.core" "Long"))) (jolt-vector _o$1863 _o$1864))) (_a$1872 (keyword #f "arg2")) (_a$1873 (let* ((_o$1865 jolt-nil) (_o$1866 (var-deref "clojure.core" "Long"))) (jolt-vector _o$1865 _o$1866))) (_a$1874 (keyword #f "arg3")) (_a$1875 (let* ((_o$1867 jolt-nil) (_o$1868 (var-deref "clojure.core" "Long"))) (jolt-vector _o$1867 _o$1868)))) (jolt-invoke _a$1869 _a$1870 _a$1871 _a$1872 _a$1873 _a$1874 _a$1875))) (_o$1890 (keyword #f "flags")) (_o$1891 (jolt-hash-set (keyword #f "colon"))) (_o$1892 (keyword #f "bracket-info")) (_o$1893 (jolt-hash-map)) (_o$1894 (keyword #f "generator-fn")) (_o$1895 (lambda (params offset) (let fnrec1876 ((params params) (offset offset)) (lambda (params navigator offsets) (let fnrec1877 ((params params) (navigator navigator) (offsets offsets)) (let* ((arg1 (jolt-get params (keyword #f "arg1"))) (arg2 (jolt-get params (keyword #f "arg2"))) (arg3 (jolt-get params (keyword #f "arg3"))) (exit (if (jolt-truthy? (jolt-get params (keyword #f "colon"))) (keyword #f "colon-up-arrow") (keyword #f "up-arrow")))) (if (jolt-truthy? (let* ((and__25__auto arg1)) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto arg2)) (if (jolt-truthy? and__25__auto) arg3 and__25__auto)) and__25__auto))) (if (jolt-n<= arg1 arg2 arg3) (let* ((_o$1878 exit) (_o$1879 navigator)) (jolt-vector _o$1878 _o$1879)) navigator) (if (jolt-truthy? (let* ((and__25__auto arg1)) (if (jolt-truthy? and__25__auto) arg2 and__25__auto))) (if (jolt= arg1 arg2) (let* ((_o$1880 exit) (_o$1881 navigator)) (jolt-vector _o$1880 _o$1881)) navigator) (if (jolt-truthy? arg1) (if (jolt= arg1 0) (let* ((_o$1882 exit) (_o$1883 navigator)) (jolt-vector _o$1882 _o$1883)) navigator) (if #t (if (if (jolt-truthy? (jolt-get params (keyword #f "colon"))) (jolt-empty? (jolt-get (jolt-get params (keyword #f "base-args")) (keyword #f "rest"))) (jolt-empty? (jolt-get navigator (keyword #f "rest")))) (let* ((_o$1884 exit) (_o$1885 navigator)) (jolt-vector _o$1884 _o$1885)) navigator) jolt-nil))))))))))) (jolt-hash-map _o$1886 _o$1887 _o$1888 _o$1889 _o$1890 _o$1891 _o$1892 _o$1893 _o$1894 _o$1895))) (_a$1998 (integer->char 87)) (_a$1999 (let* ((_o$1915 (keyword #f "directive")) (_o$1916 (integer->char 87)) (_o$1917 (keyword #f "params")) (_o$1918 (jolt-invoke (var-deref "clojure.core" "array-map"))) (_o$1919 (keyword #f "flags")) (_o$1920 (let* ((_o$1896 (keyword #f "at")) (_o$1897 (keyword #f "colon")) (_o$1898 (keyword #f "both")) (_o$1899 (keyword #f "pretty"))) (jolt-hash-set _o$1896 _o$1897 _o$1898 _o$1899))) (_o$1921 (keyword #f "bracket-info")) (_o$1922 (jolt-hash-map)) (_o$1923 (keyword #f "generator-fn")) (_o$1924 (lambda (params offset) (let fnrec1900 ((params params) (offset offset)) (if (jolt-truthy? (let* ((or__26__auto (jolt-get params (keyword #f "at")))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-get params (keyword #f "colon"))))) (let* ((bindings (let* ((_a$1907 (if (jolt-truthy? (jolt-get params (keyword #f "at"))) (let* ((_o$1901 (keyword #f "level")) (_o$1902 jolt-nil) (_o$1903 (keyword #f "length")) (_o$1904 jolt-nil)) (jolt-vector _o$1901 _o$1902 _o$1903 _o$1904)) (jolt-vector))) (_a$1908 (if (jolt-truthy? (jolt-get params (keyword #f "colon"))) (let* ((_o$1905 (keyword #f "pretty")) (_o$1906 #t)) (jolt-vector _o$1905 _o$1906)) (jolt-vector)))) (jolt-concat _a$1907 _a$1908)))) (lambda (params navigator offsets) (let fnrec1909 ((params params) (navigator navigator) (offsets offsets)) (let* ((G__78 (jolt-invoke (var-deref "clojure.pprint" "next-arg") navigator)) (arg (jolt-nth G__78 0 jolt-nil)) (navigator (jolt-nth G__78 1 jolt-nil))) (if (jolt-truthy? (jolt-apply (var-deref "clojure.pprint" "write") arg bindings)) (let* ((_o$1910 (keyword #f "up-arrow")) (_o$1911 navigator)) (jolt-vector _o$1910 _o$1911)) navigator))))) (lambda (params navigator offsets) (let fnrec1912 ((params params) (navigator navigator) (offsets offsets)) (let* ((G__79 (jolt-invoke (var-deref "clojure.pprint" "next-arg") navigator)) (arg (jolt-nth G__79 0 jolt-nil)) (navigator (jolt-nth G__79 1 jolt-nil))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.pprint" "write-out") arg)) (let* ((_o$1913 (keyword #f "up-arrow")) (_o$1914 navigator)) (jolt-vector _o$1913 _o$1914)) navigator))))))))) (jolt-hash-map _o$1915 _o$1916 _o$1917 _o$1918 _o$1919 _o$1920 _o$1921 _o$1922 _o$1923 _o$1924))) (_a$2000 (integer->char 95)) (_a$2001 (let* ((_o$1929 (keyword #f "directive")) (_o$1930 (integer->char 95)) (_o$1931 (keyword #f "params")) (_o$1932 (jolt-invoke (var-deref "clojure.core" "array-map"))) (_o$1933 (keyword #f "flags")) (_o$1934 (let* ((_o$1925 (keyword #f "at")) (_o$1926 (keyword #f "colon")) (_o$1927 (keyword #f "both"))) (jolt-hash-set _o$1925 _o$1926 _o$1927))) (_o$1935 (keyword #f "bracket-info")) (_o$1936 (jolt-hash-map)) (_o$1937 (keyword #f "generator-fn")) (_o$1938 (lambda (params offset) (let fnrec1928 ((params params) (offset offset)) (var-deref "clojure.pprint" "conditional-newline"))))) (jolt-hash-map _o$1929 _o$1930 _o$1931 _o$1932 _o$1933 _o$1934 _o$1935 _o$1936 _o$1937 _o$1938))) (_a$2002 (integer->char 73)) (_a$2003 (let* ((_o$1942 (keyword #f "directive")) (_o$1943 (integer->char 73)) (_o$1944 (keyword #f "params")) (_o$1945 (jolt-invoke (var-deref "clojure.core" "array-map") (keyword #f "n") (let* ((_o$1939 0) (_o$1940 (var-deref "clojure.core" "Long"))) (jolt-vector _o$1939 _o$1940)))) (_o$1946 (keyword #f "flags")) (_o$1947 (jolt-hash-set (keyword #f "colon"))) (_o$1948 (keyword #f "bracket-info")) (_o$1949 (jolt-hash-map)) (_o$1950 (keyword #f "generator-fn")) (_o$1951 (lambda (params offset) (let fnrec1941 ((params params) (offset offset)) (var-deref "clojure.pprint" "set-indent"))))) (jolt-hash-map _o$1942 _o$1943 _o$1944 _o$1945 _o$1946 _o$1947 _o$1948 _o$1949 _o$1950 _o$1951)))) (jolt-hash-map-fn _a$1952 _a$1953 _a$1954 _a$1955 _a$1956 _a$1957 _a$1958 _a$1959 _a$1960 _a$1961 _a$1962 _a$1963 _a$1964 _a$1965 _a$1966 _a$1967 _a$1968 _a$1969 _a$1970 _a$1971 _a$1972 _a$1973 _a$1974 _a$1975 _a$1976 _a$1977 _a$1978 _a$1979 _a$1980 _a$1981 _a$1982 _a$1983 _a$1984 _a$1985 _a$1986 _a$1987 _a$1988 _a$1989 _a$1990 _a$1991 _a$1992 _a$1993 _a$1994 _a$1995 _a$1996 _a$1997 _a$1998 _a$1999 _a$2000 _a$2001 _a$2002 _a$2003)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "param-pattern" (jolt-regex "^([vV]|#|('.)|([+-]?\\d+)|(?=,))") (let* ((_o$2004 (keyword #f "private")) (_o$2005 #t)) (jolt-hash-map _o$2004 _o$2005)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "special-params" (let* ((_o$2006 (keyword #f "parameter-from-args")) (_o$2007 (keyword #f "remaining-arg-count"))) (jolt-hash-set _o$2006 _o$2007)) (let* ((_o$2008 (keyword #f "private")) (_o$2009 #t)) (jolt-hash-map _o$2008 _o$2009)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "extract-param" (letrec ((extract-param (lambda (G__80) (let fnrec2010 ((G__80 G__80)) (let* ((G__81 G__80) (s (jolt-nth G__81 0 jolt-nil)) (offset (jolt-nth G__81 1 jolt-nil)) (saw-comma (jolt-nth G__81 2 jolt-nil))) (let* ((param (jolt-invoke (var-deref "clojure.core" "re-find") (var-deref "clojure.pprint" "param-pattern") s)) (token-str (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "vector?") param)) (jolt-first param) param))) (if (jolt-truthy? token-str) (let* ((len (jolt-count token-str)) (remainder (jolt-invoke (var-deref "clojure.core" "subs") s len)) (new-offset (jolt-n+ offset len))) (if (jolt-not (jolt= (integer->char 44) (jolt-nth remainder 0 jolt-nil))) (let* ((_o$2016 (let* ((_o$2011 token-str) (_o$2012 offset)) (jolt-vector _o$2011 _o$2012))) (_o$2017 (let* ((_o$2013 remainder) (_o$2014 new-offset) (_o$2015 #f)) (jolt-vector _o$2013 _o$2014 _o$2015)))) (jolt-vector _o$2016 _o$2017)) (let* ((_o$2023 (let* ((_o$2018 token-str) (_o$2019 offset)) (jolt-vector _o$2018 _o$2019))) (_o$2024 (let* ((_o$2020 (jolt-invoke (var-deref "clojure.core" "subs") remainder 1)) (_o$2021 (jolt-inc new-offset)) (_o$2022 #t)) (jolt-vector _o$2020 _o$2021 _o$2022)))) (jolt-vector _o$2023 _o$2024)))) (if (jolt-truthy? saw-comma) (jolt-invoke (var-deref "clojure.pprint" "format-error") "Badly formed parameters in format directive" offset) (let* ((_o$2027 jolt-nil) (_o$2028 (let* ((_o$2025 s) (_o$2026 offset)) (jolt-vector _o$2025 _o$2026)))) (jolt-vector _o$2027 _o$2028)))))))))) extract-param) (let* ((_o$2029 (keyword #f "private")) (_o$2030 #t)) (jolt-hash-map _o$2029 _o$2030)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "extract-params" (letrec ((extract-params (lambda (s offset) (let fnrec2031 ((s s) (offset offset)) (jolt-invoke (var-deref "clojure.pprint" "consume") (var-deref "clojure.pprint" "extract-param") (let* ((_o$2032 s) (_o$2033 offset) (_o$2034 #f)) (jolt-vector _o$2032 _o$2033 _o$2034))))))) extract-params) (let* ((_o$2035 (keyword #f "private")) (_o$2036 #t)) (jolt-hash-map _o$2035 _o$2036)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "translate-param" (letrec ((translate-param (lambda (G__82) (let fnrec2037 ((G__82 G__82)) (let* ((G__83 G__82) (p (jolt-nth G__83 0 jolt-nil)) (offset (jolt-nth G__83 1 jolt-nil))) (let* ((_o$2042 (if (jolt= (jolt-count p) 0) jolt-nil (if (let* ((and__25__auto (jolt= (jolt-count p) 1))) (if (jolt-truthy? and__25__auto) (let* ((_a$2040 (let* ((_o$2038 (integer->char 118)) (_o$2039 (integer->char 86))) (jolt-hash-set _o$2038 _o$2039))) (_a$2041 (jolt-nth p 0))) (jolt-contains? _a$2040 _a$2041)) and__25__auto)) (keyword #f "parameter-from-args") (if (let* ((and__25__auto (jolt= (jolt-count p) 1))) (if (jolt-truthy? and__25__auto) (jolt= (integer->char 35) (jolt-nth p 0)) and__25__auto)) (keyword #f "remaining-arg-count") (if (let* ((and__25__auto (jolt= (jolt-count p) 2))) (if (jolt-truthy? and__25__auto) (jolt= (integer->char 39) (jolt-nth p 0)) and__25__auto)) (jolt-nth p 1) (if #t (host-static-call "Long" "parseLong" p) jolt-nil)))))) (_o$2043 offset)) (jolt-vector _o$2042 _o$2043))))))) translate-param) (let* ((_o$2044 (keyword #f "private")) (_o$2045 #t)) (jolt-hash-map _o$2044 _o$2045)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "flag-defs" (let* ((_o$2046 (integer->char 58)) (_o$2047 (keyword #f "colon")) (_o$2048 (integer->char 64)) (_o$2049 (keyword #f "at"))) (jolt-hash-map _o$2046 _o$2047 _o$2048 _o$2049)) (let* ((_o$2050 (keyword #f "private")) (_o$2051 #t)) (jolt-hash-map _o$2050 _o$2051)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "extract-flags" (letrec ((extract-flags (lambda (s offset) (let fnrec2052 ((s s) (offset offset)) (let* ((_a$2074 (var-deref "clojure.pprint" "consume")) (_a$2075 (lambda (G__84) (let fnrec2053 ((G__84 G__84)) (let* ((G__85 G__84) (s (jolt-nth G__85 0 jolt-nil)) (offset (jolt-nth G__85 1 jolt-nil)) (flags (jolt-nth G__85 2 jolt-nil))) (if (jolt-empty? s) (let* ((_o$2057 jolt-nil) (_o$2058 (let* ((_o$2054 s) (_o$2055 offset) (_o$2056 flags)) (jolt-vector _o$2054 _o$2055 _o$2056)))) (jolt-vector _o$2057 _o$2058)) (let* ((flag (jolt-get (var-deref "clojure.pprint" "flag-defs") (jolt-first s)))) (if (jolt-truthy? flag) (if (jolt-contains? flags flag) (jolt-invoke (var-deref "clojure.pprint" "format-error") (jolt-invoke (var-deref "clojure.core" "str") "Flag \"" (jolt-first s) "\" appears more than once in a directive") offset) (let* ((_o$2064 #t) (_o$2065 (let* ((_o$2061 (jolt-invoke (var-deref "clojure.core" "subs") s 1)) (_o$2062 (jolt-inc offset)) (_o$2063 (jolt-assoc flags flag (let* ((_o$2059 #t) (_o$2060 offset)) (jolt-vector _o$2059 _o$2060))))) (jolt-vector _o$2061 _o$2062 _o$2063)))) (jolt-vector _o$2064 _o$2065))) (let* ((_o$2069 jolt-nil) (_o$2070 (let* ((_o$2066 s) (_o$2067 offset) (_o$2068 flags)) (jolt-vector _o$2066 _o$2067 _o$2068)))) (jolt-vector _o$2069 _o$2070))))))))) (_a$2076 (let* ((_o$2071 s) (_o$2072 offset) (_o$2073 (jolt-hash-map))) (jolt-vector _o$2071 _o$2072 _o$2073)))) (jolt-invoke _a$2074 _a$2075 _a$2076)))))) extract-flags) (let* ((_o$2077 (keyword #f "private")) (_o$2078 #t)) (jolt-hash-map _o$2077 _o$2078)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "check-flags" (letrec ((check-flags (lambda (dirdef flags) (let fnrec2079 ((dirdef dirdef) (flags flags)) (let* ((allowed (jolt-get dirdef (keyword #f "flags")))) (begin (if (jolt-truthy? (let* ((and__25__auto (jolt-not (jolt-get allowed (keyword #f "at"))))) (if (jolt-truthy? and__25__auto) (jolt-get flags (keyword #f "at")) and__25__auto))) (let* ((_a$2080 (var-deref "clojure.pprint" "format-error")) (_a$2081 (jolt-invoke (var-deref "clojure.core" "str") "\"@\" is an illegal flag for format directive \"" (jolt-get dirdef (keyword #f "directive")) "\"")) (_a$2082 (jolt-nth (jolt-get flags (keyword #f "at")) 1))) (jolt-invoke _a$2080 _a$2081 _a$2082)) jolt-nil) (if (jolt-truthy? (let* ((and__25__auto (jolt-not (jolt-get allowed (keyword #f "colon"))))) (if (jolt-truthy? and__25__auto) (jolt-get flags (keyword #f "colon")) and__25__auto))) (let* ((_a$2083 (var-deref "clojure.pprint" "format-error")) (_a$2084 (jolt-invoke (var-deref "clojure.core" "str") "\":\" is an illegal flag for format directive \"" (jolt-get dirdef (keyword #f "directive")) "\"")) (_a$2085 (jolt-nth (jolt-get flags (keyword #f "colon")) 1))) (jolt-invoke _a$2083 _a$2084 _a$2085)) jolt-nil) (if (jolt-truthy? (let* ((and__25__auto (jolt-not (jolt-get allowed (keyword #f "both"))))) (if (jolt-truthy? and__25__auto) (let* ((and__25__auto (jolt-get flags (keyword #f "at")))) (if (jolt-truthy? and__25__auto) (jolt-get flags (keyword #f "colon")) and__25__auto)) and__25__auto))) (let* ((_a$2088 (var-deref "clojure.pprint" "format-error")) (_a$2089 (jolt-invoke (var-deref "clojure.core" "str") "Cannot combine \"@\" and \":\" flags for format directive \"" (jolt-get dirdef (keyword #f "directive")) "\"")) (_a$2090 (let* ((_a$2086 (jolt-nth (jolt-get flags (keyword #f "colon")) 1)) (_a$2087 (jolt-nth (jolt-get flags (keyword #f "at")) 1))) (jolt-n-min _a$2086 _a$2087)))) (jolt-invoke _a$2088 _a$2089 _a$2090)) jolt-nil))))))) check-flags) (let* ((_o$2091 (keyword #f "private")) (_o$2092 #t)) (jolt-hash-map _o$2091 _o$2092)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "map-params" (letrec ((map-params (lambda (dirdef params flags offset) (let fnrec2093 ((dirdef dirdef) (params params) (flags flags) (offset offset)) (begin (jolt-invoke (var-deref "clojure.pprint" "check-flags") dirdef flags) (if (let* ((_a$2094 (jolt-count params)) (_a$2095 (jolt-count (jolt-get dirdef (keyword #f "params"))))) (jolt-n> _a$2094 _a$2095)) (let* ((_a$2102 (var-deref "clojure.pprint" "format-error")) (_a$2103 (let* ((_a$2096 (var-deref "clojure.pprint" "cl-format")) (_a$2097 jolt-nil) (_a$2098 "Too many parameters for directive \"~C\": ~D~:* ~[were~;was~:;were~] specified but only ~D~:* ~[are~;is~:;are~] allowed") (_a$2099 (jolt-get dirdef (keyword #f "directive"))) (_a$2100 (jolt-count params)) (_a$2101 (jolt-count (jolt-get dirdef (keyword #f "params"))))) (jolt-invoke _a$2096 _a$2097 _a$2098 _a$2099 _a$2100 _a$2101))) (_a$2104 (jolt-invoke (var-deref "clojure.core" "second") (jolt-first params)))) (jolt-invoke _a$2102 _a$2103 _a$2104)) jolt-nil) (jolt-invoke (var-deref "clojure.core" "doall") (let* ((_a$2106 (lambda (p__35_) (let fnrec2105 ((p__35_ p__35_)) (let* ((val (jolt-first p__35_))) (if (jolt-not (let* ((or__26__auto (jolt-nil? val))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-contains? (var-deref "clojure.pprint" "special-params") val)))) jolt-nil jolt-nil))))) (_a$2107 params) (_a$2108 (jolt-get dirdef (keyword #f "params")))) (jolt-map _a$2106 _a$2107 _a$2108))) (let* ((_a$2125 (var-deref "clojure.core" "merge")) (_a$2126 (let* ((_a$2116 (jolt-hash-map)) (_a$2117 (jolt-reverse (let* ((_a$2114 (lambda (G__86) (let fnrec2109 ((G__86 G__86)) (let* ((G__87 G__86) (name (jolt-nth G__87 0 jolt-nil)) (G__88 (jolt-nth G__87 1 jolt-nil)) (default (jolt-nth G__88 0 jolt-nil))) (let* ((_o$2112 name) (_o$2113 (let* ((_o$2110 default) (_o$2111 offset)) (jolt-vector _o$2110 _o$2111)))) (jolt-vector _o$2112 _o$2113)))))) (_a$2115 (jolt-get dirdef (keyword #f "params")))) (jolt-map _a$2114 _a$2115))))) (jolt-into _a$2116 _a$2117))) (_a$2127 (let* ((_a$2122 (lambda (p__36_ p__37_) (let fnrec2118 ((p__36_ p__36_) (p__37_ p__37_)) (jolt-apply jolt-assoc p__36_ p__37_)))) (_a$2123 (jolt-hash-map)) (_a$2124 (let* ((_a$2120 (lambda (p__38_) (let fnrec2119 ((p__38_ p__38_)) (jolt-first (jolt-nth p__38_ 1))))) (_a$2121 (jolt-invoke (var-deref "clojure.core" "zipmap") (jolt-keys (jolt-get dirdef (keyword #f "params"))) params))) (jolt-filter _a$2120 _a$2121)))) (jolt-reduce _a$2122 _a$2123 _a$2124))) (_a$2128 flags)) (jolt-invoke _a$2125 _a$2126 _a$2127 _a$2128))))))) map-params) (let* ((_o$2129 (keyword #f "private")) (_o$2130 #t)) (jolt-hash-map _o$2129 _o$2130)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "compile-directive" (letrec ((compile-directive (lambda (s offset) (let fnrec2131 ((s s) (offset offset)) (let* ((G__89 (jolt-invoke (var-deref "clojure.pprint" "extract-params") s offset)) (raw-params (jolt-nth G__89 0 jolt-nil)) (G__90 (jolt-nth G__89 1 jolt-nil)) (rest (jolt-nth G__90 0 jolt-nil)) (offset (jolt-nth G__90 1 jolt-nil)) (G__91 (jolt-invoke (var-deref "clojure.pprint" "extract-flags") rest offset)) (_ (jolt-nth G__91 0 jolt-nil)) (G__92 (jolt-nth G__91 1 jolt-nil)) (rest (jolt-nth G__92 0 jolt-nil)) (offset (jolt-nth G__92 1 jolt-nil)) (flags (jolt-nth G__92 2 jolt-nil)) (directive (jolt-first rest)) (dirdef (if (jolt-truthy? directive) (let* ((or__26__auto (jolt-get (var-deref "clojure.pprint" "directive-table") (jolt-first (jolt-invoke (var-deref "clojure.string" "upper-case") (jolt-invoke (var-deref "clojure.core" "str") directive)))))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-get (var-deref "clojure.pprint" "directive-table") directive))) jolt-nil)) (params (if (jolt-truthy? dirdef) (jolt-invoke (var-deref "clojure.pprint" "map-params") dirdef (jolt-map (var-deref "clojure.pprint" "translate-param") raw-params) flags offset) jolt-nil))) (begin (if (jolt-not directive) (jolt-invoke (var-deref "clojure.pprint" "format-error") "Format string ended in the middle of a directive" offset) jolt-nil) (if (jolt-not dirdef) (jolt-invoke (var-deref "clojure.pprint" "format-error") (jolt-invoke (var-deref "clojure.core" "str") "Directive \"" directive "\" is undefined") offset) jolt-nil) (let* ((_o$2136 (jolt-invoke (var-deref "clojure.pprint" "->compiled-directive") (jolt-invoke (jolt-get dirdef (keyword #f "generator-fn")) params offset) dirdef params offset)) (_o$2137 (let* ((remainder (jolt-invoke (var-deref "clojure.core" "subs") rest 1)) (offset (jolt-inc offset)) (trim? (let* ((and__25__auto (jolt= (integer->char 10) (jolt-get dirdef (keyword #f "directive"))))) (if (jolt-truthy? and__25__auto) (jolt-not (jolt-get params (keyword #f "colon"))) and__25__auto))) (trim-count (if (jolt-truthy? trim?) (jolt-invoke (var-deref "clojure.pprint" "prefix-count") remainder (let* ((_o$2132 (integer->char 32)) (_o$2133 (integer->char 9))) (jolt-vector _o$2132 _o$2133))) 0)) (remainder (jolt-invoke (var-deref "clojure.core" "subs") remainder trim-count)) (offset (jolt-n+ offset trim-count))) (let* ((_o$2134 remainder) (_o$2135 offset)) (jolt-vector _o$2134 _o$2135))))) (jolt-vector _o$2136 _o$2137)))))))) compile-directive) (let* ((_o$2138 (keyword #f "private")) (_o$2139 #t)) (jolt-hash-map _o$2138 _o$2139)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "compile-raw-string" (letrec ((compile-raw-string (lambda (s offset) (let fnrec2140 ((s s) (offset offset)) (let* ((_a$2144 (var-deref "clojure.pprint" "->compiled-directive")) (_a$2145 (lambda (_r$__285 a _) (let fnrec2141 ((_r$__285 _r$__285) (a a) (_ _)) (begin (jolt-invoke (var-deref "clojure.pprint" "print") s) a)))) (_a$2146 jolt-nil) (_a$2147 (let* ((_o$2142 (keyword #f "string")) (_o$2143 s)) (jolt-hash-map _o$2142 _o$2143))) (_a$2148 offset)) (jolt-invoke _a$2144 _a$2145 _a$2146 _a$2147 _a$2148)))))) compile-raw-string) (let* ((_o$2149 (keyword #f "private")) (_o$2150 #t)) (jolt-hash-map _o$2149 _o$2150)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "right-bracket" (letrec ((right-bracket (lambda (this) (let fnrec2151 ((this this)) (jolt-get (jolt-get (jolt-get this (keyword #f "dirdef")) (keyword #f "bracket-info")) (keyword #f "right")))))) right-bracket) (let* ((_o$2152 (keyword #f "private")) (_o$2153 #t)) (jolt-hash-map _o$2152 _o$2153)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "separator?" (letrec ((separator? (lambda (this) (let fnrec2154 ((this this)) (jolt-get (jolt-get (jolt-get this (keyword #f "dirdef")) (keyword #f "bracket-info")) (keyword #f "separator")))))) separator?) (let* ((_o$2155 (keyword #f "private")) (_o$2156 #t)) (jolt-hash-map _o$2155 _o$2156)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "else-separator?" (letrec ((else-separator? (lambda (this) (let fnrec2157 ((this this)) (let* ((and__25__auto (jolt-get (jolt-get (jolt-get this (keyword #f "dirdef")) (keyword #f "bracket-info")) (keyword #f "separator")))) (if (jolt-truthy? and__25__auto) (jolt-get (jolt-get this (keyword #f "params")) (keyword #f "colon")) and__25__auto)))))) else-separator?) (let* ((_o$2158 (keyword #f "private")) (_o$2159 #t)) (jolt-hash-map _o$2158 _o$2159)))) -(guard (e (#t #f)) - (declare-var! "clojure.pprint" "collect-clauses")) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "process-bracket" (letrec ((process-bracket (lambda (this remainder) (let fnrec2160 ((this this) (remainder remainder)) (let* ((G__93 (let* ((_a$2161 (var-deref "clojure.pprint" "collect-clauses")) (_a$2162 (jolt-get (jolt-get this (keyword #f "dirdef")) (keyword #f "bracket-info"))) (_a$2163 (jolt-get this (keyword #f "offset"))) (_a$2164 remainder)) (jolt-invoke _a$2161 _a$2162 _a$2163 _a$2164))) (subex (jolt-nth G__93 0 jolt-nil)) (remainder (jolt-nth G__93 1 jolt-nil))) (let* ((_o$2173 (let* ((_a$2168 (var-deref "clojure.pprint" "->compiled-directive")) (_a$2169 (jolt-get this (keyword #f "func"))) (_a$2170 (jolt-get this (keyword #f "dirdef"))) (_a$2171 (let* ((_a$2165 (var-deref "clojure.core" "merge")) (_a$2166 (jolt-get this (keyword #f "params"))) (_a$2167 (jolt-invoke (var-deref "clojure.pprint" "tuple-map") subex (jolt-get this (keyword #f "offset"))))) (jolt-invoke _a$2165 _a$2166 _a$2167))) (_a$2172 (jolt-get this (keyword #f "offset")))) (jolt-invoke _a$2168 _a$2169 _a$2170 _a$2171 _a$2172))) (_o$2174 remainder)) (jolt-vector _o$2173 _o$2174))))))) process-bracket) (let* ((_o$2175 (keyword #f "private")) (_o$2176 #t)) (jolt-hash-map _o$2175 _o$2176)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "process-clause" (letrec ((process-clause (lambda (bracket-info offset remainder) (let fnrec2177 ((bracket-info bracket-info) (offset offset) (remainder remainder)) (jolt-invoke (var-deref "clojure.pprint" "consume") (lambda (remainder) (let fnrec2178 ((remainder remainder)) (if (jolt-empty? remainder) (jolt-invoke (var-deref "clojure.pprint" "format-error") "No closing bracket found." offset) (let* ((this (jolt-first remainder)) (remainder (jolt-next remainder))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.pprint" "right-bracket") this)) (jolt-invoke (var-deref "clojure.pprint" "process-bracket") this remainder) (if (let* ((_a$2179 (jolt-get bracket-info (keyword #f "right"))) (_a$2180 (jolt-get (jolt-get this (keyword #f "dirdef")) (keyword #f "directive")))) (jolt= _a$2179 _a$2180)) (let* ((_o$2185 jolt-nil) (_o$2186 (let* ((_o$2181 (keyword #f "right-bracket")) (_o$2182 (jolt-get this (keyword #f "params"))) (_o$2183 jolt-nil) (_o$2184 remainder)) (jolt-vector _o$2181 _o$2182 _o$2183 _o$2184)))) (jolt-vector _o$2185 _o$2186)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.pprint" "else-separator?") this)) (let* ((_o$2191 jolt-nil) (_o$2192 (let* ((_o$2187 (keyword #f "else")) (_o$2188 jolt-nil) (_o$2189 (jolt-get this (keyword #f "params"))) (_o$2190 remainder)) (jolt-vector _o$2187 _o$2188 _o$2189 _o$2190)))) (jolt-vector _o$2191 _o$2192)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.pprint" "separator?") this)) (let* ((_o$2197 jolt-nil) (_o$2198 (let* ((_o$2193 (keyword #f "separator")) (_o$2194 jolt-nil) (_o$2195 jolt-nil) (_o$2196 remainder)) (jolt-vector _o$2193 _o$2194 _o$2195 _o$2196)))) (jolt-vector _o$2197 _o$2198)) (if #t (let* ((_o$2199 this) (_o$2200 remainder)) (jolt-vector _o$2199 _o$2200)) jolt-nil))))))))) remainder))))) process-clause) (let* ((_o$2201 (keyword #f "private")) (_o$2202 #t)) (jolt-hash-map _o$2201 _o$2202)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "collect-clauses" (letrec ((collect-clauses (lambda (bracket-info offset remainder) (let fnrec2203 ((bracket-info bracket-info) (offset offset) (remainder remainder)) (jolt-invoke (var-deref "clojure.core" "second") (let* ((_a$2241 (var-deref "clojure.pprint" "consume")) (_a$2242 (lambda (G__94) (let fnrec2204 ((G__94 G__94)) (let* ((G__95 G__94) (clause-map (jolt-nth G__95 0 jolt-nil)) (saw-else (jolt-nth G__95 1 jolt-nil)) (remainder (jolt-nth G__95 2 jolt-nil))) (let* ((G__96 (jolt-invoke (var-deref "clojure.pprint" "process-clause") bracket-info offset remainder)) (clause (jolt-nth G__96 0 jolt-nil)) (G__97 (jolt-nth G__96 1 jolt-nil)) (type (jolt-nth G__97 0 jolt-nil)) (right-params (jolt-nth G__97 1 jolt-nil)) (else-params (jolt-nth G__97 2 jolt-nil)) (remainder (jolt-nth G__97 3 jolt-nil))) (if (jolt= type (keyword #f "right-bracket")) (let* ((_o$2211 jolt-nil) (_o$2212 (let* ((_o$2209 (jolt-invoke (var-deref "clojure.core" "merge-with") jolt-concat clause-map (let* ((_o$2205 (if (jolt-truthy? saw-else) (keyword #f "else") (keyword #f "clauses"))) (_o$2206 (jolt-vector clause)) (_o$2207 (keyword #f "right-params")) (_o$2208 right-params)) (jolt-hash-map _o$2205 _o$2206 _o$2207 _o$2208)))) (_o$2210 remainder)) (jolt-vector _o$2209 _o$2210)))) (jolt-vector _o$2211 _o$2212)) (if (jolt= type (keyword #f "else")) (if (jolt-truthy? (jolt-get clause-map (keyword #f "else"))) (jolt-invoke (var-deref "clojure.pprint" "format-error") "Two else clauses (\"~:;\") inside bracket construction." offset) (if (jolt-not (jolt-get bracket-info (keyword #f "else"))) (jolt-invoke (var-deref "clojure.pprint" "format-error") "An else clause (\"~:;\") is in a bracket type that doesn't support it." offset) (if (jolt-truthy? (let* ((and__25__auto (jolt= (keyword #f "first") (jolt-get bracket-info (keyword #f "else"))))) (if (jolt-truthy? and__25__auto) (jolt-seq (jolt-get clause-map (keyword #f "clauses"))) and__25__auto))) (jolt-invoke (var-deref "clojure.pprint" "format-error") "The else clause (\"~:;\") is only allowed in the first position for this directive." offset) (if #t (if (jolt= (keyword #f "first") (jolt-get bracket-info (keyword #f "else"))) (let* ((_o$2220 #t) (_o$2221 (let* ((_o$2217 (jolt-invoke (var-deref "clojure.core" "merge-with") jolt-concat clause-map (let* ((_o$2213 (keyword #f "else")) (_o$2214 (jolt-vector clause)) (_o$2215 (keyword #f "else-params")) (_o$2216 else-params)) (jolt-hash-map _o$2213 _o$2214 _o$2215 _o$2216)))) (_o$2218 #f) (_o$2219 remainder)) (jolt-vector _o$2217 _o$2218 _o$2219)))) (jolt-vector _o$2220 _o$2221)) (let* ((_o$2227 #t) (_o$2228 (let* ((_o$2224 (jolt-invoke (var-deref "clojure.core" "merge-with") jolt-concat clause-map (let* ((_o$2222 (keyword #f "clauses")) (_o$2223 (jolt-vector clause))) (jolt-hash-map _o$2222 _o$2223)))) (_o$2225 #t) (_o$2226 remainder)) (jolt-vector _o$2224 _o$2225 _o$2226)))) (jolt-vector _o$2227 _o$2228))) jolt-nil)))) (if (jolt= type (keyword #f "separator")) (if (jolt-truthy? saw-else) (jolt-invoke (var-deref "clojure.pprint" "format-error") "A plain clause (with \"~;\") follows an else clause (\"~:;\") inside bracket construction." offset) (if (jolt-not (jolt-get bracket-info (keyword #f "allows-separator"))) (jolt-invoke (var-deref "clojure.pprint" "format-error") "A separator (\"~;\") is in a bracket type that doesn't support it." offset) (if #t (let* ((_o$2234 #t) (_o$2235 (let* ((_o$2231 (jolt-invoke (var-deref "clojure.core" "merge-with") jolt-concat clause-map (let* ((_o$2229 (keyword #f "clauses")) (_o$2230 (jolt-vector clause))) (jolt-hash-map _o$2229 _o$2230)))) (_o$2232 #f) (_o$2233 remainder)) (jolt-vector _o$2231 _o$2232 _o$2233)))) (jolt-vector _o$2234 _o$2235)) jolt-nil))) jolt-nil)))))))) (_a$2243 (let* ((_o$2238 (let* ((_o$2236 (keyword #f "clauses")) (_o$2237 (jolt-vector))) (jolt-hash-map _o$2236 _o$2237))) (_o$2239 #f) (_o$2240 remainder)) (jolt-vector _o$2238 _o$2239 _o$2240)))) (jolt-invoke _a$2241 _a$2242 _a$2243))))))) collect-clauses) (let* ((_o$2244 (keyword #f "private")) (_o$2245 #t)) (jolt-hash-map _o$2244 _o$2245)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "process-nesting" (letrec ((process-nesting (lambda (format) (let fnrec2246 ((format format)) (jolt-first (jolt-invoke (var-deref "clojure.pprint" "consume") (lambda (remainder) (let fnrec2247 ((remainder remainder)) (let* ((this (jolt-first remainder)) (remainder (jolt-next remainder)) (bracket (jolt-get (jolt-get this (keyword #f "dirdef")) (keyword #f "bracket-info")))) (if (jolt-truthy? (jolt-get bracket (keyword #f "right"))) (jolt-invoke (var-deref "clojure.pprint" "process-bracket") this remainder) (let* ((_o$2248 this) (_o$2249 remainder)) (jolt-vector _o$2248 _o$2249)))))) format)))))) process-nesting) (let* ((_o$2250 (keyword #f "private")) (_o$2251 #t)) (jolt-hash-map _o$2250 _o$2251)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "compile-format" (letrec ((compile-format (lambda (format-str) (let fnrec2252 ((format-str format-str)) (let* ((frame__20__auto (jolt-invoke (var-deref "clojure.core" "array-map") (jolt-var "clojure.pprint" "*format-str*") format-str))) (begin (jolt-invoke (var-deref "clojure.core" "push-thread-bindings") frame__20__auto) (dynamic-wind (lambda () #f) (lambda () (jolt-invoke (var-deref "clojure.pprint" "process-nesting") (jolt-first (let* ((_a$2269 (var-deref "clojure.pprint" "consume")) (_a$2270 (lambda (G__98) (let fnrec2253 ((G__98 G__98)) (let* ((G__99 G__98) (s (jolt-nth G__99 0 jolt-nil)) (offset (jolt-nth G__99 1 jolt-nil))) (if (jolt-empty? s) (let* ((_o$2254 jolt-nil) (_o$2255 s)) (jolt-vector _o$2254 _o$2255)) (let* ((tilde (record-method-dispatch s "indexOf" (jolt-vector "~")))) (if (jolt-neg? tilde) (let* ((_o$2258 (jolt-invoke (var-deref "clojure.pprint" "compile-raw-string") s offset)) (_o$2259 (let* ((_o$2256 "") (_o$2257 (jolt-n+ offset (jolt-count s)))) (jolt-vector _o$2256 _o$2257)))) (jolt-vector _o$2258 _o$2259)) (if (jolt-zero? tilde) (let* ((_a$2260 (var-deref "clojure.pprint" "compile-directive")) (_a$2261 (jolt-invoke (var-deref "clojure.core" "subs") s 1)) (_a$2262 (jolt-inc offset))) (jolt-invoke _a$2260 _a$2261 _a$2262)) (if #t (let* ((_o$2265 (jolt-invoke (var-deref "clojure.pprint" "compile-raw-string") (jolt-invoke (var-deref "clojure.core" "subs") s 0 tilde) offset)) (_o$2266 (let* ((_o$2263 (jolt-invoke (var-deref "clojure.core" "subs") s tilde)) (_o$2264 (jolt-n+ tilde offset))) (jolt-vector _o$2263 _o$2264)))) (jolt-vector _o$2265 _o$2266)) jolt-nil))))))))) (_a$2271 (let* ((_o$2267 format-str) (_o$2268 0)) (jolt-vector _o$2267 _o$2268)))) (jolt-invoke _a$2269 _a$2270 _a$2271))))) (lambda () (jolt-invoke (var-deref "clojure.core" "pop-thread-bindings")))))))))) compile-format) (let* ((_o$2272 (keyword #f "private")) (_o$2273 #t)) (jolt-hash-map _o$2272 _o$2273)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "needs-pretty" (letrec ((needs-pretty (lambda (format) (let fnrec2274 ((format format)) (let* ((format format)) (let loop2275 ((format format)) (if (jolt-empty? format) #f (if (jolt-truthy? (let* ((or__26__auto (jolt-get (jolt-get (jolt-get (jolt-first format) (keyword #f "dirdef")) (keyword #f "flags")) (keyword #f "pretty")))) (if (jolt-truthy? or__26__auto) or__26__auto (let* ((or__26__auto (jolt-invoke (var-deref "clojure.core" "some") needs-pretty (jolt-first (jolt-get (jolt-get (jolt-first format) (keyword #f "params")) (keyword #f "clauses")))))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-invoke (var-deref "clojure.core" "some") needs-pretty (jolt-first (jolt-get (jolt-get (jolt-first format) (keyword #f "params")) (keyword #f "else"))))))))) #t (loop2275 (jolt-next format)))))))))) needs-pretty) (let* ((_o$2276 (keyword #f "private")) (_o$2277 #t)) (jolt-hash-map _o$2276 _o$2277)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "execute-format" (letrec ((execute-format (case-lambda ((stream format args) (let fnrec2278 ((stream stream) (format format) (args args)) (let* ((sb (host-new "StringBuilder")) (real-stream (if (jolt-truthy? (let* ((or__26__auto (jolt-not stream))) (if (jolt-truthy? or__26__auto) or__26__auto (jolt-invoke (var-deref "clojure.core" "true?") stream)))) (jolt-invoke (var-deref "clojure.pprint" "->StringBufferWriter") sb) stream)) (wrapped-stream (if (jolt-truthy? (let* ((and__25__auto (jolt-invoke (var-deref "clojure.pprint" "needs-pretty") format))) (if (jolt-truthy? and__25__auto) (jolt-not (jolt-invoke (var-deref "clojure.pprint" "pretty-writer?") real-stream)) and__25__auto))) (jolt-invoke (var-deref "clojure.pprint" "get-pretty-writer") real-stream) real-stream))) (let* ((frame__20__auto (jolt-invoke (var-deref "clojure.core" "array-map") (jolt-var "clojure.core" "*out*") wrapped-stream))) (begin (jolt-invoke (var-deref "clojure.core" "push-thread-bindings") frame__20__auto) (dynamic-wind (lambda () #f) (lambda () (begin (dynamic-wind (lambda () #f) (lambda () (execute-format format args)) (lambda () (if (jolt-not (jolt-invoke (var-deref "clojure.core" "identical?") real-stream wrapped-stream)) (jolt-invoke (var-deref "clojure.pprint" "-pflush") wrapped-stream) jolt-nil))) (if (jolt-not stream) (jolt-invoke (var-deref "clojure.core" "str") sb) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "true?") stream)) (jolt-invoke (var-deref "clojure.core" "print") (jolt-invoke (var-deref "clojure.core" "str") sb)) (if (jolt-truthy? (keyword #f "else")) jolt-nil jolt-nil))))) (lambda () (jolt-invoke (var-deref "clojure.core" "pop-thread-bindings"))))))))) ((format args) (let fnrec2279 ((format format) (args args)) (begin (jolt-invoke (var-deref "clojure.pprint" "map-passing-context") (lambda (element context) (let fnrec2280 ((element element) (context context)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.pprint" "abort?") context)) (let* ((_o$2281 jolt-nil) (_o$2282 context)) (jolt-vector _o$2281 _o$2282)) (let* ((G__100 (jolt-invoke (var-deref "clojure.pprint" "realize-parameter-list") (jolt-get element (keyword #f "params")) context)) (params (jolt-nth G__100 0 jolt-nil)) (args (jolt-nth G__100 1 jolt-nil)) (G__101 (jolt-invoke (var-deref "clojure.pprint" "unzip-map") params)) (params (jolt-nth G__101 0 jolt-nil)) (offsets (jolt-nth G__101 1 jolt-nil)) (params (jolt-assoc params (keyword #f "base-args") args))) (let* ((_o$2288 jolt-nil) (_o$2289 (let* ((_a$2286 (jolt-get element (keyword #f "func"))) (_a$2287 (let* ((_o$2283 params) (_o$2284 args) (_o$2285 offsets)) (jolt-vector _o$2283 _o$2284 _o$2285)))) (jolt-apply _a$2286 _a$2287)))) (jolt-vector _o$2288 _o$2289)))))) args format) jolt-nil)))))) execute-format) (let* ((_o$2290 (keyword #f "private")) (_o$2291 #t)) (jolt-hash-map _o$2290 _o$2291)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "cached-compile" (jolt-invoke (var-deref "clojure.core" "memoize") (var-deref "clojure.pprint" "compile-format")) (let* ((_o$2292 (keyword #f "private")) (_o$2293 #t)) (jolt-hash-map _o$2292 _o$2293)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "reader-macros" (let* ((_o$2294 (jolt-symbol #f "quote")) (_o$2295 "'") (_o$2296 (jolt-symbol #f "var")) (_o$2297 "#'") (_o$2298 (jolt-symbol "clojure.core" "deref")) (_o$2299 "@") (_o$2300 (jolt-symbol "clojure.core" "unquote")) (_o$2301 "~")) (jolt-hash-map _o$2294 _o$2295 _o$2296 _o$2297 _o$2298 _o$2299 _o$2300 _o$2301)) (let* ((_o$2302 (keyword #f "private")) (_o$2303 #t)) (jolt-hash-map _o$2302 _o$2303)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "pprint-reader-macro" (letrec ((pprint-reader-macro (lambda (alis) (let fnrec2304 ((alis alis)) (let* ((macro-char (jolt-invoke (var-deref "clojure.pprint" "reader-macros") (jolt-first alis)))) (if (jolt-truthy? (let* ((and__25__auto macro-char)) (if (jolt-truthy? and__25__auto) (jolt= 2 (jolt-count alis)) and__25__auto))) (begin (jolt-invoke (var-deref "clojure.pprint" "-write") (var-deref "clojure.core" "*out*") macro-char) (jolt-invoke (var-deref "clojure.pprint" "write-out") (jolt-invoke (var-deref "clojure.core" "second") alis)) #t) jolt-nil)))))) pprint-reader-macro) (let* ((_o$2305 (keyword #f "private")) (_o$2306 #t)) (jolt-hash-map _o$2305 _o$2306)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "pprint-simple-list" (letrec ((pprint-simple-list (lambda (alis) (let fnrec2307 ((alis alis)) (begin (if (jolt-truthy? (jolt-invoke (var-deref "clojure.pprint" "level-exceeded"))) (jolt-invoke (var-deref "clojure.pprint" "-write") (var-deref "clojure.core" "*out*") "#") (let* ((frame__20__auto (jolt-invoke (var-deref "clojure.core" "array-map") (jolt-var "clojure.pprint" "*current-level*") (jolt-inc (var-deref "clojure.pprint" "*current-level*")) (jolt-var "clojure.pprint" "*current-length*") 0))) (begin (jolt-invoke (var-deref "clojure.core" "push-thread-bindings") frame__20__auto) (dynamic-wind (lambda () #f) (lambda () (begin (jolt-invoke (var-deref "clojure.pprint" "start-block") (var-deref "clojure.core" "*out*") "(" jolt-nil ")") (let* ((alis (jolt-seq alis))) (let loop2308 ((alis alis)) (if (jolt-truthy? alis) (begin (jolt-invoke (var-deref "clojure.pprint" "write-out") (jolt-first alis)) (if (jolt-truthy? (jolt-next alis)) (begin (jolt-invoke (var-deref "clojure.pprint" "-write") (var-deref "clojure.core" "*out*") " ") (jolt-invoke (var-deref "clojure.pprint" "pprint-newline") (keyword #f "linear")) (loop2308 (jolt-next alis))) jolt-nil)) jolt-nil))) (jolt-invoke (var-deref "clojure.pprint" "end-block") (var-deref "clojure.core" "*out*")))) (lambda () (jolt-invoke (var-deref "clojure.core" "pop-thread-bindings"))))))) jolt-nil))))) pprint-simple-list) (let* ((_o$2309 (keyword #f "private")) (_o$2310 #t)) (jolt-hash-map _o$2309 _o$2310)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "pprint-list" (letrec ((pprint-list (lambda (alis) (let fnrec2311 ((alis alis)) (if (jolt-not (jolt-invoke (var-deref "clojure.pprint" "pprint-reader-macro") alis)) (jolt-invoke (var-deref "clojure.pprint" "pprint-simple-list") alis) jolt-nil))))) pprint-list) (let* ((_o$2312 (keyword #f "private")) (_o$2313 #t)) (jolt-hash-map _o$2312 _o$2313)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "pprint-vector" (letrec ((pprint-vector (lambda (avec) (let fnrec2314 ((avec avec)) (begin (if (jolt-truthy? (jolt-invoke (var-deref "clojure.pprint" "level-exceeded"))) (jolt-invoke (var-deref "clojure.pprint" "-write") (var-deref "clojure.core" "*out*") "#") (let* ((frame__20__auto (jolt-invoke (var-deref "clojure.core" "array-map") (jolt-var "clojure.pprint" "*current-level*") (jolt-inc (var-deref "clojure.pprint" "*current-level*")) (jolt-var "clojure.pprint" "*current-length*") 0))) (begin (jolt-invoke (var-deref "clojure.core" "push-thread-bindings") frame__20__auto) (dynamic-wind (lambda () #f) (lambda () (begin (jolt-invoke (var-deref "clojure.pprint" "start-block") (var-deref "clojure.core" "*out*") "[" jolt-nil "]") (let* ((aseq (jolt-seq avec))) (let loop2315 ((aseq aseq)) (if (jolt-truthy? aseq) (begin (jolt-invoke (var-deref "clojure.pprint" "write-out") (jolt-first aseq)) (if (jolt-truthy? (jolt-next aseq)) (begin (jolt-invoke (var-deref "clojure.pprint" "-write") (var-deref "clojure.core" "*out*") " ") (jolt-invoke (var-deref "clojure.pprint" "pprint-newline") (keyword #f "linear")) (loop2315 (jolt-next aseq))) jolt-nil)) jolt-nil))) (jolt-invoke (var-deref "clojure.pprint" "end-block") (var-deref "clojure.core" "*out*")))) (lambda () (jolt-invoke (var-deref "clojure.core" "pop-thread-bindings"))))))) jolt-nil))))) pprint-vector) (let* ((_o$2316 (keyword #f "private")) (_o$2317 #t)) (jolt-hash-map _o$2316 _o$2317)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "pprint-array" (let* ((format-in__5__auto "~<[~;~@{~w~^, ~:_~}~;]~:>") (cf__3__auto (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "string?") format-in__5__auto)) (jolt-invoke (var-deref "clojure.pprint" "cached-compile") format-in__5__auto) format-in__5__auto))) (lambda args__4__auto (let fnrec2318 ((args__4__auto (list->cseq args__4__auto))) (let* ((navigator__2__auto (jolt-invoke (var-deref "clojure.pprint" "init-navigator") args__4__auto))) (jolt-invoke (var-deref "clojure.pprint" "execute-format") cf__3__auto navigator__2__auto))))) (let* ((_o$2319 (keyword #f "private")) (_o$2320 #t)) (jolt-hash-map _o$2319 _o$2320)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "pprint-map" (letrec ((pprint-map (lambda (amap) (let fnrec2321 ((amap amap)) (begin (if (jolt-truthy? (jolt-invoke (var-deref "clojure.pprint" "level-exceeded"))) (jolt-invoke (var-deref "clojure.pprint" "-write") (var-deref "clojure.core" "*out*") "#") (let* ((frame__20__auto (jolt-invoke (var-deref "clojure.core" "array-map") (jolt-var "clojure.pprint" "*current-level*") (jolt-inc (var-deref "clojure.pprint" "*current-level*")) (jolt-var "clojure.pprint" "*current-length*") 0))) (begin (jolt-invoke (var-deref "clojure.core" "push-thread-bindings") frame__20__auto) (dynamic-wind (lambda () #f) (lambda () (begin (jolt-invoke (var-deref "clojure.pprint" "start-block") (var-deref "clojure.core" "*out*") "{" jolt-nil "}") (let* ((aseq (jolt-seq amap))) (let loop2322 ((aseq aseq)) (if (jolt-truthy? aseq) (begin (begin (if (jolt-truthy? (jolt-invoke (var-deref "clojure.pprint" "level-exceeded"))) (jolt-invoke (var-deref "clojure.pprint" "-write") (var-deref "clojure.core" "*out*") "#") (let* ((frame__20__auto (jolt-invoke (var-deref "clojure.core" "array-map") (jolt-var "clojure.pprint" "*current-level*") (jolt-inc (var-deref "clojure.pprint" "*current-level*")) (jolt-var "clojure.pprint" "*current-length*") 0))) (begin (jolt-invoke (var-deref "clojure.core" "push-thread-bindings") frame__20__auto) (dynamic-wind (lambda () #f) (lambda () (begin (jolt-invoke (var-deref "clojure.pprint" "start-block") (var-deref "clojure.core" "*out*") jolt-nil jolt-nil jolt-nil) (jolt-invoke (var-deref "clojure.pprint" "write-out") (jolt-invoke (var-deref "clojure.core" "ffirst") aseq)) (jolt-invoke (var-deref "clojure.pprint" "-write") (var-deref "clojure.core" "*out*") " ") (jolt-invoke (var-deref "clojure.pprint" "pprint-newline") (keyword #f "linear")) (jolt-var-set (jolt-var "clojure.pprint" "*current-length*") 0) (jolt-invoke (var-deref "clojure.pprint" "write-out") (jolt-invoke (var-deref "clojure.core" "fnext") (jolt-first aseq))) (jolt-invoke (var-deref "clojure.pprint" "end-block") (var-deref "clojure.core" "*out*")))) (lambda () (jolt-invoke (var-deref "clojure.core" "pop-thread-bindings"))))))) jolt-nil) (if (jolt-truthy? (jolt-next aseq)) (begin (jolt-invoke (var-deref "clojure.pprint" "-write") (var-deref "clojure.core" "*out*") ", ") (jolt-invoke (var-deref "clojure.pprint" "pprint-newline") (keyword #f "linear")) (loop2322 (jolt-next aseq))) jolt-nil)) jolt-nil))) (jolt-invoke (var-deref "clojure.pprint" "end-block") (var-deref "clojure.core" "*out*")))) (lambda () (jolt-invoke (var-deref "clojure.core" "pop-thread-bindings"))))))) jolt-nil))))) pprint-map) (let* ((_o$2323 (keyword #f "private")) (_o$2324 #t)) (jolt-hash-map _o$2323 _o$2324)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "pprint-simple-default" (letrec ((pprint-simple-default (lambda (obj) (let fnrec2325 ((obj obj)) (jolt-invoke (var-deref "clojure.pprint" "-write") (var-deref "clojure.core" "*out*") (jolt-invoke (var-deref "clojure.core" "pr-str") obj)))))) pprint-simple-default) (let* ((_o$2326 (keyword #f "private")) (_o$2327 #t)) (jolt-hash-map _o$2326 _o$2327)))) -(guard (e (#t #f)) - (def-var! "clojure.pprint" "pprint-set" (let* ((format-in__5__auto "~<#{~;~@{~w~^ ~:_~}~;}~:>") (cf__3__auto (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "string?") format-in__5__auto)) (jolt-invoke (var-deref "clojure.pprint" "cached-compile") format-in__5__auto) format-in__5__auto))) (lambda args__4__auto (let fnrec2328 ((args__4__auto (list->cseq args__4__auto))) (let* ((navigator__2__auto (jolt-invoke (var-deref "clojure.pprint" "init-navigator") args__4__auto))) (jolt-invoke (var-deref "clojure.pprint" "execute-format") cf__3__auto navigator__2__auto))))))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "type-dispatcher" (letrec ((type-dispatcher (lambda (obj) (let fnrec2329 ((obj obj)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "symbol?") obj)) (keyword #f "symbol") (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "seq?") obj)) (keyword #f "list") (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "map?") obj)) (keyword #f "map") (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "vector?") obj)) (keyword #f "vector") (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "set?") obj)) (keyword #f "set") (if (jolt-nil? obj) jolt-nil (if (jolt-truthy? (keyword #f "else")) (keyword #f "default") jolt-nil))))))))))) type-dispatcher) (let* ((_o$2330 (keyword #f "private")) (_o$2331 #t)) (jolt-hash-map _o$2330 _o$2331)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "simple-dispatch" (letrec ((simple-dispatch (lambda (obj) (let fnrec2332 ((obj obj)) (let* ((G__102 (jolt-invoke (var-deref "clojure.pprint" "type-dispatcher") obj))) (if (jolt= G__102 (keyword #f "list")) (jolt-invoke (var-deref "clojure.pprint" "pprint-list") obj) (if (jolt= G__102 (keyword #f "vector")) (jolt-invoke (var-deref "clojure.pprint" "pprint-vector") obj) (if (jolt= G__102 (keyword #f "map")) (jolt-invoke (var-deref "clojure.pprint" "pprint-map") obj) (if (jolt= G__102 (keyword #f "set")) (jolt-invoke (var-deref "clojure.pprint" "pprint-set") obj) (if (jolt= G__102 jolt-nil) (jolt-invoke (var-deref "clojure.pprint" "-write") (var-deref "clojure.core" "*out*") (jolt-invoke (var-deref "clojure.core" "pr-str") jolt-nil)) (jolt-invoke (var-deref "clojure.pprint" "pprint-simple-default") obj))))))))))) simple-dispatch) (let* ((_o$2333 (keyword #f "doc")) (_o$2334 "The pretty print dispatch function for simple data structure format.")) (jolt-hash-map _o$2333 _o$2334)))) -(guard (e (#t #f)) - (declare-var! "clojure.pprint" "pprint-simple-code-list")) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "brackets" (letrec ((brackets (lambda (form) (let fnrec2335 ((form form)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "vector?") form)) (let* ((_o$2336 "[") (_o$2337 "]")) (jolt-vector _o$2336 _o$2337)) (let* ((_o$2338 "(") (_o$2339 ")")) (jolt-vector _o$2338 _o$2339))))))) brackets) (let* ((_o$2340 (keyword #f "private")) (_o$2341 #t)) (jolt-hash-map _o$2340 _o$2341)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "pprint-simple-code-list" (letrec ((pprint-simple-code-list (lambda (alis) (let fnrec2342 ((alis alis)) (begin (if (jolt-truthy? (jolt-invoke (var-deref "clojure.pprint" "level-exceeded"))) (jolt-invoke (var-deref "clojure.pprint" "-write") (var-deref "clojure.core" "*out*") "#") (let* ((frame__20__auto (jolt-invoke (var-deref "clojure.core" "array-map") (jolt-var "clojure.pprint" "*current-level*") (jolt-inc (var-deref "clojure.pprint" "*current-level*")) (jolt-var "clojure.pprint" "*current-length*") 0))) (begin (jolt-invoke (var-deref "clojure.core" "push-thread-bindings") frame__20__auto) (dynamic-wind (lambda () #f) (lambda () (begin (jolt-invoke (var-deref "clojure.pprint" "start-block") (var-deref "clojure.core" "*out*") "(" jolt-nil ")") (jolt-invoke (var-deref "clojure.pprint" "pprint-indent") (keyword #f "block") 1) (let* ((alis (jolt-seq alis))) (let loop2343 ((alis alis)) (if (jolt-truthy? alis) (begin (jolt-invoke (var-deref "clojure.pprint" "write-out") (jolt-first alis)) (if (jolt-truthy? (jolt-next alis)) (begin (jolt-invoke (var-deref "clojure.pprint" "-write") (var-deref "clojure.core" "*out*") " ") (jolt-invoke (var-deref "clojure.pprint" "pprint-newline") (keyword #f "linear")) (loop2343 (jolt-next alis))) jolt-nil)) jolt-nil))) (jolt-invoke (var-deref "clojure.pprint" "end-block") (var-deref "clojure.core" "*out*")))) (lambda () (jolt-invoke (var-deref "clojure.core" "pop-thread-bindings"))))))) jolt-nil))))) pprint-simple-code-list) (let* ((_o$2344 (keyword #f "private")) (_o$2345 #t)) (jolt-hash-map _o$2344 _o$2345)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "pprint-code-list" (letrec ((pprint-code-list (lambda (alis) (let fnrec2346 ((alis alis)) (if (jolt-not (jolt-invoke (var-deref "clojure.pprint" "pprint-reader-macro") alis)) (jolt-invoke (var-deref "clojure.pprint" "pprint-simple-code-list") alis) jolt-nil))))) pprint-code-list) (let* ((_o$2347 (keyword #f "private")) (_o$2348 #t)) (jolt-hash-map _o$2347 _o$2348)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "pprint-code-symbol" (letrec ((pprint-code-symbol (lambda (sym) (let fnrec2349 ((sym sym)) (if (jolt-truthy? (var-deref "clojure.pprint" "*print-suppress-namespaces*")) (jolt-invoke (var-deref "clojure.pprint" "print") (jolt-invoke (var-deref "clojure.core" "name") sym)) (jolt-invoke (var-deref "clojure.pprint" "pr") sym)))))) pprint-code-symbol) (let* ((_o$2350 (keyword #f "private")) (_o$2351 #t)) (jolt-hash-map _o$2350 _o$2351)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "code-dispatch" (letrec ((code-dispatch (lambda (obj) (let fnrec2352 ((obj obj)) (let* ((G__103 (jolt-invoke (var-deref "clojure.pprint" "type-dispatcher") obj))) (if (jolt= G__103 (keyword #f "list")) (jolt-invoke (var-deref "clojure.pprint" "pprint-code-list") obj) (if (jolt= G__103 (keyword #f "symbol")) (jolt-invoke (var-deref "clojure.pprint" "pprint-code-symbol") obj) (if (jolt= G__103 (keyword #f "vector")) (jolt-invoke (var-deref "clojure.pprint" "pprint-vector") obj) (if (jolt= G__103 (keyword #f "map")) (jolt-invoke (var-deref "clojure.pprint" "pprint-map") obj) (if (jolt= G__103 (keyword #f "set")) (jolt-invoke (var-deref "clojure.pprint" "pprint-set") obj) (if (jolt= G__103 jolt-nil) (jolt-invoke (var-deref "clojure.pprint" "pr") obj) (jolt-invoke (var-deref "clojure.pprint" "pprint-simple-default") obj)))))))))))) code-dispatch) (let* ((_o$2353 (keyword #f "doc")) (_o$2354 "The pretty print dispatch function for pretty printing Clojure code.")) (jolt-hash-map _o$2353 _o$2354)))) -(guard (e (#t #f)) - (jolt-invoke (var-deref "clojure.core" "alter-var-root") (jolt-var "clojure.pprint" "*print-pprint-dispatch*") (jolt-invoke (var-deref "clojure.core" "constantly") (var-deref "clojure.pprint" "simple-dispatch")))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "add-padding" (letrec ((add-padding (lambda (width s) (let fnrec2355 ((width width) (s s)) (let* ((padding (jolt-n-max 0 (jolt-n- width (jolt-count s))))) (jolt-apply (var-deref "clojure.core" "str") (jolt-invoke (var-deref "clojure.string" "join") (jolt-invoke (var-deref "clojure.core" "repeat") padding (integer->char 32))) s)))))) add-padding) (let* ((_o$2356 (keyword #f "private")) (_o$2357 #t)) (jolt-hash-map _o$2356 _o$2357)))) -(guard (e (#t #f)) - (def-var-with-meta! "clojure.pprint" "print-table" (letrec ((print-table (case-lambda ((ks rows) (let fnrec2358 ((ks ks) (rows rows)) (if (jolt-truthy? (jolt-seq rows)) (let* ((widths (jolt-map (lambda (k) (let fnrec2359 ((k k)) (let* ((_a$2361 jolt-max) (_a$2362 (jolt-count (jolt-invoke (var-deref "clojure.core" "str") k))) (_a$2363 (jolt-map (lambda (p__39_) (let fnrec2360 ((p__39_ p__39_)) (jolt-count (jolt-invoke (var-deref "clojure.core" "str") (jolt-get p__39_ k))))) rows))) (jolt-apply _a$2361 _a$2362 _a$2363)))) ks)) (spacers (jolt-map (lambda (p__40_) (let fnrec2364 ((p__40_ p__40_)) (jolt-apply (var-deref "clojure.core" "str") (jolt-invoke (var-deref "clojure.core" "repeat") p__40_ "-")))) widths)) (fmt-row (lambda (leader divider trailer row) (let fnrec2365 ((leader leader) (divider divider) (trailer trailer) (row row)) (jolt-invoke (var-deref "clojure.core" "str") leader (jolt-apply (var-deref "clojure.core" "str") (jolt-invoke (var-deref "clojure.core" "interpose") divider (let* ((_a$2368 (lambda (G__104) (let fnrec2366 ((G__104 G__104)) (let* ((G__105 G__104) (col (jolt-nth G__105 0 jolt-nil)) (width (jolt-nth G__105 1 jolt-nil))) (jolt-invoke (var-deref "clojure.pprint" "add-padding") width (jolt-invoke (var-deref "clojure.core" "str") col)))))) (_a$2369 (jolt-map jolt-vector (jolt-map (lambda (p__41_) (let fnrec2367 ((p__41_ p__41_)) (jolt-get row p__41_))) ks) widths))) (jolt-map _a$2368 _a$2369)))) trailer))))) (begin (jolt-invoke (var-deref "clojure.core" "println")) (jolt-invoke (var-deref "clojure.core" "println") (jolt-invoke fmt-row "| " " | " " |" (jolt-invoke (var-deref "clojure.core" "zipmap") ks ks))) (jolt-invoke (var-deref "clojure.core" "println") (jolt-invoke fmt-row "|-" "-+-" "-|" (jolt-invoke (var-deref "clojure.core" "zipmap") ks spacers))) (begin (jolt-count (jolt-map (lambda (row) (let fnrec2370 ((row row)) (begin (jolt-invoke (var-deref "clojure.core" "println") (jolt-invoke fmt-row "| " " | " " |" row)) jolt-nil))) rows)) jolt-nil))) jolt-nil))) ((rows) (let fnrec2371 ((rows rows)) (print-table (jolt-keys (jolt-first rows)) rows)))))) print-table) (let* ((_o$2372 (keyword #f "doc")) (_o$2373 "Prints a collection of maps in a textual table.")) (jolt-hash-map _o$2372 _o$2373)))) -(guard (e (#t #f)) - (jolt-invoke (var-deref "clojure.core" "__set-pprint-write-hook!") (lambda (s) (let fnrec2374 ((s s)) (let* ((o (var-deref "clojure.core" "*out*"))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "instance-check") (jolt-symbol #f "PrettyWriter") o)) (begin (jolt-invoke (var-deref "clojure.pprint" "-write") o s) #t) jolt-nil)))))) \ No newline at end of file diff --git a/host/chez/selfcheck.sh b/host/chez/selfcheck.sh deleted file mode 100755 index 509ccdd..0000000 --- a/host/chez/selfcheck.sh +++ /dev/null @@ -1,18 +0,0 @@ -#!/bin/sh -# self-host fixpoint gate: bootstrap.ss rebuilds the prelude + compiler image from -# source on pure Chez; the rebuild must equal the checked-in seed byte-for-byte. If -# it doesn't, a seed source changed without a re-mint — run `make remint`. -set -e -root="$(CDPATH= cd -- "$(dirname -- "$0")/../.." && pwd)" -cd "$root" -tmp="$(mktemp -d)" -trap 'rm -rf "$tmp"' EXIT -chez --script host/chez/bootstrap.ss \ - host/chez/seed/prelude.ss host/chez/seed/image.ss "$tmp/p.ss" "$tmp/i.ss" >/dev/null -if diff -q host/chez/seed/prelude.ss "$tmp/p.ss" >/dev/null \ - && diff -q host/chez/seed/image.ss "$tmp/i.ss" >/dev/null; then - echo "self-host fixpoint: rebuild == checked-in seed" -else - echo "self-host FAILED: bootstrap rebuild != checked-in seed; run 'make remint'" >&2 - exit 1 -fi diff --git a/host/chez/seq.ss b/host/chez/seq.ss deleted file mode 100644 index b10ed50..0000000 --- a/host/chez/seq.ss +++ /dev/null @@ -1,819 +0,0 @@ -;; The seq tier on the Chez RT. -;; -;; One lazy-capable node (cseq) models Clojure's list, cons, and lazy seq — all -;; print as (...), all sequential-= to each other AND to vectors. `jolt-seq` -;; coerces any seqable (vector/map/set/string/list/seq/nil) to a cseq or nil. -;; The empty seq is a distinct value (jolt-empty-list) that prints "()" — Clojure -;; (rest [1]) is () not nil, (seq []) is nil. The higher-order fns -;; (map/filter/reduce/into/remove) apply their fn argument through `jolt-invoke`, -;; so a procedure, a keyword, or a collection all work as the fn (IFn dispatch). -;; -;; Loaded by rt.ss after collections.ss. values.ss / collections.ss reach the -;; jolt-sequential? / seq=? / seq-hash hooks defined here as forward refs (nothing -;; is CALLED during load). - -;; ============================================================================ -;; the seq node + the empty-seq sentinel -;; ============================================================================ -;; head : the realized first element. tail : EITHER a realized seq (cseq | -;; jolt-nil) when forced? is #t, OR a 0-arg thunk producing one when forced? is -;; #f. Forcing memoizes (set the tail to the produced seq, flip forced?). -;; list? : #t when this cell is a PersistentList node (list literal / (list ...) -;; / cons / reverse / conj-onto-list) vs a lazy or vector-backed seq cell — the -;; only thing that distinguishes a list from any other realized seq on this host, -;; since one record type backs both (clojure.core/list?). The marker -;; lives on the cell, so (rest a-list) / (seq a-vector) / (map …) yield plain seq -;; cells and are not list?. -;; cvec/ci: for a vector-backed seq cell, the backing vector and this cell's -;; element index — so it is a real chunked-seq (chunked-seq? true, chunk-first -;; hands out a 32-element block, chunk-rest is the seq at the next block) and -;; reduce iterates the vector directly with no per-element cells. -;; cvec is #f for every other seq; stored as two fields (not a cons) so a vector -;; seq cell costs no extra allocation. The rest of the seq layer ignores them, so -;; first/rest/count/printing are unchanged. -;; crest: the ChunkedCons case — cvec holds a STANDALONE chunk pvec (<=32 already- -;; realized elements), ci the offset within it, and crest the seq AFTER the whole -;; chunk (the clojure.lang.ChunkedCons _more). This is what map/filter/range emit -;; so their result is itself a chunked-seq (chained chunked transforms each batch -;; by 32, like the JVM). crest is #f for a plain vector-backed seq (whose "rest" -;; is the next 32-block of the SAME cvec) and for every non-chunked cell. -(define-record-type cseq (fields head (mutable tail) (mutable forced?) list? cvec ci crest) (nongenerative chez-cseq-v4)) -(define (cseq-realized head tail) (make-cseq head tail #t #f #f 0 #f)) ; tail already a seq -(define (cseq-lazy head tail-thunk) (make-cseq head tail-thunk #f #f #f 0 #f)) -(define (cseq-list head tail) (make-cseq head tail #t #t #f 0 #f)) ; a PersistentList node -(define (cseq-vec head tail-thunk v i) (make-cseq head tail-thunk #f #f v i #f)) ; vector-backed -;; A ChunkedCons cell over a standalone chunk pvec: head is chunk[i], walking -;; (seq-more) advances within the chunk and then continues into `rest`. `rest` is -;; the already-coerced after-chunk seq (cseq | jolt-nil | a jolt-lazyseq), held in -;; crest for chunk-rest/chunk-next and forced lazily by the tail thunk at the chunk -;; boundary so a chunked map over an infinite chunked source stays productive. -(define (cseq-chunked chunk i rest) - (make-cseq (pvec-nth-d chunk i jolt-nil) - (lambda () (let ((i1 (fx+ i 1))) - (if (fxcseq xs) ; Scheme list -> realized cseq chain (jolt-nil if empty) - (if (null? xs) jolt-nil (cseq-realized (car xs) (list->cseq (cdr xs))))) -(define (vec->seq v i) ; chunked index seq over a persistent vector - (if (fx>=? i (pvec-count v)) jolt-nil - (cseq-vec (pvec-nth-d v i jolt-nil) (lambda () (vec->seq v (fx+ i 1))) v i))) -(define (str->seq s i) - (if (fx>=? i (string-length s)) jolt-nil - (cseq-lazy (string-ref s i) (lambda () (str->seq s (fx+ i 1)))))) -(define (jolt-seq x) - (cond - ((jolt-nil? x) jolt-nil) - ((empty-list-t? x) jolt-nil) - ((cseq? x) x) - ((pvec? x) (vec->seq x 0)) - ((pmap? x) (list->cseq (pmap-fold x (lambda (k v a) (cons (make-map-entry k v) a)) '()))) - ((pset? x) (list->cseq (pset-fold x cons '()))) - ((string? x) (str->seq x 0)) - (else (error 'seq "not seqable" x)))) - -(define (jolt-sequential? x) (or (pvec? x) (cseq? x) (empty-list-t? x))) -(define (seq->list s) ; force a finite seq to a Scheme list - (let loop ((s (jolt-seq s)) (acc '())) - (if (jolt-nil? s) (reverse acc) (loop (jolt-seq (seq-more s)) (cons (seq-first s) acc))))) - -;; ============================================================================ -;; the seq leaf ops the emitter lowers core fns to -;; ============================================================================ -(define (jolt-first x) (let ((s (jolt-seq x))) (if (jolt-nil? s) jolt-nil (seq-first s)))) -;; rest = Clojure's more(): the tail as a (possibly empty) seq, NOT nil, and -;; WITHOUT realizing it. A forced cseq (list / realized chain) hands back its tail -;; directly. An UNFORCED tail (vector / string / lazy-seq cell) is returned as a -;; deferred seq so (rest s) does not realize the next node — matching Clojure, -;; where (rest (iterate f x)) does not call f and a side-effecting lazy seq is -;; realized one element at a time. next = (seq (rest s)) still realizes one. -;; jolt-make-lazy-seq (lazy-bridge.ss) resolves at call time. -(define (jolt-rest x) - (let ((s (jolt-seq x))) - (cond - ((jolt-nil? s) jolt-empty-list) - ((cseq-forced? s) (let ((m (cseq-tail s))) (if (jolt-nil? m) jolt-empty-list m))) - ;; the lazyseq forces to a seq (cseq | nil); an empty realized lazyseq is - ;; still a sequence value, printing "()" (see lazy-bridge.ss), so (rest s) - ;; is never nil even when the tail is empty. jolt-seq coerces seq-more's - ;; result (which may be jolt-empty-list, e.g. map's tail) back to cseq | nil, - ;; the contract force-lazyseq relies on — else (seq (rest s)) of an empty - ;; tail yields a truthy empty-list and walkers (distinct, dedupe) overrun. - (else (jolt-make-lazy-seq (lambda () (jolt-seq (seq-more s)))))))) -(define (jolt-next x) ; nil when the rest is empty - ;; next = (seq (rest x)): the rest must be RE-SEQ'd so an empty tail collapses to - ;; nil. seq-more on a lazy seq (e.g. map's) forces to jolt-empty-list, which is - ;; truthy — returning it raw made (next 1-elem-lazy-seq) non-nil, so butlast and - ;; other (if (next s) ...) loops over a lazy seq ran one step too far. - (let ((s (jolt-seq x))) (if (jolt-nil? s) jolt-nil (jolt-seq (seq-more s))))) -;; Only the HEAD cell carries the list marker — (rest a-list)/(next a-list) return -;; the unmarked tail, so they are seqs and not list? (rest-of-a-list is a non-list -;; seq). cons/list/reverse/conj therefore mark -;; just the cell they create. -;; -;; cons always yields a list — (list? (cons x anything)) is true (cons -;; onto a vector/seq/nil all report list?). -(define (jolt-cons x coll) (cseq-list x (jolt-seq coll))) -;; Scheme list -> a jolt PersistentList: head is a list cell, the tail chain is -;; plain seq cells. For (list …) and quoted list literals (the emitter lowers -;; '(a b) to (jolt-list a b)). -(define (jolt-list . xs) - (if (null? xs) jolt-empty-list (cseq-list (car xs) (list->cseq (cdr xs))))) -;; reverse yields a list (seed: (list? (reverse coll)) is always true). Build a -;; plain seq chain, then mark its head as a list cell. -(define (jolt-reverse coll) - (let loop ((s (jolt-seq coll)) (acc jolt-empty-list)) - (if (jolt-nil? s) - (if (empty-list-t? acc) acc (cseq-list (seq-first acc) (seq-more acc))) - (loop (jolt-seq (seq-more s)) (cseq-realized (seq-first s) (if (empty-list-t? acc) jolt-nil acc)))))) -(define (jolt-last coll) (let loop ((s (jolt-seq coll)) (last jolt-nil)) - (if (jolt-nil? s) last (loop (jolt-seq (seq-more s)) (seq-first s))))) -;; nth over a seq (walks; forces lazily). default? selects the 3-arg behavior. -(define (seq-nth coll i default? d) - (if (fx ClassCastException. The hooks are BINARY and never re-enter -;; the variadic shims, so extension order can't recurse. -(define (jolt-add-slow a b) (jolt-num-cast-throw (if (number? a) b a))) -(define (jolt-sub-slow a b) (jolt-num-cast-throw (if (number? a) b a))) -(define (jolt-mul-slow a b) (jolt-num-cast-throw (if (number? a) b a))) -(define (jolt-div-slow a b) (jolt-num-cast-throw (if (number? a) b a))) -;; comparison of operands outside the Chez tower: numeric shims extend this to a -;; 3-way compare; anything left over is not a number. -(define (jolt-num-cmp-slow a b) - (jolt-num-cast-throw (if (number? a) b a))) - -(define (jolt-add2 a b) - (if (and (number? a) (number? b)) (+ a b) (jolt-add-slow a b))) -(define (jolt-sub2 a b) - (if (and (number? a) (number? b)) (- a b) (jolt-sub-slow a b))) -(define (jolt-mul2 a b) - (if (and (number? a) (number? b)) - (if (or (flonum? a) (flonum? b)) - (fl* (real->flonum a) (real->flonum b)) - (* a b)) - (jolt-mul-slow a b))) -(define (jolt-div2 a b) - (if (and (number? a) (number? b)) - (if (or (flonum? a) (flonum? b)) - (fl/ (real->flonum a) (real->flonum b)) - (if (eqv? b 0) (jolt-div0-throw) (/ a b))) - (jolt-div-slow a b))) -(define (jolt-lt2 a b) - (if (and (number? a) (number? b)) (< a b) (< (jolt-num-cmp-slow a b) 0))) -(define (jolt-gt2 a b) - (if (and (number? a) (number? b)) (> a b) (> (jolt-num-cmp-slow a b) 0))) -(define (jolt-le2 a b) - (if (and (number? a) (number? b)) (<= a b) (<= (jolt-num-cmp-slow a b) 0))) -(define (jolt-ge2 a b) - (if (and (number? a) (number? b)) (>= a b) (>= (jolt-num-cmp-slow a b) 0))) -;; min/max return the ORIGINAL operand (type and exactness kept, like -;; Numbers.min): (min 1 2.0) is 1, not 1.0. A NaN operand wins. -(define (jolt-min2 a b) - (cond ((and (flonum? a) (nan? a)) a) - ((and (flonum? b) (nan? b)) b) - (else (if (jolt-lt2 a b) a b)))) -(define (jolt-max2 a b) - (cond ((and (flonum? a) (nan? a)) a) - ((and (flonum? b) (nan? b)) b) - (else (if (jolt-gt2 a b) a b)))) - -;; quot/rem/mod over the full tower: truncating division; a double operand makes -;; the result a double; mod has floor semantics (result takes the divisor's -;; sign). A zero divisor throws ArithmeticException in both worlds (JVM double -;; quot/rem check the divisor before dividing). Non-tower operands hit the -;; set!-extensible slow hooks. -(define (jolt-quot-slow a b) (jolt-num-cast-throw (if (number? a) b a))) -(define (jolt-rem-slow a b) (jolt-num-cast-throw (if (number? a) b a))) -(define (jolt-mod-slow a b) (jolt-num-cast-throw (if (number? a) b a))) -(define (jolt-quot a b) - (cond ((not (and (number? a) (number? b))) (jolt-quot-slow a b)) - ((or (flonum? a) (flonum? b)) - (let ((n (real->flonum a)) (d (real->flonum b))) - (if (fl= d 0.0) (jolt-div0-throw) - (let ((q (fl/ n d))) - (when (or (nan? q) (infinite? q)) - (jolt-throw (jolt-host-throwable "java.lang.NumberFormatException" - "Infinite or NaN"))) - (fltruncate q))))) - ((eqv? b 0) (jolt-div0-throw)) - ((and (integer? a) (integer? b)) (quotient a b)) - (else (truncate (/ a b))))) -(define (jolt-rem a b) - (cond ((not (and (number? a) (number? b))) (jolt-rem-slow a b)) - ((or (flonum? a) (flonum? b)) - (let ((n (real->flonum a)) (d (real->flonum b))) - (if (fl= d 0.0) (jolt-div0-throw) - (let ((q (fl/ n d))) - (when (or (nan? q) (infinite? q)) - (jolt-throw (jolt-host-throwable "java.lang.NumberFormatException" - "Infinite or NaN"))) - (fl- n (fl* d (fltruncate q))))))) - ((eqv? b 0) (jolt-div0-throw)) - ((and (integer? a) (integer? b)) (remainder a b)) - (else (- a (* b (truncate (/ a b))))))) -(define (jolt-mod a b) - (cond ((not (and (number? a) (number? b))) (jolt-mod-slow a b)) - ((and (integer? a) (integer? b) (not (flonum? a)) (not (flonum? b))) - (if (eqv? b 0) (jolt-div0-throw) (modulo a b))) - (else - (let ((m (jolt-rem a b))) - (if (or (zero? m) (eq? (negative? m) (negative? b))) m (jolt-add2 m b)))))) - -;; value-position arithmetic (the higher-order forms: (reduce + []), (apply * xs)). -;; Folded through the binary dispatch so contagion/edge rules hold; identities -;; (+)=0 / (*)=1 are exact, matching exact integer arithmetic. The hot path uses -;; the inlined native ops, not these. -;; recognizer for slow-path numeric types; numeric shims extend it. -(define (jolt-num-slow? x) #f) -(define (jolt-num-check1 x) ; (+ x)/(* x) return x but still type-check it - (if (or (number? x) (jolt-num-slow? x)) x (jolt-num-cast-throw x))) -(define (jolt-add . xs) - (cond ((null? xs) 0) - ((null? (cdr xs)) (jolt-num-check1 (car xs))) - (else (fold-left jolt-add2 (car xs) (cdr xs))))) -(define (jolt-arity0-throw name) - (jolt-throw (jolt-host-throwable - "clojure.lang.ArityException" - (string-append "Wrong number of args (0) passed to: clojure.core/" name)))) -(define (jolt-sub . xs) - (cond ((null? xs) (jolt-arity0-throw "-")) - ((null? (cdr xs)) (jolt-sub2 0 (car xs))) - (else (fold-left jolt-sub2 (car xs) (cdr xs))))) -(define (jolt-mul . xs) - (cond ((null? xs) 1) - ((null? (cdr xs)) (jolt-num-check1 (car xs))) - (else (fold-left jolt-mul2 (car xs) (cdr xs))))) -(define (jolt-div . xs) - (cond ((null? xs) (jolt-arity0-throw "/")) - ((null? (cdr xs)) (jolt-div2 1 (car xs))) - (else (fold-left jolt-div2 (car xs) (cdr xs))))) -(define (jolt-min x . xs) (fold-left jolt-min2 x xs)) -(define (jolt-max x . xs) (fold-left jolt-max2 x xs)) -;; variadic comparison chains for value position ((apply < xs)). -(define (jolt-cmp-chain op2) - (lambda (x . xs) - (let loop ((a x) (rest xs)) - (cond ((null? rest) #t) - ((op2 a (car rest)) (loop (car rest) (cdr rest))) - (else #f))))) -(define jolt-lt (jolt-cmp-chain jolt-lt2)) -(define jolt-gt (jolt-cmp-chain jolt-gt2)) -(define jolt-le (jolt-cmp-chain jolt-le2)) -(define jolt-ge (jolt-cmp-chain jolt-ge2)) - -;; call-position arithmetic: inlined macros with the both-Chez-numbers fast path -;; open-coded; anything else falls to the binary dispatch above. Comparisons -;; return a genuine Scheme boolean (the backend's truthy elision relies on it). -(define-syntax jolt-n+ - (syntax-rules () - ((_) 0) - ((_ a) (jolt-add a)) - ((_ ea eb) (let ((a ea) (b eb)) - (if (and (number? a) (number? b)) (+ a b) (jolt-add a b)))) - ((_ a b c ...) (jolt-n+ (jolt-n+ a b) c ...)))) -(define-syntax jolt-n- - (syntax-rules () - ((_) (jolt-sub)) - ((_ a) (jolt-sub a)) - ((_ ea eb) (let ((a ea) (b eb)) - (if (and (number? a) (number? b)) (- a b) (jolt-sub a b)))) - ((_ a b c ...) (jolt-n- (jolt-n- a b) c ...)))) -(define-syntax jolt-n* - (syntax-rules () - ((_) 1) - ((_ a) (jolt-mul a)) - ((_ ea eb) (let ((a ea) (b eb)) - (if (and (number? a) (number? b)) - (if (or (flonum? a) (flonum? b)) - (fl* (real->flonum a) (real->flonum b)) - (* a b)) - (jolt-mul a b)))) - ((_ a b c ...) (jolt-n* (jolt-n* a b) c ...)))) -(define-syntax jolt-n-div - (syntax-rules () - ((_) (jolt-div)) - ((_ a) (jolt-div a)) - ((_ a b) (jolt-div2 a b)) - ((_ a b c ...) (jolt-n-div (jolt-div2 a b) c ...)))) -(define-syntax define-n-cmp - (syntax-rules () - ((_ name op op2) - (define-syntax name - (syntax-rules () - ((_) (op2)) - ((_ a) (begin a #t)) - ((_ ea eb) (let ((a ea) (b eb)) - (if (and (number? a) (number? b)) (op a b) (op2 a b)))) - ((_ ea eb c (... ...)) (let ((a ea) (b eb)) - (and (name a b) (name b c (... ...)))))))))) -(define-n-cmp jolt-n< < jolt-lt2) -(define-n-cmp jolt-n> > jolt-gt2) -(define-n-cmp jolt-n<= <= jolt-le2) -(define-n-cmp jolt-n>= >= jolt-ge2) -(define-syntax jolt-n-min - (syntax-rules () - ((_) (jolt-min)) - ((_ a) (jolt-min a)) - ((_ a b) (jolt-min2 a b)) - ((_ a b c ...) (jolt-n-min (jolt-min2 a b) c ...)))) -(define-syntax jolt-n-max - (syntax-rules () - ((_) (jolt-max)) - ((_ a) (jolt-max a)) - ((_ a b) (jolt-max2 a b)) - ((_ a b c ...) (jolt-n-max (jolt-max2 a b) c ...)))) - -;; --- unchecked (Java long) arithmetic: wrap to signed 64 bits ---------------- -;; Clojure's unchecked-* (and +/-/* under *unchecked-math*) are long ops that -;; WRAP on overflow; jolt's checked arithmetic is arbitrary-precision. These -;; truncate to the low 64 bits as a two's-complement signed long. Chez fixnums are -;; 61-bit, so wrapping uses bignum bit ops + a mask (no fx fast path). The backend -;; emits the binary jolt-unc* for :long-typed unchecked ops; the variadic -;; clojure.core/unchecked-* fns reduce through them. -(define unc-mask64 #xFFFFFFFFFFFFFFFF) -(define unc-2^63 #x8000000000000000) -(define unc-2^64 #x10000000000000000) -(define unc-neg-2^63 (- unc-2^63)) -;; Wrap to a signed 64-bit value. Fast path: an exact integer already in -;; [-2^63, 2^63) is its own wrap — skip the bignum mask, which on Chez (61-bit -;; fixnums) allocates for any value past 2^60. Only an out-of-range result (a -;; multiply overflowing into 128 bits) needs the mask + sign fixup. -(define (jolt-wrap64 x) - (if (and (exact? x) (integer? x) (>= x unc-neg-2^63) (< x unc-2^63)) - x - (let ((m (bitwise-and (if (and (number? x) (exact? x) (integer? x)) x (exact (floor x))) unc-mask64))) - (if (>= m unc-2^63) (- m unc-2^64) m)))) -;; unchecked-* only WRAP integer (long) math; on a flonum OR ratio operand they -;; are an ordinary numeric op, since *unchecked-math* never wraps a non-long — -;; Clojure's unchecked-add falls back to regular arithmetic for non-primitives: -;; (unchecked-multiply 1.5 2.0) => 3.0, (unchecked-add 2/3 2/3) => 4/3, not a -;; truncated long. (test.check's rand-double is (* double-unit shifted), and -;; gen/ratio sums ratios, both under *unchecked-math*.) Wrap iff both are exact -;; integers. -(define (unc-int? x) (and (exact? x) (integer? x))) -(define (jolt-uncadd2 a b) (if (and (unc-int? a) (unc-int? b)) (jolt-wrap64 (+ a b)) (+ a b))) -(define (jolt-uncsub2 a b) (if (and (unc-int? a) (unc-int? b)) (jolt-wrap64 (- a b)) (- a b))) -(define (jolt-uncmul2 a b) (if (and (unc-int? a) (unc-int? b)) (jolt-wrap64 (* a b)) (* a b))) -(define (jolt-uncinc x) (if (unc-int? x) (jolt-wrap64 (+ x 1)) (+ x 1))) -(define (jolt-uncdec x) (if (unc-int? x) (jolt-wrap64 (- x 1)) (- x 1))) -(define (jolt-uncneg x) (if (unc-int? x) (jolt-wrap64 (- x)) (- x))) -(define (jolt-unchecked-add . xs) (if (null? xs) 0 (fold-left jolt-uncadd2 (car xs) (cdr xs)))) -(define (jolt-unchecked-mul . xs) (if (null? xs) 1 (fold-left jolt-uncmul2 (car xs) (cdr xs)))) -(define (jolt-unchecked-sub . xs) - (cond ((null? xs) 0) ((null? (cdr xs)) (jolt-uncneg (car xs))) (else (fold-left jolt-uncsub2 (car xs) (cdr xs))))) -(define (jolt-unchecked-div a b) (quotient (jolt-wrap64 a) (jolt-wrap64 b))) -(define (jolt-unchecked-rem a b) (remainder (jolt-wrap64 a) (jolt-wrap64 b))) -;; the clojure.core/unchecked-* vars are def-var!'d in natives-seq.ss (def-var! is -;; defined after this file loads). - -;; --- ^long ops that tolerate a full 64-bit value ----------------------------- -;; A ^long is 64-bit but a Chez fixnum is only 61-bit, so the backend's fast fx -;; ops would raise on a value past 2^60 (e.g. a long from the PRNG / wrapping -;; arithmetic). These take the fx fast path when the operands ARE fixnums and fall -;; back to the generic op otherwise — so ^long comparisons / quot / min etc. on a -;; full-width long stay correct. Macros (define-syntax) so the fast path inlines. -(define-syntax define-l-binop - (syntax-rules () - ((_ name fxop genop) - (define-syntax name - (syntax-rules () - ((_ a b) (let ((x a) (y b)) - (if (and (fixnum? x) (fixnum? y)) (fxop x y) (genop x y))))))))) -(define-l-binop jolt-l< fx fx>? >) -(define-l-binop jolt-l>= fx>=? >=) -(define-l-binop jolt-l= fx=? =) -(define-l-binop jolt-l-min fxmin min) -(define-l-binop jolt-l-max fxmax max) -(define-l-binop jolt-l-quot fxquotient quotient) -(define-l-binop jolt-l-rem fxremainder remainder) -(define-l-binop jolt-l-mod fxmodulo modulo) -(define-syntax jolt-l-inc (syntax-rules () ((_ a) (let ((x a)) (if (fixnum? x) (fx1+ x) (+ x 1)))))) -(define-syntax jolt-l-dec (syntax-rules () ((_ a) (let ((x a)) (if (fixnum? x) (fx1- x) (- x 1)))))) - -;; ============================================================================ -;; IFn dispatch — the dynamic "value as fn" fallback. A callee that the emitter -;; can't statically resolve to a procedure (a keyword/coll/proc held in a local) -;; routes here. Off the arithmetic/self-recursion hot path by construction. -;; ============================================================================ -;; (pred . handler) arms making a host type invocable; handler gets (f args). -(define jolt-invoke-arms '()) -(define (register-invoke-arm! pred handler) - (set! jolt-invoke-arms (cons (cons pred handler) jolt-invoke-arms))) -(define (jolt-invoke-arm-for f) - (let loop ((as jolt-invoke-arms)) - (cond ((null? as) #f) - (((caar as) f) (cdar as)) - (else (loop (cdr as)))))) - -(define (jolt-invoke f . args) - (cond - ((procedure? f) (apply f args)) - ((keyword? f) (apply jolt-get (car args) f (cdr args))) ; (:k m [d]) -> (get m :k [d]) - ((jolt-symbol? f) (apply jolt-get (car args) f (cdr args))) ; ('s m [d]) -> (get m 's [d]) - ;; a VECTOR invokes as nth (a bad index throws, like IPersistentVector.invoke); - ;; maps and sets invoke as get. - ((pvec? f) (if (and (pair? args) (null? (cdr args))) - (jolt-nth f (car args)) - (apply jolt-get f args))) - ((jolt-coll? f) (apply jolt-get f args)) ; (coll k [d]) -> (get coll k [d]) - ((jolt-transient? f) (apply jolt-get f args)) ; a transient vec/map/set is callable on the JVM - ;; a record/reify implementing clojure.lang.IFn is callable: dispatch to its - ;; inline `invoke` method with the value itself as the leading `this`. - ((and (jrec? f) (find-method-any-protocol (jrec-tag f) "invoke")) - => (lambda (m) (apply jolt-invoke m f args))) - ((and (reified-methods f) (hashtable-ref (reified-methods f) "invoke" #f)) - => (lambda (m) (apply jolt-invoke m f args))) - ;; host types registered as callable (promise delivers, …): consulted only - ;; after every built-in case missed, so the hot dispatch pays nothing. - ((jolt-invoke-arm-for f) => (lambda (h) (h f args))) - ;; calling a non-fn: a ClassCastException naming the operator's CLASS (like - ;; the JVM's "class clojure.lang.LazySeq cannot be cast to ... IFn" — never - ;; the value, whose printed form may be unbounded: ((range)) must throw, not - ;; hang rendering an infinite seq). Thrown via jolt-throw so it is catchable - ;; and carries the throw-site continuation for a stack trace. - (else (jolt-throw (jolt-host-throwable "java.lang.ClassCastException" - (string-append - "class " - (guard (e (#t "value")) - (let ((c (jolt-class-name f))) - (if (string? c) c (jolt-pr-str f)))) - " cannot be cast to class clojure.lang.IFn")))))) - -;; ============================================================================ -;; chunked-seq accessors — the host side of the Clojure IChunkedSeq contract -;; (chunk-first ++ chunk-rest == the seq). Two chunked shapes share the cseq -;; record: a vector-backed seq (cvec = whole pvec, ci = absolute index, crest #f, -;; rest = next 32-block of cvec) and a ChunkedCons (cvec = standalone chunk pvec, -;; crest = the after-chunk seq). natives-array.ss binds these into clojure.core and -;; the chunk-buffer/chunk/chunk-cons builder API on top of them. -;; ============================================================================ -(define seq-chunk-size 32) -;; (chunk-pvec . end-index) for a chunked cell, else #f. A ChunkedCons block is the -;; whole remaining chunk (crest carries what comes after); a vector seq block is the -;; next <=32 elements within cvec. -(define (na-vblock s) - (and (cseq? s) (cseq-cvec s) - (let ((v (cseq-cvec s)) (i (cseq-ci s))) - (cons v (if (cseq-crest s) (pvec-count v) (fxmin (fx+ i seq-chunk-size) (pvec-count v))))))) -(define (na-chunked-seq? x) (and (na-vblock x) #t)) -;; Copy the block [i, end) straight out of the pvec trie's 32-element leaf node -;; (pv-chunk-for is O(log n)). seq-chunk-size == pv-width and vector-seq blocks are -;; 32-aligned, so a block is exactly one leaf; the rare non-aligned window crossing -;; a leaf boundary falls back to per-index reads. Flattening the whole backing -;; vector per block (pvec-v) made chunk-first O(n), so walking chunk-by-chunk was -;; O(n^2). A ChunkedCons chunk is a small tail-only pvec, so the leaf IS the chunk. -(define (na-chunk-first s) - (let ((vb (na-vblock s))) - (if vb - (let* ((pv (car vb)) (i (cseq-ci s)) (end (cdr vb)) (len (fx- end i)) - (node (pv-chunk-for pv i)) (off (fxand i pv-mask))) - (if (fx<=? (fx+ off len) (vector-length node)) - (make-pvec (vec-copy-range node off (fx+ off len))) - (let ((out (make-vector len))) - (let loop ((j 0)) - (if (fx (lambda (vb) - (if (fx>=? (cdr vb) (pvec-count (car vb))) jolt-empty-list (vec->seq (car vb) (cdr vb))))) - (else (jolt-rest s)))) -(define (na-chunk-next s) - (cond - ((and (cseq? s) (cseq-crest s)) (jolt-seq (cseq-crest s))) - ((na-vblock s) => (lambda (vb) - (if (fx>=? (cdr vb) (pvec-count (car vb))) jolt-nil (vec->seq (car vb) (cdr vb))))) - (else (jolt-next s)))) - -;; ============================================================================ -;; map / filter / reduce / into / remove + range / take / concat / apply -;; ============================================================================ -(define (any-nil? seqs) (and (pair? seqs) (or (jolt-nil? (car seqs)) (any-nil? (cdr seqs))))) -;; An EMPTY seq result is () (jolt-empty-list), NOT nil — Clojure's (map f []) is -;; an empty seq, so (= () (map f [])) is true and (nil? (map f [])) is false. -;; jolt-empty-list seqs back to nil, so it stays a valid lazy-tail terminator for -;; the non-empty case (printing / seq= / reduce all walk via jolt-seq). -;; Single-coll map (core.clj's [f coll] arity). Chunk-preserving: when the source -;; seq is chunked, realize the WHOLE first chunk — apply f to every element eagerly -;; into a fresh chunk — and chunk-cons it onto a lazy map of chunk-rest, so the -;; result is itself a chunked-seq. A non-chunked source maps one element at a time. -(define (map-seq f s) - (cond - ((jolt-nil? s) jolt-empty-list) - ((na-chunked-seq? s) - (let* ((c (na-chunk-first s)) (n (pvec-count c)) (out (make-vector n))) - (let loop ((i 0)) - (if (fxvector kept)) 0 - (jolt-make-lazy-seq - (lambda () (jolt-seq (filter-seq pred (jolt-seq (na-chunk-rest s)) keep))))))))))) - (else - (let walk ((s s)) - (cond ((jolt-nil? s) jolt-empty-list) - ((eq? keep (jolt-truthy? (jolt-invoke pred (seq-first s)))) - (cseq-lazy (seq-first s) (lambda () (filter-seq pred (jolt-seq (seq-more s)) keep)))) - (else (walk (jolt-seq (seq-more s))))))))) -;; filter/remove are fully lazy (LazySeq): defer the predicate and the source seq -;; until forced, like Clojure. (lazy-seq* = a 0-arg lazy node coercing to cseq|nil.) -(define (jolt-filter pred coll) - (jolt-make-lazy-seq (lambda () (jolt-seq (filter-seq pred (jolt-seq coll) #t))))) -(define (jolt-remove pred coll) - (jolt-make-lazy-seq (lambda () (jolt-seq (filter-seq pred (jolt-seq coll) #f))))) - -;; honors `reduced`: a reducing fn that returns (reduced x) stops the fold and -;; unwraps to x (so does a reduced INIT). Checked at entry, so the value returned -;; by the last step is unwrapped on the next turn before the seq is consulted. -;; reduce a vector's backing store directly by index from element i — no per- -;; element seq cells. Honors `reduced`. The chunked-seq fast path. -;; Reduce a chunk pvec from index i. Returns the accumulator RAW — a `reduced` box -;; is returned unwrapped-by reduce-seq, not here — so a ChunkedCons continuation can -;; see early termination instead of folding it back into the running value. -(define (vec-reduce f acc v i) - (let ((n (pvec-count v)) (raw (pvec-v v))) - (let loop ((i i) (acc acc)) - (cond ((jolt-reduced? acc) acc) - ((fx>=? i n) acc) - (else (loop (fx+ i 1) (jolt-invoke f acc (vector-ref raw i)))))))) -(define (reduce-seq f acc s) - (cond - ((jolt-reduced? acc) (jolt-reduced-val acc)) - ((jolt-nil? s) acc) - ;; a chunked seq reduces its chunk pvec directly, in a tight loop. A vector seq - ;; (crest #f) reduces the whole backing vector and is then done; a ChunkedCons - ;; reduces this chunk and continues into its after-chunk rest. - ((and (cseq? s) (cseq-cvec s)) - (let ((acc2 (vec-reduce f acc (cseq-cvec s) (cseq-ci s)))) - (cond ((jolt-reduced? acc2) (jolt-reduced-val acc2)) - ((cseq-crest s) (reduce-seq f acc2 (jolt-seq (cseq-crest s)))) - (else acc2)))) - (else (reduce-seq f (jolt-invoke f acc (seq-first s)) (jolt-seq (seq-more s)))))) -(define jolt-reduce - (case-lambda - ((f coll) (let ((s (jolt-seq coll))) - (if (jolt-nil? s) (jolt-invoke f) ; (reduce f []) -> (f) - (reduce-seq f (seq-first s) (jolt-seq (seq-more s)))))) - ((f init coll) - ;; IReduceInit: a deftype/record OR reify with its own `reduce` method drives - ;; the reduction, e.g. (reduce f init (reify clojure.lang.IReduceInit - ;; (reduce [_ f i] ...))) or the same on a deftype. - (cond - ((iface-method coll "reduce" 3) - => (lambda (m) (let ((r (jolt-invoke m coll f init))) - (if (jolt-reduced? r) (jolt-reduced-val r) r)))) - (else (reduce-seq f init (jolt-seq coll))))))) - -;; Fold through a transient so a pvec/pmap/pset target is built in O(n): a -;; persistent pvec-conj copies its whole backing vector each step, making a naive -;; fold O(n^2) (and into/vec/mapv/filterv all route here). jolt-transient-new -;; falls back to a copy-on-write wrapper for other targets (lists, sorted colls, -;; nil), so those keep the old per-step jolt-conj behaviour. -(define (jolt-into to from) - ;; only an editable collection rides the transient path; anything else - ;; (PersistentQueue, sorted colls, seqs) folds through conj, like RT's - ;; instanceof IEditableCollection split. - (if (or (pvec? to) (pmap? to) (pset? to)) - (meta-carry to - (jolt-persistent! (reduce-seq (lambda (t x) (jolt-conj! t x)) (jolt-transient-new to) (jolt-seq from)))) - (meta-carry to - (reduce-seq (lambda (acc x) (jolt-conj1 acc x)) to (jolt-seq from))))) - -(define (range-from n) (cseq-lazy n (lambda () (range-from (+ n 1))))) -;; A bounded range is a real chunked-seq, like clojure.lang.LongRange: eager, with -;; chunk-first handing out a block of up to 32 consecutive values. Each block is -;; materialized into a pvec and chunk-cons'd onto a lazy continuation, so a chunked -;; map/filter over a range batches by 32 (the JVM's observable realization), while a -;; huge range still produces its tail one block at a time. -;; An empty range is () (jolt-empty-list), NOT nil — (range 0) and (range 5 5) are -;; empty seqs in Clojure, so (= () (range 0)) holds, and () seqs back to nil so it -;; also terminates the chunked tail (see jolt-take). -(define (range-chunked n end step) - (if (if (> step 0.0) (< n end) (> n end)) - (let loop ((i 0) (v n) (acc '())) - (if (and (fx step 0.0) (< v end) (> v end))) - (loop (fx+ i 1) (+ v step) (cons v acc)) - (cseq-chunked (make-pvec (list->vector (reverse acc))) 0 - (jolt-make-lazy-seq (lambda () (jolt-seq (range-chunked v end step))))))) - jolt-empty-list)) -;; numeric tower: exact 0/1 defaults so (range 3) yields exact ints -;; (= JVM longs); flonum args still produce flonums (Scheme arithmetic preserves). -;; (range) with no bound is the lazy, NON-chunked (iterate inc' 0) form. -(define jolt-range - (case-lambda - (() (range-from 0)) - ((end) (range-chunked 0 end 1)) - ((start end) (range-chunked start end 1)) - ((start end step) (range-chunked start end step)))) - -;; An empty take result is () (jolt-empty-list), NOT nil — (take 0 coll) and -;; (take n []) are empty seqs in Clojure, so (= () (take 0 [:a])) and printing -;; "()" hold. jolt-empty-list seqs back to nil, so it also terminates the lazy -;; tail when n hits 0 mid-stream (see map-seq). -;; The LAST element (n=1) terminates without touching the rest, so (take n s) -;; realizes exactly n elements of a side-effecting seq — matching Clojure, where -;; (take 0 (rest s)) never seqs coll. Realizing one more, as forcing seq-more at -;; the boundary would, over-runs the source by one (medley's sequence-padded). -(define (jolt-take n coll) - ;; lazy (LazySeq): realize exactly n elements, none at construction. (take - ;; Double/POSITIVE_INFINITY coll) takes the whole coll on the JVM (the count - ;; never reaches 0); test.check's rose-tree unchunk relies on it. Coercing +inf.0 - ;; to a fixnum index would throw, so take all up front in that case. - (jolt-make-lazy-seq - (lambda () - (jolt-seq - (if (and (flonum? n) (infinite? n)) - (if (> n 0.0) (jolt-seq coll) jolt-empty-list) - (let ((n (->idx n))) - (let loop ((n n) (s (jolt-seq coll))) - (cond - ((or (fx<=? n 0) (jolt-nil? s)) jolt-empty-list) - ((fx=? n 1) (cseq-lazy (seq-first s) (lambda () jolt-empty-list))) - (else (cseq-lazy (seq-first s) (lambda () (loop (fx- n 1) (jolt-seq (seq-more s)))))))))))))) -(define (jolt-drop n coll) - (jolt-make-lazy-seq - (lambda () - (jolt-seq - (let loop ((n (->idx n)) (s (jolt-seq coll))) - (if (or (fx<=? n 0) (jolt-nil? s)) (if (jolt-nil? s) jolt-empty-list s) - (loop (fx- n 1) (jolt-seq (seq-more s))))))))) - -;; lazily append seq a then the seqable produced by the thunk `brest` — the rest -;; is NOT forced until a is exhausted, so concat is fully lazy (Clojure semantics). -;; This matters for a self-referential lazy-cat (fib = (lazy-cat [0 1] (map + (rest -;; fib) fib))): forcing the rest eagerly at construction would read fib before its -;; def binds, memoizing the tail as empty. -(define (concat2 a brest) - (if (jolt-nil? a) (jolt-seq (brest)) - (cseq-lazy (seq-first a) (lambda () (concat2 (jolt-seq (seq-more a)) brest))))) -(define (jolt-concat . colls) - (jolt-make-lazy-seq - (lambda () - (jolt-seq - (cond ((null? colls) jolt-empty-list) - ((null? (cdr colls)) (jolt-seq (car colls))) - (else (concat2 (jolt-seq (car colls)) (lambda () (apply jolt-concat (cdr colls)))))))))) - -;; Lazily concatenate a (possibly infinite) SEQ of colls — what (apply concat ss) -;; means, but without realizing ss. Pulls one coll at a time, concatenating it with -;; a lazy tail, so mapcat / (apply concat …) over an infinite source stays lazy. -(define (lazy-concat-seq ss) - (let ((s (jolt-seq ss))) - (if (jolt-nil? s) - jolt-empty-list - (jolt-concat (seq-first s) - (jolt-make-lazy-seq (lambda () (lazy-concat-seq (seq-more s)))))))) - -;; (apply f a b ... coll): spread the trailing seqable into the call. concat is -;; special-cased: it produces a LAZY result, so spreading an infinite tail through -;; a Scheme variadic (which must realize it) would hang — route to lazy-concat-seq, -;; prepending any fixed leading colls. -(define (jolt-apply f . args) - (let* ((r (reverse args)) (tail (car r)) (fixed (reverse (cdr r)))) - (if (eq? f jolt-concat) - (lazy-concat-seq (fold-right jolt-cons (jolt-seq tail) fixed)) - (apply jolt-invoke f (append fixed (seq->list (jolt-seq tail))))))) - -;; ============================================================================ -;; numeric predicates / identity — usable in fn AND value position (map/filter). -;; Return Scheme #t/#f (= jolt true/false). All-flonum model: coerce to an exact -;; integer for the parity tests. -;; ============================================================================ -;; Parity over the full integer range (JVM even?/odd? accept any integer, -;; bignums included); a fixnum-only fxand crashes on a large value (e.g. a hash). -(define (parity-int n) (if (flonum? n) (exact (floor n)) n)) -(define (jolt-parity-check n) - (unless (and (number? n) (exact? n) (integer? n)) - (jolt-throw (jolt-host-throwable - "java.lang.IllegalArgumentException" - (string-append "Argument must be an integer: " - (guard (e (#t "?")) (jolt-str n))))))) -(define (jolt-even? n) (jolt-parity-check n) (even? (parity-int n))) -(define (jolt-odd? n) (jolt-parity-check n) (odd? (parity-int n))) -(define (jolt-pos? n) (> n 0)) -(define (jolt-neg? n) (< n 0)) -(define (jolt-zero? n) (= n 0)) -(define (jolt-identity x) x) - -;; ============================================================================ -;; keys / vals — return seqs (nil on the empty map), HAMT-iteration order -;; ============================================================================ -;; keys/vals of anything empty is nil (RT.keys over a nil seq); a non-empty -;; non-map still fails (its elements are not MapEntries). -(define (jolt-keys m) - (cond ((jolt-nil? m) jolt-nil) - ((pmap? m) (list->cseq (pmap-fold m (lambda (k v a) (cons k a)) '()))) - ((jolt-nil? (jolt-seq m)) jolt-nil) - (else (list->cseq (pmap-fold m (lambda (k v a) (cons k a)) '()))))) -(define (jolt-vals m) - (cond ((jolt-nil? m) jolt-nil) - ((pmap? m) (list->cseq (pmap-fold m (lambda (k v a) (cons v a)) '()))) - ((jolt-nil? (jolt-seq m)) jolt-nil) - (else (list->cseq (pmap-fold m (lambda (k v a) (cons v a)) '()))))) - -;; ============================================================================ -;; sequential equality + hash (hooks called from values.ss / collections.ss); -;; consistent with the persistent vector's element-wise =/hash so a vector and a -;; list of the same elements are jolt= and hash alike. -;; ============================================================================ -(define (seq=? a b) - (let loop ((sa (jolt-seq a)) (sb (jolt-seq b))) - (cond ((and (jolt-nil? sa) (jolt-nil? sb)) #t) - ((or (jolt-nil? sa) (jolt-nil? sb)) #f) - ((jolt= (seq-first sa) (seq-first sb)) (loop (jolt-seq (seq-more sa)) (jolt-seq (seq-more sb)))) - (else #f)))) -(define (seq-hash x) - (let loop ((s (jolt-seq x)) (h 1)) - (if (jolt-nil? s) (bitwise-and h hmask) - (loop (jolt-seq (seq-more s)) (bitwise-and (+ (* 31 h) (key-hash (seq-first s))) hmask))))) diff --git a/host/chez/smoke.sh b/host/chez/smoke.sh deleted file mode 100755 index 8ed4506..0000000 --- a/host/chez/smoke.sh +++ /dev/null @@ -1,263 +0,0 @@ -#!/bin/sh -# CLI smoke: exercise the real bin/joltc process end to end — core eval, runtime -# eval/load-string, runtime defmacro, futures, and the numeric tower. The in-process -# corpus/unit gates cover semantics in depth; this confirms the CLI entry itself. -root="$(CDPATH= cd -- "$(dirname -- "$0")/../.." && pwd)" -cd "$root" - -fails=0 -check() { - got="$(bin/joltc -e "$1" 2>/dev/null | tail -1)" - if [ "$got" = "$2" ]; then - pass=$((pass + 1)) - else - echo " FAIL: $1" - echo " want \`$2\` got \`$got\`" - fails=$((fails + 1)) - fi -} -pass=0 - -# An uncaught error reports the source location of the top-level form (stderr). -check_loc() { - err="$(bin/joltc -e "$1" 2>&1 >/dev/null)" - if printf '%s' "$err" | grep -q "$2"; then - pass=$((pass + 1)) - else - echo " FAIL (loc): $1" - echo " want stderr to contain \`$2\`, got \`$err\`" - fails=$((fails + 1)) - fi -} - -# An uncaught error's stack trace must name the runtime-eval'd fn frames that -# survive TCO (the non-tail spine), even though the eval path registers no source -# map — "print what is available". Asserts a substring appears under " trace:". -check_trace() { - err="$(bin/joltc -e "$1" 2>&1 >/dev/null)" - if printf '%s' "$err" | grep -q ' trace:' && printf '%s' "$err" | grep -q "$2"; then - pass=$((pass + 1)) - else - echo " FAIL (trace): $1" - echo " want stderr trace to contain \`$2\`, got \`$err\`" - fails=$((fails + 1)) - fi -} - -# JOLT_TRACE opts into the tail-frame history (the ring of rings): every $2 (an -# ERE) must match the " trace:" block. Used to assert TCO-elided frames are -# recovered and non-tail caller context survives a tail loop. -check_trace_on() { - err="$(JOLT_TRACE=1 bin/joltc -e "$1" 2>&1 >/dev/null)" - ok=1 - printf '%s' "$err" | grep -q ' trace:' || ok=0 - shift - for want in "$@"; do - printf '%s' "$err" | grep -Eq "$want" || ok=0 - done - if [ "$ok" = 1 ]; then - pass=$((pass + 1)) - else - echo " FAIL (trace-on): want [$*] in trace, got \`$err\`" - fails=$((fails + 1)) - fi -} - -check '(+ 1 2)' '3' -check '(defn fib [n] (if (< n 2) n (+ (fib (- n 1)) (fib (- n 2))))) (fib 15)' '610' -check '(->> (range 10) (filter even?) (map (fn [x] (* x x))) (reduce +))' '120' -check '(let [{:keys [a b] :or {b 99}} {:a 1}] [a b])' '[1 99]' -check '(map inc [1 2 3])' '(2 3 4)' -check '(require [clojure.string :as s]) (s/upper-case "hello")' 'HELLO' -check '(eval (quote (+ 1 2)))' '3' -check '(load-string "(def y 5) (* y y)")' '25' -check '(defmacro add1 [x] (list (quote +) x 1)) (add1 10)' '11' -check '(deref (future (+ 1 2)))' '3' -check '(/ 1 2)' '1/2' -check '(= 3 3.0)' 'false' -check '(== 3 3.0)' 'true' -# a deftype whose simple name collides with a built-in host class must not shadow -# the java class: (java.io.PushbackReader. …) still builds the java reader (has -# .read), while the bare name in the deftype's own ns is the deftype. (Fresh -e -# process per check, so the deftype doesn't leak.) -check '(do (deftype PushbackReader [x]) (.read (java.io.PushbackReader. (java.io.StringReader. "A") 1)))' '65' -check '(do (deftype PushbackReader [x]) (.-x (PushbackReader. 42)))' '42' -check_loc '(throw (ex-info "boom" {}))' ' at 1:' - -# A throw that crosses the eval boundary (eval / load-string) must surface its -# ex-info :message, not Chez's "attempt to apply non-procedure" noise from -# re-wrapping a raw value raised through `eval`. -check '(try (eval (read-string "(throw (ex-info \"boom\" {}))")) (catch :default e (ex-message e)))' 'boom' -check '(try (load-string "(+") (catch :default e (ex-message e)))' 'EOF while reading' -# An uncaught throw prints the ex-info message alongside its source location. -check_loc '(throw (ex-info "boom" {}))' 'boom' -check_loc '(do (+ 1 1) (/ 1 0))' ' at 1:' - -# Runtime-eval'd fns aren't source-mapped, but their native frame names survive on -# the non-tail spine; the trace must show them. deepest/+ are tail calls (erased); -# middle and outer wait on a non-tail (inc …) so their frames are live at the throw. -trace_prog='(defn deepest [x] (+ x 1)) (defn middle [x] (inc (deepest x))) (defn outer [x] (inc (middle x))) (outer :nan)' -check_trace "$trace_prog" 'middle' -check_trace "$trace_prog" 'outer' - -# JOLT_TRACE (tail-frame history / ring of rings). An all-tail chain is entirely -# TCO-erased from the continuation, but the history recovers every frame — incl. -# `deepest`, the actual error site. -check_trace_on '(defn deepest [x] (+ x 1)) (defn middle [x] (deepest x)) (defn outer [x] (middle x)) (outer :nan)' \ - 'deepest' 'middle' 'outer' -# A tail loop (a<->b) under a NON-tail caller: the loop is confined to one rib's -# bounded inner ring, so the caller context (`driver`, `top`) is NOT flushed out — -# the point of the ring of rings. -check_trace_on '(declare b) (defn a [n] (if (zero? n) (+ :x 1) (b (dec n)))) (defn b [n] (a n)) (defn driver [] (inc (a 6))) (defn top [] (inc (driver))) (top)' \ - 'driver' 'top' -# A ^long/^double return hint wraps the body in a coercion, so the hinted fn's call -# is NOT a tail call — its own frame is still live and must appear (not be elided). -check_trace_on '(defn g [n] (+ :x n)) (defn ^long f [n] (g n)) (f 3)' 'f' 'g' -# History is per top-level form: a later form's error trace shows its own frames -# (h2/u2), not frames from an earlier, already-returned form (h1/u1). -check_trace_on '(defn h1 [x] (inc x)) (defn u1 [] (inc (h1 5))) (u1) (defn h2 [x] (+ :x x)) (defn u2 [] (inc (h2 5))) (u2)' \ - 'h2' 'u2' -err_stale="$(JOLT_TRACE=1 bin/joltc -e '(defn h1 [x] (inc x)) (defn u1 [] (inc (h1 5))) (u1) (defn h2 [x] (+ :x x)) (defn u2 [] (inc (h2 5))) (u2)' 2>&1 >/dev/null)" -if printf '%s' "$err_stale" | grep -q 'h1'; then - echo " FAIL (trace-on): stale frame h1 from an earlier form leaked into the trace" - fails=$((fails + 1)) -else - pass=$((pass + 1)) -fi -# A file-backed project run maps each runtime-compiled frame to ns/name (file:line) -# — the eval path registers source in trace mode, so the trace isn't bare names. -tr_proj="$(mktemp -d)" -mkdir -p "$tr_proj/src/tp" -printf '{:paths ["src"] :aliases {:run {:main-opts ["-m" "tp.core"]}}}\n' > "$tr_proj/deps.edn" -printf '(ns tp.core)\n(defn deep [x] (+ x 1))\n(defn mid [x] (inc (deep x)))\n(defn -main [& _] (mid :nan))\n' > "$tr_proj/src/tp/core.clj" -tr_out="$(JOLT_TRACE=1 JOLT_PWD="$tr_proj" bin/joltc -M:run 2>&1)" -if printf '%s' "$tr_out" | grep -Eq 'tp\.core/deep \(.*/tp/core\.clj:2\)'; then - pass=$((pass + 1)) -else - echo " FAIL: JOLT_TRACE trace should map a frame to ns/name (file:line)" - printf '%s\n' "$tr_out" | sed 's/^/ | /' - fails=$((fails + 1)) -fi -rm -rf "$tr_proj" - -# --help prints usage, and lists the nREPL server under its real flag name. -help_out="$(bin/joltc --help 2>/dev/null)" -if printf '%s' "$help_out" | grep -q -- '--nrepl-server'; then - pass=$((pass + 1)) -else - echo " FAIL: --help should list --nrepl-server" - fails=$((fails + 1)) -fi - -# clojure.test extension points (assert-expr / do-report / report) need separate -# top-level forms — assert-expr must register before `is` expands — so this is a -# multi-form `joltc run`, not an -e one-liner. The file self-checks its tallies. -ct_out="$(bin/joltc run test/chez/clojure-test.clj 2>/dev/null)" -if printf '%s' "$ct_out" | grep -q 'CLOJURE-TEST OK'; then - pass=$((pass + 1)) -else - echo " FAIL: clojure.test extension points" - echo " $(printf '%s' "$ct_out" | grep CLOJURE-TEST | tail -1)" - fails=$((fails + 1)) -fi - -# A data reader that returns a CODE form (deps.edn data_readers.clj -> reader fn) -# must have its result spliced in and COMPILED, like Clojure — #code [:x] becomes -# (+ 40 2) and evaluates to 42, not the literal list. A project run so the source -# root's data_readers.clj is picked up. -dr_out="$(JOLT_PWD="$root/test/chez/datareader-app" bin/joltc run -m drtest.main 2>/dev/null | tail -1)" -if [ "$dr_out" = "42" ]; then - pass=$((pass + 1)) -else - echo " FAIL: code-returning data reader (#code) not compiled — got \`$dr_out\`, want 42" - fails=$((fails + 1)) -fi - -# A required namespace's own :as aliases must not leak into the requirer: fix.main -# aliases clojure.string as ss and requires fix.lib (which aliases clojure.set as -# ss); (ss/upper-case "hi") in main must stay clojure.string -> "HI #{1 2}". -al_out="$(JOLT_PWD="$root/test/chez/alias-leak-app" bin/joltc run -m fix.main 2>/dev/null | tail -1)" -if [ "$al_out" = "HI #{1 2}" ]; then - pass=$((pass + 1)) -else - echo " FAIL: a loaded ns's alias leaked into its requirer — got \`$al_out\`, want \`HI #{1 2}\`" - fails=$((fails + 1)) -fi - -# Unit-checks the REPL read-until-complete predicate over balanced/unbalanced, -# string, comment and regex-literal inputs. A multi-form `joltc run` so jolt.main -# is loaded and its private var resolves; the file self-checks and prints a sentinel. -rr_out="$(bin/joltc run test/chez/repl-reader-test.clj 2>/dev/null)" -if printf '%s' "$rr_out" | grep -q 'REPL-READER OK'; then - pass=$((pass + 1)) -else - echo " FAIL: repl-form-complete? predicate" - echo " $(printf '%s' "$rr_out" | grep REPL-READER | tail -1)" - fails=$((fails + 1)) -fi - -# REPL must exit on :repl/quit / :exit — a reliable exit that works in any -# terminal, unlike ^D (which some terminals/editors don't deliver as EOF). -# Pipe: an evaluable form, the quit keyword, then a sentinel that must NOT run. -repl_out="$(printf '(+ 1000 23)\n:repl/quit\n(* 999 9)\n' | bin/joltc repl 2>/dev/null)" -if printf '%s' "$repl_out" | grep -q '1023' && ! printf '%s' "$repl_out" | grep -q '8991'; then - pass=$((pass + 1)) -else - echo " FAIL: repl should exit on :repl/quit before later forms" - printf '%s\n' "$repl_out" | sed 's/^/ | /' - fails=$((fails + 1)) -fi - -repl_out="$(printf '(- 2024 1)\n:exit\n(* 999 9)\n' | bin/joltc repl 2>/dev/null)" -if printf '%s' "$repl_out" | grep -q '2023' && ! printf '%s' "$repl_out" | grep -q '8991'; then - pass=$((pass + 1)) -else - echo " FAIL: repl should exit on :exit before later forms" - printf '%s\n' "$repl_out" | sed 's/^/ | /' - fails=$((fails + 1)) -fi - -# A form split across lines is accumulated and evaluated once complete, with a -# secondary continuation prompt before each continued line. -repl_out="$(printf '(+ 1\n2)\n:exit\n' | bin/joltc repl 2>/dev/null)" -if printf '%s' "$repl_out" | grep -q '3' && ! printf '%s' "$repl_out" | grep -q 'error'; then - pass=$((pass + 1)) -else - echo " FAIL: repl should accumulate multi-line forms to 3" - printf '%s\n' "$repl_out" | sed 's/^/ | /' - fails=$((fails + 1)) -fi - -# A single-line regex literal is complete on its own — the #" opens a regex whose -# body (delimiters, quotes and all) must not be miscounted as unbalanced parens. -repl_out="$(printf '(re-find #"(a)(b)" "ab")\n:exit\n' | bin/joltc repl 2>/dev/null)" -if printf '%s' "$repl_out" | grep -q 'ab' && ! printf '%s' "$repl_out" | grep -q 'error'; then - pass=$((pass + 1)) -else - echo " FAIL: repl should evaluate a one-line regex literal, not wait for more input" - printf '%s\n' "$repl_out" | sed 's/^/ | /' - fails=$((fails + 1)) -fi - -# REPL-driven development traces by default: an error in an evaluated form shows a -# tail-frame backtrace with no JOLT_TRACE set. rb tail-calls ra tail-calls +, all -# TCO-elided from the continuation — only the history recovers them. -repl_err="$(printf '(defn ra [x] (+ x 1))\n(defn rb [x] (ra x))\n(rb :nan)\n:exit\n' | bin/joltc repl 2>&1)" -if printf '%s' "$repl_err" | grep -q ' trace:' && printf '%s' "$repl_err" | grep -q 'rb'; then - pass=$((pass + 1)) -else - echo " FAIL: a REPL error should show a tail-frame trace by default" - printf '%s\n' "$repl_err" | sed 's/^/ | /' - fails=$((fails + 1)) -fi -# JOLT_TRACE=0 opts out — no trace in the REPL. -repl_off="$(printf '(defn ra [x] (+ x 1))\n(defn rb [x] (ra x))\n(rb :nan)\n:exit\n' | JOLT_TRACE=0 bin/joltc repl 2>&1)" -if printf '%s' "$repl_off" | grep -q ' trace:'; then - echo " FAIL: JOLT_TRACE=0 should suppress the REPL trace" - fails=$((fails + 1)) -else - pass=$((pass + 1)) -fi - -echo "cli smoke: $pass passed, $fails failed" -[ "$fails" -eq 0 ] diff --git a/host/chez/source-registry.ss b/host/chez/source-registry.ss deleted file mode 100644 index f88ce2a..0000000 --- a/host/chez/source-registry.ss +++ /dev/null @@ -1,206 +0,0 @@ -;; source-registry.ss — map emitted procedures back to Clojure source for native -;; stack traces, and render an uncaught throwable. -;; -;; A direct-linked def compiles to (define jv$ns$name ); the back end also -;; emits (jolt-register-source! "jv$ns$name" ns name file line) once per such def -;; — at definition time, so there is zero per-call cost. On an uncaught error we -;; walk Chez's native continuation frames, read each frame's procedure name, and -;; look it up here to print a Clojure backtrace. -;; -;; CAVEATS. Names map only for stable Chez procedure names — direct-link / AOT -;; closed-world builds. The open-world -e/repl/run path stores fns in var cells -;; as anonymous lambdas, so its frames don't map (the trace falls back to the -;; top-level location compile-eval.ss tracks). Pervasive tail-call optimization -;; also erases tail-called frames, so even a mapped trace shows only the non-tail -;; spine — the immediate error site is often a tail call and won't appear. - -;; Keyed by the procedure name Chez actually reports for a frame — the SHORT -;; munged fn name (the letrec self-binding emit-fn uses), e.g. "deepest", not the -;; jv$ns$name global. Two vars in different namespaces can share a short name; an -;; 'ambiguous marker then keeps the frame name in the trace but drops the -;; (now-uncertain) ns/file:line, so a trace is never misattributed. -(define source-registry (make-hashtable string-hash string=?)) - -(define (jolt-register-source! procname ns nm file line) - (let ((existing (hashtable-ref source-registry procname #f))) - (cond - ((not existing) (hashtable-set! source-registry procname (vector ns nm file line))) - ((and (vector? existing) - (or (not (equal? (vector-ref existing 0) ns)) - (not (equal? (vector-ref existing 1) nm)))) - (hashtable-set! source-registry procname 'ambiguous)))) - jolt-nil) -(def-var! "jolt.host" "register-source!" jolt-register-source!) - -;; The continuation to walk for an uncaught value: the one jolt-throw captured for -;; THIS value (identity-tagged via jolt-throw-cont, so a stale entry from an -;; earlier caught throw is never reused), else a host condition's own -;; &continuation, else #f. raw may arrive as the &jolt-throw condition wrapping -;; the value (the built-binary launcher hands jolt-report-throwable the guard's -;; raw value) or already unwrapped (the cli unwraps first); unwrap here so the -;; identity match holds either way. -(define (jolt-error-continuation raw) - (let* ((v (jolt-unwrap-throw raw)) - (tc (jolt-throw-cont))) - (cond - ((and (pair? tc) (eq? (car tc) v)) (cdr tc)) - ((and (condition? v) (continuation-condition? v)) (condition-continuation v)) - (else #f)))) - -;; A frame inspector's procedure name as a string, or #f for a non-frame / unnamed. -(define (srcreg-frame-name io) - (and (guard (e (#t #f)) (eq? (io 'type) 'continuation)) - (let ((code (guard (e (#t #f)) (io 'code)))) - (and code - (let ((nm (guard (e (#t #f)) (code 'name)))) - (cond ((string? nm) nm) - ((symbol? nm) (symbol->string nm)) - (else #f))))))) - -;; Frame names that are pure Chez / jolt-runtime plumbing — the eval boundary, -;; the var-cell trampoline, continuation/winder internals. They carry no Clojure -;; meaning, so an unmapped frame with one of these names is dropped from the trace -;; (a MAPPED frame is always kept — a jolt fn that happens to share the name still -;; resolves to its source). Any name Chez prefixes with `$` (system) or that jolt -;; prefixes with `jolt-` (host runtime) is plumbing too. -(define srcreg-plumbing-names - (let ((h (make-hashtable string-hash string=?))) - (for-each (lambda (s) (hashtable-set! h s #t)) - '("dynamic-wind" "winder-dummy" "ksrc" "invoke" "apply" - "call-with-values" "call/cc" "call-with-current-continuation" - "raise" "raise-continuable" "with-exception-handler" "guard" - "eval" "compile" "interpret" "expand" "read" "load" - ;; host dispatch/coercion helpers (not `jolt-` prefixed) that carry - ;; no Clojure meaning in a trace - "record-method-dispatch" "protocol-resolve" "devirt-resolve" - "list->cseq" "host-static-call" "host-call")) - h)) -(define (srcreg-plumbing-name? nm) - (or (hashtable-ref srcreg-plumbing-names nm #f) - (and (fx>? (string-length nm) 0) (char=? (string-ref nm 0) #\$)) - (and (fx>=? (string-length nm) 5) (string=? (substring nm 0 5) "jolt-")))) - -;; Walk a continuation, returning its frames (innermost first) as (frame-name . -;; record) pairs. record is a source vector #(ns name file line) for a frame that -;; maps to registered Clojure source, the symbol 'ambiguous for a short name shared -;; across namespaces, or #f for an unmapped-but-named frame (the common case on the -;; open-world eval path, where nothing is registered — the bare frame name is still -;; a useful trace line). Plumbing frames (host spine, eval boundary) and unnamed -;; frames are skipped; raw depth is capped. -(define (jolt-frame-records k) - ;; read the env at call time, not load time: a built binary runs top-level forms - ;; at heap-build time, where this would always be unset. - (let ((debug? (getenv "JOLT_DEBUG_FRAMES"))) - (guard (e (#t '())) - (let loop ((io (inspect/object k)) (n 0) (acc '())) - (if (or (not io) (fx>=? n 400)) - (reverse acc) - (let* ((nm (srcreg-frame-name io)) - (src (and nm (hashtable-ref source-registry nm #f))) - ;; keep a frame that maps, or any named frame that isn't plumbing - (keep? (and nm (or src (not (srcreg-plumbing-name? nm)))))) - (when (and debug? nm) - (display (string-append " [frame] " nm (if src " *MAPPED*" - (if keep? "" " (skipped)")) "\n") - (current-error-port))) - (loop (guard (e (#t #f)) (io 'link)) (fx+ n 1) - (if keep? (cons (cons nm src) acc) acc)))))))) - -;; Render a list of (frame-name . record) pairs (innermost/deepest first) to a -;; backtrace string. record is a source vector #(ns name file line) -> "ns/name -;; (file:line)", or 'ambiguous / #f -> the bare frame name. A run of the same -;; frame-name collapses to one "name (xN)" line (deep recursion, or a hot fn a -;; loop re-enters), and the number of distinct lines is capped. -(define (jolt-render-recs recs) - (let ((port (open-output-string))) - (let loop ((rs recs) (shown 0)) - (if (or (null? rs) (fx>=? shown 30)) - (get-output-string port) - (let* ((p (car rs)) (frame-name (car p)) (r (cdr p))) - ;; count a maximal run of the same frame-name - (let run ((tail (cdr rs)) (cnt 1)) - (if (and (pair? tail) (string=? (car (car tail)) frame-name)) - (run (cdr tail) (fx+ cnt 1)) - (begin - (put-string port " ") - (if (vector? r) - (let ((ns (vector-ref r 0)) (nm (vector-ref r 1)) - (file (vector-ref r 2)) (line (vector-ref r 3))) - (put-string port ns) (put-string port "/") (put-string port nm) - (when (string? file) - (put-string port " (") (put-string port file) - (put-string port ":") (put-string port (number->string line)) - (put-string port ")"))) - (put-string port frame-name)) ; 'ambiguous / unmapped: bare name - (when (fx>? cnt 1) - (put-string port " (x") (put-string port (number->string cnt)) (put-string port ")")) - (put-char port #\newline) - (loop tail (fx+ shown 1)))))))))) - -;; Multi-line backtrace for an uncaught value. Two sources, in preference order: -;; 1. The tail-frame history ring (rt.ss), when JOLT_TRACE enabled it — an -;; execution history of the runtime-compiled fns entered before the throw, -;; INCLUDING ones TCO erased from the live continuation. Most-recent first. -;; 2. Otherwise the live continuation (jolt-frame-records) — the accurate but -;; TCO-truncated non-tail spine. -;; Each frame maps to "ns/name (file:line)" when registered, else its bare name. -;; #f when neither source yields a frame (the caller then prints just the location). -;; The tail-frame history ring rendered as a backtrace, or #f when tracing is off / -;; empty. A mapped frame is kept; else drop plumbing (same rule as the continuation -;; path) so the two sources read consistently. -(define (jolt-history-backtrace) - (let* ((hist (jolt-trace-snapshot)) - (recs (let loop ((ns hist) (acc '())) - (if (null? ns) - (reverse acc) - (let* ((nm (car ns)) (src (hashtable-ref source-registry nm #f))) - (loop (cdr ns) - (if (or src (not (srcreg-plumbing-name? nm))) - (cons (cons nm src) acc) acc))))))) - (and (pair? recs) (jolt-render-recs recs)))) - -(define (jolt-backtrace-string v) - (or (jolt-history-backtrace) - (let ((k (jolt-error-continuation v))) - (and k - (let ((recs (jolt-frame-records k))) - (and (pair? recs) (jolt-render-recs recs))))))) - -;; Exposed for the REPL / nREPL error paths, which catch errors themselves instead -;; of going through the uncaught reporter. Returns the " trace:\n" block -;; from the tail-frame HISTORY only — the live continuation in a REPL is just the -;; REPL's own machinery — or nil when tracing is off (so a caller can when-let). -(def-var! "jolt.host" "backtrace-string" - (lambda () - (let ((bt (jolt-history-backtrace))) - (if bt (string-append " trace:\n" bt) jolt-nil)))) - -;; Render an uncaught jolt throw (any value, not just a Chez condition) to a port: -;; an ex-info shows its message + ex-data (+ a host cause); anything else is -;; pr-str'd. Shared by the cli (cli.ss) and a built binary's launcher (build.ss). -(define (jolt-render-throwable raw port) - (let ((v (jolt-unwrap-throw raw))) - (if (jolt=2 (jolt-get v jolt-kw-ex-type jolt-nil) jolt-kw-ex-info) - (begin - (display "Unhandled exception: " port) - (display (jolt-str-render-one (jolt-get v jolt-kw-message jolt-nil)) port) - (newline port) - (let ((data (jolt-get v jolt-kw-data jolt-nil))) - (unless (jolt-nil? data) - (display " ex-data: " port) (display (jolt-pr-str data) port) (newline port))) - (let ((cause (jolt-get v jolt-kw-cause jolt-nil))) - (when (condition? cause) - (display " cause: " port) - (display (with-output-to-string (lambda () (display-condition cause))) port) - (newline port)))) - (begin - (display "Unhandled exception: " port) - (display (if (condition? v) (with-output-to-string (lambda () (display-condition v))) (jolt-pr-str v)) port) - (newline port))))) - -;; Render the throwable, then its Clojure backtrace when one maps. The caller adds -;; any top-level source location (the runtime cli does; a built binary has none). -(define (jolt-report-throwable v port) - (jolt-render-throwable v port) - (let ((bt (jolt-backtrace-string v))) - (when bt (display " trace:\n" port) (display bt port)))) diff --git a/host/chez/static-native-smoke.sh b/host/chez/static-native-smoke.sh deleted file mode 100644 index c8aa019..0000000 --- a/host/chez/static-native-smoke.sh +++ /dev/null @@ -1,115 +0,0 @@ -#!/bin/sh -# static-native smoke: a project's :jolt/native lib with a :static archive is -# LINKED INTO the built binary (the default), so the binary calls the C function -# with no shared object on disk at runtime. --dynamic keeps the old behavior — -# load a shared object at runtime. -root="$(CDPATH= cd -- "$(dirname -- "$0")/../.." && pwd)" -cd "$root" - -# Preflight: needs cc (to build the test libs AND to cc-link the app) + Chez's -# kernel dev files, same as build-smoke. Skip otherwise (CI on a distro package). -csv="$JOLT_CHEZ_CSV" -if [ -z "$csv" ]; then - chez_bin="$(command -v chez || command -v scheme || command -v petite || true)" - if [ -n "$chez_bin" ]; then - base="$(cd "$(dirname "$chez_bin")/.." 2>/dev/null && pwd)" - for d in "$base"/lib/csv*/*/; do - [ -f "${d}libkernel.a" ] && csv="${d%/}" && break - done - fi -fi -if ! command -v cc >/dev/null 2>&1 || [ -z "$csv" ] || [ ! -f "$csv/scheme.h" ] || [ ! -f "$csv/libkernel.a" ]; then - echo "static-native smoke: skipped (Chez kernel dev files or C compiler not available)" - exit 0 -fi -export JOLT_CHEZ_CSV="$csv" - -case "$(uname -s)" in - Darwin) plat=":darwin"; soext="dylib"; shared="-dynamiclib" ;; - *) plat=":linux"; soext="so"; shared="-shared" ;; -esac - -work="$(mktemp -d)" -trap 'rm -rf "$work"' EXIT -app="$work/app" -mkdir -p "$app/src/app" - -# 1. a trivial C library, built BOTH as a static archive and a shared object. -cat > "$work/greet.c" <<'EOF' -int jolt_static_answer(void) { return 42; } -EOF -cc -c "$work/greet.c" -o "$work/greet.o" -ar rcs "$work/libgreet.a" "$work/greet.o" -cc $shared "$work/greet.c" -o "$work/libgreet.$soext" - -# 2. an app that binds that symbol via FFI. -cat > "$app/src/app/core.clj" <<'EOF' -(ns app.core - (:require [jolt.ffi :as ffi])) -(ffi/defcfn answer "jolt_static_answer" [] :int) -(defn -main [& _] - (println "answer:" (answer))) -EOF - -out="$work/app-bin" - -# --- default: static link --------------------------------------------------- -# A static-only spec (no runtime candidate): the build resolves the symbol by -# preloading the archive, and the binary links it in — nothing to load at runtime. -cat > "$app/deps.edn" <"$work/build.log" 2>&1; then - echo " FAIL: jolt build (static) exited non-zero"; cat "$work/build.log"; exit 1 -fi -[ -x "$out" ] || { echo " FAIL: no executable produced"; exit 1; } -# A static lib emits a process-symbol load (its archive is in-process), not a -# dlopen of the shared object. -if ! grep -q "jolt-build-load-native '() #f #t" "$out.build/flat.ss"; then - echo " FAIL: static native did not emit a process-symbol load"; exit 1 -fi -if grep -q "libgreet.$soext" "$out.build/flat.ss"; then - echo " FAIL: static native baked a runtime shared-object load"; exit 1 -fi -# Remove BOTH libs: a static-linked symbol lives in the binary, nothing to load. -rm -f "$work/libgreet.a" "$work/libgreet.$soext" "$work/greet.o" -got="$(cd / && "$out" 2>&1)" -if [ "$got" != "answer: 42" ]; then - echo " FAIL: static-linked binary output mismatch" - echo "--- want ---"; echo "answer: 42"; echo "--- got ----"; echo "$got"; exit 1 -fi - -# --- --dynamic: runtime load ------------------------------------------------ -# Rebuild the shared object (static phase deleted it) and give the spec a runtime -# candidate; --dynamic loads it at startup instead of linking the archive. -cc $shared "$work/greet.c" -o "$work/libgreet.$soext" -cat > "$app/deps.edn" <"$work/build.log" 2>&1; then - echo " FAIL: jolt build --dynamic exited non-zero"; cat "$work/build.log"; exit 1 -fi -# --dynamic loads the shared object at runtime. -if ! grep -q "libgreet.$soext" "$out.build/flat.ss"; then - echo " FAIL: --dynamic did not emit a runtime shared-object load"; exit 1 -fi -got="$(cd / && "$out" 2>&1)" -if [ "$got" != "answer: 42" ]; then - echo " FAIL: --dynamic binary output mismatch (shared object present)" - echo "--- got ----"; echo "$got"; exit 1 -fi -# With the shared object gone, a --dynamic binary must FAIL — proving the symbol -# was loaded at runtime, not baked in. -rm -f "$work/libgreet.$soext" -rc=0; { (cd / && exec "$out"); } >/dev/null 2>&1 || rc=$? -if [ "$rc" -eq 0 ]; then - echo " FAIL: --dynamic binary still ran with its shared object removed"; exit 1 -fi - -echo "static-native smoke: passed (static default + --dynamic runtime load)" diff --git a/host/chez/stub/launcher.c b/host/chez/stub/launcher.c deleted file mode 100644 index 29a270e..0000000 --- a/host/chez/stub/launcher.c +++ /dev/null @@ -1,109 +0,0 @@ -/* launcher.c — the native stub for self-contained jolt binaries (jolt-eaj). - * - * A toolchain-free `jolt build` (and joltc itself) produces an executable by - * appending a Chez boot image to a copy of this prebuilt stub, framed as: - * - * [stub bytes][boot bytes][boot-length : little-endian u64]["JOLTBOOT"] - * - * (see host/chez/java/io.ss jolt-append-payload!). At startup the stub locates - * its own executable, reads the trailing 16-byte frame to find the boot, and - * hands the boot to the Chez kernel — no external boot file, no Chez install. - * - * Built once at joltc-build time against the Chez kernel (libkernel.a + scheme.h) - * by host/chez/build-joltc.ss; the resulting binary is embedded into joltc and - * copied per app build. Inherently per-platform (the boot targets the host - * machine-type), like a native compiler. - */ -#include "scheme.h" -#include -#include -#include -#include - -#if defined(__APPLE__) -#include -static int self_path(char *buf, uint32_t size) { - /* _NSGetExecutablePath fills buf and reports the needed size on overflow. */ - return _NSGetExecutablePath(buf, &size); -} -#elif defined(_WIN32) -#include -static int self_path(char *buf, uint32_t size) { - DWORD n = GetModuleFileNameA(NULL, buf, size); - return (n == 0 || n >= size) ? -1 : 0; -} -#else -#include -static int self_path(char *buf, uint32_t size) { - ssize_t n = readlink("/proc/self/exe", buf, (size_t)size - 1); - if (n < 0) return -1; - buf[n] = '\0'; - return 0; -} -#endif - -#define JOLT_MAGIC "JOLTBOOT" -#define JOLT_MAGIC_LEN 8 -#define JOLT_TRAILER_LEN 16 /* u64 length + 8-byte magic */ - -int main(int argc, char *argv[]) { - char path[4096]; - if (self_path(path, (uint32_t)sizeof(path)) != 0) { - fprintf(stderr, "jolt: cannot resolve own executable path\n"); - return 1; - } - - FILE *f = fopen(path, "rb"); - if (!f) { fprintf(stderr, "jolt: cannot open self for reading\n"); return 1; } - - if (fseek(f, 0, SEEK_END) != 0) { fclose(f); return 1; } - long fsize = ftell(f); - if (fsize < JOLT_TRAILER_LEN) { - fprintf(stderr, "jolt: no boot payload (run was not produced by jolt build)\n"); - fclose(f); - return 1; - } - - unsigned char trailer[JOLT_TRAILER_LEN]; - if (fseek(f, fsize - JOLT_TRAILER_LEN, SEEK_SET) != 0 || - fread(trailer, 1, JOLT_TRAILER_LEN, f) != JOLT_TRAILER_LEN) { - fclose(f); - return 1; - } - if (memcmp(trailer + 8, JOLT_MAGIC, JOLT_MAGIC_LEN) != 0) { - fprintf(stderr, "jolt: boot payload not found\n"); - fclose(f); - return 1; - } - - uint64_t boot_len = 0; - for (int i = 0; i < 8; i++) - boot_len |= ((uint64_t)trailer[i]) << (8 * i); - - long boot_off = fsize - JOLT_TRAILER_LEN - (long)boot_len; - if (boot_off < 0) { - fprintf(stderr, "jolt: corrupt boot payload\n"); - fclose(f); - return 1; - } - - /* The kernel keeps the boot bytes for the life of the process (demand-loaded), - * so this buffer is freed only after Sscheme_deinit. */ - void *boot = malloc((size_t)boot_len); - if (!boot) { fclose(f); return 1; } - if (fseek(f, boot_off, SEEK_SET) != 0 || - fread(boot, 1, (size_t)boot_len, f) != (size_t)boot_len) { - free(boot); - fclose(f); - return 1; - } - fclose(f); - - Sscheme_init(0); - Sregister_boot_file_bytes("jolt", boot, (iptr)boot_len); - Sbuild_heap(0, 0); - int status = Sscheme_start(argc, (const char **)argv); - Sscheme_deinit(); - free(boot); - return status; -} diff --git a/host/chez/syntax-quote.ss b/host/chez/syntax-quote.ss deleted file mode 100644 index edb74c5..0000000 --- a/host/chez/syntax-quote.ss +++ /dev/null @@ -1,52 +0,0 @@ -;; syntax-quote form builders. A macro expander whose body was a syntax-quote -;; template (lowered by jolt.host/form-syntax-quote-lower) calls these at RUNTIME -;; to build the EXPANSION as READER forms (cseq list / pvec / pmap / tagged-set -;; pmap) so the on-Chez analyzer can re-analyze it. def-var!'d into clojure.core, -;; so the lowered body's -;; unqualified __sqcat/__sqvec/__sqmap/__sqset/__sq1 refs (which lower to var-deref -;; in prelude mode) resolve here. -;; -;; A list/vector/set template lowers to (__sqcat part ...) where each part is -;; either (__sq1 x) — a single non-spliced item — or a ~@ expr that evaluates to a -;; seqable spliced in place. Both kinds are seqables, so __sqcat just flattens each -;; part's jolt-seq in order. A map template lowers to (__sqmap k v ...) with no -;; splicing (alternating key/value, already lowered). -;; -;; Loaded by rt.ss after collections.ss/seq.ss (jolt-list/jolt-vector/jolt-hash-map/ -;; jolt-seq) and def-var!. - -;; flatten the __sqcat/__sqvec/__sqset parts (each a seqable) into a Scheme list. -(define (sq-flatten parts) - (let loop ((ps parts) (acc '())) - (if (null? ps) - (reverse acc) - (loop (cdr ps) - (let inner ((s (jolt-seq (car ps))) (a acc)) - (if (jolt-nil? s) - a - (inner (jolt-seq (seq-more s)) (cons (seq-first s) a)))))))) - -;; single non-spliced item -> a one-element seqable (__sqcat flattens it). -(define (jolt-sq1 x) (jolt-list x)) -;; list FORM: cseq with list?=#t, so the analyzer's form-list? sees a list. -(define (jolt-sqcat . parts) (apply jolt-list (sq-flatten parts))) -;; vector FORM: pvec. -(define (jolt-sqvec . parts) (apply jolt-vector (sq-flatten parts))) -;; set: a REAL set value (pset). A syntax-quote builds VALUES, and the cseq/pvec/ -;; pmap that __sqcat/__sqvec/__sqmap build double as their own form rep — but a set -;; value (pset) differs from the reader's set FORM ({:jolt/type :jolt/set :value -;; }), so building the tagged form here would make a runtime `#{~@xs} a map, -;; not a set. Build the value; the analyzer's form-set? -;; (host-contract.ss) additionally recognizes a pset, so a macro template's #{...} -;; expansion still re-analyzes as a set literal. -(define (jolt-sqset . parts) (apply jolt-hash-set (sq-flatten parts))) -;; map FORM: a plain pmap (the analyzer's form-map? = pmap with no :jolt/type). -;; Clojure's syntaxQuote builds the map via `apply hash-map`, so a `{...} template -;; is HASH-ordered (unlike a {...} literal, which keeps insertion order). -(define (jolt-sqmap . parts) (jolt-hash-map-build parts)) - -(def-var! "clojure.core" "__sq1" jolt-sq1) -(def-var! "clojure.core" "__sqcat" jolt-sqcat) -(def-var! "clojure.core" "__sqvec" jolt-sqvec) -(def-var! "clojure.core" "__sqset" jolt-sqset) -(def-var! "clojure.core" "__sqmap" jolt-sqmap) diff --git a/host/chez/transients.ss b/host/chez/transients.ss deleted file mode 100644 index 73b6385..0000000 --- a/host/chez/transients.ss +++ /dev/null @@ -1,244 +0,0 @@ -;; transients — mutable backing per collection kind, snapshotted to the immutable -;; collection on persistent!. conj!/assoc!/dissoc!/disj!/pop! mutate in place -;; (amortized O(1)); persistent! converts back to a pvec / pmap / pset once. -;; -;; vec : a growable Scheme vector (capacity) + a fill count `n`. conj!/pop! are -;; O(1) amortized — the old copy-on-write rebuilt the whole vector per op, -;; so building an N-vector was O(N^2). -;; map : a Chez hashtable keyed by key-hash / jolt= (value-equality, nil-safe — -;; a jolt-nil key stores fine here). -;; set : a Chez hashtable of elements. -;; cow : fallback for anything else (e.g. a sorted coll) — copy-on-write over -;; the persistent ops, preserving jolt's superset of Clojure's transients. -;; -;; get/count/contains?/nth see THROUGH a transient (frequencies/group-by read a -;; transient map; a transient is callable). vector? on a transient is false (it's -;; this record, not a pvec), which group-by relies on. Loaded after collections.ss -;; (persistent ops + key-hash) and converters.ss. - -;; For a transient MAP, `n` holds the array-mode capacity (entries it can hold -;; before promoting to hash order) and `ord` the reverse insertion-order key list; -;; for a vector `n` is the element count. A transient array map promotes to hash -;; at max(8, source-count) entries (TransientArrayMap, array sized max(16, len)), -;; with no keyword exception — unlike the persistent assoc growth rule. -(define-record-type jolt-transient - (fields kind (mutable buf) (mutable n) (mutable active) (mutable ord)) - (nongenerative jolt-transient-v3)) - -(define tvec-min-cap 8) -(define tmap-min-cap 8) - -(define (jolt-transient-new coll) - (cond - ((pvec? coll) - (let* ((v (pvec-v coll)) (cnt (vector-length v)) (cap (fxmax tvec-min-cap cnt)) - (buf (make-vector cap jolt-nil))) - (let loop ((i 0)) (when (fx? cnt cap) - ;; promoted past the array capacity: hash order - (let ((m empty-pmap-hash)) - (vector-for-each (lambda (k) (set! m (pmap-put-hash m k (hashtable-ref ht k jolt-nil)))) (hashtable-keys ht)) - m) - ;; array map: rebuild in insertion order - (let ((m empty-pmap)) - (for-each (lambda (k) (set! m (pmap-put-ordered m k (hashtable-ref ht k jolt-nil)))) - (reverse (jolt-transient-ord t))) - m)))) - ((set) - (let ((ht (jolt-transient-buf t)) (s empty-pset)) - (vector-for-each (lambda (e) (set! s (pset-conj s e))) (hashtable-keys ht)) - s)) - (else (jolt-transient-buf t)))) - -;; --- in-place mutation ------------------------------------------------------- -(define (tvec-ensure! t need) ; grow capacity to >= need by doubling - (let ((buf (jolt-transient-buf t))) - (when (fx>? need (vector-length buf)) - (let* ((ncap (let grow ((c (fxmax tvec-min-cap (vector-length buf)))) (if (fx>=? c need) c (grow (fx* 2 c))))) - (nbuf (make-vector ncap jolt-nil)) (cnt (jolt-transient-n t))) - (let loop ((i 0)) (when (fxidx i)) (cnt (jolt-transient-n t))) - (cond ((and (fixnum? i) (fx>=? i 0) (fx fresh transient vector; (conj! coll) -> the 1-arity transducer- -;; completion identity (JVM: no transient check). (conj! t x ...) mutates t. -(define (jolt-conj! . args) - (cond - ((null? args) (jolt-transient-new (jolt-vector))) - ((null? (cdr args)) (car args)) - (else - (let ((t (car args)) (xs (cdr args))) - (jolt-trans-check t "conj!") - (case (jolt-transient-kind t) - ((vec) (for-each (lambda (x) (tvec-conj1! t x)) xs)) - ((set) (for-each (lambda (x) (hashtable-set! (jolt-transient-buf t) x #t)) xs)) - ((map) (for-each (lambda (x) (tmap-conj-entry! t x)) xs)) - (else (jolt-transient-buf-set! t (apply jolt-conj (jolt-transient-buf t) xs)))) - t)))) - -;; assoc! is variadic. JVM: a complete first key/val pair present (>=3 kvs) with a -;; trailing lone key fills nil; a lone key alone (1 kv) is a wrong-arity throw. -(define (assoc-pad kvs) (if (and (>= (length kvs) 3) (odd? (length kvs))) (append kvs (list jolt-nil)) kvs)) -(define (jolt-assoc! t . kvs0) - (jolt-trans-check t "assoc!") - (let ((kvs (assoc-pad kvs0))) - (when (odd? (length kvs)) (error #f "assoc!: no value supplied for key")) - (case (jolt-transient-kind t) - ((map) (let lp ((xs kvs)) (unless (null? xs) (tmap-put! t (car xs) (cadr xs)) (lp (cddr xs))))) - ((vec) (let lp ((xs kvs)) (unless (null? xs) (tvec-assoc1! t (car xs) (cadr xs)) (lp (cddr xs))))) - (else (jolt-transient-buf-set! t (apply jolt-assoc (jolt-transient-buf t) kvs))))) - t) -(define (jolt-dissoc! t . ks) - (jolt-trans-check t "dissoc!") - (case (jolt-transient-kind t) - ((map) (for-each (lambda (k) (tmap-del! t k)) ks)) - (else (jolt-transient-buf-set! t (apply jolt-dissoc (jolt-transient-buf t) ks)))) - t) -(define (jolt-disj! t . xs) - (jolt-trans-check t "disj!") - (case (jolt-transient-kind t) - ((set) (for-each (lambda (x) (hashtable-delete! (jolt-transient-buf t) x)) xs)) - (else (jolt-transient-buf-set! t (apply jolt-disj (jolt-transient-buf t) xs)))) - t) -(define (jolt-pop! t) - (jolt-trans-check t "pop!") - (case (jolt-transient-kind t) - ((vec) (let ((cnt (jolt-transient-n t))) - (if (fx=? cnt 0) (error #f "pop!: can't pop empty transient vector") - (jolt-transient-n-set! t (fx- cnt 1))))) - (else (jolt-transient-buf-set! t (jolt-pop (jolt-transient-buf t))))) - t) - -;; persistent disj over sets (pset-disj already exists in collections.ss). -(define (jolt-disj s . xs) - ;; (disj nil ...) is nil on the JVM (disj is otherwise set-only). - (if (jolt-nil? s) - jolt-nil - (meta-carry s - (let loop ((s s) (xs xs)) (if (null? xs) s (loop (pset-disj s (car xs)) (cdr xs))))))) - -;; --- see-through accessors --------------------------------------------------- -(define (tvec-in-bounds? t i) (and (fixnum? i) (fx>=? i 0) (fxidx k))) (if (tvec-in-bounds? t i) (vector-ref (jolt-transient-buf t) i) d))) - ((map) (hashtable-ref (jolt-transient-buf t) k d)) - ((set) (if (hashtable-contains? (jolt-transient-buf t) k) k d)) - (else (%prev-jolt-get (jolt-transient-buf t) k d)))) -(define (t-count t) - (case (jolt-transient-kind t) - ((vec) (jolt-transient-n t)) - ((map set) (hashtable-size (jolt-transient-buf t))) - (else (%prev-jolt-count (jolt-transient-buf t))))) -(define (t-contains? t k) - (case (jolt-transient-kind t) - ((vec) (tvec-in-bounds? t (->idx k))) - ((map set) (hashtable-contains? (jolt-transient-buf t) k)) - (else (%prev-jolt-contains? (jolt-transient-buf t) k)))) - -;; Redefine the native get/count/contains?/nth (captured first) so the existing -;; emit lowerings unwrap a transient; non-transients are untouched. -(register-get-arm! jolt-transient? (lambda (coll k d) (t-get coll k d))) -(define %prev-jolt-count jolt-count) -(set! jolt-count (lambda (coll) (if (jolt-transient? coll) (t-count coll) (%prev-jolt-count coll)))) -(define %prev-jolt-contains? jolt-contains?) -(set! jolt-contains? (lambda (coll k) (if (jolt-transient? coll) (t-contains? coll k) (%prev-jolt-contains? coll k)))) -(define %prev-jolt-nth jolt-nth) -(set! jolt-nth - (case-lambda - ((coll i) - (if (jolt-transient? coll) - (if (eq? (jolt-transient-kind coll) 'vec) - (let ((idx (->idx i))) - (if (tvec-in-bounds? coll idx) (vector-ref (jolt-transient-buf coll) idx) (error 'nth "index out of bounds"))) - (%prev-jolt-nth (jolt-transient-buf coll) i)) - (%prev-jolt-nth coll i))) - ((coll i d) - (if (jolt-transient? coll) - (if (eq? (jolt-transient-kind coll) 'vec) - (let ((idx (->idx i))) (if (tvec-in-bounds? coll idx) (vector-ref (jolt-transient-buf coll) idx) d)) - (%prev-jolt-nth (jolt-transient-buf coll) i d)) - (%prev-jolt-nth coll i d))))) - -(def-var! "clojure.core" "transient" jolt-transient-new) -(def-var! "clojure.core" "transient?" jolt-transient?) -(def-var! "clojure.core" "persistent!" jolt-persistent!) -(def-var! "clojure.core" "conj!" jolt-conj!) -(def-var! "clojure.core" "assoc!" jolt-assoc!) -(def-var! "clojure.core" "dissoc!" jolt-dissoc!) -(def-var! "clojure.core" "disj!" jolt-disj!) -(def-var! "clojure.core" "pop!" jolt-pop!) -(def-var! "clojure.core" "disj" jolt-disj) diff --git a/host/chez/tree-shake-smoke.sh b/host/chez/tree-shake-smoke.sh deleted file mode 100644 index e8102ed..0000000 --- a/host/chez/tree-shake-smoke.sh +++ /dev/null @@ -1,63 +0,0 @@ -#!/bin/sh -# Tree-shake soundness smoke: build each example app twice — default and -# --tree-shake — run both, and require identical output. A wrongly-dropped def -# (incl. a core fn once core-shaking lands) shows up as a diff or a crash. Covers a -# pure-compute app and several that pull libraries via deps.edn (the key risk). -# -# Skips (like build-smoke) when the example repo or the Chez kernel dev files / -# C compiler aren't available. Slow (two full binary builds per app); not in the -# default gate — run with `make shakesmoke`. -root="$(CDPATH= cd -- "$(dirname -- "$0")/../.." && pwd)" -cd "$root" -examples="$root/../examples" -[ -d "$examples" ] || examples="$HOME/src/jolt-lang/examples" -if [ ! -d "$examples" ]; then echo "shake smoke: skipped (examples repo not found)"; exit 0; fi - -csv="$JOLT_CHEZ_CSV" -if [ -z "$csv" ]; then - chez_bin="$(command -v chez || command -v scheme || command -v petite || true)" - if [ -n "$chez_bin" ]; then - base="$(cd "$(dirname "$chez_bin")/.." 2>/dev/null && pwd)" - for d in "$base"/lib/csv*/*/; do [ -f "${d}libkernel.a" ] && csv="${d%/}" && break; done - fi -fi -if ! command -v cc >/dev/null 2>&1 || [ -z "$csv" ] || [ ! -f "$csv/scheme.h" ]; then - echo "shake smoke: skipped (Chez kernel dev files or C compiler not available)"; exit 0 -fi -export JOLT_CHEZ_CSV="$csv" - -tmp="$(mktemp -d)"; trap 'rm -rf "$tmp"' EXIT -fail=0 - -# app-dir | main-ns | args -run_case() { - app="$examples/$1"; ns="$2"; args="$3" - [ -d "$app" ] || { echo " - $1: skipped (not present)"; return; } - b0="$tmp/$1-plain"; b1="$tmp/$1-shake" - if ! JOLT_PWD="$app" bin/joltc build -m "$ns" -o "$b0" >/dev/null 2>&1; then - echo " - $1: FAIL (default build)"; fail=1; return; fi - if ! JOLT_PWD="$app" bin/joltc build -m "$ns" -o "$b1" --tree-shake >/dev/null 2>&1; then - echo " - $1: FAIL (--tree-shake build)"; fail=1; return; fi - o0="$(cd "$app" && "$b0" $args 2>&1)" - o1="$(cd "$app" && "$b1" $args 2>&1)" - if [ "$o0" != "$o1" ]; then - echo " - $1: FAIL (output differs default vs --tree-shake)" - echo " --- default ---"; echo "$o0" | head -5 - echo " --- shake -----"; echo "$o1" | head -5 - fail=1; return - fi - s0="$(wc -c < "$b0")"; s1="$(wc -c < "$b1")" - echo " - $1: ok (output identical; $((s0/1024))K -> $((s1/1024))K)" -} - -# Library apps (deps.edn git deps) with deterministic stdout — the key risk is that -# tree-shaking a binary that pulled libraries drops a reachable lib (or, later, core) -# fn. A timing/benchmark app (e.g. ray-tracer) is unsuitable: its output varies. -echo "shake smoke: building each app default vs --tree-shake (output must match)" -run_case markdown-app app.core "" -run_case malli-app app.core "" -run_case commonmark-app app.core "" -run_case hiccup-app app.core "" - -[ "$fail" = 0 ] && echo "shake smoke: passed" || echo "shake smoke: FAILED" -exit $fail diff --git a/host/chez/values.ss b/host/chez/values.ss deleted file mode 100644 index e0640f2..0000000 --- a/host/chez/values.ss +++ /dev/null @@ -1,144 +0,0 @@ -;; Jolt value model on Chez Scheme. -;; -;; The irreducible value layer the self-hosted RT rests on. Maps Clojure's value -;; types onto Chez natives where possible, and adds records only where Chez lacks -;; a distinct type (nil sentinel, keywords, ns-bearing symbols). Loaded into an -;; env that has already (import (chezscheme)). -;; -;; Design notes: -;; - nil is a UNIQUE sentinel, distinct from #f and '() (the classic Lisp-on-Lisp -;; trap). jolt false -> Chez #f, jolt true -> #t. -;; - Chez's numeric tower IS Clojure's: long->exact integer, double->flonum, -;; ratio->exact rational, bigint->bignum. Clojure `=` is exactness-aware: -;; (= 1 1.0) is FALSE. - -;; --- nil --------------------------------------------------------------------- -(define-record-type jolt-nil-t (fields) (nongenerative jolt-nil-v1)) -(define jolt-nil (make-jolt-nil-t)) -(define (jolt-nil? x) (jolt-nil-t? x)) -(define (jolt-some? x) (not (jolt-nil-t? x))) - -;; --- truthiness: only nil and false are falsey ------------------------------- -(define (jolt-truthy? x) (not (or (jolt-nil? x) (eq? x #f)))) - -;; --- keywords: interned so identity works; optional namespace ---------------- -(define-record-type keyword-t (fields ns name khash) (nongenerative keyword-v1)) -(define keyword-table (make-hashtable string-hash string=?)) -;; The common no-ns keyword is interned in a table keyed by NAME directly, so a -;; lookup of an already-interned :kw (the hot case — every (:kw x), map literal, -;; keyword arg) is one hashtable-ref with NO allocation. The ns table keeps the -;; combined key. Both share the keyword-t khash (equal-hash of the combined key), -;; so hash values are unchanged. -(define keyword-table-bare (make-hashtable string-hash string=?)) -;; NUL separator can't occur in a keyword ns/name, so the intern key is -;; unambiguous (a "/" separator would collide ns="a" name="b/c" with ns="a/b"). -(define (keyword-intern-key ns name) (string-append (or ns "") "\x0;" name)) -(define (keyword ns name) - (if ns - (let ((k (keyword-intern-key ns name))) - (or (hashtable-ref keyword-table k #f) - (let ((kw (make-keyword-t ns name (equal-hash k)))) - (hashtable-set! keyword-table k kw) - kw))) - (or (hashtable-ref keyword-table-bare name #f) - (let ((kw (make-keyword-t #f name (equal-hash (keyword-intern-key #f name))))) - (hashtable-set! keyword-table-bare name kw) - kw)))) -(define (keyword? x) (keyword-t? x)) - -;; --- symbols: ns + name + meta; NOT interned (meta varies), = by ns/name ------ -;; The ns/name STRINGS are pooled (like JVM Symbol.intern, which .intern()s them): -;; two separately-read `?a` symbols share one name-string object, so code that -;; compares symbol names by identity (core.logic's non-unique lvar equality, via -;; (str sym)) behaves like the JVM. -(define symbol-string-pool (make-hashtable string-hash string=?)) -(define (intern-symbol-string s) - (if (string? s) - (or (hashtable-ref symbol-string-pool s #f) - (begin (hashtable-set! symbol-string-pool s s) s)) - s)) -(define-record-type symbol-t (fields ns name meta) (nongenerative symbol-v1)) -(define (jolt-symbol ns name) - (make-symbol-t (intern-symbol-string ns) (intern-symbol-string name) jolt-nil)) -(define (jolt-symbol/meta ns name meta) - (make-symbol-t (intern-symbol-string ns) (intern-symbol-string name) meta)) -(define (jolt-symbol? x) (symbol-t? x)) - -;; chars/strings: Chez natives (strings treated immutable). - -;; --- jolt equality (Clojure =) — scalars + collections ---------------------- -;; A host shim registers a type's equality via register-eq-arm! instead of -;; set!-wrapping jolt=2 (cf. register-hash-arm!). An arm is (pred . handler), both -;; (a b): the arm applies when pred holds (typically either arg is the type), and -;; handler returns the #t/#f result. Arms are checked before the base scalar/coll -;; cases; the entry is stable. -(define jolt-eq-arms '()) -(define (register-eq-arm! pred handler) - (set! jolt-eq-arms (cons (cons pred handler) jolt-eq-arms))) -(define (jolt=2-base a b) - (cond - ((and (jolt-nil? a) (jolt-nil? b)) #t) - ((or (jolt-nil? a) (jolt-nil? b)) #f) - ((and (number? a) (number? b)) ; exactness-aware - (and (eq? (exact? a) (exact? b)) (= a b))) - ((and (keyword-t? a) (keyword-t? b)) (eq? a b)) ; interned - ((and (symbol-t? a) (symbol-t? b)) - (and (equal? (symbol-t-ns a) (symbol-t-ns b)) - (string=? (symbol-t-name a) (symbol-t-name b)))) - ((and (char? a) (char? b)) (char=? a b)) - ((and (string? a) (string? b)) (string=? a b)) - ((and (boolean? a) (boolean? b)) (eq? a b)) - ;; sequential (vector / list / lazy seq) compare element-wise, cross-type: - ;; (= [1 2 3] (list 1 2 3)) is true. Forward to seq.ss (loaded by rt.ss). - ((and (jolt-sequential? a) (jolt-sequential? b)) (seq=? a b)) - ((or (jolt-sequential? a) (jolt-sequential? b)) #f) - ;; other collections (map/set): forward to collections.ss. - ((and (jolt-coll? a) (jolt-coll? b)) (jolt-coll=? a b)) - (else (eq? a b)))) -(define (jolt=2 a b) - ;; identity fast path, like Util.equiv's k1 == k2: the same object equals - ;; itself without a structural walk — (= s s) on an infinite lazy seq must not - ;; realize it. Numbers keep the exactness-aware arm (Chez may intern flonum - ;; literals, and (= ##NaN ##NaN) is false like the JVM's). - (if (and (eq? a b) (not (number? a))) - #t - (let loop ((as jolt-eq-arms)) - (cond ((null? as) (jolt=2-base a b)) - (((caar as) a b) ((cdar as) a b)) - (else (loop (cdr as))))))) -(define (jolt= a . rest) - (let loop ((a a) (rest rest)) - (cond ((null? rest) #t) - ((jolt=2 a (car rest)) (loop (car rest) (cdr rest))) - (else #f)))) - -;; --- jolt hash — consistent with jolt= (for the HAMT) ----------------------- -;; A host shim (records, host-table, inst-time, …) registers its type's hash via -;; register-hash-arm! instead of set!-wrapping jolt-hash — the arms are disjoint -;; types, checked before the base cases, so the full behavior is gathered here plus -;; the registry rather than scattered across a set! chain (cf. register-str-render!). -(define jolt-hash-arms '()) -(define (register-hash-arm! pred handler) - (set! jolt-hash-arms (cons (cons pred handler) jolt-hash-arms))) -(define (jolt-hash-base x) - (cond - ((jolt-nil? x) 0) - ((keyword-t? x) (keyword-t-khash x)) - ((symbol-t? x) (equal-hash (cons (symbol-t-ns x) (symbol-t-name x)))) - ;; distinguish inexact from exact (1 and 1.0 are not jolt=); guard non-finite - ;; (inexact->exact would error on NaN/inf) - ((number? x) (if (exact? x) (equal-hash x) - (if (and (flonum? x) (or (nan? x) (infinite? x))) - (equal-hash (cons 'inexact (number->string x))) - (equal-hash (cons 'inexact (inexact->exact x)))))) - ((string? x) (string-hash x)) - ((char? x) (char->integer x)) - ((boolean? x) (if x 1 2)) - ((jolt-sequential? x) (seq-hash x)) ; vector/list/seq hash alike (forward to seq.ss) - ((jolt-coll? x) (jolt-coll-hash x)) ; map/set; forward to collections.ss - (else (equal-hash x)))) -(define (jolt-hash x) - (let loop ((as jolt-hash-arms)) - (cond ((null? as) (jolt-hash-base x)) - (((caar as) x) ((cdar as) x)) - (else (loop (cdr as)))))) diff --git a/host/chez/vars.ss b/host/chez/vars.ss deleted file mode 100644 index 3472957..0000000 --- a/host/chez/vars.ss +++ /dev/null @@ -1,50 +0,0 @@ -;; vars as first-class objects — (var x) / #'x. -;; -;; The emitter lowers :the-var to (jolt-var ns name) — the rt.ss var-cell, which -;; is now also a Clojure VAR value. var? / var-get / deref-of-var / var-as-IFn / -;; var equality / pr-str(#'ns/name) operate on it. bound? is overridden natively -;; in post-prelude.ss (the overlay reads (get v :root), nil on a record). -;; -;; Dynamic binding (binding / with-bindings* / var-set / thread-bound? / -;; with-redefs) lives in dyn-binding.ss, which chains the var-read paths set up -;; here. -;; -;; Loaded LAST (after natives-transduce.ss): chains jolt-deref (atom/volatile arms) -;; and the printers. - -(define (jolt-var-pred? x) (var-cell? x)) - -;; the var's current root; unbound is an error (Clojure throws on an unbound var). -(define (jolt-var-get v) - (if (var-cell? v) - (let ((r (var-cell-root v))) - (if (eq? r jolt-unbound) (error #f "Unbound var" v) r)) - (error #f "var-get: not a var" v))) - -;; deref of a var -> its root. -(define %v-deref jolt-deref) -(set! jolt-deref (lambda (x) (if (var-cell? x) (jolt-var-get x) (%v-deref x)))) - -;; a var is an IFn — invoking it invokes its root value ((var f) args -> (f args)). -(define %v-invoke jolt-invoke) -(set! jolt-invoke (lambda (f . args) - (if (var-cell? f) (apply jolt-invoke (var-cell-root f) args) (apply %v-invoke f args)))) - -;; two var cells are = iff same ns/name (Clojure var identity). -(register-eq-arm! (lambda (a b) (or (var-cell? a) (var-cell? b))) - (lambda (a b) (and (var-cell? a) (var-cell? b) - (string=? (var-cell-ns a) (var-cell-ns b)) - (string=? (var-cell-name a) (var-cell-name b))))) - -;; pr-str / str of a var -> #'ns/name. -(define (var->str v) (string-append "#'" (var-cell-ns v) "/" (var-cell-name v))) -(register-pr-arm! var-cell? var->str) -(register-str-render! var-cell? var->str) - -;; bound? — native (the overlay's (get v :root) is nil on a var-cell record). -(define (jolt-var-bound-one? v) (and (var-cell? v) (not (eq? (var-cell-root v) jolt-unbound)))) -(define (jolt-bound? . vars) (if (for-all jolt-var-bound-one? vars) #t #f)) - -(def-var! "clojure.core" "var?" jolt-var-pred?) -(def-var! "clojure.core" "var-get" jolt-var-get) -(def-var! "clojure.core" "deref" jolt-deref) diff --git a/install b/install deleted file mode 100755 index 45ab20d..0000000 --- a/install +++ /dev/null @@ -1,161 +0,0 @@ -#!/usr/bin/env bash - -# Installs the latest (or a specific) version of joltc, the self-contained jolt -# binary. It bundles the runtime, compiler, jolt-core + stdlib, and the Chez -# boots, so there is nothing else to install — no Chez, no cc, no JVM. - -set -euo pipefail - -version="" -checksum="" -default_install_dir="/usr/local/bin" -install_dir="$default_install_dir" -download_dir="" - -repo="jolt-lang/jolt" - -print_help() { - echo "Installs the latest (or a specific) version of joltc." - echo "Installation directory defaults to ${default_install_dir}." - echo - echo "Usage:" - echo " install [--dir ] [--download-dir ] [--version ] [--checksum ]" - echo - echo "Defaults:" - echo " * Installation directory: ${default_install_dir}" - echo " * Download directory: a temporary directory" - echo " * Version: the latest release on GitHub" - echo " * Checksum: fetched from the release and verified automatically" - exit 1 -} - -has() { - command -v "$1" >/dev/null 2>&1 -} - -fetch() { - local url=$1 - local outfile=${2:-} - if has curl; then - if [[ -n $outfile ]]; then curl -fsSL "$url" -o "$outfile"; else curl -fsSL "$url"; fi - elif has wget; then - if [[ -n $outfile ]]; then wget -qO "$outfile" "$url"; else wget -qO - "$url"; fi - else - >&2 echo "Either 'curl' or 'wget' needs to be on PATH." - exit 1 - fi -} - -while [[ $# -gt 0 ]]; do - case "$1" in - --dir) install_dir="$2"; shift 2 ;; - --download-dir) download_dir="$2"; shift 2 ;; - --version) version="$2"; shift 2 ;; - --checksum) checksum="$2"; shift 2 ;; - --help|-h) print_help ;; - *) print_help ;; - esac -done - -if [[ -z "$download_dir" ]]; then - download_dir="$(mktemp -d)" - trap 'rm -rf "$download_dir"' EXIT -fi - -# --- resolve platform / arch to a release target ----------------------------- -case "$(uname -s)" in - Linux*) platform=linux ;; - Darwin*) platform=macos ;; - *) >&2 echo "Unsupported OS: $(uname -s). Prebuilt binaries exist for Linux and macOS."; exit 1 ;; -esac - -case "$(uname -m)" in - x86_64|amd64) arch=x86_64 ;; - aarch64|arm64) arch=aarch64 ;; - *) >&2 echo "Unsupported architecture: $(uname -m)."; exit 1 ;; -esac - -target="${arch}-${platform}" -case "$target" in - x86_64-linux|aarch64-macos) ;; - x86_64-macos) - >&2 echo "No prebuilt joltc for Intel macOS (GitHub retired the Intel runner)." - >&2 echo "Build from source: https://github.com/${repo} (needs Chez Scheme + cc)." - exit 1 ;; - *) >&2 echo "No prebuilt joltc for ${target}." - >&2 echo "Available: x86_64-linux, aarch64-macos." - >&2 echo "Build from source: https://github.com/${repo} (make joltc-release)." - exit 1 ;; -esac - -# --- resolve version --------------------------------------------------------- -if [[ -z "$version" ]]; then - version="$(fetch "https://api.github.com/repos/${repo}/releases/latest" \ - | grep -m1 '"tag_name"' | sed -E 's/.*"tag_name": *"([^"]+)".*/\1/')" - if [[ -z "$version" ]]; then - >&2 echo "Could not determine the latest release. Pass --version explicitly." - exit 1 - fi -fi -tag="v${version#v}" # accept 0.1.0 or v0.1.0; the tag/asset carry the leading v - -filename="joltc-${tag}-${target}.tar.gz" -download_url="https://github.com/${repo}/releases/download/${tag}/${filename}" - -if has sha256sum; then - sha256sum_cmd="sha256sum" -elif has shasum; then - sha256sum_cmd="shasum -a 256" -else - sha256sum_cmd="" -fi - -mkdir -p "$download_dir" && ( - cd "$download_dir" - echo "Downloading ${download_url}" - fetch "$download_url" "$filename" - - # verify: an explicit --checksum wins; otherwise fetch the release's .sha256. - if [[ -z "$checksum" ]]; then - checksum="$(fetch "${download_url}.sha256" 2>/dev/null | cut -d' ' -f1 || true)" - fi - if [[ -n "$checksum" && -n "$sha256sum_cmd" ]]; then - got="$($sha256sum_cmd "$filename" | cut -d' ' -f1)" - if [[ "$got" != "$checksum" ]]; then - >&2 echo "Checksum mismatch on ${filename}" - >&2 echo " got: ${got}" - >&2 echo " expected: ${checksum}" - exit 1 - fi - elif [[ -z "$sha256sum_cmd" ]]; then - >&2 echo "Note: no sha256sum/shasum on PATH; skipping checksum verification." - fi - - tar -zxf "$filename" - rm -f "$filename" -) - -# the tarball unpacks to a directory holding the binary -extracted="${download_dir}/joltc-${tag}-${target}/joltc" -if [[ ! -f "$extracted" ]]; then - >&2 echo "Expected ${extracted} in the archive but it was not found." - exit 1 -fi - -mkdir -p "$install_dir" -if [[ -f "$install_dir/joltc" ]]; then - echo "Moving existing $install_dir/joltc to $install_dir/joltc.old" - mv -f "$install_dir/joltc" "$install_dir/joltc.old" -fi -mv -f "$extracted" "$install_dir/joltc" -chmod +x "$install_dir/joltc" - -# clear the macOS quarantine flag so Gatekeeper doesn't block the fresh download -if [[ "$platform" == "macos" ]] && has xattr; then - xattr -d com.apple.quarantine "$install_dir/joltc" 2>/dev/null || true -fi - -echo "Successfully installed joltc ${tag} to ${install_dir}/joltc" -if ! echo ":$PATH:" | grep -q ":${install_dir}:"; then - echo "Note: ${install_dir} is not on your PATH." -fi diff --git a/jolt-core/clojure/core/00-kernel.clj b/jolt-core/clojure/core/00-kernel.clj index 3a69a46..93a16e4 100644 --- a/jolt-core/clojure/core/00-kernel.clj +++ b/jolt-core/clojure/core/00-kernel.clj @@ -1,4 +1,4 @@ -;; clojure.core — kernel tier (stage just above the host primitives). +;; clojure.core — kernel tier (stage just above the Janet seed). ;; ;; These are the structural fns the self-hosted compiler itself uses ;; (jolt.analyzer): second/peek/subvec/mapv/update. Because the compiler must be @@ -6,11 +6,12 @@ ;; before it is built. So this tier is loaded FIRST and, in compile mode, is ;; bootstrap-compiled directly into clojure.core (not routed through the ;; self-hosted pipeline, which would need these to already exist — the -;; circularity that previously forced `second` to stay a host primitive). With this tier -;; in place the analyzer is built against the Clojure definitions. +;; circularity that previously forced `second` to stay in Janet). With this tier +;; in place the analyzer is built against the Clojure definitions and the Janet +;; primitives are gone. ;; ;; Constraint: depend only on core-renames primitives (first/next/nth/count/conj/ -;; vec/map/apply/assoc/get/…, all hardwired to host primitives) and on each other. +;; vec/map/apply/assoc/get/…, all hardwired to the Janet seed) and on each other. (defn second [coll] (first (next coll))) @@ -27,12 +28,12 @@ ([v start end] (when (not (vector? v)) (throw (str "subvec requires a vector"))) ;; Clojure coerces indices with (int ...): NaN -> 0, floats/ratios truncate - ;; toward zero; non-numbers throw. Only then range-check. + ;; toward zero ((quot x 1)); non-numbers throw. Only then range-check. (let [coerce (fn [x] (cond (not (number? x)) (throw (str "subvec index must be a number")) (not= x x) 0 - :else (long x))) + :else (quot x 1))) s (coerce start) e (coerce end)] (when (or (< s 0) (< e s) (< (count v) e)) @@ -43,10 +44,3 @@ (defn mapv [f & colls] (vec (apply map f colls))) (defn update [m k f & args] (assoc m k (apply f (get m k) args))) - -;; set: realize a seqable and dedup through the set constructor; nil -> #{}. The -;; compiler uses it off the emit path (backend bare-native-names, type inference), -;; so unlike boolean it can live here — compiling this tier never calls set, and by -;; the time those callers run the tier is bound. Pure composition of hash-set/seq/ -;; apply, so it lowers to the same code the native shim did. -(defn set [coll] (if (nil? coll) #{} (apply hash-set (seq coll)))) diff --git a/jolt-core/clojure/core/00-syntax.clj b/jolt-core/clojure/core/00-syntax.clj index 9c5d79c..d8e7298 100644 --- a/jolt-core/clojure/core/00-syntax.clj +++ b/jolt-core/clojure/core/00-syntax.clj @@ -4,74 +4,10 @@ ;; them is compiled — including the kernel tier, the self-hosted analyzer, and the ;; seq/coll tiers. ;; -;; CONSTRAINT: code here may use ONLY special forms (if/do/let*/fn*/not) and -;; SEED primitives (first/next/rest/nth/count/seq/...), plus earlier defs in -;; THIS file. It must NOT use kernel-tier fns (second/peek/subvec/...) or -;; anything defined later — those don't exist yet when this tier loads. Raw -;; fn*/let* (no destructuring) and no when/cond/and/or above their defmacros. -;; -;; This tier's defns load interpreted and are recompiled by the staged pass -;; (backend/recompile-defns!) once the analyzer is alive — same lifecycle as -;; the defmacro expanders. - -;; zero?/pos?/every? live HERE (not 20-coll): empty? below calls zero?, and -;; the self-hosted analyzer — compiled right after the kernel tier — uses all -;; three. Raw def+fn* per the file constraint. zero? checks number? itself -;; (= doesn't throw); pos? inherits throwing from >. -(def zero? - (fn* zero? [x] - (if (number? x) - (= x 0) - (throw (str "zero? requires a number, got: " x))))) - -;; pos? checks number? explicitly: this tier is recompiled by the staged pass, -;; where a bare (> x 0) emits the native op that happily orders strings -;; (the documented native-ops relaxation) — the guard keeps Clojure's throw. -(def pos? - (fn* pos? [x] - (if (number? x) - (> x 0) - (throw (str "pos? requires a number, got: " x))))) - -;; Canonical every?: short-circuits on the first falsey result, so infinite -;; seqs with an early counterexample terminate. -(def every? - (fn* every? [pred coll] - (if (nil? (seq coll)) - true - (if (pred (first coll)) - (recur pred (next coll)) - false)))) - -;; empty?/keys/vals live HERE (not 20-coll) because the expanders below call -;; them at expansion time, which first happens during the kernel-tier compile. -;; empty? keeps O(1) dispatch for counted things; only the lazy/list fallback -;; goes through seq's cell check. -(def empty? - (fn* empty? [coll] - (if (nil? coll) - true - (if (vector? coll) - (zero? (count coll)) - (if (map? coll) - (zero? (count coll)) - (if (set? coll) - (zero? (count coll)) - (if (string? coll) - (zero? (count coll)) - (nil? (seq coll))))))))) - -;; Canonical: the seq of entries/elements, projected. (keys {}) is nil; sorted -;; maps iterate in comparator order ((seq sm) is the value's own :seq op). -(def keys - (fn* keys [m] - (let* [s (seq m)] - (if s (map (fn* [e] (nth e 0)) s) nil)))) - -(def vals - (fn* vals [m] - (let* [s (seq m)] - (if s (map (fn* [e] (nth e 1)) s) nil)))) +;; CONSTRAINT: a macro here may use ONLY special forms (if/do/let*/fn*/not) and +;; core-renames SEED primitives (first/next/rest/nth/count/empty?/...). It must +;; NOT use kernel-tier fns (second/peek/subvec/...) or anything defined later — +;; those don't exist yet when this tier loads. (defmacro when [test & body] `(if ~test (do ~@body))) @@ -110,16 +46,9 @@ ;; then. Its body resolves fn/map/reduce/cond at EXPANSION time, by which point all ;; of 00-syntax has loaded, so using them here is fine. (defmacro ns [nm & clauses] - ;; ^{:map} metadata on the ns name reads as a (with-meta sym {...}) form, not an - ;; annotated symbol. Real libraries put :author/:doc there - ;; (clojure.tools.logging), so unwrap to the bare symbol; jolt does not track - ;; namespace metadata, so the map is dropped. - (let [nm (if (and (seq? nm) (= 'with-meta (first nm))) (second nm) nm) - calls (reduce + (let [calls (reduce (fn [acc clause] - ;; a reference clause may be a list (:require …) or a vector - ;; [:require …]; Clojure accepts both, dispatching on (first clause). - (if (or (seq? clause) (vector? clause)) + (if (seq? clause) (let [head (first clause) args (rest clause)] (cond (= head :require) (conj acc `(require ~@(map (fn [s] `(quote ~s)) args))) @@ -152,24 +81,12 @@ `(~form ~x))] `(->> ~threaded ~@(rest forms))))) -;; Forward declaration interns unbound vars (Clojure semantics). The interpreter -;; resolves forward refs lazily either way, but the COMPILER classifies globals at -;; compile time: without the var, a declared name that collides with a host root -;; binding (parse, hash, …) would compile to the host fn instead of the var. -(defmacro declare [& syms] - `(do ~@(map (fn* [s] `(def ~s)) syms))) +;; Forward declaration is a no-op on Jolt — the compiler resolves forward refs via +;; pending cells (matching the prior Janet macro). +(defmacro declare [& syms] `(do)) -;; letfn is a macro over the letfn* special form, matching Clojure: each -;; (name [params] body*) spec becomes a name + a (fn name [params] body*) binding. -;; So (macroexpand-1 '(letfn …)) yields the letfn* form macroexpansion tooling -;; (tools.macro / tools.analyzer) expects, instead of an opaque special form. -(defmacro letfn [fnspecs & body] - (cons 'letfn* - (cons (reduce (fn [acc s] (conj (conj acc (first s)) (cons 'fn s))) [] fnspecs) - body))) - -;; destructure — Clojure's binding-vector expander. -;; Turns a binding vector that may contain destructuring +;; destructure — Clojure's binding-vector expander, ported from the Janet seed +;; (was core-destructure). Turns a binding vector that may contain destructuring ;; patterns into a plain binding vector (alternating symbol / init-form) built from ;; nth/nthnext/get, so the COMPILER only ever sees plain symbols (analyze-bindings ;; rejects patterns). `let` consumes it directly; `loop`/`fn` reuse it transitively @@ -188,23 +105,9 @@ [false nil] (if or-map (keys or-map) []))) amp? (fn* [x] (and (symbol? x) (= "&" (name x)))) - ;; split a :keys/:syms/:strs name list at & into [sym bind?] pairs. Names - ;; before & bind normally (bind? true); names after & are declared-only - ;; (bind? false) — accepted keys (:keys) or required keys (:keys!), per - ;; CLJ-2961. - classify - (fn* [names] - (nth (reduce (fn* [st x] - (if (amp? x) - [(nth st 0) false] - [(conj (nth st 0) [x (nth st 1)]) (nth st 1)])) - [[] true] names) - 0)) proc (fn* proc [pat init acc] (cond - ;; CLJ-2954: & is reserved for destructuring rest, never a binding. - (amp? pat) (throw (new IllegalArgumentException "Can't use & as a local binding")) (symbol? pat) (conj (conj acc pat) init) (vector? pat) (let* [g (symbol (str (gensym))) @@ -226,87 +129,53 @@ (let* [g (symbol (str (gensym))) gm (symbol (str (gensym))) ;; kwargs: a map pattern may bind against the sequential rest - ;; of a fn — (& {:keys [...]}) — a seq of alternating k/v args, - ;; optionally with a trailing map (Clojure 1.11: (f :a 1 {:b 2}) - ;; merges the map over the pairs; (f {:a 1}) is just the map). - ;; An odd count means the last arg is that trailing map. A real - ;; map value is used as-is, so ordinary map destructuring is - ;; unaffected. g holds init once; gm is the coerced map every - ;; lookup (and :as) reads from. + ;; of a fn — (& {:keys [...]}) — which is a seq of alternating + ;; k/v args, or a single trailing map. Coerce like Clojure (and + ;; like the interpreter's destructure-bind, so interpret/compile + ;; agree): a sequential value with one map element is that map, + ;; otherwise (apply hash-map). A real map value is used as-is, so + ;; ordinary map destructuring is unaffected. g holds init once; + ;; gm is the coerced map every lookup (and :as) reads from. coerce `(if (sequential? ~g) - (if (odd? (count ~g)) - (merge (apply hash-map (butlast ~g)) (last ~g)) + (if (and (= 1 (count ~g)) (map? (first ~g))) + (first ~g) (apply hash-map ~g)) ~g) or-map (get pat :or) as-sym (get pat :as) bound (conj (conj (conj (conj acc g) init) gm) coerce) base (if as-sym (conj (conj bound as-sym) gm) bound) - ;; group binds a :keys/:strs/:syms list. dnsp is the destructuring - ;; namespace from a qualified key like :ns/keys — it both prefixes - ;; the lookup key and overrides a bare symbol's namespace. - ;; group binds a :keys/:strs/:syms list. checked? marks the - ;; :keys!/:strs!/:syms! variants (CLJ-2961): lookups use req! - ;; (throw on missing) instead of get. A pair is [sym bind?]; - ;; bind? false (names after &) is declared-only — for checked - ;; groups it still runs req! (bound to a throwaway gensym) to - ;; enforce the key, for unchecked groups it's a no-op. group - (fn* group [a names kind dnsp checked?] - (if names + (fn* [a kw kind] + (let* [names (get pat kw)] + (if names (reduce ;; s is a symbol (a b) or a keyword (:a :b); name/ ;; namespace handle both, so :keys [:major] binds ;; `major` looking up :major (str would keep the colon). - (fn* [aa pair] - (let* [s (nth pair 0) - bind? (nth pair 1) - local (name s) - nsp (or (namespace s) dnsp) + (fn* [aa s] + (let* [local (name s) + nsp (namespace s) keyform (cond (= kind :kw) (keyword (if nsp (str nsp "/" local) local)) (= kind :str) local :else `(quote ~(symbol nsp local))) - fo (find-or or-map local) - lookup (cond - checked? `(req! ~gm ~keyform) - (nth fo 0) `(get ~gm ~keyform ~(nth fo 1)) - :else `(get ~gm ~keyform))] - (cond - bind? (conj (conj aa (symbol local)) lookup) - checked? (conj (conj aa (symbol (str (gensym)))) lookup) - :else aa))) - a (classify names)) - a)) - g1 (group base (get pat :keys) :kw nil false) - g2 (group g1 (get pat :strs) :str nil false) - g3 (group g2 (get pat :syms) :sym nil false) - g4 (group g3 (get pat :keys!) :kw nil true) - g5 (group g4 (get pat :strs!) :str nil true) - g6 (group g5 (get pat :syms!) :sym nil true)] - ;; remaining keys: a qualified :ns/keys|:ns/strs|:ns/syms groups under - ;; its namespace; any other keyword is skipped; a non-keyword is a - ;; nested binding pattern. + fo (find-or or-map local)] + (conj (conj aa (symbol local)) + (if (nth fo 0) + `(get ~gm ~keyform ~(nth fo 1)) + `(get ~gm ~keyform))))) + a names) + a))) + g1 (group base :keys :kw) + g2 (group g1 :strs :str) + g3 (group g2 :syms :sym)] (reduce (fn* [a k] (if (keyword? k) - (let* [kn (name k) kns (namespace k)] - (cond - (and kns (= kn "keys")) (group a (get pat k) :kw kns false) - (and kns (= kn "strs")) (group a (get pat k) :str kns false) - (and kns (= kn "syms")) (group a (get pat k) :sym kns false) - (and kns (= kn "keys!")) (group a (get pat k) :kw kns true) - (and kns (= kn "strs!")) (group a (get pat k) :str kns true) - (and kns (= kn "syms!")) (group a (get pat k) :sym kns true) - :else a)) - ;; a direct binding {x :x}: apply its :or default - ;; (keyed by the local symbol) when the key is absent. - (let* [fo (if (symbol? k) (find-or or-map (name k)) [false nil])] - (proc k (if (nth fo 0) - `(get ~gm ~(get pat k) ~(nth fo 1)) - `(get ~gm ~(get pat k))) - a)))) - g6 (keys pat))) - :else (throw (str "unsupported destructuring pattern: " (pr-str pat))))) + a + (proc k `(get ~gm ~(get pat k)) a))) + g3 (keys pat))) + :else (throw (str "unsupported destructuring pattern")))) ploop (fn* ploop [i acc] (if (< i (count bindings)) @@ -357,56 +226,25 @@ (defmacro fn [& raw] (let [nm (if (symbol? (first raw)) (first raw) nil) aftn (if nm (next raw) raw) - ;; a return-type hint (defn f ^bytes [x] ...) reaches us as a - ;; (with-meta [x] {:tag ...}) FORM in params position — unwrap it - ;; (the hint means nothing on jolt; ring-codec carries several). - unhint (fn* [x] - (if (if (seq? x) (= 'with-meta (first x)) false) - (nth x 1) - x)) - ;; a :pre/:post conditions map (a leading map when the body has more forms - ;; after it) becomes assertions: pre before the body, then bind % to the - ;; result, post after, return %. (map? is a native, so this is tier-safe; - ;; the assert/map calls only run when a conditions map is actually present.) - wrap-conds - (fn* [body] - (if (if (map? (first body)) (next body) false) - (let [conds (first body) - real (next body) - mka (fn* [cs] (map (fn* [c] `(assert ~c)) cs))] - `(~@(mka (get conds :pre)) - (let [~'% (do ~@real)] - ~@(mka (get conds :post)) - ~'%))) - body)) md (fn* go [ps nps lets] (if (seq ps) (if (symbol? (first ps)) (go (next ps) (conj nps (first ps)) lets) - ;; a bare (gensym) returns a host symbol the destructurer rejects; - ;; round-trip through str for a jolt symbol. + ;; bare (gensym) here is Janet's (a Janet symbol the destructurer + ;; rejects); round-trip through str for a jolt symbol. (let [g (symbol (str (gensym)))] (go (next ps) (conj nps g) (conj (conj lets (first ps)) g)))) [nps lets])) mk (fn* [sig] - (let [ps (unhint (first sig)) - hinted (not (= ps (first sig))) - r (md (seq ps) [] []) - raw-body (rest sig) - body (wrap-conds raw-body) - conds? (not (= body raw-body))] - (if (if (empty? (nth r 1)) (if (not hinted) (not conds?) false) false) + (let [r (md (seq (first sig)) [] [])] + (if (empty? (nth r 1)) sig ;; build the params/let vectors via [~@..] so they are tuple forms ;; (the accumulators are plain seqs, the wrong representation). - ;; A hinted-but-undestructured arity also rebuilds, to shed the - ;; with-meta wrapper without changing the clause representation. (let [pv `[~@(nth r 0)] lv `[~@(nth r 1)]] - (if (empty? (nth r 1)) - `(~pv ~@body) - `(~pv (let ~lv ~@body)))))))] - (if (vector? (unhint (first aftn))) + `(~pv (let ~lv ~@(rest sig)))))))] + (if (vector? (first aftn)) (let [a (mk aftn)] (if nm `(fn* ~nm ~@a) `(fn* ~@a))) (let [as (vec (map mk aftn))] @@ -420,39 +258,17 @@ ;; vector + body or a sequence of ([params] body) clauses, so no arity branching is ;; needed. (map? is true for symbol forms too, so guard the attr-map with symbol?.) ;; Defined before fresh-sym below, which is a defn-. -;; defn lives in the earliest tier, so its macro body may only use primitives -;; available before the seq/coll tiers — conj (which merges a map onto a map), -;; assoc, meta, with-meta — not merge/last/butlast. (defmacro defn [fn-name & body] - (let [docstring (when (and (seq body) (string? (first body))) (first body)) - body (if docstring (rest body) body) - ;; the attr-map after an optional docstring (or after the name) — its keys - ;; merge into the var metadata, like Clojure. A map in the first arity - ;; position is the attr-map only when more body follows (else it is a lone - ;; map body) and is never a symbol (a name carries its meta as a form). - attr-map (when (and (seq body) (next body) (map? (first body)) (not (symbol? (first body)))) - (first body)) - body (if attr-map (rest body) body) - ;; the bare name + any ^{:map} metadata the reader attached to it. - fn-only-name (if (symbol? fn-name) fn-name (first (rest fn-name))) - name-meta (meta fn-only-name) - m1 (if attr-map (if name-meta (conj name-meta attr-map) attr-map) name-meta) - meta-map (if docstring (assoc (if m1 m1 {}) :doc docstring) m1)] - ;; pass the name through to fn: the compiled fn's host name carries it, so - ;; stack traces read app.deep/level3 instead of a gensym. All metadata - ;; (docstring + attr-map + the name's own) is attached to the def name symbol, - ;; which analyze-def reads and evaluates — so (meta #'f) reflects every source. - (if meta-map - `(def ~(with-meta fn-only-name meta-map) (fn ~(with-meta fn-only-name nil) ~@body)) - `(def ~fn-only-name (fn ~fn-only-name ~@body))))) + (let [body (if (and (seq body) (string? (first body))) (rest body) body) + body (if (and (seq body) (map? (first body)) (not (symbol? (first body)))) + (rest body) body)] + `(def ~fn-name (fn ~@body)))) -;; defn- marks the var :private (like Clojure). Jolt doesn't restrict access, but -;; ns-publics filters private vars out — a lib that introspects ns-publics (e.g. -;; honeysql's "all helpers have docstrings") sees only the public ones. -(defmacro defn- [fn-name & body] - `(defn ~(with-meta fn-name (assoc (if (meta fn-name) (meta fn-name) {}) :private true)) ~@body)) +;; Jolt doesn't enforce privacy, so defn- is just defn (matching how Clojure's own +;; defn- delegates to defn with :private metadata). +(defmacro defn- [fn-name & body] `(defn ~fn-name ~@body)) -;; A fresh jolt symbol inside a macro body (a bare (gensym) returns a host symbol +;; A fresh jolt symbol inside a macro body (a bare (gensym) returns a Janet symbol ;; the destructurer rejects). This defn compiles fine: by the time a tier triggers ;; the analyzer build the kernel is in place (the build is gated until then). (defn- fresh-sym [] (symbol (str (gensym)))) @@ -515,9 +331,9 @@ ;; Per binding group: :when wraps the inner form in (if test (list inner) []) so ;; mapcat drops it when false; :let wraps it in a let*; :while wraps the coll in ;; take-while. The last group with no modifiers is a plain map (no flatten needed). -;; Single body expr. The body uses only kernel/seed fns so it runs at -;; analyzer-build time. `fn` (not fn*) carries the binding so destructuring forms -;; work. +;; Faithful port of the prior Janet macro (single body expr). The body uses only +;; kernel/seed fns so it runs at analyzer-build time. `fn` (not fn*) carries the +;; binding so destructuring forms work. (defmacro for [bindings body] (let [scan (fn scan [bvec i bind coll mods] (if (and (< i (count bvec)) (keyword? (nth bvec i))) @@ -546,9 +362,7 @@ sub (wrap-mods (rest mods) inner)] (if (= (first m) :when) `(if ~(nth m 1) ~sub []) - ;; `let` (not let*) so a :let binding may itself - ;; destructure — (for [x xs :let [{:keys [y]} x]] …). - `(let ~(nth m 1) ~sub))))) + `(let* ~(nth m 1) ~sub))))) build (fn build [idx groups] (let [g (nth groups idx) my-bind (nth g 0) @@ -566,9 +380,9 @@ (build 0 (parse-groups bindings 0 [])) body))) -;; doseq runs body for side effects across the bindings, returning nil. Realizes -;; a `for` comprehension with count (for handles :when/:let/:while and multiple -;; bindings). +;; doseq runs body for side effects across the bindings, returning nil. Same +;; shortcut as the prior Janet macro: realize a `for` comprehension with count +;; (for handles :when/:let/:while and multiple bindings). (defmacro doseq [bindings & body] `(do (count (for ~bindings (do ~@body nil))) nil)) @@ -577,8 +391,6 @@ ;; name binds only in the taken branch (temp# tests the value); via `let` so the ;; binding form may itself destructure, matching Clojure. (defmacro when-let [bindings & body] - (when (not= 2 (count bindings)) - (throw (new IllegalArgumentException "when-let requires exactly 2 forms in binding vector"))) (let [form (bindings 0) tst (bindings 1)] `(let [temp# ~tst] (if temp# (let [~form temp#] ~@body) nil)))) @@ -586,7 +398,7 @@ ;; lazy-seq / lazy-cat live here (not 30-macros) because the seq/coll tiers use ;; them and compile-as-they-load: the macro must be registered before those tiers ;; or (lazy-seq …) compiles to a call of the macro-as-function and leaks its -;; expansion at runtime. They use only seed fns (make-lazy-seq/ +;; expansion at runtime (jolt-r81). They use only seed fns (make-lazy-seq/ ;; coll->cells/concat) + map, all available from the start. ;; lazy-seq defers its body: make-lazy-seq holds a thunk that realizes the body ;; to cells when forced. lazy-cat wraps each coll in a lazy-seq and concats. @@ -595,13 +407,3 @@ (defmacro lazy-cat [& colls] `(concat ~@(map (fn [c] `(lazy-seq ~c)) colls))) - -;; not= here (not 20-coll): the kernel tier uses it, and the kernel -;; bootstrap-compiles right after this file loads. Canonical Clojure arities. -(defn not= - ([x] false) - ([x y] (not (= x y))) - ([x y & more] (not (apply = x y more)))) - -;; unreduced here: the seq tier's reduce machinery unwraps with it. -(defn unreduced [x] (if (reduced? x) (deref x) x)) diff --git a/jolt-core/clojure/core/10-seq.clj b/jolt-core/clojure/core/10-seq.clj index 7a2ce6e..9418b07 100644 --- a/jolt-core/clojure/core/10-seq.clj +++ b/jolt-core/clojure/core/10-seq.clj @@ -1,27 +1,19 @@ ;; clojure.core — seq tier. Pure-Clojure leaf sequence fns on top of the kernel -;; tier (00-kernel) and the host primitives. Loaded after the kernel tier; in compile +;; tier (00-kernel) and the Janet seed. Loaded after the kernel tier; in compile ;; mode these self-host through the now-built analyzer (interpreted otherwise). ;; ;; Migration rule for adding fns here: the fn must (1) NOT be in -;; compiler/core-renames (that map emits core-X symbols directly), (2) have -;; no internal callers of its core-X binding, and (3) NOT be used by the +;; compiler/core-renames (that map emits core-X Janet symbols directly), (2) have +;; no internal Janet callers of its core-X binding, and (3) NOT be used by the ;; self-hosted compiler (jolt-core/jolt/*.clj). Compiler-facing structural fns go ;; in the kernel tier (00-kernel) instead — see its header. -;; Volatiles (this tier's transducers use them, and the analyzer ERRORS on -;; unresolved forward references). The constructor (volatile!) stays native; -;; these are pure over ref-put!/get. -(defn vreset! [vol newval] - (jolt.host/ref-put! vol :val newval) newval) -(defn vswap! [vol f & args] - (vreset! vol (apply f (get vol :val) args))) - (defn ffirst [coll] (first (first coll))) (defn nfirst [coll] (next (first coll))) (defn fnext [coll] (first (next coll))) (defn nnext [coll] (next (next coll))) -;; Canonical Clojure defs: pure first/next/loop/recur. +;; Canonical Clojure defs: pure first/next/loop/recur, no Janet realize-for-iteration. (defn last [s] (if (next s) (recur (next s)) (first s))) diff --git a/jolt-core/clojure/core/20-coll.clj b/jolt-core/clojure/core/20-coll.clj index 34a2262..ace99b4 100644 --- a/jolt-core/clojure/core/20-coll.clj +++ b/jolt-core/clojure/core/20-coll.clj @@ -4,109 +4,17 @@ ;; redefinable. Loaded after the seq tier; self-hosted in compile mode. ;; ;; Same migration rule as the seq tier (see 10-seq.clj): not in core-renames, no -;; internal callers, not used by the self-hosted compiler. +;; internal Janet callers, not used by the self-hosted compiler. -;; Tiny leaves first — fns below in this tier (and 25-sorted) use them. -(defn some? [x] (not (nil? x))) - -(defn identity [x] x) - -(defn constantly [x] (fn [& args] x)) - -;; neg? throws on non-numbers via <, as Clojure's Numbers.isNeg does. -(defn neg? [x] (< x 0)) - -;; even?/odd? stay host primitives: (filter even? ...) is idiomatic-hot and the -;; overlay versions cost an extra call layer per element (seq-pipe bench 4x). - -;; Variadic bit ops — canonical Clojure arities folding the binary host op -;; (__bit-* seams). 2-arg call sites still compile to the native op via -;; the backend's native-ops table, so the binary fast path is unchanged. -(defn bit-and - ([x y] (__bit-and x y)) - ([x y & more] (reduce __bit-and (__bit-and x y) more))) - -(defn bit-or - ([x y] (__bit-or x y)) - ([x y & more] (reduce __bit-or (__bit-or x y) more))) - -(defn bit-xor - ([x y] (__bit-xor x y)) - ([x y & more] (reduce __bit-xor (__bit-xor x y) more))) - -(defn bit-and-not - ([x y] (__bit-and-not x y)) - ([x y & more] (reduce __bit-and-not (__bit-and-not x y) more))) - -;; The printing family, over two host seams: __write (push a string to *out*) -;; and __pr-str1 (render ONE value readably). The renderer itself stays host — -;; it's representation-coupled (pvec/phm/phs/sorted internals) and shared with -;; the hot str. print uses str semantics (unreadable), pr/pr-str readable; -;; println/prn append the newline. Defined this early because printf and the -;; print-str family below call them. (print-method as a real multimethod is a -;; separate project.) -(defn pr-str [& xs] - (loop [out "" s (seq xs) first? true] - (if s - (recur (str out (if first? "" " ") (__pr-str1 (first s))) (next s) false) - out))) - -(defn pr [& xs] (__write (apply pr-str xs)) nil) - -(defn prn [& xs] (apply pr xs) (__write "\n") nil) - -;; print renders each arg non-readably (strings/chars unquoted) like str — except -;; nil, which prints as "nil" (str yields ""). Only the top-level arg needs the -;; guard; nil nested in a collection already renders as "nil" via the collection -;; printer. -;; print renders non-readably (__print1): a nested string is raw, unlike str/pr -;; which quote it. (print ["x"]) => [x], (str ["x"]) => ["x"]. -(defn print [& xs] - (__write (loop [out "" s (seq xs) first? true] - (if s - (let [x (first s) - r (__print1 x)] - (recur (str out (if first? "" " ") r) (next s) false)) - out))) - nil) - -(defn println [& xs] (apply print xs) (__write "\n") nil) - -;; Transient accumulation (canonical JVM form): assoc! into a native-backed -;; scratch table per element, then persistent! bulk-builds the HAMT once — -;; instead of a fresh persistent assoc (full trie-path rebuild) per element. -;; A transient map canonicalizes collection keys (it is canon-keyed, like a -;; PHM), so counting/grouping by collection value still works across map reps. +;; Base is (hash-map), not the {} literal: a literal map is a struct that doesn't +;; canonicalize collection keys across representations (a {:a 1} literal vs +;; (hash-map :a 1) key), whereas a PHM does — so counting/grouping by collection +;; value needs the PHM base (the prior Janet impl used make-phm for this reason). (defn frequencies [coll] - (persistent! - (reduce (fn [counts x] (assoc! counts x (inc (get counts x 0)))) (transient {}) coll))) + (reduce (fn [counts x] (assoc counts x (inc (get counts x 0)))) (hash-map) coll)) -;; Buckets are transient vectors, not persistent ones: the JVM form rebuilds the -;; bucket's persistent vector per element (conj (get ret k []) x), an O(log n) -;; trie path-rebuild + alloc per element — so a coarse grouping (few large -;; buckets) is bound on that conj, not the map build. Push onto a per-bucket -;; native array (O(1)) instead, then bulk-build the persistent map ONCE. -;; Distinct keys are recorded in a side vector so the buckets can be frozen in -;; place (no second map rebuild). A bucket's FIRST element is stored as a cheap -;; persistent [x]; only the second element promotes it to a transient — so an -;; all-singletons grouping pays no transient alloc, while any bucket that -;; actually grows rides the O(1) push. (defn group-by [f coll] - (let [tm (transient {}) - ks (reduce (fn [ks x] - (let [k (f x) - b (get tm k)] - (if (nil? b) - (do (assoc! tm k [x]) (conj! ks k)) - (if (vector? b) - (do (assoc! tm k (conj! (transient b) x)) ks) - (do (conj! b x) ks))))) - (transient []) coll)] - (reduce (fn [_ k] - (let [b (get tm k)] - (if (vector? b) nil (assoc! tm k (persistent! b))))) - nil (persistent! ks)) - (persistent! tm))) + (reduce (fn [ret x] (let [k (f x)] (assoc ret k (conj (get ret k []) x)))) (hash-map) coll)) (defn not-empty [coll] (if (or (nil? coll) (zero? (count coll))) nil coll)) @@ -155,43 +63,8 @@ (when-let [s (seq coll)] (or (pred (first s)) (recur pred (next s))))) -;; Reference arities: at least one predicate ((some-fn) is an arity error), and -;; the returned fn chains with or — a no-match result is the last predicate's -;; own falsy value (false stays false, not nil). -(defn some-fn - ([p] - (fn sp1 - ([] nil) - ([x] (p x)) - ([x y] (or (p x) (p y))) - ([x y z] (or (p x) (p y) (p z))) - ([x y z & args] (or (sp1 x y z) - (some p args))))) - ([p1 p2] - (fn sp2 - ([] nil) - ([x] (or (p1 x) (p2 x))) - ([x y] (or (p1 x) (p1 y) (p2 x) (p2 y))) - ([x y z] (or (p1 x) (p1 y) (p1 z) (p2 x) (p2 y) (p2 z))) - ([x y z & args] (or (sp2 x y z) - (some (fn [q] (or (p1 q) (p2 q))) args))))) - ([p1 p2 p3] - (fn sp3 - ([] nil) - ([x] (or (p1 x) (p2 x) (p3 x))) - ([x y] (or (p1 x) (p2 x) (p3 x) (p1 y) (p2 y) (p3 y))) - ([x y z] (or (p1 x) (p2 x) (p3 x) (p1 y) (p2 y) (p3 y) (p1 z) (p2 z) (p3 z))) - ([x y z & args] (or (sp3 x y z) - (some (fn [q] (or (p1 q) (p2 q) (p3 q))) args))))) - ([p1 p2 p3 & ps] - (let [ps (cons p1 (cons p2 (cons p3 ps)))] - (fn spn - ([] nil) - ([x] (some (fn [p] (p x)) ps)) - ([x y] (or (spn x) (spn y))) - ([x y z] (or (spn x) (spn y) (spn z))) - ([x y z & args] (or (spn x y z) - (some (fn [p] (some p args)) ps))))))) +(defn some-fn [& preds] + (fn [& xs] (some (fn [p] (some p xs)) preds))) (defn not-any? [pred coll] (not (some pred coll))) @@ -201,48 +74,29 @@ (defn split-with [pred coll] [(take-while pred coll) (drop-while pred coll)]) -(defn qualified-keyword? [x] (and (keyword? x) (some? (namespace x)))) -(defn simple-keyword? [x] (and (keyword? x) (nil? (namespace x)))) -(defn qualified-symbol? [x] (and (symbol? x) (some? (namespace x)))) -(defn simple-symbol? [x] (and (symbol? x) (nil? (namespace x)))) - (defn ident? [x] (or (keyword? x) (symbol? x))) (defn qualified-ident? [x] (or (qualified-symbol? x) (qualified-keyword? x))) (defn simple-ident? [x] (or (simple-symbol? x) (simple-keyword? x))) -;; Numeric-tower predicates over the Chez tower (jolt has exact ints, ratios, and -;; flonums). ratio? = exact non-integer; rational? = exact (int or ratio). Built on -;; the jolt.host tower tests so they lower to the same code the native shims did. -;; decimal?/integer?/float?/int?/double? stay native (bigdec-extended or on the -;; compiler emit/inference path) — see predicates.ss. -(defn ratio? [x] - (and (number? x) (jolt.host/exact? x) (jolt.host/rational-type? x) (not (integer? x)))) -(defn rational? [x] - (or (and (number? x) (jolt.host/exact? x)) (decimal? x))) -;; No first-class Class objects: class names are symbols the evaluator handles in -;; instance?/new positions, never values — so nothing is a class. -(defn class? [x] false) -;; list?: a list-marked cseq node or the empty list (). A lazy/vector-backed seq, -;; (rest list), (seq coll), (map …) are seqs but not lists. Not extended like -;; map?/set?/seq?, so it migrates cleanly. -(defn list? [x] (or (and (jolt.host/cseq? x) (jolt.host/cseq-list? x)) (jolt.host/empty-list? x))) +;; Jolt has no ratio or bigdecimal types, so these are constants / reduce to int?. +(defn ratio? [x] false) +(defn decimal? [x] false) +(defn rational? [x] (int? x)) (defn nat-int? [x] (and (int? x) (>= x 0))) (defn neg-int? [x] (and (int? x) (neg? x))) (defn pos-int? [x] (and (int? x) (pos? x))) (defn replicate [n x] (map (fn [_] x) (range n))) -;; Returns a seq (JVM does), nil when n<=0 or coll is empty. (defn take-last [n coll] (let [c (vec coll) len (count c)] - (when (pos? len) (seq (subvec c (max 0 (- len n))))))) + (when (pos? len) (subvec c (max 0 (- len n)))))) -;; The JVM definition: a lazy seq (() when empty), not a vector. (defn drop-last ([coll] (drop-last 1 coll)) - ([n coll] (map (fn [x _] x) coll (drop n coll)))) + ([n coll] (let [c (vec coll)] (subvec c 0 (max 0 (- (count c) n)))))) (defn distinct? ([x] true) @@ -256,12 +110,7 @@ true)) false))) -;; A vector input maps to a vector (eager); any other coll to a lazy seq — JVM -;; replace is type-preserving, not vector-always. -(defn replace [smap coll] - (if (vector? coll) - (mapv (fn [x] (get smap x x)) coll) - (map (fn [x] (get smap x x)) coll))) +(defn replace [smap coll] (mapv (fn [x] (get smap x x)) coll)) (defn nthnext [coll n] (loop [n n xs (seq coll)] @@ -269,14 +118,9 @@ (recur (dec n) (next xs)) xs))) -(defn bounded-count [n coll] - (if (counted? coll) - (count coll) - (loop [i 0 s (seq coll)] - (if (and s (< i n)) (recur (inc i) (next s)) i)))) +(defn bounded-count [n coll] (min n (count coll))) -;; the reducing fn returns proc's result, so a Reduced from proc short-circuits -(defn run! [proc coll] (reduce (fn [_ x] (proc x)) nil coll) nil) +(defn run! [proc coll] (reduce (fn [_ x] (proc x) nil) nil coll) nil) (defn completing ([f] (completing f identity)) @@ -304,253 +148,198 @@ (defn keyword-identical? [a b] (= a b)) -;; Clojure 1.9: true for ANY argument incl. nil (used as a spec predicate). -(defn any? [x] true) +(defn comparator [pred] + (fn [a b] (cond (pred a b) -1 (pred b a) 1 :else 0))) -;; printf: print (no newline) the formatted string to *out*. -(defn printf [fmt & args] (print (apply format fmt args))) +;; Lazy: the running accumulators, one at a time (matches Clojure). +(defn reductions + ([f coll] + (lazy-seq + (let [s (seq coll)] + (if s + (reductions f (first s) (rest s)) + (list (f)))))) + ([f init coll] + (cons init + (lazy-seq + (when-let [s (seq coll)] + (reductions f (f init (first s)) (rest s))))))) -;; bound?: every var has a root value. (jolt vars store the root in :root; -;; a nil-valued root reads as unbound — documented divergence.) -(defn bound? [& vars] - (every? (fn [v] (some? (get v :root))) vars)) +;; Lazy pre-order DFS (matches Clojure): node, then its children's walks spliced +;; via the (now lazy) mapcat. +(defn tree-seq [branch? children root] + (let [walk (fn walk [node] + (lazy-seq + (cons node + (when (branch? node) + (mapcat walk (children node))))))] + (walk root))) -;; Run f with a frame of dynamic bindings installed; restore on exit. -(defn with-bindings* [binding-map f & args] - (push-thread-bindings binding-map) - (try - (apply f args) - (finally (pop-thread-bindings)))) +;; Canonical flatten via tree-seq: the leaves (non-sequential nodes) in order. +;; Flattens lists too (sequential?), matching Clojure/CLJS. +(defn flatten [coll] + (filter (complement sequential?) (rest (tree-seq sequential? seq coll)))) -;; Capture the CURRENT thread bindings; the returned fn re-installs them -;; around every call (binding conveyance — Clojure's bound-fn*). -(defn bound-fn* [f] - (let [bs (get-thread-bindings)] - (fn [& args] (apply with-bindings* bs f args)))) +;; xml-seq: tree-seq over XML element trees. Elements are maps with :content. +(defn xml-seq [root] + (tree-seq (complement string?) (comp seq :content) root)) -(defn thread-bound? [& vars] - (every? (fn [v] (__thread-bound? v)) vars)) +;; Lazy interleave: round-robin one element from each coll until any exhausts. +(defn interleave + ([] ()) + ([c1] (lazy-seq c1)) + ([c1 c2] + (lazy-seq + (let [s1 (seq c1) s2 (seq c2)] + (when (and s1 s2) + (cons (first s1) + (cons (first s2) + (interleave (rest s1) (rest s2)))))))) + ([c1 c2 & cs] + (lazy-seq + (let [ss (map seq (list* c1 c2 cs))] + (when (every? identity ss) + (concat (map first ss) + (apply interleave (map rest ss)))))))) -(defn key [e] (if (map-entry? e) (nth e 0) (throw (ex-info "key requires a map entry" {})))) -(defn val [e] (if (map-entry? e) (nth e 1) (throw (ex-info "val requires a map entry" {})))) +;; No ratio type on Jolt, so rationalize is identity. +(defn rationalize [x] x) -;; --- Ad-hoc hierarchies (stage 3) — Clojure's canonical pure-map port. ----- -;; A hierarchy is {:parents {tag #{parents}} :ancestors {tag #{all}} -;; :descendants {tag #{all}}}. The 3-arity forms are PURE; the 1/2-arity forms -;; operate on the private global hierarchy atom. Multimethod dispatch -;; (evaluator defmulti-setup) calls isa? through the interned var. -;; -;; Ported from clojure.core with the reference's argument assertions and throw -;; contracts intact — bad shapes throw exactly where they do there (a non-map h -;; fails on the (parent-map tag) call, invalid tags fail the asserts). The class -;; arms answer through the host class graph (jolt.host/class-* seams). +;; trampoline: repeatedly calls f with args until a non-function result. -(defn make-hierarchy [] - {:parents {} :descendants {} :ancestors {}}) +;; rand-int: random integer in [0, n). Uses Janet math/random. -(def ^:private global-hierarchy (atom (make-hierarchy))) +;; Eager dedupe of consecutive equal elements (Jolt has no transducer arity yet). +(defn dedupe [coll] + (let [step (fn step [s prev] + (make-lazy-seq + (fn* [] + (let [s (seq s)] + (if s + (let [x (first s)] + (if (= x prev) + (coll->cells (step (rest s) prev)) + (coll->cells (cons x (step (rest s) x))))) + nil)))))] + (let [s (seq coll)] + (if s + (make-lazy-seq + (fn* [] (coll->cells (cons (first s) (step (rest s) (first s)))))) + ())))) -(defn- hier-assert [ok form] - (when-not ok (throw (new AssertionError (str "Assert failed: " form))))) +;; Internal helper for {:keys [...]} destructuring over a seq of k/v pairs: +;; builds a map from consecutive pairs, dropping a trailing unpaired element. +(defn seq-to-map-for-destructuring [s] + (if (sequential? s) + (loop [m {} xs (seq s)] + (if (and xs (next xs)) + (recur (assoc m (first xs) (second xs)) (next (next xs))) + m)) + s)) -;; a hierarchy tag naming a class — a class value, or the name string of a class -;; the host graph models (jolt classes are their name strings). -(defn- class-tag? [tag] (if (jolt.host/class-value? tag) true false)) +;; Phase 4 (jolt-1j0): host-coupled fns that are pure logic over existing core +;; primitives, so they need no new jolt.host surface. -(defn isa? - ([child parent] (isa? (deref global-hierarchy) child parent)) - ([h child parent] - (or (= child parent) - ;; JVM class assignability (Object root + modeled clojure.lang/java.* ancestry), - ;; so a class-keyed multimethod / (isa? (class x) C) dispatches like the JVM. - (jolt.host/class-isa? child parent) - (contains? (get (get h :ancestors) child #{}) parent) - ;; a hierarchy relationship established on one of a class's supers - (and (class-tag? child) - (some (fn [s] (contains? (get (get h :ancestors) s #{}) parent)) - (jolt.host/class-supers child))) - (and (vector? parent) (vector? child) - (= (count parent) (count child)) - (loop [ret true i 0] - (if (or (not ret) (= i (count parent))) - ret - (recur (isa? h (nth child i) (nth parent i)) (inc i)))))))) +;; vary-meta: f applied to obj's metadata (+ extra args), reattached. meta and +;; with-meta are the irreducible host primitives; vary-meta is just their compose. +(defn vary-meta [obj f & args] + (with-meta obj (apply f (meta obj) args))) -(defn parents - ([tag] (parents (deref global-hierarchy) tag)) - ([h tag] (not-empty - (let [tp (get (get h :parents) tag)] - (if (class-tag? tag) - (into (set (jolt.host/class-bases tag)) tp) - tp))))) +;; namespace-munge: Clojure namespace name -> legal Java package name (- -> _). +(defn namespace-munge [s] + (apply str (map (fn [c] (if (= c \-) \_ c)) (seq (str s))))) -(defn ancestors - ([tag] (ancestors (deref global-hierarchy) tag)) - ([h tag] (not-empty - (let [ta (get (get h :ancestors) tag)] - (if (class-tag? tag) - ;; the class's own ancestry plus hierarchy relationships derived - ;; on the class or any of its supers - (let [superclasses (set (jolt.host/class-supers tag))] - (reduce into superclasses - (cons ta (map (fn [s] (get (get h :ancestors) s)) - superclasses)))) - ta))))) +;; reduce-kv over a map (k v) or vector (index v). Both branches go through reduce, +;; so reduced short-circuits — and the vector path indexes correctly. (The prior +;; Janet version saw a pvec as a table and folded over its internal keys; it also +;; ignored reduced.) nil folds to init, matching Clojure. +(defn reduce-kv [f init coll] + (cond + (vector? coll) (reduce (fn [acc i] (f acc i (nth coll i))) init (range (count coll))) + (map? coll) (reduce (fn [acc k] (f acc k (get coll k))) init (keys coll)) + (nil? coll) init + :else (throw (str "reduce-kv not supported on: " coll)))) -(defn descendants - ([tag] (descendants (deref global-hierarchy) tag)) - ([h tag] (if (class-tag? tag) - (throw (new UnsupportedOperationException "Can't get descendants of classes")) - (not-empty (get (get h :descendants) tag))))) +;; ex-info accessors. The Janet constructor (ex-info) stays — it builds the tagged +;; value and wires into throw — but the value exposes :jolt/type/:message/:data/ +;; :cause via get, so the accessors are pure over get. A thrown non-ex-info arrives +;; wrapped as {:jolt/type :jolt/exception :value v}; unwrap that first. +(defn- ex-info-val? [x] (= (get x :jolt/type) :jolt/ex-info)) +(defn- ex-unwrap [e] + (if (= (get e :jolt/type) :jolt/exception) (get e :value) e)) +(defn ex-data [e] + (let [e (ex-unwrap e)] (if (ex-info-val? e) (get e :data) nil))) +(defn ex-message [e] + (let [e (ex-unwrap e)] + (cond (ex-info-val? e) (get e :message) + (string? e) e + :else nil))) +(defn ex-cause [e] + (let [e (ex-unwrap e)] (if (ex-info-val? e) (get e :cause) nil))) -(defn derive - ([tag parent] - (hier-assert (namespace parent) "(namespace parent)") - (hier-assert (or (class-tag? tag) - (and (or (keyword? tag) (symbol? tag)) (namespace tag))) - "(or (class? tag) (and (instance? clojure.lang.Named tag) (namespace tag)))") - (swap! global-hierarchy derive tag parent) nil) - ([h tag parent] - (hier-assert (not= tag parent) "(not= tag parent)") - (hier-assert (or (class-tag? tag) (keyword? tag) (symbol? tag)) - "(or (class? tag) (instance? clojure.lang.Named tag))") - (hier-assert (or (keyword? parent) (symbol? parent)) - "(instance? clojure.lang.Named parent)") - (let [tp (get h :parents) - td (get h :descendants) - ta (get h :ancestors) - tf (fn [m source sources target targets] - (reduce (fn [ret k] - (assoc ret k - (reduce conj (get targets k #{}) - (cons target (targets target))))) - m (cons source (sources source))))] - (or - (when-not (contains? (tp tag) parent) - (when (contains? (ta tag) parent) - (throw (new Exception (str tag " already has " parent " as ancestor")))) - (when (contains? (ta parent) tag) - (throw (new Exception (str "Cyclic derivation: " parent " has " tag " as ancestor")))) - {:parents (assoc tp tag (conj (get tp tag #{}) parent)) - :ancestors (tf ta tag td parent ta) - :descendants (tf td parent ta tag td)}) - h)))) - -(defn underive - ([tag parent] (swap! global-hierarchy underive tag parent) nil) - ([h tag parent] - (let [parent-map (get h :parents) - childs-parents (if (parent-map tag) - (disj (parent-map tag) parent) - #{}) - new-parents (if (not-empty childs-parents) - (assoc parent-map tag childs-parents) - (dissoc parent-map tag)) - deriv-seq (mapcat (fn [e] (cons (key e) (interpose (key e) (val e)))) - (seq new-parents))] - (if (contains? (parent-map tag) parent) - (reduce (fn [p [t pr]] (derive p t pr)) - (make-hierarchy) (partition 2 deriv-seq)) - h)))) - -;; --- pure-over-core leaves expressed off the host primitives ----------------- - -;; Representation predicates over the overlay's own predicates. -(defn sequential? [x] (or (vector? x) (seq? x))) -(defn associative? [x] (or (map? x) (vector? x))) -(defn counted? [x] - ;; a String is not Counted on the JVM (count works via CharSequence, not O(1)) - (or (vector? x) (map? x) (set? x) (list? x))) -(defn indexed? [x] (vector? x)) -;; sorted? is defined by the next tier (25-sorted) — declared here so this -;; tier compiles (forward references are analysis errors). -(declare sorted?) - -(defn reversible? [x] (or (vector? x) (sorted? x))) -(defn seqable? [x] - (if (or (nil? x) (coll? x) (string? x) (jolt.host/array-value? x)) true false)) - -(defn boolean? [x] (or (true? x) (false? x))) -(defn double? [x] (and (number? x) (not (integer? x)))) -(defn float? [x] (double? x)) -(defn infinite? [x] (and (number? x) (or (= x ##Inf) (= x ##-Inf)))) - -;; qualified-/simple- keyword?/symbol? moved above qualified-ident? (forward -;; references are analysis errors). - - -;; realized?: defined on the pending types only (delay/lazy-seq/future read -;; Tagged-value predicates. The constructors (atom/volatile!/...) are host -;; primitives, but every tagged value carries its kind under :jolt/type (records -;; under :jolt/deftype), reachable via get — which is nil on non-tables — so the -;; predicates are pure over get. +;; Tagged-value predicates. The constructors (atom/volatile!/...) stay in Janet, +;; but every tagged value carries its kind under :jolt/type (records under +;; :jolt/deftype), reachable via get — which is nil on non-tables — so the +;; predicates are pure over get and move out of the seed. (defn atom? [x] (= (get x :jolt/type) :jolt/atom)) (defn volatile? [x] (= (get x :jolt/type) :jolt/volatile)) (defn reader-conditional? [x] (= (get x :jolt/type) :jolt/reader-conditional)) (defn tagged-literal? [x] (= (get x :jolt/type) :jolt/tagged-literal)) (defn record? [x] (some? (get x :jolt/deftype))) -(defn uuid? [x] (= (get x :jolt/type) :jolt/uuid)) -(defn inst? [x] (= (get x :jolt/type) :jolt/inst)) -(defn char? [x] (= (get x :jolt/type) :jolt/char)) +;; Jolt has no chunked seqs (Phase 5 territory), so this is always false. +(defn chunked-seq? [x] false) -;; their realization slot; promises/atoms always-realized), error otherwise. -(defn realized? [x] - (cond - (delay? x) (boolean (get x :realized)) - (future? x) (boolean (get x :cached)) - (= :jolt/lazy-seq (get x :jolt/type)) (boolean (get x :realized)) - (atom? x) true - ;; name the class, never the value — an error message must not render an - ;; arbitrary (possibly infinite) argument. - :else (throw (str "realized? not supported on: " (class x))))) +;; Atom peripheral operations. atom/swap!/reset!/deref stay native — the compiler +;; depends on them and they're hot. swap-vals!/reset-vals!/compare-and-set! compose +;; the native ops (which already validate and notify watches); get-validator reads a +;; slot; add-watch/remove-watch/set-validator! mutate the atom (or its watches +;; sub-table) through the one host primitive jolt.host/ref-put! — the minimal +;; mutation kernel the overlay can't express over core fns (a nil value removes the +;; key). compare-and-set! compares by value, matching the prior Janet behavior. +(defn swap-vals! [a f & args] + (let [old (deref a)] [old (apply swap! a f args)])) +(defn reset-vals! [a newval] + (let [old (deref a)] (reset! a newval) [old newval])) +(defn compare-and-set! [a oldval newval] + (if (= oldval (deref a)) (do (reset! a newval) true) false)) +(defn get-validator [a] (get a :validator)) +(defn add-watch [a key f] + (jolt.host/ref-put! (get a :watches) key f) a) +(defn remove-watch [a key] + (jolt.host/ref-put! (get a :watches) key nil) a) +(defn set-validator! [a f] + (jolt.host/ref-put! a :validator f) nil) -(defn force [x] (if (delay? x) (deref x) x)) +;; Volatiles. The constructor (volatile!) stays native — it builds the mutable box — +;; but vreset! sets the box's slot through ref-put! and vswap! is pure over it + get. +(defn vreset! [vol newval] + (jolt.host/ref-put! vol :val newval) newval) +(defn vswap! [vol f & args] + (vreset! vol (apply f (get vol :val) args))) -;; pop: vectors drop the last element, lists/seqs the first; empty pops throw. -(defn pop [coll] - (cond - (nil? coll) nil - (vector? coll) - (if (zero? (count coll)) (throw "Can't pop empty vector") - (subvec coll 0 (dec (count coll)))) - (seq? coll) - (if (nil? (seq coll)) (throw "Can't pop empty list") - (rest coll)) - :else (throw (str "pop not supported on: " coll)))) +;; Future status predicates — pure reads of the future's :cached/:cancelled slots. +;; future? stays native (deref/future-cancel/realized? call it); future-call and +;; future-cancel stay native too (OS threads). +(defn future-done? [x] + (if (future? x) (boolean (get x :cached)) (throw "future-done? requires a future"))) +(defn future-cancelled? [x] + (and (future? x) (boolean (get x :cancelled)))) -;; doall/dorun: realization boundaries. dorun walks (optionally at most n -;; steps); doall walks then returns coll. -(defn dorun - ([coll] - (loop [s (seq coll)] - (when s (recur (next s))))) - ([n coll] - (loop [n n s (seq coll)] - (when (and s (pos? n)) (recur (dec n) (next s)))))) - -(defn doall - ([coll] (dorun coll) coll) - ([n coll] (dorun n coll) coll)) - -;; spread: (spread [1 2 [3 4]]) => (1 2 3 4) — list*'s variadic helper -;; (private in Clojure). -(defn- spread [arglist] - (cond - (nil? arglist) nil - (nil? (next arglist)) (seq (first arglist)) - :else (cons (first arglist) (spread (next arglist))))) - -;; list*: cons the leading args onto the final seq argument. -(defn list* - ([args] (seq args)) - ([a args] (cons a args)) - ([a b args] (cons a (cons b args))) - ([a b c args] (cons a (cons b (cons c args)))) - ([a b c d & more] - (cons a (cons b (cons c (cons d (spread more))))))) - -;; print-str family: print/println/prn into a captured *out*. -(defn print-str [& xs] (__with-out-str (fn* [] (apply print xs)))) -(defn println-str [& xs] (__with-out-str (fn* [] (apply println xs)))) -(defn prn-str [& xs] (__with-out-str (fn* [] (apply prn xs)))) +;; ns-name: a namespace object's :name as a symbol. Pure over get + symbol. +(defn ns-name [ns] + (let [nm (get ns :name)] (if nm (symbol (str nm)) nil))) +;; Java-array element access. Jolt arrays are mutable backing arrays; aget/alength +;; read them (nth/count) and aset writes a slot through ref-put!. Both handle the +;; multi-dimensional form (aget a i j ... / aset a i j ... v) by walking. The array +;; constructors (object-array/make-array/to-array/...) stay native — they build the +;; mutable backing. +(defn aget [arr & idxs] + (reduce (fn [v i] (nth v i)) arr idxs)) +(defn alength [arr] (count arr)) +(defn aset [arr & idxs+val] + (let [n (count idxs+val) + val (nth idxs+val (dec n)) + target (reduce (fn [t k] (nth t k)) arr (take (- n 2) idxs+val))] + (jolt.host/ref-put! target (nth idxs+val (- n 2)) val) + val)) diff --git a/jolt-core/clojure/core/21-coll.clj b/jolt-core/clojure/core/21-coll.clj deleted file mode 100644 index 3a12c8e..0000000 --- a/jolt-core/clojure/core/21-coll.clj +++ /dev/null @@ -1,379 +0,0 @@ -;; clojure.core — collection tier, part 2 (rand/sort host seams, the -;; clojure.test runner, fn combinators). Continues 20-coll.clj; same constraints -;; (pure, eager, no macros), loaded in the 20 slot before 25-sorted. - -;; --- leaves over the rand / sort host seams ---------------------------------- - -;; Canonical truncation toward zero via int (the kernel fn floored, which is -;; wrong for a negative n). -(defn rand-int [n] (int (rand n))) - -;; Pure-functional Fisher-Yates over vector assoc; returns a vector, as in -;; Clojure. Collections only — a string is seqable but not shuffleable, as on -;; the JVM (Collections/shuffle wants a Collection). -(defn shuffle [coll] - ;; Collections/shuffle wants a java.util.Collection — a map is not one - (when (or (not (coll? coll)) (map? coll)) - (throw (ex-info (str "shuffle requires a collection, got: " coll) {}))) - (loop [v (vec coll) i (dec (count v))] - (if (pos? i) - (let [j (rand-int (inc i)) - t (nth v i)] - (recur (assoc (assoc v i (nth v j)) j t) (dec i))) - v))) - -;; Canonical sort-by: the default comparator is compare (so nil sorts first, -;; like Clojure — the kernel fn used host ordering, which put nil last); the -;; comparator compares KEYS and may be 3-way or a boolean predicate (the host -;; sort seam normalizes). -(defn sort-by - ([keyfn coll] (sort-by keyfn compare coll)) - ([keyfn comp coll] - ;; a collection is never a Comparator (the JVM cast would fail); catching it - ;; here beats silently "sorting" through coll-as-fn lookups - (when (coll? comp) - (throw (new ClassCastException (str (class comp) " cannot be cast to java.util.Comparator")))) - (sort (fn [x y] (comp (keyfn x) (keyfn y))) coll))) - -;; parse-uuid: nil unless s is a canonical 8-4-4-4-12 hex UUID string; throws -;; on a non-string (Clojure 1.11). __make-uuid is the host constructor for the -;; tagged value (overlay source can't write :jolt/type map literals — the -;; reader treats them as tagged forms). -(defn parse-uuid [s] - (if (string? s) - (when (re-matches - #"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}" s) - (__make-uuid s)) - (throw (str "parse-uuid requires a string, got: " s)))) - -;; Version-4 UUID (RFC 4122): zero-padded hex groups 8-4-4-4-12, version -;; nibble 4, variant 8-b — built over rand-int and validated by parse-uuid. -(defn random-uuid [] - (let [hx4 (fn [] (format "%04x" (rand-int 0x10000))) - hx3 (fn [] (format "%03x" (rand-int 0x1000)))] - (parse-uuid (str (hx4) (hx4) "-" (hx4) "-4" (hx3) - "-" (format "%x" (+ 8 (rand-int 4))) (hx3) - "-" (hx4) (hx4) (hx4))))) - -;; The char escape/name tables, as char-keyed maps (Clojure's shape). -(def ^:private char-escape-strings - {\newline "\\n" \tab "\\t" \return "\\r" \formfeed "\\f" - \backspace "\\b" \" "\\\"" \\ "\\\\"}) -(defn char-escape-string [c] (get char-escape-strings c)) - -(def ^:private char-name-strings - {\newline "newline" \tab "tab" \return "return" \formfeed "formfeed" - \backspace "backspace" \space "space"}) -(defn char-name-string [c] (get char-name-strings c)) - -;; Random selection over the host rand primitives — the reference shape: -;; nth directly (nil returns nil via RT.nth; a set throws like the JVM). -(defn rand-nth [coll] - (nth coll (rand-int (count coll)))) - -(defn random-sample - ([prob] (filter (fn [_] (< (rand) prob)))) - ([prob coll] (filter (fn [_] (< (rand) prob)) coll))) - -(defn comparator [pred] - (fn [a b] (cond (pred a b) -1 (pred b a) 1 :else 0))) - -;; Lazy: the running accumulators, one at a time (matches Clojure). -(defn reductions - ([f coll] - (lazy-seq - (let [s (seq coll)] - (if s - (reductions f (first s) (rest s)) - (list (f)))))) - ([f init coll] - (cons init - (lazy-seq - (when-let [s (seq coll)] - (reductions f (f init (first s)) (rest s))))))) - -;; Lazy pre-order DFS (matches Clojure): node, then its children's walks spliced -;; via the (now lazy) mapcat. -(defn tree-seq [branch? children root] - (let [walk (fn walk [node] - (lazy-seq - (cons node - (when (branch? node) - (mapcat walk (children node))))))] - (walk root))) - -;; file-seq: the tree of paths under root (root included), directories walked -;; via the host dir primitives. Paths (strings), not File objects. (Lives below -;; tree-seq: forward references are analysis errors.) -(defn file-seq [root] - (if (__file? root) - ;; java.io.File tree: walk via the File method surface so leaves are File - ;; values callers can invoke .isFile/.getName/slurp on. - (tree-seq (fn [f] (.isDirectory f)) (fn [f] (seq (.listFiles f))) root) - (tree-seq __dir? __list-dir root))) - -;; Canonical flatten via tree-seq: the leaves (non-sequential nodes) in order. -;; Flattens lists too (sequential?), matching Clojure/CLJS. -(defn flatten [coll] - (filter (complement sequential?) (rest (tree-seq sequential? seq coll)))) - -;; xml-seq: tree-seq over XML element trees. Elements are maps with :content. -(defn xml-seq [root] - (tree-seq (complement string?) (comp seq :content) root)) - -;; Lazy interleave: round-robin one element from each coll until any exhausts. -(defn interleave - ([] ()) - ([c1] (lazy-seq c1)) - ([c1 c2] - (lazy-seq - (let [s1 (seq c1) s2 (seq c2)] - (when (and s1 s2) - (cons (first s1) - (cons (first s2) - (interleave (rest s1) (rest s2)))))))) - ([c1 c2 & cs] - (lazy-seq - (let [ss (map seq (list* c1 c2 cs))] - (when (every? identity ss) - (concat (map first ss) - (apply interleave (map rest ss)))))))) - -;; rationalize is host-native (java/bigdec.ss): a double routes through its -;; shortest decimal print like BigDecimal.valueOf, so (rationalize 1.1) is 11/10. - -;; 0-arg: a stateful transducer (tracks [seen? prev] in a volatile, so no sentinel -;; value is needed). 1-arg: eager dedupe of consecutive equal elements. -(defn dedupe - ([] - (fn [rf] - (let [pv (volatile! [false nil])] - (fn - ([] (rf)) - ([result] (rf result)) - ([result input] - (let [[seen prior] @pv] - (vreset! pv [true input]) - (if (and seen (= prior input)) result (rf result input)))))))) - ([coll] - (let [step (fn step [s prev] - (make-lazy-seq - (fn* [] - (let [s (seq s)] - (if s - (let [x (first s)] - (if (= x prev) - (coll->cells (step (rest s) prev)) - (coll->cells (cons x (step (rest s) x))))) - nil)))))] - ;; defer (seq coll) into the lazy-seq so a side-effecting source is not - ;; realized at construction (dedupe is lazy, like Clojure's). - (make-lazy-seq - (fn* [] - (let [s (seq coll)] - (if s - (coll->cells (cons (first s) (step (rest s) (first s)))) - nil))))))) - -;; Internal helper for {:keys [...]} destructuring over a seq of k/v pairs — -;; canonical Clojure 1.11 shape (core.clj seq-to-map-for-destructuring): -;; even pairs build a map (later keys win, as createAsIfByAssoc), a SINGLE -;; element is returned as-is (the trailing-map calling convention), and an -;; unpaired key past pairs throws. -(defn seq-to-map-for-destructuring [s] - (if (next s) - (loop [m {} xs (seq s)] - (if xs - (if (next xs) - (recur (assoc m (first xs) (second xs)) (nnext xs)) - (throw (str "No value supplied for key: " (first xs)))) - m)) - (if (seq s) (first s) {}))) - -;; Host-coupled fns that are pure logic over existing core primitives, so they -;; need no new jolt.host surface. - -;; vary-meta: f applied to obj's metadata (+ extra args), reattached. meta and -;; with-meta are the irreducible host primitives; vary-meta is just their compose. -(defn vary-meta [obj f & args] - (with-meta obj (apply f (meta obj) args))) - -;; namespace-munge: Clojure namespace name -> legal Java package name (- -> _). -(defn namespace-munge [s] - (apply str (map (fn [c] (if (= c \-) \_ c)) (seq (str s))))) - -;; reduce-kv over a map (k v) or vector (index v). Both branches go through reduce, -;; so reduced short-circuits — and the vector path indexes correctly. nil folds -;; to init, matching Clojure. -(defn reduce-kv [f init coll] - (cond - (vector? coll) (reduce (fn [acc i] (f acc i (nth coll i))) init (range (count coll))) - (map? coll) (reduce (fn [acc k] (f acc k (get coll k))) init (keys coll)) - (nil? coll) init - :else (throw (str "reduce-kv not supported on: " coll)))) - -;; ex-info accessors. The constructor (ex-info) stays native — it builds the tagged -;; value and wires into throw — but the value exposes :jolt/type/:message/:data/ -;; :cause via get, so the accessors are pure over get. A thrown non-ex-info arrives -;; wrapped as {:jolt/type :jolt/exception :value v}; unwrap that first. -(defn- ex-info-val? [x] (= (get x :jolt/type) :jolt/ex-info)) -(defn- ex-unwrap [e] - (if (= (get e :jolt/type) :jolt/exception) (get e :value) e)) -(defn ex-data [e] - (let [e (ex-unwrap e)] (if (ex-info-val? e) (get e :data) nil))) -(defn ex-message [e] - (let [e (ex-unwrap e)] - (cond (ex-info-val? e) (get e :message) - :else nil))) -(defn ex-cause [e] - (let [e (ex-unwrap e)] (if (ex-info-val? e) (get e :cause) nil))) - -;; inst-ms: epoch milliseconds of an instant; throws on a non-inst (Clojure -;; protocol behavior). -(defn inst-ms [x] - (if (inst? x) (get x :ms) (throw (str "inst-ms requires an inst, got: " x)))) - -;; Clojure 1.11 map transformers. An empty-map base keeps insertion order; -;; transformed keys canonicalize via assoc (collisions: last entry in seq order -;; wins, matching the reference). -(defn update-keys [m f] - (reduce-kv (fn [acc k v] (assoc acc (f k) v)) {} m)) - -(defn update-vals [m f] - (reduce-kv (fn [acc k v] (assoc acc k (f v))) {} m)) - -;; Vector-returning partition variants (1.11): lazy seqs OF vectors. -(defn partitionv - ([n coll] (map vec (partition n coll))) - ([n step coll] (map vec (partition n step coll))) - ([n step pad coll] (map vec (partition n step pad coll)))) - -;; partition-all is a lazy-tier fn (40-lazy) — declared so partitionv-all -;; compiles; bound by the time anything calls it. -(declare partition-all) - -(defn partitionv-all - ([n coll] (map vec (partition-all n coll))) - ([n step coll] (map vec (partition-all n step coll)))) - -;; First part a vector, rest a seq — matching the reference implementation. -(defn splitv-at [n coll] - [(vec (take n coll)) (drop n coll)]) - -;; with-redefs-fn: temporarily set each var's root to the mapped value, run -;; the thunk, restore the saved roots even on throw. The with-redefs macro -;; (30-macros) builds the {var val} map from names. -(defn with-redefs-fn [binding-map func] - (let [vars (vec (keys binding-map)) - saved (mapv var-get vars)] - (doseq [v vars] (var-set v (get binding-map v))) - (try - (func) - (finally - ;; loop/recur, not dotimes: dotimes is a 30-macros macro and this tier - ;; compiles before it exists (a forward ref would resolve to the macro - ;; fn at runtime and mis-apply it). - (loop [i 0] - (when (< i (count vars)) - (var-set (nth vars i) (nth saved i)) - (recur (inc i)))))))) -;; A vector's seq IS a real chunked-seq (chunk-first hands out a 32-element block). -;; This is only a placeholder so references compile during overlay load; the host -;; rebinds chunked-seq? to na-chunked-seq? in post-prelude.ss, which returns true -;; for a vector seq and false otherwise. -(defn chunked-seq? [x] false) - -;; Atom peripheral operations. atom/swap!/reset!/deref stay native — the compiler -;; depends on them and they're hot. swap-vals!/reset-vals!/compare-and-set! compose -;; the native ops (which already validate and notify watches); get-validator reads a -;; slot; add-watch/remove-watch/set-validator! mutate the atom (or its watches -;; sub-table) through the one host primitive jolt.host/ref-put! — the minimal -;; mutation kernel the overlay can't express over core fns (a nil value removes the -;; key). compare-and-set! compares by value. -(defn swap-vals! [a f & args] - (let [old (deref a)] [old (apply swap! a f args)])) -(defn reset-vals! [a newval] - (let [old (deref a)] (reset! a newval) [old newval])) -(defn compare-and-set! [a oldval newval] - (if (= oldval (deref a)) (do (reset! a newval) true) false)) -(defn get-validator [a] (get a :validator)) -(defn add-watch [a key f] - (jolt.host/ref-put! (get a :watches) key f) a) -(defn remove-watch [a key] - (jolt.host/ref-put! (get a :watches) key nil) a) -(defn set-validator! [a f] - (jolt.host/ref-put! a :validator f) nil) - -;; vreset!/vswap! live in the seq tier (10-seq.clj): its transducers use them. - -;; Future status predicates — pure reads of the future's :cached/:cancelled slots. -;; future? stays native (deref/future-cancel/realized? call it); future-call and -;; future-cancel stay native too (OS threads). -(defn future-done? [x] - (if (future? x) (boolean (get x :cached)) (throw "future-done? requires a future"))) -(defn future-cancelled? [x] - (and (future? x) (boolean (get x :cancelled)))) - -;; ns-name: a namespace object's :name as a symbol. Pure over get + symbol. -(defn ns-name [ns] - (let [nm (get ns :name)] (if nm (symbol (str nm)) nil))) - -;; Java-array element access. Jolt arrays are mutable backing arrays; aget/alength -;; read them (nth/count) and aset writes a slot through ref-put!. Both handle the -;; multi-dimensional form (aget a i j ... / aset a i j ... v) by walking. The array -;; constructors (object-array/make-array/to-array/...) stay native — they build the -;; mutable backing. -(defn aget [arr & idxs] - (reduce (fn [v i] (nth v i)) arr idxs)) -(defn alength [arr] (count arr)) -(defn aset [arr & idxs+val] - (let [n (count idxs+val) - val (nth idxs+val (dec n)) - target (reduce (fn [t k] (nth t k)) arr (take (- n 2) idxs+val))] - (jolt.host/ref-put! target (nth idxs+val (- n 2)) val) - val)) - -;; --- fn combinators + host-free stubs ---------------------------------------- - -(defn complement - "Takes a fn f and returns a fn that takes the same arguments as f, has the - same effects, if any, and returns the opposite truth value." - [f] - (fn [& args] (not (apply f args)))) - -;; Canonical Clojure fnil: patches only the FIRST 1-3 arguments. -(defn fnil - ([f x] - (fn [a & args] (apply f (if (nil? a) x a) args))) - ([f x y] - (fn [a b & args] (apply f (if (nil? a) x a) (if (nil? b) y b) args))) - ([f x y z] - (fn [a b c & args] - (apply f (if (nil? a) x a) (if (nil? b) y b) (if (nil? c) z c) args)))) - -(defn clojure-version [] "1.11.0-jolt") - -;; bigdec is a host fn (host/chez/java/bigdec.ss) — a real BigDecimal value type. -;; numerator/denominator are host natives (converters.ss) over Chez's exact -;; rationals; a non-ratio is the Ratio cast failure. - -;; jolt has no reflection, but a few common JVM interfaces carry a modeled -;; ancestry (jolt.host/class-supers) so reflective checks like -;; (ancestors (class f)) answer like the JVM. -(defn supers [x] - (let [s (jolt.host/class-supers x)] - (if s (set s) #{}))) - -;; Like Clojure's munge: rewrite dashes to underscores, preserving the argument's -;; type — a symbol munges to a symbol, anything else to a string. (jolt only -;; rewrites dashes, not the full Compiler CHAR_MAP.) -(defn munge [s] - (let [m (str-replace-all "-" "_" (str s))] - (if (symbol? s) (symbol m) m))) - -(defn test - "Calls the :test fn from v's metadata; :ok if it runs, :no-test if absent." - [v] - (let [t (:test (meta v))] - (if t (do (t) :ok) :no-test))) - diff --git a/jolt-core/clojure/core/22-coll.clj b/jolt-core/clojure/core/22-coll.clj deleted file mode 100644 index 873dcfa..0000000 --- a/jolt-core/clojure/core/22-coll.clj +++ /dev/null @@ -1,377 +0,0 @@ -;; clojure.core — collection tier, part 3 (canonical Clojure ports: key/val/find, -;; merge-with, memoize, group-by, frequencies, transduce/into/eduction, and the -;; JVM-shape stubs). Continues 21-coll.clj; same constraints. - -;; --- canonical Clojure ports ------------------------------------------------- -;; key/val/find first — merge-with and memoize below use them. - -;; Strict, as in Clojure: an entry is what (seq m) yields (a host tuple), NOT -;; a plain vector — (key [1 2]) throws. -;; key/val moved above the hierarchies section (underive uses them). - -;; find was previously missing from jolt entirely. Presence (contains?), not -;; value, decides — so (find {:a nil} :a) is [:a nil]. Works on vectors by -;; index. The result must be a REAL entry (key/val are strict), so it is -;; minted as the first entry of a one-entry map — nil values survive (the -;; map builder switches to a phm when nil is involved). -(defn find [m k] - (when (contains? m k) (first {k (get m k)}))) - -;; some? lives in the top leaf block now (forward refs are errors). -(defn true? [x] (= true x)) -(defn false? [x] (= false x)) - -;; Presence-preserving and order-preserving: a key with a nil value is kept, and -;; the result follows keyseq order (an empty-map base keeps nil values and -;; canonicalizes collection keys). -(defn select-keys [map keyseq] - (reduce (fn [m k] (if (contains? map k) (assoc m k (get map k)) m)) - {} keyseq)) - -(defn zipmap [keys vals] - (loop [m {} ks (seq keys) vs (seq vals)] - (if (and ks vs) - (recur (assoc m (first ks) (first vs)) (next ks) (next vs)) - m))) - -;; Structmaps (legacy). A struct basis is the ordered vector of slot keys; a -;; struct map is a plain map carrying every basis key (nil when unset), in basis -;; order, so it looks up and compares like any other map. -(defn create-struct [& keys] (vec keys)) - -(defn struct-map [basis & inits] - (let [base (loop [m {} ks (seq basis)] - (if ks (recur (assoc m (first ks) nil) (next ks)) m))] - (loop [m base kvs (seq inits)] - (if kvs - (recur (assoc m (first kvs) (first (next kvs))) (next (next kvs))) - m)))) - -(defn struct [basis & vals] - (loop [m (struct-map basis) ks (seq basis) vs (seq vals)] - (if (and ks vs) - (recur (assoc m (first ks) (first vs)) (next ks) (next vs)) - m))) - -(defn accessor [basis key] - (fn [m] (get m key))) - -;; conj semantics per entry arg (a map merges, a [k v] pair adds); nil args are -;; no-ops; all-nil (or no args) is nil. -(defn merge [& maps] - (when (some identity maps) - (reduce (fn [acc m] (if (nil? m) acc (conj (or acc {}) m))) - maps))) - -(defn merge-with [f & maps] - (when (some identity maps) - (let [merge-entry (fn [m e] - (let [k (key e) v (val e)] - ;; presence — not nil-of-value — decides combination - (if (contains? m k) - (assoc m k (f (get m k) v)) - (assoc m k v)))) - merge2 (fn [m1 m2] - (reduce merge-entry (or m1 {}) (seq m2)))] - (reduce merge2 maps)))) - -(defn get-in - ([m ks] (reduce get m ks)) - ([m ks not-found] - ;; a fresh table is its own identity — a present-but-nil step is - ;; distinguished from a missing one - (let [sentinel (hash-map)] - (loop [m m ks (seq ks)] - (if ks - (let [nxt (get m (first ks) sentinel)] - (if (identical? sentinel nxt) - not-found - (recur nxt (next ks)))) - m))))) - -(defn req! - "Returns the value mapped to key k in map m, like `get`, but throws - IllegalArgumentException when k is not present. Unlike `get`, does not nil-pun: - a key present with a nil value returns nil, an absent key throws. The primitive - behind checked-keys destructuring (:keys! / :syms! / :strs!)." - {:added "1.13"} - [m k] - ;; a fresh map is its own identity, so a present-but-nil value is distinguished - ;; from an absent key (same trick as get-in's sentinel). - (let [sentinel (hash-map) - v (get m k sentinel)] - (if (identical? sentinel v) - (throw (new IllegalArgumentException (str "Expected key: " k))) - v))) - -;; find-based, so nil RESULTS are cached too; args canonicalize as a collection key. -(defn memoize [f] - (let [mem (atom (hash-map))] - (fn [& args] - ;; plain let/if, not if-let: this tier loads before 30-macros defines it - (let [e (find (deref mem) args)] - (if e - (val e) - (let [ret (apply f args)] - (swap! mem assoc args ret) - ret)))))) - -(defn partial - ([f] f) - ([f a] (fn [& args] (apply f a args))) - ([f a b] (fn [& args] (apply f a b args))) - ([f a b c] (fn [& args] (apply f a b c args))) - ([f a b c & more] (fn [& args] (apply f a b c (concat more args))))) - -(defn trampoline - ([f] (let [ret (f)] (if (fn? ret) (trampoline ret) ret))) - ([f & args] (trampoline (fn [] (apply f args))))) - -;; Canonical pairwise max/min: > / < throw on non-numbers, and the NaN -;; behavior is Clojure's by construction. -(defn max - ([x] x) - ([x y] (if (> x y) x y)) - ([x y & more] (reduce max (max x y) more))) - -(defn min - ([x] x) - ([x y] (if (< x y) x y)) - ([x y & more] (reduce min (min x y) more))) - -(defn reverse [coll] (reduce conj (list) coll)) - -;; An empty coll of the same category, carrying the receiver's metadata (Clojure's -;; .empty() does EMPTY.withMeta(meta())). Sorted colls keep their comparator (the -;; value's own :empty op). Strings and scalars are nil, as in Clojure; a lazy -;; seq empties to (). -(defn empty [coll] - (cond - (nil? coll) nil - ;; a deftype/record with its own empty (IPersistentCollection) — e.g. - ;; data.priority-map — uses it, before the generic map/set/vector arms. - (jolt.host/jrec-method? coll "empty") (.empty coll) - ;; a defrecord without its own empty can't have one (RT: UnsupportedOperation) - (record? coll) (throw (new UnsupportedOperationException - (str "Can't create empty: " (.getName (class coll))))) - (sorted? coll) ((get (jolt.host/ref-get coll :ops) :empty) coll) - (map? coll) (with-meta {} (meta coll)) - (set? coll) (with-meta #{} (meta coll)) - (vector? coll) (with-meta [] (meta coll)) - (coll? coll) (with-meta () (meta coll)) - :else nil)) - -(defn assoc-in [m [k & ks] v] - (if ks - (assoc m k (assoc-in (get m k) ks v)) - (assoc m k v))) - -(defn update-in [m ks f & args] - (let [up (fn up [m ks f args] - (let [[k & ks] ks] - (if ks - (assoc m k (up (get m k) ks f args)) - (assoc m k (apply f (get m k) args)))))] - (up m ks f args))) - -;; jolt keywords have no intern table (any keyword "exists"), so find-keyword -;; always finds — babashka makes the same call. -(defn find-keyword - ([nm] (keyword nm)) - ([ns nm] (keyword ns nm))) - -;; The raw Inst protocol method; jolt insts have one representation, so it is -;; inst-ms itself. -(defn inst-ms* [i] (inst-ms i)) - -;; Canonical comp — here rather than a host primitive so each stage is invoked with -;; jolt call semantics: (comp seq :content) works because the keyword stage -;; goes through IFn dispatch. -(defn comp - ([] identity) - ([f] f) - ([f g] - ;; fixed arities first (Clojure's own shape): the 1-arg path — every - ;; map/filter stage — is two direct calls, no rest-seq, no apply. - (fn - ([] (f (g))) - ([x] (f (g x))) - ([x y] (f (g x y))) - ([x y z] (f (g x y z))) - ([x y z & args] (f (apply g x y z args))))) - ([f g & fs] (reduce comp (comp f g) fs))) - -;; Canonical IFn set: fns, keywords, symbols, maps (sorted incl.), sets, -;; vectors, vars — NOT lists ((ifn? '(1 2)) is false in Clojure) — plus the -;; host callables (multimethods, promises) and a deftype/record implementing -;; clojure.lang.IFn's invoke. -(defn ifn? [x] - (if (or (fn? x) (keyword? x) (symbol? x) (map? x) (set? x) (vector? x) (var? x) - (jolt.host/callable-host? x) - (jolt.host/jrec-method? x "invoke")) - true - false)) - -;; Auto-promoting (') and unchecked arithmetic. Jolt numbers don't overflow, -;; so all of these are the checked ops; fixed arities mirror Clojure's -;; signatures. unchecked-divide-int goes through quot, so dividing by zero -;; throws as on the JVM. -(def +' +) -(def -' -) -(def *' *) -(def inc' inc) -(def dec' dec) -;; unchecked-add / -subtract / -multiply / -negate / -inc / -dec (+ the -int -;; variants), -divide-int / -remainder-int, and the unchecked-long/-int casts are -;; host-defined (host/chez/seq.ss, converters.ss): they WRAP like the JVM -;; primitive conversions, which a plain overlay over checked casts can't do. - -;; int? is integer? on jolt: one number type, so fixed-precision and -;; arbitrary-precision integers coincide. -(defn int? [x] (integer? x)) - -;; num: Clojure coerces to java.lang.Number; jolt just checks. -(defn num [x] - (if (number? x) x (throw (str "num requires a number, got: " x)))) - -;; == numeric equality: 1-arity is trivially true without inspecting the value -;; (Clojure's shape); 2+ args must be numbers, as Numbers.equiv throws. -(defn == - ([x] true) - ([x y] - (if (and (number? x) (number? y)) - (= x y) - (throw (str "Cannot cast to number: " (if (number? x) y x))))) - ([x y & more] - (if (== x y) - (apply == y more) - false))) - -;; ensure-reduced / halt-when: canonical Clojure. halt-when smuggles the halt -;; value through reduce in a ::halt-keyed map and unwraps it in the completion -;; arity, so the halt REPLACES the whole reduction result. -(defn ensure-reduced [x] (if (reduced? x) x (reduced x))) - -(defn halt-when - ([pred] (halt-when pred nil)) - ([pred retf] - (fn [rf] - (fn - ([] (rf)) - ([result] - (if (and (map? result) (contains? result ::halt)) - (get result ::halt) - (rf result))) - ([result input] - (if (pred input) - (reduced (hash-map ::halt (if retf (retf (rf result) input) input))) - (rf result input))))))) - -;; parse-boolean: exact "true"/"false" only; nil on anything else, throw on a -;; non-string (Clojure 1.11). -(defn parse-boolean [s] - (if (string? s) - (cond (= s "true") true (= s "false") false :else nil) - (throw (str "parse-boolean requires a string, got: " s)))) - -(defn newline [] (print "\n") nil) - -;; seque: jolt is single-threaded eager here — the queue is a no-op and the -;; coll passes through. -(defn seque - ([s] s) - ([n-or-q s] s)) - -(defn array-seq [arr & _] (seq arr)) - -(defn to-array-2d [coll] (to-array (map to-array coll))) - -;; Wrapping (unchecked) coercions: truncate to the width and sign-fold like the -;; JVM primitive conversions ((unchecked-byte 200) is -56); unchecked-char wraps -;; into char range. unchecked-long/int are host natives (converters.ss). -(defn unchecked-byte [x] - (let [b (bit-and (unchecked-long x) 0xff)] (if (< b 128) b (- b 256)))) -(defn unchecked-short [x] - (let [s (bit-and (unchecked-long x) 0xffff)] (if (< s 32768) s (- s 65536)))) -(defn unchecked-char [x] (char (bit-and (unchecked-long x) 0xffff))) -(defn unchecked-float [x] (double x)) -(defn unchecked-double [x] (double x)) - -;; --- transduce / into / eduction --------------------------------------------- -;; Canonical transduce: build the stacked rf once, reduce (which honors -;; `reduced` and steps lazy seqs incrementally), then run the completion arity. -(defn transduce - ([xform f coll] (transduce xform f (f) coll)) - ([xform f init coll] - (let [xf (xform f)] - (xf (reduce xf init coll))))) - -;; into stays a host primitive: it's perf-wall hot (the into-vec bench pays ~11% -;; through the overlay call layers — same lesson as even?/odd?). - -;; eduction is EAGER on jolt (documented divergence): the composed -;; xforms applied to coll, realized into a vector. -;; A lazy application of the composed xforms to coll (sequence is lazy now), so an -;; infinite or expensive source isn't realized up front. Not a re-iterable Eduction -;; object, but reduce / into / seq / first over it all work. -(defn eduction [& args] - (let [coll (last args) - xforms (butlast args)] - (if xforms - (sequence (apply comp xforms) coll) - (sequence coll)))) - -(defn ->Eduction [xform coll] (sequence xform coll)) - -;; --- JVM-shape stubs and trivial shells -------------------------------------- -;; Pure compositions or documented jolt stubs; the host keeps nothing. -;; enumeration-seq drives a java.util.Enumeration (StringTokenizer, etc.) through -;; hasMoreElements/nextElement, like the JVM; an already-seqable arg (a jolt seq — -;; some host code passes a list) just seqs. -(defn enumeration-seq [e] - (if (or (nil? e) (seq? e) (sequential? e)) - (seq e) - (lazy-seq (when (.hasMoreElements e) - (cons (.nextElement e) (enumeration-seq e)))))) -(defn iterator-seq [i] (seq i)) - -;; jolt is single-threaded: a promise is an atom, deref never blocks -;; ((deref undelivered) is nil rather than a hang). -(defn promise [] (atom nil)) -(defn deliver [p v] (reset! p v) p) - -(defn bean [x] (if (map? x) x {})) - -(defn uri? [x] false) - -;; An EVALUATED set of quoted symbols — a quoted set literal ('#{if ...}) -;; stays an unevaluated reader form on jolt and contains? can't see into it. -(def ^:private special-syms - #{'if 'do 'let* 'fn* 'quote 'var 'def 'loop* 'recur 'throw 'try 'catch - 'finally 'new 'set! '. 'monitor-enter 'monitor-exit - '& 'case* 'deftype* 'letfn* 'reify*}) - -(defn special-symbol? [s] (contains? special-syms s)) - -;; print-method / print-dup are real multimethods in the io tier (50-io.clj). - -;; JVM proxies don't exist on this host: the read-only surface is inert, -;; the constructive surface throws. -(defn proxy-mappings [p] {}) -(defn proxy-call-with-super [f p meth] (f)) -(defn init-proxy [p mappings] p) -(defn update-proxy [p mappings] p) -(defn proxy-super [& args] (throw "proxy-super: JVM proxies are not supported in Jolt")) -(defn construct-proxy [c & args] (throw "construct-proxy: not supported in Jolt")) -(defn get-proxy-class [& interfaces] (throw "get-proxy-class: not supported in Jolt")) - -;; resolve, requiring the symbol's namespace first when it isn't loaded yet — -;; the dynamic-require pattern (tooling, plugin registries). The require and -;; resolve are the runtime fns, so this works identically under joltc run and -;; in an AOT binary (which compiles the namespace from the source roots). -(defn requiring-resolve [sym] - (if (qualified-symbol? sym) - (or (resolve sym) - (do (require (symbol (namespace sym))) - (resolve sym))) - (throw (new IllegalArgumentException (str "Not a qualified symbol: " sym))))) diff --git a/jolt-core/clojure/core/25-sorted.clj b/jolt-core/clojure/core/25-sorted.clj deleted file mode 100644 index c9d0d10..0000000 --- a/jolt-core/clojure/core/25-sorted.clj +++ /dev/null @@ -1,358 +0,0 @@ -;; clojure.core — sorted collections tier. -;; -;; A sorted-map / sorted-set is a tagged host table -;; {:jolt/type :jolt/sorted-map|:jolt/sorted-set -;; :tree RB-NODE | nil ; a red-black tree, comparator-ordered -;; :cnt N ; element count (O(1)) -;; :cmp FN-or-nil ; 3-way comparator; nil = natural order (compare) -;; :ops {op-kw fn}} ; this tier's implementations, attached to the value -;; -;; The tree is a left-leaning-free red-black tree — Rich Hickey's algorithm, -;; ported from the ClojureScript PersistentTreeMap (cljs.core: tree-map-add / -;; balance-left / balance-right / tree-map-append / balance-*-del). assoc / get / -;; dissoc / contains are O(log n). cljs uses BlackNode/RedNode -;; deftypes, but this tier loads before 30-macros (no deftype), so a node is a -;; plain vector [color k v left right] (color :red/:black; left/right node|nil) -;; and the methods become functions — the algorithm is identical. -;; -;; A sorted-SET stores its elements as keys with a nil value; its ops project the -;; key. ALL the semantics live here in Clojure; the host keeps only its -;; dispatch branches (conj/assoc/get/seq/count/…), each a one-line call through -;; the value's own :ops table, so the ops travel WITH the value (correct across -;; contexts, forks, and AOT images). The wrapper is minted/read through the host -;; value primitives jolt.host/tagged-table + ref-put! + ref-get. - -;; Raw field read on the wrapper (host primitive). Plain `get` on a sorted coll -;; IS the comparator lookup — it dispatches back into these ops, so reading -;; :tree/:cmp/:ops with it would recurse forever. -(defn- sfield [sc k] (jolt.host/ref-get sc k)) - -;; Clojure's fn->comparator: a comparator fn may return a number (3-way) or a -;; boolean less-than predicate. -(defn- fn->cmp [f] - (fn [a b] - (let [r (f a b)] - (if (number? r) - r - (if r -1 (if (f b a) 1 0)))))) - -(defn- the-cmp [sc] (or (sfield sc :cmp) compare)) - -;; --- red-black tree nodes: [color key val left right] ----------------------- -(defn- nd-key [n] (nth n 1)) -(defn- nd-val [n] (nth n 2)) -(defn- nd-left [n] (nth n 3)) -(defn- nd-right [n] (nth n 4)) -(defn- red? [n] (and n (identical? :red (nth n 0)))) -(defn- black? [n] (and n (identical? :black (nth n 0)))) -(defn- mk-red [k v l r] [:red k v l r]) -(defn- mk-black [k v l r] [:black k v l r]) -;; BlackNode.blacken = self; RedNode.blacken = a black copy. -(defn- blacken [n] (if (red? n) [:black (nd-key n) (nd-val n) (nd-left n) (nd-right n)] n)) -;; BlackNode.redden = a red copy; RedNode.redden = invariant violation (never hit -;; on the paths that call it: redden is only applied to a known-black node). -(defn- redden [n] [:red (nd-key n) (nd-val n) (nd-left n) (nd-right n)]) -;; replace a node's key/val/children KEEPING its color. -(defn- replace-node [n k v l r] (if (red? n) (mk-red k v l r) (mk-black k v l r))) - -;; --- insert balancing (the RedNode/BlackNode .balance-left/.balance-right) --- -(defn- ins-balance-left [ins parent] - (if (red? ins) - (let [l (nd-left ins) r (nd-right ins)] - (cond - (red? l) (mk-red (nd-key ins) (nd-val ins) - (blacken l) - (mk-black (nd-key parent) (nd-val parent) r (nd-right parent))) - (red? r) (mk-red (nd-key r) (nd-val r) - (mk-black (nd-key ins) (nd-val ins) l (nd-left r)) - (mk-black (nd-key parent) (nd-val parent) (nd-right r) (nd-right parent))) - :else (mk-black (nd-key parent) (nd-val parent) ins (nd-right parent)))) - (mk-black (nd-key parent) (nd-val parent) ins (nd-right parent)))) - -(defn- ins-balance-right [ins parent] - (if (red? ins) - (let [l (nd-left ins) r (nd-right ins)] - (cond - (red? r) (mk-red (nd-key ins) (nd-val ins) - (mk-black (nd-key parent) (nd-val parent) (nd-left parent) l) - (blacken r)) - (red? l) (mk-red (nd-key l) (nd-val l) - (mk-black (nd-key parent) (nd-val parent) (nd-left parent) (nd-left l)) - (mk-black (nd-key ins) (nd-val ins) (nd-right l) r)) - :else (mk-black (nd-key parent) (nd-val parent) (nd-left parent) ins))) - (mk-black (nd-key parent) (nd-val parent) (nd-left parent) ins))) - -;; node .add-left / .add-right (parent gains a new left/right subtree `ins`) -(defn- add-left [parent ins] - (if (red? parent) - (mk-red (nd-key parent) (nd-val parent) ins (nd-right parent)) - (ins-balance-left ins parent))) -(defn- add-right [parent ins] - (if (red? parent) - (mk-red (nd-key parent) (nd-val parent) (nd-left parent) ins) - (ins-balance-right ins parent))) - -;; insert k/v into tree, assuming k is NOT already present (the caller checks). -(defn- tree-ins [cmp tree k v] - (if (nil? tree) - (mk-red k v nil nil) - (if (neg? (cmp k (nd-key tree))) - (add-left tree (tree-ins cmp (nd-left tree) k v)) - (add-right tree (tree-ins cmp (nd-right tree) k v))))) - -;; replace the value at an existing key, keeping the tree structure (and the -;; first-inserted key, like Clojure's PersistentTreeMap). -(defn- tree-replace [cmp tree k v] - (let [c (cmp k (nd-key tree))] - (cond - (zero? c) (replace-node tree (nd-key tree) v (nd-left tree) (nd-right tree)) - (neg? c) (replace-node tree (nd-key tree) (nd-val tree) (tree-replace cmp (nd-left tree) k v) (nd-right tree)) - :else (replace-node tree (nd-key tree) (nd-val tree) (nd-left tree) (tree-replace cmp (nd-right tree) k v))))) - -(defn- tree-lookup [tree cmp k] - (loop [t tree] - (if (nil? t) - nil - (let [c (cmp k (nd-key t))] - (cond (zero? c) t - (neg? c) (recur (nd-left t)) - :else (recur (nd-right t))))))) - -;; --- delete balancing (cljs standalone balance-left / balance-right / *-del) - -(defn- balance-left [k v ins right] - (if (red? ins) - (let [il (nd-left ins) ir (nd-right ins)] - (cond - (red? il) (mk-red (nd-key ins) (nd-val ins) (blacken il) (mk-black k v ir right)) - (red? ir) (mk-red (nd-key ir) (nd-val ir) - (mk-black (nd-key ins) (nd-val ins) il (nd-left ir)) - (mk-black k v (nd-right ir) right)) - :else (mk-black k v ins right))) - (mk-black k v ins right))) - -(defn- balance-right [k v left ins] - (if (red? ins) - (let [il (nd-left ins) ir (nd-right ins)] - (cond - (red? ir) (mk-red (nd-key ins) (nd-val ins) (mk-black k v left il) (blacken ir)) - (red? il) (mk-red (nd-key il) (nd-val il) - (mk-black k v left (nd-left il)) - (mk-black (nd-key ins) (nd-val ins) (nd-right il) ir)) - :else (mk-black k v left ins))) - (mk-black k v left ins))) - -(defn- balance-left-del [k v del right] - (cond - (red? del) (mk-red k v (blacken del) right) - (black? right) (balance-right k v del (redden right)) - (and (red? right) (black? (nd-left right))) - (mk-red (nd-key (nd-left right)) (nd-val (nd-left right)) - (mk-black k v del (nd-left (nd-left right))) - (balance-right (nd-key right) (nd-val right) (nd-right (nd-left right)) (redden (nd-right right)))) - :else (throw (ex-info "red-black tree invariant violation" {})))) - -(defn- balance-right-del [k v left del] - (cond - (red? del) (mk-red k v left (blacken del)) - (black? left) (balance-left k v (redden left) del) - (and (red? left) (black? (nd-right left))) - (mk-red (nd-key (nd-right left)) (nd-val (nd-right left)) - (balance-left (nd-key left) (nd-val left) (redden (nd-left left)) (nd-left (nd-right left))) - (mk-black k v (nd-right (nd-right left)) del)) - :else (throw (ex-info "red-black tree invariant violation" {})))) - -;; merge two subtrees (the children of a removed node) -(defn- tree-append [left right] - (cond - (nil? left) right - (nil? right) left - (red? left) - (if (red? right) - (let [app (tree-append (nd-right left) (nd-left right))] - (if (red? app) - (mk-red (nd-key app) (nd-val app) - (mk-red (nd-key left) (nd-val left) (nd-left left) (nd-left app)) - (mk-red (nd-key right) (nd-val right) (nd-right app) (nd-right right))) - (mk-red (nd-key left) (nd-val left) (nd-left left) - (mk-red (nd-key right) (nd-val right) app (nd-right right))))) - (mk-red (nd-key left) (nd-val left) (nd-left left) (tree-append (nd-right left) right))) - (red? right) - (mk-red (nd-key right) (nd-val right) (tree-append left (nd-left right)) (nd-right right)) - :else - (let [app (tree-append (nd-right left) (nd-left right))] - (if (red? app) - (mk-red (nd-key app) (nd-val app) - (mk-black (nd-key left) (nd-val left) (nd-left left) (nd-left app)) - (mk-black (nd-key right) (nd-val right) (nd-right app) (nd-right right))) - (balance-left-del (nd-key left) (nd-val left) (nd-left left) - (mk-black (nd-key right) (nd-val right) app (nd-right right))))))) - -;; remove k from tree, assuming k IS present (the caller checks). -(defn- tree-del [cmp tree k] - (let [c (cmp k (nd-key tree))] - (cond - (zero? c) (tree-append (nd-left tree) (nd-right tree)) - (neg? c) (let [del (tree-del cmp (nd-left tree) k)] - (if (black? (nd-left tree)) - (balance-left-del (nd-key tree) (nd-val tree) del (nd-right tree)) - (mk-red (nd-key tree) (nd-val tree) del (nd-right tree)))) - :else (let [del (tree-del cmp (nd-right tree) k)] - (if (black? (nd-right tree)) - (balance-right-del (nd-key tree) (nd-val tree) (nd-left tree) del) - (mk-red (nd-key tree) (nd-val tree) (nd-left tree) del)))))) - -;; in-order walk: conj (proj node) for each node, ascending. -(defn- tree-collect [t proj acc] - (if (nil? t) - acc - (tree-collect (nd-right t) proj - (conj (tree-collect (nd-left t) proj acc) (proj t))))) - -(defn- make-sorted [tag tree cnt cmp ops] - (-> (jolt.host/tagged-table tag) - (jolt.host/ref-put! :tree tree) - (jolt.host/ref-put! :cnt cnt) - (jolt.host/ref-put! :cmp cmp) - (jolt.host/ref-put! :ops ops))) - -;; entries as a vector (ascending), the materialized form seq/rseq/subseq use. -(defn- sc-entries [sc proj] - (tree-collect (sfield sc :tree) proj [])) - -;; --- sorted-map ops --------------------------------------------------------- -;; a real map-entry (map-entry? true), so key/val/seq destructuring work like a -;; regular map's entries. -(defn- map-entry [t] (jolt.host/map-entry (nd-key t) (nd-val t))) - -(defn- sm-get [sm k not-found] - (let [n (tree-lookup (sfield sm :tree) (the-cmp sm) k)] - (if (nil? n) not-found (nd-val n)))) - -(defn- sm-assoc-1 [sm k v] - (let [cmp (the-cmp sm) tree (sfield sm :tree) - node (tree-lookup tree cmp k)] - (cond - (and node (= v (nd-val node))) sm - node (make-sorted :jolt/sorted-map (tree-replace cmp tree k v) (sfield sm :cnt) (sfield sm :cmp) (sfield sm :ops)) - :else (make-sorted :jolt/sorted-map (blacken (tree-ins cmp tree k v)) (inc (sfield sm :cnt)) (sfield sm :cmp) (sfield sm :ops))))) - -(defn- sm-assoc-many [sm kvs] - (let [n (count kvs)] - (when (odd? n) - (throw (ex-info "sorted-map assoc expects an even number of key/values" {:count n}))) - (loop [m sm i 0] - (if (< i n) - (recur (sm-assoc-1 m (nth kvs i) (nth kvs (inc i))) (+ i 2)) - m)))) - -(defn- sm-dissoc-1 [sm k] - (let [cmp (the-cmp sm) tree (sfield sm :tree)] - (if (nil? (tree-lookup tree cmp k)) - sm - (let [t (tree-del cmp tree k)] - (make-sorted :jolt/sorted-map (when t (blacken t)) (dec (sfield sm :cnt)) (sfield sm :cmp) (sfield sm :ops)))))) - -(defn- sm-dissoc-many [sm ks] (reduce sm-dissoc-1 sm ks)) - -;; conj on a map: a [k v] pair (2-vector / map-entry) or a map to merge; -;; nil is a no-op, as in Clojure. -(defn- sm-conj-1 [sm x] - (cond - (nil? x) sm - (map? x) (reduce (fn [m e] (sm-assoc-1 m (first e) (second e))) sm (seq x)) - (and (vector? x) (= 2 (count x))) (sm-assoc-1 sm (nth x 0) (nth x 1)) - :else (throw (ex-info "conj on a sorted-map requires a [key value] pair or a map" {})))) - -(defn- sm-conj-many [sm xs] (reduce sm-conj-1 sm xs)) - -;; --- sorted-set ops (elements stored as keys, nil value) -------------------- -(defn- ss-get [ss x not-found] - (let [n (tree-lookup (sfield ss :tree) (the-cmp ss) x)] - (if (nil? n) not-found (nd-key n)))) - -(defn- ss-conj-1 [ss x] - (let [cmp (the-cmp ss) tree (sfield ss :tree)] - (if (tree-lookup tree cmp x) - ss - (make-sorted :jolt/sorted-set (blacken (tree-ins cmp tree x nil)) (inc (sfield ss :cnt)) (sfield ss :cmp) (sfield ss :ops))))) - -(defn- ss-conj-many [ss xs] (reduce ss-conj-1 ss xs)) - -(defn- ss-disj-1 [ss x] - (let [cmp (the-cmp ss) tree (sfield ss :tree)] - (if (nil? (tree-lookup tree cmp x)) - ss - (let [t (tree-del cmp tree x)] - (make-sorted :jolt/sorted-set (when t (blacken t)) (dec (sfield ss :cnt)) (sfield ss :cmp) (sfield ss :ops)))))) - -(defn- ss-disj-many [ss xs] (reduce ss-disj-1 ss xs)) - -;; --- the ops tables the host dispatches through ------------------------ - -(def ^:private sm-ops - {:count (fn [sm] (sfield sm :cnt)) - :entries (fn [sm] (sc-entries sm map-entry)) - :seq (fn [sm] (seq (sc-entries sm map-entry))) - :rseq (fn [sm] (seq (vec (reverse (sc-entries sm map-entry))))) - :first (fn [sm] (first (sc-entries sm map-entry))) - :get sm-get - :contains (fn [sm k] (not (nil? (tree-lookup (sfield sm :tree) (the-cmp sm) k)))) - :assoc sm-assoc-many - :dissoc sm-dissoc-many - :conj sm-conj-many - :empty (fn [sm] (make-sorted :jolt/sorted-map nil 0 (sfield sm :cmp) (sfield sm :ops)))}) - -(def ^:private ss-ops - {:count (fn [ss] (sfield ss :cnt)) - :entries (fn [ss] (sc-entries ss nd-key)) - :seq (fn [ss] (seq (sc-entries ss nd-key))) - :rseq (fn [ss] (seq (vec (reverse (sc-entries ss nd-key))))) - :first (fn [ss] (first (sc-entries ss nd-key))) - :get ss-get - :contains (fn [ss x] (not (nil? (tree-lookup (sfield ss :tree) (the-cmp ss) x)))) - :conj ss-conj-many - :disj ss-disj-many - :empty (fn [ss] (make-sorted :jolt/sorted-set nil 0 (sfield ss :cmp) (sfield ss :ops)))}) - -;; --- constructors + predicates ----------------------------------------------- - -(defn sorted-map [& kvs] - (sm-assoc-many (make-sorted :jolt/sorted-map nil 0 nil sm-ops) (vec kvs))) - -(defn sorted-map-by [comparator & kvs] - (sm-assoc-many (make-sorted :jolt/sorted-map nil 0 (fn->cmp comparator) sm-ops) (vec kvs))) - -(defn sorted-set [& xs] - (ss-conj-many (make-sorted :jolt/sorted-set nil 0 nil ss-ops) (vec xs))) - -(defn sorted-set-by [comparator & xs] - (ss-conj-many (make-sorted :jolt/sorted-set nil 0 (fn->cmp comparator) ss-ops) (vec xs))) - -(defn sorted-map? [x] (= :jolt/sorted-map (sfield x :jolt/type))) -(defn sorted-set? [x] (= :jolt/sorted-set (sfield x :jolt/type))) -(defn sorted? [x] (or (sorted-map? x) (sorted-set? x))) - -;; --- subseq / rsubseq --------------------------------------------------------- -;; test is one of < <= > >= applied Clojure-style to the comparator result: -;; keep entries whose (cmp entry-key k) satisfies (test _ 0). Returns a seq or -;; nil, like Clojure. - -(defn- sc-keyf [sc] (if (sorted-map? sc) first identity)) -(defn- sc-proj [sc] (if (sorted-map? sc) map-entry nd-key)) - -(defn- sub-filter [sc tests] - (let [cmp (the-cmp sc) - keyf (sc-keyf sc)] - (filterv (fn [e] - (every? (fn [[test k]] (test (cmp (keyf e) k) 0)) tests)) - (sc-entries sc (sc-proj sc))))) - -(defn subseq - ([sc test k] (seq (sub-filter sc [[test k]]))) - ([sc start-test start-k end-test end-k] - (seq (sub-filter sc [[start-test start-k] [end-test end-k]])))) - -(defn rsubseq - ([sc test k] (seq (vec (reverse (sub-filter sc [[test k]]))))) - ([sc start-test start-k end-test end-k] - (seq (vec (reverse (sub-filter sc [[start-test start-k] [end-test end-k]])))))) diff --git a/jolt-core/clojure/core/30-macros.clj b/jolt-core/clojure/core/30-macros.clj index be1c240..79001fd 100644 --- a/jolt-core/clojure/core/30-macros.clj +++ b/jolt-core/clojure/core/30-macros.clj @@ -1,13 +1,13 @@ -;; clojure.core — macro tier. Macros expressed in Clojure (defmacro + syntax-quote). -;; Loaded after the fn tiers, so a macro here may use any already-frozen core -;; fn/macro. +;; clojure.core — macro tier. Macros expressed in Clojure (defmacro + syntax-quote) +;; rather than as hand-built Janet form-transformers. Loaded after the fn tiers, +;; so a macro here may use any already-frozen core fn/macro. ;; ;; IMPORTANT — only macros NOT used by the self-hosted compiler (jolt-core/jolt/*) ;; or by the earlier overlay tiers belong here; those (and/or/when/when-not/ ;; when-let/cond/case/doseq/declare/cond->/->) must stay available before this -;; tier loads, so they remain host primitives for now. Everything here is user-facing. +;; tier loads, so they remain in Janet for now. Everything here is user-facing. ;; -;; Migration: remove the host core-X macro fn AND its core-macro-names entry when +;; Migration: remove the Janet core-X macro fn AND its core-macro-names entry when ;; moving a macro here (defmacro installs the :macro flag itself). (defmacro comment [& body] nil) @@ -21,125 +21,11 @@ ;; clojure.core fns) so they compile as plain invokes. name/mm are passed quoted; ;; the dispatch fn, options, and dispatch value evaluate normally, and the method ;; body becomes a compiled (fn …). -;; Clojure allows (defmulti name docstring? attr-map? dispatch-fn & options); -;; drop a leading docstring and/or attr-map so the dispatch fn isn't mistaken for -;; one (migratus's multimethods carry docstrings). -(defmacro defmulti [name & args] - (let [args (if (string? (first args)) (rest args) args) - args (if (and (map? (first args)) (not (symbol? (first args)))) (rest args) args) - dispatch (first args) - opts (rest args) - ;; qualify with the EXPANSION ns: a defmulti deferred inside a fn (a - ;; deftest body) must still define in the ns it was written in. - qname (symbol (str (clojure.core/ns-name clojure.core/*ns*)) - (clojure.core/name name))] - `(defmulti-setup (quote ~qname) ~dispatch ~@opts))) +(defmacro defmulti [name dispatch & opts] + `(defmulti-setup (quote ~name) ~dispatch ~@opts)) (defmacro defmethod [mm dispatch-val & fn-tail] - ;; the expansion ns rides along so a deferred defmethod resolves its multifn - ;; against the ns it was written in (aliases and refers included). - `(defmethod-setup (quote ~mm) ~dispatch-val (fn ~@fn-tail) - ~(str (clojure.core/ns-name clojure.core/*ns*)))) - -;; Multimethod table ops: a multimethod's method table lives on its -;; VAR (the value is just the dispatch closure), so these pass the name quoted -;; to ctx-capturing setups — the same shape as defmulti/defmethod above. -(defmacro prefer-method [mm dval-a dval-b] - `(prefer-method-setup (quote ~mm) ~dval-a ~dval-b)) - -(defmacro remove-method [mm dval] - `(remove-method-setup (quote ~mm) ~dval)) - -(defmacro remove-all-methods [mm] - `(remove-all-methods-setup (quote ~mm))) - -;; methods/get-method take the multimethod VALUE (Clojure semantics); the setup -;; maps it back to its var via the registry, so a bare multifn ref works from a -;; compiled fn in any namespace. -(defmacro get-method [mm dval] - `(get-method-setup ~mm ~dval)) - -(defmacro methods [mm] - `(methods-setup ~mm)) - -;; prefers reads the store off the VAR (the multifn value can't carry it) — -;; same symbol-passing shape as the other multimethod table ops. -(defmacro prefers [mm] - `(prefers-setup (quote ~mm))) - -;; instance?: class names don't evaluate to values on jolt, so the type arg is -;; passed quoted to the ctx-capturing checker; the value evaluates normally. -;; A LIST in type position is a class-valued expression (e.g. Selmer's -;; (Class/forName "[C")) — evaluate it instead. -(defmacro instance? [t x] - (if (seq? t) - `(instance-check ~t ~x) - `(instance-check (quote ~t) ~x))) - -;; Take x's monitor for the duration of body (futures/agents/threads share one -;; heap, so this is a real per-object lock), releasing on any exit. -(defmacro locking [x & body] - `(jolt.host/with-monitor ~x (fn* [] ~@body))) - -;; defonce: define name only if it isn't already bound to a non-nil root; -;; returns the existing var untouched otherwise. -;; time: evaluate expr, print the elapsed wall-clock, return the value. -;; current-time-ms is the host's monotonic clock. -(defmacro time [expr] - `(let [start# (current-time-ms) - ret# ~expr] - (println (str "Elapsed time: " (- (current-time-ms) start#) " msecs")) - ret#)) - -;; with-redefs: temporary root rebinding, restored on exit (incl. throw). -;; Builds (hash-map (var n1) v1 ...) — a call form, since map-literal forms -;; can't carry call forms as keys. -(defmacro with-redefs [bindings & body] - (let [pairs (reduce (fn [acc p] (conj (conj acc `(var ~(first p))) (second p))) - [] (partition 2 bindings))] - `(with-redefs-fn (hash-map ~@pairs) (fn [] ~@body)))) - -;; Fresh free-standing var cells bound as locals; read/write with -;; var-get/var-set. The cells come from the host seam __local-var. -(defmacro with-local-vars [bindings & body] - (let [binds (reduce (fn [acc p] (conj (conj acc (first p)) `(__local-var ~(second p)))) - [] (partition 2 bindings))] - `(let [~@binds] ~@body))) - -;; Canonical recursive expansion; closing goes through the host seam __close -;; (a map-like value's :close fn or a host file — no .close interop here). -(defmacro with-open [bindings & body] - (if (zero? (count bindings)) - `(do ~@body) - `(let [~(first bindings) ~(second bindings)] - (try - (with-open ~(vec (drop 2 bindings)) ~@body) - (finally (__close ~(first bindings))))))) - -;; Binds *math-context*; BigDecimal arithmetic in the dynamic scope rounds its -;; results to the precision with the rounding mode (default HALF_UP, like -;; java.math.MathContext). -(defmacro with-precision [precision & exprs] - (let [[rounding body] (if (= :rounding (first exprs)) - [(second exprs) (drop 2 exprs)] - ['HALF_UP exprs])] - `(binding [clojure.core/*math-context* {:precision ~precision :rounding '~rounding}] - ~@body))) - -(defmacro with-bindings [binding-map & body] - `(with-bindings* ~binding-map (fn [] ~@body))) - -(defmacro bound-fn [& fntail] - `(bound-fn* (fn ~@fntail))) - -(defmacro defonce [name expr] - ;; only def when the var has no root value. In a top-level (do ...) the name is - ;; already interned (an unbound cell) by the time this runs, so check bound? — - ;; var-get would throw on the unbound cell. - `(let [v# (resolve (quote ~name))] - (if (and v# (bound? v#)) - v# - (def ~name ~expr)))) + `(defmethod-setup (quote ~mm) ~dispatch-val (fn ~@fn-tail))) ;; Single arglist (Jolt defmacro is single-arity); the optional else defaults nil ;; via rest-destructuring. @@ -175,11 +61,14 @@ (loop [~i 0] (when (< ~i n#) ~@body (recur (inc ~i))))))) -;; fresh-sym (a macro-body gensym round-tripped through str) is defined in -;; 00-syntax, which loads before this tier — reuse it. +;; A fresh jolt symbol inside a macro body: (gensym) here resolves to Janet's +;; builtin (a Janet symbol the destructurer rejects), so round-trip through str. +(defn- fresh-sym [] (symbol (str (gensym)))) ;; Lazy-safe: take only the head via first (Clojure uses (seq coll), but Jolt's -;; eager seq would realize an infinite coll like (repeat nil) and hang). +;; eager seq would realize an infinite coll like (repeat nil) and hang). Matches +;; the prior Janet behavior; the nil/false-head distinction waits on Phase 5 +;; laziness. (defmacro when-first [bindings & body] (let [x (bindings 0) coll (bindings 1)] `(when-let [~x (first ~coll)] ~@body))) @@ -218,14 +107,8 @@ `(let [~g ~expr ~@(thread-binds g steps)] ~(if (empty? steps) g (last steps))))) (defmacro assert [x & [message]] - (let [msg (if message - (str "Assert failed: " message "\n" (pr-str x)) - (str "Assert failed: " (pr-str x)))] - `(when-not ~x (throw (new AssertionError ~msg))))) - -;; (pvalues e1 e2 ...) — each expression evaluated in parallel (pcalls). -(defmacro pvalues [& exprs] - `(pcalls ~@(map (fn [e] `(fn [] ~e)) exprs))) + (let [msg (if message message (str "Assert failed: " (pr-str x)))] + `(when-not ~x (throw (ex-info ~msg {}))))) (defmacro delay [& body] `(make-delay (fn [] ~@body))) @@ -235,10 +118,10 @@ ;; Build the fn* form via a template (a reader-list array): cons/list in a macro ;; body produce a plist the evaluator can't call as a form. -;; letfn is a primitive special form (analyze-letfn -> letrec*), not a macro: its -;; fns are mutually recursive, which a (let* …) expansion cannot express. Defining -;; it as a macro would shadow the special once macroexpansion runs first (the -;; canonical order), so it is intentionally NOT a macro here. +(defmacro letfn [fnspecs & body] + (let [binds (reduce (fn [acc spec] (conj (conj acc (first spec)) `(fn* ~@(rest spec)))) + [] fnspecs)] + `(let* [~@binds] ~@body))) ;; Dynamic binding: install a thread-binding frame of var->value (array-map keeps ;; var-get happy, unlike a phm), restore on exit. @@ -274,14 +157,9 @@ ;; Group a flat seq that starts with a head symbol followed by its list specs ;; into [[head spec spec ...] ...] runs. Used by extend-protocol and defrecord. -;; Group deftype/defrecord/reify body forms: a symbol/nil head starts a new -;; group, every other form appends to the current one. (extend-protocol uses -;; parse-extend-impls instead — it must treat a COMPUTED class type like -;; (Class/forName "[B"), a seq, as a head, which this would misread as a method.) (defn- group-by-head [items] - ;; nil is a valid extension head (extend-protocol P ... nil (m [x] ...)). (reduce (fn [acc x] - (if (or (symbol? x) (nil? x)) + (if (symbol? x) (conj acc [x]) (conj (pop acc) (conj (peek acc) x)))) [] items)) @@ -292,10 +170,6 @@ ;; type's fields, bound from the instance (the method's first param), matching ;; Clojure's deftype scope. defrecord (below) expands to a bodyless (deftype …) and ;; handles its own methods, so this also serves the no-body case. -;; Legacy structmap definer: binds a var to the struct basis (see create-struct). -(defmacro defstruct [name & keys] - `(def ~name (create-struct ~@keys))) - (defmacro deftype [tname fields & body] ;; strip ^meta off the type name and fields (the reader yields a (with-meta sym m) ;; form for e.g. (deftype ^{:doc …} Foo …)), so (name …) sees a bare symbol. @@ -307,132 +181,18 @@ ;; a seq of field keywords; spliced into a vector LITERAL below ([~@…]) so ;; the analyzer sees a vector form, not a runtime pvec value. field-kws (map (fn [f] (keyword (name f))) fields) - ;; per-field TYPE HINT: ^Vec3 origin -> "Vec3" (a record type - ;; name), ^:num x -> "num", else nil. Lets the inference know a field's - ;; exact type up front, so reading it back carries that type (not :any) — - ;; the key to fast nested-record code. Spliced as a vector literal too. - field-tags (map (fn [f] (let [mt (meta f)] - (cond (and mt (:tag mt)) (name (:tag mt)) ; symbol or string -> string - (and mt (:num mt)) "num" - :else nil))) - fields) - ;; per-field MUTABILITY: ^:unsynchronized-mutable / ^:volatile- - ;; mutable marks a field set!-able. A type with any mutable field opts out - ;; of the immutable shape-rec layout and uses the mutable table form, so - ;; set! can mutate it (the ctor reads this vector). Spliced as a literal. - field-muts (map (fn [f] (let [mt (meta f)] - (if (and mt (or (:unsynchronized-mutable mt) - (:volatile-mutable mt))) - true false))) - fields) - ;; mutable field symbols (^:unsynchronized-mutable / ^:volatile-mutable): - ;; (set! field v) in a method body lowers to (set! (.-field inst) v), the - ;; in-place field write the analyzer compiles to jolt-set-field!. - mutable-syms (map first (filter second (map vector fields field-muts))) - mutable? (fn [s] (boolean (some (fn [m] (= m s)) mutable-syms))) - ;; rewrite a method body: (set! mut-field v) -> an in-place (.-field inst) - ;; write, and a READ of a mutable field -> (.-field inst) so it observes the - ;; live value after a set! (the double-checked-locking idiom re-reads a field - ;; after taking a lock). Immutable fields stay let-bound (captured once is - ;; correct and cheaper). Tracks lexical shadowing through let/loop/fn/letfn so - ;; a same-named local wins over a field. - rewrite-body - (fn rw [inst shadowed form] - (cond - (and (seq? form) (seq form) (symbol? (first form)) - (= "set!" (name (first form))) - (symbol? (second form)) (mutable? (second form)) - (not (contains? shadowed (second form)))) - (list 'set! (list (symbol (str ".-" (name (second form)))) inst) - (rw inst shadowed (nth form 2))) - ;; let/loop-style vector-binding forms: rewrite inits, then shadow the - ;; bound names in the body. - (and (seq? form) (seq form) (symbol? (first form)) - (contains? #{"let" "let*" "loop" "binding" "when-let" "if-let" - "when-some" "if-some"} (name (first form))) - (vector? (second form))) - (let [bv (second form) n (count bv) - bv' (loop [i 0 acc []] - (if (< i n) - (recur (+ i 2) - (let [a (conj acc (nth bv i))] - (if (< (inc i) n) (conj a (rw inst shadowed (nth bv (inc i)))) a))) - acc)) - sh (loop [i 0 acc shadowed] - (if (< i n) - (recur (+ i 2) (if (symbol? (nth bv i)) (conj acc (nth bv i)) acc)) - acc))] - (cons (first form) (cons bv' (map (fn [x] (rw inst sh x)) (drop 2 form))))) - ;; fn/fn*: shadow each arity's params in its body. - (and (seq? form) (seq form) (symbol? (first form)) - (contains? #{"fn" "fn*"} (name (first form)))) - (let [head (first form) tail (rest form) - named? (and (seq tail) (symbol? (first tail))) - fname (when named? (first tail)) - arts (if named? (rest tail) tail) - psyms (fn [pv] (loop [p (seq pv) acc shadowed] - (if p - (recur (next p) - (if (and (symbol? (first p)) (not= (name (first p)) "&")) - (conj acc (first p)) acc)) - acc))) - do-art (fn [ar] (cons (first ar) (map (fn [x] (rw inst (psyms (first ar)) x)) (rest ar)))) - arts' (if (vector? (first arts)) (do-art arts) (map do-art arts))] - (concat (list head) (when named? (list fname)) arts')) - ;; a bare read of a mutable field -> live field access - (and (symbol? form) (mutable? form) (not (contains? shadowed form))) - (list (symbol (str ".-" (name form))) inst) - (seq? form) (map (fn [x] (rw inst shadowed x)) form) - (vector? form) (mapv (fn [x] (rw inst shadowed x)) form) - :else form)) - ;; inline impls register for dispatch but are NOT extenders of the - ;; protocol (the JVM compiles them into the class) — register-inline-method, - ;; not extend-type. - ;; build one method clause (argv + field-bound body) from a method spec. - ;; The clause is DATA, not a syntax-quote: a body that is itself a syntax- - ;; quote would have its ~unquotes consumed a level early if re-spliced. - mk-clause (fn [spec] - ;; fresh-name each _ param so two _ params don't collide on the - ;; field binds / live-read instance (see defrecord's mk-clause). - (let [argv (mapv (fn [p] (if (= p (quote _)) (gensym "_p") p)) (nth spec 1)) - inst (first argv) - ;; A method param shadows a same-named field (Clojure - ;; semantics): don't let-bind a field the param already - ;; provides, and treat those params as shadowing so a - ;; mutable field's live-read rewrite doesn't override them. - pnames (set (map name argv)) - ;; let-bind only immutable fields; mutable ones are read live - ;; via rewrite-body so a set! within the method is observed. - binds (vec (mapcat (fn [f] [f `(get ~inst ~(keyword (name f)))]) - (filter (fn [f] (and (not (mutable? f)) - (not (contains? pnames (name f))))) - fields))) - mbody (map (fn [bf] (rewrite-body inst (set argv) bf)) (drop 2 spec))] - (list argv (list* 'let binds mbody)))) - groups (group-by-head body) - ;; merge clauses by method NAME across ALL protocols into one multi-arity - ;; fn, so a name appearing in two interfaces with different arities - ;; (data.priority-map's seq is in Seqable [this] AND Sorted [this asc]) - ;; dispatches by arg count instead of one registration shadowing the other. - ;; (Within one protocol, distinct arities like Indexed's nth merge the same - ;; way.) Each (protocol, name) registers the merged fn, so dispatch by name - ;; and satisfies? by protocol both hold. - by-name (reduce (fn [m spec] - (let [nm (name (first spec))] - (assoc m nm (conj (get m nm []) (mk-clause spec))))) - {} (mapcat rest groups))] + impl (fn [proto specs] + `(extend-type ~tname ~proto + ~@(map (fn [spec] + (let [argv (nth spec 1) + inst (first argv) + binds (vec (mapcat (fn [f] [f `(get ~inst ~(keyword (name f)))]) fields))] + `(~(first spec) ~argv (let [~@binds] ~@(drop 2 spec))))) + specs)))] `(do - (def ~tname (make-deftype-ctor (quote ~tname) [~@field-kws] [~@field-tags] [~@field-muts])) + (def ~tname (make-deftype-ctor (quote ~tname) [~@field-kws])) (def ~arrow ~tname) - ~@(mapcat (fn [g] - (let [proto (first g) - names (distinct (map (fn [spec] (name (first spec))) (rest g)))] - (cons `(register-inline-protocol! ~(name tname) ~(name proto)) - (map (fn [nm] - `(register-inline-method ~(name tname) ~(name proto) ~nm - (fn ~@(get by-name nm)))) - names)))) - groups) + ~@(map (fn [g] (impl (first g) (rest g))) (group-by-head body)) ~tname))) ;; The protocol value is built by make-protocol (a fn call) rather than an embedded @@ -440,178 +200,52 @@ ;; instead of evaluating its fields. methods is a {kw {:name str}} map (only :name ;; is consulted). Each method is a thin dispatch fn over protocol-dispatch. (defmacro defprotocol [pname & sigs] - ;; Clojure's defprotocol takes an optional docstring and leading keyword - ;; options (:extend-via-metadata true, honeysql uses it) before the method - ;; signatures — drop them (metadata extension is a JVM dispatch detail). - (let [sigs (loop [s sigs] - (cond - (string? (first s)) (recur (rest s)) - (keyword? (first s)) (recur (rest (rest s))) - :else s)) - methods (reduce (fn [m sig] + (let [methods (reduce (fn [m sig] (assoc m (keyword (name (first sig))) {:name (name (first sig))})) {} sigs)] `(do (def ~pname (make-protocol ~(name pname) ~methods)) - ;; register method var-keys for devirtualization; the inference - ;; reads this (via infer-unit!) to resolve a protocol call on a known record - (register-protocol-methods! ~(name pname) [~@(map (fn [s] (name (first s))) sigs)]) - ;; one fn clause per declared arity. The protocol/method NAMES pass as - ;; strings so the body compiles as a plain invoke (not symbol-as-var). The - ;; common 1/2/3-param arities call positional protocol-dispatchN, which - ;; applies the impl directly — no rest-list cons; 4+ params fall back to the - ;; variadic protocol-dispatch with a vector of the extra args. ~@(map (fn [sig] - (let [pn (name pname) - mn (name (first sig)) - arglists (filter vector? (rest sig)) - clause (fn [argv] - (let [ps (mapv (fn [_] (fresh-sym)) argv) - n (count ps) - obj (first ps)] - (cond - (= n 1) (list ps (list 'protocol-dispatch1 pn mn obj)) - (= n 2) (list ps (list 'protocol-dispatch2 pn mn obj (nth ps 1))) - (= n 3) (list ps (list 'protocol-dispatch3 pn mn obj (nth ps 1) (nth ps 2))) - :else (list ps (list 'protocol-dispatch pn mn obj (vec (rest ps)))))))] - (if (seq arglists) - `(def ~(first sig) (fn* ~@(map clause arglists))) - `(def ~(first sig) - (fn* [this# & rest#] (protocol-dispatch ~pn ~mn this# rest#)))))) + `(def ~(first sig) + ;; protocol-dispatch is a fn (clojure.core); pass the protocol / + ;; method NAMES as strings (not the symbols) so it compiles as a + ;; plain invoke rather than evaluating the symbols as vars. + (fn* [this# & rest#] + (protocol-dispatch ~(name pname) ~(name (first sig)) this# rest#)))) sigs)))) -;; Member threading: (.. x f g) => (. (. x f) g); a parenthesized member -;; carries args. Canonical Clojure shape, single-arity defmacro. -(defmacro .. [x form & more] - (let [step (if (seq? form) - `(. ~x ~(first form) ~@(rest form)) - `(. ~x ~form))] - (if (seq more) - `(.. ~step ~@more) - step))) - -;; True when atype's methods were registered for this protocol (via extend / -;; extend-type). Tags are canonical host names or ns-qualified record names, so a -;; name matches its tag when either is a dotted suffix of the other — a bare -;; record name matches its "ns.Name" tag, and a query for a qualified host class -;; (java.util.Map) matches the canonical short tag (Map) extend registered it as. -(defn extends? [protocol atype] - (let [want (if (nil? atype) "nil" (name atype)) - suffix? (fn [long short] - (let [d (str "." short)] - (and (> (count long) (count d)) - (= (subs long (- (count long) (count d))) d))))] - (boolean (some (fn [t] - (let [tn (name t)] - (or (= tn want) (suffix? tn want) (suffix? want tn)))) - (extenders protocol))))) - -;; The canonical name for a protocol-extension type: a symbol/keyword via name, a -;; string as-is, nil as "nil" (extends on nil values), and a Class VALUE — e.g. -;; (Class/forName "[B") for the byte-array class — via .getName. Lets a library -;; extend a protocol to a class it computes rather than names with a symbol. -(defn type->name [t] - (cond (nil? t) "nil" - (string? t) t - (symbol? t) (name t) - (keyword? t) (name t) - :else (.getName t))) - -;; extend, the FUNCTION (extend-type's runtime sibling): protocol + method-map -;; pairs, methods registered under the type's (canonicalized) name — so -;; (extend 'String P {:m (fn [x] ...)}) dispatches exactly like extend-type. -(defn extend [atype & proto+mmaps] - ;; nil extends on nil values; its host tag is the string "nil" (as extend-type). - (let [tname (type->name atype)] - (loop [s (seq proto+mmaps)] - (when s - (let [proto (first s) - mmap (second s) - pname (name (get proto :name))] - (doseq [[k f] mmap] - (register-method tname pname (name k) f))) - (recur (nnext s)))))) - -(defmacro extend-type [tsym & body] +(defmacro extend-type [tsym psym & impls] ;; register-method is a fn (clojure.core); pass type/protocol/method NAMES as - ;; strings (not the symbols) so the call compiles as a plain invoke. A nil - ;; type extends on nil values (the host tag is the string "nil"). - ;; `body` is one or more protocols, each followed by its method specs: - ;; (extend-type T P1 (m1 [_] ..) P2 (m2 [_] ..)) — a bare symbol switches the - ;; current protocol (like reify), so multiple protocols extend in one form. - ;; tsym may be a symbol/nil (name resolved at compile time) or a computed class - ;; expression like (Class/forName "[B") — bind its runtime name once. - (let [literal? (or (nil? tsym) (symbol? tsym)) - tn (gensym "tname") - tref (if literal? (if (nil? tsym) "nil" (name tsym)) tn) - emit (fn [] - (loop [items (seq body) proto nil forms []] - (if (empty? items) - forms - (let [x (first items)] - (if (symbol? x) - (recur (rest items) (name x) forms) - (recur (rest items) proto - (conj forms - `(register-method ~tref ~proto ~(name (first x)) - (fn ~(nth x 1) ~@(drop 2 x))))))))))] - (if literal? - `(do ~@(emit)) - `(let [~tn (type->name ~tsym)] ~@(emit) nil)))) - -;; Group an extend-protocol body into [type method-spec*] groups: the type is the -;; first item and its method specs are the seqs that follow it (up to the next -;; type — a symbol/nil — or end). Handles a computed class type (a seq like -;; (Class/forName "[B")) positionally, matching Clojure's parse-impls. -(defn- parse-extend-impls [items] - (loop [s (seq items) groups []] - (if (empty? s) - groups - (let [after (rest s)] - (recur (drop-while seq? after) - (conj groups (vec (cons (first s) (take-while seq? after))))))))) + ;; strings (not the symbols) so the call compiles as a plain invoke. + `(do ~@(map (fn [spec] + `(register-method ~(name tsym) ~(name psym) ~(name (first spec)) + (fn* ~(nth spec 1) ~@(drop 2 spec)))) + impls))) (defmacro extend-protocol [psym & type-impls] `(do ~@(map (fn [g] `(extend-type ~(first g) ~psym ~@(rest g))) - (parse-extend-impls type-impls)))) + (group-by-head type-impls)))) -;; extend is a real FUNCTION — defined above extend-type. -;; JVM proxies are unsupported in general, EXCEPT (proxy [ThreadLocal] [] (initialValue -;; [] body)) — a per-thread store with a lazy initial value (test.check's no-seed -;; PRNG uses one). Other proxies stay nil. -(defmacro proxy [supers ctor-args & methods] - (when (and (vector? supers) (= 1 (count supers)) - (let [s (name (first supers))] (or (= s "ThreadLocal") (= s "InheritableThreadLocal")))) - (let [init (some (fn [m] (when (= "initialValue" (name (first m))) m)) methods)] - `(jolt.host/make-thread-local (fn [] ~@(when init (nnext init))))))) -;; definterface is JVM-only; bind the name to a marker and return the name (not a -;; var), matching the JVM where definterface yields the interface Class. -(defmacro definterface [name-sym & body] - `(do (def ~name-sym {}) (quote ~name-sym))) +;; extend (the fn form) is not supported — stub to nil, as before. +(defmacro extend [& args] nil) +;; JVM proxies are unsupported. +(defmacro proxy [& args] nil) +;; definterface is JVM-only; bind the name to an empty marker. +(defmacro definterface [name-sym & body] `(def ~name-sym {})) ;; make-reified is a fn (clojure.core); the method map {kw (fn* ...)} is an ;; ordinary map literal that evaluates to {keyword fn}, and the protocol NAME is ;; passed as a string (not the symbol) so the call compiles as a plain invoke. (defmacro reify [& forms] - ;; a reify can implement SEVERAL protocols; collect them all (each bare symbol - ;; switches the current protocol, like extend-type) and pass every protocol name - ;; to make-reified so (instance? Proto r)/satisfies? recognise all of them. - ;; Several bodies for the same method name are distinct arities (clojure.spec - ;; reifies (specize* [s]) and (specize* [s _])): group them into one multi-arity - ;; fn so dispatch picks the clause by arg count. - (loop [items (seq forms) protos [] methods {} order []] + (loop [items (seq forms) proto nil methods {}] (if (empty? items) - `(make-reified - ~(reduce (fn [m k] (assoc m k `(fn ~@(get methods k)))) {} order) - ~@(vec (map name protos))) + `(make-reified ~(name proto) ~methods) (let [x (first items)] (if (symbol? x) - (recur (rest items) (conj protos x) methods order) - (let [k (keyword (name (first x))) - clause `(~(nth x 1) ~@(drop 2 x))] - (recur (rest items) protos - (assoc methods k (conj (get methods k []) clause)) - (if (contains? methods k) order (conj order k))))))))) + (recur (rest items) (if proto proto x) methods) + (recur (rest items) proto + (assoc methods (keyword (name (first x))) + `(fn* ~(nth x 1) ~@(drop 2 x))))))))) (defmacro defrecord [name-sym fields & body] (let [tn (name name-sym) @@ -621,64 +255,24 @@ ;; each method body sees the record fields, bound from the instance (the ;; method's first param), matching Clojure's defrecord method scope. vec the ;; spliced binding seq so ~@ splices its elements, not the lazy-seq itself. - ;; inline impls register for dispatch but are NOT extenders of the - ;; protocol (the JVM compiles them into the class) — register-inline-method, - ;; not extend-type. - ;; one clause from a spec; `this` is hinted with the record type so the - ;; inference reads its fields bare-index. Clause as DATA (see deftype). - mk-clause (fn [spec] - ;; rename each _ parameter to a fresh symbol so two _ params - ;; (the common (m [_ _] …) on a 1-arg protocol method) don't - ;; collide — the field binds read (get this :field) off the - ;; FIRST param, which an ignored second _ would otherwise shadow. - (let [argv (mapv (fn [p] (if (= p (quote _)) (gensym "_p") p)) (nth spec 1)) - inst (first argv) - hinted (assoc argv 0 (vary-meta inst assoc :tag (name name-sym))) - ;; a method param shadows a same-named field (Clojure - ;; semantics), so don't rebind a field the param provides. - pnames (set (map name argv)) - binds (vec (mapcat (fn [f] [f `(get ~inst ~(keyword (name f)))]) - (remove (fn [f] (contains? pnames (name f))) fields)))] - (list hinted (list* 'let binds (drop 2 spec))))) - groups (group-by-head body) - ;; merge clauses by name across protocols into one multi-arity fn (see - ;; deftype's by-name). - by-name (reduce (fn [m spec] - (let [nm (name (first spec))] - (assoc m nm (conj (get m nm []) (mk-clause spec))))) - {} (mapcat rest groups))] + impl (fn [proto specs] + `(extend-type ~name-sym ~proto + ~@(map (fn [spec] + (let [argv (nth spec 1) + inst (first argv) + binds (vec (mapcat (fn [f] [f `(get ~inst ~(keyword (name f)))]) fields))] + `(~(first spec) ~argv (let [~@binds] ~@(drop 2 spec))))) + specs)))] `(do ;; deftype already defines ->name (= the ctor); no (name. …) interop needed, ;; so defrecord compiles too. map->name builds via that ctor. (deftype ~name-sym ~fields) - ;; mark the type a record (map?/record?/field-seq); a bare deftype is not. - (register-record-type! (quote ~name-sym)) - ;; build via the positional ctor for declared fields, then carry any - ;; remaining keys as extension fields (JVM keeps them on the record). - (def ~mapf (fn* [~m] - (reduce-kv assoc - (~arrow ~@(map (fn [f] `(get ~m ~(keyword (name f)))) fields)) - (dissoc ~m ~@(map (fn [f] (keyword (name f))) fields))))) - ~@(mapcat (fn [g] - (let [proto (first g) - names (distinct (map (fn [spec] (name (first spec))) (rest g)))] - (cons `(register-inline-protocol! ~(name name-sym) ~(name proto)) - (map (fn [nm] - `(register-inline-method ~(name name-sym) ~(name proto) ~nm - (fn ~@(get by-name nm)))) - names)))) - groups)))) + (def ~mapf (fn* [~m] (~arrow ~@(map (fn [f] `(get ~m ~(keyword (name f)))) fields)))) + ~@(map (fn [g] (impl (first g) (rest g))) (group-by-head body))))) ;; --- laziness -------------------------------------------------------------- ;; lazy-seq / lazy-cat moved to the 00-syntax tier: the seq/coll tiers (10-seq, ;; 20-coll) use lazy-seq, and in compile mode a tier's forms are compiled as it ;; loads — so the macro must be registered BEFORE those tiers, else (lazy-seq …) -;; compiles as a call to the macro-as-function and leaks its expansion at runtime. -;; They only need seed fns (make-lazy-seq/coll->cells/concat). - -;; memfn: a fn wrapping a method call, (memfn toUpperCase) => #(.toUpperCase %). -;; The method symbol is rewritten to jolt's .method call sugar; extra arg names -;; become fn params, as in Clojure. -(defmacro memfn [method-name & args] - `(fn [target# ~@args] - (~(symbol (str "." (name method-name))) target# ~@args))) +;; compiles as a call to the macro-as-function and leaks its expansion at runtime +;; (jolt-r81). They only need seed fns (make-lazy-seq/coll->cells/concat). diff --git a/jolt-core/clojure/core/40-lazy.clj b/jolt-core/clojure/core/40-lazy.clj index 880fb48..655e4be 100644 --- a/jolt-core/clojure/core/40-lazy.clj +++ b/jolt-core/clojure/core/40-lazy.clj @@ -76,15 +76,17 @@ (mapi 0 coll)))) ;; --- cycle --- -;; Lazy, like the JVM: never counts coll, so it terminates on a lazy/infinite -;; argument instead of forcing it. (defn cycle [coll] - (if (seq coll) - (lazy-seq (concat coll (cycle coll))) + (if-let [vals (seq coll)] + (let [n (count vals)] + (letfn [(cstep [i] + (lazy-seq + (cons (nth vals (mod i n)) (cstep (inc i)))))] + (cstep 0))) ())) ;; --- repeatedly --- ((f) throws on a non-fn; (take n …) throws on a non-number -;; count — both enforced by the host (jolt-call / take), so the canonical +;; count — both now enforced in the seed (jolt-call / core-take), so the canonical ;; CLJ form matches the repeatedly.cljc exception cases.) (defn repeatedly ([f] (lazy-seq (cons (f) (repeatedly f)))) @@ -96,19 +98,15 @@ ([n x] (take n (repeat x)))) ;; --- iterate --- -;; f is applied lazily, inside the tail thunk — (first (iterate f x)) is x with no -;; call to f, matching clojure.lang.Iterate. Wrapping the whole body in lazy-seq -;; instead would force (f x) the moment the head realizes (it is an eager argument -;; to cons), realizing one step ahead. (defn iterate [f x] - (cons x (lazy-seq (iterate f (f x))))) + (lazy-seq (cons x (iterate f (f x))))) ;; --- partition-all --- (transducer + [n coll] + [n step coll]) ;; The collection arities realize EXACTLY n per chunk via a first/rest loop and ;; continue from the advanced cursor (not a re-drop / nthrest), so they realize -;; minimally — the laziness counters depend on this. -;; (A take/nthrest form is correct but over-realizes.) +;; minimally — matching the Janet pstep the §6.3 laziness counters were written +;; against. (A take/nthrest form is correct but over-realizes.) (defn partition-all ([n] (fn [rf] @@ -129,13 +127,10 @@ (letfn [(go [s] (lazy-seq (when (seq s) - ;; realize exactly n via first/rest (minimal realization), but emit - ;; the chunk as a SEQ — JVM partition-all chunks are seqs, not - ;; vectors (partitionv-all is the vector variant). - (loop [i 0 acc () cur s] + (loop [i 0 chunk [] cur s] (if (and (< i n) (seq cur)) - (recur (inc i) (cons (first cur) acc) (rest cur)) - (cons (reverse acc) (go cur)))))))] + (recur (inc i) (conj chunk (first cur)) (rest cur)) + (cons chunk (go cur)))))))] (go coll))) ([n step coll] (letfn [(go [s] @@ -143,54 +138,3 @@ (when (seq s) (cons (take n s) (go (nthrest s step))))))] (go coll)))) - -;; --- canonical lazy + transducer arities ------------------------------------- - -(defn interpose - ([sep] - (fn [rf] - (let [started (volatile! false)] - (fn - ([] (rf)) - ([result] (rf result)) - ([result input] - (if (deref started) - (let [sepr (rf result sep)] - (if (reduced? sepr) - sepr - (rf sepr input))) - (do (vreset! started true) - (rf result input)))))))) - ([sep coll] - (drop 1 (interleave (repeat sep) coll)))) - -(defn take-nth - ([n] - (fn [rf] - (let [iv (volatile! -1)] - (fn - ([] (rf)) - ([result] (rf result)) - ([result input] - (let [i (vswap! iv inc)] - (if (zero? (rem i n)) - (rf result input) - result))))))) - ([n coll] - (lazy-seq - (when-let [s (seq coll)] - (cons (first s) (take-nth n (drop n s))))))) - -;; --- pmap family: parallel map over real-thread futures ---------------------- -;; Each element's work runs on its own OS thread with SNAPSHOT semantics -;; (futures marshal captured state — pure fns only, mutations don't propagate -;; back). All futures are spawned up front (doall), then derefed in order: -;; coarse-grained work only, as with Clojure's pmap. - -(defn pmap - ([f coll] - (map deref (doall (map (fn [x] (future (f x))) coll)))) - ([f coll & colls] - (pmap (fn [xs] (apply f xs)) (apply map vector coll colls)))) - -(defn pcalls [& fns] (pmap (fn [f] (f)) fns)) diff --git a/jolt-core/clojure/core/50-io.clj b/jolt-core/clojure/core/50-io.clj deleted file mode 100644 index 2d80196..0000000 --- a/jolt-core/clojure/core/50-io.clj +++ /dev/null @@ -1,213 +0,0 @@ -;; clojure.core — IO tier: the *in* reader family. -;; -;; *in* is a dynamic var holding a READER: a plain map whose two ops close -;; over their source — :read-line-fn (next line, newline -;; stripped, nil at EOF) and :read-fn (next FORM, advancing past exactly that -;; form; the eof sentinel at end of input). The default *in* reads real stdin -;; through the host seam __stdin-read-line, with a shared leftover buffer so -;; read and read-line interleave; with-in-str rebinds *in* to a string reader -;; over one atom-held buffer, so (read) consumes its form and a following -;; (read-line) returns the REST of that line — as in Clojure. -;; -;; Forms are parsed by the host seam __parse-next (one form + the rest of the -;; string, nil when only whitespace remains). Known wart shared with that -;; contract: input that is only a comment reads as nil rather than EOF. - -(def ^:private reader-eof :jolt/reader-eof) - -;; *in* is a Reader, not a map — so (map? *in*) is false, matching the JVM -;; (java.io.Reader). The reader is a reify over IReader (a non-map value, unlike -;; a defrecord which IS a map); read/read-line/read+string dispatch through its -;; methods. Each implementation closes over its own buffer atom: read may pull a -;; whole line to parse a form and hands the remainder to the next read/read-line. -(defprotocol IReader - (-read-line [rdr] "Next line, newline stripped; nil at EOF.") - (-read-form [rdr] "Next form; the reader-eof sentinel at end of input.") - (-read+string [rdr eof-error? eof-value] - "Next form plus the exact text consumed (leading whitespace included), as - [form text]. On EOF: throws, or returns [eof-value \"\"] when eof-error? is false.")) - -(defn __string-reader - "A reader over string s (the with-in-str expansion calls this)." - [s] - (let [buf (atom s)] - (reify IReader - (-read-line [_] - (let [cur @buf] - (when (pos? (count cur)) - (let [i (str-find "\n" cur)] - (if (nil? i) - (do (reset! buf "") cur) - (do (reset! buf (subs cur (inc i))) (subs cur 0 i))))))) - (-read-form [_] - (let [r (__parse-next @buf)] - (if (nil? r) - reader-eof - (do (reset! buf (nth r 1)) (nth r 0))))) - (-read+string [_ eof-error? eof-value] - (let [s @buf - r (__parse-next s)] - (if (nil? r) - (if eof-error? - (throw (ex-info "EOF while reading" {})) - [eof-value ""]) - (do (reset! buf (nth r 1)) - [(nth r 0) (subs s 0 (- (count s) (count (nth r 1))))]))))))) - -;; Real stdin, with a leftover buffer shared by read and read-line. -(def ^:private stdin-buf (atom "")) - -(def ^:dynamic *in* - (reify IReader - (-read-line [_] - (let [cur @stdin-buf] - (if (pos? (count cur)) - (let [i (str-find "\n" cur)] - (if (nil? i) - (do (reset! stdin-buf "") cur) - (do (reset! stdin-buf (subs cur (inc i))) (subs cur 0 i)))) - (__stdin-read-line)))) - (-read-form [_] - (loop [] - (let [r (__parse-next @stdin-buf)] - (if (nil? r) - (let [line (__stdin-read-line)] - (if (nil? line) - reader-eof - (do (swap! stdin-buf (fn [b] (str b line "\n"))) (recur)))) - (do (reset! stdin-buf (nth r 1)) (nth r 0)))))) - (-read+string [_ eof-error? eof-value] - (loop [] - (let [s @stdin-buf - r (__parse-next s)] - (if (nil? r) - (let [line (__stdin-read-line)] - (if (nil? line) - (if eof-error? - (throw (ex-info "EOF while reading" {})) - [eof-value ""]) - (do (swap! stdin-buf (fn [b] (str b line "\n"))) (recur)))) - (do (reset! stdin-buf (nth r 1)) - [(nth r 0) (subs s 0 (- (count s) (count (nth r 1))))]))))))) - -(defn read-line - "Reads the next line from the stream that is the current value of *in*. - Returns nil at EOF." - [] - (-read-line *in*)) - -(defn read - "Reads the next object from stream (defaults to *in*). At EOF, throws — - or returns eof-value when eof-error? is false." - ([] (read *in*)) - ([stream] - (let [v (-read-form stream)] - (if (= v reader-eof) - (throw (ex-info "EOF while reading" {})) - v))) - ([stream eof-error? eof-value] - (let [v (-read-form stream)] - (if (= v reader-eof) - (if eof-error? (throw (ex-info "EOF while reading" {})) eof-value) - v)))) - -(defmacro with-in-str - "Evaluates body with *in* bound to a fresh reader over string s." - [s & body] - `(binding [*in* (__string-reader ~s)] - ~@body)) - -(defn read+string - ([] (read+string *in*)) - ([stream] (read+string stream true nil)) - ([stream eof-error? eof-value] - (-read+string stream eof-error? eof-value))) - -(defn line-seq - "Returns the lines of text from rdr as a lazy sequence of strings, as by - read-line. (Jolt extension kept from the old kernel stub: a plain string - splits into its lines.)" - [rdr] - (if (string? rdr) - (seq (str-split "\n" rdr)) - (lazy-seq - (let [line (-read-line rdr)] - (when line - (cons line (line-seq rdr))))))) - -;; --- print-method ------------------------------------------------ -;; Canonical dispatch (clojure/core.clj 3693): the :type metadata when it's a -;; keyword, else the value's type. On jolt, type is the keyword tag for -;; builtins and the deftype name SYMBOL for records — so a record method is -;; (defmethod print-method 'ns.Type [r w] ...) (class names aren't values -;; here, the quoted full name is the dispatch value). -;; -;; The :default renders through the host's fast printer. The host renderer -;; calls BACK into this table for records (the api wires the hook after the -;; overlay loads), so a record method fires nested inside collections too. -;; Builtin overrides (e.g. a :number method) fire only when print-method is -;; called directly — pr/pr-str keep the native fast path for builtins (a -;; documented jolt divergence). -(defmulti print-method (fn [x writer] - (let [t (get (meta x) :type)] - (if (keyword? t) t (__type-tag x))))) - -(defmethod print-method :default [o w] - (.write w (__pr-str1 o)) - nil) - -;; print-dup: jolt has one print representation, so dup routes to print-method -;; (as Clojure's default does for most types). -(defmulti print-dup (fn [x writer] - (let [t (get (meta x) :type)] - (if (keyword? t) t (__type-tag x))))) - -(defmethod print-dup :default [o w] (print-method o w)) - -;; Cold tagged-type renderings, migrated from the host renderer (the hot -;; types — numbers, strings, symbols, collections — stay native). Each is the -;; exact output the host branch produced. -(defmethod print-method :jolt/uuid [u w] - (.write w (str "#uuid \"" (get u :str) "\"")) - nil) - -(defmethod print-method :jolt/regex [re w] - (.write w (str "#\"" (get re :source) "\"")) - nil) - -;; a transient's get IS the dispatched collection lookup — read the wrapper's -;; own :kind field with the host accessor (same trap as sorted colls). -(defmethod print-method :jolt/transient [t w] - (.write w (str "#")) - nil) - -(defmethod print-method :jolt/chan [c w] - (.write w "#") - nil) - -;; Minimal synchronous agent shim. jolt has no thread pool or STM, so this is -;; enough for libraries that hold an agent but don't depend on asynchronous -;; dispatch (e.g. clojure.tools.logging's *logging-agent*, which only sends from -;; within a transaction — never the case here, so it always logs directly). An -;; agent is an atom; send/send-off apply the action immediately. NOT concurrent. -(defn agent - "Creates an agent (an atom on jolt — synchronous, no async dispatch)." - [state & _opts] - (atom state)) - -(defn send-off - "Apply (action state & args) to the agent's state immediately; return the agent." - [a f & args] - (apply swap! a f args) - a) - -(defn send - "Like send-off on jolt (no separate thread pool)." - [a f & args] - (apply swap! a f args) - a) - -(defn agent-error - "jolt agents never enter an error state." - [_a] - nil) diff --git a/jolt-core/clojure/core/MIGRATION.md b/jolt-core/clojure/core/MIGRATION.md new file mode 100644 index 0000000..ef14f59 --- /dev/null +++ b/jolt-core/clojure/core/MIGRATION.md @@ -0,0 +1,96 @@ +# clojure.core migration worklist (jolt-1j0) + +Tracking the move of clojure.core from native Janet (`src/jolt/core.janet`, +4145 lines / 421 `core-*` fns) into the self-hosted Clojure overlay +(`jolt-core/clojure/core/`). Goal: shrink the Janet seed to `core-renames` + +genuinely host-coupled fns. + +## Phase 0 classification (heuristic — validate per batch) + +| Bucket | Count | Disposition | +|---|---|---| +| SEED (in `compiler/core-renames`) | 73 | stay in Janet (compiler emits `core-X` directly) | +| MACRO (in `core-macro-names`) | 44 | Phase 3 | +| HOST-coupled (atoms/vars/meta/proxy/transient/arrays/futures/ns/io) | 80 | Phase 4 (where feasible) / stay | +| LAZY-coupled | 28 | Phase 5 | +| MOVABLE pure-eager (candidates) | 193 | **Phase 2** | + +Counts are heuristic (name + body markers); the MOVABLE list still has some +host/lazy leakage (e.g. transient `assoc!`/`conj!`, `doall`/`dorun`, +`chunk-*`, `deliver`) to filter out as each batch is actually moved. + +**Key finding:** after removing SEED + HOST, the self-hosted compiler +(`jolt-core/jolt/{ir,analyzer}.clj`) uses **no** additional clojure.core fns +beyond the kernel tier (`second`/`peek`/`subvec`/`mapv`/`update`) plus host +primitives (`atom`/`swap!`/`reset!`). So **Phase 1 (compiler-dep kernel tier) +is essentially already complete** — to verify, not build. + +## Performance baseline (test/bench/core-bench.janet, compile mode, min of 5, ms) + +| bench | ms | +|---|---| +| fib | 128 | +| seq-pipe | 88 | +| reduce | 391 | +| into-vec | 194 | +| map-build | 681 | +| map-read | 6 | +| str-join | 244 | +| hof | 604 | +| **TOTAL** | **2336** | + +Re-run after each phase; watch for regressions as fns move from native Janet to +self-hosted Clojure (interpreted/compiled, slower than native primitives). + +## Per-batch workflow + gate (every migration step) +1. Canonical Clojure def in the overlay tier; remove the Janet `core-X` defn + + its `core-bindings` entry (confirm leaf first: only defn+binding refs). +2. **Add regression tests** for each moved fn — spec cases (test/spec/*-spec.janet, + interpret) and, for any fn whose behavior is subtle or was buggy, a case in the + 3-mode conformance set (test/integration/conformance-test.janet). +3. Gate: conformance ×3 modes · clojure-test-suite ≥ baseline · stage2==stage3 + fixpoint · fib compiled-fast · core-bench A/B under identical load (the + absolute number is load-sensitive — compare batch-vs-prior back to back). + +If a moved fn surfaces a latent bug (e.g. nthrest's nil-vs-() result, the +if-let/when-let else-scope leak), fix it to match Clojure and add a regression +test, rather than preserving the bug. + +## MOVABLE candidates (Phase 2 worklist, 193) +>Eduction NaN? abs aclone alength ancestors array-map array-seq assoc! associative? bean bigdec bigint biginteger boolean boolean? booleans byte bytes bytes? cat char char-escape-string char-name-string char? chars chunk chunk-append chunk-buffer chunk-cons chunk-first chunk-next chunk-rest chunked-seq? class clojure-version comparator compare-and-set! completing conj! counted? decimal? deliver denominator derive descendants destructure disj disj! dissoc! distinct? doall dorun double? doubles drop-last eduction empty ensure-reduced enumeration-seq ex-cause ex-data ex-info ex-info? ex-message find float? floats force halt-when hash-combine hash-map hash-ordered-coll hash-set hash-unordered-coll ident? ifn? indexed? infinite? inst-ms inst? integer? ints isa? iterator-seq key keyword keyword-identical? list* list? longs macrofy map-entry? memfn munge nat-int? neg-int? not-any? not-every? nthnext nthrest numerator numeric= object? parents persistent! pop pop! pos-int? pr prefers println-str prn-str promise qualified-ident? qualified-keyword? qualified-symbol? rand rand-nth random-sample ratio? rational? rationalize re-groups re-matcher record? reduce-kv reduced reduced? reductions replace replicate resolve reversible? rseq rsubseq run! seq-to-map-for-destructuring seque set set? short shorts shuffle simple-ident? simple-keyword? simple-symbol? some-search sort sort-by sorted-map sorted-map-by sorted-map? sorted-set sorted-set-by sorted-set? special-symbol? split-at split-with str-join str-replace-all str-replace-first str-split subseq supers symbol tagged-literal tagged-literal? take-last test transduce unchecked-add unchecked-byte unchecked-char unchecked-dec unchecked-divide-int unchecked-double unchecked-float unchecked-inc unchecked-int unchecked-multiply unchecked-negate unchecked-remainder-int unchecked-short unchecked-subtract undefined? underive uri? uuid? val vector volatile! volatile? xml-seq + +## HOST-coupled (Phase 4 / stay, 80) +add-watch aget alter-meta! alter-var-root aset aset-boolean aset-byte aset-char aset-double aset-float aset-int aset-long aset-short atom atom? avoid-method-too-large boolean-array bounded-count byte-array char-array construct-proxy copy-core-var copy-var delay? deref double-array float-array future-call future-cancel future-cancelled? future-done? future? get-proxy-class get-validator init-proxy int-array intern into-array long-array make-array make-delay meta namespace namespace-munge new-var ns-name object-array pop-thread-bindings prefer-method print-dup print-method print-str proxy-call-with-super proxy-mappings proxy-super push-thread-bindings reader-conditional reader-conditional? remove-watch reset! reset-meta! reset-vals! set-validator! short-array swap! swap-vals! thread-first thread-last to-array to-array-2d transient transient? update-proxy var-dynamic? var-get var-set var? vary-meta vreset! vswap! with-meta + +## LAZY-coupled (Phase 5, 28) +concat cycle dedupe distinct flatten interleave interpose iterate keep keep-indexed line-seq macro-names map-indexed mapcat partition partition-all partition-by rand-int random-uuid realized? repeat repeatedly seqable? sequence sequential? take-nth trampoline tree-seq unreduced + +## Phase 3 (macros) — status & findings + +20 macros moved to the overlay: 19 user-facing in `30-macros.clj`, plus `when` +in a new `00-syntax.clj` tier loaded **before** the kernel (interpreted defmacros, +so the macros exist before any code that uses them compiles). + +Macro-authoring toolkit for jolt (learned the hard way): +- single-template hygiene: auto-gensym `foo#` +- shared explicit fresh symbol: `(symbol (str (gensym)))` — a bare `(gensym)` in a + macro body returns a *Janet* symbol the destructurer rejects +- let-rebinding: splice binding *pairs* into a TEMPLATE vector (`[~a ~b ~@pairs]`), + not a pre-built pvec value — `core-let` wants a tuple form +- build sub-forms via templates, never `cons`/`list` (those make plists the + evaluator can't run as a form) +- Jolt `defmacro` is **single-arity** — use `& rest`/destructuring +- syntax-tier macros may use only special forms + core-renames seed primitives + +**Performance wall (the hot macros stay in Janet for now):** the load-order story +works, but moving the *hot* fundamental control macros (`and`/`or`/`cond`/ +`when-not`) regressed the battery — as interpreted overlay defmacros they expand +slower than native Janet, and since they appear in nearly every form the +cumulative overhead tipped a heavy suite file over the 6 s per-file timeout +(3930 -> 3911, +1 timeout). They are correct (conformance 228×3, all edge cases), +but reverted. Moving `and/or/cond/when-not/case/doseq/declare/cond->/->/->>` +needs a **fast (compiled) macro-expansion path**, not interpreted defmacros. + +Deferred: `defn/defn-/fn/let/loop` (fundamental + same speed concern), the type +machinery (`defrecord/defprotocol/extend-*/reify/proxy/definterface` → Phase 4), +`lazy-seq/lazy-cat` (→ Phase 5). diff --git a/jolt-core/jolt/analyzer.clj b/jolt-core/jolt/analyzer.clj index b8c2016..66ac5e7 100644 --- a/jolt-core/jolt/analyzer.clj +++ b/jolt-core/jolt/analyzer.clj @@ -1,13 +1,13 @@ (ns jolt.analyzer "Portable Clojure analyzer: reader form -> host-neutral IR (see jolt.ir). - Depends only on the host contract (jolt.host) and IR - constructors (jolt.ir). The contract fns are referred unqualified + Pure jolt-core — depends only on the host contract (jolt.host) and IR + constructors (jolt.ir), never on Janet. The contract fns are referred unqualified (host form predicates are `form-*` to avoid colliding with clojure.core), so the bootstrap can compile this namespace via its plain :var path. ctx is an opaque host handle threaded to the contract fns; the analyzer never inspects it. - Unsupported forms throw :jolt/uncompilable + Coverage grows toward compiler.janet; unsupported forms throw :jolt/uncompilable so the caller falls back to the interpreter (the hybrid contract). `env` carries lexical state: {:locals #{names} :recur recur-target-name|nil}. @@ -16,31 +16,19 @@ them to one keeps the compiled namespace simple." (:require [jolt.ir :refer [const local var-ref the-var host-ref if-node do-node invoke def-node let-node fn-node vector-node map-node set-node - quote-node throw-node host-static host-new]] + quote-node throw-node]] [jolt.host :refer [form-sym? form-sym-name form-sym-ns form-list? - form-vec? form-map? form-set? - form-literal? form-keyword? form-elements form-vec-items + form-vec? form-map? form-set? form-char? + form-literal? form-elements form-vec-items form-map-pairs form-set-items form-special? compile-ns - form-regex? form-regex-source - form-inst? form-inst-source form-uuid? form-uuid-source - form-bigdec? form-bigdec-source - form-ns-value? form-ns-value-name - form-var-value? form-var-value-ns form-var-value-name - unchecked-math? form-macro? form-expand-1 resolve-global - form-sym-meta form-coll-meta host-intern! form-syntax-quote-lower - record-type? record-ctor-key deftype-ctor-class form-position late-bind? - resolve-class-hint]])) + form-sym-meta host-intern! form-syntax-quote-lower]])) (declare analyze) -;; Special forms analyze-special has a dispatch arm for — the subset of the host -;; contract's reserved words (jolt.host/form-special?) the analyzer lowers itself. -;; The two differ deliberately (e.g. interop heads like `new`/`.` are reserved but -;; analyzed in analyze-list), so keep them in sync by intent, not by equality. (def ^:private handled #{"quote" "if" "do" "def" "fn*" "let*" "loop*" "recur" "throw" "try" - "syntax-quote" "var" "letfn*" "set!" "defmacro"}) + "syntax-quote" "var"}) (defn- uncompilable [why] (throw (str "jolt/uncompilable: " why))) @@ -51,62 +39,11 @@ (swap! gensym-counter inc) (str "_r$" prefix n))) -(defn- empty-env [] {:locals #{} :hints {}}) +(defn- empty-env [] {:locals #{}}) (defn- local? [env nm] (contains? (:locals env) nm)) (defn- add-locals [env names] (update env :locals #(reduce conj % names))) -;; &env value handed to a macro: a map of each in-scope local SYMBOL to nil -;; (Clojure's &env maps locals to compiler binding objects; consumers like -;; core.logic's matche only read its keys to tell locals from fresh pattern vars). -(defn- amp-env-map [env] - (reduce (fn [m n] (assoc m (symbol n) nil)) {} (:locals env))) (defn- with-recur [env name] (assoc env :recur name)) -;; Type hints. The reader keeps ^hint metadata on the binding symbol. -;; Two hints resolve to the :struct fast path (a constant-keyword lookup skips -;; the :jolt/type guard and emits a bare get): ^:struct (a plain struct/record -;; map) and ^TypeName where TypeName is a defrecord/deftype (its instances are -;; tagged :jolt/deftype, not :jolt/type, so a raw get is correct). Every other -;; hint (^String, ^long, ...) parses and is ignored, as before. -(defn- hint-of [ctx sym] - (let [m (form-sym-meta sym)] - (cond - (nil? m) nil - (get m :struct) :struct - :else (let [t (get m :tag)] - (when (and t (record-type? ctx t)) :struct))))) -(defn- add-hint [env nm h] - (if h (assoc env :hints (assoc (:hints env) nm h)) env)) - -;; The resolved record ctor-key ("ns/->Name") for a ^Type param hint, or nil. -;; Unlike hint-of (which collapses any record hint to the coarse :struct guard- -;; skip marker), this carries the SPECIFIC record type — cross-namespace aware — -;; so the inference can seed the param's type and read its fields shaped/typed, -;; not just :any (the lever for a typed multi-namespace program without whole- -;; program inference). -(defn- phint-of [ctx sym] - (let [m (form-sym-meta sym)] - (when m (let [t (get m :tag)] (when t (record-ctor-key ctx t)))))) - -;; A ^long / ^double tag -> :long / :double, else nil. The tag is a string on the -;; data reader; tolerate a symbol from macroexpansion too. -(defn- tag->nkind [t] - (let [s (cond (form-sym? t) (form-sym-name t) (string? t) t :else nil)] - (cond (= s "double") :double (= s "long") :long :else nil))) - -;; A primitive numeric hint (^long / ^double) on a binding symbol. Drives the -;; fl*/fx* fast path (jolt.passes.numeric). -(defn- nhint-of [ctx sym] - (let [m (form-sym-meta sym)] (when m (tag->nkind (get m :tag))))) - -;; Push a numeric return hint (from ^double/^long on a defn's name) onto each arity -;; of its fn, so the back end coerces the body's value to that kind on return — -;; making the hint a contract a caller's arithmetic can trust. -(defn- with-ret-nhint [node kind] - (if (and kind (= :fn (:op node))) - (assoc node :arities (mapv (fn [a] (if (:ret-nhint a) a (assoc a :ret-nhint kind))) - (:arities node))) - node)) - (defn- analyze-seq [ctx forms env] (let [v (mapv #(analyze ctx % env) forms) n (count v)] @@ -122,95 +59,42 @@ (when-not (form-sym? bsym) (uncompilable "destructuring binding")) (let [nm (form-sym-name bsym) init (analyze ctx (nth bvec (inc i)) env)] - (recur (+ i 2) (add-hint (add-locals env [nm]) nm (hint-of ctx bsym)) - (conj pairs [nm init])))) + (recur (+ i 2) (add-locals env [nm]) (conj pairs [nm init])))) [pairs env]))) -(defn- parse-params [ctx pvec] - ;; :hints is a vector of [name hint] pairs (vector, not a map, so the caller - ;; folds it with a plain reduce — no reduce-over-map in the kernel subset). - ;; :phints is the parallel vector of [name ctor-key] for record param hints, - ;; carrying the specific type for the inference to seed. - (loop [i 0 fixed [] rest-name nil hints [] phints [] nhints []] +(defn- parse-params [pvec] + (loop [i 0 fixed [] rest-name nil] (if (< i (count pvec)) (let [p (nth pvec i)] (when-not (form-sym? p) (uncompilable "destructuring fn param")) (if (= "&" (form-sym-name p)) (let [r (nth pvec (inc i))] (when-not (form-sym? r) (uncompilable "destructuring fn rest")) - (recur (+ i 2) fixed (form-sym-name r) hints phints nhints)) - (let [nm (form-sym-name p) h (hint-of ctx p) ph (phint-of ctx p) nh (nhint-of ctx p)] - (recur (inc i) (conj fixed nm) rest-name - (if h (conj hints [nm h]) hints) - (if ph (conj phints [nm ph]) phints) - (if nh (conj nhints [nm nh]) nhints))))) - {:fixed fixed :rest rest-name :hints hints :phints phints :nhints nhints}))) - -;; Clojure lets a later param shadow an earlier same-named one (a macro expander -;; uses _ for both its &form and &env slots, so its param list is (_ _ …)); the -;; body binds the LAST occurrence. Chez rejects duplicate formals, so rename every -;; earlier duplicate to a fresh name — it is shadowed and unreferenceable. -(defn- uniquify-params [names] - (let [n (count names)] - (loop [i 0 out []] - (if (< i n) - (let [nm (nth names i) - dup? (loop [j (inc i)] - (cond (>= j n) false - (= nm (nth names j)) true - :else (recur (inc j))))] - (recur (inc i) (conj out (if dup? (gen-name (str nm "_")) nm)))) - out)))) + (recur (+ i 2) fixed (form-sym-name r))) + (recur (inc i) (conj fixed (form-sym-name p)) rest-name))) + {:fixed fixed :rest rest-name}))) (defn- analyze-arity [ctx pvec body env fn-name] - (let [pp (parse-params ctx (vec (form-vec-items pvec))) - fixed (uniquify-params (:fixed pp)) + (let [pp (parse-params (vec (form-vec-items pvec))) + fixed (:fixed pp) rst (:rest pp) ;; Always a recur target, variadic included: the back end gives the rest ;; param an ordinary positional slot (holding the collected seq), so recur ;; is a self-call carrying the rest seq directly — Clojure semantics. - ;; The recur target doubles as the COMPILED FN'S NAME, which is what a - ;; host stack trace shows — so carry the Clojure ns/fn-name: - ;; an error inside app.deep/level3 traces as _r$app.deep/level3--N - ;; (report-error demangles the _r$/--N wrapper). gen-name's counter - ;; keeps recur targets unique per compilation unit. - rname (gen-name (str (compile-ns ctx) "/" (or fn-name "fn") "--")) + rname (gen-name "arity") names (cond-> (vec fixed) rst (conj rst) fn-name (conj fn-name)) - env0 (-> (add-locals env names) (with-recur rname)) - env* (reduce (fn [e pr] (add-hint e (nth pr 0) (nth pr 1))) env0 (:hints pp)) + env* (-> (add-locals env names) (with-recur rname)) arity {:params fixed :recur-name rname - :body (analyze-seq ctx body env*)} - ;; carry record param hints (name -> ctor-key) for the inference to seed - ;; the param type; only when present so a hintless arity stays a struct. - arity (if (seq (:phints pp)) (assoc arity :phints (:phints pp)) arity) - ;; numeric param hints (name -> :long/:double) for jolt.passes.numeric. - arity (if (seq (:nhints pp)) (assoc arity :nhints (:nhints pp)) arity)] + :body (analyze-seq ctx body env*)}] ;; :rest only when variadic — an absent :rest reads back nil, same as before, ;; but keeps a fixed arity a nil-free struct rather than a phm. (if rst (assoc arity :rest rst) arity))) -;; A reader that lowers ^meta on a collection to a runtime (with-meta ) -;; form (the Chez data reader) wraps an arglist vector carrying a return-type hint -;; (^bytes [b] / ^String [x y]). Unwrap to the underlying vector so fn parsing sees -;; the params — the hint is ignored at runtime. Only the (with-meta _) shape -;; matches, so a real arity clause (head is a vector) and a -;; meta-on-vector arglist pass through unchanged. -(defn- strip-arglist-meta [form] - (if (form-list? form) - (let [es (vec (form-elements form))] - (if (and (= 3 (count es)) - (form-sym? (first es)) - (= "with-meta" (form-sym-name (first es))) - (form-vec? (nth es 1))) - (nth es 1) - form)) - form)) - (defn- analyze-fn [ctx items env] (let [named (form-sym? (nth items 1)) fn-name (when named (form-sym-name (nth items 1))) rest-items (if named (drop 2 items) (drop 1 items)) - first* (strip-arglist-meta (first rest-items))] + first* (first rest-items)] (cond (form-vec? first*) (fn-node fn-name [(analyze-arity ctx first* (rest rest-items) env fn-name)]) @@ -218,18 +102,15 @@ (fn-node fn-name (mapv (fn [clause] (let [cl (vec (form-elements clause))] - (analyze-arity ctx (strip-arglist-meta (first cl)) (rest cl) env fn-name))) + (analyze-arity ctx (first cl) (rest cl) env fn-name))) rest-items)) :else (uncompilable "fn: bad params")))) -;; class names that catch everything (the JVM root types); a (catch Throwable e …) -;; clause matches any thrown value unconditionally. -(def ^:private catch-all-names #{"Throwable" "java.lang.Throwable" "Object" "java.lang.Object"}) - (defn- analyze-try [ctx items env] (let [clauses (rest items) body (atom []) - catches (atom []) ; ordered vector of (catch class binding body*) clauses + catch-sym (atom nil) + catch-body (atom nil) finally-body (atom nil)] (doseq [c clauses] (let [head (when (form-list? c) (first (vec (form-elements c)))) @@ -237,187 +118,33 @@ (cond (= hname "catch") (let [cl (vec (form-elements c))] - ;; (catch class binding body*) — binding (3rd elem) MUST be a symbol. - ;; Validate eagerly (plain throw, NOT uncompilable, so it's a real - ;; error rather than a compile->interpret punt) instead of letting - ;; form-sym-name crash on a non-symbol. - (when (or (< (count cl) 3) (not (form-sym? (nth cl 2)))) - (throw "Unable to parse catch clause; expected (catch class binding body*)")) - (swap! catches conj cl)) + (reset! catch-sym (form-sym-name (nth cl 2))) + (reset! catch-body (drop 3 cl))) (= hname "finally") (reset! finally-body (rest (vec (form-elements c)))) :else (swap! body conj c)))) - ;; Multiple catch clauses dispatch on the thrown value's class, in order. Lower - ;; them to ONE guard binding a fresh local, then a nested-if chain testing each - ;; clause's class with (instance? C e) — which respects the exception supertype - ;; hierarchy — plus __catch-broad? for an untyped host condition. No match - ;; re-throws. (The earlier single-catch IR ignored the class and caught - ;; everything; this gives real per-class dispatch.) :catch-sym/:catch-body/ - ;; :finally are added only when present — an absent key must stay absent (a - ;; nil-valued key would make the node a phm and force back-end densification). - (let [n {:op :try :body (analyze-seq ctx @body env)} - n (if (seq @catches) - (let [evar-name (gen-name "catch") - raw-name (gen-name "catch-raw") - evar (symbol evar-name) - dispatch - (reduce - (fn [else cl] - (let [cform (nth cl 1) - bindsym (nth cl 2) - bodyf (drop 3 cl) - letform (cons 'let (cons (vector bindsym evar) bodyf)) - fullname (when (form-sym? cform) (form-sym-name cform)) - catch-all? (or (not (form-sym? cform)) - (contains? catch-all-names fullname))] - (if catch-all? - letform - (list 'if (list 'or - (list 'instance? cform evar) - (list '__catch-broad? fullname evar)) - letform else)))) - (list 'throw evar) - (reverse @catches))] - (assoc n :catch-sym evar-name - :catch-raw-sym raw-name - :catch-body (analyze-seq ctx (list dispatch) - (add-locals env [evar-name])))) - n) - n (if @finally-body - (assoc n :finally (analyze-seq ctx @finally-body env)) - n)] - n))) - -;; letfn*: (letfn* [name1 fn1 name2 fn2 …] body*) — the special form Clojure's -;; letfn macro expands to (flat name/fn-form pairs, the fn forms already named). -;; The named local fns are MUTUALLY recursive, so bind every name into the env -;; BEFORE analyzing any fn form — each then resolves its siblings (and itself) as -;; locals. Emitted as a :let flagged :letrec so the back end lowers it to -;; `letrec*`; the interpreter's shared mutable env gives the same semantics. -(defn- analyze-letfn* [ctx items env] - (let [bvec (vec (form-vec-items (nth items 1))) - n (quot (count bvec) 2) - names (mapv (fn [i] (form-sym-name (nth bvec (* 2 i)))) (range n)) - env* (add-locals env names) - binds (mapv (fn [i] - [(nth names i) - (analyze ctx (nth bvec (inc (* 2 i))) env*)]) - (range n))] - {:op :let :letrec true :bindings binds - :body (analyze-seq ctx (drop 2 items) env*)})) - -;; A `.-field` head: `(.-field target)` is field access (the dash signals field -;; access to the host-call dispatcher). Defined above analyze-special so its set! -;; arm and analyze-list both reach it without a forward reference. -(defn- field-head? [nm] - (and (> (count nm) 2) (= ".-" (subs nm 0 2)))) - -;; Clojure evaluates def metadata values as expressions: ^{:k (f)} stores the -;; result of (f), ^{:a some-fn} stores the fn value. Build an IR map that evaluates -;; each value at def time. :tag keeps the resolved class-name string (jolt models a -;; type hint as its class name, not a runtime expression). nil when there's no -;; metadata, so a plain def keeps the cheap static path. -(defn- def-meta-expr [ctx base env] - (when (pos? (count base)) - (map-node (mapv (fn [p] - (let [k (first p) v (second p)] - ;; :tag stays a literal (a resolved class-name string or a - ;; primitive-hint symbol like `double`) — quote it rather - ;; than evaluate it. Everything else is evaluated. - [(const k) - (if (= k :tag) (quote-node v) (analyze ctx v env))])) - (seq base))))) - -(defn- analyze-def [ctx items env] - (let [name-sym (nth items 1)] - ;; ^{:map} metadata reads as (def (with-meta name m) v): the metadata is a - ;; runtime expression, so the interpreter evaluates the whole def. - (when-not (form-sym? name-sym) - (uncompilable "def name with map metadata")) - (if (< (count items) 3) - ;; (def name) with no init (declare): intern + reserve the cell so a forward - ;; reference resolves; the back end keys on :no-init. - (let [nm (form-sym-name name-sym) cur (compile-ns ctx)] - (host-intern! ctx cur nm) - {:op :def :ns cur :name nm :no-init true}) - ;; (def name docstring value): docstring is form 2, value form 3 — matching - ;; the interpreter, else the docstring is taken as the value. - (let [nm (form-sym-name name-sym) - cur (compile-ns ctx) - has-doc (and (> (count items) 3) (string? (nth items 2))) - val-form (nth items (if has-doc 3 2)) - base0 (or (form-sym-meta name-sym) {}) - ;; resolve a ^Type hint to its canonical class name at def time, as the - ;; JVM compiler does (^String -> java.lang.String); unknown hints pass. - tag (get base0 :tag) - tag-name (cond (form-sym? tag) (form-sym-name tag) - (string? tag) tag - :else nil) - base-meta (if tag-name - (let [c (resolve-class-hint tag-name)] - (if c (assoc base0 :tag c) base0)) - base0) - node-meta (if has-doc (assoc base-meta :doc (nth items 2)) base-meta)] - (host-intern! ctx cur nm) - ;; a ^double/^long return hint on the name applies to all arities of the fn. - (let [node (def-node cur nm (with-ret-nhint (analyze ctx val-form env) (tag->nkind tag)) node-meta) - me (def-meta-expr ctx node-meta env)] - (if me (assoc node :meta-expr me) node)))))) - -;; (set! (.-field obj) v) mutates a deftype instance field in place; (set! *var* v) -;; sets the var's innermost thread binding, else its root. A local target (jolt -;; binds fields immutably) or any other shape is uncompilable. -(defn- analyze-set! [ctx items env] - (let [target (nth items 1) - val-node (analyze ctx (nth items 2) env) - ti (when (form-list? target) (vec (form-elements target))) - thead (when (and ti (pos? (count ti)) (form-sym? (first ti))) - (form-sym-name (first ti)))] - (cond - (and thead (field-head? thead)) - {:op :set-field :obj (analyze ctx (nth ti 1) env) - :field (subs thead 2) :val val-node} - ;; (set! (. Class member) val) — a host static-field set. clojure.spec.alpha - ;; toggles clojure.lang.RT/checkSpecAsserts this way. Lowered to a runtime - ;; jolt.host/set-static-field! call (the read side is a :host-static ref). - (and (= thead ".") (>= (count ti) 3) (form-sym? (nth ti 1)) (form-sym? (nth ti 2)) - (= :class (:kind (resolve-global ctx (nth ti 1))))) - (invoke (var-ref "jolt.host" "set-static-field!") - [(const (:name (resolve-global ctx (nth ti 1)))) - (const (form-sym-name (nth ti 2))) val-node]) - (form-sym? target) - (do (when (local? env (form-sym-name target)) (uncompilable "set! of a local")) - (let [r (resolve-global ctx target)] - (when-not (= :var (:kind r)) (uncompilable "set! of a non-var")) - {:op :set-var :the-var (the-var (:ns r) (:name r)) :val val-node})) - :else (uncompilable "set! of an unsupported target")))) + {:op :try + :body (analyze-seq ctx @body env) + :catch-sym @catch-sym + :catch-body (when @catch-body + (analyze-seq ctx @catch-body (add-locals env [@catch-sym]))) + :finally (when @finally-body (analyze-seq ctx @finally-body env))})) (defn- analyze-special [ctx op items env] (case op - ;; A quoted collection keeps its USER metadata (rewrite-clj coerces - ;; '^:x (4 5 6) and expects the meta back), but not the reader's location keys - ;; (:line/:column/:file) — like Clojure, which strips those from a quoted - ;; constant. The kept metadata is itself part of the literal, so quote it. - "quote" (let [qf (second items) - m (form-coll-meta qf) - m (when (map? m) - (let [u (dissoc m :line :column :end-line :end-column :file)] - (when (seq u) u)))] - (if (nil? m) - (quote-node qf) - (invoke (var-ref "clojure.core" "with-meta") [(quote-node qf) (quote-node m)]))) - "if" (do - ;; 2 or 3 argument forms only (spec 03-special-forms X1) - (when (or (< (count items) 3) (> (count items) 4)) - (throw (str "Wrong number of args (" (dec (count items)) ") passed to: if"))) - (if-node (analyze ctx (nth items 1) env) - (analyze ctx (nth items 2) env) - (if (> (count items) 3) - (analyze ctx (nth items 3) env) - (const nil)))) + "quote" (quote-node (second items)) + "if" (if-node (analyze ctx (nth items 1) env) + (analyze ctx (nth items 2) env) + (if (> (count items) 3) + (analyze ctx (nth items 3) env) + (const nil))) "do" (analyze-seq ctx (rest items) env) "throw" (throw-node (analyze ctx (nth items 1) env)) - "def" (analyze-def ctx items env) + "def" (let [name-sym (nth items 1) + nm (form-sym-name name-sym) + cur (compile-ns ctx)] + (host-intern! ctx cur nm) + (def-node cur nm (analyze ctx (nth items 2) env) (form-sym-meta name-sym))) "let*" (let [bvec (vec (form-vec-items (nth items 1))) r (analyze-bindings ctx bvec env)] (let-node (first r) (analyze-seq ctx (drop 2 items) (second r)))) @@ -432,7 +159,6 @@ {:op :recur :recur-name rt :args (mapv #(analyze ctx % env) (rest items))}) "try" (analyze-try ctx items env) - "letfn*" (analyze-letfn* ctx items env) "fn*" (analyze-fn ctx items env) ;; Lower the backtick to construction code (zero runtime cost), then analyze ;; it — the macroexpand/compile-time step, per read -> macroexpand -> compile. @@ -442,200 +168,21 @@ (if (= :var (:kind r)) (the-var (:ns r) (:name r)) (uncompilable (str "var of non-var " (form-sym-name sym))))) - ;; (set! *var* val): set the var's innermost thread binding, else its root - ;; (jolt-var-set). A local target is a deftype mutable field — not yet - ;; supported (jolt binds fields immutably); an interop (.-field) target too. - ;; A defmacro that is not top-level (the spine intercepts those) — e.g. one - ;; produced by a macro like (when … (defmacro …)). Lower it the way the spine - ;; does: def the expander fn, then mark the var a macro at runtime so later - ;; forms expand it. Strip a leading docstring / attr-map, as defmacro allows. - "defmacro" (let [name-sym (nth items 1) - nm (form-sym-name name-sym) - cur (compile-ns ctx) - after (drop 2 items) - after (if (string? (first after)) (rest after) after) - after (if (form-map? (first after)) (rest after) after) - ;; build (fn params body…) and analyze it through the fn MACRO - ;; so a destructuring macro arglist desugars (the fn* primitive - ;; would not), then def it and mark the var a macro. - fn-form (cons (symbol "fn") after)] - (host-intern! ctx cur nm) - {:op :defmacro :ns cur :name nm - :fn (analyze ctx fn-form env)}) - "set!" (analyze-set! ctx items env) (uncompilable (str "special form " op)))) -;; Host interop method call. `(.method target arg*)` — a head that -;; starts with "." but not ".-" (field access stays punted). Analyzes to a -;; :host-call node; the Chez back end lowers it to a jolt-host-call dispatch. -(defn- method-head? [nm] - (and (> (count nm) 1) - (= "." (subs nm 0 1)) - (not (= "-" (subs nm 1 2))) ; .-field is field access - (not (= "." (subs nm 1 2))))) ; .. is the threading macro, not .method - -(defn- analyze-host-call [ctx hname items env] - (when (< (count items) 2) - (throw (str "Malformed member expression, expecting (.method target ...): " hname))) - {:op :host-call - :method (subs hname 1) - :target (analyze ctx (nth items 1) env) - :args (mapv #(analyze ctx % env) (drop 2 items))}) - -;; A constructor head: `Class.` — a symbol ending in "." (but not the member -;; access `.method` / `..` forms). `(Class. args*)` builds an instance. -(defn- ctor-head? [nm] - (and (> (count nm) 1) - (= "." (subs nm (dec (count nm)) (count nm))) - (not (= "." (subs nm 0 1))))) - -;; `(Class. args*)` and `(new Class args*)` -> a :host-new node carrying the class -;; token and the analyzed args. The Chez back end lowers it to a runtime -;; constructor dispatch. -(defn- analyze-ctor [ctx class args env] - ;; Qualify a bare (Name. …) to its deftype's FQN when THIS ns defined the deftype, - ;; so a deftype named like a built-in host class (tools.reader's PushbackReader) - ;; resolves to the deftype here while an unrelated ns's bare (PushbackReader. …) - ;; still reaches java.io.PushbackReader. - (host-new (or (deftype-ctor-class ctx class) class) - (mapv #(analyze ctx % env) args))) - -;; jolt.ffi/__cfn: the low-level foreign-function form a jolt library -;; uses (via the jolt.ffi/foreign-fn macro) to bind native code. Shape: -;; (jolt.ffi/__cfn "c_symbol" [:argtype ...] :rettype) ; non-blocking -;; (jolt.ffi/__cfn "c_symbol" [:argtype ...] :rettype :blocking) ; may block -;; The C symbol is a string literal and the types are literal keywords, read here -;; at compile time; the Chez back end lowers it to a real `foreign-procedure` -;; (typed marshaling, no runtime eval). A :blocking call is emitted __collect_safe -;; so it deactivates the thread for the call — a blocking call (accept/recv/...) -;; must not pin the stop-the-world collector. A leaf IR node. -(defn- analyze-ffi-fn [ctx items env] - (when-not (<= 4 (count items) 5) - (throw (str "jolt.ffi/foreign-fn expects (foreign-fn \"sym\" [argtypes] rettype [:blocking])"))) - {:op :ffi-fn - :csym (nth items 1) - :argtypes (mapv name (form-vec-items (nth items 2))) - :rettype (name (nth items 3)) - :blocking (and (= 5 (count items)) (= "blocking" (name (nth items 4))))}) - -;; jolt.ffi/__ccallable: the foreign-CALLBACK form (via the jolt.ffi/foreign-callable -;; macro) — the inverse of __cfn. It wraps a jolt fn as a C-callable function -;; pointer so C can call back INTO jolt (GTK signal handlers, qsort comparators). -;; Shape: -;; (jolt.ffi/__ccallable f [:argtype ...] :rettype) ; thread stays active -;; (jolt.ffi/__ccallable f [:argtype ...] :rettype :collect-safe) ; may be invoked -;; ; while the thread is -;; ; parked in a :blocking call -;; Unlike __cfn, the fn is a CHILD expression (analyzed + walked by the passes); -;; the types are literal keywords read at compile time. The Chez back end lowers -;; it to a locked `foreign-callable` and returns its entry-point address (a jolt -;; pointer). :collect-safe is required when C invokes the callback from a thread -;; that is deactivated inside a :blocking foreign call (e.g. a GTK main loop). -(defn- analyze-ffi-callable [ctx items env] - (when-not (<= 4 (count items) 5) - (throw (str "jolt.ffi/foreign-callable expects (foreign-callable f [argtypes] rettype [:collect-safe])"))) - {:op :ffi-callable - :fn (analyze ctx (nth items 1) env) - :argtypes (mapv name (form-vec-items (nth items 2))) - :rettype (name (nth items 3)) - :collect-safe (and (= 5 (count items)) (= "collect-safe" (name (nth items 4))))}) - -;; The `.` special form: `(. target member arg*)` — member access / method call. -;; A symbol member whose name starts with "-" is a field read; otherwise it is a -;; method (call with the trailing args). Both lower to a :host-call carrying the -;; member name verbatim (the leading "-" survives so the runtime dispatcher reads -;; it as a field). The Chez back end dispatches it through record-method-dispatch. -(defn- analyze-dot [ctx items env] - (when (< (count items) 3) - (throw (str "Malformed (. target member ...) form"))) - (let [member0 (nth items 2) - ;; (. target (member arg*)) is sugar for (. target member arg*) — - ;; flatten the list-member form so the rest of the dispatch is uniform. - items (if (form-list? member0) - (let [ml (vec (form-elements member0))] - (into [(nth items 0) (nth items 1) (first ml)] (rest ml))) - items) - target (nth items 1) - member (nth items 2) - ;; (. Class method args*) with a class target is a static call — - ;; equivalent to (Class/method args*). resolve-global tags a class - ;; symbol :kind :class; a local of the same name shadows it. - class-target (when (and (form-sym? target) - (not (local? env (form-sym-name target)))) - (let [r (resolve-global ctx target)] - (when (= :class (:kind r)) (:name r))))] - (cond - (and class-target (form-sym? member)) - (invoke (host-static class-target (form-sym-name member)) - (mapv #(analyze ctx % env) (drop 3 items))) - (form-sym? member) - {:op :host-call - :method (form-sym-name member) - :target (analyze ctx target env) - :args (mapv #(analyze ctx % env) (drop 3 items))} - ;; (. obj :kw) is a keyword lookup — invoke the keyword on the target. - (form-keyword? member) - (invoke (analyze ctx member env) [(analyze ctx (nth items 1) env)]) - :else (uncompilable "special form . (non-symbol member)")))) - -(defn- analyze-field [ctx hname items env] - (when (< (count items) 2) - (throw (str "Malformed (.-field target) form"))) - {:op :host-call - :method (subs hname 1) ; ".-field" -> "-field" - :target (analyze ctx (nth items 1) env) - :args []}) - (defn- analyze-symbol [ctx form env] (let [nm (form-sym-name form) ns (form-sym-ns form)] (cond - (and (nil? ns) (local? env nm)) - (let [h (get (:hints env) nm)] (if h (assoc (local nm) :hint h) (local nm))) + (and (nil? ns) (local? env nm)) (local nm) ns (let [r (resolve-global ctx form)] (if (= :var (:kind r)) - (cond-> (var-ref (:ns r) (:name r)) (:num-ret r) (assoc :num-ret (:num-ret r))) - ;; A non-var qualified ref `Class/member` is a host class static - ;; (Math/sqrt, Long/MAX_VALUE, System/getenv). The Chez back end - ;; lowers it to a runtime static dispatch. - (host-static ns nm))) + (var-ref (:ns r) (:name r)) + (uncompilable (str "qualified ref " ns "/" nm)))) :else (let [r (resolve-global ctx form)] (case (:kind r) - ;; :num-ret (a ^double/^long declared return) rides on the var node so - ;; jolt.passes.numeric types a call to it (an accumulator over the result). - :var (cond-> (var-ref (:ns r) (:name r)) (:num-ret r) (assoc :num-ret (:num-ret r))) + :var (var-ref (:ns r) (:name r)) :host (host-ref (:name r)) - ;; a class-name symbol (java.util.Map) self-evaluates to its name - ;; string — jolt models a class as its name, with no JVM classes. - :class (const (:name r)) - ;; :unresolved — emitting a var-ref here would auto-intern an - ;; UNBOUND var, so a typo'd symbol would die later as 'Cannot call - ;; nil as a function' with no hint which symbol. - ;; Punt to the interpreter: its resolver raises Clojure's - ;; 'Unable to resolve symbol' when the form actually runs (at - ;; eval for top-level forms, at call for fn bodies). A punt - ;; rather than a hard throw because runtime-interning forms - ;; (defmulti's setup call) legitimately reference the var they - ;; are about to create when nested in a non-top-level do. Real - ;; forward references want (declare ...), as in Clojure. - ;; Under late-bind? (the Chez back end, which has no interpreter - ;; to punt to) an unresolved symbol instead lowers to a var-ref - ;; against the compile ns — resolved at runtime, the open-world - ;; semantics of -e — so defmulti/defmethod forward references work. - (if (late-bind? ctx) - (var-ref (compile-ns ctx) nm) - (uncompilable (str "Unable to resolve symbol: " nm " in this context")))))))) - -;; The wrapping unchecked-* name a core arithmetic op rewrites to under -;; *unchecked-math*, or nil. n is the full item count (head + args); unary - is a -;; negate. -(defn- unchecked-arith [hname n] - (cond - (= hname "+") "unchecked-add" - (= hname "*") "unchecked-multiply" - (= hname "-") (if (= n 2) "unchecked-negate" "unchecked-subtract") - (= hname "inc") "unchecked-inc" - (= hname "dec") "unchecked-dec" - :else nil)) + (var-ref (compile-ns ctx) nm)))))) (defn- analyze-list [ctx form env] (let [items (vec (form-elements form))] @@ -643,97 +190,17 @@ (quote-node form) (let [head (first items) hname (when (and (form-sym? head) (nil? (form-sym-ns head))) (form-sym-name head)) - ;; a special-form head may arrive clojure.core-qualified: syntax-quote - ;; namespace-qualifies a macro like `letfn` to `clojure.core/letfn` - ;; (matching Clojure, where it is a macro), so a macro-emitted - ;; (clojure.core/letfn …) must still dispatch to the special form. - sf-name (or hname - (when (and (form-sym? head) - (= "clojure.core" (form-sym-ns head)) - (contains? handled (form-sym-name head))) - (form-sym-name head))) - shadowed (and hname (local? env hname)) - ;; under *unchecked-math*, a core +/-/*/inc/dec becomes its wrapping - ;; unchecked-* (computed once; nil when off or not such an op). The op - ;; may arrive bare (+) or clojure.core-qualified (clojure.core/*), the - ;; latter from a macro's syntax-quote — both must wrap. - unm (when (unchecked-math?) - (let [opn (cond (and hname (not shadowed)) hname - (and (form-sym? head) (= "clojure.core" (form-sym-ns head))) - (form-sym-name head))] - (when opn (unchecked-arith opn (count items)))))] + shadowed (and hname (local? env hname))] (cond - ;; *unchecked-math* rewrite, before macro/special dispatch (these are - ;; ordinary core fns). The unchecked-* form re-analyzes normally. - unm (analyze ctx (cons (symbol unm) (rest items)) env) - ;; Canonical order (Clojure/CLJS analyze-seq): macroexpand FIRST, then - ;; dispatch special forms / interop / invoke. A local shadows the macro. - ;; A true special form is NOT shadowable by a same-named macro, matching - ;; the reference macroexpand1's isSpecial check — so a ns that redefs a - ;; macro `def`/`and`/`or` (clojure.spec.alpha) keeps the special form `def`. - (and (form-sym? head) (not shadowed) - (not (contains? handled sf-name)) (form-macro? ctx head)) - ;; defn/defn- expand to (def name (fn …)); carry the ORIGINAL form's - ;; source offset onto the resulting def, since the macro builds a fresh - ;; (def …) with no metadata. So the back end can register fn defs. - (let [node (analyze ctx (form-expand-1 ctx form (amp-env-map env)) env) - p (form-position form)] - (if (and p (= :def (:op node))) (assoc node :pos p) node)) - ;; jolt.ffi/__cfn — the foreign-function special form (always emitted - ;; fully-qualified by the jolt.ffi/foreign-fn macro, so aliases resolve). - (and (form-sym? head) (= "jolt.ffi" (form-sym-ns head)) - (= "__cfn" (form-sym-name head))) - (analyze-ffi-fn ctx items env) - ;; jolt.ffi/__ccallable — the foreign-callback special form (the fn is a - ;; child expression, analyzed here). - (and (form-sym? head) (= "jolt.ffi" (form-sym-ns head)) - (= "__ccallable" (form-sym-name head))) - (analyze-ffi-callable ctx items env) - ;; special-form heads are NOT shadowable (unlike macros): a local named - ;; `if` does not change the meaning of (if …) in operator position, per - ;; spec §3 and the reference. No (not shadowed) guard here. - (and sf-name (contains? handled sf-name)) - ;; stamp the form's source offset onto a top-level def so the back end - ;; can register it (jv$ns$name -> source) for native stack traces. - (let [node (analyze-special ctx sf-name items env) - p (form-position form)] - (if (and p (= :def (:op node))) (assoc node :pos p) node)) - (and hname (not shadowed) (method-head? hname)) - (analyze-host-call ctx hname items env) - ;; (Class. args*) — trailing-dot constructor sugar. - (and hname (not shadowed) (ctor-head? hname)) - (analyze-ctor ctx (subs hname 0 (dec (count hname))) (rest items) env) - ;; (new Class args*) — explicit constructor. - (and (= hname "new") (not shadowed) (>= (count items) 2) - (form-sym? (nth items 1))) - (analyze-ctor ctx (form-sym-name (nth items 1)) (drop 2 items) env) - ;; (. target member arg*) — the `.` special form. - (and (= hname ".") (not shadowed)) - (analyze-dot ctx items env) - ;; (.-field target) — field-access head. - (and hname (not shadowed) (field-head? hname)) - (analyze-field ctx hname items env) + (and hname (not shadowed) (contains? handled hname)) + (analyze-special ctx hname items env) (and hname (not shadowed) (form-special? hname)) (uncompilable (str "special form " hname)) + (and (form-sym? head) (not shadowed) (form-macro? ctx head)) + (analyze ctx (form-expand-1 ctx form) env) :else - ;; stamp the list form's source offset onto the :invoke - ;; so the success checker can report file:line:col. nil when the - ;; reader did not record it (synthetic/macro-built forms). - (let [n (invoke (analyze ctx head env) - (mapv #(analyze ctx % env) (rest items))) - p (form-position form)] - (if p (assoc n :pos p) n))))))) - -;; A vector/map/set literal carrying reader metadata (^:foo {…}, ^{:tag :int} [1]) -;; keeps it as a runtime value: wrap the collection node in (with-meta coll meta). -;; The metadata is itself a form (its values may be expressions, ^{:a (f)}), so -;; analyze it. nil meta passes the node through. Arglist vectors never reach here — -;; analyze-arity reads their items directly — so a ^Type [args] hint is not wrapped. -(defn- with-coll-meta [ctx form env node] - (let [m (form-coll-meta form)] - (if (nil? m) - node - (invoke (var-ref "clojure.core" "with-meta") [node (analyze ctx m env)])))) + (invoke (analyze ctx head env) + (mapv #(analyze ctx % env) (rest items)))))))) (defn analyze ([ctx form] (analyze ctx form (empty-env))) @@ -741,30 +208,10 @@ (cond (form-literal? form) (const form) (form-sym? form) (analyze-symbol ctx form env) - (form-vec? form) (with-coll-meta ctx form env - (vector-node (mapv #(analyze ctx % env) (form-vec-items form)))) - (form-map? form) (with-coll-meta ctx form env - (map-node (mapv (fn [p] [(analyze ctx (first p) env) - (analyze ctx (second p) env)]) - (form-map-pairs form)))) - (form-set? form) (with-coll-meta ctx form env - (set-node (mapv #(analyze ctx % env) (form-set-items form)))) + (form-vec? form) (vector-node (mapv #(analyze ctx % env) (form-vec-items form))) + (form-map? form) (map-node (mapv (fn [p] [(analyze ctx (first p) env) + (analyze ctx (second p) env)]) + (form-map-pairs form))) + (form-set? form) (set-node (mapv #(analyze ctx % env) (form-set-items form))) (form-list? form) (analyze-list ctx form env) - ;; regex literal #"…" -> a :regex IR node (leaf). The Chez back end emits a - ;; jolt-regex value over the vendored irregex. - (form-regex? form) {:op :regex :source (form-regex-source form)} - ;; #inst / #uuid literals -> :inst / :uuid IR leaves. The Chez back - ;; end emits a runtime inst/uuid value (host/chez/java/inst-time.ss). - (form-inst? form) {:op :inst :source (form-inst-source form)} - (form-uuid? form) {:op :uuid :source (form-uuid-source form)} - ;; bigdecimal literal (1.5M) -> a :bigdec leaf; the back end emits a runtime - ;; jbigdec built from the numeric text. - (form-bigdec? form) {:op :bigdec :source (form-bigdec-source form)} - ;; a live namespace value spliced into a form (~*ns* in a macro) -> a - ;; :the-ns leaf the back end reconstructs by name at the call site. - (form-ns-value? form) {:op :the-ns :name (form-ns-value-name form)} - ;; a live Var value spliced into a form (a macro that resolves a var and - ;; splices it, e.g. core.contracts' defcurry-from) -> a :the-var reference, - ;; same as (var ns/name); the back end emits (jolt-var ns name). - (form-var-value? form) (the-var (form-var-value-ns form) (form-var-value-name form)) :else (uncompilable "unsupported form")))) diff --git a/jolt-core/jolt/backend_scheme.clj b/jolt-core/jolt/backend_scheme.clj deleted file mode 100644 index 473f36c..0000000 --- a/jolt-core/jolt/backend_scheme.clj +++ /dev/null @@ -1,979 +0,0 @@ -(ns jolt.backend-scheme - "Lowers the host-neutral IR (jolt.ir) to Chez Scheme source text. - - The analyzer produces IR; this emitter turns each IR op into a string of Scheme - source, which the host compiles with (eval (read ...)). It depends only on - clojure.core and clojure.string, so once cross-compiled it runs on Chez and can - emit its own code — the bootstrap spine. Quoted forms are walked through the - portable jolt.host form-* contract, the same seam the analyzer uses, so the - emitter never touches a concrete host representation directly." - (:require [clojure.string :as str] - [jolt.host :refer [form-sym? form-sym-name form-sym-ns form-sym-meta - form-list? form-vec? form-map? form-set? form-char? - form-literal? form-elements form-vec-items - form-map-pairs form-set-items form-char-code - form-regex? form-regex-source - form-inst? form-inst-source form-uuid? form-uuid-source]])) - -;; Hot clojure.core primitives lowered to native Scheme. -;; `=` is the exactness-aware jolt= from values.ss; inc/dec/ -;; not are rt shims. Arithmetic and comparisons lower to the jolt-n* checked -;; macros (host/chez/seq.ss): the both-Chez-numbers fast path is open-coded and -;; anything else (BigDecimal, a non-number) takes the Numbers.ops-style category -;; dispatch, with JVM contagion (a double operand wins; an exact zero divisor is -;; ArithmeticException; a double zero divisor is ##Inf/##NaN). -(def ^:private native-ops - {"+" "jolt-n+" "-" "jolt-n-" "*" "jolt-n*" "/" "jolt-n-div" - "<" "jolt-n<" ">" "jolt-n>" "<=" "jolt-n<=" ">=" "jolt-n>=" - "=" "jolt=" "inc" "jolt-inc" "dec" "jolt-dec" "not" "jolt-not" - "min" "jolt-n-min" "max" "jolt-n-max" - "mod" "jolt-mod" "rem" "jolt-rem" "quot" "jolt-quot" - "vector" "jolt-vector" "hash-map" "jolt-hash-map-fn" "hash-set" "jolt-hash-set" - "conj" "jolt-conj" "get" "jolt-get" "nth" "jolt-nth" "count" "jolt-count" - "assoc" "jolt-assoc" "dissoc" "jolt-dissoc" "contains?" "jolt-contains?" - "empty?" "jolt-empty?" "peek" "jolt-peek" "pop" "jolt-pop" - "first" "jolt-first" "rest" "jolt-rest" "next" "jolt-next" "seq" "jolt-seq" - "cons" "jolt-cons" "list" "jolt-list" "reverse" "jolt-reverse" "last" "jolt-last" - "map" "jolt-map" "filter" "jolt-filter" "remove" "jolt-remove" - "reduce" "jolt-reduce" "into" "jolt-into" "concat" "jolt-concat" "apply" "jolt-apply" - "range" "jolt-range" "take" "jolt-take" "drop" "jolt-drop" - "keys" "jolt-keys" "vals" "jolt-vals" - "even?" "jolt-even?" "odd?" "jolt-odd?" "pos?" "jolt-pos?" "neg?" "jolt-neg?" - "zero?" "jolt-zero?" "identity" "jolt-identity" "nil?" "jolt-nil?" "some?" "jolt-some?" - "ex-info" "jolt-ex-info" - ;; bit ops: and/or/xor/not are Chez bitwise primitives (inlined to native code, - ;; no helper call); operands must be integers (a non-integer errors, like the - ;; JVM). The shifts keep their helpers (Java >>> masking / arithmetic shift) but - ;; emit a direct call instead of var-deref + the variadic overlay. - ;; and/or/xor/not map to variadic Chez bitwise prims (safe as a value at any - ;; arity). bit-and-not is left to its overlay: its only Scheme impl is 2-arg, so - ;; a value-position arity-3 use (via the variadic overlay) would mis-emit. - "bit-and" "bitwise-and" "bit-or" "bitwise-ior" "bit-xor" "bitwise-xor" "bit-not" "bitwise-not" - "bit-shift-left" "jolt-bit-shift-left" "bit-shift-right" "jolt-bit-shift-right" - "unsigned-bit-shift-right" "jolt-unsigned-bit-shift-right" - ;; positional protocol-method dispatch (defprotocol-emitted shims) — bind - ;; directly to the records.ss entry points so a protocol call doesn't var-deref. - "protocol-dispatch1" "protocol-dispatch1" "protocol-dispatch2" "protocol-dispatch2" - "protocol-dispatch3" "protocol-dispatch3"}) - -;; Value-position resolution for a clojure.core ref passed AS A VALUE (to map / -;; filter / reduce / apply). The jolt-n* call-position forms are macros, so value -;; position substitutes the variadic procedures over the same binary dispatch. -(def ^:private core-value-procs - (merge native-ops {"+" "jolt-add" "-" "jolt-sub" "*" "jolt-mul" "/" "jolt-div" - "min" "jolt-min" "max" "jolt-max" - "<" "jolt-lt" ">" "jolt-gt" "<=" "jolt-le" ">=" "jolt-ge"})) - -;; Per-op arity gate: only lower when the Scheme prim and the jolt fn agree at -;; this arity. Ops absent from the table are variadic (legal at any arity). -(def ^:private op-arity - {"inc" #(= % 1) "dec" #(= % 1) "not" #(= % 1) - "count" #(= % 1) "empty?" #(= % 1) "peek" #(= % 1) "pop" #(= % 1) - "mod" #(= % 2) "rem" #(= % 2) "quot" #(= % 2) "contains?" #(= % 2) - "get" #(or (= % 2) (= % 3)) "nth" #(or (= % 2) (= % 3)) - "assoc" #(and (>= % 3) (odd? %)) "dissoc" #(>= % 1) "conj" #(>= % 1) - "first" #(= % 1) "rest" #(= % 1) "next" #(= % 1) "seq" #(= % 1) - "reverse" #(= % 1) "last" #(= % 1) "keys" #(= % 1) "vals" #(= % 1) - "even?" #(= % 1) "odd?" #(= % 1) "pos?" #(= % 1) "neg?" #(= % 1) - "zero?" #(= % 1) "identity" #(= % 1) "nil?" #(= % 1) "some?" #(= % 1) - "protocol-dispatch1" #(= % 3) "protocol-dispatch2" #(= % 4) "protocol-dispatch3" #(= % 5) - "cons" #(= % 2) "filter" #(= % 2) "remove" #(= % 2) "into" #(= % 2) - "take" #(= % 2) "drop" #(= % 2) "map" #(>= % 2) "apply" #(>= % 2) - "reduce" #(or (= % 2) (= % 3)) "range" #(and (>= % 0) (<= % 3)) - "ex-info" #(or (= % 2) (= % 3)) - "bit-and" #(= % 2) "bit-or" #(= % 2) "bit-xor" #(= % 2) "bit-not" #(= % 1) - "bit-shift-left" #(= % 2) "bit-shift-right" #(= % 2) - "unsigned-bit-shift-right" #(= % 2)}) - -;; jolt's comparison ops are vacuously true at arity 1 and DON'T inspect the arg, -;; but Scheme's < demands a number even there — special-case. -(def ^:private cmp1-ops #{"jolt-n<" "jolt-n>" "jolt-n<=" "jolt-n>="}) - -;; Host interop methods with a Chez RT shim (rt.ss jolt-host-call). A `.method` -;; call on any other method routes to record-method-dispatch (a reify/record -;; protocol method). -(def ^:private supported-host-methods #{"isDirectory" "listFiles"}) - -;; Native-op Scheme procedures that return a genuine Scheme boolean (#t/#f), so an -;; :if test built from them needs no jolt-truthy? wrapper. -(def ^:private bool-returning-ops - #{"jolt-n<" "jolt-n<=" "jolt-n>" "jolt-n>=" "jolt=" "jolt-not" - "jolt-even?" "jolt-odd?" "jolt-pos?" "jolt-neg?" - "jolt-zero?" "jolt-empty?" "jolt-contains?" "jolt-nil?" "jolt-some?"}) - -;; Numeric-specialized op strings. jolt.passes.numeric tags an arithmetic invoke -;; :num-kind :double|:long when every operand is that kind; these are the Chez -;; flonum/fixnum ops it lowers to — no generic dispatch, fixnums unboxed. fl?/fx? -;; comparisons carry the question mark; fl+/fx+ don't. -;; -;; CONTRACT: every op name jolt.passes.numeric/dbl-spec (resp. lng-spec) tags must -;; have an entry here, or emit-numeric splices a nil op string into the output. Keep -;; these tables and those specializers in sync. -(def ^:private dbl-ops - {"+" "fl+" "-" "fl-" "*" "fl*" "/" "fl/" "min" "flmin" "max" "flmax" - "<" "fl" "fl>?" "<=" "fl<=?" ">=" "fl>=?" "=" "fl=?" "==" "fl=?"}) -;; A ^long is 64-bit; a Chez fixnum is only 61-bit. Arithmetic +/-/* keep the raw -;; fx ops (the fast-arith path; under *unchecked-math* they're already rewritten to -;; the wrapping unchecked-*). The comparisons / min/max / quot/rem/mod use the -;; jolt-l* fast-path-with-fallback macros (host/chez/seq.ss) so a full 64-bit -;; operand falls back to the generic op instead of raising. -(def ^:private lng-ops - {"+" "fx+" "-" "fx-" "*" "fx*" "min" "jolt-l-min" "max" "jolt-l-max" - ;; unchecked-* WRAP to signed 64 bits (Java long), so they can't use the raising - ;; fx ops — the backend emits the wrapping jolt-unc* helpers (host/chez/seq.ss). - "unchecked-add" "jolt-uncadd2" "unchecked-subtract" "jolt-uncsub2" "unchecked-multiply" "jolt-uncmul2" - "quot" "jolt-l-quot" "rem" "jolt-l-rem" "mod" "jolt-l-mod" - "<" "jolt-l<" ">" "jolt-l>" "<=" "jolt-l<=" ">=" "jolt-l>=" "=" "jolt-l=" "==" "jolt-l="}) - -;; BigDecimal ops. jolt.passes.numeric tags an arithmetic/comparison invoke -;; :num-kind :bigdec when every operand is a bigdec (or an integer literal); these -;; are the bigdec.ss engine procedures it lowers to. Variadic where the source op -;; is; an integer-literal operand is coerced to a bigdec at runtime, so unlike the -;; flonum path no literal rewrite is needed. -(def ^:private bd-ops - {"+" "jbd-add" "-" "jbd-sub" "*" "jbd-mul" "/" "jbd-div" - "min" "jbd-min" "max" "jbd-max" - "quot" "jbd-quot" "rem" "jbd-rem" - "<" "jbd-lt?" ">" "jbd-gt?" "<=" "jbd-le?" ">=" "jbd-ge?" - "zero?" "jbd-zero?" "pos?" "jbd-pos?" "neg?" "jbd-neg?"}) - -;; PRELUDE MODE. The default (subset) mode rejects any clojure.core ref -;; that isn't a native-op — a clean "out of subset" signal for user-facing `-e`. -;; When emitting clojure.core ITSELF as a prelude, core fns reference each other -;; constantly; those lower to var-deref (resolved at runtime). -(def prelude-mode? (atom false)) -(defn set-prelude-mode! [on] (reset! prelude-mode? on)) - -;; DIRECT-LINK MODE. Off for ordinary runs, the seed mint, and `-e`/repl/load-string -;; (open world — vars are redefinable). `jolt build` (release/optimized) flips it on -;; during app emission: a closed-world program where every app def is final, so an -;; app->app call binds to the def's Scheme binding directly, skipping the var-table -;; lookup and the generic jolt-invoke dispatch. -(def direct-link? (atom false)) -(defn set-direct-link! [on] (reset! direct-link? on)) - -;; Fully-qualified app var names ("ns/name") already emitted with a direct-link -;; binding in the current unit. A call/value-ref direct-links only to a name in this -;; set — one defined earlier in emission order (or itself), so the Scheme binding -;; exists by the time the reference runs. Reset per build. -(def direct-link-defined (atom #{})) -;; Of those, the ones whose init is a fn literal — safe to call as a raw Scheme -;; application. A def of a non-fn value (a map, set, keyword, …) is invokable in -;; Clojure but is not a Scheme procedure, so its calls must still route through -;; jolt-invoke even with a direct binding. -(def direct-link-fns (atom #{})) -(defn direct-link-reset! [] (reset! direct-link-defined #{}) (reset! direct-link-fns #{})) - -;; Cache a resolved var cell in a per-site cell so a non-direct-linked var -;; reference skips the name lookup (string-append + hash) after the first use. -;; OFF during the seed mint (the seed must stay a byte-fixpoint, and caching the -;; compiler's own refs shifts the gensym-numbered cell names every pass); the -;; runtime eval path turns it on for user code, where it's the big win. -(def var-cache? (atom false)) -(defn set-var-cache! [on] (reset! var-cache? on)) - -;; Opt-in tail-frame history (JOLT_TRACE): emit a (jolt-trace-push! "name") at the -;; head of every named fn body, so an entry records the frame into the runtime ring -;; buffer (rt.ss) and a TCO-elided frame still shows in an error's backtrace. OFF -;; during the seed mint and `jolt build` (byte-determinism + no runtime cost); -;; compile-eval.ss turns it on for runtime-eval'd user code when JOLT_TRACE is set. -(def trace-frames? (atom false)) -(defn set-trace-frames! [on] (reset! trace-frames? on)) - -;; A direct-link Scheme binding name for a var. The fqn maps to a unique identifier -;; jv$$; chars that break a Scheme identifier or the `$` separator are -;; escaped so distinct vars never collide. -(defn- dl-munge [s] - (-> s (str/replace "$" "_D_") (str/replace "#" "_H_") (str/replace "'" "_Q_"))) -(defn- dl-name [ns nm] (str "jv$" (dl-munge ns) "$" (dl-munge nm))) -(defn- dl-fqn [ns nm] (str ns "/" nm)) -(defn- direct-linkable? [ns nm] - (and @direct-link? (contains? @direct-link-defined (dl-fqn ns nm)))) -;; A direct-linked var whose value is a fn literal — its binding is a Scheme -;; procedure, so a call site can apply it directly. -(defn- direct-link-fn? [ns nm] - (contains? @direct-link-fns (dl-fqn ns nm))) - -;; recur-target and the set of munged local names known to hold a procedure (a -;; named fn's self-recursion name) are lexically scoped — dynamic vars so the -;; recursion auto-restores them (no manual save/restore, no throw-leak). -(def ^:dynamic *recur-target* nil) -(def ^:dynamic *known-procs* #{}) -;; True while emitting a node in TAIL position. Only used, in trace mode, to mark a -;; tail call so the runtime routes its callee into the current history rib instead -;; of a new one (rt.ss). It never affects semantics — a wrong value only mislabels -;; a debug trace line — so partial propagation is safe. `emit` (the wrapper below) -;; clears it by default; the tail-transparent forms (fn body, if/do/let/loop) pass -;; it to their tail child. Default false so a top-level form is treated non-tail. -(def ^:dynamic *tail?* false) - -(def ^:private gensym-counter (atom 0)) -(defn- fresh-label [prefix] (str prefix (swap! gensym-counter inc))) - -;; Per-site cache cells collected while emitting one top-level def. A site that -;; resolves a STABLE value — a devirtualized impl (constant tag/proto/method) or a -;; var cell (interned, so the cell never changes even when the var is redefined) — -;; resolves it once, not per call, the inline cache the JVM gets for free. When a -;; def init is being emitted this holds an atom; each site appends a fresh cell name -;; (bound to #f in a let wrapping the def, so it persists across calls and is shared -;; by every invocation) and resolves into it on first use. nil outside a def (a site -;; there falls back to a per-call resolve). -(def ^:private cache-cells (atom nil)) - -;; Emit a def's init (via the supplied thunk) under a fresh cache-cell collector, -;; then wrap the result in a let binding any cells its body registered so they -;; persist in the def's closure. Saves/restores the outer collector for nested -;; defs. Used by both the runtime def emit and the direct-link top-level emit. -(defn- emit-with-cells [emit-thunk] - (let [cells (atom []) - prev @cache-cells - _ (reset! cache-cells cells) - raw (emit-thunk) - _ (reset! cache-cells prev)] - (if (seq @cells) - (str "(let (" (str/join " " (map (fn [c] (str "(" c " #f)")) @cells)) ") " raw ")") - raw))) - -;; Scheme syntactic keywords. A jolt local with one of these names would, when -;; emitted verbatim, shadow the Scheme form in operator position (a local named -;; `if` would turn the special form (if …) the back end emits into a call), so -;; such locals are prefixed. Matches the spec: special-form heads are not -;; shadowable, but a value local may legally be named `if`. -(def ^:private scheme-reserved - #{"if" "begin" "lambda" "let" "let*" "letrec" "letrec*" "quote" "quasiquote" - "unquote" "set!" "define" "define-syntax" "cond" "case" "when" "unless" - "and" "or" "do" "else" "guard" "parameterize" "delay" "values"}) - -;; clojure.core ops emitted as a BARE Scheme name (where native-ops maps the op -;; to itself: + - * / < > min max …). A local binding with one of these names -;; would otherwise shadow the emitted prim — e.g. (fn [max] (clojure.core/max …)) -;; emits (max …) calling the param — so such locals are prefixed, like reserved -;; words. Derived from native-ops so the two never drift. -(def ^:private bare-native-names - (set (keep (fn [[k v]] (when (= k v) k)) native-ops))) - -;; Most jolt names are already valid Scheme identifiers. The one that isn't is -;; `#`, which jolt auto-gensyms use as a suffix (p1__0000X4# from #(...)) — `#` -;; starts a datum in Scheme, so replace it with `_`. A name that collides with a -;; Scheme keyword OR a bare-emitted native op is prefixed with `_` so it can never -;; shadow the emitted form. -(defn- munge-name [s] - ;; A Clojure symbol may contain chars that break a Scheme identifier: ' is the - ;; quote reader macro (a bare f' would read as f then 'rest), # already maps to - ;; _. Munge both to safe tokens; the same mapping applies at the binding and at - ;; every reference, so resolution stays consistent. - (let [s (-> s - (str/replace "#" "_") - (str/replace "'" "_PRIME_"))] - (if (or (contains? scheme-reserved s) (contains? bare-native-names s)) (str "_" s) s))) - -(declare emit) -(declare emit*) -;; Ops that pass tail position through to a child (the child can itself be a tail -;; call): if/do carry it to their tail branch/last form, let/loop to their body, -;; and invoke reads it to decide whether the call is tail. Every other op's -;; children are non-tail, so `emit` clears *tail?* before dispatching them — that -;; way a stray true can't leak into, say, a call sitting in a vector literal. -(def ^:private tail-transparent-ops #{:if :do :let :loop :invoke}) -(defn emit [node] - (if (and *tail?* (not (tail-transparent-ops (:op node)))) - (binding [*tail?* false] (emit* node)) - (emit* node))) - -;; A Chez string literal. Every char outside printable ASCII becomes a -;; codepoint hex escape \x; ; the named escapes (\n \t \r \" \\) match what -;; Chez's reader accepts. For pure printable ASCII this is byte-identical to %j. -(defn- char-escape [cp] - (cond - (= cp 34) "\\\"" - (= cp 92) "\\\\" - (= cp 10) "\\n" - (= cp 9) "\\t" - (= cp 13) "\\r" - (and (>= cp 32) (< cp 127)) (str (char cp)) - :else (str "\\x" (format "%x" cp) ";"))) - -(defn- chez-str-lit [s] - (str "\"" (apply str (map (fn [c] (char-escape (int c))) s)) "\"")) - -(defn- emit-const [v] - (cond - (nil? v) "jolt-nil" - (boolean? v) (if v "#t" "#f") - ;; Numeric tower: emit a literal Chez re-reads as the SAME number. - ;; Exact integers -> "42", exact ratios -> "1/2" (str renders both faithfully); - ;; a flonum must carry a decimal point/exponent or Chez reads it back as exact, - ;; so a whole flonum (str drops its .0) gets ".0" appended. ##Inf/##-Inf/##NaN - ;; -> Chez's flonum literals. - (number? v) (cond - (= v ##Inf) "+inf.0" - (= v ##-Inf) "-inf.0" - (not= v v) "+nan.0" - (float? v) (let [s (str v)] - (if (or (str/includes? s ".") (str/includes? s "e")) s (str s ".0"))) - :else (str v)) - (string? v) (chez-str-lit v) - ;; keyword literal -> (keyword ns name) - (keyword? v) (if-let [kns (namespace v)] - (str "(keyword " (chez-str-lit kns) " " (chez-str-lit (name v)) ")") - (str "(keyword #f " (chez-str-lit (name v)) ")")) - ;; char literal -> (integer->char ). Get the codepoint via the host - ;; contract (form-char-code), NOT (get v :ch): on Chez (the self-hosted spine) - ;; a char is a native char, so a struct-field read returns nil and would emit - ;; (integer->char) with no arg. - (form-char? v) (str "(integer->char " (form-char-code v) ")") - :else (throw (ex-info (str "emit-const: unsupported literal " (pr-str v)) {})))) - -;; Emit a call `(ctor a0 a1 ...)` with the args evaluated LEFT-TO-RIGHT. Chez's -;; procedure-argument evaluation order is unspecified (in practice right-to-left), -;; but Clojure evaluates collection-literal elements left to right, so a literal -;; like [(read r) (read r)] over side-effecting reads must bind in source order. -;; Bind each arg to a fresh temp in a let* then construct. Only wraps at >= 2 args. -(defn- emit-ordered [ctor arg-strs] - (if (< (count arg-strs) 2) - (str "(" ctor (if (empty? arg-strs) "" (str " " (str/join " " arg-strs))) ")") - (let [tmps (map (fn [_] (fresh-label "_o$")) arg-strs) - binds (str/join " " (map (fn [t a] (str "(" t " " a ")")) tmps arg-strs))] - (str "(let* (" binds ") (" ctor " " (str/join " " tmps) "))")))) - -;; An operand whose evaluation has no observable effect and whose result doesn't -;; depend on when it runs: constants, locals, var/the-var reads, quoted literals. -;; Re-ordering such operands relative to others is invisible. -(defn- side-effect-free? [n] - (contains? #{:const :local :var :the-var :quote} (:op n))) - -;; Clojure evaluates a call's operands (and recur's args) left to right; Chez's -;; application order is unspecified (right-to-left in practice). Force source -;; order by binding operands to fresh temps in a let* — but only when two or more -;; could have observable effects, so hot calls over locals/consts stay un-wrapped. -(defn- needs-order? [nodes] - (> (count (remove side-effect-free? nodes)) 1)) - -;; Build a call from operand strings, forcing left-to-right evaluation when -;; needed. `nodes`/`strs` are the operands (parallel); `build` receives the -;; operand strings to splice (temps when wrapped, raw otherwise) and returns the -;; call. Operands that don't need ordering are passed through inline. -(defn- ordered-call [nodes strs build] - (if (needs-order? nodes) - (let [tmps (mapv (fn [_] (fresh-label "_a$")) strs) - binds (str/join " " (map (fn [t a] (str "(" t " " a ")")) tmps strs))] - (str "(let* (" binds ") " (build tmps) ")")) - (build strs))) - -;; Quoted literals. A :quote node's :form is the RAW reader form; -;; reconstruct each as the matching Chez RT constructor — the runtime value of a -;; quote is just that literal data. The form is walked via the jolt.host form-* -;; contract (the portable seam the analyzer uses), NOT host-native predicates, so -;; this stays host-neutral — the contract walks the host's reader forms. -(declare emit-quoted) -(defn- emit-quoted-map [pairs] - ;; pairs: a jolt vector of [k-form v-form] pairs (form-map-pairs) - (str "(jolt-hash-map " - (str/join " " (mapcat (fn [p] [(emit-quoted (nth p 0)) (emit-quoted (nth p 1))]) pairs)) - ")")) -(defn- emit-quoted-map-value [m] - ;; A jolt map VALUE (def/symbol metadata is a value, not a reader form). (keys m) - ;; iterates in host-hash order, which is not stable across Chez versions, so emit - ;; the pairs sorted by their emitted Scheme text — keeps the seed byte-fixed - ;; regardless of the host hash (jolt-8479). - (let [pairs (sort (map (fn [k] (str (emit-quoted k) " " (emit-quoted (get m k)))) (keys m)))] - (str "(jolt-hash-map " (str/join " " pairs) ")"))) -;; emit-quoted reconstructs both raw reader forms (from :quote) AND plain jolt -;; values (def/symbol :meta). Reader forms are walked via the jolt.host form-* -;; contract; the native-predicate branches below catch genuine jolt collection -;; VALUES. The form-* branches come first so a reader form (a host-native struct/ -;; array that a native predicate might also match) is always handled as a form. -(defn- emit-quoted [form] - (cond - (form-char? form) (emit-const form) - (form-literal? form) (emit-const form) - (form-sym? form) - (let [m (form-sym-meta form) sns (form-sym-ns form) nm (form-sym-name form)] - (if (and m (pos? (count m))) - ;; carry reader metadata (^:foo bar) onto the quoted symbol so (meta 'x) sees it - (str "(jolt-symbol/meta " (if sns (chez-str-lit sns) "#f") " " (chez-str-lit nm) " " - (emit-quoted m) ")") - (str "(jolt-symbol " (if sns (chez-str-lit sns) "#f") " " (chez-str-lit nm) ")"))) - ;; sort items by emitted text: a set has no source order, and host-hash order - ;; is not stable across Chez versions (jolt-8479). - (form-set? form) (str "(jolt-hash-set " (str/join " " (sort (map emit-quoted (form-set-items form)))) ")") - (form-list? form) (str "(jolt-list " (str/join " " (map emit-quoted (form-elements form))) ")") - (form-vec? form) (str "(jolt-vector " (str/join " " (map emit-quoted (form-vec-items form))) ")") - (form-map? form) (emit-quoted-map (form-map-pairs form)) - ;; a quoted #"…" regex value -> reconstruct it (same as the :regex IR leaf). - (form-regex? form) (str "(jolt-regex " (chez-str-lit (form-regex-source form)) ")") - ;; quoted #inst / #uuid literals construct their value, like the JVM reader - ;; (which builds the Date/UUID at read time, so a quoted/macro form carries the - ;; value, not the raw tagged form). Same emit as the :inst / :uuid IR leaves. - (form-inst? form) (str "(jolt-inst-from-string " (chez-str-lit (form-inst-source form)) ")") - (form-uuid? form) (str "(jolt-uuid-from-string " (chez-str-lit (form-uuid-source form)) ")") - ;; a quoted custom #tag with no registered reader -> a tagged-literal value - ;; (Clojure's reader builds a TaggedLiteral), not the raw reader map. The tag is - ;; stored as a :#name keyword; strip the leading # to the bare symbol. - (and (map? form) (= :jolt/tagged (get form :jolt/type))) - (let [nm (name (get form :tag)) - tsym (if (= \# (first nm)) (subs nm 1) nm)] - (str "(jolt-tagged-literal (jolt-symbol #f " (chez-str-lit tsym) ") " - (emit-quoted (get form :form)) ")")) - ;; plain jolt VALUES (metadata maps and anything nested in them) - (map? form) (emit-quoted-map-value form) - (vector? form) (str "(jolt-vector " (str/join " " (map emit-quoted form)) ")") - (set? form) (str "(jolt-hash-set " (str/join " " (sort (map emit-quoted form))) ")") - (seq? form) (str "(jolt-list " (str/join " " (map emit-quoted form)) ")") - :else (throw (ex-info (str "emit-quoted: unsupported quoted form " (pr-str form)) {})))) - -;; A def's :meta is a jolt map value. Non-empty? (a plain def carries {}). -(defn- jmeta-nonempty? [m] (and (map? m) (pos? (count m)))) - -;; The meta argument to def-var-with-meta!. When the analyzer attached a -;; :meta-expr (metadata with values to evaluate, e.g. ^{:a some-fn}), emit it as a -;; runtime expression; otherwise the static :meta map as quoted data. -(defn- emit-def-meta [node] - (if (:meta-expr node) - (emit (:meta-expr node)) - (emit-quoted (:meta node)))) - -(defn- emit-binding [b] - (str "(" (munge-name (nth b 0)) " " (emit (nth b 1)) ")")) - -;; letfn lowers to a :let flagged :letrec (mutually-recursive named local fns): -;; Scheme `letrec*` binds them so each sees its siblings. A plain let uses let*. -(defn- emit-let [node] - (let [kw (if (:letrec node) "letrec*" "let*") - ;; bindings are non-tail; the body inherits the let's tail position - binds (binding [*tail?* false] (str/join " " (mapv emit-binding (:bindings node))))] - (str "(" kw " (" binds ") " (emit (:body node)) ")"))) - -(defn- emit-loop [node] - (let [label (fresh-label "loop") - pairs (:bindings node) - names (map #(munge-name (nth % 0)) pairs) - ;; inits evaluate in the OUTER scope (recur-target unchanged) and, like - ;; Clojure loop/let, SEQUENTIALLY — wrap a let* around the named let. - inits (binding [*tail?* false] (mapv #(emit (nth % 1)) pairs)) - seq-bs (str/join " " (map (fn [n i] (str "(" n " " i ")")) names inits)) - rebinds (str/join " " (map (fn [n] (str "(" n " " n ")")) names)) - ;; the loop body inherits the loop's tail position - body (binding [*recur-target* label] (emit (:body node)))] - (str "(let* (" seq-bs ") (let " label " (" rebinds ") " body "))"))) - -;; jolt.ffi/__cfn -> a Chez foreign-procedure (jolt-ffi). The C symbol + types are -;; compile-time literals from the analyzer, so this emits a real typed binding; -;; the resulting Scheme procedure is callable like any jolt fn. The library must -;; have loaded the shared object (jolt.ffi/load-library) before this def runs. -(def ^:private ffi-types - {"int" "int" "uint" "unsigned-int" "long" "long" "ulong" "unsigned-long" - "int64" "integer-64" "uint64" "unsigned-64" "size_t" "size_t" "ssize_t" "ssize_t" - "iptr" "iptr" "uptr" "uptr" "double" "double" "float" "float" - "pointer" "void*" "void*" "void*" "string" "string" "void" "void" - "uint8" "unsigned-8" "u8" "unsigned-8" "byte" "unsigned-8" "char" "char"}) -(defn- ffi-type->chez [t] - (or (ffi-types t) (throw (ex-info (str "jolt.ffi: unknown foreign type :" t) {})))) -(defn- emit-ffi-fn [node] - (str "(foreign-procedure " (when (:blocking node) "__collect_safe ") (chez-str-lit (:csym node)) - " (" (str/join " " (map ffi-type->chez (:argtypes node))) ") " - (ffi-type->chez (:rettype node)) ")")) - -;; jolt.ffi/__ccallable -> a Chez foreign-callable wrapping the emitted jolt fn, -;; locked + registered (jolt-ffi-register-callable!, host/chez/java/ffi.ss) so the -;; collector neither moves nor reclaims it while C may still call through it. The -;; expression evaluates to the entry-point address — a jolt pointer the caller -;; hands to C. :collect-safe emits the convention that reactivates the thread on -;; entry, for callbacks invoked while it is parked in a :blocking foreign call. -(defn- emit-ffi-callable [node] - (str "(jolt-ffi-register-callable! (foreign-callable " - (when (:collect-safe node) "__collect_safe ") - (emit (:fn node)) - " (" (str/join " " (map ffi-type->chez (:argtypes node))) ") " - (ffi-type->chez (:rettype node)) "))")) - -(defn- emit-recur [node] - (when-not *recur-target* (throw (ex-info "emit: recur outside a loop/fn target" {}))) - (let [arg-nodes (:args node)] - (ordered-call arg-nodes (mapv emit arg-nodes) - (fn [as] (str "(" *recur-target* " " (str/join " " as) ")"))))) - -;; One arity -> a Scheme lambda param-list + a named-let-wrapped body. The named -;; let lets fn-level `recur` rebind this arity's params. A variadic arity takes a -;; Scheme rest arg coerced to a jolt seq (nil when empty); recur carries the rest -;; seq directly, and the named let's init only runs on first entry. -;; Coerce a numeric-hinted param at fn entry, the way the JVM coerces a primitive -;; parameter: ^double -> exact->inexact, ^long -> jolt->fx. Only the named-let init -;; (first entry) coerces — recur carries already-typed values, like a JVM goto. This -;; is what makes the hint a contract the body's fl*/fx* ops can rely on. `orig` is -;; the param's source name (the :nhints key); `munged` the emitted identifier. -(defn- nhint-init [nh orig munged] - (let [k (get nh orig)] - (cond (= k :double) (str "(exact->inexact " munged ")") - (= k :long) (str "(jolt->fx " munged ")") - :else munged))) - -(defn- emit-arity-clause [a] - (let [orig (:params a) - nh (into {} (:nhints a)) - params (map munge-name orig) - restp (when-let [r (:rest a)] (munge-name r)) - label (fresh-label "fnrec") - ret (:ret-nhint a) - ;; the body is the fn's tail position — UNLESS a ^double/^long return hint - ;; wraps it in a coercion below, which puts the body back in non-tail. - body-tail? (not (or (= ret :double) (= ret :long))) - body (binding [*recur-target* label *tail?* body-tail?] (emit (:body a))) - paramlist (cond - (and restp (empty? params)) restp - restp (str "(" (str/join " " params) " . " restp ")") - :else (str "(" (str/join " " params) ")")) - pbind (map (fn [o p] (str "(" p " " (nhint-init nh o p) ")")) orig params) - binds (if restp - (concat pbind [(str "(" restp " (list->cseq " restp "))")]) - pbind) - lett (str "(let " label " (" (str/join " " binds) ") " body ")") - ;; a ^double/^long return hint coerces the arity's value on the way out - ;; (exact->inexact / jolt->fx), like a JVM primitive return — so a caller's - ;; arithmetic over the result is sound. - ret (:ret-nhint a)] - [paramlist (cond (= ret :double) (str "(exact->inexact " lett ")") - (= ret :long) (str "(jolt->fx " lett ")") - :else lett)])) - -(defn- emit-fn [node] - (let [arities (:arities node) - ;; a named fn binds its own name as a known-procedure local across ALL - ;; arities, so self-calls emit directly rather than via jolt-invoke. - self (when-let [nm (:name node)] (munge-name nm)) - clauses (binding [*known-procs* (if self (conj *known-procs* self) *known-procs*)] - (mapv emit-arity-clause arities)) - ;; trace mode: record this frame on entry (before the body), so a frame - ;; the body then tail-calls away is still in the ring at throw time. A - ;; `recur` re-enters via the named-let, not the lambda, so a tight loop - ;; records once, not per iteration. - clauses (if (and @trace-frames? self) - (mapv (fn [c] [(nth c 0) - (str "(begin (jolt-trace-push! " (chez-str-lit self) ") " - (nth c 1) ")")]) - clauses) - clauses) - lambda (if (= 1 (count clauses)) - (let [c (first clauses)] (str "(lambda " (nth c 0) " " (nth c 1) ")")) - (str "(case-lambda " - (str/join " " (map (fn [c] (str "(" (nth c 0) " " (nth c 1) ")")) clauses)) - ")"))] - ;; A named fn references itself by name — the analyzer binds that name as a - ;; :local in the body. letrec makes the name visible to the lambda. - (if-let [nm (:name node)] - (let [m (munge-name nm)] (str "(letrec ((" m " " lambda ")) " m ")")) - lambda))) - -;; If fnode is a clojure.core (or host) ref to a native-op primitive, return the -;; Scheme op string — only at an arity where the Scheme op and the jolt fn agree. -(defn- native-op [fnode nargs] - (let [nm (case (:op fnode) - :var (when (= "clojure.core" (:ns fnode)) (:name fnode)) - :host (:name fnode) - nil) - op (when nm (native-ops nm)) - arity-ok (when nm (op-arity nm))] - (cond - (nil? op) nil - (and arity-ok (not (arity-ok nargs))) nil - :else op))) - -;; IFn dispatch for a LITERAL callee (Clojure's "value as fn"): a keyword looks -;; itself up in its arg; a map/set/vector literal looks up its arg. -(defn- ifn-kind [fnode] - (case (:op fnode) - :const (when (keyword? (:val fnode)) :keyword) - (:map :set :vector) :coll - nil)) - -;; A reference into the Clojure stdlib (clojure.*) with no impl on Chez yet. -(defn- stdlib-var? [n] - (and (= :var (:op n)) (str/starts-with? (or (:ns n) "") "clojure."))) - -;; Emit a :num-kind-tagged arithmetic call as a Chez flonum/fixnum op. inc/dec are -;; unary (fl +/- 1.0, fx1+/fx1-); the rest map through dbl-ops/lng-ops. Integer -;; literal operands of a :double op were coerced to flonums by jolt.passes.numeric. -(defn- emit-numeric [kind nm args order-args] - (cond - (and (= kind :double) (= nm "inc")) (str "(fl+ " (first args) " 1.0)") - (and (= kind :double) (= nm "dec")) (str "(fl- " (first args) " 1.0)") - ;; inc/dec tolerate a 64-bit operand (jolt-l-inc/dec fall back past fixnum range); - ;; unchecked-inc/dec wrap (Java long). Neither can use the raising fx1+/fx1-. - (and (= kind :long) (= nm "inc")) (str "(jolt-l-inc " (first args) ")") - (and (= kind :long) (= nm "dec")) (str "(jolt-l-dec " (first args) ")") - (and (= kind :long) (= nm "unchecked-inc")) (str "(jolt-uncinc " (first args) ")") - (and (= kind :long) (= nm "unchecked-dec")) (str "(jolt-uncdec " (first args) ")") - :else - (let [op (case kind :double (dbl-ops nm) :long (lng-ops nm) :bigdec (bd-ops nm))] - (order-args (fn [as] (str "(" op " " (str/join " " as) ")")))))) - -;; slot of a declared field key in a record's field-order shape, or nil. -(defn- struct-field-index [shape kw] - (when shape - (loop [i 0] - (cond (>= i (count shape)) nil - (= (nth shape i) kw) i - :else (recur (inc i)))))) - -;; A plain Scheme application: (callee op ...). -(defn- plain-call [callee operand-strs] - (str "(" callee (if (seq operand-strs) (str " " (str/join " " operand-strs)) "") ")")) -;; A tail call in trace mode. Force-bind the operands to temps FIRST (so any -;; operand whose own evaluation records a trace entry runs before our mark), THEN -;; set the tail mark, THEN apply — the callee's entry prologue consumes the mark -;; with nothing in between, so it can't be clobbered. Still a tail call: the let*'s -;; last form is the application, so TCO is preserved. -(defn- tail-marked-call [callee operand-strs] - (let [tmps (mapv (fn [_] (fresh-label "_tt$")) operand-strs) - binds (str/join " " (map (fn [t a] (str "(" t " " a ")")) tmps operand-strs))] - (str "(let* (" binds ") (jolt-trace-mark! #t) " (plain-call callee tmps) ")"))) -;; Emit a call, tail-marked when we're in tail position and tracing is on; a plain -;; application otherwise. The mark is consumed by the callee's entry prologue — -;; direct calls (:local known-proc, direct-link) always have one; a jolt-invoke -;; call usually reaches one but not always (see the best-effort note in rt.ss). -(defn- emit-call [tail? callee operand-strs] - (if (and @trace-frames? tail?) - (tail-marked-call callee operand-strs) - (plain-call callee operand-strs))) - -(defn- emit-invoke [node] - (let [tail? *tail?*] ; capture: children below emit non-tail - (binding [*tail?* false] - (let [fnode (:fn node) - arg-nodes (:args node) - args (mapv emit arg-nodes) - nop (native-op fnode (count args)) - kind (ifn-kind fnode) - ;; order args left-to-right (build receives the spliced operand strings) - order-args (fn [build] (ordered-call arg-nodes args build)) - defstr (fn [as] (if (> (count as) 1) (str " " (nth as 1)) "")) - ;; jolt-invoke dispatch: Clojure evaluates the fn expr before the args, so - ;; order [callee & args] together when ordering is observable. - invoke (fn [] - (ordered-call (cons fnode arg-nodes) (cons (emit fnode) args) - (fn [operands] (emit-call tail? "jolt-invoke" operands))))] - (cond - ;; devirtualized protocol call: the inference proved the receiver (arg 0) is - ;; one record type, so resolve the impl by that static tag instead of routing - ;; through the protocol var -> jolt-invoke -> protocol-resolve (which recomputes - ;; the tag and walks the type table). devirt-resolve does the same table lookup - ;; the dispatch would, but with no var-deref and no receiver-type computation; - ;; it falls back to ordinary dispatch when the static tag has no direct impl (a - ;; record satisfying the protocol via an Object/host-tag default). Fires only on - ;; a monomorphic site (a megamorphic receiver joins to :any, no :devirt-type). - ;; The receiver is bound once — it feeds both the resolve and the application. - (:devirt-type node) - (order-args (fn [as] - (let [r (fresh-label "_r$") - dv (str "(devirt-resolve " (chez-str-lit (:devirt-type node)) " " - (chez-str-lit (:devirt-proto node)) " " (chez-str-lit (:devirt-method node)) - " " r ")") - cells @cache-cells - ;; cache the resolved impl in a per-site cell when inside a - ;; def (resolved once on first call, then reused); else - ;; resolve per call. - resolver (if cells - (let [c (fresh-label "_dvc$")] - (swap! cells conj c) - (str "(or " c " (let ((_f " dv ")) (set! " c " _f) _f))")) - dv)] - (str "(let* ((" r " " (first as) ")) (" - resolver " " (str/join " " (cons r (rest as))) "))")))) - ;; hint-directed fast arithmetic: jolt.passes.numeric proved every operand a - ;; flonum (^double) or fixnum (^long), so emit the Chez fl*/fx* op. - (:num-kind node) (emit-numeric (:num-kind node) (:name fnode) args order-args) - ;; zero-arg + / * : exact integer identity (= JVM long: (+) -> 0, (*) -> 1). - (and nop (empty? args) (= nop "+")) "0" - (and nop (empty? args) (= nop "*")) "1" - (and nop (= 1 (count args)) (cmp1-ops nop)) (str "(begin " (first args) " #t)") - nop (order-args (fn [as] (str "(" nop " " (str/join " " as) ")"))) - ;; (:k coll [default]) -> (jolt-get coll :k [default]) — the key (fnode) is a - ;; const, so only the coll/default args carry order. When the inference typed - ;; the receiver as a record whose declared fields include :k (it carries the - ;; field-order :shape), read the field by its static slot — no field-key - ;; lookup, no jolt-get dispatch. Only the no-default form (a declared field is - ;; always present, so a default is never taken). - (= kind :keyword) - (let [recv (first arg-nodes) - idx (when (and (= :struct (:hint recv)) (= 1 (count arg-nodes))) - (struct-field-index (:shape recv) (:val fnode)))] - (if idx - (order-args (fn [as] (str "(jrec-field-at " (first as) " " idx " " (emit fnode) ")"))) - (order-args (fn [as] (str "(jolt-get " (first as) " " (emit fnode) (defstr as) ")"))))) - ;; (coll k [default]) -> lookup — coll (fnode) is the callee, evaluated - ;; before the key/default args. A VECTOR literal invokes as nth (a bad - ;; index throws, IPersistentVector.invoke); maps/sets invoke as get. - (= kind :coll) - (ordered-call (cons fnode arg-nodes) (cons (emit fnode) args) - (fn [[c & as]] - (str (if (and (= :vector (:op fnode)) (= 1 (count as))) - "(jolt-nth " - "(jolt-get ") - c " " (str/join " " as) ")"))) - (and (stdlib-var? fnode) (not (deref prelude-mode?))) - (throw (ex-info (str "emit: unsupported stdlib fn `" (:ns fnode) "/" (:name fnode) - "` (no core on Chez yet)") {})) - ;; static method call (Class/method arg*) -> (host-static-call ...). - (= :host-static (:op fnode)) - (order-args (fn [as] - (str "(host-static-call " (chez-str-lit (:class fnode)) " " (chez-str-lit (:member fnode)) - (if (empty? as) "" (str " " (str/join " " as))) ")"))) - (= :host (:op fnode)) - (throw (ex-info (str "emit: unsupported host call `" (:name fnode) "`") {})) - ;; a :local callee: a known procedure (the letrec-bound self-name of a named - ;; fn — i.e. self-recursion) is a real Scheme proc, so call it directly with - ;; no jolt-invoke / arg consing; case-lambda handles arity. Any other local - ;; holds an arbitrary IFn -> dynamic dispatch. - (= :local (:op fnode)) - (if (*known-procs* (munge-name (:name fnode))) - (order-args (fn [as] (emit-call tail? (munge-name (:name fnode)) as))) - (invoke)) - ;; closed-world direct call: the callee var is an app fn def already emitted - ;; with a Scheme binding — apply it directly, no var lookup, no jolt-invoke. - ;; Only fn-valued defs qualify; a non-fn invokable value (a map/set/keyword - ;; held in a var) isn't a Scheme procedure, so it falls through to jolt-invoke - ;; below (which still uses the direct binding as the invoke target). - (and (= :var (:op fnode)) (direct-linkable? (:ns fnode) (:name fnode)) - (direct-link-fn? (:ns fnode) (:name fnode))) - (order-args (fn [as] (emit-call tail? (dl-name (:ns fnode) (:name fnode)) as))) - ;; a late-bound :var call head can hold a procedure OR a non-applicable - ;; value the RT dispatches (multimethod, keyword/coll IFn) — route via - ;; jolt-invoke (transparent for a procedure). - (= :var (:op fnode)) - (invoke) - ;; a computed callee can yield ANY IFn — route through jolt-invoke. - :else - (invoke)))))) - -;; try/catch/finally. throw raises a Chez condition wrapping the jolt value -;; (jolt-throw = Scheme `raise` of a &jolt-throw condition); catch lowers to -;; `guard`, whose raw binding is unwrapped via jolt-unwrap-throw so the catch var -;; receives the jolt value (preserving ex-data/ex-message and the backtrace -;; identity tag). finally lowers to `dynamic-wind`'s after-thunk (runs on -;; success, catch and escape — Clojure finally semantics). Both keys optional. -(defn- emit-try [node] - (let [core (if-let [cs (:catch-sym node)] - (let [raw (munge-name (:catch-raw-sym node))] - (str "(guard (" raw " (else (let ((" (munge-name cs) " (jolt-unwrap-throw " raw "))) " - (emit (:catch-body node)) "))) " - (emit (:body node)) ")")) - (emit (:body node)))] - (if-let [fin (:finally node)] - (str "(dynamic-wind (lambda () #f) (lambda () " core ") (lambda () " (emit fin) "))") - core))) - -;; Does this IR node emit to an expression that yields a Scheme boolean? Used to -;; drop the redundant jolt-truthy? on an :if test. Sees through the let*/if an -;; (or ...)/(and ...) of bool-returning ops desugars to: `or` is -;; (let* [g E1] (if (truthy? g) g E2)), `and` is (let* [g E1] (if (truthy? g) E2 g)) -;; — both return a Scheme boolean when E1/E2 are bool ops, since the value yielded -;; is always one of the (boolean) operand results. `bools` tracks let-bound locals -;; proven to hold a Scheme boolean. -(defn- returns-scheme-bool? - ([node] (returns-scheme-bool? node #{})) - ([node bools] - (cond - (and (= :const (:op node)) (boolean? (:val node))) true - (= :invoke (:op node)) - (let [nop (native-op (:fn node) (count (:args node)))] - (boolean (and nop (bool-returning-ops nop)))) - (= :local (:op node)) (contains? bools (:name node)) - (= :if (:op node)) - (and (returns-scheme-bool? (:then node) bools) - (returns-scheme-bool? (:else node) bools)) - (= :let (:op node)) - (let [bools' (reduce (fn [s b] - (if (returns-scheme-bool? (nth b 1) s) - (conj s (nth b 0)) - (disj s (nth b 0)))) - bools (:bindings node))] - (returns-scheme-bool? (:body node) bools')) - :else false))) - -;; In trace mode, a fn def also registers its source so the tail-frame history maps -;; the recorded frame-name to "ns/name (file:line)" instead of a bare name. Keyed by -;; the SAME munged name the entry push records (emit-fn's letrec self-binding = the -;; fn's own name). Returns "" when off / not a positioned fn def, so trace-off output -;; (seed mint, `jolt build`) is byte-identical. Direct-link builds already register -;; via emit-def-cached; this covers the open-world eval path. -(defn- trace-source-reg [node] - (let [init (:init node) pos (:pos node)] - (if (and @trace-frames? (= :fn (:op init)) (:name init) pos) - (str " (jolt-register-source! " (chez-str-lit (munge-name (:name init))) " " - (chez-str-lit (:ns node)) " " (chez-str-lit (:name node)) " " - (if (:file pos) (chez-str-lit (:file pos)) "jolt-nil") " " - (or (:line pos) 0) ")") - ""))) - -(defn emit* [node] - (case (:op node) - :const (emit-const (:val node)) - :local (munge-name (:name node)) - ;; late-bound var: read the cell's current root at use time. A value-position - ;; ref to a clojure.core fn the RT provides lowers to the RT procedure. - :var (let [core-proc (and (= "clojure.core" (:ns node)) (core-value-procs (:name node)))] - (cond - core-proc core-proc - ;; direct-linked app var used as a value -> reference its binding (same - ;; root as the var cell for a final var; helps DCE keep it live). - (direct-linkable? (:ns node) (:name node)) (dl-name (:ns node) (:name node)) - (and (stdlib-var? node) (not (deref prelude-mode?))) - (throw (ex-info (str "emit: unsupported stdlib ref `" (:ns node) "/" (:name node) - "` (no core on Chez yet)") {})) - ;; inside a def, cache the interned var cell in a per-site cell so the - ;; name lookup (string-append + hash) runs once, not per access; the - ;; cell is stable and def-var! mutates its root in place, so this stays - ;; correct under redefinition. Read through var-cell-deref — the - ;; cell-based var-deref: binding-aware (a thread-bound dynamic var - ;; resolves to its binding) AND lenient on an unbound root (the strict - ;; jolt-var-get throws on a forward-declared var). Outside a def, - ;; resolve per access. - :else - (let [cells @cache-cells - nslit (chez-str-lit (:ns node)) nmlit (chez-str-lit (:name node))] - (if (and @var-cache? cells) - (let [c (fresh-label "_vc$")] - (swap! cells conj c) - (str "(var-cell-deref (or " c " (let ((_v (jolt-var " nslit " " nmlit "))) (set! " c " _v) _v)))")) - (str "(var-deref " nslit " " nmlit ")"))))) - :the-var (str "(jolt-var " (chez-str-lit (:ns node)) " " (chez-str-lit (:name node)) ")") - ;; (set! *var* val) -> set the var's innermost binding (else root); returns val. - :set-var (str "(jolt-var-set " (emit (:the-var node)) " " (emit (:val node)) ")") - ;; (set! (.-field obj) val) -> mutate the deftype instance field in place. - :set-field (str "(jolt-set-field! " (emit (:obj node)) " (keyword #f " - (chez-str-lit (:field node)) ") " (emit (:val node)) ")") - ;; a non-top-level defmacro -> def the expander fn + mark the var a macro at - ;; runtime (the spine does the same for top-level forms). - :defmacro (str "(begin (def-var! " (chez-str-lit (:ns node)) " " (chez-str-lit (:name node)) " " - (emit (:fn node)) ") (mark-macro! " (chez-str-lit (:ns node)) " " - (chez-str-lit (:name node)) ") jolt-nil)") - :host (throw (ex-info (str "emit: unsupported host ref `" (:name node) "`") {})) - :host-static (str "(host-static-ref " (chez-str-lit (:class node)) " " - (chez-str-lit (:member node)) ")") - :host-new (str "(host-new " (chez-str-lit (:class node)) - (let [args (map emit (:args node))] - (if (empty? args) "" (str " " (str/join " " args)))) ")") - ;; the test is non-tail; then/else inherit the if's tail position - :if (let [test (:test node) - t (binding [*tail?* false] - (if (returns-scheme-bool? test) (emit test) - (str "(jolt-truthy? " (emit test) ")")))] - (str "(if " t " " (emit (:then node)) " " (emit (:else node)) ")")) - ;; non-last statements are non-tail; the ret inherits the do's tail position - :do (str "(begin " (binding [*tail?* false] (str/join " " (mapv emit (:statements node)))) - (if (empty? (:statements node)) "" " ") (emit (:ret node)) ")") - :invoke (emit-invoke node) - ;; collection literals -> rt constructors (collections.ss). Elements are - ;; already-analyzed IR nodes; evaluate LEFT-TO-RIGHT (emit-ordered). - :vector (emit-ordered "jolt-vector" (map emit (:items node))) - :set (emit-ordered "jolt-hash-set" (map emit (:items node))) - :map (emit-ordered "jolt-hash-map" - (mapcat (fn [p] [(emit (nth p 0)) (emit (nth p 1))]) (:pairs node))) - :quote (emit-quoted (:form node)) - :throw (str "(jolt-throw " (emit (:expr node)) ")") - ;; numeric coercion (from an inlined ^double/^long param or return). - :coerce (let [e (emit (:expr node))] - (cond (= :double (:kind node)) (str "(exact->inexact " e ")") - (= :long (:kind node)) (str "(jolt->fx " e ")") - :else e)) - :try (emit-try node) - ;; regex literal #"…" -> a jolt-regex value (regex.ss, vendored irregex). - :regex (str "(jolt-regex " (chez-str-lit (:source node)) ")") - ;; #inst / #uuid literals -> runtime inst / uuid values. - :inst (str "(jolt-inst-from-string " (chez-str-lit (:source node)) ")") - :uuid (str "(jolt-uuid-from-string " (chez-str-lit (:source node)) ")") - ;; bigdecimal literal (1.5M) -> a runtime jbigdec from its numeric text. - :bigdec (str "(jolt-bigdec-from-string " (chez-str-lit (:source node)) ")") - ;; a namespace value spliced into a form (~*ns*) -> reconstruct by name. - :the-ns (str "(intern-ns! " (chez-str-lit (:name node)) ")") - ;; (.method target arg*) -> jolt-host-call for an rt-shimmed method, else - ;; record-method-dispatch (a reify/record protocol method). - :host-call (let [m (:method node) - target (emit (:target node)) - args (map emit (:args node))] - (if (supported-host-methods m) - (str "(jolt-host-call " (chez-str-lit m) " " target - (if (empty? args) "" (str " " (str/join " " args))) ")") - (str "(record-method-dispatch " target " " (chez-str-lit m) - " (jolt-vector" (if (empty? args) "" (str " " (str/join " " args))) "))"))) - :let (emit-let node) - :loop (emit-loop node) - :recur (emit-recur node) - :ffi-fn (emit-ffi-fn node) - :ffi-callable (emit-ffi-callable node) - :fn (emit-fn node) - ;; (def name) with no init (declare): reserve the cell. A def with non-empty - ;; reader metadata lowers to def-var-with-meta! (ported in a later increment). - :def (let [reg (trace-source-reg node) - d (cond - (:no-init node) - (str "(declare-var! " (chez-str-lit (:ns node)) " " (chez-str-lit (:name node)) ")") - (jmeta-nonempty? (:meta node)) - (str "(def-var-with-meta! " (chez-str-lit (:ns node)) " " (chez-str-lit (:name node)) " " - (emit-with-cells #(emit (:init node))) " " (emit-def-meta node) ")") - :else - (str "(def-var! " (chez-str-lit (:ns node)) " " (chez-str-lit (:name node)) " " - (emit-with-cells #(emit (:init node))) ")"))] - (if (= reg "") d (str "(begin " d reg ")"))) - (throw (ex-info (str "emit: op not yet ported / unhandled: " (pr-str (:op node))) {})))) - -;; ^:dynamic / ^:redef on a def opts it out of direct-linking: it stays redefinable, -;; so callers must go through the var cell. m is a def's :meta (a jolt map value). -(defn- dl-opt-out? [m] (or (get m :dynamic) (get m :redef))) - -;; Per-form entry used by the image/build emitter. In direct-link mode a TOP-LEVEL -;; def (form root, or spliced from a top-level do) without an opt-out also binds -;; jv$ and aliases the var cell to it, so app->app calls/refs bind directly. -;; Off direct-link mode this is exactly `emit`, so the seed mint and runtime eval are -;; byte-unchanged. Nested defs (a defonce's inner def) never reach a top-level branch -;; here, so they stay indirect — a `define` would be illegal in their position. -;; Emit a def, wrapping its init in a let that binds each per-site cache cell -;; (var-ref + devirt) so a hot loop's lookups resolve once into the def's closure. -;; Runs in BOTH modes; in direct-link mode a non-opt-out def also binds jv$ -;; and registers it for app->app direct linking + a source-map frame. -(defn- emit-def-cached [node] - (let [ns (:ns node) nm (:name node) - dl? (and @direct-link? (not (dl-opt-out? (:meta node)))) - b (dl-name ns nm) - fn? (= :fn (:op (:init node))) - ;; A fn def gets a source-registry entry so a native backtrace can map its - ;; frame to ns/name (file:line). Chez names the frame by whatever emit-fn - ;; binds the lambda to: a NAMED fn (defn, or (fn foo …)) gets a letrec - ;; self-binding = munge-name of the fn's own name; an ANONYMOUS fn def has - ;; no letrec, so the lambda sits directly under (define jv$ns$name …) and - ;; takes that name. Register under whichever Chez will report. - pos (:pos node) - frame-name (when fn? (if-let [fnm (:name (:init node))] (munge-name fnm) b)) - reg (when (and dl? fn? pos) - (str " (jolt-register-source! " (chez-str-lit frame-name) " " - (chez-str-lit ns) " " (chez-str-lit nm) " " - (if (get pos :file) (chez-str-lit (get pos :file)) "jolt-nil") " " - (or (get pos :line) 0) ")")) - ;; register before emitting the init so a self-referential body direct-links. - _ (when dl? (swap! direct-link-defined conj (dl-fqn ns nm)) - (when fn? (swap! direct-link-fns conj (dl-fqn ns nm)))) - init (emit-with-cells #(emit (:init node)))] - (cond - dl? - (if (jmeta-nonempty? (:meta node)) - (str "(begin (define " b " " init ") (def-var-with-meta! " - (chez-str-lit ns) " " (chez-str-lit nm) " " b " " (emit-def-meta node) ")" (or reg "") ")") - (str "(begin (define " b " " init ") (def-var! " - (chez-str-lit ns) " " (chez-str-lit nm) " " b ")" (or reg "") ")")) - (jmeta-nonempty? (:meta node)) - (str "(def-var-with-meta! " (chez-str-lit ns) " " (chez-str-lit nm) " " init " " (emit-def-meta node) ")") - :else - (str "(def-var! " (chez-str-lit ns) " " (chez-str-lit nm) " " init ")")))) - -(defn emit-top-form [node] - (cond - ;; off direct-link (the seed mint + runtime-via-image) this is exactly `emit`, - ;; whose :def case already wraps cache cells, so the seed stays byte-unchanged. - (not @direct-link?) (emit node) - ;; top-level do splices: each statement/ret is itself a top-level form. - (= :do (:op node)) - (str "(begin " (str/join " " (map emit-top-form (:statements node))) - (if (empty? (:statements node)) "" " ") (emit-top-form (:ret node)) ")") - (and (= :def (:op node)) (not (:no-init node)) (not (dl-opt-out? (:meta node)))) - (emit-def-cached node) - :else (emit node))) diff --git a/jolt-core/jolt/deps.clj b/jolt-core/jolt/deps.clj deleted file mode 100644 index f7c6799..0000000 --- a/jolt-core/jolt/deps.clj +++ /dev/null @@ -1,174 +0,0 @@ -(ns jolt.deps - "Resolve a deps.edn into an ordered list of source roots — git + local deps - only, no Maven. A reduced tools.deps: :paths, :deps (`:git/url`+`:git/sha` / - `:local/root`), :aliases (:extra-paths / :extra-deps / :main-opts), :tasks. - - The deps walk is breadth-first so a top-level coordinate registers before any - transitive one (a top-level pin wins). Git deps clone into a sha-immutable - cache ($JOLT_GITLIBS, else ~/.jolt/gitlibs) shared across projects. Resolution - shells out to `git` through jolt.host/sh; nothing here touches the JVM." - (:require [clojure.edn :as edn] - [clojure.string :as str])) - -;; --- small host seams ------------------------------------------------------- -(defn- getenv [n] (jolt.host/getenv n)) -(defn- file-exists? [p] (jolt.host/file-exists? p)) -(defn- sh [cmd] (jolt.host/sh cmd)) ; exit code, inherits stdout/stderr -(defn- sh-out [cmd] (jolt.host/sh-out cmd)) ; captured stdout -(defn- warn [& xs] (println (str "[jolt.deps] " (apply str xs)))) - -(defn- read-edn [path] - (when (file-exists? path) - (try (edn/read-string (slurp path)) - (catch :default e (warn "could not read " path ": " (ex-message e)) nil)))) - -(defn- abspath [dir p] - (if (str/starts-with? p "/") p (str dir "/" p))) - -;; --- git cache -------------------------------------------------------------- -(defn- gitlibs-dir [] - (or (getenv "JOLT_GITLIBS") - (str (or (getenv "HOME") ".") "/.jolt/gitlibs"))) - -(defn- alnum? [c] - (let [n (int c)] - (or (and (>= n 48) (<= n 57)) ; 0-9 - (and (>= n 65) (<= n 90)) ; A-Z - (and (>= n 97) (<= n 122))))) ; a-z -(defn- sanitize [s] - (str/join (map (fn [c] (if (or (alnum? c) (= c \.) (= c \-)) c \_)) (seq s)))) - -(defn- ensure-git - "Clone url at sha into the cache (once); return the checkout dir." - [url sha] - (let [dir (str (gitlibs-dir) "/" (sanitize url) "/" sha)] - (if (file-exists? dir) - dir - (do - (warn "fetching " url " @ " (subs sha 0 (min 12 (count sha)))) - (sh (str "mkdir -p " (pr-str dir))) - (when-not (zero? (sh (str "git clone --quiet " (pr-str url) " " (pr-str dir)))) - (throw (ex-info (str "git clone failed: " url) {:url url}))) - (when-not (zero? (sh (str "git -C " (pr-str dir) " checkout --quiet " (pr-str sha)))) - (throw (ex-info (str "git checkout failed: " sha " in " url) {:url url :sha sha}))) - ;; submodules are pinned in the checkout; pull them if the dep uses any. - (sh (str "git -C " (pr-str dir) " submodule update --init --recursive --quiet")) - dir)))) - -;; --- coordinate -> root dir ------------------------------------------------- -(defn- coord-root - "The on-disk root directory for one dependency coordinate, or nil to skip." - [coord spec base-dir] - (cond - (:local/root spec) (abspath base-dir (:local/root spec)) - (and (:git/url spec) (:git/sha spec)) - (let [checkout (ensure-git (:git/url spec) (:git/sha spec))] - (if-let [root (:deps/root spec)] (str checkout "/" root) checkout)) - (:jolt/module spec) - (do (warn "skipping janet dependency " coord " (:jolt/module is obsolete on Chez)") nil) - ;; jolt IS Clojure — a dependency on org.clojure/clojure is satisfied - ;; intrinsically, so skip it silently rather than warning about the (unusable) - ;; :mvn/version coordinate. - (= coord 'org.clojure/clojure) nil - :else - (do (warn "skipping unsupported coordinate " coord " " (pr-str spec)) nil))) - -(defn- dep-source-roots - "Source roots a resolved dep contributes: its deps.edn :paths (default [\"src\"]) - resolved under its root dir." - [root] - (let [edn (read-edn (str root "/deps.edn")) - paths (or (:paths edn) ["src"])] - (map #(abspath root %) paths))) - -;; --- reconciliation --------------------------------------------------------- -;; Dependencies are resolved as a TREE (resolve-deps' BFS, which visits each -;; coordinate once) and then reconciled into a definitive, de-duplicated set — -;; one place, not ad-hoc per call site. dedup-by keeps the first item per key, -;; order preserved; it dedups both source roots (by path) and native libraries -;; (by identity), so an app pulling two libs that declare the same shared object -;; (e.g. libcrypto via both http-client and the ring adapter) includes and loads -;; it ONCE. -(defn- dedup-by [key xs] - (second (reduce (fn [[seen acc] x] - (let [k (key x)] - (if (contains? seen k) [seen acc] [(conj seen k) (conj acc x)]))) - [#{} []] xs))) - -(defn- native-key - "Identity of a :jolt/native spec. A :process lib (the running process's own - symbols, e.g. libc) keys on that flag; a file lib on its :name, else on its - platform candidate paths — two deps naming the same lib reconcile to one load." - [spec] - (letfn [(cands [k] (let [v (get spec k)] (cond (string? v) [v] (sequential? v) (vec v) :else [])))] - (if (:process spec) - [:process (:name spec)] - [:native (or (:name spec) (vec (sort (concat (cands :darwin) (cands :linux)))))]))) - -(defn- resolve-deps - "Breadth-first walk of a deps map; returns {:roots [...] :natives [...]} — the - source-root directories and the collected :jolt/native declarations from every - dep's deps.edn (raw, in walk order; reconcile-project dedups them). `base-dir` - resolves :local/root and is replaced by a dep's own root as the walk descends." - [deps base-dir] - ;; queue grows by appending children at the tail; an index cursor walks it so - ;; each dequeue is O(1) (was (subvec (vec queue) 1) per pop -> O(n^2)). - (loop [queue (mapv (fn [[c s]] [c s base-dir]) (seq deps)) - i 0 - seen #{} - roots [] - natives []] - (if (>= i (count queue)) - {:roots roots :natives natives} - (let [[coord spec bd] (nth queue i) - i (inc i)] - (if (contains? seen coord) - (recur queue i seen roots natives) - (let [root (coord-root coord spec bd)] - (if (nil? root) - (recur queue i (conj seen coord) roots natives) - (let [edn (read-edn (str root "/deps.edn")) - child (mapv (fn [[c s]] [c s root]) (seq (:deps edn)))] - (recur (into queue child) - i - (conj seen coord) - (into roots (dep-source-roots root)) - (into natives (:jolt/native edn))))))))))) - -;; --- public ----------------------------------------------------------------- -(defn resolve-project - "Resolve `project-dir`'s deps.edn with the selected alias keywords. Returns - {:roots [...] :main-opts [...] :tasks {...} :natives [...]}; :main-opts is the - last selected alias's, else nil; :natives are the project's + deps' :jolt/native - shared-library declarations." - ([project-dir] (resolve-project project-dir [])) - ([project-dir alias-kws] - (let [edn (read-edn (str project-dir "/deps.edn")) - aliases (:aliases edn) - selected (keep #(get aliases %) alias-kws) - extra-paths (mapcat :extra-paths selected) - extra-deps (apply merge (map :extra-deps selected)) - main-opts (some :main-opts (reverse selected)) - project-paths (concat (or (:paths edn) ["src"]) extra-paths) - project-roots (map #(abspath project-dir %) project-paths) - all-deps (merge (:deps edn) extra-deps) - {dep-roots :roots dep-natives :natives} (resolve-deps all-deps project-dir)] - ;; reconcile: the project's own roots/natives + every dep's, deduped once. - {:roots (dedup-by identity (concat project-roots dep-roots)) - :main-opts main-opts - ;; the project's own paths (relative to project-dir) and absolute resource - ;; roots, plus its :jolt/build options — `jolt build` uses these to bundle - ;; resources into / alongside a standalone binary. - :project-dir project-dir - :project-paths (vec project-paths) - :project-roots (vec project-roots) - :build (:jolt/build edn) - :embed-dirs (mapv #(abspath project-dir %) (:embed (:jolt/build edn))) - :tasks (:tasks edn) - :natives (dedup-by native-key (concat (:jolt/native edn) dep-natives)) - ;; nREPL middleware a library contributes (jolt.nrepl composes them over its - ;; built-in handler) — symbols resolving to a middleware fn or a vector of them. - :nrepl-middleware (:nrepl/middleware edn)}))) - -(defn has-deps-edn? [project-dir] - (file-exists? (str project-dir "/deps.edn"))) diff --git a/jolt-core/jolt/ir.clj b/jolt-core/jolt/ir.clj index 2ae650d..b869f24 100644 --- a/jolt-core/jolt/ir.clj +++ b/jolt-core/jolt/ir.clj @@ -20,21 +20,13 @@ ;; end emits the embedded var cell so `binding`'s thread-binding frame can key on it. (defn the-var [ns name] {:op :the-var :ns ns :name name}) -;; A name that resolves only via the host's own environment (e.g. + or int?) — -;; the back end emits a host-appropriate reference. +;; A runtime primitive (cons, +, get, apply, …) the back end maps to the host RT. +(defn rt [name] {:op :rt :name name}) + +;; A name that resolves only via the host's own environment (e.g. + or int? on +;; Janet) — the back end emits a host-appropriate reference. (defn host-ref [name] {:op :host :name name}) -;; A qualified static reference to a host class member, `Class/member` (e.g. -;; Math/sqrt, Long/MAX_VALUE, System/getenv). A leaf node carrying the class and -;; member names. The Chez back end lowers a value ref to host-static-ref and a -;; call head to host-static-call (host-static.ss). -(defn host-static [class member] {:op :host-static :class class :member member}) - -;; A host constructor, `(Class. args*)` / `(new Class args*)`. Carries the class -;; name and the analyzed argument nodes. Chez lowers to host-new (host-static.ss -;; class-ctor registry). -(defn host-new [class args] {:op :host-new :class class :args args}) - (defn if-node [test then else] {:op :if :test test :then then :else else}) (defn do-node [statements ret] {:op :do :statements statements :ret ret}) @@ -66,110 +58,4 @@ (defn quote-node [form] {:op :quote :form form}) (defn throw-node [expr] {:op :throw :expr expr}) -;; Numeric coercion of a value to a primitive kind (:double / :long), the way a JVM -;; ^double/^long parameter or return coerces. The back end lowers it (exact->inexact -;; / jolt->fx) and jolt.passes.numeric reads its :kind as the value's numeric kind. -;; Carrying coercion as an IR node (rather than a back-end string wrap) lets it -;; travel with inlining and keeps the typed-arithmetic fast path sound. -(defn coerce-node [kind expr] {:op :coerce :kind kind :expr expr}) - -;; --------------------------------------------------------------------------- -;; Structural recursion over IR child nodes. -;; -;; A tree-rewriting pass recurses into each op's child NODE positions and -;; rebuilds the node; this combinator does that one place, so the per-op child -;; layout is single-sourced and adding an op is a one-site change here (was: an -;; edit to every walk). `(map-ir-children f node)` returns node with f applied to -;; each child IR node — re-applied per element for seq positions (:args/:items/ -;; :statements), per value for :map pairs, per init for :let/:loop bindings, and -;; per arity :body for :fn. Non-node positions (binding NAMES, fn :params/:rest, -;; the :op tag, :ns/:name/:val) are left intact. Leaf ops and any op with no -;; child nodes pass through unchanged, so walks built on this are TOTAL over the -;; op set (an unknown op recurses nowhere rather than being silently dropped). -;; -;; Uses cond/=/get only — same constructs as the passes that consume it, so it -;; loads at the same compiler tier with no new macro dependency. -(defn map-ir-children [f node] - (let [op (get node :op)] - (cond - (= op :if) (assoc node :test (f (get node :test)) - :then (f (get node :then)) - :else (f (get node :else))) - (= op :do) (assoc node :statements (mapv f (get node :statements)) - :ret (f (get node :ret))) - (= op :throw) (assoc node :expr (f (get node :expr))) - (= op :coerce) (assoc node :expr (f (get node :expr))) - (= op :set-var) (assoc node :val (f (get node :val))) - (= op :set-field) (assoc node :obj (f (get node :obj)) :val (f (get node :val))) - (= op :defmacro) (assoc node :fn (f (get node :fn))) - (= op :ffi-callable) (assoc node :fn (f (get node :fn))) - (= op :invoke) (assoc node :fn (f (get node :fn)) - :args (mapv f (get node :args))) - (= op :vector) (assoc node :items (mapv f (get node :items))) - (= op :set) (assoc node :items (mapv f (get node :items))) - (= op :map) (assoc node :pairs (mapv (fn [pr] [(f (nth pr 0)) (f (nth pr 1))]) - (get node :pairs))) - (= op :let) (assoc node :bindings (mapv (fn [b] [(nth b 0) (f (nth b 1))]) - (get node :bindings)) - :body (f (get node :body))) - (= op :loop) (assoc node :bindings (mapv (fn [b] [(nth b 0) (f (nth b 1))]) - (get node :bindings)) - :body (f (get node :body))) - (= op :recur) (assoc node :args (mapv f (get node :args))) - (= op :fn) (assoc node :arities (mapv (fn [a] (assoc a :body (f (get a :body)))) - (get node :arities))) - (= op :def) (let [n (assoc node :init (f (get node :init)))] - (if (get node :meta-expr) - (assoc n :meta-expr (f (get node :meta-expr))) - n)) - (= op :host-call) (assoc node :target (f (get node :target)) - :args (mapv f (get node :args))) - (= op :host-new) (assoc node :args (mapv f (get node :args))) - ;; :catch-body / :finally are optional; recurse them only when PRESENT. - ;; Assoc'ing them nil-when-absent would turn the node into a phm (jolt's - ;; nil-valued-key representation) and force backend densification — so we - ;; preserve the node's shape and never introduce a nil key. - (= op :try) - (let [n (assoc node :body (f (get node :body))) - n (if (get node :catch-body) (assoc n :catch-body (f (get node :catch-body))) n) - n (if (get node :finally) (assoc n :finally (f (get node :finally))) n)] - n) - ;; :const :local :var :host :host-static :the-var :quote — no child nodes - :else node))) - -;; The read-only companion to map-ir-children: fold f over node's child IR nodes, -;; left to right, threading acc — same single-sourced child layout, so a read-only -;; analysis (size/closedness/purity) built on it is TOTAL over the op set (an -;; unknown op, or a leaf, folds over no children and returns acc unchanged). Skips -;; the same non-node positions map-ir-children does (binding NAMES, fn :params/ -;; :rest, :op/:ns/:name/:val). f is (acc child) -> acc. -(defn reduce-ir-children [f acc node] - (let [op (get node :op)] - (cond - (= op :if) (f (f (f acc (get node :test)) (get node :then)) (get node :else)) - (= op :do) (f (reduce f acc (get node :statements)) (get node :ret)) - (= op :throw) (f acc (get node :expr)) - (= op :coerce) (f acc (get node :expr)) - (= op :set-var) (f acc (get node :val)) - (= op :set-field) (f (f acc (get node :obj)) (get node :val)) - (= op :defmacro) (f acc (get node :fn)) - (= op :ffi-callable) (f acc (get node :fn)) - (= op :invoke) (reduce f (f acc (get node :fn)) (get node :args)) - (= op :vector) (reduce f acc (get node :items)) - (= op :set) (reduce f acc (get node :items)) - (= op :map) (reduce (fn [a pr] (f (f a (nth pr 0)) (nth pr 1))) acc (get node :pairs)) - (= op :let) (f (reduce (fn [a b] (f a (nth b 1))) acc (get node :bindings)) (get node :body)) - (= op :loop) (f (reduce (fn [a b] (f a (nth b 1))) acc (get node :bindings)) (get node :body)) - (= op :recur) (reduce f acc (get node :args)) - (= op :fn) (reduce (fn [a ar] (f a (get ar :body))) acc (get node :arities)) - (= op :def) (let [a (if (get node :init) (f acc (get node :init)) acc)] - (if (get node :meta-expr) (f a (get node :meta-expr)) a)) - (= op :host-call) (reduce f (f acc (get node :target)) (get node :args)) - (= op :host-new) (reduce f acc (get node :args)) - (= op :try) - (let [a (f acc (get node :body)) - a (if (get node :catch-body) (f a (get node :catch-body)) a) - a (if (get node :finally) (f a (get node :finally)) a)] - a) - ;; leaves and any op with no child nodes - :else acc))) +(defn op [node] (:op node)) diff --git a/jolt-core/jolt/main.clj b/jolt-core/jolt/main.clj deleted file mode 100644 index 9254099..0000000 --- a/jolt-core/jolt/main.clj +++ /dev/null @@ -1,334 +0,0 @@ -(ns jolt.main - "The jolt CLI dispatch: resolve a project's deps.edn, set the source roots, and - run a namespace's -main, a file, a deps.edn task, or a REPL. Driven by cli.ss, - which hands it the raw argv; the project directory is JOLT_PWD (the user's cwd - before the launcher cd'd to the jolt repo)." - (:require [jolt.deps :as deps] - [clojure.string :as str])) - -(defn- project-dir [] (or (jolt.host/getenv "JOLT_PWD") ".")) - -(defn- version [] (jolt.host/jolt-version)) - -(defn- current-platform [] - (let [os (str/lower-case (or (System/getProperty "os.name") ""))] - (cond (str/includes? os "mac") :darwin - (str/includes? os "win") :windows - :else :linux))) - -;; Load a library's declared native shared objects (deps.edn :jolt/native) before -;; its Clojure is required, so its foreign-fn bindings resolve. Each entry is a -;; map: {:name "sqlite3" :darwin ["libsqlite3.0.dylib" ...] :linux ["libsqlite3.so.0" ...]} -;; with optional :optional (missing is fine — a feature-gated dep) and :process -;; (use the running process's symbols, e.g. libc sockets — no external file). -(defn- load-natives! [natives] - (when (seq natives) - (let [plat (current-platform)] - (doseq [spec natives] - (if (:process spec) - (jolt.ffi/load-library) - (let [c (get spec plat) - cands (if (string? c) [c] (vec c)) - hit (some #(when (jolt.ffi/loaded? %) %) cands)] - ;; A :static spec has no runtime shared object (it's linked into a - ;; built binary), so an interpreted `run`/`repl` has nothing to load — - ;; skip it rather than fail. Its foreign calls only resolve in a static - ;; build; document a dynamic candidate too to use it under `run`. - (when (and (nil? hit) (not (:optional spec)) (not (:static spec))) - (throw (ex-info (str "required native library " - (or (:name spec) (first cands) "?") - " not found — tried " (pr-str cands) " for " (name plat)) - {:native spec}))))))))) - -;; Apply a resolved project's roots on top of the current (jolt-core) roots so app -;; namespaces resolve while jolt.* stays loadable, then load its native deps. -(defn- apply-project! [{:keys [roots natives]}] - (jolt.host/set-source-roots! (vec (distinct (concat roots (jolt.host/source-roots))))) - (load-natives! natives)) - -(defn- run-ns - "Require ns-name and invoke its -main with the string app args." - [ns-name app-args] - (require (symbol ns-name)) - (if-let [mainv (ns-resolve (symbol ns-name) (symbol "-main"))] - (apply (deref mainv) app-args) - (throw (ex-info (str "namespace " ns-name " has no -main") {:ns ns-name})))) - -;; main-opts is a vector like ["-m" "app.core"] (optionally trailing args). Apply -;; it with the user-supplied extra args appended. -(defn- apply-main-opts [main-opts extra-args] - (cond - (and (seq main-opts) (= "-m" (first main-opts))) - (run-ns (second main-opts) (concat (drop 2 main-opts) extra-args)) - :else - (throw (ex-info (str "unsupported :main-opts " (pr-str main-opts)) {})))) - -(defn- parse-aliases [s] ; "-M:a:b" / ":a:b" -> [:a :b] - (let [s (if (str/starts-with? s "-") (subs s 2) s)] - (->> (str/split s #":") (remove str/blank?) (map keyword) vec))) - -;; run [-m NS args… | FILE] -(defn- cmd-run [more] - (apply-project! (deps/resolve-project (project-dir))) - (cond - (= "-m" (first more)) (run-ns (second more) (drop 2 more)) - (seq more) (do (load-file (first more)) nil) - :else (throw (ex-info "run needs -m NS or a FILE" {})))) - -;; -M:alias… — resolve with the aliases, run their :main-opts -(defn- cmd-M [arg more] - (let [aliases (parse-aliases arg) - {:keys [main-opts] :as resolved} (deps/resolve-project (project-dir) aliases)] - (apply-project! resolved) - (if main-opts - (apply-main-opts main-opts more) - (throw (ex-info (str "alias(es) " (pr-str aliases) " have no :main-opts") {}))))) - -;; -A:alias… — add the aliases' paths/deps, then run the remaining argv as a command -(defn- cmd-A [arg more] - (let [aliases (parse-aliases arg)] - (apply-project! (deps/resolve-project (project-dir) aliases)) - (when (seq more) (run-ns (second more) (drop 2 more))))) - -(defn- cmd-path [] - (let [{:keys [roots]} (deps/resolve-project (project-dir))] - (println (str/join ":" roots)))) - -(defn- repl-form-complete? - "True when `s` has balanced ()/[]/{}, no open string/char/regex, and at most - a trailing comment past the last form. Drives the REPL's read-until-complete - decision so a form split across lines is accumulated, not evaluated half-read." - [s] - (let [n (count s)] - (loop [i 0 depth 0 state :code] ; state: :code :string :regex :comment - (if (>= i n) - (and (<= depth 0) (#{:code :comment} state)) - (let [c (get s i)] - (case state - :code (cond - (= c \;) (recur (inc i) depth :comment) - (= c \\) (recur (+ i 2) depth :code) ; char literal: \( - (= c \") (recur (inc i) depth :string) - (= c \#) (if (= (get s (inc i)) \") - (recur (+ i 2) depth :regex) ; consume the #" together - (recur (inc i) depth :code)) - (#{\( \[ \{} c) (recur (inc i) (inc depth) :code) - (#{\) \] \}} c) (recur (inc i) (dec depth) :code) - :else (recur (inc i) depth :code)) - :string (cond - (= c \\) (recur (+ i 2) depth :string) ; escaped char - (= c \") (recur (inc i) depth :code) - :else (recur (inc i) depth :string)) - :regex (cond - (= c \\) (recur (+ i 2) depth :regex) - (= c \") (recur (inc i) depth :code) - :else (recur (inc i) depth :regex)) - :comment (recur (inc i) depth - (if (#{\newline \return} c) :code :comment)))))))) - -(defn- repl-read-form [] - ;; Read lines — printing a secondary prompt for continuations — until the - ;; accumulated buffer is a complete form. Returns the (possibly multi-line) - ;; buffer, or nil on EOF at the primary prompt. - (loop [buf nil] - (print (if buf "... " "user=> ")) (flush) - (let [line (read-line)] - (cond - (nil? line) buf ; EOF: nil at primary, partial mid-form - (nil? buf) (cond - (str/blank? line) (recur nil) ; skip a blank first line - (repl-form-complete? line) line - :else (recur line)) - :else (let [nb (str buf "\n" line)] - (if (repl-form-complete? nb) nb (recur nb))))))) - -(defn- repl [] - ;; resolve the project so deps (git libs) are on the roots and native libs are - ;; loaded — same context a run gets, so (require '[some.lib]) works in the REPL. - (try (apply-project! (deps/resolve-project (project-dir))) - (catch :default _ nil)) - ;; REPL-driven development: trace by default so an uncaught error in evaluated - ;; code shows a tail-frame backtrace, no JOLT_TRACE needed (JOLT_TRACE=0 opts out). - (jolt.host/enable-trace!) - (println (str ";; jolt " (version) " repl — :repl/quit or ^D to exit")) - (loop [] - (let [form (repl-read-form)] - (when form - ;; :repl/quit / :exit exit the loop — a reliable gesture that works in any - ;; terminal, unlike ^D (some terminals/editors don't deliver it as EOF). - (if (#{:repl/quit :exit} (try (read-string form) (catch :default _ nil))) - nil - (do - (try (println (pr-str (load-string form))) - (catch :default e - (println "error:" (or (ex-message e) - (try ((resolve 'jolt.host/condition-message) e) (catch :default _ nil)) - (pr-str e))) - (when-let [bt (jolt.host/backtrace-string)] - (print bt)))) - (recur))))))) - -;; A deps.edn :tasks entry: a string is a shell command; a map is {:main-opts …}. -(defn- run-task [name more] - (let [{:keys [tasks] :as resolved} (deps/resolve-project (project-dir)) - task (get tasks (symbol name))] - (cond - (nil? task) (throw (ex-info (str "unknown command or task: " name) {:name name})) - (string? task) (jolt.host/sh task) - (map? task) (do (apply-project! resolved) (apply-main-opts (:main-opts task) more)) - :else (throw (ex-info (str "bad task " name) {}))))) - -;; build [-m NS | FILE] [-o OUT] [--opt | --dev] [--direct-link] — AOT-compile the -;; app into a standalone executable. Resolves deps + roots like `run`, then hands the -;; entry namespace to the host build driver (jolt.host/build-binary, defined by -;; build.ss). Default mode is release; --opt selects optimized, --dev unoptimized. -;; --direct-link (or deps.edn :jolt/build {:direct-link true}) opts into closed-world -;; direct-linking: app->app calls bind directly, giving up runtime redefinition of -;; those vars and eval/load-string. Off by default — release stays dynamically linked. -;; The static-link description of a :jolt/native spec for this platform, or nil. -;; :static may be flat ({:archive "…"} / {:lib "z" :libdir "…"}) or per-platform -;; ({:darwin {…} :linux {…}}). Returns a vector build.ss reads and wraps in the -;; platform's force-load flags: ["archive" abspath] or ["lib" name libdir]. -(defn- static-link-spec [spec plat] - (when-let [s (:static spec)] - (let [p (get s plat) - s (if (map? p) p s)] - (cond - (:archive s) ["archive" (:archive s)] - (:lib s) ["lib" (:lib s) (or (:libdir s) "")] - :else nil)))) - -;; Encode a deps.edn :jolt/native spec for the build launcher, resolving the -;; current platform's candidate list now (the binary runs on this OS). Each entry -;; becomes a vector the launcher (build.ss) reads: -;; ["process"] — the running binary's own symbols (libc) -;; ["static" form …] — the lib's archive, cc-linked into the binary; its -;; symbols load from the process (default when :static -;; is present and --dynamic wasn't passed) -;; ["req"|"opt" cand…] — load a shared object at runtime, trying each in turn -;; dynamic? forces the runtime path for every lib (the --dynamic build flag). -(defn- encode-natives [natives dynamic?] - (let [plat (current-platform)] - (vec (for [spec natives] - (let [static (and (not dynamic?) (static-link-spec spec plat))] - (cond - (:process spec) ["process"] - static (into ["static"] static) - :else (let [c (get spec plat) - cands (if (string? c) [c] (vec c))] - (into [(if (:optional spec) "opt" "req")] cands)))))))) - -(defn- cmd-build [more] - (let [{:keys [project-paths embed-dirs build] :as resolved} - (deps/resolve-project (project-dir))] - (apply-project! resolved) - (let [opts (loop [a more, entry nil, out nil] - (cond - (empty? a) {:entry entry :out out} - (= "-m" (first a)) (recur (drop 2 a) (second a) out) - (= "-o" (first a)) (recur (drop 2 a) entry (second a)) - (str/starts-with? (first a) "-") (recur (rest a) entry out) - :else (recur (rest a) (or entry (first a)) out))) - entry (:entry opts) - mode (cond (some #{"--opt"} more) "optimized" - (some #{"--dev"} more) "dev" - :else "release")] - (when (nil? entry) - (throw (ex-info "build needs an entry: -m NS" {}))) - ;; Output paths resolve against the project dir (JOLT_PWD), not the CLI's - ;; cwd — bin/joltc cd's to the jolt repo, so a bare relative path would land - ;; there. Default output is cargo-style under target/: --dev -> target/debug, - ;; release/--opt -> target/release, the binary named after the project dir - ;; (falling back to the entry's first segment). The .build scratch dir - ;; the driver creates sits next to it, so it lands under the same target dir. - ;; An explicit -o is honored: absolute as-is, relative against the project. - (let [pdir (project-dir) - proj (let [seg (last (str/split pdir #"/"))] - (if (or (str/blank? seg) (= "." seg)) (first (str/split entry #"\.")) seg)) - out (let [o (:out opts)] - (cond - (nil? o) (str pdir "/target/" (if (= mode "dev") "debug" "release") "/" proj) - (str/starts-with? o "/") o - :else (str pdir "/" o))) - ;; :jolt/native libs with a :static archive are cc-linked into the - ;; binary by default; --dynamic (or deps.edn :jolt/build {:dynamic-natives - ;; true}) keeps the old behavior — load a shared object at runtime. - dynamic-natives? (boolean (or (some #{"--dynamic"} more) (:dynamic-natives build))) - natives (encode-natives (:natives resolved) dynamic-natives?) - ;; closed-world direct-linking is opt-in: the --direct-link flag or a - ;; deps.edn :jolt/build {:direct-link true}. Off otherwise. - direct-link? (boolean (or (some #{"--direct-link"} more) (:direct-link build))) - ;; tree-shaking (drop library code not reachable from -main): --tree-shake - ;; or deps.edn :jolt/build {:tree-shake true}. - tree-shake? (boolean (or (some #{"--tree-shake"} more) (:tree-shake build)))] - ;; embed-dirs (absolute) are walked + baked into the binary by the driver; - ;; project-paths (relative) become runtime io/resource roots (ship-alongside). - (jolt.host/build-binary entry out mode natives embed-dirs project-paths direct-link? tree-shake?))))) - -(defn- nrepl [more] - ;; resolve the project (deps on the roots, native libs loaded), then start the - ;; nREPL server so an editor can connect and (require '[some.lib]) live. A - ;; library's middleware (deps.edn :nrepl/middleware) is composed over the - ;; built-in handler — sessions / interruptible-eval / completion etc. - (let [resolved (deps/resolve-project (project-dir))] - (apply-project! resolved) - (let [port (or (some-> (first (filter #(not (str/starts-with? % "-")) more)) parse-long) - (parse-long (or (jolt.host/getenv "JOLT_NREPL_PORT") "7888")))] - (require 'jolt.nrepl) - ;; start binds the socket synchronously on this (primordial) thread, so a - ;; failure like the port already being in use surfaces here and exits rather - ;; than being swallowed by a background thread. It then runs the accept loop - ;; on a worker thread and returns a stop fn, leaving this thread free to own - ;; the GUI main loop: glimmer's run marshals its startup here via - ;; jolt.host/call-on-main-thread — on macOS GTK quartz, g_application_run - ;; must run on the main thread or AppKit aborts when it sets the main menu. - ;; Block SIGINT in this (primordial) thread before starting the server so the - ;; accept-loop future — and the conn-handler futures it spawns — inherit a - ;; blocked SIGINT mask. Without this, ^C lands on the accept loop blocked in - ;; c-accept (a foreign call), where Chez can't fire the keyboard-interrupt - ;; handler, and the server hangs. park-until-interrupt unblocks SIGINT here - ;; once its own ^C handler is installed, so ^C reaches this thread and the - ;; shutdown hooks run cleanly. - (jolt.host/block-sigint) - (let [stop ((resolve 'jolt.nrepl/start) port (:nrepl-middleware resolved))] - ;; register stop so ^C (handled by park-until-interrupt) closes the socket - ;; and drops .nrepl-port on the way out. - (jolt.host/add-shutdown-hook stop) - ;; park here until ^C (handled by park-until-interrupt's keyboard-interrupt- - ;; handler, which runs the shutdown hooks and exits). The accept loop - ;; inherited SIGINT-blocked above, so ^C is delivered to this thread. - (jolt.host/park-until-interrupt) - (when stop (stop)))))) - -(defn- usage [] - (println (str "jolt " (version))) - (println "usage: jolt [args]") - (println " -e EXPR evaluate EXPR and print the result") - (println " run -m NS [args] resolve deps.edn, load NS, call its -main") - (println " run FILE load a Clojure file") - (println " build -m NS [-o OUT] [--opt|--dev] [--direct-link] [--tree-shake] [--dynamic] compile a standalone binary") - (println " -M:alias [args] run the alias's :main-opts") - (println " -A:alias [args] add the alias's paths/deps") - (println " repl start a line REPL") - (println " --nrepl-server [port] start an nREPL server (default 7888) for editors") - (println " path print the resolved source roots") - (println " run a deps.edn :tasks entry") - (println " --version print the jolt version") - (println " --help print this message")) - -(defn -main [& args] - (let [[cmd & more] args] - (cond - (nil? cmd) (usage) - (= cmd "--help") (usage) - (= cmd "-h") (usage) - (#{"--version" "-V"} cmd) (println (str "jolt " (version))) - (= cmd "run") (cmd-run more) - (= cmd "repl") (repl) - (= cmd "--nrepl-server") (nrepl more) - (= cmd "path") (cmd-path) - (str/starts-with? cmd "-M") (cmd-M cmd more) - (str/starts-with? cmd "-A") (cmd-A cmd more) - (= cmd "-m") (cmd-run (cons "-m" more)) - (= cmd "build") (cmd-build more) - :else (run-task cmd more)))) diff --git a/jolt-core/jolt/nrepl.clj b/jolt-core/jolt/nrepl.clj deleted file mode 100644 index 96056c8..0000000 --- a/jolt-core/jolt/nrepl.clj +++ /dev/null @@ -1,310 +0,0 @@ -(ns jolt.nrepl - "A minimal, extensible nREPL server for jolt, so an editor (CIDER / Calva / - Cursive) can connect and develop a project live. Speaks bencode over a loopback - TCP socket bound through jolt.ffi. Built in: clone, describe, eval, load-file, - close — enough to connect and eval, with the project's deps on the roots and - native libs loaded (jolt.main applies the project first), so (require '[lib]) - works. - - EXTENSIBLE: a library can add the heavier nREPL features (sessions, - interruptible-eval, completion, lookup) as MIDDLEWARE without bloating core. A - middleware is `(fn [handler] (fn [request] ...))`; list them in deps.edn under - :nrepl/middleware (symbols resolving to a middleware fn, or to a vector of them) - and jolt.nrepl composes them over the built-in handler. The request is the - decoded bencode map (string keys: \"op\" \"code\" \"ns\" \"id\" \"session\" …) - plus :reply — a thread-safe (fn [response-map]) that adds id/session and sends. - Public seam for middleware: respond, evaluate, register-ops!, new-session. - - Writes .nrepl-port in the project dir so editors auto-detect the port." - (:require [clojure.string :as str] - [clojure.java.io :as io] - [jolt.ffi :as ffi])) - -;; --- sockets (loopback server) --------------------------------------------- -(def ^:private os-name - (str/lower-case (or (System/getProperty "os.name") ""))) -(def ^:private macos? (str/includes? os-name "mac")) -(def ^:private windows? (str/includes? os-name "win")) - -;; Load the library that provides the socket symbols BEFORE the foreign-fn -;; bindings below — defcfn resolves the C entry point when the def is evaluated -;; (at ns load), so the symbols must already be available. POSIX: the running -;; process's own libc symbols. Windows: the Winsock DLL (ws2_32), whose symbols -;; are NOT in joltc.exe's export table even though it's linked in — without this -;; explicit load, (ffi/defcfn c-socket "socket" ...) fails at load with -;; "no entry for socket". -(if windows? - (ffi/load-library "ws2_32.dll") - (ffi/load-library)) - -;; A socket is an int fd on POSIX; on Win64 it's a SOCKET (uintptr_t) handle, but -;; those are small kernel handle values that round-trip through :int, and the -;; INVALID_SOCKET error sentinel (~0) reads back as -1 — so the fd checks below -;; work unchanged on both. -(ffi/defcfn c-socket "socket" [:int :int :int] :int) -(ffi/defcfn c-bind "bind" [:int :pointer :int] :int) -(ffi/defcfn c-listen "listen" [:int :int] :int) -(ffi/defcfn c-setsockopt "setsockopt" [:int :int :int :pointer :int] :int) -(ffi/defcfn c-accept "accept" [:int :pointer :pointer] :int :blocking) - -;; recv/send and the socket-close call differ by platform. Winsock's recv/send -;; take an int length and return int (not ssize_t), and a socket is closed with -;; closesocket, not close. A symbol that exists on only one OS (closesocket on -;; Windows, close on POSIX) can only be bound there, so these live in the taken -;; platform branch — jolt interns the vars from both branches at analysis time, -;; so later references resolve either way. -(if windows? - (do - (ffi/defcfn c-recv "recv" [:int :pointer :int :int] :int :blocking) - (ffi/defcfn c-send "send" [:int :pointer :int :int] :int :blocking) - (ffi/defcfn c-close "closesocket" [:int] :int) - ;; Winsock must be initialized once per process before any socket call. - (ffi/defcfn c-wsastartup "WSAStartup" [:int :pointer] :int)) - (do - (ffi/defcfn c-recv "recv" [:int :pointer :size_t :int] :ssize_t :blocking) - (ffi/defcfn c-send "send" [:int :pointer :size_t :int] :ssize_t :blocking) - (ffi/defcfn c-close "close" [:int] :int))) - -(def ^:private AF-INET 2) -(def ^:private SOCK-STREAM 1) -;; SOL_SOCKET / SO_REUSEADDR: 0xffff / 4 on macOS and Windows, 1 / 2 on Linux. -(def ^:private sol-socket (if (or macos? windows?) 0xffff 1)) -(def ^:private so-reuse (if (or macos? windows?) 4 2)) - -;; Initialize Winsock (a no-op off Windows). WSAStartup is refcounted and must -;; precede any socket call; WSADATA is ~408 bytes on x64, so 512 is ample. -(defn- ensure-winsock! [] - (when windows? - (let [wsadata (ffi/alloc 512)] - (try - (let [r (c-wsastartup 0x0202 wsadata)] - (when-not (zero? r) - (throw (ex-info (str "WSAStartup failed: " r) {})))) - (finally (ffi/free wsadata)))))) - -(defn- make-sockaddr [port] - (let [sa (ffi/alloc 16)] - (dotimes [i 16] (ffi/write sa :uint8 i 0)) - (if macos? - (do (ffi/write sa :uint8 0 16) (ffi/write sa :uint8 1 AF-INET)) - (ffi/write sa :uint8 0 AF-INET)) - (ffi/write sa :uint8 2 (bit-and (bit-shift-right port 8) 0xff)) - (ffi/write sa :uint8 3 (bit-and port 0xff)) - (ffi/write sa :uint8 4 127) (ffi/write sa :uint8 7 1) ; 127.0.0.1 - sa)) - -(defn- listen-socket [port] - (ensure-winsock!) ; no-op off Windows - (let [fd (c-socket AF-INET SOCK-STREAM 0)] - (when (neg? fd) (throw (ex-info "socket() failed" {}))) - (let [opt (ffi/alloc 4)] (ffi/write opt :int 0 1) (c-setsockopt fd sol-socket so-reuse opt 4) (ffi/free opt)) - (let [sa (make-sockaddr port)] - (when (neg? (c-bind fd sa 16)) (c-close fd) (ffi/free sa) (throw (ex-info (str "bind() failed on port " port) {}))) - (ffi/free sa)) - (when (neg? (c-listen fd 16)) (c-close fd) (throw (ex-info "listen() failed" {}))) - fd)) - -;; bytes flow as latin1 strings on the wire (1 char = 1 byte). Text fields that -;; may carry unicode (code / value / out) convert at the boundary. -(defn- ->wire [s] (String. (.getBytes (str s) "UTF-8") "ISO-8859-1")) -(defn- wire-> [s] (String. (byte-array (map int s)) "UTF-8")) - -(def ^:private bufsize 65536) -(defn- recv-str [fd] - (let [buf (ffi/alloc bufsize)] - (try (let [n (c-recv fd buf bufsize 0)] - (when (pos? n) (String. (ffi/read-array buf n) "ISO-8859-1"))) - (finally (ffi/free buf))))) - -(defn- send-str [fd s] - (let [data (byte-array (map int s)) n (alength data) buf (ffi/alloc (max 1 n))] - (try (ffi/write-array buf data) - (loop [off 0] (when (< off n) (let [sent (c-send fd (+ buf off) (- n off) 0)] - (when (pos? sent) (recur (+ off sent)))))) - (finally (ffi/free buf))))) - -;; --- bencode --------------------------------------------------------------- -(defn- bencode [v] - (cond - (integer? v) (str "i" v "e") - (string? v) (let [w (->wire v)] (str (count w) ":" w)) - (keyword? v) (let [w (->wire (name v))] (str (count w) ":" w)) - (map? v) (str "d" (apply str (mapcat (fn [[k val]] [(bencode (name k)) (bencode val)]) - (sort-by #(name (first %)) v))) "e") - (or (seq? v) (vector? v)) (str "l" (apply str (map bencode v)) "e") - (nil? v) "0:" - :else (let [w (->wire (str v))] (str (count w) ":" w)))) - -;; decode one value from `s` at index `i` -> [value next-index], or nil if the -;; buffer doesn't yet hold a complete value. -(defn- bdecode [s i] - (when (< i (count s)) - (let [c (nth s i)] - (cond - (= c \i) (let [e (str/index-of s "e" i)] - (when e [(parse-long (subs s (inc i) e)) (inc e)])) - (= c \l) (loop [j (inc i) acc []] - (cond (>= j (count s)) nil - (= (nth s j) \e) [acc (inc j)] - :else (let [r (bdecode s j)] (when r (recur (second r) (conj acc (first r))))))) - (= c \d) (loop [j (inc i) acc {}] - (cond (>= j (count s)) nil - (= (nth s j) \e) [acc (inc j)] - :else (let [k (bdecode s j)] - (when k (let [val (bdecode s (second k))] - (when val (recur (second val) (assoc acc (wire-> (first k)) (first val))))))))) - (and (char? c) (>= (int c) 48) (<= (int c) 57)) ; string: : - (let [colon (str/index-of s ":" i)] - (when colon - (let [n (parse-long (subs s i colon)) start (inc colon) end (+ start n)] - (when (<= end (count s)) [(subs s start end) end])))) - :else nil)))) - -;; --- public seam for middleware -------------------------------------------- -(def ^:private session-counter (atom 0)) -(defn new-session - "A fresh session id (middleware that implements sessions uses this)." - [] (str "jolt-" (swap! session-counter inc))) - -(defn respond - "Send a response map for `request` (id/session added, then bencoded)." - [request m] ((:reply request) m)) - -(defn err-msg - "Best-effort message for any thrown value (ex-info, or a raw Chez condition — - ex-message is nil for those, so fall back to the host condition text)." - [e] - (or (ex-message e) - (try ((resolve 'jolt.host/condition-message) e) (catch :default _ nil)) - (pr-str e))) - -(defn evaluate - "Evaluate `code` (optionally in loaded ns `ns-str`), capturing *out*. Returns - {:value .. :out .. :ns .. :err ..}. in-ns — not (binding [*ns* ..]) — sets the - ns load-string resolves against on jolt. Reusable by eval middleware." - [code ns-str] - (let [result (atom nil) err (atom nil) - out (with-out-str - (try (when (and ns-str (not (str/blank? ns-str)) (find-ns (symbol ns-str))) - (in-ns (symbol ns-str))) - (reset! result (load-string code)) - (catch :default e - (reset! err (str (err-msg e) - (when-let [bt (jolt.host/backtrace-string)] - (str "\n" bt)))))))] - {:value (when (nil? @err) (pr-str @result)) - :out out - :ns (str (ns-name *ns*)) - :err @err})) - -;; ops middleware advertise via describe (built-ins + any a library registers). -(def ^:private extra-ops (atom #{})) -(defn register-ops! - "Register op name(s) so `describe` advertises them. Call at middleware load." - [& ops] (swap! extra-ops into (map name ops))) - -;; --- built-in handler ------------------------------------------------------ -(defn- built-in-handler [request] - (let [op (get request "op")] - (cond - (= op "clone") (respond request {"new-session" (new-session) "status" ["done"]}) - (= op "close") (respond request {"status" ["session-closed" "done"]}) - (= op "describe") (respond request {"status" ["done"] - "versions" {"jolt-nrepl" {"major" 0 "minor" 1}} - "ops" (zipmap (into #{"clone" "close" "describe" "eval" "load-file"} - @extra-ops) - (repeat {}))}) - (or (= op "eval") (= op "load-file")) - (let [code (wire-> (if (= op "load-file") (get request "file") (get request "code"))) - {:keys [value out ns err]} (evaluate code (get request "ns"))] - (when (seq out) (respond request {"out" out})) - (if err - (do (respond request {"err" (str err "\n")}) - (respond request {"ex" (str err) "status" ["eval-error" "done"]})) - (respond request {"value" value "ns" ns "status" ["done"]}))) - :else (respond request {"status" ["done" "unknown-op"]})))) - -;; --- middleware composition ------------------------------------------------ -;; resolve deps.edn :nrepl/middleware symbols to middleware fns. An entry may -;; resolve to a single (fn [handler] handler') or to a vector of them (so a -;; library can export one `default-middleware` var). -(defn- resolve-middleware [syms] - (vec (mapcat - (fn [sym] - (require (symbol (namespace sym))) - (let [v (deref (resolve sym))] - (if (sequential? v) (map #(if (var? %) (deref %) %) v) [v]))) - syms))) - -(defn- build-handler [middleware] - ;; first listed middleware is outermost. - (reduce (fn [h mw] (mw h)) built-in-handler (reverse middleware))) - -(defn- handle-conn [fd handler] - ;; one send lock per connection: eval/session middleware reply from other - ;; threads, so sends must not interleave. - (let [lock (Object.) - reply-for (fn [msg] - (let [id (get msg "id") session (or (get msg "session") "none")] - (fn [m] - (locking lock - (send-str fd (bencode (cond-> m id (assoc "id" id) - session (assoc "session" session))))))))] - (loop [buf ""] - (let [chunk (recv-str fd)] - (if (nil? chunk) - (c-close fd) - (let [rest-buf (loop [b (str buf chunk)] - (let [r (bdecode b 0)] - (if (nil? r) b - (do (when (map? (first r)) - (let [msg (first r)] - (try (handler (assoc msg :reply (reply-for msg))) - (catch :default e (println "nrepl handler error:" (err-msg e)))))) - (recur (subs b (second r)))))))] - (recur rest-buf))))))) - -(defn start - "Start the nREPL server on `port` (a concrete port; loopback only). `middleware` - is a vector of deps.edn :nrepl/middleware symbols to compose over the built-in - handler. - - Binds the socket synchronously, so a startup failure (e.g. the port is already - in use) is thrown to the caller rather than swallowed by the accept thread, then - accepts connections on a background thread and returns immediately. Writes - .nrepl-port. Does NOT block — the caller keeps the process alive (jolt.main - parks the main thread in jolt.host/run-main-pump). - - Returns a zero-arg stop fn: it stops the accept loop, closes the listen socket - (freeing the port), and removes .nrepl-port. Calling it more than once is a - no-op." - ([port] (start port nil)) - ([port middleware] - ;; An nREPL session is REPL-driven development: trace by default so an uncaught - ;; error in code evaluated over the connection shows a tail-frame backtrace, with - ;; no JOLT_TRACE needed. Covers both `--nrepl-server` and an app that starts its - ;; own server under `-M:run` (reload a namespace to trace already-loaded code). - (jolt.host/enable-trace!) - (let [handler (build-handler (resolve-middleware (or middleware []))) - fd (listen-socket port) ; throws on bind/listen failure - stopped (atom false)] - (try (spit ".nrepl-port" (str port)) (catch :default _ nil)) - (println (str "jolt " (jolt.host/jolt-version) " nREPL server started on port " - port " (127.0.0.1) — .nrepl-port written")) - (when (seq middleware) (println (str ";; middleware: " (str/join " " middleware)))) - (println ";; connect your editor; ^C to stop") - (future - ;; A stop closes fd, which makes the blocking accept() return an error; the - ;; @stopped check then breaks the loop instead of spinning on the dead fd. - (loop [] - (let [conn (c-accept fd ffi/null ffi/null)] - (when-not @stopped - (when (>= conn 0) - (future (try (handle-conn conn handler) - (catch :default e (println "nrepl conn error:" (err-msg e)) (c-close conn))))) - (recur))))) - (fn stop [] - (when (compare-and-set! stopped false true) - (c-close fd) - (jolt.host/delete-file ".nrepl-port")) - nil)))) diff --git a/jolt-core/jolt/passes.clj b/jolt-core/jolt/passes.clj deleted file mode 100644 index b4e4f75..0000000 --- a/jolt-core/jolt/passes.clj +++ /dev/null @@ -1,97 +0,0 @@ -(ns jolt.passes - "IR optimization passes (nanopass-lite) + the inference/checking - driver. Façade over three weakly-coupled namespaces, loaded with the compiler: - - jolt.passes.fold — const-fold (always-on) + the shared const-shape predicate. - jolt.passes.inline — inline + flatten-lets + scalar-replace (direct-link only). - jolt.passes.types — collection-type inference + success-type checking - (RFC 0006) + the inter-procedural driver API. - - run-passes (below) is the single entry the back end applies to every analyzed - form. The driver/checker fns the back end looks up by name (check-form, - infer-body, reinfer-def, set-rtenv!, take-diags!, …) are re-exported here via - :refer, so jolt.passes stays the only namespace the back end imports. - - Portable Clojure: kernel-tier fns + seed primitives only." - (:require [jolt.host :refer [inline-enabled? record-shapes protocol-methods stash-inline!]] - [jolt.passes.fold :refer [const-fold]] - [jolt.passes.numeric :as numeric] - [jolt.passes.inline :refer [inline-node flatten-lets scalar-replace dirty set-rec-shapes!]] - [jolt.passes.types :refer [run-inference - check-form infer-body reinfer-def phint-seed - set-rtenv! set-vtypes! join-types - set-record-shapes! set-map-shapes! set-protocol-methods! - reset-escapes! collected-escapes - wp-infer! param-seeds-for param-num-seeds-for - set-check-mode! take-diags!]])) - -;; Cap on inline -> flatten -> scalar-replace -> const-fold iterations. Each pass -;; sets `dirty` when it rewrote something; the loop stops at a clean pass or here. -(def ^:private inline-fixpoint-cap 8) - -;; A top-level defn the inline pass may splice: a single fixed arity (no rest). The -;; pass itself checks body size + closedness, so any such fn is stashable. -(defn- inline-eligible? [node] - (and (= :def (:op node)) (:init node) (= :fn (:op (:init node))) - (= 1 (count (:arities (:init node)))) - (not (:rest (first (:arities (:init node))))))) - -(defn- stash-of [node] - (let [a (first (:arities (:init node)))] - {:params (:params a) :body (:body a) :nhints (:nhints a) :ret (:ret-nhint a)})) - -(defn inject-wp-nhints - "Merge the whole-program :double param seeds into a def's arity :nhints as - synthetic ^double hints, so the numeric pass unboxes a hintless fn whose callers - all pass flonums (the entry coercion exact->inexact is a no-op on a proven - flonum). Only un-hinted params are added — an explicit hint wins. A no-op unless - the closed-world fixpoint typed a param :double (param-num-seeds-for)." - [node] - (let [seeds (when (= :def (:op node)) (param-num-seeds-for (str (:ns node) "/" (:name node)))) - f (:init node)] - (if (and seeds (= :fn (:op f)) (= 1 (count (:arities f)))) - (let [a (first (:arities f)) - have (into #{} (map first (:nhints a))) - add (for [[p k] seeds :when (not (have p))] [p k])] - (assoc node :init (assoc f :arities [(assoc a :nhints (vec (concat (:nhints a) add)))]))) - node))) - -(defn run-passes - "All passes, in order. The back end applies this to every analyzed form. When - inlining is enabled for the unit (user code under direct-linking), - run inline + flatten + scalar-replace + const-fold to a capped fixpoint — - inlining exposes map literals to lookups, scalar-replace collapses them, which - may expose more — then a collection-type inference pass (optionally - also emitting success diagnostics) that auto-drops the lookup guard where the - type is proven. Otherwise (core + bootstrap) just const-fold, as before. - - numeric/annotate runs last in both branches (hint-directed fl*/fx* arithmetic); - it benefits open builds too, so it is not gated on inlining." - [node ctx] - ;; stash an inline-eligible defn so later call sites can splice it (closed-world - ;; optimization only). Done before optimizing, from the analyzed node. - (when (and (inline-enabled? ctx) (inline-eligible? node)) - (stash-inline! ctx (:ns node) (:name node) (stash-of node))) - (numeric/annotate - (if (inline-enabled? ctx) - (let [_ (set-rec-shapes! (record-shapes ctx)) ;; record ctor fold - ;; resolve ^Record param hints (incl. defrecord/extend-type method - ;; `this`) to bare field reads per-form, not only under whole-program. - ;; Same shapes the inline pass uses. - _ (set-record-shapes! (record-shapes ctx)) - _ (set-protocol-methods! (protocol-methods ctx)) ;; devirtualization - opt (loop [i 0 n (const-fold node)] - (reset! dirty false) - (let [n2 (const-fold (scalar-replace (flatten-lets (inline-node n ctx))))] - (if (and @dirty (< i inline-fixpoint-cap)) - (recur (inc i) n2) - n2))) - ;; a top-level def whose params the whole-program fixpoint typed gets - ;; reinferred with those seeds (record types flow in from its callers); - ;; everything else takes the ordinary per-form inference. - seeds (when (= :def (:op opt)) (param-seeds-for (str (:ns opt) "/" (:name opt))))] - ;; a final const-fold after inference propagates any predicate folded to a - ;; constant, collapsing the `if` it gates to the taken branch; then inject - ;; any whole-program :double param hints for the numeric pass that follows. - (inject-wp-nhints (const-fold (if seeds (reinfer-def opt seeds) (run-inference opt))))) - (const-fold node)))) diff --git a/jolt-core/jolt/passes/fold.clj b/jolt-core/jolt/passes/fold.clj deleted file mode 100644 index c13d38e..0000000 --- a/jolt-core/jolt/passes/fold.clj +++ /dev/null @@ -1,91 +0,0 @@ -(ns jolt.passes.fold - "Constant folding (always-on IR pass) plus the shared const-shape predicate. - Bottom-up numeric folding + dead-branch removal, total over node :ops (unknown - ops pass through with folded children). Portable Clojure: kernel-tier fns + - seed primitives only — it loads with the compiler namespaces, before the later - core tiers." - (:require [jolt.ir :refer [map-ir-children]])) - -;; Folding computes with THE ACTUAL jolt fns, so a folded result matches what -;; the unfolded code would produce at runtime by construction. Conservative: -;; numbers only, the op table only names pure numeric fns, and any throw -;; during folding (e.g. (mod x 0)) leaves the node alone for runtime. -(def ^:private foldable - ;; SEED fns only: this ns loads with the compiler, BEFORE the later core - ;; tiers — a name from 20-coll (min/max/abs) wouldn't resolve yet. - {"+" + "-" - "*" * "/" / - "<" < ">" > "<=" <= ">=" >= "=" = - "inc" inc "dec" dec - "mod" mod "rem" rem "quot" quot - ;; the __bit-* seams: the PUBLIC bit fns are 20-coll variadic shells now, - ;; which don't exist yet when this ns loads. Folding stays 2-arg (a 3+-arg - ;; constant call throws arity inside the fold and is left for runtime). - "bit-and" __bit-and "bit-or" __bit-or "bit-xor" __bit-xor}) - -(defn- const? [n] (= :const (get n :op))) -(defn- const-num? [n] (and (const? n) (number? (get n :val)))) - -(defn- fold-fn [fnode] - (let [op (get fnode :op)] - (when (or (and (= op :var) (= "clojure.core" (get fnode :ns))) - (= op :host)) - (get foldable (get fnode :name))))) - -(defn const-fold - "Bottom-up constant folding: a call of a foldable numeric fn whose args are - all constant numbers becomes a constant; an if with a constant test becomes - the taken branch." - [node] - (let [op (get node :op)] - (cond - (= op :invoke) - ;; fold children first, then this call if the fn is foldable over consts - (let [n (map-ir-children const-fold node) - ff (fold-fn (get n :fn)) - args (get n :args) - folded (when (and ff (pos? (count args)) (every? const-num? args)) - (try - {:op :const :val (apply ff (mapv (fn [a] (get a :val)) args))} - ;; :default (not Exception) — match the rest of jolt-core and - ;; also catch a raw host condition from a folding primitive. - (catch :default e nil)))] - (or folded n)) - - (= op :if) - (let [t (const-fold (get node :test))] - (if (const? t) - ;; jolt truthiness = Clojure's: nil/false take else - (if (or (nil? (get t :val)) (= false (get t :val))) - (const-fold (get node :else)) - (const-fold (get node :then))) - (assoc node - :test t - :then (const-fold (get node :then)) - :else (const-fold (get node :else))))) - - ;; every other op: fold each child (let/loop bindings are [name init] - ;; pairs, handled by the combinator) - :else (map-ir-children const-fold node)))) - -;; A const node whose value is a scalar literal (kw/str/num/bool). Shared by the -;; scalar-replace pass (jolt.passes.inline) and the collection-type inference -;; (jolt.passes.types), which both reason about const-keyed maps. -(defn scalar-const? [n] - (and (= :const (get n :op)) - (let [v (get n :val)] (or (keyword? v) (string? v) (number? v) (boolean? v))))) - -;; The two callee shapes a constant-keyword map lookup takes: a keyword in fn -;; position — (:k m) — or clojure.core/get with a const key — (get m :k). The -;; inliner (scalar replacement) and the type inferencer both recognize these; -;; sharing the head predicates keeps the two from drifting. Each caller still -;; imposes its own arity, subject, and key-type constraints. -(defn kw-callee? - "True if fnode is a constant keyword used as a function head — the (:k m) form." - [fnode] - (and (= :const (get fnode :op)) (keyword? (get fnode :val)))) - -(defn get-callee? - "True if fnode is the clojure.core/get (or host get) callee — the (get m k) form." - [fnode] - (or (and (= :var (get fnode :op)) (= "clojure.core" (get fnode :ns)) (= "get" (get fnode :name))) - (and (= :host (get fnode :op)) (= "get" (get fnode :name))))) diff --git a/jolt-core/jolt/passes/inline.clj b/jolt-core/jolt/passes/inline.clj deleted file mode 100644 index 08f5bc8..0000000 --- a/jolt-core/jolt/passes/inline.clj +++ /dev/null @@ -1,558 +0,0 @@ -(ns jolt.passes.inline - "Inlining + flatten-lets + scalar-replace (AOT escape analysis). These run only - when host/inline-enabled? (user code opted into direct-linking); they - share the alpha-rename invariant (every spliced binder is made globally fresh) - and the `dirty` fixpoint flag. Portable Clojure (compiler-tier)." - (:require [jolt.host :refer [inline-ir]] - [jolt.ir :refer [map-ir-children reduce-ir-children coerce-node]] - [jolt.passes.fold :refer [scalar-const? kw-callee? get-callee?]])) - -;; --------------------------------------------------------------------------- -;; Shared state: a dirty flag the fixpoint loop reads, and a fresh-name counter -;; for alpha-renaming inlined bodies (same atom pattern as analyzer/gen-name). -;; --------------------------------------------------------------------------- -(def dirty (atom false)) ;; read/reset by the run-passes fixpoint (jolt.passes) -(defn- mark! [] (reset! dirty true)) - -;; Record-ctor shape registry ("ns/->Name" -> {:fields (:k ..) :type tag}), fed -;; per unit by run-passes (set-rec-shapes!) before the fixpoint so scalar-replace -;; can recognize a (->Rec ..) call and map its positional args to declared fields -;; — the record analogue of the inline keys a map literal already carries in the -;; IR. -(def ^:private rec-shapes (atom {})) -(defn set-rec-shapes! - "Install the record-ctor shape registry the record fold consults." - [m] (reset! rec-shapes (or m {}))) - -(def ^:private fresh-counter (atom 0)) -(defn- fresh [base] - (let [n @fresh-counter] - (swap! fresh-counter inc) - (str base "__il" n))) - -;; --------------------------------------------------------------------------- -;; Inlining. The back end stashes {:params [..] :body ir} on the var -;; cell of each single-fixed-arity defn compiled under :inline?; here we splice -;; that body at a call site. To stay capture-safe we ALPHA-RENAME the body — -;; every param and every inner let-bound name becomes a globally fresh name — -;; then bind the fresh params to the call's args in a wrapping let (args eval -;; once, in source order). After full renaming no name in the spliced body can -;; collide with a caller local, so flatten-lets and scalar-replace need no -;; shadowing logic. -;; --------------------------------------------------------------------------- - -(defn- safe-op? [op] - ;; ops an inline-eligible body may contain. recur/loop/fn/try/def are excluded - ;; (binding/control forms the splicer doesn't handle), so a body containing one - ;; is rejected by body-size below and never inlined or alpha-renamed. - (or (= op :const) (= op :local) (= op :var) (= op :host) (= op :the-var) - (= op :quote) (= op :if) (= op :do) (= op :let) (= op :invoke) - (= op :map) (= op :vector) (= op :set) (= op :throw) (= op :coerce))) - -(def ^:private inline-budget 120) - -(defn- body-size - "Node count of an inline-eligible body. A disallowed op contributes a number - larger than any budget, so the caller's (<= size budget) test fails and we - never try to inline (or alpha-rename) such a body. Only reached for safe ops, - so the shared child fold covers it exactly (leaves fold to 1)." - [node] - (if (not (safe-op? (get node :op))) - 100000 - (reduce-ir-children (fn [acc c] (+ acc (body-size c))) 1 node))) - -(defn- subst - "Substitute locals in node per env (a map name -> replacement IR node), and - alpha-rename every inner :let binder to a globally fresh name (so the spliced - body shares no name with the caller). env seeds the params: a trivial arg - (local/const) maps a param straight to the arg node (copy propagation — this - is what lets scalar-replace see a map-literal arg through the call boundary); - a non-trivial arg maps the param to a fresh :local that a wrapping let binds." - [node env] - (let [op (get node :op)] - (cond - (= op :local) (let [r (get env (get node :name))] - ;; carry the param's ^:struct hint onto a let-bound fresh - ;; local, so lookups inside the inlined body keep the bare - ;; (no-guard) path. The param hint asserts the - ;; arg is a struct; inlining doesn't change that contract. - (if r - (if (and (= :local (get r :op)) (get node :hint) (not (get r :hint))) - (assoc r :hint (get node :hint)) - r) - node)) - ;; :let alpha-renames each binder to a fresh name, threading the extended - ;; env left-to-right — sequential scope the uniform combinator can't model, - ;; so it stays explicit. - (= op :let) - (let [res (reduce (fn [acc b] - (let [e (nth acc 0) - binds (nth acc 1) - nm (nth b 0) - init (subst (nth b 1) e) - f (fresh nm)] - [(assoc e nm {:op :local :name f}) (conj binds [f init])])) - [env []] - (get node :bindings))] - (assoc node :bindings (nth res 1) :body (subst (get node :body) (nth res 0)))) - ;; every other op substitutes env uniformly into its children. Inline - ;; bodies only contain safe ops (see safe-op?), so loop/recur/fn/def/try - ;; never reach here; the combinator handles them harmlessly regardless. - :else (map-ir-children (fn [c] (subst c env)) node)))) - -(defn- trivial-arg? [n] - ;; safe to substitute directly (immutable, free to duplicate): a local read or - ;; a constant. Everything else is let-bound so it evaluates exactly once. - (let [op (get n :op)] (or (= op :local) (= op :const)))) - -(defn- body-closed? - "True if every :local in node is bound — by a param (in the initial scope set) - or by an enclosing :let within the body. A self-recursive fn fails this: the - analyzer binds the fn's own name as a local, so its body has a FREE local (the - self-reference) that would dangle once the body is spliced elsewhere." - [node scope] - (let [op (get node :op)] - (cond - (= op :local) (contains? scope (get node :name)) - ;; :let threads scope sequentially (each binding extends it), so it can't go - ;; through the uniform fold. - (= op :let) - (let [res (reduce (fn [acc b] - (let [sc (nth acc 0) ok (nth acc 1)] - (if (not ok) - acc - [(conj sc (nth b 0)) (body-closed? (nth b 1) sc)]))) - [scope true] - (get node :bindings))] - (and (nth res 1) (body-closed? (get node :body) (nth res 0)))) - ;; leaves (:const/:var/:host/:the-var/:quote) fold to true; the rest AND - ;; their children. Unsafe ops never reach here (body-size rejects them). - (safe-op? op) (reduce-ir-children (fn [ok c] (and ok (body-closed? c scope))) true node) - :else false))) - -(defn- try-inline - "node is an :invoke whose children are already inlined. If its :fn is a var - with a stashed, in-budget, arity-matching inline body, return the spliced - let; else node." - [node ctx] - (let [f (get node :fn)] - (if (= :var (get f :op)) - (let [stash (inline-ir ctx (get f :ns) (get f :name))] - (if stash - (let [params (get stash :params) - body (get stash :body) - nh (reduce (fn [m pr] (assoc m (nth pr 0) (nth pr 1))) {} (get stash :nhints)) - ret (get stash :ret) - args (get node :args)] - (if (and (= (count params) (count args)) - (<= (body-size body) inline-budget) - (body-closed? body (reduce conj #{} params))) - (let [n (count params) - ;; trivial args (local/const) substitute straight in (copy - ;; propagation); the rest get a fresh local bound once in a - ;; wrapping let, so they evaluate exactly once in source order. - ;; A ^double/^long param always binds (no copy-prop) so its - ;; entry coercion runs — preserving the called fn's semantics. - res (loop [i 0 env {} binds []] - (if (< i n) - (let [p (nth params i) a (nth args i) k (get nh p)] - (cond - k (let [f (fresh p)] - (recur (inc i) (assoc env p {:op :local :name f}) - (conj binds [f (coerce-node k a)]))) - (trivial-arg? a) (recur (inc i) (assoc env p a) binds) - :else (let [f (fresh p)] - (recur (inc i) (assoc env p {:op :local :name f}) - (conj binds [f a]))))) - [env binds])) - env (nth res 0) - binds (nth res 1) - rbody0 (subst body env) - ;; preserve the fn's ^double/^long return coercion. - rbody (if ret (coerce-node ret rbody0) rbody0)] - (mark!) - (if (= 0 (count binds)) - rbody - {:op :let :bindings binds :body rbody})) - node)) - node)) - node))) - -(defn inline-node - "Bottom-up: inline children first, then attempt to inline this node." - [node ctx] - (if (= :invoke (get node :op)) - ;; inline children first, then attempt to splice this call - (try-inline (map-ir-children (fn [c] (inline-node c ctx)) node) ctx) - (map-ir-children (fn [c] (inline-node c ctx)) node))) - -;; --------------------------------------------------------------------------- -;; flatten-lets: (let [a (let [b X] Y) ..] body) -> (let [b X a Y ..] body). -;; Safe because inlined bodies are alpha-renamed (every binder unique), so the -;; hoisted bindings can't collide. Exposes a map-returning init directly to -;; scalar-replace when it was wrapped in an inlined arg's let. -;; --------------------------------------------------------------------------- -(defn- flatten-let-bindings [binds] - ;; returns a flattened binding vector; sets dirty when it hoists. - (reduce (fn [out b] - (let [nm (nth b 0) init (nth b 1)] - (if (= :let (get init :op)) - (do (mark!) - (conj (reduce conj out (get init :bindings)) - [nm (get init :body)])) - (conj out b)))) - [] - binds)) - -(defn flatten-lets [node] - (if (= :let (get node :op)) - ;; flatten children first, then hoist any let-valued binding inits - (let [n (map-ir-children flatten-lets node)] - (assoc n :bindings (flatten-let-bindings (get n :bindings)))) - (map-ir-children flatten-lets node))) - -;; --------------------------------------------------------------------------- -;; scalar-replace (AOT escape analysis). A map allocation whose ONLY use is -;; constant-keyword lookup is dead weight: replace each (:k m) with the literal -;; value at :k and drop the allocation. Two forms: -;; (a) direct: (:k {:k a ..}) -> a -;; (b) let-bound: (let [m {:k a ..}] .. (:k m) ..) -> .. a .. (m non-escaping) -;; Both require the dropped sibling values to be pure (we duplicate/discard them). -;; --------------------------------------------------------------------------- - -(def ^:private pure-fns - #{"+" "-" "*" "/" "<" ">" "<=" ">=" "=" "not=" "inc" "dec" - "mod" "rem" "quot" "min" "max" "abs" - "nil?" "some?" "not" "get" "zero?" "pos?" "neg?" "even?" "odd?" - "bit-and" "bit-or" "bit-xor"}) - -(defn- pure-fn? [f] - (let [op (get f :op)] - (cond - (kw-callee? f) true - (= op :var) (and (= "clojure.core" (get f :ns)) (contains? pure-fns (get f :name))) - (= op :host) (contains? pure-fns (get f :name)) - :else false))) - -;; forward ref: a record ctor (allocating an immutable struct from its args) is -;; side-effect-free, so pure? treats (->Rec pure-args..) as pure — which lets a -;; nested record (a Ray holding a Vec3) fold bottom-up. -(declare ctor-shape) - -(defn- pure? - "Conservative: true only for expressions with no side effects that are safe to - duplicate or discard. A var/host ref is a pure read; an invoke is pure for a - known-pure fn (arithmetic, comparison, keyword lookup, get) or a record - constructor (an immutable struct alloc) whose args are themselves pure." - [node] - (let [op (get node :op)] - (cond - ;; :invoke is pure only for a known-pure fn / record ctor, and only its ARGS - ;; are folded (not the :fn position) — so it can't go through the uniform fold. - (= op :invoke) (and (or (pure-fn? (get node :fn)) (ctor-shape node)) - (every? pure? (get node :args))) - ;; leaves (:const/:local/:var/:host/:the-var/:quote) fold to true; :if/:do/ - ;; :let/:vector/:set/:map AND their children's purity. - (safe-op? op) (reduce-ir-children (fn [ok c] (and ok (pure? c))) true node) - :else false))) - -(defn- const-key-map? [node] - (let [prs (get node :pairs)] - (and (> (count prs) 0) - (every? (fn [pr] (scalar-const? (nth pr 0))) prs)))) - -(defn- all-vals-pure? [node] - (every? (fn [pr] (pure? (nth pr 1))) (get node :pairs))) - -(defn- map-val - "The value IR at scalar key k in a const-key map node, or a nil constant when k - is absent (struct-eligible literal: a missing key reads nil, like the back end)." - [mapnode k] - (let [prs (get mapnode :pairs) n (count prs)] - (loop [i 0] - (if (< i n) - (let [pr (nth prs i)] - (if (= (get (nth pr 0) :val) k) (nth pr 1) (recur (inc i)))) - {:op :const :val nil})))) - -(defn- lookup-key - "If node is a constant-keyword lookup of (:local nm) — either (:k nm) or - (get nm :k) — return the keyword k; else nil." - [node nm] - (if (= :invoke (get node :op)) - (let [f (get node :fn) args (get node :args)] - (cond - (and (kw-callee? f) - (= 1 (count args)) - (= :local (get (nth args 0) :op)) (= nm (get (nth args 0) :name))) - (get f :val) - - (and (get-callee? f) - (= 2 (count args)) - (= :local (get (nth args 0) :op)) (= nm (get (nth args 0) :name)) - (scalar-const? (nth args 1))) - (get (nth args 1) :val) - - :else nil)) - nil)) - -(defn- any-binding-named? [binds nm] - (loop [i 0] - (if (< i (count binds)) - (if (= nm (nth (nth binds i) 0)) true (recur (inc i))) - false))) - -(defn- any-name? [names nm] - (loop [i 0] - (if (< i (count names)) - (if (= nm (nth names i)) true (recur (inc i))) - false))) - -(defn- local-escapes? - "Does local nm escape in node — i.e. is it used anywhere other than as the - subject of a constant-keyword lookup? Precise over straight-line expression - ops; conservatively true for loop/fn/try/recur/def (and any rebinding of nm), - so scalar replacement only fires where the whole use region is simple. - - Stays an explicit per-op walk (not the shared reduce-ir-children fold): its - default is conservatively TRUE, and the lookup-subject and rebinding cases - inspect node shape beyond child purity — folding an unhandled op over its - children would under-report escape and is unsound for scalar replacement." - [node nm] - (let [op (get node :op) - k (lookup-key node nm)] - (cond - ;; an ok lookup of nm: nm itself is consumed; still scan any extra args - ;; (a get default could reference nm), never the subject local at arg 0. - k (let [args (get node :args)] - (if (> (count args) 1) - (loop [i 1] - (if (< i (count args)) - (if (local-escapes? (nth args i) nm) true (recur (inc i))) - false)) - false)) - (= op :local) (= nm (get node :name)) - (= op :const) false - (= op :var) false - (= op :host) false - (= op :the-var) false - (= op :quote) false - (= op :if) (or (local-escapes? (get node :test) nm) - (local-escapes? (get node :then) nm) - (local-escapes? (get node :else) nm)) - (= op :do) (or (loop [i 0 ss (get node :statements)] - (if (< i (count ss)) - (if (local-escapes? (nth ss i) nm) true (recur (inc i) ss)) - false)) - (local-escapes? (get node :ret) nm)) - (= op :throw) (local-escapes? (get node :expr) nm) - (= op :invoke) (or (local-escapes? (get node :fn) nm) - (loop [i 0 as (get node :args)] - (if (< i (count as)) - (if (local-escapes? (nth as i) nm) true (recur (inc i) as)) - false))) - (= op :vector) (loop [i 0 xs (get node :items)] - (if (< i (count xs)) - (if (local-escapes? (nth xs i) nm) true (recur (inc i) xs)) - false)) - (= op :set) (loop [i 0 xs (get node :items)] - (if (< i (count xs)) - (if (local-escapes? (nth xs i) nm) true (recur (inc i) xs)) - false)) - (= op :map) (loop [i 0 ps (get node :pairs)] - (if (< i (count ps)) - (if (or (local-escapes? (nth (nth ps i) 0) nm) - (local-escapes? (nth (nth ps i) 1) nm)) - true (recur (inc i) ps)) - false)) - (= op :let) (let [binds (get node :bindings)] - (if (any-binding-named? binds nm) - true ;; nm rebound here — bail (safe; inlined names are unique) - (or (loop [i 0] - (if (< i (count binds)) - (if (local-escapes? (nth (nth binds i) 1) nm) true (recur (inc i))) - false)) - (local-escapes? (get node :body) nm)))) - ;; recur binds nothing — its args are ordinary expressions (this is the - ;; common loop-body tail; treating it as a blanket escape would block - ;; scalar replacement in every loop). - (= op :recur) (loop [i 0 as (get node :args)] - (if (< i (count as)) - (if (local-escapes? (nth as i) nm) true (recur (inc i) as)) - false)) - (= op :loop) (let [binds (get node :bindings)] - (if (any-binding-named? binds nm) - true - (or (loop [i 0] - (if (< i (count binds)) - (if (local-escapes? (nth (nth binds i) 1) nm) true (recur (inc i))) - false)) - (local-escapes? (get node :body) nm)))) - (= op :fn) (loop [i 0 ars (get node :arities)] - (if (< i (count ars)) - (let [ar (nth ars i) - ps (get ar :params)] - ;; a param (or rest) shadowing nm hides ours in that arity - (if (or (any-name? ps nm) (= nm (get ar :rest))) - true - (if (local-escapes? (get ar :body) nm) true (recur (inc i) ars)))) - false)) - (= op :try) (or (local-escapes? (get node :body) nm) - (let [cb (get node :catch-body)] - (and cb (not (= nm (get node :catch-sym))) (local-escapes? cb nm))) - (let [f (get node :finally)] (and f (local-escapes? f nm)))) - (= op :def) (local-escapes? (get node :init) nm) - :else true))) - -;; --- record constructors as foldable struct sources ------------------------- -;; A record ctor (->Rec a b ..) is a positional struct: the registry maps its -;; ctor key ("ns/->Name", exactly how the IR names the call head) to the DECLARED -;; field order. A field read on a non-escaping ctor folds to the matching arg, -;; just as (:k {:k a ..}) folds to a. Two soundness differences from maps: -;; - the ctor's args are duplicated/discarded, so they must be pure (like map -;; vals), and the arg count must equal the field count (a positional call); -;; - a record answers the virtual :jolt/deftype key with its type tag and any -;; other non-field key with nil — neither is a positional arg, so we only -;; fold DECLARED-field reads and keep the allocation otherwise. - -(defn- ctor-shape - "If node is a record-constructor :invoke (its :fn a :var whose ns/name is a - registered ctor key, with arg count matching the declared field count), return - that record's shape entry; else nil." - [node] - (if (= :invoke (get node :op)) - (let [f (get node :fn)] - (if (= :var (get f :op)) - (let [rs (get @rec-shapes (str (get f :ns) "/" (get f :name)))] - (if (and rs (= (count (get rs :fields)) (count (get node :args)))) - rs - nil)) - nil)) - nil)) - -(defn- ctor-all-args-pure? [node] (every? pure? (get node :args))) - -(defn- field-index - "Index of scalar key k in the declared field tuple fields, or nil." - [fields k] - (let [n (count fields)] - (loop [i 0] - (if (< i n) - (if (= (nth fields i) k) i (recur (inc i))) - nil)))) - -(defn- ctor-val - "The positional arg IR at declared field k of record ctor node (shape rs). Only - called for a key known to be a field, so the index is always present." - [ctor rs k] - (nth (get ctor :args) (field-index (get rs :fields) k))) - -(defn- collect-keys! - "Accumulate (into atom acc) every constant-keyword lookup key applied to local - nm in node. The caller has proven (via local-escapes?) that nm appears only as - a lookup subject and is never rebound, so a uniform recursion suffices: at a - lookup of nm we record the key and stop (its subject is nm itself); elsewhere - we recurse into children." - [node nm acc] - (let [k (lookup-key node nm)] - (if k - (swap! acc conj k) - (map-ir-children (fn [c] (collect-keys! c nm acc) c) node)))) - -(defn- lookups-all-fields? - "True if every lookup of nm across nodes uses a declared field in fields — the - record-only guard that keeps a :jolt/deftype/unknown-key read (not a positional - arg) from being folded to the wrong value." - [nodes nm fields] - (every? (fn [node] - (let [acc (atom #{})] - (collect-keys! node nm acc) - (every? (fn [k] (field-index fields k)) @acc))) - nodes)) - -(defn- src-val - "Field value at k from a foldable struct source — a const-key map (absent key - -> nil, struct-map semantics) or a record ctor (k is always a declared field - here, guaranteed by lookups-all-fields?)." - [src k] - (if (= :map (get src :op)) - (map-val src k) - (ctor-val src (ctor-shape src) k))) - -(defn- subst-lookup - "Replace every (:k nm)/(get nm :k) in node with the source value at k. The - caller guarantees (via local-escapes?) that nm is never rebound here and - appears only as a lookup subject, so no shadowing logic is needed." - [node nm src] - (let [k (lookup-key node nm)] - (if k - (src-val src k) - ;; the caller's escape check guarantees nm is never rebound below, so we - ;; recurse uniformly into every child — leaving any lookup of nm - ;; un-substituted would dangle. - (map-ir-children (fn [c] (subst-lookup c nm src)) node)))) - -(defn- fold-kw-literal - "(a) (:k ) -> the value at k. is a const-key pure map - ((:k {:k a ..}) -> a) or a pure record ctor ((:k (->Rec a ..)) -> the arg for - field k). Siblings are duplicated/discarded, so all must be pure; a record - lookup folds only for a declared field." - [node] - (let [f (get node :fn) args (get node :args)] - (if (and (kw-callee? f) (= 1 (count args))) - (let [m (nth args 0) k (get f :val)] - (if (and (= :map (get m :op)) (const-key-map? m) (all-vals-pure? m)) - (do (mark!) (map-val m k)) - (let [rs (ctor-shape m)] - (if (and rs (ctor-all-args-pure? m) (field-index (get rs :fields) k)) - (do (mark!) (ctor-val m rs k)) - node)))) - node))) - -(defn- elim-let-structs - "(b) Drop the first non-escaping let binding whose init is a foldable struct - source — a pure const-key map literal or a pure record ctor — substituting its - field reads into the remaining bindings and body. Fixpoint re-runs us for the - rest, so one elimination per call keeps it simple. For a record every lookup - of the binding must hit a declared field, else we keep the allocation." - [node] - (let [binds (get node :bindings) n (count binds) body (get node :body)] - (loop [i 0] - (if (< i n) - (let [b (nth binds i) nm (nth b 0) init (nth b 1) - ismap (and (= :map (get init :op)) (const-key-map? init) (all-vals-pure? init)) - rs (when (not ismap) (ctor-shape init)) - isrec (and rs (ctor-all-args-pure? init))] - (if (and (or ismap isrec) - (not (any-binding-named? (subvec binds (inc i) n) nm)) - (not (loop [j (inc i)] - (if (< j n) - (if (local-escapes? (nth (nth binds j) 1) nm) true (recur (inc j))) - false))) - (not (local-escapes? body nm)) - (or ismap - (lookups-all-fields? - (conj (mapv (fn [bb] (nth bb 1)) (subvec binds (inc i) n)) body) - nm (get rs :fields)))) - (let [head (subvec binds 0 i) - tail (mapv (fn [bb] [(nth bb 0) (subst-lookup (nth bb 1) nm init)]) - (subvec binds (inc i) n)) - newbinds (reduce conj head tail) - newbody (subst-lookup body nm init)] - (mark!) - (if (= 0 (count newbinds)) - newbody - (assoc node :bindings newbinds :body newbody))) - (recur (inc i)))) - node)))) - -(defn scalar-replace - "Bottom-up: scalar-replace children, then apply (a) at invokes / (b) at lets." - [node] - (let [op (get node :op)] - (cond - ;; (a) fold (:k ) at invokes, after scalar-replacing children - (= op :invoke) (fold-kw-literal (map-ir-children scalar-replace node)) - ;; (b) drop a non-escaping foldable-struct let binding, after children - (= op :let) (elim-let-structs (map-ir-children scalar-replace node)) - :else (map-ir-children scalar-replace node)))) diff --git a/jolt-core/jolt/passes/numeric.clj b/jolt-core/jolt/passes/numeric.clj deleted file mode 100644 index 1f2df79..0000000 --- a/jolt-core/jolt/passes/numeric.clj +++ /dev/null @@ -1,275 +0,0 @@ -(ns jolt.passes.numeric - "Hint-directed numeric specialization. A local forward type-flow that seeds - local kinds from `^double`/`^long` fn-param hints and float literals, propagates - them through let inits, arithmetic results, and if/do, and tags an arithmetic - `:invoke` node with `:num-kind :double` or `:long` when every operand is that - kind (an integer literal is a wildcard, valid in either). The back end then emits - Chez `fl*`/`fx*` ops instead of generic arithmetic. - - Soundness: `:long` is seeded ONLY from an explicit `^long` hint — never a bare - integer literal — so un-hinted integer code keeps jolt's arbitrary-precision - numbers (no fixnum overflow surprise). `:double` is seeded from `^double` hints - and float literals; flonum arithmetic is always flonum, so this matches the - generic result. A `^long` hint is a promise the value is a fixnum: `fx+` raises - on overflow rather than promoting, exactly as a JVM primitive long is fixed-width. - - Runs in every build and at `-e`/repl, but not the seed mint (which compiles with - the passes off), so it stays out of the self-host fixpoint and benefits open and - closed builds alike." - (:require [jolt.ir :refer [map-ir-children]])) - -;; --- operand classification ------------------------------------------------- -(defn- int-lit? [n] - (and (= :const (get n :op)) - (let [v (get n :val)] (and (number? v) (integer? v))))) -(defn- float-lit? [n] - (and (= :const (get n :op)) - (let [v (get n :val)] (and (number? v) (float? v))))) - -;; result kind of a double-specialized op at this name/arity, or nil if N/A. -;; arithmetic -> :double; comparison -> :bool (operands specialized, result not numeric). -;; Every op name dbl-spec / lng-spec returns non-nil for must have a Chez op in -;; jolt.backend-scheme/dbl-ops resp. lng-ops, or emit-numeric splices a nil op. -(defn- dbl-spec [nm n] - (cond - (and (>= n 1) (contains? #{"+" "-" "*" "/" "min" "max"} nm)) :double - (and (= n 1) (contains? #{"inc" "dec"} nm)) :double - (and (>= n 2) (contains? #{"<" ">" "<=" ">=" "=" "=="} nm)) :bool - :else nil)) - -;; result kind of a long-specialized op, or nil. `/` is absent on purpose: -;; (/ long long) is a Ratio in Clojure, not a long. unchecked-* join the fast path -;; (they aren't native ops otherwise). -(defn- lng-spec [nm n] - (cond - (and (>= n 1) (contains? #{"+" "-" "*" "min" "max" - "unchecked-add" "unchecked-subtract" "unchecked-multiply"} nm)) :long - (and (= n 1) (contains? #{"inc" "dec" "unchecked-inc" "unchecked-dec"} nm)) :long - (and (= n 2) (contains? #{"quot" "rem" "mod"} nm)) :long - (and (>= n 2) (contains? #{"<" ">" "<=" ">=" "=" "=="} nm)) :bool - :else nil)) - -;; result kind of a bigdec-specialized op, or nil. Arithmetic / quot / rem yield a -;; bigdec; the comparisons and zero?/pos?/neg? yield a bool. `=` is left to the -;; generic jolt= (already bigdec-aware), and `/` can throw (non-terminating) but is -;; still a bigdec op. Each non-nil name must have an entry in backend bd-ops. -(defn- bd-spec [nm n] - (cond - (and (>= n 1) (contains? #{"+" "-" "*" "/" "min" "max"} nm)) :bigdec - (and (= n 2) (contains? #{"quot" "rem"} nm)) :bigdec - (and (= n 1) (contains? #{"zero?" "pos?" "neg?"} nm)) :bool - (and (>= n 2) (contains? #{"<" ">" "<=" ">="} nm)) :bool - :else nil)) - -;; A non-numeric result (a comparison) doesn't propagate a numeric kind. -(defn- propagate [spec] (if (= spec :bool) nil spec)) - -(declare an) - -;; The recur-arg kinds for the recurs targeting THIS loop level. recur only appears -;; in tail position (an if branch, a do's ret, a let body), so descend only those; -;; a nested loop/fn (and any non-tail child) owns its own recur and is skipped. -(defn- recur-kinds [node tenv] - (let [op (get node :op)] - (cond - (= op :recur) [(mapv (fn [a] (nth (an a tenv) 0)) (get node :args))] - (= op :let) (recur-kinds (get node :body) - (reduce (fn [te b] (assoc te (nth b 0) (nth (an (nth b 1) te) 0))) - tenv (get node :bindings))) - (= op :if) (concat (recur-kinds (get node :then) tenv) (recur-kinds (get node :else) tenv)) - (= op :do) (recur-kinds (get node :ret) tenv) - :else []))) - -;; The recur-arg NODE lists for the recurs at THIS loop level (structural, no env), -;; parallel to recur-kinds. Used to recognise a counter. -(defn- recur-arg-lists [node] - (let [op (get node :op)] - (cond - (= op :recur) [(get node :args)] - (= op :let) (recur-arg-lists (get node :body)) - (= op :if) (concat (recur-arg-lists (get node :then)) (recur-arg-lists (get node :else))) - (= op :do) (recur-arg-lists (get node :ret)) - :else []))) - -;; Is `arg` an increment-style step of loop var `vname`: the var unchanged, or -;; inc/dec/unchecked-inc/dec, or (+/- var )? Bounded growth that a -;; fixnum-range counter can sustain for any realistic loop — unlike (* acc x), which -;; overflows fast, so a multiplicative accumulator never qualifies and stays -;; arbitrary-precision. -(defn- counter-step? [arg vname] - (cond - (and (= :local (get arg :op)) (= vname (get arg :name))) true - (= :invoke (get arg :op)) - (let [f (get arg :fn) as (get arg :args)] - (and (= :var (get f :op)) (= "clojure.core" (get f :ns)) - (let [nm (get f :name) - v? (fn [n] (and (= :local (get n :op)) (= vname (get n :name))))] - (cond - (and (contains? #{"inc" "dec" "unchecked-inc" "unchecked-dec"} nm) (= 1 (count as))) - (v? (nth as 0)) - (and (contains? #{"+" "unchecked-add"} nm) (= 2 (count as))) - (or (and (v? (nth as 0)) (int-lit? (nth as 1))) - (and (v? (nth as 1)) (int-lit? (nth as 0)))) - (and (contains? #{"-" "unchecked-subtract"} nm) (= 2 (count as))) - (and (v? (nth as 0)) (int-lit? (nth as 1))) - :else false)))) - :else false)) - -;; Loop-var kinds by bounded fixpoint. A var keeps its init kind (:double or :long) -;; only if every recur arg in that slot is the same kind (under the current -;; assumption) — a monotone demotion that stops at a fixpoint, bounded by the var -;; count. An integer-literal init has kind nil and stays generic, so a bignum loop -;; keeps arbitrary precision (no :long from a bare literal). A typed loop var's init -;; and recur args are all flonums/fixnums (a :long init flows from a coerced ^long -;; value or an fx op), so no entry coercion is needed here, unlike a fn param. -(defn- loop-kinds [names seed body tenv] - (loop [cur seed iter 0] - (if (> iter (count names)) - cur - (let [te (reduce (fn [t i] (assoc t (nth names i) (nth cur i))) tenv (range (count names))) - rks (recur-kinds body te) - nxt (mapv (fn [j] - (let [k (nth cur j)] - (if (and k (every? (fn [rk] (= k (nth rk j))) rks)) k nil))) - (range (count names)))] - (if (= nxt cur) cur (recur nxt (inc iter))))))) - -;; Seed a fn arity's local env from its numeric param hints; an unhinted param -;; shadows any same-named outer local to nil. -(defn- arity-env [tenv a] - (let [nh (into {} (get a :nhints)) - pe (reduce (fn [e p] (assoc e p (get nh p))) tenv (get a :params))] - (if (get a :rest) (assoc pe (get a :rest) nil) pe))) - -(defn- an-invoke - "Annotate an :invoke with its numeric kind. An arithmetic core op specializes to - the Chez fl*/fx* op only when every operand is the same kind (:double or :long), - except an integer literal is :wild — valid in either — so (+ ^double x 2) stays - double. A call to a ^double/^long-returning var yields that kind without lowering - the call (its body already coerces the return)." - [node tenv] - (let [fnode (get node :fn) - nm (when (and (= :var (get fnode :op)) (= "clojure.core" (get fnode :ns))) - (get fnode :name)) - ars (mapv (fn [a] (an a tenv)) (get node :args)) - argnodes (mapv (fn [r] (nth r 1)) ars) - node1 (assoc node :args argnodes) - n (count ars)] - (cond - ;; a field read the structural inference proved is a flonum (a ^double record - ;; field) is a :double operand — so (* (:x v) (:x v)) unboxes. The read itself - ;; isn't lowered here; it keeps its keyword/jrec-field-at emit. - (= :double (get node :num-read)) [:double node1] - ;; a call to a var with a declared numeric return (^double/^long) yields that - ;; kind, so an accumulator over the result types. The call itself isn't an - ;; arithmetic op to lower — its body already coerces the return. - (get fnode :num-ret) [(get fnode :num-ret) node1] - (nil? nm) [nil node1] - :else - (let [;; per-operand class: :double / :long / :bigdec (typed), :wild (integer - ;; literal, usable in any), or :no (anything else — blocks specialization). - cls (mapv (fn [r] (let [k (nth r 0) nd (nth r 1)] - (cond (= k :double) :double - (= k :long) :long - (= k :bigdec) :bigdec - (int-lit? nd) :wild - :else :no))) - ars) - ok? (fn [allowed need] - (and (pos? n) - (every? (fn [c] (or (= c :wild) (= c allowed))) cls) - (some (fn [c] (= c need)) cls))) - ds (dbl-spec nm n) - ls (lng-spec nm n) - bs (bd-spec nm n)] - (cond - (and ds (ok? :double :double) - ;; min/max return the ORIGINAL operand (Numbers.min: an integer - ;; literal stays exact), so an int-literal operand blocks the - ;; flonum lowering there — flmin would coerce it. - (or (not (contains? #{"min" "max"} nm)) - (every? (fn [c] (= c :double)) cls))) - ;; coerce integer-literal operands to flonum so fl-ops never see an exact int. - (let [args' (mapv (fn [nd] (if (int-lit? nd) (assoc nd :val (double (get nd :val))) nd)) - argnodes)] - [(propagate ds) (assoc node1 :args args' :num-kind :double)]) - (and ls (ok? :long :long)) - [(propagate ls) (assoc node1 :num-kind :long)] - ;; bigdec: every operand a bigdec (integer literals allowed, coerced at - ;; runtime). A flonum operand blocks this (double contagion) and falls - ;; through to the generic op. - (and bs (ok? :bigdec :bigdec)) - [(propagate bs) (assoc node1 :num-kind :bigdec)] - :else [nil node1]))))) - -;; Returns [kind node'] — kind is :double, :long, or nil. -(defn- an [node tenv] - (let [op (get node :op)] - (cond - (= op :const) [(if (float-lit? node) :double nil) node] - ;; a bigdec (M) literal seeds the :bigdec kind so call-position arithmetic - ;; over it (and let-bound copies of it) dispatches to the bigdec engine. - (= op :bigdec) [:bigdec node] - (= op :local) [(get tenv (get node :name)) node] - (= op :coerce) [(get node :kind) (assoc node :expr (nth (an (get node :expr) tenv) 1))] - (= op :invoke) (an-invoke node tenv) - (= op :let) - (let [res (reduce (fn [acc b] - (let [te (nth acc 0) binds (nth acc 1) - ir (an (nth b 1) te)] - [(assoc te (nth b 0) (nth ir 0)) (conj binds [(nth b 0) (nth ir 1)])])) - [tenv []] (get node :bindings)) - br (an (get node :body) (nth res 0))] - [(nth br 0) (assoc node :bindings (nth res 1) :body (nth br 1))]) - (= op :loop) - ;; inits evaluate in the OUTER env; loop vars get their fixpoint kinds for the body. - (let [binds (get node :bindings) - names (mapv (fn [b] (nth b 0)) binds) - ik (mapv (fn [b] (nth (an (nth b 1) tenv) 0)) binds) - rlists (recur-arg-lists (get node :body)) - ;; seed each var: an already-typed init keeps its kind; an integer-literal - ;; init whose recur args are all counter steps is a fixnum counter (:long). - seed (mapv (fn [j] - (let [k (nth ik j) b (nth binds j)] - (cond - k k - ;; an int-literal var is a fixnum counter only in a real - ;; iterating loop (>= 1 recur) whose every step is bounded. - ;; A recur-less loop is a let — its int literal stays - ;; generic (arbitrary precision), like a let binding. - (and (seq rlists) - (int-lit? (nth b 1)) - (every? (fn [args] (counter-step? (nth args j) (nth b 0))) rlists)) - :long - :else nil))) - (range (count names))) - lk (loop-kinds names seed (get node :body) tenv) - te (reduce (fn [t i] (assoc t (nth names i) (nth lk i))) tenv (range (count names)))] - [nil (assoc node - :bindings (mapv (fn [b] [(nth b 0) (nth (an (nth b 1) tenv) 1)]) binds) - :body (nth (an (get node :body) te) 1))]) - (= op :if) - (let [tr (an (get node :test) tenv) - thn (an (get node :then) tenv) - els (an (get node :else) tenv) - tk (nth thn 0) ek (nth els 0)] - [(if (= tk ek) tk nil) - (assoc node :test (nth tr 1) :then (nth thn 1) :else (nth els 1))]) - (= op :do) - (let [stmts (mapv (fn [s] (nth (an s tenv) 1)) (get node :statements)) - r (an (get node :ret) tenv)] - [(nth r 0) (assoc node :statements stmts :ret (nth r 1))]) - (= op :fn) - [nil (assoc node :arities - (mapv (fn [a] (assoc a :body (nth (an (get a :body) (arity-env tenv a)) 1))) - (get node :arities)))] - (= op :def) [nil (assoc node :init (nth (an (get node :init) tenv) 1))] - ;; every other op introduces no bindings and isn't numeric: descend with the - ;; same env to specialize nested arithmetic, no kind. - :else [nil (map-ir-children (fn [c] (nth (an c tenv) 1)) node)]))) - -(defn annotate - "Tag arithmetic nodes with :num-kind from local numeric type-flow. Returns the - rewritten IR (no kind escapes to the caller)." - [node] - (nth (an node {}) 1)) diff --git a/jolt-core/jolt/passes/types.clj b/jolt-core/jolt/passes/types.clj deleted file mode 100644 index 1aeba9a..0000000 --- a/jolt-core/jolt/passes/types.clj +++ /dev/null @@ -1,932 +0,0 @@ -(ns jolt.passes.types - "Collection-type inference and success-type checking (RFC 0006). - A forward, soft-typing pass (simplified HM: monovariant, never-fails, lattice - top = :any) that types expressions and reuses the same walk as a loose success - checker. Also the inter-procedural driver API the back end calls to - propagate param types across a unit / the whole program. Weakly coupled to the - IR-rewriting passes — shares the const-shape predicates (jolt.passes.fold)." - (:require [jolt.ir :refer [reduce-ir-children]] - [jolt.passes.fold :refer [scalar-const? kw-callee? get-callee?]] - [jolt.passes.types.check :refer - [not-callable? type-name check-invoke register-user-fn!]] - [jolt.passes.types.lattice :refer - [velem selem sfields vec-type? set-type? struct-type? mk-vec mk-set - mk-struct union-cap scalar-t? union-type? umembers union-of merge-fields - join-t join type-depth cap struct-safe? field-type shape-order type-shape - mark-struct truthy-type? num-ret-fns vector-ret-fns nilable? strip-nilable]])) - -;; --- engine state ------------------------------------------------------------ -;; The walk threads an immutable `env` (mk-env) instead of reading scattered -;; module atoms: it carries the read-only config (rtenv/vtypes/record-shapes/ -;; protocol-methods/map-shapes?) plus the per-run flags (checking?/strict?) and -;; per-run accumulator/guard CELLS (diags/calls/checking-set/diag-memo). A fresh -;; env per run makes the pass re-entrant — a nested probe (isolated-diag-count) -;; runs under a sub-env with its own diags cell, no save/restore. -;; -;; Only state whose lifecycle spans separate API calls stays module-level: the -;; config the orchestrator installs (set-*! before a sweep), the escapes and -;; user-sig registries (collected/registered across the forms of a sweep), and a -;; bridge holding the last checking run's diagnostics for take-diags!. -(def ^:private config-box - (atom {:rtenv {} ;; "ns/name" -> inferred return type - :vtypes {} ;; "ns/name" -> var VALUE type (fn=:truthy, def=init type) - :record-shapes {} ;; "ns/->Name" -> {:fields :tags :type} - :protocol-methods {} ;; "ns/method" -> [proto method] - :map-shapes? false})) ;; shape generic const-key maps (opt-in, JOLT_SHAPE) -;; var-keys used as a VALUE (not a call head) — accumulated across a whole sweep, -;; reset by reset-escapes! and read by collected-escapes. -(def ^:private escapes-box (atom #{})) -;; User-function error domains, opt-in. As the checker walks defs it registers -;; each non-redefinable single-fixed-arity user fn's {:params :body} here, keyed -;; "ns/name"; a later call site (strict mode) re-checks the body with one param -;; bound to its concrete argument type. Accumulates ACROSS forms — a def must -;; precede its call (the closed-world ordering RFC 0005 assumes). -(def ^:private user-sig-box (atom {})) ;; "ns/name" -> {:params [..] :body ir} -;; Diagnostics from the last checking run-inference, for take-diags! to drain. -(def ^:private last-diags-box (atom [])) -;; Whether run-inference also checks, and strictly. Set by set-check-mode!. -(def ^:private check-mode-box (atom {:on false :strict false})) -;; "Proto/method" -> the join of its impls' return types, so a protocol-method call -;; types as that record when every impl returns the same one (monomorphic return — -;; e.g. all Scatter impls return a ScatterResult). Set by collect-pm-rets! before -;; the fixpoint, read by call-ret-type. A disagreeing impl widens it to :any. -(def ^:private pm-rets-box (atom {})) - -;; build a per-run env: a snapshot of the installed config plus this run's flags -;; and fresh accumulator/guard cells. escapes/user-sigs reference the sweep-level -;; module cells (their lifecycle spans calls); diags/calls/checking-set/diag-memo -;; are this run's own. -(defn- mk-env [checking? strict?] - (let [c @config-box] - {:rtenv (get c :rtenv) :vtypes (get c :vtypes) - :record-shapes (get c :record-shapes) :protocol-methods (get c :protocol-methods) - :map-shapes? (get c :map-shapes?) - :checking? checking? :strict? strict? - :diags (atom []) :calls (atom []) :checking-set (atom #{}) :diag-memo (atom {}) - :escapes escapes-box :user-sigs user-sig-box})) - -;; build a record's struct TYPE from its registry entry, resolving each field's -;; declared type hint against `shapes` ("ns/->Name" -> entry). A field tagged with -;; a record type (its ctor-key) recurses, so a Vec3 stored in a Ray field reads -;; back as Vec3 — not :any — which is what lets nested-record code prove its reads. -;; Depth-bounded so a self/cyclic-referencing record type can't loop. -(declare record-type-from-entry) -(defn- field-type-from-tag [tag depth shapes] - (cond - (or (nil? tag) (<= depth 0)) :any - (= tag "num") :num - (= tag "double") :double ; a ^double field reads back as a flonum - :else (let [e (get shapes tag)] - (if e (record-type-from-entry e depth shapes) :any)))) -(defn- record-type-from-entry [rs depth shapes] - (let [fields (get rs :fields) - tags (get rs :tags) - fmap (reduce (fn [m i] - (assoc m (nth fields i) - (field-type-from-tag (when tags (nth tags i)) (dec depth) shapes))) - {} (range (count fields)))] - (assoc (mk-struct fmap) :shape (vec fields) :type (get rs :type)))) - -;; fns that RETURN an element of their (first) collection arg, so a lookup on the -;; result of (rand-nth coll-of-structs) etc. types as the element. -(def ^:private elem-fns #{"rand-nth" "first" "peek" "last" "nth" "fnext" "second"}) - -;; defined after infer but referenced from it (the rest of the checker lives in -;; jolt.passes.types.check, required above) -(declare check-user-call) - -(defn- var-key [fnode] (str (get fnode :ns) "/" (get fnode :name))) - -(defn- call-ret-type [fnode env] - (let [op (get fnode :op) - shapes (get env :record-shapes)] - (cond - ;; a user fn whose return type the fixpoint has estimated - (= op :var) (let [rs (get shapes (var-key fnode))] - (if rs - ;; record ctor -> struct of declared shape; :shape - ;; is the DECLARED field order the back end indexes by, :type - ;; the record tag (devirt), and field types come from the - ;; declared hints so nested records stay typed - (record-type-from-entry rs type-depth shapes) - (let [r (get (get env :rtenv) (var-key fnode))] - (if r r - ;; a protocol-method call types as its impls' joined return - ;; (monomorphic): so (:ray (scatter m ..)) reads off a Ray. - (let [pm (get (get env :protocol-methods) (var-key fnode)) - pmr (when pm (get @pm-rets-box (str (nth pm 0) "/" (nth pm 1))))] - (if (and pmr (not= pmr :any)) - pmr - (let [nm (and (= "clojure.core" (get fnode :ns)) (get fnode :name))] - (cond (nil? nm) :any - (contains? num-ret-fns nm) :num - (contains? vector-ret-fns nm) (mk-vec :any) - :else :any)))))))) - (= op :host) (let [nm (get fnode :name)] - (cond (contains? num-ret-fns nm) :num - (contains? vector-ret-fns nm) (mk-vec :any) - :else :any)) - :else :any))) - -;; Predicate folding: a type predicate whose argument's type is -;; PROVEN folds to a compile-time boolean. Only the precise tags are folded — -;; :num/:str/:kw mean exactly that scalar, and a record carries its defrecord -;; :type tag. NOT folded: vector?/set?/map?, because the :vec tag conflates a -;; real vector with a range/seq (so vector? could be wrong) — left for when the -;; lattice distinguishes them. :any and :truthy carry no structural info (a -;; value known only non-nil could be any concrete type), so every predicate is -;; unknown on them. nil?/some? fold because every concrete type here is -;; provably non-nil. -(def ^:private fold-preds - #{"number?" "string?" "keyword?" "record?" "nil?" "some?"}) -(defn- record-t? [t] (and (struct-type? t) (some? (get t :type)))) -(defn- pred-on [pname t] - (cond - (or (= t :any) (= t :truthy)) nil - ;; a nilable struct might be nil — nil?/some?/record? can't be proven, so the - ;; runtime guard must stay (this is what makes the narrowing sound). - (nilable? t) nil - ;; a bounded scalar union folds only when every member agrees - (union-type? t) - (let [vs (map (fn [m] (pred-on pname m)) (umembers t))] - (if (and (seq vs) (not (nil? (first vs))) (apply = vs)) (first vs) nil)) - :else - (case pname - "number?" (or (= t :num) (= t :double)) - "string?" (= t :str) - "keyword?" (= t :kw) - "record?" (record-t? t) - "nil?" false - "some?" true - nil))) -;; Side-effect-free node whose evaluation can be dropped when its predicate -;; folds away (a wider purity analysis can broaden this later). -(defn- pure-node? [n] (let [op (get n :op)] (or (= op :const) (= op :local)))) - -;; Flow-sensitive nil narrowing: in (if (some? x) ..) / (if x ..) / (if (nil? x) ..) -;; a nilable-struct local x is proven non-nil in one branch, so its field reads -;; bare-index and unbox there. Only a nilable local narrows — nothing else changes. -(defn- test-local [test pred-name] - (when (= :invoke (get test :op)) - (let [f (get test :fn) args (get test :args)] - (when (and (= :var (get f :op)) (= "clojure.core" (get f :ns)) - (= pred-name (get f :name)) - (= 1 (count args)) (= :local (get (nth args 0) :op))) - (get (nth args 0) :name))))) -(defn- narrow-nonnil [tenv nm] - (let [t (get tenv nm)] (if (nilable? t) (assoc tenv nm (strip-nilable t)) tenv))) -;; [then-tenv else-tenv] for an `if` whose test narrows a nilable local. -(defn- if-narrow [test tenv] - (let [somev (test-local test "some?") - nilv (test-local test "nil?")] - (cond - (= :local (get test :op)) [(narrow-nonnil tenv (get test :name)) tenv] - somev [(narrow-nonnil tenv somev) tenv] - nilv [tenv (narrow-nonnil tenv nilv)] - :else [tenv tenv]))) - -(declare infer) - -;; infer (and infer-fn-seeded) return a [type node'] tuple — the result type plus -;; the rewritten subtree. A bare (nth r 0)/(nth r 1) transposes silently and still -;; type-checks, so name the projections; the call-pattern code below is dense in them. -(defn- ty [r] (nth r 0)) -(defn- nd [r] (nth r 1)) - -;; Arg types for a self-recursive call. A same-position pass-through of the -;; enclosing param (arg i is the bare param i) contributes nil — the join identity — -;; instead of its type: it can't add information (param i ⊇ param i is trivial), but -;; its type is :any until external callers determine it, and :any is absorbing, so -;; collecting it would pin the param at :any forever (a recursive fn that threads a -;; param straight through, e.g. ray-cast passing `hittables` unchanged). A computed -;; arg, or a DIFFERENT param at this position, is a real constraint and is collected. -(defn- self-rec-argtys [args ares self-params] - (mapv (fn [i] - (let [a (nth args i)] - (if (and self-params (< i (count self-params)) - (= :local (get a :op)) (= (get a :name) (nth self-params i))) - nil - (ty (nth ares i))))) - (range (count ares)))) - -;; arithmetic core ops that yield a flonum when their operands are flonums — a -;; mirror of jolt.passes.numeric/dbl-spec's arithmetic set, used to flow :double -;; across fn boundaries so a hintless fn whose callers all pass doubles is unboxed. -;; Comparisons are excluded: they yield a boolean, not a number. -(def ^:private dbl-arith-ops #{"+" "-" "*" "/" "min" "max" "inc" "dec"}) -(defn- int-lit-node? [n] - (and (= :const (get n :op)) (let [v (get n :val)] (and (number? v) (integer? v))))) -;; an arithmetic result is :double when every operand is a proven flonum or an -;; integer literal (a wildcard the fl-op coerces) and at least one is a flonum — so -;; (* x 2) with x:double is :double, but (* a b) with both :num stays :num (no -;; flonum proof, no fl-op). -(defn- dbl-arith? [ares argnodes] - (and (pos? (count ares)) - (every? (fn [i] (or (= :double (ty (nth ares i))) (int-lit-node? (nth argnodes i)))) - (range (count ares))) - (some (fn [r] (= :double (ty r))) ares))) - -;; HOFs that apply their fn arg to the ELEMENTS of a collection. :epos is which -;; param of the fn receives an element. reduce is -;; handled separately (its arity changes the coll position, and its closure -;; also takes an accumulator). -(def ^:private hof-table - {"map" {:epos 0} "mapv" {:epos 0} "filter" {:epos 0} "filterv" {:epos 0} - "keep" {:epos 0} "remove" {:epos 0} "run!" {:epos 0} "mapcat" {:epos 0}}) - -(defn- infer-fn-seeded - "Infer a fn-literal passed to a HOF, seeding the given params to element/accum - types (seeds: param-index -> type), other params :any, captured locals from - tenv. Returns [ret-type node'] — ret is the lub of arity tail types, used to - type the HOF result (e.g. reduce's accumulator, mapv's element)." - [node seeds tenv env] - (let [res (mapv (fn [a] - (let [params (get a :params) - pe (reduce (fn [e i] - (assoc e (nth params i) - (let [s (get seeds i)] (if s s :any)))) - tenv (range (count params))) - pe (if (get a :rest) (assoc pe (get a :rest) :any) pe) - br (infer (get a :body) pe env)] - [(ty br) (assoc a :body (nd br))])) - (get node :arities)) - rets (mapv (fn [r] (ty r)) res) - ret (if (empty? rets) :any (reduce join (first rets) (rest rets)))] - [ret (assoc node :arities (mapv (fn [r] (nd r)) res))])) - -;; --- :invoke call patterns --------------------------------------------------- -;; infer's :invoke arm splits the callee/args once, then dispatches by callee -;; shape to one of these. Each returns [type node']; all recurse through `infer`. - -(defn- infer-pred-fold - "A type predicate over a single side-effect-free arg whose type PROVES the answer - folds to a boolean constant — eliminating the call, and (once const-fold runs - after inference) collapsing any `if` it gates. Falls back to the normal call path - when the answer isn't provable or the arg is impure." - [node fnode cn args tenv env] - (let [ar (infer (nth args 0) tenv env) - v (pred-on cn (ty ar))] - (if (and (not (nil? v)) (pure-node? (nd ar))) - [:any {:op :const :val v}] - [(call-ret-type fnode env) (assoc node :args [(nd ar)])]))) - -(defn- infer-kw-lookup - "(:k m) / (:k m default): the result is m's field type, and if m is a struct the - subject is tagged so the back end drops the guard — this types nested access end - to end (RFC 0005)." - [node fnode args n tenv env] - (let [mr (infer (nth args 0) tenv env) - mt (ty mr) - msub (if (struct-safe? mt) (mark-struct (nd mr) mt) (nd mr)) - ft (field-type mt (get fnode :val)) - dr (when (= n 2) (infer (nth args 1) tenv env)) - rt (if dr (join ft (ty dr)) ft) - node' (assoc node :args (if dr [msub (nd dr)] [msub]))] - ;; a flonum field read is a :double operand for the numeric pass (fl-ops); the - ;; lookup itself still emits as a keyword/jrec-field-at read, this only feeds - ;; its kind up so (* (:x v) (:x v)) over a ^double-fielded record unboxes. - [rt (if (= rt :double) (assoc node' :num-read :double) node')])) - -(defn- infer-get-lookup - "(get m :k [default]): the keyword-lookup result type, when the key is a constant - keyword." - [node args n tenv env] - (let [mr (infer (nth args 0) tenv env) - mt (ty mr) - msub (if (struct-safe? mt) (mark-struct (nd mr) mt) (nd mr)) - kr (infer (nth args 1) tenv env) - ft (field-type mt (get (nth args 1) :val)) - dr (when (= n 3) (infer (nth args 2) tenv env)) - rt (if dr (join ft (ty dr)) ft) - node' (assoc node :args (if dr [msub (nd kr) (nd dr)] [msub (nd kr)]))] - [rt (if (= rt :double) (assoc node' :num-read :double) node')])) - -(defn- infer-reduce-hof - "reduce over a typed vector with a fn-literal: seed the closure's accumulator - (param 0) to the init type and its element (param 1) to the vector's element - type, so its body — and any calls it makes — see those types." - [node args n tenv env] - (let [three (>= n 3) - coll-r (infer (nth args (if three 2 1)) tenv env) - init-r (when three (infer (nth args 1) tenv env)) - et (let [ct (ty coll-r)] (if (vec-type? ct) (velem ct) :any)) - init-t (if init-r (ty init-r) :any) - fn-r (infer-fn-seeded (nth args 0) {0 init-t 1 et} tenv env)] - [(join init-t (ty fn-r)) - (assoc node :args (if three - [(nd fn-r) (nd init-r) (nd coll-r)] - [(nd fn-r) (nd coll-r)]))])) - -(defn- infer-seq-hof - "map/mapv/filter/... over a typed vector with a fn-literal: seed the fn's element - param; mapv/filterv produce a typed vector." - [node cn args tenv env] - (let [coll-r (infer (nth args 1) tenv env) - et (let [ct (ty coll-r)] (if (vec-type? ct) (velem ct) :any)) - fn-r (infer-fn-seeded (nth args 0) {(get (get hof-table cn) :epos) et} tenv env) - rt (cond (= cn "mapv") (mk-vec (ty fn-r)) - (= cn "filterv") (mk-vec et) - :else :any)] - [rt (assoc node :args [(nd fn-r) (nd coll-r)])])) - -(defn- infer-conj-into - "conj/into: track the element type of a vector being grown." - [node fnode cn args n tenv env] - (let [ares (mapv (fn [a] (infer a tenv env)) args) - base (ty (nth ares 0)) - rest-ts (mapv (fn [r] (ty r)) (rest ares)) - rt (cond - (and (= cn "conj") (vec-type? base)) - (mk-vec (reduce join (velem base) rest-ts)) - (and (= cn "into") (vec-type? base) (= 2 n) (vec-type? (nth rest-ts 0))) - (mk-vec (join (velem base) (velem (nth rest-ts 0)))) - :else (call-ret-type fnode env))] - [rt (assoc node :args (mapv (fn [r] (nd r)) ares))])) - -(defn- infer-call - "Everything else: type the args, collect the call (var callee) for whole-program - inference, run the success-type check, and use the declared/estimated return type. - range produces a numeric vector; an element-returning fn over a typed vector - yields the element type. A protocol-method call whose receiver (arg 0) is a known - record type is annotated [type-tag proto method] for devirtualization — the back - end looks up the impl at emit time and calls it directly, skipping the registry - dispatch (~19x cheaper)." - [node fnode iscall-var cn args n tenv env] - (let [fr (when (not iscall-var) (infer fnode tenv env)) - fnode' (if iscall-var fnode (nd fr)) - ;; the callee's value type: a var's from vtypes (a fn is :truthy, a def - ;; carries its inferred type), else the inferred type of the callee expr - callee-t (if iscall-var (get (get env :vtypes) (var-key fnode)) (ty fr)) - ares (mapv (fn [a] (infer a tenv env)) args)] - (when iscall-var - ;; a `defn` recurses through its own VAR, so a self-recursion is a var-call - ;; here (not the :local case below). When the callee is the enclosing def, - ;; drop same-position pass-through args so threading a param straight through - ;; the recursion doesn't poison it to :any. - (swap! (get env :calls) conj - [(var-key fnode) - (if (= (var-key fnode) (get env :self-key)) - (self-rec-argtys args ares (get env :self-params)) - (mapv (fn [r] (ty r)) ares))])) - ;; a named fn calling itself binds its name as a :local, so the recursion is - ;; invisible to the var-call collection above — yet it constrains the fn's own - ;; params. Collect it under the fn's var-key so the whole-program fixpoint joins - ;; the recursive arg types (else a self-recursive param is typed from external - ;; callers alone and may be specialized to a type the recursion violates). - (when (and (= :local (get fnode :op)) (get env :self-key) - (= (get fnode :name) (get env :self-name))) - (swap! (get env :calls) conj - [(get env :self-key) (self-rec-argtys args ares (get env :self-params))])) - ;; success-type check at this call, reusing the arg types just computed (jolt - ;; audit): core error domains always, user-fn domains in strict mode. - (when (get env :checking?) - (let [ats (mapv (fn [r] (ty r)) ares) pos (get node :pos)] - (when cn (check-invoke cn args ats pos env)) - (when (not-callable? callee-t) - (swap! (get env :diags) conj - {:op :call :type (type-name callee-t) :pos pos - :msg (str "cannot call " (type-name callee-t) " as a function")})) - (when (and (get env :strict?) iscall-var) - (let [k (var-key fnode) usig (get @(get env :user-sigs) k)] - (when usig (check-user-call k usig ats pos env)))))) - (let [pm (and iscall-var (get (get env :protocol-methods) (var-key fnode))) - rtype (when (and pm (pos? n)) (get (ty (nth ares 0)) :type)) - base (assoc node :fn fnode' :args (mapv (fn [r] (nd r)) ares))] - [(cond - (= cn "range") (mk-vec :num) - (and cn (contains? elem-fns cn) (> n 0)) - (let [a0 (ty (nth ares 0))] (if (vec-type? a0) (velem a0) :any)) - ;; flonum arithmetic yields a flonum — flows :double into a callee param - ;; (and into the fixpoint's return type) so hintless double code unboxes. - (and cn (contains? dbl-arith-ops cn) (dbl-arith? ares args)) :double - :else (call-ret-type fnode env)) - (if rtype - (assoc base :devirt-type rtype :devirt-proto (nth pm 0) :devirt-method (nth pm 1)) - base)]))) - -(defn- infer-invoke - "Split the callee/args once and dispatch by callee shape to a pattern helper." - [node tenv env] - (let [fnode (get node :fn) - iscall-var (= :var (get fnode :op)) - cn (when (and iscall-var (= "clojure.core" (get fnode :ns))) (get fnode :name)) - args (get node :args) - n (count args)] - (cond - (and iscall-var (contains? fold-preds cn) (= n 1)) - (infer-pred-fold node fnode cn args tenv env) - - (and (kw-callee? fnode) (>= n 1) (<= n 2)) - (infer-kw-lookup node fnode args n tenv env) - - (and (get-callee? fnode) - (>= n 2) (= :const (get (nth args 1) :op)) (keyword? (get (nth args 1) :val))) - (infer-get-lookup node args n tenv env) - - (and (= cn "reduce") (>= n 2) (= :fn (get (nth args 0) :op))) - (infer-reduce-hof node args n tenv env) - - (and cn (get hof-table cn) (>= n 2) (= :fn (get (nth args 0) :op))) - (infer-seq-hof node cn args tenv env) - - (and (or (= cn "conj") (= cn "into")) (>= n 1)) - (infer-conj-into node fnode cn args n tenv env) - - :else - (infer-call node fnode iscall-var cn args n tenv env)))) - -(defn- infer - "Returns [type node'] — the inferred type of node and node with struct-safe - :local references annotated :hint :struct. tenv maps in-scope local names to - inferred types; env carries the inference config and this run's accumulators." - [node tenv env] - (let [op (get node :op)] - (cond - (= op :const) - [(let [v (get node :val)] - (cond (and (number? v) (float? v)) :double ; a flonum literal is :double - (number? v) :num - (string? v) :str - (keyword? v) :kw - (nil? v) :nil ; a record|nil branch types as a nilable record - (= false v) :any ; false is not struct-eligible - :else :truthy)) ; true, char, ... -> non-nil - node] - (= op :local) - (let [t (get tenv (get node :name))] - [(if t t :any) - (cond - (struct-safe? t) (let [n (assoc node :hint :struct)] - (if (type-shape t) (assoc n :shape (type-shape t)) n)) - (vec-type? t) (assoc node :hint :vector) - :else node)]) - (= op :map) - (let [pairs (get node :pairs) - res (mapv (fn [pr] - (let [kr (infer (nth pr 0) tenv env) - vr (infer (nth pr 1) tenv env)] - [(nth kr 1) (nth vr 1) (nth vr 0) (get (nth pr 0) :val)])) - pairs) - struct? (and (> (count res) 0) - (every? (fn [pr] (scalar-const? (nth pr 0))) pairs) - (every? (fn [r] (truthy-type? (nth r 2))) res)) - base (when struct? - (cap (mk-struct (reduce (fn [m r] (assoc m (nth r 3) (nth r 2))) {} res)) type-depth)) - ;; a literal is a COMPLETE shape: carry its sorted key vector so the - ;; back end can lay it out and bare-index lookups - shp (when (and (get env :map-shapes?) base (struct-type? base)) (shape-order (keys (sfields base)))) - t (if base (if shp (assoc base :shape shp) base) :any) - node' (assoc node :pairs (mapv (fn [r] [(nth r 0) (nth r 1)]) res))] - [t (if shp (assoc node' :shape shp) node')]) - (= op :vector) - (let [irs (mapv (fn [x] (infer x tenv env)) (get node :items)) - ets (mapv (fn [r] (nth r 0)) irs) - el (if (empty? ets) :any (reduce join (first ets) (rest ets)))] - [(cap (mk-vec el) type-depth) (assoc node :items (mapv (fn [r] (nth r 1)) irs))]) - (= op :set) - (let [irs (mapv (fn [x] (infer x tenv env)) (get node :items)) - ets (mapv (fn [r] (nth r 0)) irs) - el (if (empty? ets) :any (reduce join (first ets) (rest ets)))] - [(cap (mk-set el) type-depth) (assoc node :items (mapv (fn [r] (nth r 1)) irs))]) - (= op :if) - (let [test (get node :test) - tr (infer test tenv env) - nr (if-narrow test tenv) ; narrow a nilable local in the proven branch - thn (infer (get node :then) (nth nr 0) env) - els (infer (get node :else) (nth nr 1) env)] - [(join (nth thn 0) (nth els 0)) - (assoc node :test (nth tr 1) :then (nth thn 1) :else (nth els 1))]) - (= op :do) - (let [stmts (mapv (fn [s] (nth (infer s tenv env) 1)) (get node :statements)) - r (infer (get node :ret) tenv env)] - [(nth r 0) (assoc node :statements stmts :ret (nth r 1))]) - (= op :throw) - [:any (assoc node :expr (nth (infer (get node :expr) tenv env) 1))] - ;; a :var reached HERE is in value position (an arg, a let init, ...), not - ;; a call head — so the fn it names escapes and its params can't be inferred. - ;; Its VALUE type comes from vtypes (a fn is :truthy, a def carries its - ;; inferred type); unknown -> :any. - (= op :var) (do (swap! (get env :escapes) conj (var-key node)) - [(let [vt (get (get env :vtypes) (var-key node))] (if vt vt :any)) node]) - (= op :invoke) (infer-invoke node tenv env) - (= op :let) - (let [res (reduce (fn [acc b] - (let [te (nth acc 0) binds (nth acc 1) - ir (infer (nth b 1) te env)] - [(assoc te (nth b 0) (nth ir 0)) (conj binds [(nth b 0) (nth ir 1)])])) - [tenv []] (get node :bindings)) - br (infer (get node :body) (nth res 0) env)] - [(nth br 0) (assoc node :bindings (nth res 1) :body (nth br 1))]) - (= op :loop) - ;; conservative + sound: loop bindings join across recur, which we don't - ;; track here, so they stay :any. Still descend to annotate any - ;; known-type lookups inside the body. A recur inside this body targets the - ;; loop, not the enclosing fn, so mark :in-loop? to suppress self-collection. - (let [lenv (assoc env :in-loop? true)] - [:any (assoc node - :bindings (mapv (fn [b] [(nth b 0) (nth (infer (nth b 1) tenv env) 1)]) (get node :bindings)) - :body (nth (infer (get node :body) tenv lenv) 1))]) - (= op :recur) - (let [ares (mapv (fn [a] (infer a tenv env)) (get node :args))] - ;; a fn-level recur (not inside a loop) rebinds the enclosing fn's params, - ;; so its args constrain them like a self-call — collect under the fn key. - (when (and (not (get env :in-loop?)) (get env :self-key)) - (swap! (get env :calls) conj - [(get env :self-key) (self-rec-argtys (get node :args) ares (get env :self-params))])) - [:any (assoc node :args (mapv (fn [r] (nd r)) ares))]) - (= op :fn) - ;; a closure inherits the enclosing tenv so CAPTURED locals keep their - ;; types (e.g. a reduce closure that calls (f captured-struct ...)). Its own - ;; params shadow to :any UNLESS a param carries a ^Record declared hint - ;; (:phints, name -> ctor-key) — then seed it to that record type so field - ;; reads off it bare-index per-form, not only under whole-program. This is - ;; what makes a protocol method's `this` (hinted by defrecord/extend-type) - ;; read its fields without the runtime tag guard. - ;; a nested closure resets the self/loop context: its own recur/self-call - ;; targets IT, not the enclosing whole-program def, so it must not collect - ;; into that def's param key. - (let [fenv (assoc env :self-name nil :self-key nil :self-params nil :in-loop? false)] - [:any (assoc node :arities - (mapv (fn [a] - (let [shapes (get env :record-shapes) - phm (reduce (fn [m pr] (assoc m (nth pr 0) (nth pr 1))) - {} (get a :phints)) - pe (reduce (fn [e p] - (assoc e p - (let [ent (get shapes (get phm p))] - (if ent (record-type-from-entry ent type-depth shapes) :any)))) - tenv (get a :params)) - pe (if (get a :rest) (assoc pe (get a :rest) :any) pe)] - (assoc a :body (nth (infer (get a :body) pe fenv) 1)))) - (get node :arities)))]) - (= op :def) - (do (when (get env :checking?) (register-user-fn! node env)) - [:any (assoc node :init (nth (infer (get node :init) tenv env) 1))]) - (= op :try) - [:any (assoc node - :body (nth (infer (get node :body) tenv env) 1) - :catch-body (when (get node :catch-body) (nth (infer (get node :catch-body) tenv env) 1)) - :finally (when (get node :finally) (nth (infer (get node :finally) tenv env) 1)))] - :else [:any node]))) - -(defn- infer-top [node env] (nth (infer node {} env) 1)) - -;; --------------------------------------------------------------------------- -;; Success-type checking (RFC 0006). Reuse the inference above as a loose type -;; checker: flag a core-fn call ONLY when an argument's inferred type is -;; concrete AND lies in that op's error domain (the op provably throws on it). -;; Everything ambiguous — :any, :truthy (true/char/...), :nil — is accepted, so -;; there are no false positives. The table is curated to genuinely-throwing -;; cases; lenient ops ((get 5 :k) -> nil, (:k 5) -> nil) are NOT listed. - -;; --- user-function error domains, opt-in ------------------------------------- -(defn- all-any-env - "tenv binding every param name to :any (the all-ambiguous baseline)." - [params] - (reduce (fn [e p] (assoc e p :any)) {} params)) - -(defn- isolated-diag-count - "Count of diagnostics typing body under tenv produces. Runs under a SUB-ENV - with its own diags cell, so this probe never leaks into the real report (the - shared calls/escapes/guard cells are intentionally still threaded — they are - not read here). Runs the same checking inference as check-form." - [body tenv env] - (let [sub (assoc env :diags (atom []))] - (infer body tenv sub) - (count @(get sub :diags)))) - -(defn- check-user-call - "Strict mode: report a call to a registered user fn that provably throws — - either a WRONG ARITY (the registered fn has one fixed arity, so a different - arg count always throws) or an argument whose concrete type the body - rejects. For the latter, re-check the body with ONLY that parameter bound to - its arg type (others :any); a diagnostic the all-:any body did not already - have means the argument alone is provably wrong. Monotonic — binding a - concrete type can only ADD error-domain hits — so no false positive. - Cycle-guarded (env's checking-set) so mutually recursive fns terminate." - [key sig arg-types pos env] - (let [cset (get env :checking-set)] - (when (not (contains? @cset key)) - (let [prev @cset] - (reset! cset (conj prev key)) - (let [params (:params sig) - body (:body sig) - npar (count params) - nargs (count arg-types) - memo (get env :diag-memo)] - (if (not= npar nargs) - ;; arity is provably wrong regardless of types — report and stop (the - ;; per-arg type re-check would bind params positionally, meaningless - ;; under a mismatch) - (swap! (get env :diags) conj - {:op :user-call :type :arity :pos pos - :msg (str "wrong number of args (" nargs ") passed to `" - (:name sig) "` (expected " npar ")")}) - ;; all-any-env is built once (was rebuilt per param), and each probe is - ;; memoized by [key i argtype] so the same fn re-checked across call - ;; sites in this form re-infers its body at most once per (param, type). - (let [base-env (all-any-env params) - base (let [bk [:base key]] - (if (contains? @memo bk) - (get @memo bk) - (let [b (isolated-diag-count body base-env env)] - (swap! memo assoc bk b) b)))] - (reduce - (fn [_ i] - (let [at (nth arg-types i)] - (when (and (not= at :any) (not= at :truthy)) - (let [mk [:arg key i at] - rejects (if (contains? @memo mk) - (get @memo mk) - (let [r (> (isolated-diag-count body (assoc base-env (nth params i) at) env) base)] - (swap! memo assoc mk r) r))] - (when rejects - (swap! (get env :diags) conj - {:op :user-call :argpos i :type (type-name at) :pos pos - :msg (str "argument " (inc i) " to `" (:name sig) - "` is " (type-name at) - ", which its body provably rejects")}))))) - nil) - nil (range npar))))) - (reset! cset prev))))) - -;; --- Inter-procedural driver API consumed by the back end ------------------- -(defn set-rtenv! - "Install the current return-type estimates (a map \"ns/name\" -> type) used to - type call results during the fixpoint." - [m] (swap! config-box assoc :rtenv (or m {}))) - -;; install record-ctor shapes ("ns/->Name" -> [field-kw ...]) and the -;; map-shaping flag (opt-in JOLT_SHAPE), both read by infer. -(defn set-record-shapes! [m] (swap! config-box assoc :record-shapes (or m {}))) -(defn set-protocol-methods! [m] (swap! config-box assoc :protocol-methods (or m {}))) -(defn set-map-shapes! [b] (swap! config-box assoc :map-shapes? (boolean b))) - -(defn set-vtypes! - "Install var VALUE types (a map \"ns/name\" -> type): fn vars are :truthy - (non-nil), def vars carry their inferred init type." - [m] (swap! config-box assoc :vtypes (or m {}))) - -(defn join-types - "Public structural join (lub), used by the orchestrator's fixpoint so param/ - return types join field-wise/element-wise instead of collapsing to :any." - [a b] (join-t a b)) - -(defn reset-escapes! [] (reset! escapes-box #{})) -(defn collected-escapes [] (vec @escapes-box)) - -(defn check-form - "Success-type check a single analyzed form (RFC 0006). Returns a vector of - diagnostics [{:op :argpos :type :msg} ...] for provably-wrong calls; empty - when nothing is provably wrong. Runs independently of specialization so it is - usable in normal builds (the decoupled checking path). - - With strict? true, also reports calls to registered user functions whose - concrete argument types provably make the body throw (opt-in, - closed-world). user-sig-box accumulates registered defs across forms, so a - def must precede its call — the same ordering RFC 0005 already assumes." - ([node] (check-form node false)) - ([node strict?] - ;; the check IS the inference: one walk that types and emits diagnostics into - ;; this run's env. The optimization fixpoint runs with checking? false so it - ;; stays silent. - (let [env (mk-env true strict?)] - (infer node {} env) - (vec @(get env :diags))))) - -(defn infer-body - "Type `body` under tenv (local-name -> type). Returns [ret-type node' calls], - where calls is the [[\"ns/name\" [arg-types...]] ...] this body invokes (for - propagating into callee param types). Also accumulates escapes (read with - collected-escapes after a full sweep). With self-name/self-key, a recursive - self-call or fn-level recur in `body` is collected under self-key too, so a - self-recursive fn's params are constrained by its recursion, not just callers." - ([body tenv] (infer-body body tenv nil nil nil)) - ([body tenv self-name self-key] (infer-body body tenv self-name self-key nil)) - ([body tenv self-name self-key self-params] - (let [env (assoc (mk-env false false) - :self-name self-name :self-key self-key :self-params self-params) - r (infer body tenv env)] - [(nth r 0) (nth r 1) @(get env :calls)]))) - -;; --- protocol-method return types ------------------------------------------- -;; An impl is emitted as (register-(inline-)method TAG "Proto" "method" (fn ...)). -;; Its fn body's return type is one impl's contribution to the method's return; the -;; join over every impl is the method's return type (monomorphic when all agree). -(defn- impl-reg-ret [node] - (when (= :invoke (get node :op)) - (let [f (get node :fn) args (get node :args)] - (when (and (= :var (get f :op)) - (or (= "register-inline-method" (get f :name)) - (= "register-method" (get f :name))) - (= 4 (count args))) - (let [proto (get (nth args 1) :val) - method (get (nth args 2) :val) - fnn (nth args 3)] - (when (and (string? proto) (string? method) - (= :fn (get fnn :op)) (seq (get fnn :arities))) - [(str proto "/" method) - (nth (infer-body (get (first (get fnn :arities)) :body) {}) 0)])))))) - -(defn- walk-pm-rets [node acc] - (let [kr (impl-reg-ret node) - acc (if kr (update acc (nth kr 0) (fn [t] (if t (join t (nth kr 1)) (nth kr 1)))) acc)] - (reduce-ir-children (fn [a c] (walk-pm-rets c a)) acc node))) - -(defn collect-pm-rets! - "Scan the unit's nodes for protocol-method impl registrations and stash each - method's joined impl-return type (record-shapes must already be installed)." - [nodes] - (reset! pm-rets-box (reduce (fn [acc n] (walk-pm-rets n acc)) {} nodes))) - -(defn reinfer-def - "Re-run inference on a stashed :def's fn arity bodies with param types seeded - (ptmap: param-name -> type), returning the def with annotated bodies. The back - end emits the result directly (no further passes), so the param-typed lookups - keep their specialization. Used by the inter-procedural recompile." - [def-node ptmap] - (let [fnode (get def-node :init) - env (mk-env false false) - shapes (get env :record-shapes)] - (if (= :fn (get fnode :op)) - (assoc def-node :init - (assoc fnode :arities - (mapv (fn [a] - ;; seed declared record param hints (:phints, name -> - ;; ctor-key) so a record param is typed even with no - ;; inferred caller type — the open-world / cross-ns - ;; case. An inferred type in ptmap wins (it's at least - ;; as precise), so this only fills the gaps. - (let [pt (reduce (fn [m pr] - (let [nm (nth pr 0) - e (get shapes (nth pr 1))] - (if (and e (not (contains? m nm))) - (assoc m nm (record-type-from-entry e type-depth shapes)) - m))) - ptmap (get a :phints))] - (assoc a :body (nth (infer (get a :body) pt env) 1)))) - (get fnode :arities)))) - def-node))) - -(defn phint-seed - "Positional declared-hint type seeds for a fn arity. Given the param-name - vector and the arity's :phints (a seq of [name ctor-key] pairs), return a - vector parallel to params whose slot i is the resolved record TYPE of that - param's ^Record hint (via the record-shapes registry), or nil. The - whole-program fixpoint seeds these as a param-type FLOOR so a declared hint - propagates to a fn's callees DURING inference — not only at the final re-emit - (reinfer-def). Without it a hinted param with no callers stays :any through the - fixpoint, so a field read off it (e.g. (:origin ^Ray r)) never tells a shared - callee its arg is a Vec3." - [params phints] - (let [shapes (get @config-box :record-shapes) - m (reduce (fn [acc pr] (assoc acc (nth pr 0) (nth pr 1))) {} phints)] - (mapv (fn [nm] - (let [ck (get m nm) - e (and ck (get shapes ck))] - (when e (record-type-from-entry e type-depth shapes)))) - params))) - -;; --- whole-program param-type fixpoint -------------------------------------- -;; Re-derive each app fn's param types from its call sites under closed world -;; (--opt), so a record type flows across fn boundaries: a ctor's return type -;; reaches a callee param ((check-tree (make-tree d)) -> node is a Node), and a -;; typed vector's element reaches a HOF closure's param (sum-area's reduce sees a -;; Circle). The back end then bare-indexes a field read and devirtualizes a -;; protocol call at those sites. Only single-fixed-arity fns are specialized; -;; anything called in value position (collected-escapes) keeps :any params — -;; its callers aren't all visible, so a concrete seed would be unsound. -(def ^:private wp-seeds-box (atom {})) -(defn param-seeds-for - "The param-name -> type seed map a top-level def should be reinferred with, or - nil. Set by wp-infer!, read by run-passes during the final per-def emit." - [k] (get @wp-seeds-box k)) - -;; numeric refinement of the same fixpoint: params the closed-world join proved -;; are always flonums. Kept SEPARATE from the structural box — these don't reinfer -;; (field-read/devirt), they become synthetic ^double nhints (jolt.passes/inject- -;; wp-nhints) so the hint-directed pass unboxes the arithmetic. -(def ^:private wp-num-seeds-box (atom {})) -(defn param-num-seeds-for - "The param-name -> :double seed map for a def's hintless flonum params, or nil." - [k] (get @wp-num-seeds-box k)) - -;; var-key -> {:params [names] :body ir} for each single-fixed-arity fn def. -(defn- wp-specializable [nodes] - (reduce (fn [m d] - (let [f (get d :init)] - (if (and (= :def (get d :op)) (= :fn (get f :op)) - (= 1 (count (get f :arities))) - (not (get (first (get f :arities)) :rest))) - (let [a (first (get f :arities))] - (assoc m (str (get d :ns) "/" (get d :name)) - {:name (get d :name) :params (get a :params) :body (get a :body)})) - m))) - {} nodes)) - -(defn- wp-empty-ptypes [spec ks] - (reduce (fn [m k] (assoc m k (vec (repeat (count (:params (get spec k))) nil)))) {} ks)) - -;; join one call's arg types into its (specializable) callee's param slots. -(defn- wp-accum [pt spec calls] - (reduce (fn [pt2 c] - (let [callee (nth c 0) args (nth c 1)] - (if (contains? spec callee) - (let [cur (get pt2 callee)] - (assoc pt2 callee - (vec (map-indexed - (fn [i t] (if (< i (count args)) (join t (nth args i)) t)) cur)))) - pt2))) - pt calls)) - -;; one fixpoint pass over every top-level node: a specializable def is typed -;; under the current param seeds (so a seeded record flows into the calls it -;; makes) and contributes its return type; any other form is typed only to -;; harvest its call sites and escapes. Returns {:rets :ptypes}, with ptypes -;; recomputed fresh each pass — :any is absorbing, so accumulating across passes -;; would pin a param at :any before its callers' return types are known. -(defn- wp-pass [nodes spec ks ptypes] - (reduce - (fn [acc node] - (let [k (when (= :def (get node :op)) (str (get node :ns) "/" (get node :name))) - s (and k (get spec k))] - (if s - (let [r (infer-body (:body s) (zipmap (:params s) (get ptypes k)) (:name s) k (:params s))] - (-> acc (assoc-in [:rets k] (nth r 0)) - (update :ptypes wp-accum spec (nth r 2)))) - (update acc :ptypes wp-accum spec (nth (infer-body node {}) 2))))) - {:rets {} :ptypes (wp-empty-ptypes spec ks)} nodes)) - -(defn wp-infer! - "Run the closed-world param-type fixpoint over the unit's analyzed top-level - nodes and stash the resulting per-def seed maps (read via param-seeds-for). - record-shapes / protocol-methods must already be installed. Idempotent — resets - the seed box; called once per build before per-form emit." - [nodes] - (collect-pm-rets! nodes) - (let [spec (wp-specializable nodes) - ks (keys spec)] - (loop [iter 0 ptypes (wp-empty-ptypes spec ks) rets {}] - (set-rtenv! (reduce (fn [m k] (let [v (get rets k)] (if (some? v) (assoc m k v) m))) {} ks)) - (reset-escapes!) - (let [pass (wp-pass nodes spec ks ptypes) - escaped (set (collected-escapes)) - ;; a fn used in value position has callers we can't see -> :any params - new-ptypes (reduce (fn [m k] - (if (contains? escaped k) - (assoc m k (vec (repeat (count (get m k)) :any))) m)) - (:ptypes pass) ks) - new-rets (:rets pass) - converged? (and (= new-ptypes ptypes) (= new-rets rets))] - (if (or converged? (>= iter 16)) - ;; On convergence new-ptypes is the least fixpoint (sound). On hitting the - ;; cap without convergence it's a pre-fixpoint — more specific than the - ;; fixpoint, so seeding it would be unsound; widen every param to :any - ;; (emit no seeds). The cap isn't reached in practice (~2 passes), this is - ;; a defensive floor. - (let [seed-ptypes (if converged? - new-ptypes - (reduce (fn [m k] (assoc m k (vec (repeat (count (get m k)) :any)))) - new-ptypes ks)) - ;; build both seed maps from the same converged ptypes: the - ;; structural one (struct/vec, drives reinfer-def's field-read/ - ;; devirt) excludes :double; the numeric one keeps only :double. - pick (fn [keep?] - (reduce (fn [m k] - (let [s (get spec k) - pm (reduce (fn [pm pr] - (let [nm (nth pr 0) t (nth pr 1)] - (if (and t (keep? t)) (assoc pm nm t) pm))) - {} (map vector (:params s) (get seed-ptypes k)))] - (if (seq pm) (assoc m k pm) m))) - {} ks))] - (reset! wp-seeds-box (pick (fn [t] (and (not= t :any) (not= t :double))))) - (reset! wp-num-seeds-box (pick (fn [t] (= t :double))))) - (recur (inc iter) new-ptypes new-rets)))))) - -;; Piggyback checking (jolt audit). In direct-link mode infer-top already runs -;; one inference pass for specialization; turning checking? on during it makes -;; the success checker nearly free there (no extra traversal — just the -;; per-call error-domain predicates). The back end sets the mode before -;; run-passes and reads take-diags! after. It checks the POST-optimization IR, -;; which matches what the optimized program actually evaluates (scalar-replace -;; only drops provably-pure code, an accepted opt-mode divergence). -(defn set-check-mode! - "Enable/disable checking during the next run-passes inference (direct-link)." - [on strict?] (reset! check-mode-box {:on (if on true false) :strict (if strict? true false)})) -(defn take-diags! - "Diagnostics accumulated by the last checking run-passes; clears the buffer." - [] (let [d @last-diags-box] (reset! last-diags-box []) d)) - -(defn run-inference - "Type-infer the optimized node (the inference walk specializes struct-safe - lookups). When check mode is on (set-check-mode!), the same walk also emits - success-type diagnostics, stashed for take-diags! to drain afterward. Pulled - out of run-passes so the checking state stays private to this namespace." - [opt] - (if (get @check-mode-box :on) - (let [env (mk-env true (get @check-mode-box :strict)) - r (infer-top opt env)] - (reset! last-diags-box @(get env :diags)) - r) - (infer-top opt (mk-env false false)))) diff --git a/jolt-core/jolt/passes/types/check.clj b/jolt-core/jolt/passes/types/check.clj deleted file mode 100644 index a6355d5..0000000 --- a/jolt-core/jolt/passes/types/check.clj +++ /dev/null @@ -1,102 +0,0 @@ -(ns jolt.passes.types.check - "Success-type error domains (RFC 0006): the curated tables of which concrete - types each core op provably throws on, the diagnostic emitter, and the user-fn - signature registry. Pure over inferred types plus the run's `env` cells — no - inference — so the inferencer (jolt.passes.types) and these rules can't perturb - each other. The inferencer calls these during its walk; the infer-coupled user - call probes (re-inference) stay in the inferencer." - (:require [jolt.passes.types.lattice :refer - [union-type? umembers struct-type? vec-type? set-type?]])) - -;; concrete non-numbers: arithmetic provably throws on these. A union is in the -;; error domain only when EVERY member is — if any member is an -;; accepted type the call is accepted (no false positive). -(defn- not-number? [t] - (if (union-type? t) - (every? not-number? (umembers t)) - (or (= t :str) (= t :kw) (= t :phm) - (struct-type? t) (vec-type? t) (set-type? t)))) - -;; concrete non-seqable scalars: seq/count/first/nth provably throw on these. -;; (Strings and collections ARE seqable/countable; :truthy is ambiguous; :nil -;; and :any are accepted.) A union throws only when every member does. -(defn- not-seqable? [t] - (if (union-type? t) - (every? not-seqable? (umembers t)) - (or (= t :num) (= t :kw)))) - -;; concrete non-callable values: calling them throws "Cannot call X -;; as a function". Only :num and :str — keywords/maps/vectors/sets are IFn, -;; :truthy/:any/:nil are ambiguous (accepted). A union is non-callable only when -;; every member is. -(defn not-callable? [t] - (if (union-type? t) - (every? not-callable? (umembers t)) - (or (= t :num) (= t :str)))) - -;; arithmetic / numeric ops: EVERY argument must be a number. -(def ^:private num-ops - #{"+" "-" "*" "/" "inc" "dec" "mod" "rem" "quot" "min" "max" "abs" - "bit-and" "bit-or" "bit-xor" "bit-not" "bit-shift-left" "bit-shift-right"}) -;; seq/count/index ops: argument 0 must be seqable/countable. -(def ^:private seq-ops #{"count" "first" "rest" "next" "seq" "nth"}) - -(defn type-name - "Render an inferred type for an error message." - [t] - (cond (union-type? t) - (reduce (fn [s m] (if (= s "") (type-name m) (str s " or " (type-name m)))) - "" (umembers t)) - (struct-type? t) "a map" - (vec-type? t) "a vector" - (set-type? t) "a set" - (= t :str) "a string" - (= t :kw) "a keyword" - (= t :num) "a number" - (= t :phm) "a map" - :else (str t))) - -(defn check-invoke - "If node is a core-op call whose argument type is provably in the error domain, - conj a diagnostic into env's diags cell. arg-types is the vector of inferred - argument types; pos is the call form's source offset, carried into each - diagnostic." - [cn args arg-types pos env] - (cond - (contains? num-ops cn) - (reduce (fn [_ i] - (let [t (nth arg-types i)] - (when (not-number? t) - (swap! (get env :diags) conj - {:op cn :argpos i :type (type-name t) :pos pos - :msg (str "`" cn "` requires a number, but argument " - (inc i) " is " (type-name t))}))) - nil) - nil (range (count args))) - (and (contains? seq-ops cn) (> (count args) 0)) - (let [t (nth arg-types 0)] - (when (not-seqable? t) - (swap! (get env :diags) conj - {:op cn :argpos 0 :type (type-name t) :pos pos - :msg (str "`" cn "` requires " - (if (= cn "count") "a countable collection" "a seqable") - ", but argument 1 is " (type-name t))}))) - :else nil)) - -(defn register-user-fn! - "Record a (def name (fn [params] body)) — single fixed arity, not redefinable — - for later user-fn call checking. Redefinable/dynamic and multi/variadic fns are - skipped (their body is not a stable requirement)." - [node env] - (let [init (get node :init) - m (get node :meta) - redefable (and m (or (get m :redef) (get m :dynamic)))] - (when (and (not redefable) (= :fn (get init :op))) - (let [arities (get init :arities)] - (when (= 1 (count arities)) - (let [ar (first arities)] - (when (not (get ar :rest)) - (swap! (get env :user-sigs) assoc - (str (get node :ns) "/" (get node :name)) - {:name (get node :name) - :params (get ar :params) :body (get ar :body)})))))))) diff --git a/jolt-core/jolt/passes/types/lattice.clj b/jolt-core/jolt/passes/types/lattice.clj deleted file mode 100644 index 29cd422..0000000 --- a/jolt-core/jolt/passes/types/lattice.clj +++ /dev/null @@ -1,182 +0,0 @@ -(ns jolt.passes.types.lattice - "Structural type lattice for jolt.passes.types: scalar/struct/vec/set/union - types, join, depth-cap, shape, and the numeric/vector return-fn name sets. Pure - (no inference state) — the inference + checker in jolt.passes.types build on it.") - -;; --------------------------------------------------------------------------- -;; Collection-type inference, intra-procedural. A forward, -;; soft-typing-style pass (simplified HM: monovariant, never-fails, lattice top -;; = :any) that types expressions from literals/arithmetic and flows the type -;; through let bindings and if-joins. Where a keyword-lookup subject is PROVEN a -;; plain struct map it sets :hint :struct (the same channel a manual hint uses, -;; so the back end drops the guard); where the type is :any it leaves the -;; dynamic guard in place. Sound by construction: a concrete type is assigned -;; only when proven, so a wrong bare get is impossible. -;; -;; Recursive STRUCTURAL types (RFC 0005). A type mirrors the data tree: -;; compound: {:struct {field -> T}} (raw-get-safe map, field types) -;; {:vec T} (vector of T) -;; {:set T} (set of T) -;; scalar: :num :str :kw :truthy (all provably non-nil/non-false) -;; :phm (persistent hash map; NOT raw-get-safe) -;; :any (top), nil (bottom, identity for join). -;; Compound types are small jolt maps, so they compare by value on both the -;; Clojure and the host (orchestrator) side. struct/vec/set use distinct keys so -;; a type is recognised by which key it carries. -;; (get t :KEY) is nil for a keyword type and the child for a compound, so a -;; compound is detected by some? — no map?/contains? needed. -(defn velem [t] (get t :vec)) -(defn selem [t] (get t :set)) -(defn sfields [t] (get t :struct)) -(defn vec-type? [t] (some? (velem t))) -(defn set-type? [t] (some? (selem t))) -(defn struct-type? [t] (some? (sfields t))) -(defn mk-vec [t] {:vec (if t t :any)}) -(defn mk-set [t] {:set (if t t :any)}) -(defn mk-struct [fs] {:struct fs}) - -;; Bounded union types (RFC 0006). A union {:union #{T...}} records -;; that a value is provably one of a small, fixed set of SCALAR types — what -;; differing if-branches used to collapse to :any. It exists so the success -;; checker can reject a use where EVERY member is in the op's error domain -;; ((inc (if c "a" :k))) while still accepting one where any member is valid -;; ((inc (if c 1 "x"))). Scalars only, capped cardinality: the member space is -;; the five scalar tags, so the lattice stays finite and the inter-procedural -;; fixpoint terminates. A union is opaque to every STRUCTURAL predicate -;; (struct-type?/vec-type?/set-type? key on :struct/:vec/:set, which a union -;; lacks), so specialization treats it exactly like :any — codegen is -;; unchanged; only the checker reads inside it. -(def union-cap 4) -(defn scalar-t? [t] (or (= t :num) (= t :str) (= t :kw) (= t :truthy) (= t :phm))) -(defn union-type? [t] (some? (get t :union))) -(defn umembers [t] (get t :union)) -(defn union-of - "Normalize a seq of member types into a lattice value: flatten nested unions, - keep only scalars (any non-scalar member collapses the whole thing to :any, - the conservative top), then return the lone member if one, {:union #{...}} - for 2..cap distinct scalars, or :any past the cap." - [ts] - (let [flat (reduce (fn [acc t] - (if (union-type? t) - (reduce conj acc (umembers t)) - (conj acc t))) - #{} ts)] - (cond - (not (every? scalar-t? flat)) :any - (= 0 (count flat)) :any - (= 1 (count flat)) (first flat) - (> (count flat) union-cap) :any - :else {:union flat}))) - -(declare join-t) -(defn merge-fields - "Per-field join of two field maps (a key in only one side joins with :any)." - [fa fb] - (let [m1 (reduce (fn [m k] (assoc m k (join-t (get fa k :any) (get fb k :any)))) {} (keys fa))] - (reduce (fn [m k] (if (get m k) m (assoc m k (join-t (get fa k :any) (get fb k :any))))) m1 (keys fb)))) -(defn join-t [a b] - (cond - (= a b) a - (nil? a) b - (nil? b) a - ;; :nil is the type of a literal nil. With a struct it forms a NILABLE struct — - ;; field reads still bare-index (jrec-field-at falls back to jolt-get on nil), but - ;; some?/nil? won't fold and a guard narrows it back to non-nil. With anything - ;; else it widens to :any (nil is not a safe scalar/vec — no fl/fx, no bare elem). - (or (= a :nil) (= b :nil)) - (let [o (if (= a :nil) b a)] - (cond (= o :nil) :nil - (struct-type? o) (assoc o :nilable true) - :else :any)) - ;; :double is a flonum refinement of :num: two doubles stay :double (caught by - ;; = above), but a double joined with anything else loses the flonum guarantee - ;; and widens to :num before joining — so a param is :double only when EVERY - ;; contributing value is a flonum, which is what makes the hintless fl-op sound. - (or (= a :double) (= b :double)) - (join-t (if (= a :double) :num a) (if (= b :double) :num b)) - (and (struct-type? a) (struct-type? b)) - (let [merged (mk-struct (merge-fields (sfields a) (sfields b))) - ;; joining two values of the SAME complete shape / record type preserves - ;; it — the merged struct has the same key set. Different shapes/types - ;; (or an incomplete side) drop it, as the layout is no longer proven. - merged (if (and (get a :shape) (= (get a :shape) (get b :shape))) - (assoc merged :shape (get a :shape)) merged) - merged (if (and (get a :type) (= (get a :type) (get b :type))) - (assoc merged :type (get a :type)) merged) - ;; nilability is contagious: a nilable side makes the join nilable. - merged (if (or (get a :nilable) (get b :nilable)) - (assoc merged :nilable true) merged)] - merged) - (and (vec-type? a) (vec-type? b)) (mk-vec (join-t (velem a) (velem b))) - (and (set-type? a) (set-type? b)) (mk-set (join-t (selem a) (selem b))) - ;; differing kinds: form a scalar union when both sides reduce to scalars - ;; (or scalar unions); anything compound on either side stays :any - :else (let [ma (cond (union-type? a) (umembers a) (scalar-t? a) #{a} :else nil) - mb (cond (union-type? b) (umembers b) (scalar-t? b) #{b} :else nil)] - (if (and ma mb) (union-of (reduce conj ma mb)) :any)))) -(defn join [a b] (join-t a b)) -;; depth cap (RFC 0005): truncate a type below depth d to :any, so recursive data -;; can't make an infinite type and the inter-procedural fixpoint stays finite. -(def type-depth 4) -(defn cap [t d] - (cond - (<= d 0) (if (or (struct-type? t) (vec-type? t) (set-type? t)) :any t) - (struct-type? t) - ;; capping truncates VALUES below depth d, but the KEY SET is unchanged, so - ;; a complete :shape survives — keep it so nested/container field reads can - ;; still bare-index. cap recurses into fields, so a nested - ;; shaped value (a vec3 inside a hit-info) keeps its own :shape too. - (let [capped (mk-struct (reduce (fn [m k] (assoc m k (cap (get (sfields t) k) (dec d)))) - {} (keys (sfields t)))) - ;; the record :type tag (and :shape) are independent of field-value - ;; depth, so they survive truncation — a record read from a deep - ;; container keeps its identity, so devirtualization, record? folding, - ;; and the record fast path still fire on it. - capped (if (get t :shape) (assoc capped :shape (get t :shape)) capped) - capped (if (get t :type) (assoc capped :type (get t :type)) capped)] - capped) - (vec-type? t) (mk-vec (cap (velem t) (dec d))) - (set-type? t) (mk-set (cap (selem t) (dec d))) - :else t)) -;; raw-get-safe (a struct / record): a struct type. The field type of key -;; k, if known, else :any. -(defn struct-safe? [t] (struct-type? t)) -;; a nilable struct yields :any for every field (the whole value might be nil, so a -;; field read can be nil) — conservative + sound. A guard narrows it to non-nil first -;; (strip-nilable), after which the real field types flow. -(defn field-type [t k] (if (and (struct-type? t) (not (get t :nilable))) (get (sfields t) k :any) :any)) -(defn nilable? [t] (and (map? t) (get t :nilable) true)) -(defn strip-nilable [t] (if (and (map? t) (get t :nilable)) (dissoc t :nilable) t)) -;; Shape (hidden class). A struct type built from a map LITERAL carries -;; its complete layout — :shape, the canonical (str-sorted) key vector. The back -;; end represents such a map as a shape tuple and reads a field by bare index. -;; A struct type from a JOIN or from field-access inference has no :shape -;; (incomplete: the full key set isn't proven), so it keeps the dynamic path — -;; never a bare index. No shape is hardcoded; any constant key set is one. -(defn shape-order - "Canonical key order for a shape: keys sorted by their string form, so two - literals with the same keys in any order intern to the same shape." - [ks] (vec (sort (fn [a b] (compare (str a) (str b))) ks))) -(defn type-shape [t] (get t :shape)) -;; tag a node (any expression, not just a :local) so the back end can specialize -;; a lookup whose SUBJECT is that node — this is what makes nested access work: -;; (:direction ray) is tagged struct, so (:r (:direction ray)) drops its guard. -;; tag a lookup subject as a struct, carrying the complete shape when known -;; (so the back end bare-indexes). -(defn mark-struct [node t] - (let [n (assoc node :hint :struct)] - (if (get t :shape) (assoc n :shape (get t :shape)) n))) -;; a value provably neither nil nor false — the back end only builds a struct -;; (vs a phm) when every value is non-nil/non-false, so a map literal is a struct -;; only when all its values have such a type. Collections are non-nil. -(defn truthy-type? [t] - (or (= t :num) (= t :double) (= t :str) (= t :kw) (= t :truthy) (= t :phm) - (and (struct-type? t) (not (get t :nilable))) ; a nilable struct may be nil - (vec-type? t) (set-type? t))) - -;; core fns whose result is a number (so it is non-nil/non-false and, for the -;; success-type checker, provably numeric). -(def num-ret-fns - #{"+" "-" "*" "/" "inc" "dec" "mod" "rem" "quot" "min" "max" "abs" - "bit-and" "bit-or" "bit-xor" "count"}) -(def vector-ret-fns #{"vec" "vector" "mapv" "filterv" "subvec"}) diff --git a/project.janet b/project.janet new file mode 100644 index 0000000..d6d9ddd --- /dev/null +++ b/project.janet @@ -0,0 +1,16 @@ +(declare-project + :name "jolt" + :description "Clojure interpreter on Janet") + +(declare-source + :source @["src"]) + +(declare-executable + :name "jolt" + :entry "src/jolt/main.janet") + +# Separate tool (like jpm beside janet): resolves deps.edn into Jolt source +# roots. The jolt runtime stays deps-agnostic — it just reads JOLT_PATH. +(declare-executable + :name "jolt-deps" + :entry "src/jolt/deps_cli.janet") diff --git a/src/jolt/aot.janet b/src/jolt/aot.janet new file mode 100644 index 0000000..0626a2e --- /dev/null +++ b/src/jolt/aot.janet @@ -0,0 +1,47 @@ +# Ahead-of-time images for compiled namespaces. +# +# Compile-by-default turns each form into Janet bytecode at load time. AOT skips +# that work on subsequent runs by serializing a namespace's compiled vars to a +# bytecode image and loading them back. +# +# The trick is the marshal dictionary. A compiled jolt function closes over core +# fns (core-map, +, …) and var cells; those core fns are Janet cfunctions/closures +# that can't be marshaled by value. But the runtime env that holds them is baked +# into the binary and is byte-for-byte identical at save and load time, so we +# marshal *against* it: core fns are referenced by name, and only the user's +# bytecode plus its var cells are actually serialized. + +(use ./compiler) # jolt-runtime-env +(use ./types) + +# Forward dict (key -> value) for unmarshal; reverse (value -> key) for marshal. +# Built from the runtime env, which chains to the Janet boot env, so both core fns +# and Janet builtins resolve by name. +(defn- fwd-dict [] (env-lookup jolt-runtime-env)) +(defn- rev-dict [] (invert (env-lookup jolt-runtime-env))) + +(defn marshal-ns + "Marshal namespace `ns-name`'s var mappings to a byte buffer. The whole mappings + table is marshaled in one call so var cells shared between defs stay shared." + [ctx ns-name] + (marshal ((ctx-find-ns ctx ns-name) :mappings) (rev-dict))) + +(defn unmarshal-ns! + "Install mappings produced by marshal-ns into `ns-name` in ctx, overwriting + same-named vars. Returns ns-name." + [ctx ns-name bytes] + (let [mappings (unmarshal bytes (fwd-dict)) + ns (ctx-find-ns ctx ns-name)] + (each [sym v] (pairs mappings) (put (ns :mappings) sym v)) + ns-name)) + +(defn save-ns + "Write an AOT image of compiled namespace `ns-name` to `path`." + [ctx ns-name path] + (spit path (marshal-ns ctx ns-name))) + +(defn load-ns-image + "Read an AOT image written by save-ns back into ctx under `ns-name`. Skips + parse/analyze/emit/compile entirely — the bytecode is already built." + [ctx ns-name path] + (unmarshal-ns! ctx ns-name (slurp path))) diff --git a/src/jolt/api.janet b/src/jolt/api.janet new file mode 100644 index 0000000..dc2cfc9 --- /dev/null +++ b/src/jolt/api.janet @@ -0,0 +1,226 @@ +# Jolt Public API +# High-level interface for the Clojure-on-Janet interpreter. + +(use ./types) +(use ./pv) +(use ./plist) +(use ./reader) +(use ./evaluator) +(use ./core) +(use ./compiler) +(use ./loader) +(use ./async) +(import ./backend :as backend) +(import ./stdlib_embed :as stdlib-embed) +(import ./host_iface :as host) + +# A defmacro expander compiles to a native fn (built as (fn args body...) and run +# through the self-hosted pipeline) so macro expansion is COMPILED code, zero runtime +# cost — instead of an interpreted closure, mirroring Clojure (macros are ordinary +# compiled fns). Wrapped in the `fn` MACRO (not the `fn*` primitive) so a destructured +# macro arglist — `[a & [b]]`, `[& {:keys [x]}]`, nested — desugars before lowering; +# raw fn* punts on a destructuring rest param. Returns nil when the analyzer isn't +# built yet (the early macros, expanded WHILE the analyzer is being bootstrapped) or +# the body isn't compilable; in that case defmacro keeps an interpreted closure, and +# backend/recompile-macros! replaces it with a compiled expander once the analyzer +# comes alive (staged bootstrap — the interpreter is a build-time crutch, gone by +# steady state). +(set macro-compile-hook + (fn [ctx args-form body] + (backend/try-compile-fn ctx + (array/concat @[{:jolt/type :symbol :ns nil :name "fn"} args-form] body)))) + +(defn normalize-pvecs + "Deep-convert any sequential (pvec/tuple/array) to a Janet tuple. Test helper + so Janet-level `=`/deep= can compare jolt collection results against Janet + tuple literals regardless of representation — mirroring Clojure, where vectors + and lists with the same elements are equal." + [x] + (cond + # lazy-seq: realize to a tuple (map/filter/take now return lazy seqs). + (and (table? x) (= (get x :jolt/type) :jolt/lazy-seq)) + (tuple ;(map normalize-pvecs (realize-for-iteration x))) + (pvec? x) (tuple ;(map normalize-pvecs (pv->array x))) + (plist? x) (tuple ;(map normalize-pvecs (pl->array x))) + (tuple? x) (tuple ;(map normalize-pvecs x)) + (array? x) (tuple ;(map normalize-pvecs x)) + x)) + + +# Ordered clojure.core tiers (embedded jolt-core/clojure/core/NN-*.clj). Each tier +# may reference only the Janet seed + earlier tiers. A :kernel tier holds the +# structural fns the self-hosted compiler itself uses (second/peek/subvec/mapv/ +# update); in compile mode it must be bootstrap-compiled into clojure.core BEFORE +# the analyzer is built (the analyzer depends on it), so it bypasses the +# self-hosted pipeline. Non-kernel tiers route through eval-toplevel like any +# source (compiled when :compile?, interpreted otherwise — the analyzer, built +# lazily on the first such form, sees the kernel tier already in place). +(def- core-tiers + [{:ns "clojure.core.00-syntax" :kernel false} + {:ns "clojure.core.00-kernel" :kernel true} + {:ns "clojure.core.10-seq" :kernel false} + {:ns "clojure.core.20-coll" :kernel false} + {:ns "clojure.core.30-macros" :kernel false} + {:ns "clojure.core.40-lazy" :kernel false}]) + +(defn- eval-overlay-source [ctx src] + (var s src) + (while (> (length (string/trim s)) 0) + (def [form rest] (parse-next s)) + (set s rest) + (when (not (nil? form)) (eval-toplevel ctx form)))) + +(defn- load-core-overlay! + "Load the Clojure portion of clojure.core in dependency-ordered tiers. See + core-tiers and jolt-core/clojure/core/." + [ctx] + (def env (ctx :env)) + (def compile? (get env :compile?)) + # Core compiles with direct-linking on when :aot-core? (so core->core calls + # are direct). The flag is restored to the user-code default afterward, so + # user/REPL code stays indirect and fully redefinable. + (def user-dl (get env :direct-linking?)) + (def core-dl (get env :aot-core?)) + (def saved (ctx-current-ns ctx)) + (ctx-set-current-ns ctx "clojure.core") + # Gate the analyzer build until the kernel tier loads (see ensure-analyzer): + # present-and-false here means pre-kernel compiles fall back to the interpreter. + (put env :kernel-ready? false) + (each tier core-tiers + (when-let [src (get stdlib-embed/sources (tier :ns))] + (put env :direct-linking? core-dl) + (if (and compile? (tier :kernel)) + (backend/bootstrap-load-source ctx "clojure.core" src) + (eval-overlay-source ctx src)) + # The self-hosted compiler depends on the kernel tier (second/peek/mapv/...). + # Mark it ready once that tier is in place so the analyzer can be built; a + # pre-kernel tier that triggers a compile (e.g. a defn in 00-syntax) instead + # falls back to the interpreter rather than building the analyzer against a + # half-loaded core (which would forward-ref the missing kernel fns to nil). + (when (tier :kernel) (put env :kernel-ready? true)))) + (put env :direct-linking? user-dl) + (ctx-set-current-ns ctx saved) + # Staged bootstrap: the early macros (00-syntax) were defined while the analyzer + # was still being built, so their expanders are interpreted closures. Now that the + # full overlay + analyzer are in place, recompile those expanders to native code — + # by steady state no macro expansion runs interpreted (no-op in interpreter mode). + (backend/ensure-macros-compiled! ctx)) + +(defn init + "Create a new Jolt evaluation context. + opts may contain: + :namespaces — map of {ns-name → {sym → value, ...}, ...} + :mutable? — use Janet mutable data structures instead of persistent + :compile? — compile Clojure forms via the self-hosted pipeline (analyzer -> + IR -> Janet back end), falling back to the interpreter as needed + :paths — extra source roots to search for namespaces (after the stdlib)" + [&opt opts] + (default opts {}) + (let [ctx (make-ctx opts)] + # The .clj stdlib (clojure.string, jolt.http, …) baked into the image at build + # time, so it loads from any directory; the loader falls back to this when a + # namespace isn't found on disk. (See stdlib-embed.) + (put (ctx :env) :embedded-sources stdlib-embed/sources) + # Extra source roots: opts :paths, then JOLT_PATH (colon-separated). These are + # searched after the stdlib so (require ...) finds deps.edn-resolved libs. + (let [roots (get (ctx :env) :source-paths)] + (each p (get opts :paths []) (array/push roots p)) + (when-let [jp (os/getenv "JOLT_PATH")] + (each p (string/split ":" jp) (when (> (length p) 0) (array/push roots p))))) + # Collection representation (persistent vs mutable) is selected at BUILD time + # via JOLT_MUTABLE (see config.janet); init-core! registers vec/vector/conj/ + # etc. that produce the mode-appropriate values, so nothing extra to load. + (init-core! ctx) + # clojure.core.async (channels + go blocks on Janet fibers); pre-populated + # so (require '[clojure.core.async ...]) finds it and applies :as/:refer. + (install-async! ctx) + # Host contract (ns jolt.host): the seam the portable jolt-core compiler calls. + (host/install! ctx) + # Stateful primitives as ctx-capturing clojure.core fns (protocol-dispatch, + # register-method, …) — so the protocol macros compile to plain invokes. Must + # precede the overlay (its defprotocol/extend-type expansions call these). + (install-stateful-fns! ctx) + # Clojure portion of clojure.core (jolt-core/clojure/core.clj): fns expressed + # in plain Clojure on top of the Janet primitives interned above. Loaded into + # clojure.core and compiled by the self-hosted pipeline (or interpreted when + # :compile? is off). Phase 4 kernel-shrink seam — see that file. + (load-core-overlay! ctx) + ctx)) + +# --- Context snapshot/fork (cheap isolated copies) -------------------------- +# +# init is expensive (~50 ms interpreted, ~900 ms compiled: tier loading, analyzer +# build, macro recompilation). For workloads that need MANY isolated contexts — +# the test harnesses build a fresh ctx per case — snapshot a fully-built ctx once +# and fork cheap deep copies (~2 ms) from it via Janet marshal/unmarshal. A fork +# shares nothing mutable with the original: defs, protocol extensions, hierarchy +# changes, atom states in one fork are invisible to the others. +# +# The reverse-lookup dicts must be built from root-env (cfunctions and abstract +# values from the Janet runtime marshal by reference through them) BEFORE any ctx +# values exist in scope — module load time here, so user code can't leak into it. +(def- image-load-dict (env-lookup root-env)) +(def- image-make-dict (invert image-load-dict)) + +(defn snapshot + "Marshal a fully-built context into a buffer that fork can cheaply clone. + Build the ctx (init), customize it if needed, then snapshot once." + [ctx] + (marshal ctx image-make-dict)) + +(defn fork + "A fresh, fully-isolated deep copy of a snapshotted context (~2 ms, vs + re-running init). (fork (snapshot ctx)) behaves exactly like ctx did at + snapshot time; mutations to a fork never affect the original or other forks." + [snap] + (unmarshal snap image-load-dict)) + +(defn eval-one + "Evaluate a single already-parsed form. Routing (compile when :compile? is set, + stateful forms interpret, interpreter fallback for forms the compiler can't + handle) lives in loader/eval-toplevel so load-ns and eval-one stay in sync." + [ctx form] + (eval-toplevel ctx form)) + +(defn eval-string + "Evaluate a Clojure source string in a Jolt context. + When :compile? is enabled, compiles to Janet and evaluates. + Macros are expanded at compile time. + Context-modifying forms (ns, defmacro, deftype, require, in-ns, defmulti, defmethod) + always use the interpreter." + [ctx s] + (eval-one ctx (parse-string s))) + +(defn eval-string* + "Evaluate a Clojure source string with explicit bindings." + [ctx s bindings] + (let [form (parse-string s)] + (eval-form ctx bindings form))) + +(defn load-string + "Evaluate all forms from a Clojure source string. + Uses parse-next to load every top-level form in sequence. + Returns the result of the last form evaluated." + [ctx s] + (var cur s) + (var result nil) + (while (> (length (string/trim cur)) 0) + (def [form rest] (parse-next cur)) + (set cur rest) + (when (not (nil? form)) + (set result (eval-one ctx form)))) + result) + +(defn compile-string + "Compile a Clojure source string to Janet source. + Returns the Janet source string." + [s] + (let [form (parse-string s)] + (compile-form form))) + +(defn compile-file + "Compile a .clj file to Janet source and optionally eval it. + When ctx has :compile? enabled, also evaluates the compiled forms. + Returns the namespace name." + [ctx filepath] + (load-ns ctx filepath)) diff --git a/src/jolt/async.janet b/src/jolt/async.janet new file mode 100644 index 0000000..8f9c385 --- /dev/null +++ b/src/jolt/async.janet @@ -0,0 +1,208 @@ +# clojure.core.async on Janet fibers. +# +# Janet fibers are stackful coroutines, so a `go` block is just "run the body in +# a fiber" — the body parks on a channel op by yielding to the event loop, and +# the whole interpreter call stack rides along on the fiber's stack. No CPS/state +# machine transform (unlike Clojure's `go` macro), so ! work anywhere +# (inside try, nested fns, loops, …). +# +# A channel is a pair of Janet ev/chans wrapped in a tagged table: a `:ch` that +# carries values and a `:done` that is closed to signal channel close. A take is +# `(ev/select :ch :done)` — ev/select checks in order, so buffered values drain +# before the close signal is seen, giving Clojure's drain-then-nil semantics. We +# use a separate `:done` channel because Janet's ev/chan-close *discards* a +# channel's buffered values. close! just closes :done (idempotent, no fiber), so +# nothing leaks. +# +# Single OS thread: go blocks run cooperatively on the event loop, so buf 0)) {:kind :fixed :n buf} + nil)) + (def vc (if spec (ev/chan (spec :n)) (ev/chan))) + (def w (wrap vc (ev/chan))) + (when spec (put w :bufkind (spec :kind))) + (when (and xform (not (nil? xform))) + (put w :xrf (xform (make-add-rf w)))) + w) + +(defn async-close! [ch] + (when (not (in (ch :closed) 0)) + (put (ch :closed) 0 true) + # flush any buffered state of a stateful transducer (completion arity) + (when (ch :xrf) (protect ((ch :xrf) (ch :ch)))) + (protect (ev/chan-close (ch :done)))) + nil) + +# ! / >!! — put, parking the fiber. Returns true if delivered, false if the +# channel is closed. nil may not be put on a channel (it is the closed value). +# With a transducer, the value is run through it (so one put may yield zero or +# more values on the channel); a `reduced` result (e.g. from `take`) closes it. +(defn async-give [ch v] + (when (nil? v) (error "Can't put nil on a channel")) + (cond + (in (ch :closed) 0) false + (ch :xrf) + (let [r ((ch :xrf) (ch :ch) v)] + (when (reduced? r) (async-close! ch)) + true) + (buf-give ch v))) + +# Run thunk (a jolt 0-arg closure, directly callable) in a fiber; return a +# buffered(1) channel that conveys its value once, then closes. A nil result +# just closes. Buffered(1) so a fire-and-forget go leaves no parked fiber. +# +# The dynamic-var bindings in effect at spawn time are conveyed into the fiber +# (Clojure binding conveyance): we snapshot them here (on the spawning fiber) +# and install a private copy inside the new fiber before running the body. +(defn async-go-spawn [thunk] + (def snap (snapshot-bindings)) + (def w (async-chan 1)) + (ev/go (fn [] + (install-bindings snap) + (def res (protect (thunk))) + (when (and (in res 0) (not (nil? (in res 1)))) + (async-give w (in res 1))) + (async-close! w))) + w) + +# (alts! [ch ...]) — take from whichever channel is ready first; returns +# [value channel] (value is nil if that channel closed). Take-only for v1. +(defn async-alts [chans] + (def cs (cond (pvec? chans) (pv->array chans) + (tuple? chans) chans + (array? chans) chans + (error "alts! expects a vector of channels"))) + (def raws @[]) + (def lookup @{}) # raw ev/chan -> [jolt-chan done?] + (each c cs + (array/push raws (c :ch)) (put lookup (c :ch) [c false]) + (array/push raws (c :done)) (put lookup (c :done) [c true])) + (def r (ev/select ;raws)) + (def info (get lookup (in r 1))) + (def jc (in info 0)) + (def val (if (or (in info 1) (not= :take (in r 0))) nil (in r 2))) + (pv-from-indexed @[val jc])) + +# (timeout ms) — a channel that closes after ms milliseconds. +(defn async-timeout [ms] + (def w (async-chan)) + (ev/go (fn [] (ev/sleep (/ ms 1000)) (async-close! w))) + w) + +# (put! ch v [cb]) — async put; (take! ch cb) — async take. Fire a fiber and +# call the optional callback with the result. +(defn async-put! [ch v &opt cb] + (ev/go (fn [] + (def ok (async-give ch v)) + (when (and cb (not (nil? cb))) (cb ok)))) + nil) +(defn async-take! [ch cb] + (ev/go (fn [] + (def val (async-take ch)) + (when (and cb (not (nil? cb))) (cb val)))) + nil) + +# --- macros (Janet macro-fns that return forms) --- + +(defn- sym [name &opt ns] {:jolt/type :symbol :ns ns :name name}) + +# (go body...) -> (go-spawn (fn* [] body...)) +(defn async-go [& body] + @[(sym "go-spawn" "clojure.core.async") (array (sym "fn*") [] ;body)]) + +# (go-loop bindings body...) -> (go (loop bindings body...)) +(defn async-go-loop [bindings & body] + @[(sym "go" "clojure.core.async") (array (sym "loop") bindings ;body)]) + +# (thread body...) — runs cooperatively in a fiber here (no OS thread); same +# shape as go (returns a result channel). +(defn async-thread [& body] + @[(sym "go-spawn" "clojure.core.async") (array (sym "fn*") [] ;body)]) + +(def- async-bindings + @{"chan" async-chan + "chan?" jolt-chan? + "close!" async-close! + "!" async-give ">!!" async-give + "alts!" async-alts "alts!!" async-alts + "timeout" async-timeout + "buffer" async-buffer + "dropping-buffer" async-dropping-buffer + "sliding-buffer" async-sliding-buffer + "put!" async-put! + "take!" async-take! + "go-spawn" async-go-spawn + "go" async-go + "go-loop" async-go-loop + "thread" async-thread}) + +(def- async-macros @{"go" true "go-loop" true "thread" true}) + +(defn install-async! + "Create/populate the clojure.core.async namespace in ctx." + [ctx] + (let [ns (ctx-find-ns ctx "clojure.core.async")] + (loop [[name f] :pairs async-bindings] + (def v (ns-intern ns name f)) + (when (get async-macros name) (put v :macro true))) + ns)) diff --git a/src/jolt/backend.janet b/src/jolt/backend.janet new file mode 100644 index 0000000..071c4a4 --- /dev/null +++ b/src/jolt/backend.janet @@ -0,0 +1,444 @@ +# Janet back end: host-neutral IR (from jolt.analyzer) -> Janet form -> bytecode. +# +# Host-specific by definition (it targets Janet). It resolves name-based :var +# nodes to Janet var cells and reuses runtime helpers (jolt-call, make-vec, +# build-map-literal). The portable front end (jolt.analyzer) never sees any of +# this; a different runtime provides its own back end against the same IR. +# +# In src/jolt/ (not host/janet/) for the same module-resolution reason as +# host_iface — see that file's header. + +(use ./types) +(use ./core) +(import ./compiler :as comp) +(use ./evaluator) +(import ./reader :as r) +(import ./phm :as phm) + +# The IR is portable data; reading its representation is a host-layer concern. +# Most nodes are Janet structs (raw-readable), but a node carrying a nil-valued +# field — an anonymous fn's :name, a nil const's :val, a def with no :meta, an +# arity with no :rest — is a phm, whose fields live under :buckets, not as direct +# keys. Densify such a node to a struct: phm-to-struct drops exactly those +# nil-valued fields, which is what the back end wants (it already treats an absent +# field as nil). Structs (the common case) pass through untouched. Applied at the +# few points where a node first reaches the emitter, so the rest of the back end +# keeps using plain (node :key) access and the portable front end never sees this. +(defn- norm-node [n] + (if (phm/phm? n) (phm/phm-to-struct n) n)) + +# Var late-binding: reads go through `(var-get cell)` with the cell embedded as a +# constant, so compiled code sees redefinition (Janet early-binds plain symbols) +# — var-get reads the cell's root live. Writes go through a memoized setter. +(defn- var-setter [cell] + (or (get cell :jolt/setter) + (let [s (fn [v] (bind-root cell v) cell)] (put cell :jolt/setter s) s))) + +# Setter that also applies def metadata to the var (so ^:dynamic / ^:redef / +# ^:private survive compilation, matching the interpreter's def). Not memoized: +# the meta is specific to this def site. +(defn- var-setter-meta [cell meta] + (fn [v] + (bind-root cell v) + (put cell :meta (merge (or (cell :meta) {}) meta)) + (when (get meta :dynamic) (put cell :dynamic true)) + cell)) + +(defn- cell-for [ctx ns-name nm] + (ns-intern (ctx-find-ns ctx ns-name) nm)) + +# Direct-linking decision (call-site/unit property, Clojure-style). A var +# reference compiles to its embedded value (direct) iff: +# - the compiling unit has direct-linking on (env :direct-linking?), +# - the target opts in (NOT ^:redef / ^:dynamic — those force indirect), +# - the target is already defined AND its root is a Janet function. +# The function? guard is essential: embedding a non-function value (a jolt +# collection/symbol) into the emitted form would make Janet evaluate it AS code. +# So we direct-link exactly the call-optimization case; everything else stays +# indirect (live var deref → redefinable). Default user/REPL units: flag off, +# so all user calls are indirect and redefinable with no annotation. +(defn- direct-var? [ctx cell] + (and (get (ctx :env) :direct-linking?) + (not (cell :dynamic)) + (not (let [m (cell :meta)] (and m (get m :redef)))) + (function? (cell :root)))) + +# Fresh Janet symbol for back-end-introduced bindings (arity dispatch). NOT +# Janet's `gensym` — `(use ./core)` shadows it with Jolt's, which returns a jolt +# symbol struct (invalid in a Janet param position). +(var- gsym-counter 0) +(defn- gsym [] (def s (symbol "_be$" gsym-counter)) (++ gsym-counter) s) + +(var emit nil) + +(defn- emit-seq [ctx node] + (def out @['do]) + (each s (vview (node :statements)) (array/push out (emit ctx s))) + (array/push out (emit ctx (node :ret))) + (tuple/slice out)) + +(defn- emit-let [ctx node] + (def binds @[]) + (each pair (vview (node :bindings)) + (def p (vview pair)) + (array/push binds (symbol (in p 0))) + (array/push binds (emit ctx (in p 1)))) + ['let (tuple/slice binds) (emit ctx (node :body))]) + +# An arity compiles to a named Janet fn whose name is its recur target, so recur +# is a self-call (Janet tail-calls it). The rest param is an ORDINARY positional +# param holding a seq (not Janet `&`), so `(recur fixed... rest-seq)` re-enters +# the way Clojure recur into a variadic arity does (rebinds the rest seq directly, +# no re-collection). The dispatch wrapper (emit-fn-body) collects the call's args. +(defn- emit-arity-fn [ctx ar] + (def ps @[]) + (each pn (vview (ar :params)) (array/push ps (symbol pn))) + (when (ar :rest) (array/push ps (symbol (ar :rest)))) + ['fn (symbol (ar :recur-name)) (tuple/slice ps) (emit ctx (ar :body))]) + +# Invoke an arity's fn with args pulled from the dispatch tuple: fixed params by +# index, rest as a slice from n-fixed on. +(defn- emit-arity-invoke [ctx ar jargs] + (def nfixed (length (vview (ar :params)))) + (def call @[(emit-arity-fn ctx ar)]) + (for i 0 nfixed (array/push call ['in jargs i])) + (when (ar :rest) (array/push call ['tuple/slice jargs nfixed])) + (tuple/slice call)) + +(defn- emit-loop [ctx node] + (def L (symbol (node :recur-name))) + (def params @[]) + # Initial inits bind SEQUENTIALLY (a later init can reference an earlier binding, + # like let / Clojure's loop) — emit them in a Janet `let`, then enter the recur + # target L with those values, rather than computing all inits in the outer scope. + (def let-binds @[]) + (each pair (vview (node :bindings)) + (def p (vview pair)) + (def sym (symbol (in p 0))) + (array/push params sym) + (array/push let-binds sym) + (array/push let-binds (emit ctx (in p 1)))) + ['do + ['var L nil] + ['set L ['fn (tuple/slice params) (emit ctx (node :body))]] + ['let (tuple/slice let-binds) (tuple/slice (array/concat @[L] params))]]) + +(defn- emit-recur [ctx node] + (tuple/slice (array/concat @[(symbol (node :recur-name))] + (map |(emit ctx $) (vview (node :args)))))) + +(defn- emit-try [ctx node] + (def core + (if (node :catch-sym) + ['try (emit ctx (node :body)) + [[(symbol (node :catch-sym))] (emit ctx (node :catch-body))]] + (emit ctx (node :body)))) + (if (node :finally) + ['defer (emit ctx (node :finally)) core] + core)) + +(defn- emit-fn-body [ctx node] + (def arities (map norm-node (vview (node :arities)))) + (def multi (> (length arities) 1)) + (cond + # Single fixed arity (the hot case): emit the arity fn directly — its name is + # the recur target, no dispatch overhead. + (and (not multi) (not ((first arities) :rest))) + (emit-arity-fn ctx (first arities)) + # Single variadic arity: a thin wrapper collects the call's args so the rest + # seq can be built, then hands off to the arity fn. + (not multi) + (let [jargs (gsym)] + ['fn ['& jargs] (emit-arity-invoke ctx (first arities) jargs)]) + # Multi-arity: dispatch on arg count. Fixed arities match exactly; the (one) + # variadic arity matches >= its fixed count. + (let [jargs (gsym) + nsym (gsym) + cf @['cond]] + (each ar arities + (def nfixed (length (vview (ar :params)))) + (array/push cf (if (ar :rest) [>= nsym nfixed] [= nsym nfixed])) + (array/push cf (emit-arity-invoke ctx ar jargs))) + (array/push cf ['error "wrong number of args passed to fn"]) + ['fn ['& jargs] + ['do ['def nsym ['length jargs]] (tuple/slice cf)]]))) + +# A named fn (fn self [..] .. (self ..)) references itself by name. The analyzer +# binds that name as a local; bind it here to the fn value via a var (set before +# any call, so the captured closure sees it — same scheme as emit-loop). recur +# stays a separate self-call to the arity fn; this only covers by-name self-refs. +(defn- emit-fn [ctx node] + (def body (emit-fn-body ctx node)) + (if (node :name) + (let [s (symbol (node :name))] + ['do ['var s nil] ['set s body] s]) + body)) + +# A direct Janet call (f args) is only correct when the callee is definitely a +# function: Janet calling a pvec/keyword/etc. does get (or the wrong thing), not +# IFn dispatch. So only emit a direct call for :fn / :host (always functions) and +# a :var whose CURRENT root is a function (the common user/core-fn case). A :var +# holding an IFn COLLECTION (vector/keyword/set used as a fn) or a :local of +# unknown value falls through to jolt-call, which dispatches IFn correctly +# (function fast-path first). Trade-off, like direct-linking: a fn-var redefined +# to a collection after this call was compiled would still emit a direct call. +(defn- direct-call? [ctx fnode] + (case (fnode :op) + :fn true + :host true + :var (let [r (get (cell-for ctx (fnode :ns) (fnode :name)) :root)] + (or (function? r) (cfunction? r))) + false)) + +# Hot primitives emitted as native Janet ops (host-specific optimization): a +# call to clojure.core/+ etc. becomes (+ …) rather than a var deref + variadic +# core fn. Matches numeric semantics; relaxes the non-number checks (a documented +# perf-mode divergence, same as the bootstrap's core-renames). +(def- native-ops + {"+" '+ "-" '- "*" '* "<" '< ">" '> "<=" '<= ">=" '>= "inc" '++ "dec" '--}) + +(defn- native-op + "If fnode is a clojure.core ref (or host ref) to a native-op primitive, return + the Janet op symbol, else nil. inc/dec are unary so only at arity 1." + [fnode nargs] + (def nm (case (fnode :op) + :var (when (= "clojure.core" (fnode :ns)) (fnode :name)) + :host (fnode :name) + nil)) + (def op (and nm (get native-ops nm))) + (cond + (nil? op) nil + (and (or (= op '++) (= op '--)) (not= nargs 1)) nil + op)) + +(defn- emit-invoke [ctx node] + (def fnode (norm-node (node :fn))) + (def args (map |(emit ctx $) (vview (node :args)))) + (def nop (native-op fnode (length args))) + (cond + nop (case nop + '++ ['+ (in args 0) 1] + '-- ['- (in args 0) 1] + (tuple nop ;args)) + (direct-call? ctx fnode) (tuple (emit ctx fnode) ;args) + (tuple jolt-call (emit ctx fnode) ;args))) + +(defn- emit-vector [ctx node] + (def items (map |(emit ctx $) (vview (node :items)))) + (tuple make-vec (tuple/slice (array/concat @['tuple] items)))) + +(defn- emit-map [ctx node] + (def args @[comp/build-map-literal]) + (each pair (vview (node :pairs)) + (def p (vview pair)) + (array/push args (emit ctx (in p 0))) + (array/push args (emit ctx (in p 1)))) + (tuple/slice args)) + +# A set literal: build (make-phs e1 e2 …) so each element is evaluated at runtime +# then the persistent set is constructed — mirrors compiler.janet's emit-set-expr. +(defn- emit-set [ctx node] + (def items (map |(emit ctx $) (vview (node :items)))) + (tuple/slice (array/concat @[phm/make-phs] items))) + +(set emit + (fn emit [ctx raw] + (def node (norm-node raw)) + (case (node :op) + :const (node :val) + :local (symbol (node :name)) + :host (symbol (node :name)) + :var (let [cell (cell-for ctx (node :ns) (node :name))] + (if (direct-var? ctx cell) + (cell :root) # direct link: embed the fn value + # Indirect: live deref. Quote the cell so it's embedded by + # reference (a bare table in arg position would be re-evaluated as + # a constructor — deep-copying it, and any atom in :root, each call). + (tuple var-get (tuple 'quote cell)))) + # (var x): the var object itself (not its value) — the embedded cell, by + # reference. binding keys its thread-binding frame on this exact cell. + :the-var (tuple 'quote (cell-for ctx (node :ns) (node :name))) + :if ['if (emit ctx (node :test)) (emit ctx (node :then)) (emit ctx (node :else))] + :do (emit-seq ctx node) + :loop (emit-loop ctx node) + :recur (emit-recur ctx node) + :try (emit-try ctx node) + :throw ['error (emit ctx (node :expr))] + :def (let [cell (cell-for ctx (node :ns) (node :name)) + meta (node :meta)] + (tuple (if (and meta (not (empty? meta))) (var-setter-meta cell meta) (var-setter cell)) + (emit ctx (node :init)))) + :let (emit-let ctx node) + :fn (emit-fn ctx node) + :invoke (emit-invoke ctx node) + :vector (emit-vector ctx node) + :map (emit-map ctx node) + :set (emit-set ctx node) + :quote ['quote (node :form)] + (error (string "backend: unhandled op " (node :op)))))) + +(defn emit-ir + "IR node -> Janet form (public entry for the back end)." + [ctx node] + (emit ctx node)) + +# --- pipeline wiring (the self-hosted compile path) --- + +# Bootstrap-compile a source string into target-ns: each form is compiled via the +# bootstrap (native Janet) compiler and its defs interned in target-ns. This is +# the stage-1 builder — it runs BEFORE the self-hosted analyzer exists, so it's +# how both the compiler namespaces (jolt.ir/jolt.analyzer) and the clojure.core +# kernel tier (the structural fns the analyzer itself calls) get built. The +# analyzer uses unqualified referred names (jolt.host form-* + IR ctors), so the +# bootstrap's plain :var path compiles it; stateful forms fall back to interp. +(defn bootstrap-load-source [ctx target-ns src] + (def saved (ctx-current-ns ctx)) + (ctx-set-current-ns ctx target-ns) + (var s src) + (while (> (length (string/trim s)) 0) + (def parsed (r/parse-next s)) + (set s (in parsed 1)) + (def f (in parsed 0)) + (when (not (nil? f)) + # Guard BOTH compile and the Janet-compile-of-emitted step: a form whose + # emitted Janet is invalid (e.g. a bad splice) falls back to interpreted + # definition rather than killing the whole load. + (def r (protect (comp/eval-compiled (comp/compile-ast f ctx) ctx))) + (unless (r 0) (eval-form ctx @{} f)))) + (ctx-set-current-ns ctx saved)) + +# Compile-load an embedded jolt-core namespace by name (source from the stdlib map). +(defn- compile-load [ctx ns-name] + (def src (get (get (ctx :env) :embedded-sources @{}) ns-name)) + (when src (bootstrap-load-source ctx ns-name src))) + +# Build the self-hosted compiler (IR ctors + analyzer) via the bootstrap. The +# analyzer's references to clojure.core fns it uses (second/peek/subvec/mapv/ +# update) resolve to whatever is interned in clojure.core at this point — so the +# kernel tier must already be loaded (see api/load-core-overlay!). +(defn- build-compiler! [ctx] + (compile-load ctx "jolt.ir") + (compile-load ctx "jolt.analyzer")) + +(defn- ensure-analyzer [ctx] + # Don't build until the kernel tier is loaded (see api/load-core-overlay! and + # build-compiler!). Before then a compile request — e.g. a defn in a pre-kernel + # tier — must fall back to the interpreter, not build the analyzer against a + # core missing the fns it references (which would intern them as nil cells that + # then shadow the real definitions on the self-rebuild). The flag is absent in + # bare/test contexts that never load core; treat that as ready so those keep + # building the analyzer lazily as before. + (def env (ctx :env)) + (def gated (and (has-key? env :kernel-ready?) (not (get env :kernel-ready?)))) + (when (and (not gated) + (= 0 (length ((ctx-find-ns ctx "jolt.analyzer") :mappings)))) + (build-compiler! ctx))) + +(defn rebuild-compiler! + "Recompile the self-hosted compiler (jolt.ir + jolt.analyzer) against the + CURRENT clojure.core. The fractal turn: once a core tier supplies Clojure + definitions the compiler itself uses, rebuilding makes the compiler run on + them. Idempotent; re-interns the compiler namespaces over the existing cells." + [ctx] + (build-compiler! ctx)) + +(defn analyze-form + "Run the portable Clojure analyzer (jolt.analyzer/analyze) on a reader form, + returning host-neutral IR." + [ctx form] + (ensure-analyzer ctx) + # Capture the real compile ns: the analyzer runs interpreted (defined in + # jolt.analyzer), and the interpreter rebinds current-ns to a fn's defining ns + # while it runs — so h/current-ns must read this instead of ctx-current-ns. + (put (ctx :env) :compile-ns (ctx-current-ns ctx)) + (def av (ns-find (ctx-find-ns ctx "jolt.analyzer") "analyze")) + # Pre-kernel bootstrap: ensure-analyzer is gated until the kernel tier loads + # (see api/load-core-overlay!), so a compile request from an earlier tier (e.g. + # 00-syntax's destructure defn) finds no analyzer. That fallback is DESIGNED — + # route it through the sanctioned punt channel rather than crashing on a nil var. + (unless av (error "jolt/uncompilable: analyzer not built (pre-kernel bootstrap)")) + (def r ((var-get av) ctx form)) + (put (ctx :env) :compile-ns nil) + r) + +# The analyzer's deliberate punt signal — (uncompilable why) throws the string +# "jolt/uncompilable: ". Anything else escaping the compile step is an +# unexpected compiler error, not a punt. +(defn- uncompilable-error? [err] + (and (or (string? err) (buffer? err)) + (string/has-prefix? "jolt/uncompilable" (string err)))) + +(defn compile-and-eval + "Self-hosted compile path: analyze (portable Clojure) -> IR -> Janet -> eval. + The interpreter fallback is DELIBERATE-ONLY (Stage 2): only an analyzer punt + (jolt/uncompilable — the curated stateful/letrec set) falls back; any other + compile-step error is a compiler bug and propagates rather than being silently + hidden by interpretation. Runtime errors in compiled code propagate as before + (no double-eval, no hidden errors)." + [ctx form] + (def compiled (protect (emit-ir ctx (analyze-form ctx form)))) + (if (compiled 0) + (eval (compiled 1) (comp/ctx-janet-env ctx)) + (if (uncompilable-error? (compiled 1)) + (eval-form ctx @{} form) + (error (compiled 1))))) + +(defn analyzer-built? [ctx] + (> (length ((ctx-find-ns ctx "jolt.analyzer") :mappings)) 0)) + +(defn try-compile-fn + "Compile a fn* form to a native Janet fn via the self-hosted pipeline, or nil if + it can't be compiled (analyzer not yet built, or the body isn't compilable). + Used to compile macro expanders for native-speed expansion." + [ctx fn-form] + (when (analyzer-built? ctx) + (def compiled (protect (emit-ir ctx (analyze-form ctx fn-form)))) + (when (compiled 0) + (def r (protect (eval (compiled 1) (comp/ctx-janet-env ctx)))) + (when (r 0) (r 1))))) + +# Wrap expanders in the `fn` MACRO, not the `fn*` primitive: `fn` desugars a +# destructured macro arglist (`[a & [b]]`, `[& {:keys [x]}]`) before lowering, +# whereas raw fn* punts on a destructuring rest param. +(def- fn-sym {:jolt/type :symbol :ns nil :name "fn"}) + +(defn recompile-macros! + "Staged-bootstrap second pass: once the self-hosted analyzer is alive, replace + every interpreted macro expander with a COMPILED one. The early macros (00-syntax + etc.) are defined WHILE the analyzer is still being bootstrapped, so their + expanders can't compile yet (the analyzer they'd compile through doesn't exist) — + defmacro gives them an interpreted closure as a build-time crutch and stashes the + source on the var (:macro-src). This pass compiles that source through the now-live + analyzer and rebinds the var, so by steady state no macro expansion is interpreted + — mirroring how a self-hosting compiler recompiles its seed once it can. + + Idempotent: a var compiled once is marked :macro-compiled and skipped (so the + refer of a core macro into another ns, or a later rebuild, costs nothing). A macro + whose body uses &env/&form keeps its interpreted closure (the compiled fn* has no + such params). Returns the number of expanders compiled this pass." + [ctx] + (var n 0) + (each ns (all-ns ctx) + (each v (ns :mappings) + (when (and (var? v) (var-macro? v) + (v :macro-src) (not (v :macro-compiled)) + (not (v :macro-uses-env))) + (def [args-form body] (v :macro-src)) + (def compiled + (try-compile-fn ctx (array/concat @[fn-sym args-form] body))) + (when compiled + (bind-root v compiled) + (put v :macro-compiled true) + (++ n))))) + n) + +(defn ensure-macros-compiled! + "Called once the overlay is fully loaded (api/load-core-overlay!): in compile + mode, ensure the analyzer is built, then run the staged macro-recompile pass so + the early (interpreted-during-bootstrap) macro expanders become compiled. No-op + in interpreter mode (no analyzer, macros stay interpreted by design) and cheap to + call again (recompile-macros! skips already-compiled vars)." + [ctx] + (when (get (ctx :env) :compile?) + (ensure-analyzer ctx) + (when (analyzer-built? ctx) (recompile-macros! ctx)))) diff --git a/stdlib/clojure/data.clj b/src/jolt/clojure/data.clj similarity index 100% rename from stdlib/clojure/data.clj rename to src/jolt/clojure/data.clj diff --git a/src/jolt/clojure/edn.clj b/src/jolt/clojure/edn.clj new file mode 100644 index 0000000..ea271b3 --- /dev/null +++ b/src/jolt/clojure/edn.clj @@ -0,0 +1,41 @@ +;; clojure.edn — reading EDN data. Delegates to the Jolt reader via +;; clojure.core/read-string (which parses, never evaluates — safe for EDN), and +;; adds the opts-map arity with :eof plus nil/blank-input handling. +(ns clojure.edn + "Reading EDN data." + (:require [clojure.string :as cstr])) + +;; The reader yields set literals as a FORM ({:jolt/type :jolt/set :value [...]}) +;; rather than a constructed set, so build the actual values, recursing into +;; maps/vectors/lists. (Lists stay lists — EDN never evaluates them as code.) +(defn- edn->value [x] + (cond + (and (map? x) (= :jolt/set (get x :jolt/type))) (set (map edn->value (get x :value))) + ;; Only untagged structs are real maps; symbols/chars/tagged literals are also + ;; struct? (=> map?) but carry a :jolt/type and must pass through unchanged. + (and (map? x) (nil? (get x :jolt/type))) + (into {} (map (fn [e] [(edn->value (key e)) (edn->value (val e))]) x)) + (vector? x) (mapv edn->value x) + (seq? x) (map edn->value x) + :else x)) + +;; Private helper, NOT named read-string: an unqualified (read-string …) call +;; dispatches the core read-string SPECIAL FORM (by name, regardless of ns), so +;; the 1-arity can't delegate to the 2-arity through that name. +(defn- read-edn [opts s] + (if (or (nil? s) (cstr/blank? s)) + (get opts :eof nil) + (edn->value (clojure.core/read-string s)))) + +(defn read-string + "Reads one object from the string s. Returns the :eof option value (default + nil) for nil or blank input. opts is an options map; :eof sets the value + returned at end of input." + ([s] (read-edn {} s)) + ([opts s] (read-edn opts s))) + +(defn read + "Reads the next line from reader and parses one EDN object from it." + [reader] + (let [line ((get (dyn :current-env) (symbol "file/read")) reader :line)] + (when line (read-string line)))) diff --git a/src/jolt/clojure/java/io.clj b/src/jolt/clojure/java/io.clj new file mode 100644 index 0000000..53e587b --- /dev/null +++ b/src/jolt/clojure/java/io.clj @@ -0,0 +1,46 @@ +; Jolt Standard Library: clojure.java.io +; +; A Janet-backed shim: file I/O via Janet's file/ and os/ through the janet.* +; interop bridge. It deals in plain path strings and Janet file handles, not +; java.io objects — so JVM-specific interop on the results (.toURL, .lastModified, +; …) won't work, but file/reader/writer/resource/copy/slurp do. + +(defn file + "A file path. With a parent and child, joins them with '/'." + ([path] (str path)) + ([parent child] (str parent "/" child))) + +(defn as-file [x] (str x)) + +(defn reader [x] (janet.file/open (str x) :r)) +(defn writer [x] (janet.file/open (str x) :w)) +(defn input-stream [x] (reader x)) +(defn output-stream [x] (writer x)) + +(defn resource + "Returns a slurp-able path for `path` if it exists, else nil. (Clojure returns + a URL; a path works the same with slurp here, since there's no classpath.)" + [path] + (let [p (str path)] (when (janet.os/stat p) p))) + +(defn delete-file + ([f] (delete-file f false)) + ([f silently] + (try (do (janet.os/rm (str f)) true) + (catch Throwable e (if silently false (throw e)))))) + +(defn make-parents + "Create the parent directories of `f`." + [f] + (let [path (str f) + i (clojure.string/last-index-of path "/")] + (when (and i (pos? i)) + (let [parent (subs path 0 i)] + (make-parents parent) + (when-not (janet.os/stat parent) (janet.os/mkdir parent)))))) + +(defn copy + "Copy from a path/handle `in` to a path/handle `out`." + [in out] + (let [content (if (string? in) (slurp in) (janet.file/read in :all))] + (if (string? out) (spit out content) (janet.file/write out content)))) diff --git a/src/jolt/clojure/lang/persistent_vector.clj b/src/jolt/clojure/lang/persistent_vector.clj new file mode 100644 index 0000000..6dced9d --- /dev/null +++ b/src/jolt/clojure/lang/persistent_vector.clj @@ -0,0 +1,165 @@ +(ns jolt.lang.persistent-vector + "PersistentVector: 32-way branching trie with tail optimization.") + +(def branch-factor 32) +(def shift-increment 5) +(def tail-max 31) + +(deftype VectorNode [^:volatile-mutable arr]) +(deftype PersistentVector [cnt shift root tail _meta]) + +(def empty-array (object-array 0)) +(def EMPTY (PersistentVector. 0 shift-increment nil empty-array nil)) + +(defn- tailoff [pv] + (int (- (.-cnt pv) (unsigned-bit-shift-right (.-cnt pv) shift-increment)))) + +(defn- new-path [level node] + (if (= level 0) + node + (let [arr (object-array branch-factor)] + (aset arr 0 (new-path (int (- level shift-increment)) node)) + (VectorNode. arr)))) + +(defn- push-tail [parent level tailnode cnt] + (let [subidx (int (bit-and (unsigned-bit-shift-right (int cnt) (int level)) tail-max)) + ret (VectorNode. (aclone (.-arr parent)))] + (if (= level shift-increment) + (do (aset (.-arr ret) subidx tailnode) ret) + (let [child (aget (.-arr parent) subidx)] + (aset (.-arr ret) subidx + (if child + (push-tail child (int (- level shift-increment)) tailnode cnt) + (new-path (int (- level shift-increment)) tailnode))) + ret)))) + +(defn- do-assoc [level node i val] + (let [ret (VectorNode. (aclone (.-arr node)))] + (if (= level 0) + (do (aset (.-arr ret) (int (bit-and i tail-max)) val) ret) + (let [subidx (int (bit-and (unsigned-bit-shift-right (int i) (int level)) tail-max))] + (aset (.-arr ret) subidx + (do-assoc (int (- level shift-increment)) (aget (.-arr node) subidx) i val)) + ret)))) + +(defn- array-for [pv i] + (if (and (<= 0 i) (< i (.-cnt pv))) + (if (>= i (tailoff pv)) + (.-tail pv) + (loop [node (.-root pv) level (.-shift pv)] + (if (> level 0) + (recur (aget (.-arr node) + (int (bit-and (unsigned-bit-shift-right (int i) (int level)) tail-max))) + (int (- level shift-increment))) + (.-arr node)))) + nil)) + +(defn pv-conj [pv val] + (let [cnt (.-cnt pv)] + (if (< (- cnt (tailoff pv)) branch-factor) + (let [old-len (alength (.-tail pv)) + new-tail (object-array (+ old-len 1))] + (loop [i 0] + (if (< i old-len) + (do (aset new-tail i (aget (.-tail pv) i)) (recur (unchecked-inc i))) + (do (aset new-tail i val) + (PersistentVector. (unchecked-inc cnt) (.-shift pv) (.-root pv) new-tail (.-_meta pv)))))) + (let [tail-node (VectorNode. (.-tail pv)) + root-overflow? (> (unchecked-inc (unsigned-bit-shift-right cnt shift-increment)) + (bit-shift-left 1 (.-shift pv)))] + (if root-overflow? + (let [nr (object-array branch-factor)] + (aset nr 0 (.-root pv)) + (aset nr 1 (new-path (.-shift pv) tail-node)) + (let [new-root (VectorNode. nr) + new-shift (+ (.-shift pv) shift-increment) + new-tail (object-array 1)] + (aset new-tail 0 val) + (PersistentVector. (unchecked-inc cnt) new-shift new-root new-tail (.-_meta pv)))) + (let [new-root (push-tail (.-root pv) (.-shift pv) tail-node cnt) + new-tail (object-array 1)] + (aset new-tail 0 val) + (PersistentVector. (unchecked-inc cnt) (.-shift pv) new-root new-tail (.-_meta pv)))))))) + +(defn pv-nth [pv i] + (let [node (array-for pv i)] + (if node + (aget node (int (bit-and i tail-max))) + (throw (str "Index out of bounds: " i))))) + +(defn pv-assoc [pv i val] + (let [cnt (.-cnt pv)] + (if (and (<= 0 i) (< i cnt)) + (if (>= i (tailoff pv)) + (let [new-tail (object-array (alength (.-tail pv)))] + (loop [j 0] + (if (< j (alength new-tail)) + (do (aset new-tail j + (if (= j (int (bit-and i tail-max))) val (aget (.-tail pv) j))) + (recur (unchecked-inc j))) + (PersistentVector. cnt (.-shift pv) (.-root pv) new-tail (.-_meta pv))))) + (PersistentVector. cnt (.-shift pv) (do-assoc (.-shift pv) (.-root pv) i val) (.-tail pv) (.-_meta pv))) + (if (= i cnt) + (pv-conj pv val) + (throw (str "Index out of bounds: " i)))))) + +(defn- pop-tail [level node cnt] + (let [subidx (int (bit-and (unsigned-bit-shift-right (int (- cnt 2)) (int level)) tail-max))] + (if (> level shift-increment) + (let [new-child (pop-tail (int (- level shift-increment)) (aget (.-arr node) subidx) cnt)] + (if (and (nil? new-child) (zero? subidx)) + nil + (let [ret (VectorNode. (aclone (.-arr node)))] + (aset (.-arr ret) subidx new-child) + ret))) + (if (zero? subidx) + nil + (let [ret (VectorNode. (aclone (.-arr node)))] + (aset (.-arr ret) subidx nil) + ret))))) + +(defn- pv-nth-internal [cnt shift root i] + (if (and (<= 0 i) (< i cnt)) + (if (>= i (- cnt (int (bit-and cnt tail-max)))) + nil + (loop [node root level shift] + (if (> level 0) + (recur (aget (.-arr node) (int (bit-and (unsigned-bit-shift-right (int i) (int level)) tail-max))) + (int (- level shift-increment))) + (aget (.-arr node) (int (bit-and i tail-max)))))) + nil)) + +(defn pv-pop [pv] + (let [cnt (.-cnt pv)] + (cond + (zero? cnt) (throw "Can't pop empty vector") + (= cnt 1) EMPTY + (> (- cnt (tailoff pv)) 1) + (let [old-tail (.-tail pv) + new-tail (object-array (dec (alength old-tail)))] + (loop [i 0] + (if (< i (alength new-tail)) + (do (aset new-tail i (aget old-tail i)) (recur (unchecked-inc i))) + (PersistentVector. (dec cnt) (.-shift pv) (.-root pv) new-tail (.-_meta pv))))) + :else + (let [new-root (pop-tail (.-shift pv) (.-root pv) cnt) + new-cnt (dec cnt) + new-tail-len (int (bit-and new-cnt tail-max)) + tail-len (if (zero? new-tail-len) branch-factor new-tail-len) + new-tail (object-array tail-len)] + (loop [i 0] + (if (< i tail-len) + (let [idx (+ (- new-cnt tail-len) i)] + (aset new-tail i (pv-nth-internal new-cnt (.-shift pv) new-root idx)) + (recur (unchecked-inc i))) + (PersistentVector. new-cnt (.-shift pv) new-root new-tail (.-_meta pv)))))))) + +(defn pv-empty [_] EMPTY) + +(defn vector [& args] + (loop [acc EMPTY items (seq args)] + (if (seq items) + (recur (pv-conj acc (first items)) (rest items)) + acc))) + +(defn vector? [x] (instance? PersistentVector x)) diff --git a/stdlib/clojure/sci/host_stubs.clj b/src/jolt/clojure/sci/host_stubs.clj similarity index 100% rename from stdlib/clojure/sci/host_stubs.clj rename to src/jolt/clojure/sci/host_stubs.clj diff --git a/stdlib/clojure/sci/io_stubs.clj b/src/jolt/clojure/sci/io_stubs.clj similarity index 100% rename from stdlib/clojure/sci/io_stubs.clj rename to src/jolt/clojure/sci/io_stubs.clj diff --git a/stdlib/clojure/sci/lang_stubs.clj b/src/jolt/clojure/sci/lang_stubs.clj similarity index 100% rename from stdlib/clojure/sci/lang_stubs.clj rename to src/jolt/clojure/sci/lang_stubs.clj diff --git a/stdlib/clojure/set.clj b/src/jolt/clojure/set.clj similarity index 86% rename from stdlib/clojure/set.clj rename to src/jolt/clojure/set.clj index e721890..e9ad98a 100644 --- a/stdlib/clojure/set.clj +++ b/src/jolt/clojure/set.clj @@ -1,22 +1,18 @@ ; Jolt Standard Library: clojure.set -; Set operations. +; Set operations. Note: no & rest arities (evaluator limitation). (defn union - ([] #{}) ([s1] s1) - ([s1 s2] (if (< (count s1) (count s2)) (reduce conj s2 s1) (reduce conj s1 s2))) - ([s1 s2 & sets] (reduce union (union s1 s2) sets))) + ([s1 s2] (reduce conj s2 s1))) (defn intersection ([s1] s1) ([s1 s2] - (reduce (fn [acc item] (if (contains? s2 item) acc (disj acc item))) s1 s1)) - ([s1 s2 & sets] (reduce intersection (intersection s1 s2) sets))) + (reduce (fn [acc item] (if (contains? s2 item) acc (disj acc item))) s1 s1))) (defn difference ([s1] s1) - ([s1 s2] (reduce disj s1 s2)) - ([s1 s2 & sets] (reduce difference (difference s1 s2) sets))) + ([s1 s2] (reduce disj s1 s2))) (defn select [pred s] diff --git a/src/jolt/clojure/string.clj b/src/jolt/clojure/string.clj new file mode 100644 index 0000000..c435719 --- /dev/null +++ b/src/jolt/clojure/string.clj @@ -0,0 +1,137 @@ +; Jolt Standard Library: clojure.string +; String manipulation functions using Jolt core string interop. + +(defn blank? + [s] + (if (nil? s) true + (= 0 (count (str-trim s))))) + +(defn capitalize + + [s] + (if (< 1 (count s)) + (str (str-upper (subs s 0 1)) + (str-lower (subs s 1))) + (str-upper s))) + +(defn lower-case + + [s] + (str-lower s)) + +(defn upper-case + + [s] + (str-upper s)) + +(defn includes? + + [s substr] + (not (nil? (str-find substr s)))) + +(defn join + + ([coll] (str-join coll)) + ([separator coll] (str-join coll separator))) + +(defn replace + [s match replacement] + (str-replace-all match replacement s)) + +(defn replace-first + [s match replacement] + (str-replace match replacement s)) + +(defn reverse + [s] + (str-reverse-b s)) + +(defn str-reverse + [s] + (str-reverse-b s)) + +(defn split + ([s re] + (vec (str-split re s))) + ([s re limit] + (vec (take limit (str-split re s))))) + +(defn split-lines + "Split s on \\n or \\r\\n, returning a vector of lines." + [s] + (vec (str-split #"\r?\n" s))) + +(defn starts-with? + + [s substr] + (let [slen (count s) slen2 (count substr)] + (and (>= slen slen2) + (= (subs s 0 slen2) substr)))) + +(defn ends-with? + + [s substr] + (let [slen (count s) slen2 (count substr)] + (and (>= slen slen2) + (= (subs s (- slen slen2)) substr)))) + +(defn trim + + [s] + (str-trim s)) + +(defn triml + + [s] + (str-triml s)) + +(defn trimr + + [s] + (str-trimr s)) + +(defn trim-newline + + [s] + (var result s) + (while (or (= (subs result (dec (count result))) "\n") + (= (subs result (dec (count result))) "\r")) + (set result (subs result 0 (dec (count result))))) + result) + +(defn escape + + [s cmap] + (apply str + (map (fn [ch] + (if-let [rep (cmap ch)] rep (str ch))) + s))) + +(defn index-of + "0-based index of the first occurrence of value in s, or nil." + ([s value] + (str-find value s)) + ([s value from] + (let [idx (str-find value (subs s from))] + (when idx (+ from idx))))) + +(defn last-index-of + + ([s value] + (let [r (str-reverse-b s) sval (str-reverse-b value) + idx (str-find sval r)] + (when idx (- (count s) (+ idx (count value)))))) + ([s value from] + (let [sub (subs s 0 from) r (str-reverse-b sub) sval (str-reverse-b value) + idx (str-find sval r)] + (when idx (- from (+ idx (count value))))))) + +(defn re-quote-replacement + "Escape special characters (backslash and dollar) in a regex replacement + string so it is used literally rather than interpreted." + [replacement] + (apply str + (map (fn [ch] + (let [c (str ch)] + (if (or (= c "\\") (= c "$")) (str "\\" c) c))) + (seq replacement)))) diff --git a/src/jolt/clojure/walk.clj b/src/jolt/clojure/walk.clj new file mode 100644 index 0000000..f2ba5e2 --- /dev/null +++ b/src/jolt/clojure/walk.clj @@ -0,0 +1,46 @@ +; Jolt Standard Library: clojure.walk +; Tree walking for Clojure data structures. +; Simplified: uses vector? and map? predicates (no list? or seq?). + +(defn walk + [inner outer form] + (cond + (vector? form) (outer (vec (map inner form))) + (map? form) (outer (into (empty form) (map inner form))) + :else (outer form))) + +(defn postwalk + [f form] + (walk (partial postwalk f) f form)) + +(defn prewalk + [f form] + (walk (partial prewalk f) identity (f form))) + +(defn postwalk-demo + "Demonstrates the behavior of postwalk by printing each form as it is walked." + [form] + (postwalk (fn [x] (print "Walked: ") (prn x) x) form)) + +(defn prewalk-demo + "Demonstrates the behavior of prewalk by printing each form as it is walked." + [form] + (prewalk (fn [x] (print "Walked: ") (prn x) x) form)) + +(defn postwalk-replace + [smap form] + (postwalk (fn [x] (if (contains? smap x) (get smap x) x)) form)) + +(defn prewalk-replace + [smap form] + (prewalk (fn [x] (if (contains? smap x) (get smap x) x)) form)) + +(defn keywordize-keys + [m] + (let [f (fn [[k v]] (if (string? k) [(keyword k) v] [k v]))] + (postwalk (fn [x] (if (map? x) (into {} (map f x)) x)) m))) + +(defn stringify-keys + [m] + (let [f (fn [[k v]] (if (keyword? k) [(name k) v] [k v]))] + (postwalk (fn [x] (if (map? x) (into {} (map f x)) x)) m))) diff --git a/stdlib/clojure/zip.clj b/src/jolt/clojure/zip.clj similarity index 95% rename from stdlib/clojure/zip.clj rename to src/jolt/clojure/zip.clj index af3e502..914c90c 100644 --- a/stdlib/clojure/zip.clj +++ b/src/jolt/clojure/zip.clj @@ -5,7 +5,7 @@ ;; Ported from clojure.zip (Rich Hickey). A loc is a vector [node path] carrying ;; the zipper fns (:zip/branch? :zip/children :zip/make-node) as metadata. The ;; reference indexes a loc with (loc 0)/(loc 1); Jolt uses (nth loc ...) because a -;; metadata-bearing vector is not currently invocable as a fn. +;; metadata-bearing vector is not currently invocable as a fn (see jolt-vh5). (ns clojure.zip "Functional hierarchical zipper, with navigation, editing, and enumeration.") @@ -28,16 +28,6 @@ [root] (zipper vector? seq (fn [node children] (with-meta (vec children) (meta node))) root)) -(defn xml-zip - "Returns a zipper for xml elements (as from clojure.xml/parse), given a root - element" - [root] - (zipper (complement string?) - (comp seq :content) - (fn [node children] - (assoc node :content (and children (apply vector children)))) - root)) - (defn node "Returns the node at loc" [loc] (nth loc 0)) (defn branch? "Returns true if the node at loc is a branch" diff --git a/src/jolt/compiler.janet b/src/jolt/compiler.janet new file mode 100644 index 0000000..4f2f0d1 --- /dev/null +++ b/src/jolt/compiler.janet @@ -0,0 +1,1099 @@ +# Jolt Compiler +# Source-to-source: Clojure forms → Janet source +# Two-phase: analyze-form (classify) → emit-ast (generate) +# +# When ctx is passed to analyze-form, macros are expanded at analyze time. + +(use ./types) +(use ./core) +(use ./phm) + +# The compiler emits Janet that references the core fns (core-+, core-<, …), +# which are bare-bound in this module's environment via (use ./core). Capture it +# so each Jolt context can get a child env where those resolve and where compiled +# `def`/`defn` bindings persist across forms (isolated per context). +(def jolt-runtime-env (curenv)) + +(defn ctx-janet-env + "Lazily create/cache a per-context Janet environment for compiled code: a child + of the runtime env (so core fns resolve) that holds this context's user defs. + For a nil context (one-off compile/eval) returns a fresh child env." + [ctx] + (if (and ctx (table? (get ctx :env))) + (or (get (ctx :env) :janet-rt) + (let [e (make-env jolt-runtime-env)] + (put (ctx :env) :janet-rt e) + e)) + (make-env jolt-runtime-env))) + +(def- core-renames + # Compile mode emits NATIVE Janet ops for the hot numeric primitives (+,-,* + # and the comparisons), which match Jolt's semantics for numbers and are + # ~10-20x faster than the variadic core fns. Trade-off: the strict non-number + # checks (e.g. (< nil 1) throwing) are relaxed under compilation — a + # documented perf-mode divergence. = / not= / quot / rem / mod / division stay + # as core fns (their semantics differ from Janet's). + @{"+" "+" + "-" "-" + "*" "*" + "/" "core-/" + "inc" "core-inc" + "dec" "core-dec" + "=" "core-=" + "not=" "core-not=" + "<" "<" + ">" ">" + "<=" "<=" + ">=" ">=" + "nil?" "core-nil?" + "not" "core-not" + "some?" "core-some?" + "string?" "core-string?" + "number?" "core-number?" + "fn?" "core-fn?" + "keyword?" "core-keyword?" + "symbol?" "core-symbol?" + "vector?" "core-vector?" + "map?" "core-map?" + "seq?" "core-seq?" + "coll?" "core-coll?" + "first" "core-first" + "rest" "core-rest" + "next" "core-next" + "cons" "core-cons" + "conj" "core-conj" + "assoc" "core-assoc" + "dissoc" "core-dissoc" + "get" "core-get" + "get-in" "core-get-in" + "assoc-in" "core-assoc-in" + "update-in" "core-update-in" + "fnil" "core-fnil" + "contains?" "core-contains?" + "count" "core-count" + "empty?" "core-empty?" + "every?" "core-every?" + "seq" "core-seq" + "vec" "core-vec" + "map" "core-map" + "filter" "core-filter" + "remove" "core-remove" + "reduce" "core-reduce" + "apply" "core-apply" + "str" "core-str" + "prn" "core-prn" + "pr-str" "core-pr-str" + "println" "core-println" + "print" "core-print" + "identity" "core-identity" + "comp" "core-comp" + "partial" "core-partial" + "complement" "core-complement" + "constantly" "core-constantly" + "memoize" "core-memoize" + "range" "core-range" + "take" "core-take" + "drop" "core-drop" + "take-while" "core-take-while" + "drop-while" "core-drop-while" + "interpose" "core-interpose" + "nth" "core-nth" + "mapcat" "core-mapcat" + "apply" "core-apply" + "trampoline" "core-trampoline" + "list" "core-list" + "name" "core-name" + "subs" "core-subs" + "reverse" "core-reverse" + "into" "core-into" + "merge" "core-merge" + "merge-with" "core-merge-with" + "keys" "core-keys" + "vals" "core-vals" + "zipmap" "core-zipmap" + "select-keys" "core-select-keys" + "max" "core-max" + "min" "core-min" + "odd?" "core-odd?" + "even?" "core-even?" + "zero?" "core-zero?" + "pos?" "core-pos?" + "neg?" "core-neg?" + "true?" "core-true?" + "false?" "core-false?" + "identical?" "core-identical?" + "quot" "core-quot" + "rem" "core-rem" + "mod" "core-mod"}) + +(defn- literal? + [form] + (or (nil? form) (= true form) (= false form) + (number? form) (string? form) (keyword? form) (bytes? form) (buffer? form))) + +(defn- special-form? + [name] + (or (= name "quote") (= name "syntax-quote") (= name "do") + (= name "if") (= name "def") (= name "defmacro") (= name "fn*") + (= name "let*") (= name "loop*") (= name "recur") (= name "throw") + (= name "try") (= name "set!") (= name "var") (= name ".") + (= name "eval") + (= name "new") (= name "deftype") (= name "instance?") + (= name "defmulti") (= name "defmethod") (= name "locking") + (= name "prefer-method") (= name "remove-method") (= name "remove-all-methods"))) + +# Forms the compiler can't compile correctly: definitional/stateful special +# forms and macros that mutate the context or build runtime values the emitter +# doesn't model (types, protocols, multimethods, dynamic binding, host interop). +# analyze-form throws uncompilable on these so the enclosing top-level form falls +# back to the interpreter — which handles them — instead of silently miscompiling. +# (Top-level occurrences are usually routed straight to the interpreter by +# loader/stateful-head?; this also covers them nested inside compiled forms.) +(def- uncompilable-heads + (let [t @{}] + # Interpreter special forms the compiler does NOT itself implement (it + # handles quote/do/if/def/fn*/let*/loop*/recur/throw/try). Kept in sync with + # eval-form's special-form match in evaluator.janet. + (each n ["syntax-quote" "unquote" "unquote-splicing" "eval" "read-string" + "macroexpand-1" "defonce" "defmacro" "deftype" "defmulti" + "defmethod" "prefer-method" "remove-method" "remove-all-methods" + "get-method" "methods" + # var-get/var-set/var?/alter-var-root/alter-meta!/reset-meta!/ + # find-var/intern are plain clojure.core fns now (core-bindings + + # install-stateful-fns!) — ordinary invokes, no punt (Stage 2 tier 6). + "satisfies?" "instance?" "set!" "var" + "ns" "in-ns" "require" "create-ns" "remove-ns" + "find-ns" "all-ns" "the-ns" "resolve" + "ns-resolve" "ns-aliases" "ns-imports" "ns-interns" + "locking" "new" + # Definitional/host macros that mutate context or build runtime + # values the emitter doesn't model. + "defrecord" "defprotocol" "definterface" "reify" "proxy" + "extend-type" "extend-protocol" "extend" "gen-class" "import" + "use" "refer" "monitor-enter" "monitor-exit" "binding" "." + # letfn needs all its fns in scope simultaneously (mutual + # recursion); the sequential let* the compiler would build can't + # express that, so interpret it. + "letfn"] + (put t n true)) + t)) + +(defn- uncompilable-head? [name] (get uncompilable-heads name)) + +# ============================================================ +# Macro resolution +# ============================================================ + +(defn- resolve-macro + [ctx sym-s] + (when ctx + (let [name (sym-s :name) + ns-sym (sym-s :ns)] + (if ns-sym + # Resolve :as aliases (e.g. (t/is …) where t aliases clojure.test) so + # aliased macros are recognized as macros — matching the interpreter's + # resolve-var — rather than miscompiled as a value ref to the macro var. + (let [cur (ctx-find-ns ctx (ctx-current-ns ctx)) + aliased (ns-import-lookup cur ns-sym) + target-ns (ctx-find-ns ctx (or aliased ns-sym)) + v (ns-find target-ns name)] + (if (and v (var-macro? v)) v)) + (let [current-ns-name (ctx-current-ns ctx) + current-ns (ctx-find-ns ctx current-ns-name) + v (ns-find current-ns name)] + (if v + (if (var-macro? v) v) + (let [core-ns (ctx-find-ns ctx "clojure.core") + cv (ns-find core-ns name)] + (if (and cv (var-macro? cv)) cv)))))))) + +# Loop counter for generating unique loop function names +(var loop-counter 0) + +(defn- make-loop-name + [] + (let [name (string "_loop_" loop-counter)] + (++ loop-counter) + name)) + +(defn- make-gensym + "A fresh, collision-proof Janet symbol name for compiler-introduced bindings + (recur targets, arity-dispatch arg vectors). The leading `_jolt$` can't appear + in a Clojure source symbol, so these never shadow user names." + [prefix] + (let [name (string "_jolt$" prefix "_" loop-counter)] + (++ loop-counter) + name)) + +# ============================================================ +# Syntax-quote expansion +# ============================================================ + +(defn- sq-list? + "Check if form is a (unquote ...) or (unquote-splicing ...) call." + [form] + (and (array? form) (> (length form) 0) + (struct? (first form)) (= :symbol ((first form) :jolt/type)) + (or (= "unquote" ((first form) :name)) + (= "unquote-splicing" ((first form) :name))))) + +(defn- sq-has-unquote? + "Check if any item in a collection is an unquote/unquote-splicing form." + [items] + (var found false) (var i 0) + (while (and (< i (length items)) (not found)) + (if (sq-list? (in items i)) (set found true)) (++ i)) + found) + +(defn- sq-resolve-sym + "Qualify an unqualified symbol with the current namespace." + [sym-s ctx] + (if (and ctx (nil? (sym-s :ns))) + {:jolt/type :symbol :ns (ctx-current-ns ctx) :name (sym-s :name)} + sym-s)) + +(defn- syntax-quote-expand + "Expand a syntax-quoted form into a plain Clojure form. + Simple forms are wrapped in (quote ...). Forms with unquote produce + (concat (list ...) ...) calls." + [form ctx] + (cond + # unquote → just the inner expression + (and (array? form) (> (length form) 0) + (struct? (first form)) (= :symbol ((first form) :jolt/type)) + (= "unquote" ((first form) :name))) + (in form 1) + + # unquote-splicing → just the inner expression + (and (array? form) (> (length form) 0) + (struct? (first form)) (= :symbol ((first form) :jolt/type)) + (= "unquote-splicing" ((first form) :name))) + (in form 1) + + # Literals → (quote literal) + (or (nil? form) (= true form) (= false form) + (number? form) (string? form) (keyword? form)) + [{:jolt/type :symbol :ns nil :name "quote"} form] + + # Symbols → (quote resolved-symbol) + (and (struct? form) (= :symbol (form :jolt/type))) + [{:jolt/type :symbol :ns nil :name "quote"} (sq-resolve-sym form ctx)] + + # Lists/arrays with unquote → (concat (list ...) (list ...) ...) + (array? form) + (if (sq-has-unquote? form) + (let [items (map |(syntax-quote-expand $ ctx) form) + concat-args @[]] + (each item items + (array/push concat-args + [{:jolt/type :symbol :ns nil :name "list"} item])) + (if (> (length concat-args) 1) + (tuple ;(array/insert concat-args 0 + {:jolt/type :symbol :ns nil :name "concat"})) + (in concat-args 0))) + [{:jolt/type :symbol :ns nil :name "quote"} form]) + + # Vectors → (vec (concat (list ...) ...)) + (tuple? form) + (if (sq-has-unquote? form) + (let [items (map |(syntax-quote-expand $ ctx) form) + concat-args @[]] + (each item items + (array/push concat-args + [{:jolt/type :symbol :ns nil :name "list"} item])) + [{:jolt/type :symbol :ns nil :name "vec"} + (tuple ;(array/insert concat-args 0 + {:jolt/type :symbol :ns nil :name "concat"}))]) + [{:jolt/type :symbol :ns nil :name "quote"} form]) + + # Default → (quote form) + [{:jolt/type :symbol :ns nil :name "quote"} form])) + +# ============================================================ +# Analyzer +# ============================================================ + +(defn- plain-symbol? + "A bare Clojure symbol (not a destructuring pattern). `&` counts — it's the + varargs marker, which the emitter passes straight through to Janet." + [x] + (and (struct? x) (= :symbol (x :jolt/type)))) + +(defn- uncompilable + "Signal that the compiler can't (yet) handle this form. eval-one catches this + and falls back to the interpreter, which handles every form correctly. Throwing + here — rather than miscompiling — is what makes the hybrid path sound." + [reason] + (error (string "jolt/uncompilable: " reason))) + +# fn* analysis is large enough (optional self-name, multi-arity, varargs, recur +# targets) to live in its own helper. Forward-declared so the fn* case in +# analyze-form can call it; defined after analyze-form (which it recurses into). +(var analyze-fn nil) + +(defn analyze-form + "Analyze a Clojure form and return an AST node with :op key. + Takes bindings (table) and optional ctx (for macro expansion)." + [form bindings &opt ctx] + (default ctx nil) + (cond + (literal? form) + {:op :const :val form} + + (and (struct? form) (= :symbol (form :jolt/type))) + (let [name (form :name) + ns (form :ns)] + (if ns + {:op :qualified-symbol :ns ns :name name} + (if (get bindings name) + {:op :local :name name} + (if (and (not (special-form? name)) (get core-renames name)) + {:op :core-symbol :name name :janet-name (get core-renames name)} + # A global reference. Resolution mirrors the interpreter's resolve-sym + # so compiled and interpreted code agree: + # 1. a jolt var in the current ns (which also holds refers) or + # clojure.core -> deref through the cell, so redefinition is + # visible to compiled callers (Janet early-binds plain symbols); + # 2. otherwise a binding in the runtime/Janet env (resolve-sym's own + # fallback — this is how int?, type, etc. resolve) -> emit it + # directly; + # 3. otherwise a forward reference -> intern a pending cell whose + # getter derefs at call time, once a later def fills it in. + # No ctx -> plain symbol. + (if ctx + (let [cur-ns (ctx-find-ns ctx (ctx-current-ns ctx)) + cell (or (ns-find cur-ns name) + (ns-find (ctx-find-ns ctx "clojure.core") name))] + (cond + cell {:op :var :name name :var cell} + (get jolt-runtime-env (symbol name)) + {:op :core-symbol :name name :janet-name name} + {:op :var :name name :var (ns-intern cur-ns name)})) + {:op :symbol :name name}))))) + + (array? form) + (let [first-form (first form) + head-name (if (and (struct? first-form) (= :symbol (first-form :jolt/type))) + (first-form :name) + nil)] + (when (and head-name (uncompilable-head? head-name)) + (uncompilable head-name)) + # Macro expansion + (if (and ctx head-name + (not (special-form? head-name)) + (resolve-macro ctx first-form)) + (let [macro-var (resolve-macro ctx first-form) + macro-fn (var-get macro-var) + expanded (apply macro-fn (tuple/slice form 1))] + (analyze-form expanded bindings ctx)) + (if head-name + (match head-name + "quote" {:op :quote :expr (in form 1)} + "throw" {:op :throw :val (analyze-form (in form 1) bindings ctx)} + "try" (let [body-form (in form 1) + clauses (tuple/slice form 2) + n (length clauses)] + (var catch-sym nil) + (var catch-body nil) + (var finally-body nil) + (var i 0) + (while (< i n) + (let [clause (in clauses i) + head (first clause)] + (if (and (struct? head) (= :symbol (head :jolt/type))) + (match (head :name) + "catch" (do + (set catch-sym (in clause 2)) + (set catch-body (tuple/slice clause 3))) + "finally" (set finally-body (tuple/slice clause 1))))) + (++ i)) + (let [catch-bindings (if catch-sym + (do + (var cb @{}) + (loop [[k v] :pairs bindings] (put cb k v)) + (put cb (catch-sym :name) :jolt/local) + cb) + nil)] + {:op :try + :body (analyze-form body-form bindings ctx) + :catch-sym (if catch-sym (catch-sym :name)) + :catch-body (if catch-body + (map |(analyze-form $ catch-bindings ctx) catch-body)) + :finally-body (if finally-body + (map |(analyze-form $ bindings ctx) finally-body))})) + "recur" (let [args (map |(analyze-form $ bindings ctx) (tuple/slice form 1)) + loop-name (get bindings :jolt/current-loop)] + {:op :recur :args args :loop-name loop-name}) + "do" (let [all-statements (array/slice form 1) + n (length all-statements) + analyzed (map |(analyze-form $ bindings ctx) all-statements)] + (if (= n 0) + {:op :const :val nil} # (do) -> nil + {:op :do + :statements (array/slice analyzed 0 (- n 1)) + :ret (in analyzed (- n 1))})) + "if" {:op :if + :test (analyze-form (in form 1) bindings ctx) + :then (analyze-form (in form 2) bindings ctx) + :else (if (> (length form) 3) + (analyze-form (in form 3) bindings ctx) + {:op :const :val nil})} + "def" (let [name-sym (in form 1) + nm (if (struct? name-sym) (name-sym :name) (string name-sym)) + # Create/find the var cell first so a recursive init body + # self-references the same cell. + cell (when ctx (ns-intern (ctx-find-ns ctx (ctx-current-ns ctx)) nm)) + # (def x) with no init (declare) -> nil. + init-form (if (> (length form) 2) (in form 2) nil)] + {:op :def :name name-sym :var cell + :init (analyze-form init-form bindings ctx)}) + "fn*" (analyze-fn form bindings ctx) + "let*" (let [bind-vec (in form 1) + body-exprs (tuple/slice form 2) + # Accumulate scope as we go so a later binding's init can + # reference an earlier binding (sequential let scoping). + acc (do (var bb @{}) (loop [[k v] :pairs bindings] (put bb k v)) bb) + binding-pairs (do + (var pairs @[]) + (var i 0) + (let [n (length bind-vec)] + (while (< i n) + (let [sym-s (in bind-vec i) + _ (unless (plain-symbol? sym-s) + (uncompilable "destructuring let binding")) + name (sym-s :name) + val-form (if (< (+ i 1) n) (in bind-vec (+ i 1)) nil) + val-ast (if val-form (analyze-form val-form acc ctx) {:op :const :val nil})] + (array/push pairs {:name name :init val-ast}) + (put acc name :jolt/local) + (+= i 2)))) + pairs) + body-bindings acc + analyzed-body (map |(analyze-form $ body-bindings ctx) body-exprs) + n-body (length analyzed-body)] + {:op :let + :binding-pairs binding-pairs + :body (if (> n-body 1) + {:op :do + :statements (array/slice analyzed-body 0 (- n-body 1)) + :ret (last analyzed-body)} + (first analyzed-body))}) + "loop*" (let [bind-vec (in form 1) + loop-name (make-loop-name) + acc (do (var bb @{}) (loop [[k v] :pairs bindings] (put bb k v)) bb) + binding-pairs (do + (var pairs @[]) + (var i 0) + (let [n (length bind-vec)] + (while (< i n) + (let [sym-s (in bind-vec i) + _ (unless (plain-symbol? sym-s) + (uncompilable "destructuring loop binding")) + name (sym-s :name) + val-form (if (< (+ i 1) n) (in bind-vec (+ i 1)) nil) + val-ast (if val-form (analyze-form val-form acc ctx) {:op :const :val nil})] + (array/push pairs {:name name :init val-ast}) + (put acc name :jolt/local) + (+= i 2)))) + pairs) + param-names (map |($ :name) binding-pairs) + body-bindings (do + (var bb @{}) + (loop [[k v] :pairs bindings] (put bb k v)) + (each bp binding-pairs + (put bb (bp :name) :jolt/local)) + (put bb :jolt/current-loop loop-name) + bb) + body-exprs (tuple/slice form 2) + analyzed-body (map |(analyze-form $ body-bindings ctx) body-exprs) + n-body (length analyzed-body)] + {:op :loop + :loop-name loop-name + :param-names param-names + :init-vals (map |($ :init) binding-pairs) + :body (if (> n-body 1) + {:op :do + :statements (array/slice analyzed-body 0 (- n-body 1)) + :ret (last analyzed-body)} + (first analyzed-body))}) + (let [f-ast (analyze-form first-form bindings ctx) + args (map |(analyze-form $ bindings ctx) (tuple/slice form 1))] + {:op :invoke :fn f-ast :args args})) + (let [f-ast (analyze-form first-form bindings ctx) + args (map |(analyze-form $ bindings ctx) (tuple/slice form 1))] + {:op :invoke :fn f-ast :args args})))) + + (tuple? form) + (let [items (map |(analyze-form $ bindings ctx) form)] + {:op :vector :items items}) + + (struct? form) + (cond + (= :jolt/set (form :jolt/type)) + {:op :set :items (map |(analyze-form $ bindings ctx) (form :value))} + (= :jolt/char (form :jolt/type)) + {:op :const :val form} + # Tagged literals (#"regex", data readers) need runtime construction the + # compiler doesn't model — interpret them. + (form :jolt/type) + (uncompilable (string "tagged literal " (form :jolt/type))) + # Plain map literal: keys and values are expressions to evaluate. + {:op :map + :pairs (map (fn [k] [(analyze-form k bindings ctx) + (analyze-form (get form k) bindings ctx)]) + (keys form))}) + + {:op :const :val form})) + +(defn- parse-fn-params + "Split a param vector into fixed param names and an optional rest name. Only + plain symbols are handled here; destructuring params signal uncompilable so the + whole fn falls back to the interpreter." + [params] + (unless (tuple? params) (uncompilable "fn params not a vector")) + (def fixed @[]) + (var rest-name nil) + (var i 0) + (def n (length params)) + (while (< i n) + (def p (in params i)) + (unless (plain-symbol? p) (uncompilable "destructuring fn params")) + (if (= "&" (p :name)) + (do + (++ i) + (when (< i n) + (def r (in params i)) + (unless (plain-symbol? r) (uncompilable "destructuring fn rest param")) + (set rest-name (r :name))) + (++ i)) + (do (array/push fixed (p :name)) (++ i)))) + {:fixed (tuple/slice fixed) :rest rest-name}) + +(set analyze-fn + (fn analyze-fn [form bindings ctx] + # (fn* name? params-or-clauses...) where a clause is (params body...). + (def named? (plain-symbol? (in form 1))) + (def fn-name (when named? ((in form 1) :name))) + (def idx (if named? 2 1)) + (def first-clause (in form idx)) + # Single arity: a param vector at idx. Multi arity: each remaining element is + # an (params body...) list. + (def raw-clauses + (cond + (tuple? first-clause) [[first-clause (tuple/slice form (+ idx 1))]] + (array? first-clause) (map |[(in $ 0) (tuple/slice $ 1)] (tuple/slice form idx)) + (uncompilable "fn: unexpected param shape"))) + (def multi (> (length raw-clauses) 1)) + # Public name: the symbol the fn binds to itself. Single-arity fns recur + # straight into this name; multi-arity fns recur into a per-arity inner fn so + # recur stays in its own arity rather than re-dispatching. + (def outer-name (or fn-name (make-gensym "fn"))) + (def arities + (map + (fn [clause] + (def pinfo (parse-fn-params (in clause 0))) + (def fixed (pinfo :fixed)) + (def rest-name (pinfo :rest)) + (def recur-name + (if (and (not multi) (not rest-name)) outer-name (make-gensym "arity"))) + (def body-bindings + (do + (var bb @{}) + (loop [[k v] :pairs bindings] (put bb k v)) + (when fn-name (put bb fn-name :jolt/local)) + (each pn fixed (put bb pn :jolt/local)) + (when rest-name (put bb rest-name :jolt/local)) + (put bb :jolt/current-loop recur-name) + bb)) + (def body-exprs (in clause 1)) + (def analyzed (map |(analyze-form $ body-bindings ctx) body-exprs)) + (def n-body (length analyzed)) + {:param-names fixed + :rest-name rest-name + :n-fixed (length fixed) + :recur-name recur-name + :body (cond + (= 0 n-body) {:op :const :val nil} + (= 1 n-body) (first analyzed) + {:op :do + :statements (array/slice analyzed 0 (- n-body 1)) + :ret (last analyzed)})}) + raw-clauses)) + {:op :fn :name outer-name :fn-name fn-name :multi multi :arities arities})) + +# ============================================================ +# Emitter — AST → Janet source string +# ============================================================ + +(var emit-ast nil) + +(defn- emit-const-str [val buf] + (cond + (nil? val) (buffer/push buf "nil") + (= true val) (buffer/push buf "true") + (= false val) (buffer/push buf "false") + (string? val) (do (buffer/push buf "\"") (buffer/push buf val) (buffer/push buf "\"")) + (keyword? val) (do (buffer/push buf ":") (buffer/push buf (string val))) + (buffer/push buf (string val)))) + +(defn- emit-do-str [statements ret buf] + (buffer/push buf "(do ") + (var i 0) + (let [n (length statements)] + (while (< i n) + (emit-ast (in statements i) buf) + (buffer/push buf " ") + (++ i))) + (when ret (emit-ast ret buf)) + (buffer/push buf ")")) + +(defn- emit-if-str [test then else buf] + (buffer/push buf "(if ") + (emit-ast test buf) (buffer/push buf " ") + (emit-ast then buf) + (when else (buffer/push buf " ") (emit-ast else buf)) + (buffer/push buf ")")) + +(defn- emit-def-str [name-sym init buf] + (buffer/push buf "(def ") (buffer/push buf (name-sym :name)) + (buffer/push buf " ") (emit-ast init buf) (buffer/push buf ")")) + +(defn- emit-arity-str [ar buf] + (buffer/push buf "[") + (var i 0) + (let [n (length (ar :param-names))] + (while (< i n) + (buffer/push buf (in (ar :param-names) i)) + (when (or (< (+ i 1) n) (ar :rest-name)) (buffer/push buf " ")) + (++ i))) + (when (ar :rest-name) + (buffer/push buf "& ") (buffer/push buf (ar :rest-name))) + (buffer/push buf "] ") + (emit-ast (ar :body) buf)) + +# Debug/source rendering. Single arity matches the original `(fn [params] body)` +# shape; multi-arity renders each arity as a clause. This path is for inspection +# (compile-string); the data emitter is the one that actually runs. +(defn- emit-fn-str [ast buf] + (def arities (ast :arities)) + (if (ast :multi) + (do + (buffer/push buf "(fn") + (each ar arities + (buffer/push buf " (") (emit-arity-str ar buf) (buffer/push buf ")")) + (buffer/push buf ")")) + (do + (buffer/push buf "(fn ") (emit-arity-str (first arities) buf) (buffer/push buf ")")))) + +(defn- emit-let-str [binding-pairs body buf] + (buffer/push buf "(let [") + (var i 0) + (let [n (length binding-pairs)] + (while (< i n) + (let [bp (in binding-pairs i)] + (buffer/push buf (bp :name)) (buffer/push buf " ") + (emit-ast (bp :init) buf) + (when (< (+ i 1) n) (buffer/push buf " "))) + (++ i))) + (buffer/push buf "] ") (emit-ast body buf) (buffer/push buf ")")) + +(defn- emit-throw-str [val buf] + (buffer/push buf "(error ") (emit-ast val buf) (buffer/push buf ")")) + +(defn- emit-try-str [body catch-sym catch-body finally-body buf] + (buffer/push buf "(try ") + (emit-ast body buf) + (when catch-sym + (buffer/push buf " ([") + (buffer/push buf catch-sym) + (buffer/push buf "] ") + (if (= 1 (length catch-body)) + (emit-ast (first catch-body) buf) + (do + (buffer/push buf "(do ") + (var i 0) + (let [n (length catch-body)] + (while (< i n) + (emit-ast (in catch-body i) buf) + (when (< (+ i 1) n) (buffer/push buf " ")) + (++ i))) + (buffer/push buf ")"))) + (buffer/push buf ")")) + (buffer/push buf ")")) + +(defn- emit-loop-str [loop-name param-names init-vals body buf] + (buffer/push buf "(do (var ") (buffer/push buf loop-name) (buffer/push buf " nil) ") + (buffer/push buf "(set ") (buffer/push buf loop-name) (buffer/push buf " (fn [") + (var i 0) + (let [n (length param-names)] + (while (< i n) + (buffer/push buf (in param-names i)) + (when (< (+ i 1) n) (buffer/push buf " ")) + (++ i))) + (buffer/push buf "] ") + (emit-ast body buf) + (buffer/push buf ")) (") + (buffer/push buf loop-name) + (each iv init-vals + (buffer/push buf " ") + (emit-ast iv buf)) + (buffer/push buf "))")) + +(defn- emit-recur-str [args loop-name buf] + (buffer/push buf "(") (buffer/push buf loop-name) + (each arg args + (buffer/push buf " ") + (emit-ast arg buf)) + (buffer/push buf ")")) + +(defn- emit-invoke-str [f-ast args buf] + (buffer/push buf "(") (emit-ast f-ast buf) + (each arg args (buffer/push buf " ") (emit-ast arg buf)) + (buffer/push buf ")")) + +(defn- emit-symbol-str [name buf] (buffer/push buf name)) +(defn- emit-local-str [name buf] (buffer/push buf name)) +(defn- emit-core-symbol-str [janet-name buf] (buffer/push buf janet-name)) + +(defn- emit-qualified-symbol-str [ns name buf] + (buffer/push buf "(ns-get \"") (buffer/push buf ns) + (buffer/push buf "\" \"") (buffer/push buf name) (buffer/push buf "\")")) + +(defn- emit-vector-str [items buf] + (buffer/push buf "[") + (var i 0) + (let [n (length items)] + (while (< i n) + (emit-ast (in items i) buf) + (when (< (+ i 1) n) (buffer/push buf " ")) + (++ i))) + (buffer/push buf "]")) + +(defn- emit-map-str [pairs buf] + (buffer/push buf "(build-map-literal") + (each [k v] pairs + (buffer/push buf " ") (emit-ast k buf) + (buffer/push buf " ") (emit-ast v buf)) + (buffer/push buf ")")) + +(defn- emit-set-str [items buf] + (buffer/push buf "(make-phs") + (each it items (buffer/push buf " ") (emit-ast it buf)) + (buffer/push buf ")")) + +(defn- raw-form->janet + "Convert a Jolt reader form to a Janet data structure for quoting." + [form] + (cond + (and (struct? form) (= :symbol (form :jolt/type))) + (if (form :ns) + (symbol (string (form :ns) "/" (form :name))) + (symbol (form :name))) + (array? form) + (tuple/slice (tuple ;(map raw-form->janet form))) + (tuple? form) + (tuple/slice (tuple ;(map raw-form->janet form))) + form)) + +(defn- emit-quote-str [expr buf] + (buffer/push buf "'") + (def janet-val (raw-form->janet expr)) + (cond + (symbol? janet-val) (buffer/push buf (string janet-val)) + (number? janet-val) (buffer/push buf (string janet-val)) + (string? janet-val) (do (buffer/push buf "\"") (buffer/push buf janet-val) (buffer/push buf "\"")) + (keyword? janet-val) (do (buffer/push buf ":") (buffer/push buf (string janet-val))) + (nil? janet-val) (buffer/push buf "nil") + (= true janet-val) (buffer/push buf "true") + (= false janet-val) (buffer/push buf "false") + (buffer/push buf (string janet-val)))) + +(set emit-ast + (fn [ast buf] + (match (ast :op) + :const (emit-const-str (ast :val) buf) + :symbol (emit-symbol-str (ast :name) buf) + :var (emit-symbol-str (ast :name) buf) + :local (emit-local-str (ast :name) buf) + :core-symbol (emit-core-symbol-str (ast :janet-name) buf) + :qualified-symbol (emit-qualified-symbol-str (ast :ns) (ast :name) buf) + :do (emit-do-str (ast :statements) (ast :ret) buf) + :if (emit-if-str (ast :test) (ast :then) (ast :else) buf) + :def (emit-def-str (ast :name) (ast :init) buf) + :fn (emit-fn-str ast buf) + :let (emit-let-str (ast :binding-pairs) (ast :body) buf) + :throw (emit-throw-str (ast :val) buf) + :try (emit-try-str (ast :body) (ast :catch-sym) (ast :catch-body) (ast :finally-body) buf) + :loop (emit-loop-str (ast :loop-name) (ast :param-names) (ast :init-vals) (ast :body) buf) + :recur (emit-recur-str (ast :args) (ast :loop-name) buf) + :invoke (emit-invoke-str (ast :fn) (ast :args) buf) + :vector (emit-vector-str (ast :items) buf) + :map (emit-map-str (ast :pairs) buf) + :set (emit-set-str (ast :items) buf) + :quote (emit-quote-str (ast :expr) buf) + (buffer/push buf (string "/* unhandled op: " (ast :op) " */"))))) + +# ============================================================ +# Emitter — AST → Janet data structure (for direct eval) +# ============================================================ + +(var emit-expr nil) + +(defn- emit-const-expr [val] val) +(defn- emit-symbol-expr [name] (symbol name)) +(defn- emit-local-expr [name] (symbol name)) + +# Native Janet numeric ops: emit them as SYMBOLS (not inlined fn values) so +# Janet's compiler recognizes the primitive and uses its fast arithmetic/compare +# opcode rather than a function call. +(def- native-ops @{"+" true "-" true "*" true "<" true ">" true "<=" true ">=" true}) + +(defn- emit-core-symbol-expr [janet-name] + (if (get native-ops janet-name) + (symbol janet-name) + # Resolve the core-* function value from the compiler's runtime env (where + # `(use ./core)` bound them all) rather than a hand-maintained table that can + # drift out of sync. A name with no binding falls back to the interpreter. + (let [b (get jolt-runtime-env (symbol janet-name))] + (if b (b :value) + (uncompilable (string "core fn not found: " janet-name)))))) + +(defn- emit-qualified-symbol-expr [ns name] + (error (string "Cannot eval qualified symbol at compile time: " ns "/" name))) + +(defn- emit-do-expr [statements ret] + (def exprs @['do]) + (each s statements (array/push exprs (emit-expr s))) + (when ret (array/push exprs (emit-expr ret))) + (tuple/slice (tuple ;exprs))) + +(defn- emit-if-expr [test then else] + (def exprs @['if]) + (array/push exprs (emit-expr test)) + (array/push exprs (emit-expr then)) + (when else (array/push exprs (emit-expr else))) + (tuple/slice (tuple ;exprs))) + +(defn- emit-def-expr [name-sym init] + ['def (symbol (name-sym :name)) (emit-expr init)]) + +# Var-indirection: a global reference derefs its cell at call time, and a def +# sets the same cell's root and returns it (Clojure's #'var). Janet COPIES table +# constants when compiling but references functions, so we embed memoized +# getter/setter CLOSURES over the cell (by reference) rather than the cell itself. +(defn- var-getter [cell] + (or (get cell :jolt/getter) + (let [g (fn [] (var-get cell))] (put cell :jolt/getter g) g))) +(defn- var-setter [cell] + (or (get cell :jolt/setter) + (let [s (fn [v] (bind-root cell v) cell)] (put cell :jolt/setter s) s))) +(defn- emit-var-expr [cell] (tuple (var-getter cell))) +(defn- emit-def-var-expr [cell init] (tuple (var-setter cell) (emit-expr init))) + +# An arity compiles to a named Janet fn whose name is its recur target — a +# recur is just a self-call (Janet tail-calls it). The rest param is an ordinary +# param holding a seq (not Janet `&`), so `(recur fixed... rest-seq)` works the +# way Clojure recur into a variadic arity does. +(defn- emit-arity-fn [ar] + (def ps @[]) + (each pn (ar :param-names) (array/push ps (symbol pn))) + (when (ar :rest-name) (array/push ps (symbol (ar :rest-name)))) + ['fn (symbol (ar :recur-name)) (tuple/slice ps) (emit-expr (ar :body))]) + +# Invoke an arity's fn with the actual args pulled out of the dispatch vector: +# fixed params by index, rest as a tuple slice. +(defn- emit-arity-invoke [ar jargs] + (def call @[(emit-arity-fn ar)]) + (for i 0 (ar :n-fixed) (array/push call ['in jargs i])) + (when (ar :rest-name) (array/push call ['tuple/slice jargs (ar :n-fixed)])) + (tuple/slice call)) + +(defn- emit-fn-expr [ast] + (def arities (ast :arities)) + (cond + # Single fixed arity — the common, hot case. Emit the arity fn directly + # (its name is the public name and the recur target); no dispatch overhead. + (and (not (ast :multi)) (not ((first arities) :rest-name))) + (emit-arity-fn (first arities)) + # Single variadic arity: a thin wrapper collects the call's args so the rest + # seq can be built, then hands off to the arity fn. + (not (ast :multi)) + (let [jargs (symbol (make-gensym "args"))] + ['fn (symbol (ast :name)) ['& jargs] (emit-arity-invoke (first arities) jargs)]) + # Multi-arity: dispatch on arg count. Fixed arities match exactly; the (one) + # variadic arity matches >= its fixed count and goes last. + (let [jargs (symbol (make-gensym "args")) + n-sym (symbol (make-gensym "n")) + cond-form @['cond]] + (each ar arities + (if (ar :rest-name) + (array/push cond-form ['>= n-sym (ar :n-fixed)]) + (array/push cond-form ['= n-sym (ar :n-fixed)])) + (array/push cond-form (emit-arity-invoke ar jargs))) + (array/push cond-form ['error "Wrong number of args passed to fn"]) + ['fn (symbol (ast :name)) ['& jargs] + ['let [n-sym ['length jargs]] (tuple/slice cond-form)]]))) + +(defn- emit-let-expr [binding-pairs body] + (def bind-tuple @[]) + (each bp binding-pairs + (array/push bind-tuple (symbol (bp :name))) + (array/push bind-tuple (emit-expr (bp :init)))) + ['let (tuple/slice (tuple ;bind-tuple)) (emit-expr body)]) + +(defn- emit-throw-expr [val] + ['error (emit-expr val)]) + +(defn- emit-try-expr [body catch-sym catch-body finally-body] + # Janet try: (try body ([err] handler-body)) + (def forms @['try (emit-expr body)]) + (when catch-sym + (def err-binding [(symbol catch-sym)]) + (def handler + (if (= 1 (length catch-body)) + (emit-expr (first catch-body)) + (do + (def do-body @['do]) + (each cb catch-body (array/push do-body (emit-expr cb))) + (tuple/slice (tuple ;do-body))))) + (array/push forms [(tuple ;err-binding) handler])) + (when finally-body + (def finally-do @['do]) + (each fb finally-body (array/push finally-do (emit-expr fb))) + (array/push forms (tuple/slice (tuple ;finally-do)))) + (tuple/slice (tuple ;forms))) + +(defn- emit-loop-expr [loop-name param-names init-vals body] + # Emit: (do (var loop-name nil) (set loop-name (fn [params] body)) (loop-name init-vals...)) + (def param-syms (map symbol param-names)) + (def loop-sym (symbol loop-name)) + (def body-emitted (emit-expr body)) + # For recur calls, rewrite (recur arg1 arg2) → (loop-name arg1 arg2) + # This is done by the :recur op handler below which uses the loop-name from ast + ['do + ['var loop-sym nil] + ['set loop-sym ['fn (tuple/slice (tuple ;param-syms)) body-emitted]] + (tuple ;(array/insert (map emit-expr init-vals) 0 loop-sym))]) + +(defn- emit-recur-expr [args loop-name] + # Emit: (loop-name arg1 arg2...) + (def exprs @[(symbol loop-name)]) + (each arg args (array/push exprs (emit-expr arg))) + (tuple/slice (tuple ;exprs))) + +(defn- emit-invoke-expr [f-ast args] + # Emit a DIRECT Janet call (f arg…) when the callee is a function reference — + # a core op/fn, a local/global symbol, or an fn literal — so native ops keep + # their fast opcodes and recursion is a direct call. Fall back to jolt-call + # only when the head is a keyword/collection literal in call position (an IFn + # that needs runtime lookup), e.g. (:k m) or ({:a 1} :a). + (def direct (case (f-ast :op) + :core-symbol true :symbol true :var true :local true + :qualified-symbol true :fn true + false)) + (def f (emit-expr f-ast)) + (def exprs (if direct @[f] @[jolt-call f])) + (each arg args (array/push exprs (emit-expr arg))) + (tuple/slice (tuple ;exprs))) + +# A vector literal builds a mode-appropriate jolt vector (pvec when immutable, +# array when mutable) via make-vec — the same constructor the interpreter uses — +# so compiled and interpreted vectors share one representation. (Emitting a bare +# Janet tuple diverged: type-strict ops like rseq reject tuples.) +(defn- emit-vector-expr [items] + (def t @['tuple]) + (each item items (array/push t (emit-expr item))) + [make-vec (tuple/slice t)]) + +# Build a jolt map literal from evaluated alternating k/v args, mirroring the +# interpreter (eval-form's map-literal case): a Janet struct unless a key is a +# collection, in which case a phm so the key compares by value. Embedded as a +# function constant in emitted code (functions marshal by reference). +(defn build-map-literal [& kvs] + # phm (not a Janet struct) when a key is a collection (value-based hashing) or a + # key/value is nil (structs drop nil; phm preserves it, matching Clojure). + (var need-phm false) + (var ki 0) + (while (< ki (length kvs)) + (let [kk (in kvs ki) vv (in kvs (+ ki 1))] + (when (or (table? kk) (array? kk) (nil? kk) (nil? vv)) (set need-phm true))) + (+= ki 2)) + (if need-phm + (do (var m (make-phm)) (var j 0) + (while (< j (length kvs)) (set m (phm-assoc m (in kvs j) (in kvs (+ j 1)))) (+= j 2)) + m) + (struct ;kvs))) + +(defn- emit-map-expr [pairs] + (def call @[build-map-literal]) + (each [k v] pairs + (array/push call (emit-expr k)) + (array/push call (emit-expr v))) + (tuple/slice call)) + +(defn- emit-set-expr [items] + (tuple/slice (tuple make-phs ;(map emit-expr items)))) + +(defn- emit-quote-expr [expr] + ['quote (raw-form->janet expr)]) + +(set emit-expr + (fn [ast] + (match (ast :op) + :const (emit-const-expr (ast :val)) + :symbol (emit-symbol-expr (ast :name)) + :var (emit-var-expr (ast :var)) + :local (emit-local-expr (ast :name)) + :core-symbol (emit-core-symbol-expr (ast :janet-name)) + :qualified-symbol (emit-qualified-symbol-expr (ast :ns) (ast :name)) + :do (emit-do-expr (ast :statements) (ast :ret)) + :if (emit-if-expr (ast :test) (ast :then) (ast :else)) + :def (if (ast :var) (emit-def-var-expr (ast :var) (ast :init)) + (emit-def-expr (ast :name) (ast :init))) + :fn (emit-fn-expr ast) + :let (emit-let-expr (ast :binding-pairs) (ast :body)) + :throw (emit-throw-expr (ast :val)) + :try (emit-try-expr (ast :body) (ast :catch-sym) (ast :catch-body) (ast :finally-body)) + :loop (emit-loop-expr (ast :loop-name) (ast :param-names) (ast :init-vals) (ast :body)) + :recur (emit-recur-expr (ast :args) (ast :loop-name)) + :invoke (emit-invoke-expr (ast :fn) (ast :args)) + :vector (emit-vector-expr (ast :items)) + :map (emit-map-expr (ast :pairs)) + :set (emit-set-expr (ast :items)) + :quote (emit-quote-expr (ast :expr)) + (error (string "Unhandled op: " (ast :op)))))) + +# ============================================================ +# Public API +# ============================================================ + +(defn compile-form + "Compile a Clojure form to a Janet source string." + [form &opt ctx] + (default ctx nil) + (let [ast (analyze-form form @{} ctx) + buf @""] + (emit-ast ast buf) + (string buf))) + +(defn compile-ast + "Compile a Clojure form to an eval-able Janet data structure." + [form &opt ctx] + (default ctx nil) + (emit-expr (analyze-form form @{} ctx))) + +(defn compile-and-eval + "Compile a Clojure form and evaluate it as Janet. Globals resolve through Jolt + var cells (see analyze-form/:var), so compiled def/defn results are visible to + the interpreter (the cell is the namespace var), recursion self-references the + cell, and redefinition is seen by compiled callers — no separate interning or + named-fn rewrite needed." + [form ctx] + (eval (compile-ast form ctx) (ctx-janet-env ctx))) + +(defn eval-compiled + "Evaluate an already-compiled Janet form (the result of compile-ast) in the + context's compiled env. Split out from compile-and-eval so callers can guard + the compile step alone — see eval-one's hybrid fallback." + [compiled ctx] + (eval compiled (ctx-janet-env ctx))) diff --git a/src/jolt/config.janet b/src/jolt/config.janet new file mode 100644 index 0000000..f4e6a11 --- /dev/null +++ b/src/jolt/config.janet @@ -0,0 +1,15 @@ +# Build-time collection mode. +# +# Jolt can be built with either immutable (persistent) collections — proper +# Clojure value semantics — or fast Janet-native mutable collections. +# +# jpm build # immutable (default) +# JOLT_MUTABLE=1 jpm build # mutable +# +# This reads the environment at module-load time, so for a jpm-compiled +# executable the value is fixed when the binary is built (a true compile flag). +# `mutable?` is a constant, so the type-mode branches throughout core fold away. +(def mutable? (= "1" (os/getenv "JOLT_MUTABLE"))) + +# Convenience: immutable? is the default. +(def immutable? (not mutable?)) diff --git a/src/jolt/core.janet b/src/jolt/core.janet new file mode 100644 index 0000000..39937ae --- /dev/null +++ b/src/jolt/core.janet @@ -0,0 +1,3180 @@ +# Jolt Core Library +# Clojure-compatible core functions for the Jolt interpreter. + +(use ./types) +(use ./phm) +(use ./regex) +(use ./config) +(use ./pv) +(use ./plist) + +# ------------------------------------------------------------ +# Vector representation helpers +# +# In immutable mode a vector value is a structural-sharing persistent vector +# (pvec); in mutable mode it is a plain Janet array. Janet tuples may also still +# appear (e.g. literals that have not been routed through make-vec), so the read +# helpers below accept tuple, pvec and (mutable mode) array uniformly. +# ------------------------------------------------------------ + +(defn jvec? + "True when x is a vector VALUE. In immutable mode that is a persistent vector + or tuple; in mutable mode vectors are plain arrays (so vectors and lists share + one fast representation — `vector?` is true for both)." + [x] + (if mutable? + (or (array? x) (tuple? x)) + (or (tuple? x) (pvec? x)))) + +(defn vcount [x] (if (pvec? x) (pv-count x) (length x))) +(defn vnth [x i] (if (pvec? x) (pv-nth x i) (in x i))) + +(defn vview + "An indexed (tuple/array) view of a vector value, for iteration/slicing." + [x] + (if (pvec? x) (pv->array x) x)) + +(defn make-vec + "Build a vector value from a Janet array/tuple of elements, honoring the + build-time collection mode." + [xs] + (if mutable? (array ;xs) (pv-from-indexed xs))) + +(defn core-transient? + "True when x is a transient (a mutable scratch collection). See `transient`." + [x] + (and (table? x) (= :jolt/transient (get x :jolt/type)))) + +# Canonicalize a collection key/element to a value-hashable Janet struct/tuple so +# the PHM/PHS treat value-equal maps/vectors as the same key (Janet hashes tables +# by identity otherwise). Installed into phm via set-canonicalize-key!. +(var canon-key nil) +(set canon-key + (fn [k] + (cond + (pvec? k) (tuple ;(map canon-key (pv->array k))) + (plist? k) (tuple ;(map canon-key (pl->array k))) + (set? k) (do (def t @{}) (each e (phs-seq k) (put t (canon-key e) true)) (table/to-struct t)) + (phm? k) (do (def t @{}) (each pair (phm-entries k) (put t (canon-key (in pair 0)) (canon-key (in pair 1)))) (table/to-struct t)) + (and (table? k) (get k :jolt/deftype)) + (do (def t @{}) (each kk (keys k) (when (not= kk :jolt/deftype) (put t kk (canon-key (get k kk))))) (table/to-struct t)) + (struct? k) (do (def t @{}) (each kk (keys k) (put t (canon-key kk) (canon-key (get k kk)))) (table/to-struct t)) + (array? k) (tuple ;(map canon-key k)) + (tuple? k) (tuple ;(map canon-key k)) + k))) +(set-canonicalize-key! canon-key) + +# All [k v] entries of a map (struct or phm), nil-valued keys included. Use this +# instead of (keys (phm-to-struct m)) — phm-to-struct drops keys whose value is +# nil, which is exactly what Clojure maps must keep. +(defn- map-entries-of [m] + (if (phm? m) (phm-entries m) (map (fn [k] [k (in m k)]) (keys m)))) + +# assoc one entry onto a map value (struct or phm), preserving a nil key/value and +# value-comparing collection keys (promotes a struct to a phm when needed). A +# single-entry core-assoc usable by fns defined before core-assoc itself. +(defn- map-assoc1 [m k v] + (cond + (phm? m) (phm-assoc m k v) + (or (nil? k) (nil? v) (table? k) (array? k)) + (do (var p (make-phm)) (each ek (keys m) (set p (phm-assoc p ek (in m ek)))) (phm-assoc p k v)) + (do (def t (merge @{} m)) (put t k v) (table/to-struct t)))) + +# Build a map from a flat [k v k v ...] array: a phm when any key/value is nil or +# a key is a collection (value hashing); a struct otherwise. One O(n) pass. +(defn- kvs->map [kvs] + (var need-phm false) (var i 0) + (while (< i (length kvs)) + (let [k (in kvs i) v (in kvs (+ i 1))] + (when (or (nil? k) (nil? v) (table? k) (array? k)) (set need-phm true))) + (+= i 2)) + (if need-phm + (do (var m (make-phm)) (var j 0) + (while (< j (length kvs)) (set m (phm-assoc m (in kvs j) (in kvs (+ j 1)))) (+= j 2)) m) + (struct ;kvs))) + +(defn realize-for-iteration [c] + "Normalize a seqable to a Janet array/tuple for iteration: pvec -> array, + set -> seq, lazy-seq -> realized array; others pass through. Warning: will + loop on infinite lazy-seqs. Terminates on the empty cell, not on nil." + (cond + # nil is an empty seq in Clojure — iterating it yields nothing. + (nil? c) @[] + (pvec? c) (pv->array c) + (plist? c) (pl->array c) + (set? c) (phs-seq c) + (phm? c) (phm-entries c) + # byte array (Janet buffer) -> array of byte values + (buffer? c) (let [a @[]] (each x c (array/push a x)) a) + # struct map literal (no :jolt/type marker — not a symbol/char) -> entries + (and (struct? c) (nil? (get c :jolt/type))) (map (fn [k] (tuple k (get c k))) (keys c)) + (lazy-seq? c) + (do + (var items @[]) + (var cur c) + (var go true) + (while go + (let [cell (realize-ls cur)] + (if (or (nil? cell) (= :jolt/pending cell) (= 0 (length cell))) + (set go false) + (do + (array/push items (in cell 0)) + (let [rt (in cell 1)] + (if (nil? rt) (set go false) (set cur (make-lazy-seq rt)))))))) + items) + c)) + +# Syntax-quote form builders. The syntax-quote lowering (evaluator) emits calls to +# these so a `(...)/`[...] body is plain compilable code instead of an interpreted +# special form. A list FORM is a Janet array, a vector FORM a tuple (the reader's +# representation), so these build those types. Each concat part is either a 1-elem +# wrap (__sq1, a non-spliced item) or a spliced seq (~@), flattened in order. +(defn core-sq1 [x] @[x]) + +(defn core-sqcat [& parts] + (def r @[]) + (each p parts (each x (realize-for-iteration p) (array/push r x))) + r) + +(defn core-sqvec [& parts] + (def r @[]) + (each p parts (each x (realize-for-iteration p) (array/push r x))) + (tuple/slice r)) + +# Map builder: parts are alternating k v (no splicing in map syntax-quote). +(defn core-sqmap [& parts] (kvs->map (array ;parts))) + +# Set builder: like core-sqvec but yields a set, so `#{~@a} splices into a set. +(defn core-sqset [& parts] + (def r @[]) + (each p parts (each x (realize-for-iteration p) (array/push r x))) + (apply make-phs r)) + +# ============================================================ +# Predicates +# ============================================================ + +(defn core-char? [x] (and (struct? x) (= :jolt/char (x :jolt/type)))) +(defn char-code [c] (c :ch)) +(defn char->string [c] (string/from-bytes (c :ch))) + +(defn core-nil? [x] (nil? x)) +(defn core-not [x] (if x false true)) +(defn core-some? [x] (not (nil? x))) +(defn core-string? [x] (string? x)) +(defn core-number? [x] (number? x)) +(defn core-fn? [x] (or (function? x) (cfunction? x))) +(defn core-keyword? [x] (keyword? x)) +(defn core-symbol? [x] (and (struct? x) (= :symbol (x :jolt/type)))) +(defn core-vector? [x] (jvec? x)) +(defn core-map? [x] (or (phm? x) (struct? x) (if (and (table? x) (get x :jolt/deftype)) true false))) +# seq? is true only for actual sequences (lists, lazy-seqs) — NOT vectors, which +# are not ISeq in Clojure. (A Janet array represents a Clojure list/seq result.) +(defn core-seq? [x] (or (array? x) (plist? x) (lazy-seq? x))) +(defn core-coll? [x] (or (array? x) (tuple? x) (pvec? x) (plist? x) (struct? x) (phm? x) (set? x) (lazy-seq? x))) + +(defn core-true? [x] (= true x)) +(defn core-false? [x] (= false x)) +(defn core-identical? [a b] (= a b)) + +# Strictness helpers: like Clojure, numeric ops reject non-numbers, and the +# integer ops (odd?/even?) reject non-integers (incl. infinities, NaN, fractions). +(defn- finite-num? [x] (and (number? x) (= x x) (< (if (< x 0) (- x) x) math/inf))) +(defn- need-num [x op] + (if (number? x) x (error (string op " requires a number, got " (type x))))) +(defn- need-int [x op] + (if (and (number? x) (= x x) (< (if (< x 0) (- x) x) math/inf) (= x (math/floor x))) x + (error (string op " requires an integer")))) + +(defn core-zero? [x] (= (need-num x "zero?") 0)) +(defn core-pos? [x] (> (need-num x "pos?") 0)) +(defn core-neg? [x] (< (need-num x "neg?") 0)) +(defn core-even? [n] (= 0 (% (need-int n "even?") 2))) +(defn core-odd? [n] (not= 0 (% (need-int n "odd?") 2))) + +(defn core-integer? [x] (and (number? x) (= x (math/floor x)))) +(defn core-boolean? [x] (or (= x true) (= x false))) +(defn core-list? [x] (or (plist? x) (and (array? x) (not (get x :jolt/type))))) + +(defn core-empty? [coll] + (if (nil? coll) true + (if (set? coll) (= 0 (coll :cnt)) + (if (phm? coll) (= 0 (coll :cnt)) + (if (pvec? coll) (= 0 (pv-count coll)) + (if (plist? coll) (pl-empty? coll) + # Cell-based, NOT (nil? (ls-first)): a lazy-seq whose first element is + # legitimately nil (e.g. a `nil` case-constant) is non-empty. + (if (lazy-seq? coll) + (let [cell (realize-ls coll)] + (or (nil? cell) (= :jolt/pending cell) (= 0 (length cell)))) + (if (struct? coll) (= 0 (length (keys coll))) + (= 0 (length coll)))))))))) + +(defn core-every? [pred coll] + # Short-circuit on the first false — and pull lazily so an infinite seq with an + # early false (e.g. (every? pos? (range))) returns rather than hanging. Walks + # cells via realize-ls directly (core-first/lazy-from are defined later). + (if (lazy-seq? coll) + (do + (var cur coll) (var result true) (var go true) + (while (and result go) + (let [cell (realize-ls cur)] + (if (or (nil? cell) (= :jolt/pending cell) (= 0 (length cell))) + (set go false) + (if (pred (in cell 0)) + (let [rt (in cell 1)] + (if (nil? rt) (set go false) (set cur (make-lazy-seq rt)))) + (set result false))))) + result) + (do + (var result true) + (each x (realize-for-iteration coll) + (if (not (pred x)) (do (set result false) (break)))) + result))) + +# ============================================================ +# Math — Clojure semantics (variadic, / with one arg = reciprocal) +# ============================================================ + +(def core-+ (fn [& args] (if (= 0 (length args)) 0 (+ ;args)))) + +(def core-sub + (fn [& args] + (if (= 0 (length args)) + (error "Wrong number of args (0) passed to: -") + (apply - args)))) + +(def core-* (fn [& args] (if (= 0 (length args)) 1 (* ;args)))) + +(def core-/ + (fn [& args] + (case (length args) + 0 (error "Wrong number of args (0) passed to: /") + 1 (/ 1 (args 0)) + (apply / args)))) + +(def core-inc inc) +(def core-dec dec) +# Clojure integer division: quot truncates toward zero; rem matches the sign of +# the dividend; mod matches the sign of the divisor (floored). +(def core-quot (fn [n d] + (when (or (not (finite-num? n)) (not (finite-num? d))) (error "quot requires finite numbers")) + (when (= d 0) (error "Divide by zero")) + (let [q (/ n d)] (if (< q 0) (math/ceil q) (math/floor q))))) +(def core-rem (fn [n d] (- n (* (core-quot n d) d)))) +(def core-mod (fn [n d] + (let [m (core-rem n d)] + (if (or (= m 0) (= (> n 0) (> d 0))) m (+ m d))))) + +(defn core-max [& args] (each x args (need-num x "max")) (apply max args)) +(defn core-min [& args] (each x args (need-num x "min")) (apply min args)) + +(defn core-rand [& n] (let [r (math/random)] (if (empty? n) r (* r (in n 0))))) +(defn core-rand-int [n] (math/floor (* (math/random) n))) + +# ============================================================ +# Comparison +# ============================================================ + +(defn- eq-seqable + "If x is a Clojure sequential (vector/list/lazy-seq), return its elements as + an array; otherwise nil. Lets = compare across tuple/array/lazy-seq." + [x] + (cond + (lazy-seq? x) (realize-for-iteration x) + (pvec? x) (pv->array x) + (plist? x) (pl->array x) + (tuple? x) x + (array? x) x + nil)) + +(defn- eq-map-pairs + "Return [k v] pairs for a map-like value (phm/struct/table), else nil." + [x] + (cond + (phm? x) (phm-entries x) + (and (table? x) (get x :jolt/deftype)) nil + (struct? x) (pairs x) + (table? x) (pairs x) + nil)) + +(var jolt-equal? nil) +(set jolt-equal? + (fn [a b] + (let [sa (eq-seqable a) sb (eq-seqable b)] + (cond + # both sequential: compare element-wise (vectors/lists/lazy-seqs equal) + (and sa sb) + (if (= (length sa) (length sb)) + (do (var ok true) (var i 0) + (while (and ok (< i (length sa))) + (unless (jolt-equal? (in sa i) (in sb i)) (set ok false)) + (++ i)) + ok) + false) + (or sa sb) false + # sets + (or (set? a) (set? b)) + # value-based: same size and every element of a is value-equal to some + # element of b (so #{ {:a 1} } equals #{ (hash-map :a 1) } regardless of + # the elements' underlying representations) + (if (and (set? a) (set? b) (= (a :cnt) (b :cnt))) + (let [eb (phs-seq b)] + (var ok true) + (each x (phs-seq a) + (unless (some (fn [y] (jolt-equal? x y)) eb) (set ok false))) + ok) + false) + # maps: compare key/value pairs recursively, order-independent + true + (let [pa (eq-map-pairs a) pb (eq-map-pairs b)] + (if (or pa pb) + (if (and pa pb (= (length pa) (length pb))) + (do (var ok true) + (each pair pa + (let [k (in pair 0) v (in pair 1) + found (do (var fv :jolt/none) + (each p2 pb (when (jolt-equal? k (in p2 0)) (set fv (in p2 1)))) + fv)] + (unless (and (not= found :jolt/none) (jolt-equal? v found)) (set ok false)))) + ok) + false) + (deep= a b))))))) + +(defn core-= [& args] + (if (< (length args) 2) true + (do + (var ok true) + (var i 0) + (while (and ok (< i (dec (length args)))) + (unless (jolt-equal? (args i) (args (+ i 1))) (set ok false)) + (++ i)) + ok))) + +(defn core-not= [& args] (not (apply core-= args))) + +# Comparisons are variadic: (< a b c) means a < b < c. +(defn- chain-cmp [op opname xs] + # 1-arity (e.g. (< x)) is true regardless of x and does no type check. + (when (>= (length xs) 2) (each x xs (need-num x opname))) + (var ok true) (var i 0) + (while (and ok (< i (dec (length xs)))) + (unless (op (in xs i) (in xs (+ i 1))) (set ok false)) + (++ i)) + ok) +(defn core-< [& xs] (chain-cmp < "<" xs)) +(defn core-> [& xs] (chain-cmp > ">" xs)) +(defn core-<= [& xs] (chain-cmp <= "<=" xs)) +(defn core->= [& xs] (chain-cmp >= ">=" xs)) + +# ============================================================ +# Collections +# ============================================================ + +# Is x a map value (for conj/merge semantics: conj-ing a map merges its entries)? +(defn- map-value? [x] + (or (phm? x) (and (struct? x) (nil? (get x :jolt/type))))) + +# --- Sorted collections (sorted-map / sorted-set) ------------------------------- +# Defined here (before the collection fns) so conj/assoc/get/contains?/keys/vals/ +# disj can branch on them. A sorted-map is {:jolt/type :jolt/sorted-map :map STRUCT}; +# a sorted-set is {:jolt/type :jolt/sorted-set :items SORTED-ARRAY}. Keys/elements +# are assumed Comparable scalars (the premise of a sorted coll); ops return a fresh +# wrapper (persistent — source unchanged). A wrapper may carry an optional :cmp +# (set by the by-comparator constructors) that all derived colls propagate. +(defn core-sorted-map? [x] (and (table? x) (= :jolt/sorted-map (x :jolt/type)))) +(defn core-sorted-set? [x] (and (table? x) (= :jolt/sorted-set (x :jolt/type)))) +(defn core-sorted? [x] (or (core-sorted-map? x) (core-sorted-set? x))) +# A sorted coll may carry a :cmp — a Janet 2-arg comparator returning a Clojure +# compare result (neg/0/pos). nil means natural order (Janet's < via sort). The +# by-comparator constructors install one (built from the user IFn); all derived +# colls (assoc/conj/...) propagate it so ordering stays consistent. +# A Clojure comparator is either a (neg/0/pos)-returning fn or a boolean predicate +# (true => a sorts before b, like <). Reduce both to a strict less-than for sort. +(defn- cmp-lt? [cmp a b] + (let [r (cmp a b)] + (if (boolean? r) r (if (number? r) (< r 0) (truthy? r))))) +(defn- sorted-by [cmp arr] (if cmp (sort arr (fn [a b] (cmp-lt? cmp a b))) (sort arr))) +(defn sm-make [m &opt cmp] @{:jolt/type :jolt/sorted-map :map m :cmp cmp}) +(defn ss-make [items &opt cmp] @{:jolt/type :jolt/sorted-set :items items :cmp cmp}) +(defn core-sorted-map [& kvs] + (var m @{}) (var i 0) + (while (< i (length kvs)) (put m (kvs i) (kvs (+ i 1))) (+= i 2)) + (sm-make (table/to-struct m))) +(defn core-sorted-set [& xs] + (var seen @{}) (each x xs (put seen x true)) + (ss-make (sorted-by nil (array ;(keys seen))))) +(defn sorted-map-keys [sm] (sorted-by (sm :cmp) (array ;(keys (sm :map))))) +(defn sorted-map-entries [sm] (let [m (sm :map)] (map (fn [k] [k (get m k)]) (sorted-map-keys sm)))) +(defn sm-assoc-many [sm kvs] + (var m @{}) (each k (keys (sm :map)) (put m k (get (sm :map) k))) + (var i 0) (while (< i (length kvs)) (put m (kvs i) (kvs (+ i 1))) (+= i 2)) + (sm-make (table/to-struct m) (sm :cmp))) +(defn sm-dissoc-many [sm ks] + (def rm @{}) (each x ks (put rm x true)) + (var m @{}) (each k (keys (sm :map)) (unless (get rm k) (put m k (get (sm :map) k)))) + (sm-make (table/to-struct m) (sm :cmp))) +(defn ss-contains? [ss x] (var f false) (each e (ss :items) (when (deep= e x) (set f true) (break))) f) +(defn ss-conj-many [ss xs] + (var seen @{}) (each e (ss :items) (put seen e true)) (each x xs (put seen x true)) + (ss-make (sorted-by (ss :cmp) (array ;(keys seen))) (ss :cmp))) +(defn ss-disj-many [ss xs] + (def rm @{}) (each x xs (put rm x true)) + (ss-make (filter (fn [e] (not (get rm e))) (ss :items)) (ss :cmp))) + +(defn core-conj [& args] + (if (= 0 (length args)) (make-vec @[]) # (conj) -> [] + (let [coll (first args) xs (tuple/slice args 1)] + (if (nil? coll) + # conj onto nil builds a list (prepends): (conj nil 1 2) -> (2 1) + (do (var result nil) (each x xs (set result (pl-cons x result))) result) + (if (core-sorted-map? coll) + # conj a [k v] entry (or merge a map) into a sorted-map + (do (var m coll) + (each x xs + (if (map-value? x) + (each e (map-entries-of x) (set m (sm-assoc-many m [(in e 0) (in e 1)]))) + (set m (sm-assoc-many m [(vnth x 0) (vnth x 1)])))) + m) + (if (core-sorted-set? coll) + (ss-conj-many coll xs) + (if (pvec? coll) + (do (var result coll) (each x xs (set result (pv-conj result x))) result) + (if (plist? coll) + # list: prepend, O(1) per element via structural sharing + (do (var result coll) (each x xs (set result (pl-cons x result))) result) + (if (tuple? coll) + (tuple/slice (tuple ;(array/concat (array/slice coll) xs))) + (if (array? coll) + (if mutable? + # mutable mode: arrays are vectors — append in place + (do (each x xs (array/push coll x)) coll) + # immutable mode: arrays are lists — prepend onto a persistent cons node, + # sharing the original array as the tail (O(1) per element, no copy) + (do (var result coll) (each x xs (set result (pl-cons x result))) result)) + (if (set? coll) + (apply phs-conj coll xs) + (if (phm? coll) + (do + (var result coll) + (each x xs + (if (map-value? x) + # conj a map -> merge its entries + (each e (map-entries-of x) + (set result (phm-assoc result (in e 0) (in e 1)))) + (set result (phm-assoc result (vnth x 0) (vnth x 1))))) + result) + (do + (var result coll) + (each x xs + (if (map-value? x) + (each e (map-entries-of x) + (set result (map-assoc1 result (in e 0) (in e 1)))) + (set result (map-assoc1 result (vnth x 0) (vnth x 1))))) + result))))))))))))) + +(defn core-assoc [m & kvs] + (when (odd? (length kvs)) + (error "assoc expects an even number of key/value arguments")) + # assoc is defined on maps, vectors and nil; reject other shapes + (when (or (number? m) (string? m) (buffer? m) (keyword? m) (boolean? m) + (plist? m) (set? m) (core-transient? m) + (and (struct? m) (get m :jolt/type))) + (error (string "assoc requires a map or vector, got " (type m)))) + (cond + (core-sorted-map? m) (sm-assoc-many m kvs) + (phm? m) + (do (var result m) (var i 0) (while (< i (length kvs)) (set result (phm-assoc result (kvs i) (kvs (+ i 1)))) (+= i 2)) result) + (pvec? m) + (do (var result m) (var i 0) + (while (< i (length kvs)) + (let [idx (kvs i)] + (when (not (and (number? idx) (= idx (math/floor idx)) (>= idx 0) (<= idx (pv-count result)))) + (error (string "Index " idx " out of bounds for assoc on a vector of length " (pv-count result)))) + (set result (pv-assoc result idx (kvs (+ i 1))))) + (+= i 2)) result) + # vector: assoc by integer index (appending at count is allowed); stays a vector + (or (tuple? m) (array? m)) + (do (var result (array/slice m)) (var i 0) + (while (< i (length kvs)) + (let [idx (kvs i) v (kvs (+ i 1))] + (when (not (and (number? idx) (= idx (math/floor idx)) (>= idx 0) (<= idx (length result)))) + (error (string "Index " idx " out of bounds for assoc on a vector of length " (length result)))) + (if (= idx (length result)) (array/push result v) (put result idx v))) + (+= i 2)) + (if (tuple? m) (tuple/slice (tuple ;result)) result)) + # map (struct/table). Promote to a phm when any new key is a collection (a + # Janet struct/table would key it by identity) or any new key/value is nil (a + # struct drops nil; phm preserves it, matching Clojure). m itself is a struct + # here (phm handled above), so only the new kvs can introduce these. + (let [coll-key (do (var c false) (var i 0) + (while (< i (length kvs)) + (let [k (in kvs i) v (in kvs (+ i 1))] + (when (or (table? k) (array? k) (nil? k) (nil? v)) (set c true))) + (+= i 2)) c)] + (if coll-key + (do (var result (make-phm)) + (when m (each k (keys m) (set result (phm-assoc result k (get m k))))) + (var i 0) (while (< i (length kvs)) (set result (phm-assoc result (in kvs i) (in kvs (+ i 1)))) (+= i 2)) + result) + (do (var result @{}) (when m (each k (keys m) (put result k (get m k)))) + (var i 0) (while (< i (length kvs)) (let [k (kvs i) v (kvs (+ i 1))] (put result k v) (+= i 2))) + (if (struct? m) (table/to-struct result) result)))))) + +(defn core-dissoc [m & ks] + (cond + (nil? m) nil + (core-sorted-map? m) (sm-dissoc-many m ks) + (phm? m) (do (var result m) (each k ks (set result (phm-dissoc result k))) result) + # reject clearly non-map values (scalars, sequences, sets, symbol/char structs) + (or (number? m) (string? m) (buffer? m) (keyword? m) (boolean? m) + (pvec? m) (plist? m) (tuple? m) (array? m) (set? m) (core-transient? m) + (and (struct? m) (get m :jolt/type))) + (error (string "dissoc requires a map, got " (type m))) + # struct map / sorted-map / record / meta-wrapped map + (do (var result @{}) (each k (keys m) (var in-ks false) (each k2 ks (if (deep= k k2) (do (set in-ks true) (break)))) (if (not in-ks) (put result k (m k)))) + (if (struct? m) (table/to-struct result) result)))) + +(defn core-get [m k &opt default] + (default default nil) + (if (nil? m) default + (if (core-sorted-map? m) (let [v (get (m :map) k)] (if (nil? v) default v)) + (if (core-sorted-set? m) (if (ss-contains? m k) k default) + (if (core-transient? m) + (case (m :kind) + :vector (if (and (number? k) (>= k 0) (< k (length (m :arr)))) (in (m :arr) k) default) + :map (let [p (get (m :tbl) (canon-key k))] (if p (in p 1) default)) + :set (if (nil? (get (m :tbl) (canon-key k))) default k)) + (if (set? m) (phs-get m k default) + (if (phm? m) (phm-get m k default) + (if (pvec? m) + (if (and (number? k) (>= k 0) (< k (pv-count m))) (pv-nth m k) default) + (if (or (struct? m) (table? m)) + (let [v (m k)] + (if (nil? v) default v)) + (if (and (or (tuple? m) (array? m)) (number? k) (>= k 0) (< k (length m))) + (in m k) + default)))))))))) + +# Runtime invoke dispatch for COMPILED code (interpreter uses evaluator's +# jolt-invoke). Handles real functions plus Clojure IFn collections. +(defn jolt-call [f & args] + (cond + (or (function? f) (cfunction? f)) (apply f args) + (keyword? f) (core-get (get args 0) f (get args 1)) + (and (struct? f) (= :symbol (f :jolt/type))) (core-get (get args 0) f (get args 1)) + (core-sorted-map? f) (let [v (get (f :map) (get args 0))] (if (nil? v) (get args 1) v)) + (core-sorted-set? f) (if (ss-contains? f (get args 0)) (get args 0) (get args 1)) + (phm? f) (phm-get f (get args 0) (get args 1)) + (set? f) (if (phs-contains? f (get args 0)) (get args 0) (get args 1)) + (pvec? f) + (let [k (get args 0)] + (if (and (number? k) (= k (math/floor k)) (>= k 0) (< k (pv-count f))) + (pv-nth f k) + (error (string "Index " k " out of bounds for vector of length " (pv-count f))))) + (or (tuple? f) (array? f)) + (let [k (get args 0)] + (if (and (number? k) (= k (math/floor k)) (>= k 0) (< k (length f))) + (in f k) + (error (string "Index " k " out of bounds for vector of length " (length f))))) + # Map literal (struct with no :jolt/type marker) or a record: callable as a + # key lookup. A TAGGED struct (char/etc.) is NOT a fn — symbols are handled + # above; everything else with a :jolt/type falls through to the error. + (or (and (struct? f) (nil? (get f :jolt/type))) (and (table? f) (get f :jolt/deftype))) + (let [v (get f (get args 0) :jolt/not-found)] + (if (= v :jolt/not-found) (get args 1) v)) + (error (string "Cannot call " (type f) " as a function")))) + +(defn core-apply + "(apply f a b ... coll) — call f with the leading args plus the elements of + the final collection spliced in. Materializes pvec/lazy-seq/set tails." + [f & args] + (let [n (length args)] + (if (= n 0) + (jolt-call f) + (let [fixed (array/slice args 0 (- n 1)) + t (in args (- n 1)) + tail (cond (set? t) (phs-seq t) (phm? t) (tuple ;(phm-entries t)) + (realize-for-iteration t))] + (jolt-call f ;fixed ;tail))))) + +(defn core-get-in [m ks &opt default] + (default default nil) + (def ks (vview ks)) + # Walk with a fresh sentinel so a PRESENT key whose value is nil is distinguished + # from a missing key: only a genuinely-absent step falls back to default. + (def absent @{}) + (var current m) + (var i 0) + (var missing false) + (while (< i (length ks)) + (let [nxt (core-get current (ks i) absent)] + (if (= nxt absent) (do (set missing true) (break)) (set current nxt))) + (++ i)) + (if missing default current)) + +(defn core-contains? [coll key] + (if (core-sorted-map? coll) (not (nil? (get (coll :map) key))) + (if (core-sorted-set? coll) (ss-contains? coll key) + (if (core-transient? coll) + (case (coll :kind) + :vector (and (number? key) (>= key 0) (< key (length (coll :arr)))) + (not (nil? (get (coll :tbl) (canon-key key))))) + (if (set? coll) (phs-contains? coll key) + (if (phm? coll) (let [b (get (coll :buckets) (phm-hash-key key))] (if b (phm-bucket-contains? b key) false)) + (if (pvec? coll) (and (number? key) (>= key 0) (< key (pv-count coll))) + (if (struct? coll) (not (nil? (coll key))) + (if (table? coll) (not (nil? (coll key))) + (if (or (tuple? coll) (array? coll)) + (and (number? key) (>= key 0) (< key (length coll))) + false)))))))))) + +# Coerce a Clojure IFn value to a Janet-callable fn for higher-order fns +# (map/filter/sort-by/group-by/...). Janet functions pass through; a keyword or +# symbol becomes a key lookup, a map a key lookup, a set a membership test — so +# (map :k coll), (sort-by :k coll), (filter a-set coll) work. +(defn- as-fn [f] + (cond + (or (function? f) (cfunction? f)) f + (keyword? f) (fn [x &opt d] (core-get x f d)) + (core-symbol? f) (fn [x &opt d] (core-get x f d)) + (phm? f) (fn [k &opt d] (core-get f k d)) + (set? f) (fn [x &opt d] (if (core-contains? f x) x d)) + true f)) + +# Sorted collections — minimal: backed by a struct (map) / sorted array (set), +# ordered by key/element on read. Defined early so seq/count/get can dispatch. +# sorted-map/sorted-set predicates, constructors and ops live ABOVE core-conj so +# the collection fns (conj/assoc/get/contains?/…) can branch on them. + +(defn core-count [coll] + (cond + (nil? coll) 0 + (core-transient? coll) (length (if (= :vector (coll :kind)) (coll :arr) (coll :tbl))) + (core-sorted-map? coll) (length (keys (coll :map))) + (core-sorted-set? coll) (length (coll :items)) + (lazy-seq? coll) (ls-count coll) + (pvec? coll) (pv-count coll) + (plist? coll) (pl-count coll) + (set? coll) (coll :cnt) + (phm? coll) (coll :cnt) + (and (table? coll) (get coll :jolt/deftype)) (- (length (keys coll)) 1) + (or (string? coll) (buffer? coll) (struct? coll) (tuple? coll) (array? coll)) (length coll) + # count is undefined on scalars (numbers/keywords/symbols/booleans/chars) + (error (string "count not supported on " (type coll))))) + +(defn core-first [coll] + (cond + (core-sorted-map? coll) (let [e (sorted-map-entries coll)] (if (empty? e) nil (in e 0))) + (core-sorted-set? coll) (let [i (coll :items)] (if (empty? i) nil (in i 0))) + (lazy-seq? coll) (ls-first coll) + (pvec? coll) (if (= 0 (pv-count coll)) nil (pv-nth coll 0)) + (plist? coll) (if (pl-empty? coll) nil (pl-first coll)) + # maps and sets: first of their seq (an entry / element) + (phm? coll) (let [e (phm-entries coll)] (if (= 0 (length e)) nil (in e 0))) + (set? coll) (let [s (phs-seq coll)] (if (= 0 (length s)) nil (in s 0))) + (and (struct? coll) (nil? (get coll :jolt/type))) + (let [ks (keys coll)] (if (= 0 (length ks)) nil (tuple (in ks 0) (get coll (in ks 0))))) + (nil? coll) nil + (string? coll) (if (= 0 (length coll)) nil (make-char (in coll 0))) + # scalars aren't seqable + (or (number? coll) (boolean? coll) (keyword? coll) (and (struct? coll) (get coll :jolt/type))) + (error (string "first not supported on " (type coll))) + (= 0 (length coll)) nil + (in coll 0))) + +(defn- seq-done? + "True when cursor c (a lazy-seq or a concrete collection) is exhausted. + Uses cell realization for lazy-seqs so nil elements don't end the seq early." + [c] + (if (lazy-seq? c) + (let [cell (realize-ls c)] + (or (nil? cell) (= :jolt/pending cell) (= 0 (length cell)))) + (or (nil? c) (= 0 (length c))))) + +(defn core-rest [coll] + (cond + # rest never returns nil — Clojure's rest yields () on an exhausted seq. + (lazy-seq? coll) (let [r (ls-rest coll)] (if (nil? r) @[] r)) + (plist? coll) (pl-rest coll) + (pvec? coll) (let [a (pv->array coll)] (if (<= (length a) 1) @[] (array/slice a 1))) + (or (nil? coll) (= 0 (length coll))) @[] + (string? coll) (tuple ;(map make-char (string/bytes (string/slice coll 1)))) + (tuple? coll) (tuple/slice coll 1) + (array/slice coll 1))) + +(defn core-next [coll] + # next is rest, but nil when the rest is empty. seq-done? realizes one lazy + # cell so a lazy rest that turns out empty (length on the table won't tell us) + # collapses to nil, matching Clojure. + (let [r (core-rest coll)] + (if (seq-done? r) nil r))) + +(defn core-cons [x coll] + "Prepend x onto coll. For concrete collections this is an O(1) persistent cons + node; for lazy-seqs it stays a lazy cell so laziness is preserved." + (cond + # Lazy tail: return a LazySeq (NOT a bare cell), so a cons-of-a-cons stays a + # proper lazy-seq and the rest-thunk never leaks as a plain array element. + (lazy-seq? coll) (make-lazy-seq (fn [] @[x (fn [] coll)])) + (or (nil? coll) (plist? coll) (array? coll) (tuple? coll)) (pl-cons x coll) + # second arg must be seqable (a collection or string); reject scalars + (not (or (core-coll? coll) (string? coll))) + (error (string "Don't know how to create ISeq from: " (type coll))) + (pl-cons x (realize-for-iteration coll)))) + +(defn core-seq [coll] + (cond + (core-sorted-map? coll) (let [e (sorted-map-entries coll)] (if (empty? e) nil (tuple ;e))) + (core-sorted-set? coll) (let [i (coll :items)] (if (empty? i) nil (tuple ;i))) + (or (nil? coll) (and (or (tuple? coll) (array? coll)) (= 0 (length coll)))) nil + # Cell-based emptiness, NOT (nil? (ls-first)): a lazy-seq whose first element + # is legitimately nil is non-empty, so (seq (cons nil ...)) must not be nil. + (lazy-seq? coll) (let [cell (realize-ls coll)] + (if (or (nil? cell) (= :jolt/pending cell) (= 0 (length cell))) nil coll)) + (pvec? coll) (if (= 0 (pv-count coll)) nil (tuple ;(pv->array coll))) + (plist? coll) (if (pl-empty? coll) nil (tuple ;(pl->array coll))) + (buffer? coll) (if (= 0 (length coll)) nil (let [a @[]] (each x coll (array/push a x)) (tuple ;a))) + (set? coll) (phs-seq coll) + (phm? coll) (tuple ;(phm-entries coll)) + (tuple? coll) (tuple/slice coll) + (string? coll) (if (= 0 (length coll)) nil (tuple ;(map make-char (string/bytes coll)))) + (struct? coll) (tuple ;(map (fn [k] (tuple k (get coll k))) (keys coll))) + (array? coll) (tuple ;coll) + (and (table? coll) (get coll :jolt/deftype)) coll + # scalars/functions aren't seqable + (error (string "seq not supported on " (type coll))))) + +(defn core-vec [coll] + (when (not (or (nil? coll) (core-coll? coll) (string? coll))) + (error (string "Don't know how to create a vector from " (type coll)))) + (let [coll (realize-for-iteration coll)] + (cond + (array? coll) (make-vec coll) + (tuple? coll) (make-vec coll) + (struct? coll) (make-vec (map |(in (kvs coll) (+ (* $ 2) 1)) (range (/ (length (kvs coll)) 2)))) + (string? coll) (make-vec (map |(string/from-bytes $) (string/bytes coll))) + (make-vec @[])))) + +(defn- into-conj [to items] + (cond + (or (phm? to) (struct? to) (and (table? to) (get to :jolt/deftype))) + (do (var result to) + (each item items (set result (core-assoc result (vnth item 0) (vnth item 1)))) + result) + (pvec? to) (do (var result to) (each x items (set result (pv-conj result x))) result) + (array? to) (if mutable? + (do (each x items (array/push to x)) to) # vector: append + (do (var result (array/slice to)) (each x items (array/insert result 0 x)) result)) # list: prepend + (tuple? to) (tuple/slice (tuple ;(array/concat (array/slice to) (array/slice items)))) + to)) + +(defn core-merge [& maps] + # Clojure: (when (some identity maps) (reduce conj (or (first maps) {}) (rest maps))) + # - (merge) and (merge nil nil) -> nil; nil args elsewhere are no-ops. + # - later args follow conj semantics (a map merges its entries; a [k v] + # vector/map-entry adds that entry). + (var any false) + (each m maps (when (not (nil? m)) (set any true))) + (if (not any) + nil + (do + (var result (let [f (in maps 0)] (if (nil? f) (struct) f))) + (var i 1) + (while (< i (length maps)) + (let [m (in maps i)] + (cond + (nil? m) nil + (or (phm? m) (struct? m)) + (each e (map-entries-of m) + (set result (core-assoc result (in e 0) (in e 1)))) + # a [k v] pair (map-entry / 2-vector), per conj + (and (or (pvec? m) (tuple? m) (array? m)) + (= 2 (if (pvec? m) (pv-count m) (length m)))) + (set result (core-assoc result (vnth m 0) (vnth m 1))) + # scalars, sets, and wrong-length sequentials can't merge into a map + # (a length-2 vector was handled above; anything else here is bad) + (or (number? m) (string? m) (buffer? m) (keyword? m) (boolean? m) + (set? m) (plist? m) (pvec? m) (tuple? m) (array? m) + (and (struct? m) (get m :jolt/type))) + (error (string "Can't merge " (type m) " into a map")) + # other map-like tables (records, sorted-maps, host tables): lenient conj + (set result (core-conj result m)))) + (++ i)) + result))) + +(defn core-merge-with [f & maps] + # Presence — not nil-of-value — decides whether to combine: a key present in the + # accumulator with a nil value still triggers (f existing v), matching Clojure. + (if (= 0 (length maps)) + nil + (do + (var result (first maps)) + (var mi 1) + (while (< mi (length maps)) + (let [m (maps mi)] + (when m + (each e (map-entries-of m) + (let [k (in e 0) v (in e 1)] + (set result + (if (core-contains? result k) + (core-assoc result k (f (core-get result k) v)) + (core-assoc result k v))))))) + (++ mi)) + result))) + +(defn core-keys [m] + # phm-entries (not phm-to-struct) so keys mapped to nil values are not dropped. + (if (core-sorted-map? m) (tuple ;(sorted-map-keys m)) + (if (phm? m) (tuple ;(map |(in $ 0) (phm-entries m))) (tuple ;(keys m))))) + +(defn core-vals [m] + (if (core-sorted-map? m) (tuple ;(map |(in $ 1) (sorted-map-entries m))) + (if (phm? m) (tuple ;(map |(in $ 1) (phm-entries m))) (tuple ;(map |(m $) (keys m)))))) + +(defn core-select-keys [m ks] + # Include a key when it is PRESENT (contains?), even if its value is nil — a + # struct/table would drop a nil value, so collect entries and build via kvs->map. + (def kvs @[]) + (each k (realize-for-iteration ks) + (when (core-contains? m k) + (array/push kvs k) (array/push kvs (core-get m k)))) + (kvs->map kvs)) + +(defn core-zipmap [ks vs] + (let [ks (realize-for-iteration ks) vs (realize-for-iteration vs)] + # collect pairs, then build once — a nil key/value must survive (kvs->map -> phm) + (def kvs @[]) + (var i 0) + (while (and (< i (length ks)) (< i (length vs))) + (array/push kvs (in ks i)) (array/push kvs (in vs i)) + (++ i)) + (kvs->map kvs))) + +# ============================================================ +# Transducers +# ============================================================ +# A transducer is (fn [rf] rf') where rf' is a reducing fn with arities +# []=init, [acc]=complete, [acc x]=step. map/filter/take/... return a +# transducer when called with no collection. + +(defn core-reduced [x] @{:jolt/type :jolt/reduced :val x}) +(defn core-reduced? [x] (and (table? x) (= :jolt/reduced (x :jolt/type)))) +(defn core-unreduced [x] (if (core-reduced? x) (x :val) x)) +(defn- ensure-reduced [x] (if (core-reduced? x) x (core-reduced x))) + +(defn td-map [f] + (fn [rf] (fn [& a] (case (length a) 0 (rf) 1 (rf (a 0)) (rf (a 0) (f (a 1))))))) +(defn td-filter [pred] + (fn [rf] (fn [& a] (case (length a) 0 (rf) 1 (rf (a 0)) + (if (truthy? (pred (a 1))) (rf (a 0) (a 1)) (a 0)))))) +(defn td-remove [pred] (td-filter (fn [x] (not (pred x))))) +# td-keep removed: keep (incl its transducer arity) lives in core/40-lazy.clj. +(defn td-take [n] + (fn [rf] + (var left n) + (fn [& a] (case (length a) 0 (rf) 1 (rf (a 0)) + (if (<= left 0) (core-reduced (a 0)) + (let [r (rf (a 0) (a 1))] (set left (dec left)) + (if (<= left 0) (ensure-reduced r) r))))))) +(defn td-drop [n] + (fn [rf] + (var left n) + (fn [& a] (case (length a) 0 (rf) 1 (rf (a 0)) + (if (> left 0) (do (set left (dec left)) (a 0)) (rf (a 0) (a 1))))))) +(defn td-take-while [pred] + (fn [rf] + (fn [& a] (case (length a) 0 (rf) 1 (rf (a 0)) + (if (truthy? (pred (a 1))) (rf (a 0) (a 1)) (core-reduced (a 0))))))) +(defn td-drop-while [pred] + (fn [rf] + (var dropping true) + (fn [& a] (case (length a) 0 (rf) 1 (rf (a 0)) + (do (when (and dropping (not (truthy? (pred (a 1))))) (set dropping false)) + (if dropping (a 0) (rf (a 0) (a 1)))))))) +# td-map-indexed removed: map-indexed (incl transducer arity) lives in core/40-lazy.clj. + +# Stateful windowing transducers. The 1-arg (completion) arity flushes a partial +# trailing window before delegating to rf's completion; matches Clojure. +# td-partition-all removed: partition-all (incl transducer arity) lives in core/40-lazy.clj. + +# partition-by's transducer arity lives with its (lazy) collection arity in the +# overlay (10-seq tier), written in Clojure with volatiles. + +(defn- reduce-with-reduced + "Reduce coll with reducing fn rf and seed init, honoring `reduced`. Steps lazy + seqs one cell at a time so a reducing fn that returns `reduced` (e.g. the + `take`/`take-while` transducers) can short-circuit over an INFINITE seq instead + of realizing it eagerly. Returns the final (unwrapped) accumulator." + [rf init coll] + (var acc init) + (if (lazy-seq? coll) + (do + (var cur coll) (var go true) + (while go + (let [cell (realize-ls cur)] + (if (or (nil? cell) (= :jolt/pending cell) (= 0 (length cell))) + (set go false) + (do + (set acc (rf acc (in cell 0))) + (if (core-reduced? acc) + (do (set acc (acc :val)) (set go false)) + (let [rt (in cell 1)] + (if (nil? rt) (set go false) (set cur (make-lazy-seq rt)))))))))) + (do + (var stop false) + (each x (if (set? coll) (phs-seq coll) (realize-for-iteration coll)) + (when (not stop) + (set acc (rf acc x)) + (when (core-reduced? acc) (set acc (acc :val)) (set stop true)))))) + acc) + +(defn- transduce-reduce + "Reduce coll with reducing fn rf and seed init, honoring `reduced`." + [rf init coll] + (reduce-with-reduced rf init coll)) + +(defn core-transduce + "(transduce xform f coll) or (transduce xform f init coll)." + [xform f & rest] + (let [has-init (= 2 (length rest)) + init (if has-init (in rest 0) (f)) + coll (if has-init (in rest 1) (in rest 0)) + rf (xform f)] + (rf (transduce-reduce rf init coll)))) + +(defn core-into + "(into to from) or (into to xform from)." + [to & rest] + (if (= 2 (length rest)) + (let [xform (in rest 0) from (in rest 1)] + (core-transduce xform (fn [& a] (case (length a) 0 to 1 (a 0) (core-conj (a 0) (a 1)))) to from)) + (into-conj to (realize-for-iteration (in rest 0))))) + +(defn core-sequence + "(sequence coll) -> a seq of coll. (sequence xform coll) -> a LAZY seq of coll + transformed by xform: elements are pulled and pushed through the transducer one + at a time, with outputs buffered and emitted lazily — so it works over infinite + input (matching Clojure). Honors `reduced` (early stop) and runs the completion + arity to flush stateful transducers (e.g. partition-all)." + [a & rest] + (if (= 0 (length rest)) + (core-seq a) + (let [xform a + coll (in rest 0) + buf @[] + state @{:stopped false :completed false} + rf (fn [& args] + (case (length args) + 0 buf + 1 (in args 0) + (do (array/push (in args 0) (in args 1)) (in args 0)))) + xf (xform rf)] + # Pull/complete until buf holds an output or the source is fully drained. + (defn ensure-buf [src] + (var s src) + (while (and (= 0 (length buf)) (not (state :stopped)) (not (seq-done? s))) + (let [r (xf buf (core-first s))] + (set s (core-rest s)) + (when (core-reduced? r) (put state :stopped true)))) + (when (and (= 0 (length buf)) (not (state :completed)) + (or (state :stopped) (seq-done? s))) + (put state :completed true) + (xf buf)) # completion arity — flushes any buffered state + s) + (defn gen [src] + (fn [] + (let [s (ensure-buf src)] + (if (= 0 (length buf)) nil + (let [val (in buf 0)] + (array/remove buf 0 1) + @[val (gen s)]))))) + # core-seq normalizes to a tuple / lazy-seq / nil — all walkable by + # core-first/rest/seq-done?. (Walking a raw pvec/set would misfire: + # seq-done? uses length, which counts a pvec table's KEYS, not elements.) + (make-lazy-seq (gen (core-seq coll)))))) + + +(defn coll->cells [c] + "Convert a seqable to a lazy-seq cell chain: nil or [first, rest-thunk]. + A cons cell is a MUTABLE array `@[val rest-thunk]` (produced by `cons`/the lazy + transformers); user collections (tuples, pvecs, lists) are immutable. We rely + on that distinction: only a mutable 2-array whose tail is a function is treated + as an already-built cell — a user vector like `[first last]` (tail is the fn + `last`) is data and must NOT be misread as a cell. User data is recursed through + immutable tuples so its tails never reach the cell-detection branch." + (if (nil? c) nil + (if (pvec? c) (coll->cells (tuple ;(pv->array c))) + (if (plist? c) (coll->cells (tuple ;(pl->array c))) + (if (function? c) + (let [r (c)] + (if (and (array? r) (= 2 (length r)) (function? (in r 1))) + r + (coll->cells r))) + (if (lazy-seq? c) + (let [cell (realize-ls c)] + (if (= :jolt/pending cell) nil cell)) + (if (tuple? c) + # user sequential data: every element is a value, no cell-detection. + (if (= 0 (length c)) nil + @[(in c 0) (fn [] (coll->cells (tuple/slice c 1)))]) + (if (array? c) + # mutable array: a genuine cons cell, or an eager seq result. + (if (= 0 (length c)) nil + (if (and (= 2 (length c)) (function? (in c 1))) + c # already a cell [val, rest-thunk] + @[(in c 0) (fn [] (coll->cells (array/slice c 1)))])) + # Other concrete seqables (set/map/string/buffer): coerce to a tuple + # seq via core-seq, then recurse. (lazy/indexed handled above.) + (if (or (set? c) (phm? c) (buffer? c) (string? c) + (and (struct? c) (nil? (get c :jolt/type)))) + (coll->cells (core-seq c)) + nil))))))))) + +(defn lazy-from + "Coerce any seqable to a uniform lazy view without forcing. + Returns nil if coll is nil or empty, the LazySeq unchanged if already lazy, + or a new LazySeq that walks element by element." + [coll] + (if (nil? coll) nil + (if (lazy-seq? coll) coll + (do + # Reject non-seqable scalars (number/boolean/keyword, and tagged structs + # like char/symbol) so a lazy transformer over bad input throws when + # realized — matching Clojure — instead of silently yielding empty. + (when (or (number? coll) (boolean? coll) (keyword? coll) + (and (struct? coll) (not (nil? (get coll :jolt/type))))) + (error (string "Don't know how to create ISeq from: " (type coll)))) + (let [cell (coll->cells coll)] + (if (nil? cell) nil + (make-lazy-seq (fn [] cell)))))))) + +(defn core-map [f & colls] + (def f (as-fn f)) + (if (= 0 (length colls)) + (td-map f) # transducer arity + (if (= 1 (length colls)) + (let [coll (colls 0)] + # Option A: always lazy, even over concrete collections (matches Clojure — + # map returns a seq, not a vector). + (do + (defn mstep [c] + (fn [] + (if (seq-done? c) nil + @[(f (core-first c)) (mstep (core-rest c))]))) + (make-lazy-seq (mstep (lazy-from coll))))) + # Multi-collection: lazy-seq with per-element independent state + (let [init-cs (array/new-filled (length colls) nil) + init-idxs (array/new-filled (length colls) 0) + init-reals (array/new-filled (length colls) nil) + _ (do + (var i 0) + (while (< i (length colls)) + (let [c (in colls i)] + (if (lazy-seq? c) + (put init-cs i c) + (do (put init-cs i nil) + (put init-reals i (if (set? c) (phs-seq c) (realize-for-iteration c)))))) + (++ i)) + nil)] + (defn step [cs idxs reals] + "cs: current lazy-seq cursors, idxs: indices, reals: realized colls" + (fn [] + (var args @[]) + (var next-cs (array/new-filled (length cs) nil)) + (var next-idxs (array/new-filled (length idxs) 0)) + (var next-reals (array/new-filled (length reals) nil)) + (var ok true) + (var i 0) + (while (< i (length cs)) + (let [cur (in cs i) ridx (in idxs i) real (in reals i)] + (if (not (nil? cur)) + # Detect exhaustion with seq-done?, NOT (nil? (ls-first)): a + # lazy-seq can legitimately contain nil elements, and treating the + # first nil as end-of-seq truncates (e.g. mapping over a previous + # map result that holds nils). + (if (seq-done? cur) (do (set ok false) (break)) + (do (array/push args (ls-first cur)) + (put next-cs i (ls-rest cur)) + (put next-idxs i (+ ridx 1)) + (put next-reals i nil))) + (let [c (if (nil? real) + (let [rc (realize-for-iteration (in colls i))] + (put next-reals i rc) rc) + real)] + (if (>= ridx (length c)) (do (set ok false) (break)) + (do (array/push args (in c ridx)) + (put next-cs i nil) + (put next-idxs i (+ ridx 1)) + (put next-reals i c)))))) + (++ i)) + (if (and ok (= (length args) (length cs))) + @[(apply f args) (step next-cs next-idxs next-reals)] + nil))) + (make-lazy-seq (step init-cs init-idxs init-reals)))))) + +(defn core-filter [pred & rest] + (def pred (as-fn pred)) + (if (= 0 (length rest)) (td-filter pred) + (let [coll (in rest 0)] + # Option A: always lazy (matches Clojure — filter returns a seq). + (do + (defn fstep [c] + (fn [] + (var cur c) (var hit nil) (var found false) + (while (and (not found) (not (seq-done? cur))) + (let [x (core-first cur)] + (if (pred x) (do (set hit @[x (core-rest cur)]) (set found true)) + (set cur (core-rest cur))))) + (if found @[(in hit 0) (fstep (in hit 1))] nil))) + (make-lazy-seq (fstep (lazy-from coll))))))) + +(defn core-remove [pred & rest] + (def pred (as-fn pred)) + (if (= 0 (length rest)) (td-remove pred) + (core-filter (fn [x] (not (pred x))) (in rest 0)))) + +(def core-reduce + (fn [& args] + (case (length args) + # 2-arg: seed is the first element; reduce over the rest. Lazy seqs are + # stepped incrementally (via reduce-with-reduced) so `reduced` can + # short-circuit an infinite seq rather than realizing it. + 2 (let [f (args 0) coll (args 1)] + (if (lazy-seq? coll) + (let [cell (realize-ls coll)] + (if (or (nil? cell) (= :jolt/pending cell) (= 0 (length cell))) + (f) + (let [rt (in cell 1)] + (if (nil? rt) (in cell 0) + (reduce-with-reduced f (in cell 0) (make-lazy-seq rt)))))) + (let [c (if (set? coll) (phs-seq coll) (realize-for-iteration coll))] + (if (= 0 (length c)) (f) + (reduce-with-reduced f (in c 0) (array/slice c 1)))))) + 3 (let [f (args 0) val (args 1) coll (args 2)] + (reduce-with-reduced f val coll)) + (error "Wrong number of args passed to: reduce")))) + +(defn core-take [n & rest] + # n is a count — reject non-numbers (e.g. a char/string) like Clojure, rather + # than letting Janet's >= silently compare mixed types. + (unless (number? n) (error (string "take: n must be a number, got " (type n)))) + (if (= 0 (length rest)) (td-take n) + (let [coll (in rest 0)] + # Option A: lazy take (returns a seq, not a vector, even over a vector). + (defn tstep [c i] + (fn [] + (if (or (>= i n) (seq-done? c)) nil + @[(core-first c) (tstep (core-rest c) (+ i 1))]))) + (make-lazy-seq (tstep (lazy-from coll) 0))))) + +(defn core-drop [n & rest] + (if (= 0 (length rest)) (td-drop n) + (let [coll (in rest 0)] + # Option A: lazy drop — skip n (forcing only those), return the lazy tail. + (make-lazy-seq + (fn [] + (var cur (lazy-from coll)) + (var i 0) + (while (and (< i n) (not (seq-done? cur))) + (set cur (core-rest cur)) + (++ i)) + (coll->cells cur)))))) + +# ffirst/nfirst/fnext/nnext/last/butlast (seq tier) and second/peek/subvec/mapv/ +# update (kernel tier) now live in the Clojure clojure.core tiers under +# jolt-core/clojure/core/. The kernel tier is bootstrap-compiled before the +# self-hosted analyzer is built, so the structural fns the analyzer uses come +# from Clojure, not Janet — see api/load-core-overlay! and core/00-kernel.clj. + +(defn core-take-while [pred & rest] + (def pred (as-fn pred)) + (if (= 0 (length rest)) (td-take-while pred) + (let [coll (in rest 0)] + # Option A: lazy take-while. + (defn twstep [c] + (fn [] + (if (seq-done? c) nil + (let [x (core-first c)] + (if (pred x) @[x (twstep (core-rest c))] nil))))) + (make-lazy-seq (twstep (lazy-from coll)))))) + +(defn core-drop-while [pred & rest] + (def pred (as-fn pred)) + (if (= 0 (length rest)) (td-drop-while pred) + (let [coll (in rest 0)] + (if (lazy-seq? coll) + (do + (defn dwstep [c] + (fn [] + (var cur c) + (while (and (not (seq-done? cur)) (pred (ls-first cur))) + (set cur (ls-rest cur))) + (if (seq-done? cur) nil (realize-ls cur)))) + (make-lazy-seq (dwstep coll))) + (let [c (realize-for-iteration coll)] + (var start 0) + (while (and (< start (length c)) (pred (c start))) + (++ start)) + (if (tuple? c) + (tuple/slice c start) + (array/slice c start))))))) + +(defn core-concat [& colls] + "Truly lazy concatenation. `step` returns a 0-arg thunk that is only forced + when the consumer asks for the next cell, so nothing in `colls` is realized at + construction time. This is essential for self-referential lazy seqs (e.g. + (def fib (lazy-cat [0 1] (map + (rest fib) fib)))): the later colls must not be + forced until after the surrounding `def` has bound the var." + (if (= 0 (length colls)) @[] + (let [colls (if (tuple? colls) (array/slice colls) colls)] + (defn step [cs] + (fn [] + (if (= 0 (length cs)) + nil + (let [c (in cs 0) + remaining (array/slice cs 1) + cell (coll->cells c)] + (if (nil? cell) + # current coll is empty: advance to the next one + ((step remaining)) + (let [val (in cell 0) + rest-fn (in cell 1)] + @[val (step (if (nil? rest-fn) + remaining + (array/insert remaining 0 rest-fn)))])))))) + (make-lazy-seq (step colls))))) + + +(defn core-mapcat + "(mapcat f & colls) — map then concat. (mapcat f) returns a transducer." + [f & colls] + (if (= 0 (length colls)) + # transducer: map f over each input, then splice (cat) the result + (fn [rf] + (fn [& a] + (case (length a) + 0 (rf) + 1 (rf (a 0)) + (do (var acc (a 0)) + (each x (realize-for-iteration (f (a 1))) + (set acc (rf acc x))) + acc)))) + # collection arity: direct lazy implementation. Pull one element + # from each input coll, apply f, then yield elements from f's result. + # No apply-forcing — walk input colls lazily element-by-element. + (do + (var n (length colls)) + (var init-cs @[]) + (var i 0) + (while (< i n) + (array/push init-cs (lazy-from (in colls i))) + (++ i)) + (defn step [cs res] + (fn [] + (var cursors cs) (var cur-res res) (var hit nil) (var ok false) + (while (not ok) + (if (nil? cur-res) + (do + (var args @[]) (var next-cs @[]) (var exhausted false) (var j 0) + (while (and (< j n) (not exhausted)) + (let [c (in cursors j)] + (if (seq-done? c) (set exhausted true) + (do + (array/push args (ls-first c)) + (array/push next-cs (ls-rest c))))) + (++ j)) + (if exhausted (break)) + (let [r (apply f args)] + (set cursors next-cs) + (set cur-res (if (or (nil? r) (tuple? r) (array? r) + (lazy-seq? r) (pvec? r) (set? r) (plist? r)) + (lazy-from r) + (lazy-from (tuple r)))))) + (if (seq-done? cur-res) + (set cur-res nil) + (let [val (ls-first cur-res) rest (ls-rest cur-res)] + (set hit @[val (step cursors rest)]) + (set ok true))))) + (if ok hit nil))) + (make-lazy-seq (step init-cs nil))))) + +(defn core-reverse [coll] + (if (nil? coll) @[] + (if (lazy-seq? coll) + (do + (var result @[]) + (var cur coll) + # seq-done?, not (nil? (ls-first)): a nil element must not end the walk. + (while (not (seq-done? cur)) + (array/push result (core-first cur)) + (set cur (core-rest cur))) + (var reversed @[]) + (var i (dec (length result))) + (while (>= i 0) + (array/push reversed (in result i)) + (-- i)) + reversed) + (let [c (realize-for-iteration coll)] + (var result @[]) + (var i (dec (length c))) + (while (>= i 0) + (array/push result (in c i)) + (-- i)) + result)))) + +(defn core-nth + "Return the nth element of a sequential collection. With a not-found arg, return + it when idx is out of bounds (even if it's nil); without one, throw — matching + Clojure, where (nth coll i nil) returns nil rather than throwing." + [coll idx & rest] + (def has-default (> (length rest) 0)) + (def default (if has-default (in rest 0) nil)) + (defn oob [n] (if has-default default (error (string "Index " idx " out of bounds, length: " n)))) + (if (nil? coll) default # (nth nil i) -> nil / default, never throws + (if (core-transient? coll) + (let [a (coll :arr)] (if (and (>= idx 0) (< idx (length a))) (in a idx) (oob (length a)))) + (if (plist? coll) + (let [a (pl->array coll)] + (if (and (>= idx 0) (< idx (length a))) (in a idx) (oob (length a)))) + (if (pvec? coll) + (if (and (>= idx 0) (< idx (pv-count coll))) + (pv-nth coll idx) + (oob (pv-count coll))) + (if (lazy-seq? coll) + # Walk with seq-done?, NOT (ls-first cur): a lazy element may legitimately be + # false or nil, which truthiness would mistake for end-of-seq. + (if (< idx 0) (oob 0) + (do + (var cur coll) + (var i 0) + (while (and (< i idx) (not (seq-done? cur))) + (set cur (core-rest cur)) + (++ i)) + (if (seq-done? cur) (oob i) (core-first cur)))) + (do + (var c (realize-for-iteration coll)) + (if (and (>= idx 0) (< idx (length c))) + (if (string? c) (make-char (in c idx)) (in c idx)) + (oob (length c)))))))))) + +(defn core-sort + "(sort coll) or (sort comparator coll). Comparator may return a boolean or a + Clojure-style negative/zero/positive number." + [a & rest] + (let [has-cmp (> (length rest) 0) + cmp (if has-cmp a nil) + coll (if has-cmp (first rest) a)] + (if (nil? coll) @[] + (let [arr (array/slice (realize-for-iteration coll))] + (if has-cmp + (sort arr (fn [x y] (let [r (cmp x y)] (if (number? r) (< r 0) (truthy? r))))) + (sort arr)) + (tuple/slice (tuple ;arr)))))) + +# (sort-by keyfn coll) or (sort-by keyfn comparator coll). The comparator (when +# given) compares the KEYS and may return a boolean or a Clojure-style number. +(defn core-sort-by [keyfn & rest] + (def keyfn (as-fn keyfn)) + (let [has-cmp (> (length rest) 1) + coll (if has-cmp (in rest 1) (first rest))] + (if (nil? coll) (tuple) + (let [c (realize-for-iteration coll) + arr (if (tuple? c) (array/slice c) (array/slice c))] + (if has-cmp + (let [cmp (first rest)] + (sort arr (fn [x y] (let [r (cmp (keyfn x) (keyfn y))] + (if (number? r) (< r 0) (truthy? r)))))) + (sort-by keyfn arr)) + (tuple/slice (tuple ;arr)))))) + +# distinct now lives in the Clojure lazy tier (core/40-lazy.clj). +# group-by / frequencies now live in the Clojure collection tier +# (core/20-coll.clj). + +(defn core-partition + "(partition n coll) or (partition n step coll). Only complete partitions of + size n are kept (use partition-all to keep the trailing remainder)." + [n & rest] + (let [has-step (> (length rest) 1) + step (if has-step (first rest) n) + coll (if has-step (in rest 1) (first rest))] + # Option A: always lazy. + (defn pstep [c] + (fn [] + (if (seq-done? c) nil + (do + (var part @[]) (var cur c) (var i 0) + (while (and (< i n) (not (seq-done? cur))) + (array/push part (core-first cur)) + (set cur (core-rest cur)) + (++ i)) + (if (= i n) + (let [next-cur (if (= step n) cur (lazy-from (core-drop (- step n) cur)))] + @[(tuple/slice (tuple ;part)) (pstep next-cur)]) + nil))))) + (make-lazy-seq (pstep (lazy-from coll))))) + +# partition-by now lives in the Clojure seq tier (core/10-seq.clj). + +# partition-all now lives in the Clojure lazy tier (core/40-lazy.clj). + + +# keep-indexed / map-indexed / cycle now live in the Clojure lazy tier +# (core/40-lazy.clj). + +# reduce-kv now lives in the Clojure collection tier (core/20-coll.clj). + +# pop is defined only on stacks (vectors -> last end, lists -> front); Clojure +# throws on sets/maps/seqs/strings/scalars. (peek lives in the Clojure kernel +# tier — core/00-kernel.clj.) +(defn core-pop [coll] + (cond + (nil? coll) nil + (plist? coll) (if (pl-empty? coll) (error "Can't pop empty list") (pl-rest coll)) + (pvec? coll) (if (= 0 (pv-count coll)) (error "Can't pop empty vector") (pv-pop coll)) + (tuple? coll) (if (= 0 (length coll)) (error "Can't pop empty vector") (tuple/slice coll 0 (- (length coll) 1))) + (array? coll) (if (= 0 (length coll)) (error "Can't pop empty list") (array/slice coll 1)) + (error (string "pop not supported on " (type coll))))) + +# subvec lives in the Clojure kernel tier — core/00-kernel.clj. + +(defn core-trampoline [f & args] + (var result (apply f args)) + (while (function? result) (set result (result))) + result) + +(def core-format (fn [fmt & args] (string/format fmt ;args))) + +# ============================================================ +# Sequence generators +# ============================================================ + +(def core-range + (fn [& args] + (if (= 0 (length args)) + # (range) — infinite lazy sequence 0, 1, 2, ... + (do + (defn rstep [i] (fn [] @[i (rstep (+ i 1))])) + (make-lazy-seq (rstep 0))) + (let [start (if (> (length args) 1) (args 0) 0) + end (if (> (length args) 1) (args 1) (args 0)) + step (if (> (length args) 2) (args 2) 1)] + (var result @[]) + (var i start) + (while (if (pos? step) (< i end) (> i end)) + (array/push result i) + (+= i step)) + (tuple/slice (tuple ;result)))))) + +# repeat / iterate now live in the Clojure lazy tier (core/40-lazy.clj). + +# repeatedly now lives in the Clojure lazy tier (core/40-lazy.clj). + +# ============================================================ +# Higher-order functions +# ============================================================ + +(def core-identity (fn [x] x)) + +(def core-constantly (fn [x] (fn [& _] x))) + +(defn core-complement [f] + (fn [& args] (not (apply f args)))) + +(defn core-qualified-symbol? [x] + "Returns true if x is a symbol with a namespace." + (and (struct? x) (= :symbol (x :jolt/type)) (not (nil? (x :ns))))) + +(defn core-simple-symbol? [x] + (and (struct? x) (= :symbol (x :jolt/type)) (nil? (x :ns)))) +(defn core-qualified-keyword? [x] + (and (keyword? x) (not (nil? (string/find "/" (string x)))))) +(defn core-simple-keyword? [x] + (and (keyword? x) (nil? (string/find "/" (string x))))) +# Jolt has no inst/uri/uuid host types, so these are always false; inst-ms has +# nothing valid to read. +(defn core-inst? [x] false) +(defn core-inst-ms [x] (error "Not an instant (no inst type in Jolt)")) +(defn core-uri? [x] false) +(defn core-uuid? [x] false) +(defn core-bytes? [x] (buffer? x)) +# tagged-literal? now lives in the Clojure collection tier (tagged-value predicate). + +(defn core-meta [x] + "Returns the metadata of x, or nil." + (cond + (var? x) (var-meta x) + # symbols carry reader metadata (type hints etc.) in a :meta field + (and (struct? x) (= :symbol (get x :jolt/type))) (get x :meta) + (table? x) (or (get x :jolt/meta) (get x :meta)) + nil)) + +# every-pred now lives in the Clojure collection tier (core/20-coll.clj). + +(def core-comp + (fn [& fs] + (case (length fs) + 0 identity + 1 (fs 0) + 2 (let [f (fs 0) g (fs 1)] (fn [& args] (f (apply g args)))) + (let [f (last fs) + gs (array/slice fs 0 (dec (length fs)))] + (fn [& args] + (var result (apply (last gs) args)) + (var i (- (length gs) 2)) + (while (>= i 0) + (set result ((gs i) result)) + (-- i)) + (f result)))))) + +(defn core-partial [f & args] + (fn [& more] (apply f (array/concat (array/slice args) more)))) + +# juxt now lives in the Clojure collection tier (core/20-coll.clj). + +(defn core-memoize [f] + (var cache @{}) + (fn [& args] + (let [key (tuple ;args)] + (if-let [v (get cache key)] + v + (let [result (apply f args)] + (put cache key result) + result))))) + +# ============================================================ +# Collection constructors +# ============================================================ + +(defn core-vector [& xs] (make-vec xs)) +(defn core-hash-map [& kvs] (make-phm kvs)) + +(defn core-array-map [& kvs] + (var result @{}) + (var i 0) + (while (< i (length kvs)) + (put result (kvs i) (kvs (+ i 1))) + (+= i 2)) + (table/to-struct result)) + +(defn core-hash-set [& xs] + (apply make-phs xs)) + +(defn core-set? [x] (set? x)) +(defn core-disj [s & ks] + (cond + (core-sorted-set? s) (ss-disj-many s ks) + (set? s) (apply phs-disj s ks) + (error "disj expects a set"))) + +(defn core-set [coll] + (apply core-hash-set (realize-for-iteration coll))) + +(defn core-list [& xs] + (array ;xs)) + +# ============================================================ +# String functions +# ============================================================ + +# Readable rendering of a value (Clojure pr semantics): strings quoted, +# keywords with leading ':', symbols by name, collections with their reader +# syntax. Used by both pr-str (readable) and str (collection elements). +(var pr-render nil) + +# Format a number the way Clojure prints it: infinity and NaN have named forms +# (Janet renders them "inf"/"-inf"/"nan"). +(defn- fmt-number [v] + (cond + (not (number? v)) (string v) + (= v math/inf) "Infinity" + (= v (- math/inf)) "-Infinity" + (not= v v) "NaN" + (string v))) + +(defn- pr-render-seq [buf items open close] + (buffer/push-string buf open) + (var first true) + (each x items + (if first (set first false) (buffer/push-string buf " ")) + (pr-render buf x)) + (buffer/push-string buf close)) + +(defn- pr-render-pairs [buf pairs] + (buffer/push-string buf "{") + (var first true) + (each pair pairs + (if first (set first false) (buffer/push-string buf ", ")) + (pr-render buf (in pair 0)) + (buffer/push-string buf " ") + (pr-render buf (in pair 1))) + (buffer/push-string buf "}")) + +(defn- name-of + "Extract a plain name string from a string, symbol struct, or a namespace/var + table (reading its :name) — never recurses into the cyclic ns structure." + [x] + (cond + (nil? x) nil + (string? x) x + (and (struct? x) (= :symbol (get x :jolt/type))) (x :name) + (or (struct? x) (table? x)) (name-of (get x :name)) + (string x))) + +(defn- var-display + "Render a Jolt var as #'ns/name. A var's :meta/:ns refs are cyclic, so this + reads only its :name and :ns name — printing the var's pairs would loop." + [v] + (let [nm (name-of (v :name)) + ns (name-of (v :ns))] + (if ns (string "#'" ns "/" nm) (string "#'" nm)))) + +(set pr-render + (fn [buf v] + (cond + (nil? v) (buffer/push-string buf "nil") + (= true v) (buffer/push-string buf "true") + (= false v) (buffer/push-string buf "false") + (string? v) (do (buffer/push-string buf "\"") (buffer/push-string buf v) (buffer/push-string buf "\"")) + (buffer? v) (do (buffer/push-string buf "\"") (buffer/push-string buf (string v)) (buffer/push-string buf "\"")) + (keyword? v) (do (buffer/push-string buf ":") (buffer/push-string buf (string v))) + (core-char? v) (do (buffer/push-string buf "\\") + (buffer/push-string buf + (case (v :ch) + 10 "newline" 32 "space" 9 "tab" 13 "return" + 12 "formfeed" 8 "backspace" 0 "nul" + (char->string v)))) + (regex? v) (do (buffer/push-string buf "#\"") (buffer/push-string buf (v :source)) (buffer/push-string buf "\"")) + (number? v) (buffer/push-string buf (fmt-number v)) + (and (struct? v) (= :symbol (v :jolt/type))) + (buffer/push-string buf (if (v :ns) (string (v :ns) "/" (v :name)) (v :name))) + (and (table? v) (= :jolt/var (get v :jolt/type))) (buffer/push-string buf (var-display v)) + (core-sorted-map? v) (pr-render-pairs buf (sorted-map-entries v)) + (core-sorted-set? v) (pr-render-seq buf (v :items) "#{" "}") + (lazy-seq? v) (pr-render-seq buf (realize-for-iteration v) "(" ")") + (set? v) (pr-render-seq buf (phs-seq v) "#{" "}") + (phm? v) (pr-render-pairs buf (phm-entries v)) + (core-transient? v) (buffer/push-string buf (string "#")) + (and (table? v) (= :jolt/chan (get v :jolt/type))) (buffer/push-string buf "#") + (pvec? v) (pr-render-seq buf (pv->array v) "[" "]") + (plist? v) (pr-render-seq buf (pl->array v) "(" ")") + (and (table? v) (get v :jolt/deftype)) (buffer/push-string buf (string v)) + (tuple? v) (pr-render-seq buf v "[" "]") + # mutable mode: arrays are vectors -> print with [] (else lists -> ()) + (array? v) (if mutable? (pr-render-seq buf v "[" "]") (pr-render-seq buf v "(" ")")) + (struct? v) (pr-render-pairs buf (pairs v)) + (table? v) (pr-render-pairs buf (pairs v)) + true (buffer/push-string buf (string v))))) + +(defn- str-render-one + "Render one value with Clojure's `str`/.toString semantics (bare strings, + nil -> empty, keywords/symbols by name, collections via pr-render)." + [v] + (cond + (nil? v) "" + (string? v) v + (buffer? v) (string v) + (core-char? v) (char->string v) + (keyword? v) (string ":" (string v)) + (and (struct? v) (= :symbol (v :jolt/type))) + (if (v :ns) (string (v :ns) "/" (v :name)) (v :name)) + (and (table? v) (= :jolt/var (get v :jolt/type))) (var-display v) + (number? v) (fmt-number v) + (= true v) "true" + (= false v) "false" + (let [buf @""] (pr-render buf v) (string buf)))) + +(defn core-str [& xs] + (if (= 0 (length xs)) "" + (do + (var result @[]) + (each x xs (array/push result (str-render-one x))) + (string/join result "")))) + +(defn core-str-join + "clojure.string/join: stringify each element (Clojure semantics), then join." + [coll &opt sep] + (default sep "") + (let [items (realize-for-iteration coll) + parts @[]] + (each x items (array/push parts (str-render-one x))) + (string/join parts (str-render-one sep)))) + +(defn core-name + "Returns the name string of a keyword, symbol, or string (without namespace)." + [x] + (cond + (keyword? x) (let [s (string x) i (string/find "/" s)] (if i (string/slice s (+ i 1)) s)) + (and (struct? x) (= :symbol (x :jolt/type))) (x :name) + (string? x) x + "")) + +(defn core-namespace + "Returns the namespace string of a keyword/symbol, or nil if none." + [x] + (cond + (keyword? x) (let [s (string x) i (string/find "/" s)] (if i (string/slice s 0 i) nil)) + (and (struct? x) (= :symbol (x :jolt/type))) + (if (x :ns) (if (struct? (x :ns)) ((x :ns) :name) (string (x :ns))) nil) + nil)) + +(def core-subs + (fn [& args] + (when (not (or (= 2 (length args)) (= 3 (length args)))) + (error "Wrong number of args passed to: subs")) + (let [s (args 0) + start (get args 1)] + (when (not (string? s)) (error (string "subs requires a string, got " (type s)))) + (let [len (length s) + end (if (= 3 (length args)) (args 2) len)] + # Clojure validates bounds (no negative/from-end/clamping like Janet): + # 0 <= start <= end <= (count s). + (when (not (and (number? start) (number? end) + (= start (math/floor start)) (= end (math/floor end)) + (>= start 0) (<= start end) (<= end len))) + (error "String index out of range")) + (string/slice s start end))))) + +# ============================================================ +# I/O — minimal wrappers +# ============================================================ + +# print/println use str semantics (bare strings); pr/prn use readable (quoted). +# All space-separate their args, like Clojure. +(defn core-print [& xs] + (var i 0) + (while (< i (length xs)) + (if (> i 0) (prin " ")) + (prin (str-render-one (xs i))) + (++ i)) + nil) + +(defn core-println [& xs] + (apply core-print xs) + (prin "\n") + nil) + +# Capture *out*: run thunk with Janet's :out dynamic bound to a buffer, so all +# print/println/pr/prn output (which go through `prin` -> (dyn :out)) is collected +# and returned as a string. The with-out-str macro (overlay) wraps a body thunk. +(defn core-with-out-str [thunk] + (def buf @"") + (with-dyns [:out buf] (thunk)) + (string buf)) + +(defn core-pr [& xs] + (var i 0) + (while (< i (length xs)) + (if (> i 0) (prin " ")) + (let [b @""] (pr-render b (xs i)) (prin (string b))) + (++ i)) + nil) + +(defn core-prn [& xs] + (apply core-pr xs) + (prin "\n") + nil) + +(defn core-pr-str [& xs] + (def buf @"") + (var i 0) + (let [n (length xs)] + (while (< i n) + (pr-render buf (xs i)) + (when (< (+ i 1) n) (buffer/push-string buf " ")) + (++ i))) + (string buf)) + +# ============================================================ +# Java-style arrays — backed by Janet's C primitives. Byte arrays use Janet +# buffers (contiguous, O(1) indexed get/put — genuinely fast); object and +# numeric arrays use Janet arrays. aget/aset/alength/aclone work over both. +# ============================================================ + +# alength / aget / aset now live in the Clojure collection tier — count/nth reads +# and an aset write through jolt.host/ref-put!. The typed/object array constructors +# below stay native (they build the mutable backing). + +(defn core-aclone [arr] + (if (buffer? arr) (buffer/slice arr) (array/slice arr))) + +# Numeric / object arrays: (T-array size) | (T-array size init) | (T-array seq) +(defn- make-num-array [a rest init] + (if (number? a) + (array/new-filled a (if (> (length rest) 0) (in rest 0) init)) + (array ;(realize-for-iteration a)))) +(defn core-object-array [a & rest] (make-num-array a rest nil)) +(defn core-int-array [a & rest] (make-num-array a rest 0)) +(defn core-long-array [a & rest] (make-num-array a rest 0)) +(defn core-short-array [a & rest] (make-num-array a rest 0)) +(defn core-double-array [a & rest] (make-num-array a rest 0)) +(defn core-float-array [a & rest] (make-num-array a rest 0)) +(defn core-char-array [a & rest] (make-num-array a rest (make-char 0))) +(defn core-boolean-array [a & rest] (make-num-array a rest false)) + +# Byte arrays — Janet buffers (each element a 0..255 byte). +(defn core-byte-array [a & rest] + (if (number? a) + (buffer/new-filled a (band (if (> (length rest) 0) (in rest 0) 0) 0xff)) + (let [b (buffer/new 0)] + (each x (realize-for-iteration a) (buffer/push-byte b (band x 0xff))) + b))) + +(defn core-aset-byte [arr i v] (put arr i (band v 0xff)) v) +(defn core-aset-int [arr i v] (put arr i v) v) +(defn core-aset-long [arr i v] (put arr i v) v) +(defn core-aset-short [arr i v] (put arr i v) v) +(defn core-aset-double [arr i v] (put arr i v) v) +(defn core-aset-float [arr i v] (put arr i v) v) +(defn core-aset-char [arr i v] (put arr i v) v) +(defn core-aset-boolean [arr i v] (put arr i v) v) + +(defn core-make-array [a & rest] + # (make-array len) or (make-array type len ...); ignore the type tag + (let [len (if (number? a) a (in rest 0))] (array/new-filled len nil))) + +(defn core-into-array [a & rest] + (let [s (if (> (length rest) 0) (in rest 0) a)] + (array ;(realize-for-iteration s)))) + +(defn core-to-array [coll] + (def arr @[]) (each x (realize-for-iteration coll) (array/push arr x)) arr) +(defn core-to-array-2d [coll] + (def arr @[]) (each row (realize-for-iteration coll) (array/push arr (core-to-array row))) arr) + +# Array-element casts — identity on arrays; `bytes` coerces to a byte buffer. +(defn core-bytes [x] (if (buffer? x) x (core-byte-array x))) +(defn core-booleans [x] x) +(defn core-ints [x] x) +(defn core-longs [x] x) +(defn core-shorts [x] x) +(defn core-doubles [x] x) +(defn core-floats [x] x) +(defn core-chars [x] x) + +# Scalar numeric coercions +(defn core-byte [x] (let [b (band (math/trunc x) 0xff)] (if (>= b 128) (- b 256) b))) +(defn core-short [x] (let [s (band (math/trunc x) 0xffff)] (if (>= s 0x8000) (- s 0x10000) s))) +(defn core-unchecked-byte [x] (band (math/trunc x) 0xff)) +(defn core-unchecked-short [x] (band (math/trunc x) 0xffff)) +(defn core-unchecked-char [x] (band (math/trunc x) 0xffff)) +(defn core-unchecked-float [x] (* 1.0 x)) +(defn core-unchecked-double [x] (* 1.0 x)) + +# 64-bit integers (Janet int/s64 — C-backed) +(defn core-bigint [x] (int/s64 x)) +(defn core-biginteger [x] (int/s64 x)) +(defn core-bigdec [x] (* 1.0 x)) # no BigDecimal; use a double + +# Chunked seqs — Jolt does not chunk, so these are simple eager equivalents. +(defn core-chunk-buffer [capacity] @[]) +(defn core-chunk-append [b x] (array/push b x) b) +(defn core-chunk [b] b) +# chunked-seq? now lives in the Clojure collection tier (always false on Jolt). +(defn core-chunk-first [s] (core-first s)) +(defn core-chunk-rest [s] (core-rest s)) +(defn core-chunk-next [s] (core-next s)) +(defn core-chunk-cons [chunk rest] (core-concat (realize-for-iteration chunk) rest)) + +# More clojure.core: real implementations backed by existing Jolt machinery. +(defn core-boolean [x] (if x true false)) +(defn core-cat [rf] + (fn [& a] + (case (length a) + 0 (rf) 1 (rf (a 0)) + (do (var acc (a 0)) (each x (realize-for-iteration (a 1)) (set acc (rf acc x))) acc)))) +(defn core-random-sample [prob & rest] + (if (= 0 (length rest)) + (core-filter (fn [_] (< (math/random) prob))) + (core-filter (fn [_] (< (math/random) prob)) (in rest 0)))) +(defn core-reader-conditional [form splicing?] + @{:jolt/type :jolt/reader-conditional :form form :splicing? splicing?}) +# reader-conditional? now lives in the Clojure collection tier (tagged-value predicate). +# The user comparator is a Clojure IFn; wrap it as a Janet 2-arg fn returning the +# numeric compare result, then thread it through the sorted wrapper. +(defn core-sorted-map-by [cmp & kvs] + (let [jc (fn [a b] (jolt-call cmp a b))] + (var m @{}) (var i 0) + (while (< i (length kvs)) (put m (kvs i) (kvs (+ i 1))) (+= i 2)) + (sm-make (table/to-struct m) jc))) +(defn core-sorted-set-by [cmp & xs] + (let [jc (fn [a b] (jolt-call cmp a b))] + (var seen @{}) (each x xs (put seen x true)) + (ss-make (sorted-by jc (array ;(keys seen))) jc))) +(defn core-array-seq [arr & _] (core-seq arr)) +(defn core-seque [& args] (in args (- (length args) 1))) +(defn core-supers [x] (make-phs)) +(defn core-class [x] + (cond + (nil? x) nil (number? x) "java.lang.Number" (string? x) "java.lang.String" + (boolean? x) "java.lang.Boolean" (keyword? x) "clojure.lang.Keyword" + (function? x) "clojure.lang.IFn" (buffer? x) "[B" + (string (type x)))) +(defn core-clojure-version [] "1.11.0-jolt") +(defn core-munge [s] + (string/replace-all "-" "_" (string s))) +(defn core-test [v] + (let [t (and (core-meta v) (get (core-meta v) :test))] + (if t (do (t) :ok) :no-test))) + + +# ============================================================ +# Bit operations (needed for persistent data structures) +# ============================================================ + +(def core-bit-and (fn [a b] (band a b))) +(def core-bit-or (fn [a b] (bor a b))) +(def core-bit-xor (fn [a b] (bxor a b))) +(def core-bit-not (fn [a] (bnot a))) +(def core-bit-shift-left (fn [x n] (blshift x n))) +(def core-bit-shift-right (fn [x n] (brshift x n))) +(def core-bit-clear (fn [x n] (band x (bnot (blshift 1 n))))) +(def core-bit-set (fn [x n] (bor x (blshift 1 n)))) +(def core-bit-flip (fn [x n] (bxor x (blshift 1 n)))) +(def core-bit-test (fn [x n] (not= 0 (band x (blshift 1 n))))) +(def core-bit-and-not (fn [a b] (band a (bnot b)))) +(def core-unsigned-bit-shift-right (fn [x n] (brushift x n))) + +# ============================================================ +# Integer coercion +# ============================================================ + +(def core-int (fn [x] (if (core-char? x) (x :ch) (math/trunc x)))) +(def core-long (fn [x] (if (core-char? x) (x :ch) (math/trunc x)))) +(def core-double (fn [x] (* 1.0 (if (core-char? x) (x :ch) x)))) +(def core-float core-double) +(def core-num (fn [x] (if (number? x) x (error (string "num requires a number, got " (type x)))))) +(defn core-char [x] + "(char code-or-char) -> a character value." + (cond + (core-char? x) x + (number? x) (make-char (math/trunc x)) + (string? x) (make-char (in x 0)) + (error "char expects a number or character"))) +(def core-unchecked-inc (fn [x] (+ x 1))) +(def core-unchecked-dec (fn [x] (- x 1))) +(def core-unchecked-add (fn [& xs] (+ ;xs))) +(def core-unchecked-subtract (fn [& xs] (- ;xs))) + +# ============================================================ +# Hash +# ============================================================ + +(def core-hash (fn [x] (hash x))) + + +# ============================================================ +# Atom +# ============================================================ + +(defn core-atom + "Create an atom. Accepts optional :validator fn and :meta map." + [val & opts] + (var atm @{:jolt/type :jolt/atom :value val :watches @{} :validator nil}) + (var i 0) + (while (< i (length opts)) + (case (opts i) + :validator (put atm :validator (opts (+ i 1))) + :meta (let [m (opts (+ i 1))] + (var meta-tab @{}) + (each k (keys m) (put meta-tab k (get m k))) + (table/setproto atm meta-tab) + (put atm :jolt/meta m))) + (+= i 2)) + atm) + +# atom? now lives in the Clojure collection tier (tagged-value predicate). + +# Futures — run the body on a real OS thread (ev/thread) for true parallelism. +# Janet threads have separate heaps, so the thunk and the state it closes over are +# MARSHALLED (copied) to the worker thread and the result is marshalled back. A +# future therefore sees a *snapshot* of captured state and communicates only via +# its return value — mutating a captured atom does not propagate to the parent. +# Coordination uses two channels: a thread-chan carries the single [:ok v] / +# [:error e] result back, and a parent-local chan acts as a broadcast latch that +# is closed when the result lands so any number of deref-ers can unpark. +(defn core-future? [x] (and (table? x) (= :jolt/future (x :jolt/type)))) + +(defn core-future-call [thunk] + (def tc (ev/thread-chan 1)) # worker thread -> collector (shared, thread-safe) + (def latch (ev/chan)) # parent-local: closed when the result is in + (def fut @{:jolt/type :jolt/future :latch latch :cached false :res nil :cancelled false}) + # Worker: compute on a fresh OS thread, send back a marshalled result. The give + # is guarded so a non-marshallable value can't strand deref-ers forever. + (ev/spawn-thread + (def res (try [:ok (thunk)] ([e] [:error e]))) + (try (ev/give tc res) + ([_] (ev/give tc [:error "future result is not marshallable across threads"])))) + # Collector: a parent-side fiber bridges the single result into the box and + # closes the latch to wake every waiter. If the future was already cancelled, + # the box is finalized — drop the late result and don't re-close the latch. + (ev/spawn + (def res (ev/take tc)) + (when (not (fut :cancelled)) + (put fut :res res) + (put fut :cached true) + (try (ev/chan-close latch) ([_] nil)))) + fut) + +(defn- future-result [fut] + (def res (fut :res)) + (if (= :error (in res 0)) (error (in res 1)) (in res 1))) + +# future-done? / future-cancelled? now live in the Clojure collection tier (pure +# reads of :cached/:cancelled). core-future? stays — deref/future-cancel call it. +# Janet OS threads can't be interrupted, so the worker still runs to completion +# in the background; we can only mark the *future* cancelled (done) so deref +# raises and realized?/future-done?/future-cancelled? reflect it. Returns false +# if the future has already completed (matching Clojure). +(defn core-future-cancel [x] + (if (and (core-future? x) (not (x :cached)) (not (x :cancelled))) + (do + (put x :cancelled true) + (put x :res [:error "future cancelled"]) + (put x :cached true) + (try (ev/chan-close (x :latch)) ([_] nil)) + true) + false)) + +# future macro: (future body...) -> (future-call (fn* [] body...)) +(defn core-deref [ref & opts] + (cond + (and (table? ref) (= :jolt/reduced (ref :jolt/type))) + (ref :val) + (and (table? ref) (= :jolt/atom (ref :jolt/type))) + (ref :value) + (and (table? ref) (= :jolt/volatile (ref :jolt/type))) + (ref :val) + (and (table? ref) (= :jolt/delay (ref :jolt/type))) + (if (ref :realized) (ref :val) + (let [v ((ref :fn))] (put ref :val v) (put ref :realized true) v)) + (and (table? ref) (= :jolt/future (ref :jolt/type))) + (if (empty? opts) + (do (when (not (ref :cached)) (ev/take (ref :latch))) (future-result ref)) + # (deref future timeout-ms timeout-val): wait at most timeout-ms. The + # deadline cancels the parked take; if the result still hasn't landed we + # return the supplied timeout value (the future keeps running). + (let [timeout-val (in opts 1)] + (when (not (ref :cached)) + (try (ev/with-deadline (/ (in opts 0) 1000) (ev/take (ref :latch))) ([_] nil))) + (if (ref :cached) (future-result ref) timeout-val))) + (and (table? ref) (= :jolt/var (ref :jolt/type))) + (ref :root) + ref)) + +(defn- atom-validate + "Call validator on atm. Returns the value if valid, errors otherwise." + [atm val] + (let [v (atm :validator)] + (if v + (if (v val) val + (error "Validator rejected value")) + val))) + +(defn- atom-notify-watches + [atm old-val new-val] + (loop [[k w] :pairs (atm :watches)] + (w k atm old-val new-val))) + +(defn core-reset! [atm val] + (let [old-val (atm :value)] + (atom-validate atm val) + (put atm :value val) + (atom-notify-watches atm old-val val) + val)) + +(defn core-swap! [atm f & args] + (var old-val (atm :value)) + (var new-val (apply f old-val args)) + (atom-validate atm new-val) + (put atm :value new-val) + (atom-notify-watches atm old-val new-val) + new-val) + +# Atom peripheral ops (swap-vals!/reset-vals!/compare-and-set!/get-validator/ +# add-watch/remove-watch/set-validator!) now live in the Clojure collection tier — +# composed over the native atom ops + jolt.host/ref-put!. atom/swap!/reset!/deref +# and the atom-validate/atom-notify-watches helpers stay native (compiler-critical). + +# ============================================================ +# Threading macros (as regular functions? No, as macros in Clojure) +# These need to be defined as macros in the Jolt namespace system. +# For now, skip — they need proper macro definition via the evaluator. +# ============================================================ + +# ============================================================ +# Initialization — intern everything into a context's namespace +# ============================================================ + +(def gensym_counter @{:val 0}) + +(defn gensym + "Returns a new symbol with a unique name." + [&opt prefix-string] + (default prefix-string "G__") + (def n (get gensym_counter :val)) + (put gensym_counter :val (+ n 1)) + {:jolt/type :symbol :ns nil :name (string prefix-string n)}) + + +# if-let/when-let/if-some/when-some now live in the Clojure overlay +# (core/30-macros.clj) as defmacros. + +(defn core-push-thread-bindings [b] (push-thread-bindings b)) +(defn core-pop-thread-bindings [] (pop-thread-bindings)) + +(defn core-var-get [v] (var-get v)) +(defn core-var-set [v val] (var-set v val)) +(defn core-var? [x] (var? x)) +(defn core-alter-var-root [v f & args] (apply alter-var-root v f args)) +(defn core-alter-meta! [v f & args] (apply alter-meta! v f args)) +(defn core-reset-meta! [v meta] (reset-meta! v meta)) + +# intern is a ctx-capturing clojure.core fn now (install-stateful-fns!). + +# Hierarchy stubs for sci bootstrap +(def core-make-hierarchy make-hierarchy) +(defn core-derive + [& args] + (case (length args) + 2 (let [[tag parent] args] (derive* the-global-hierarchy tag parent) nil) + 3 (let [[h tag parent] args] (derive* h tag parent)))) +(defn core-isa? + [& args] + (case (length args) + 2 (let [[child parent] args] (isa? the-global-hierarchy child parent)) + 3 (let [[h child parent] args] (isa? h child parent)))) +(defn core-ancestors + [& args] + (case (length args) + 1 (apply make-phs (ancestors the-global-hierarchy (in args 0))) + 2 (let [[h tag] args] (apply make-phs (ancestors h tag))))) +(defn core-descendants + [& args] + (case (length args) + 1 (apply make-phs (descendants the-global-hierarchy (in args 0))) + 2 (let [[h tag] args] (apply make-phs (descendants h tag))))) +(defn core-parents + [& args] + (let [[h tag] (if (= 1 (length args)) [the-global-hierarchy (in args 0)] args) + p (get (h :parents) tag)] + (if p (make-phs p) (make-phs)))) +(defn core-underive [& args] + (case (length args) + 2 (let [[tag parent] args] (underive the-global-hierarchy tag parent) nil) + 3 (let [[h tag parent] args] (underive h tag parent)))) +(def core-get-method (fn [mm-var dispatch-val] + (let [methods (get mm-var :jolt/methods)] + (or (get methods dispatch-val) (get methods :default))))) +(def core-methods (fn [mm-var] (get mm-var :jolt/methods))) +(def core-remove-method (fn [mm-var dispatch-val] + (let [methods (get mm-var :jolt/methods)] + (put methods dispatch-val nil) mm-var))) +(def core-remove-all-methods (fn [mm-var] + (put mm-var :jolt/methods @{}) mm-var)) +(defn core-prefer-method [mm-var dispatch-val-a dispatch-val-b] + (let [prefs (or (get mm-var :jolt/prefers) + (do (put mm-var :jolt/prefers @{}) (mm-var :jolt/prefers)))] + (put prefs dispatch-val-a dispatch-val-b) mm-var)) + +(defn core-with-meta [obj meta] + # Functions and scalars can't carry metadata in Jolt's model — return as-is + # rather than crashing (Clojure attaches meta only to IObj values). + (if (or (function? obj) (cfunction? obj) (number? obj) (boolean? obj) + (nil? obj) (string? obj) (keyword? obj) (buffer? obj)) + obj + (do + (var new-obj @{}) + (each k (keys obj) + (put new-obj k (get obj k))) + # table/setproto requires a table, convert struct meta to table. meta may + # be nil (Clojure allows (with-meta obj nil) to clear metadata). + (var meta-tab @{}) + (when meta (each k (keys meta) (put meta-tab k (get meta k)))) + (table/setproto new-obj meta-tab) + (put new-obj :jolt/meta meta) + new-obj))) + +(defn core-var-dynamic? [v] + (var-dynamic? v)) + +# Java interop stubs +(def core-Object (fn [] (struct ;[:jolt/type :jolt/java-object]))) + +# Volatiles — typed box so deref/volatile? can recognize them. +(defn core-volatile! [v] @{:jolt/type :jolt/volatile :val v}) +# volatile? / vreset! / vswap! now live in the Clojure collection tier — vreset! +# over jolt.host/ref-put!, vswap! over vreset! + get. The constructor stays native. + +# Delays — created lazily by the `delay` macro; forced once via force/deref. +(defn core-make-delay [thunk] @{:jolt/type :jolt/delay :fn thunk :realized false :val nil}) +(defn core-delay? [x] (and (table? x) (= :jolt/delay (x :jolt/type)))) +(defn core-force [x] + (if (core-delay? x) + (if (x :realized) (x :val) + (let [v ((x :fn))] (put x :val v) (put x :realized true) v)) + x)) +(defn core-realized? [x] + (cond + (core-delay? x) (x :realized) + (core-future? x) (truthy? (x :cached)) + (lazy-seq? x) (truthy? (x :realized)) + (and (table? x) (= :jolt/atom (x :jolt/type))) true + # Clojure's realized? is only defined on IPending; reject anything else. + (error (string "realized? not supported on " (type x))))) + + +# Proxy stub — returns nil form (macro, args not evaluated) +# Thread stubs +(def core-Thread (fn [& args] (struct ;[:jolt/type :jolt/thread]))) +(def core-ThreadLocal (fn [& args] (struct ;[:jolt/type :jolt/thread-local]))) +(def core-IllegalStateException (fn [& args] (struct ;[:jolt/type :jolt/exception]))) + + + +# letfn — mutually-recursive local fns. Expands to let* of fn* bindings; jolt +# closures capture the (shared, mutable) bindings table, so forward references +# between the fns resolve at call time. + +# doseq — like `for` but eager and returns nil. Reuse `for`, force realization +# with `count`, discard the result. +# assert — (assert x) / (assert x message). Throws when x is falsy. + +# resolve stub — returns nil (symbols not found in Jolt's clojure.core) +(defn core-resolve [sym] nil) # shadowed by the resolve special form (needs ctx) +# ns-name now lives in the Clojure collection tier (pure over get + symbol). + +# update lives in the Clojure kernel tier — core/00-kernel.clj. update-in stays +# (it's recursive and has internal callers). +(defn- ks-rest [ks] + (if (tuple? ks) (tuple/slice ks 1) (array/slice ks 1))) + +(defn core-assoc-in [m ks v] + (let [ks (vview ks) k (in ks 0)] + (if (<= (length ks) 1) + (core-assoc m k v) + (let [sub (core-get m k)] + (core-assoc m k (core-assoc-in (if (nil? sub) {} sub) (ks-rest ks) v)))))) + +(defn core-update-in [m ks f & args] + (let [ks (vview ks) k (in ks 0)] + (if (<= (length ks) 1) + (core-assoc m k (apply f (core-get m k) args)) + (let [sub (core-get m k)] + (core-assoc m k (apply core-update-in (if (nil? sub) {} sub) (ks-rest ks) f args)))))) + +(defn core-fnil [f & defaults] + (fn [& args] + (def new-args (array/slice args)) + (var i 0) + (each d defaults + (when (and (< i (length new-args)) (nil? (in new-args i))) + (put new-args i d)) + (++ i)) + (apply f new-args))) + +# copy-var stubs for sci.impl.copy-vars (used by sci.impl.namespaces) +(defn core-copy-core-var [sym] nil) +(defn core-copy-var [sym & args] nil) +(defn core-macrofy [sym fn & more] fn) +(defn core-new-var [sym & args] nil) +(defn core-avoid-method-too-large [& args] @{}) + +# declare macro — accepts symbols, does nothing (forward declaration) + +# Build a protocol value (a self-evaluating tagged table). Exposed so the overlay +# `defprotocol` can construct one via a fn call rather than embedding a tagged +# struct literal (which the interpreter would try to re-evaluate). `methods` is a +# {kw {:name str}} map; only :name is consulted (by satisfies?). +(defn core-make-protocol [name-str methods] + @{:jolt/type :jolt/protocol + :name {:jolt/type :symbol :ns nil :name name-str} + :methods methods}) + +(def core-satisfies? (fn [proto-sym obj] false)) + +(def core-extends? (fn [& args] false)) +(def core-implements? (fn [& args] false)) +(def core-type->str (fn [& args] "")) + +# ============================================================ +# Additional clojure.core functions (conformance batch) +# ============================================================ + +(defn core-find [m k] + (cond + (phm? m) (if (phm-contains? m k) [k (phm-get m k)] nil) + (or (struct? m) (table? m)) (let [v (get m k :jolt/nf)] (if (= v :jolt/nf) nil [k v])) + nil)) + +(defn core-keyword + "(keyword name) or (keyword ns name). Namespaced keywords are `:ns/name`. + (keyword nil) is nil; the 2-arg form requires string args (nil ns allowed)." + [& args] + (case (length args) + 1 (let [a (in args 0)] + (cond + (nil? a) nil + (keyword? a) a + (or (string? a) (core-symbol? a)) (keyword (core-name a)) + (error (string "keyword requires a string, symbol or keyword, got " (type a))))) + 2 (let [ns (in args 0) nm (in args 1)] + (when (not (and (or (nil? ns) (string? ns)) (string? nm))) + (error "keyword ns and name must be strings")) + (keyword (if ns (string ns "/" nm) nm))) + (keyword ;args))) + +(defn core-symbol + "(symbol name) or (symbol ns name) -> a jolt symbol struct. name/ns must be + strings (a single symbol arg is returned as-is)." + [& args] + (case (length args) + 1 (let [a (in args 0)] + (cond + (core-symbol? a) a + (or (string? a) (keyword? a)) {:jolt/type :symbol :ns nil :name (core-name a)} + (error (string "symbol requires a string or symbol, got " (type a))))) + 2 (let [ns (in args 0) nm (in args 1)] + (when (not (and (or (nil? ns) (string? ns)) (string? nm))) + (error "symbol ns and name must be strings")) + {:jolt/type :symbol :ns ns :name nm}) + (error "symbol expects 1 or 2 args"))) + +(defn- td-take-nth [n] + (fn [rf] + (var i 0) + (fn [& a] (case (length a) 0 (rf) 1 (rf (a 0)) + (let [keep (= 0 (mod i n))] (++ i) + (if keep (rf (a 0) (a 1)) (a 0))))))) +(defn core-take-nth [n & rest] + (if (= 0 (length rest)) (td-take-nth n) + (let [coll (in rest 0)] + # Option A: always lazy. + (defn tstep [c] + (fn [] + (if (seq-done? c) nil + (let [drop-n (lazy-from (core-drop n c))] + (if (seq-done? drop-n) @[(core-first c) nil] + @[(core-first c) (tstep drop-n)]))))) + (make-lazy-seq (tstep (lazy-from coll)))))) + +# filterv now lives in the Clojure collection tier (core/20-coll.clj). + +# mapv lives in the Clojure kernel tier — core/00-kernel.clj. + +(defn- td-interpose [sep] + (fn [rf] + (var started false) + (fn [& a] (case (length a) 0 (rf) 1 (rf (a 0)) + (if started (rf (rf (a 0) sep) (a 1)) + (do (set started true) (rf (a 0) (a 1)))))))) +(defn core-interpose [sep & rest] + (if (= 0 (length rest)) (td-interpose sep) + (let [coll (in rest 0)] + # Option A: always lazy. + (defn istep [c need-sep] + (fn [] + (if (seq-done? c) nil + (if need-sep + @[sep (istep c false)] + @[(core-first c) (istep (core-rest c) true)])))) + (make-lazy-seq (istep (lazy-from coll) false))))) + +# keep now lives in the Clojure lazy tier (core/40-lazy.clj). + +(defn core-empty [coll] + (cond + (phm? coll) (make-phm) + (set? coll) (make-phs) + (plist? coll) EMPTY-PLIST + (pvec? coll) (make-vec @[]) + (struct? coll) (struct) + (tuple? coll) (make-vec @[]) + (array? coll) @[] + (table? coll) @{} + nil)) + +# not-empty now lives in the Clojure collection tier (core/20-coll.clj). + +# rseq is defined only on vectors and sorted collections (Reversible). +(defn core-rseq [coll] + (cond + (pvec? coll) (tuple/slice (tuple ;(reverse (pv->array coll)))) + (core-sorted-map? coll) (tuple/slice (tuple ;(reverse (sorted-map-entries coll)))) + (core-sorted-set? coll) (tuple/slice (tuple ;(reverse (coll :items)))) + (error (string "rseq requires a vector or sorted collection, got " (type coll))))) + +(defn core-shuffle [coll] + (when (not (core-coll? coll)) (error (string "shuffle requires a collection, got " (type coll)))) + (let [c (array/slice (realize-for-iteration coll))] + (var i (- (length c) 1)) + (while (> i 0) + (let [j (math/floor (* (math/random) (+ i 1))) + tmp (in c i)] + (put c i (in c j)) (put c j tmp)) + (-- i)) + (tuple/slice (tuple ;c)))) + +# some-fn now lives in the Clojure collection tier (core/20-coll.clj). + +(defn core-sequential? [x] (or (tuple? x) (array? x) (pvec? x) (plist? x) (lazy-seq? x))) +# Associative = maps and (real) vectors only. pvec is a literal/built vector; +# tuples and lists are seq results, not associative. +(defn core-associative? [x] + (or (pvec? x) (phm? x) (core-sorted-map? x) + (and (struct? x) (nil? (get x :jolt/type))))) +(defn core-ifn? [x] + (or (function? x) (cfunction? x) (keyword? x) (phm? x) (set? x) (tuple? x) (array? x) (pvec? x) + (and (struct? x) (= :symbol (x :jolt/type))))) +(defn core-indexed? [x] (or (tuple? x) (array? x) (pvec? x))) + + +# With a single item, Clojure returns it WITHOUT calling f. On ties, the last +# extremal item wins (>=/<= update), matching Clojure. +# Clojure's min-key/max-key: the 2-arg base compares with strict < / > (so the +# second wins on ties/NaN), and each further item switches on <= / >=. This +# asymmetry reproduces the JVM's NaN-ordering behavior. Janet's < / > are used +# directly (NaN comparisons are false, never throwing). +# keys must be numbers (NaN allowed) — like Clojure, which compares them with . +# min-key / max-key now live in the Clojure collection tier (core/20-coll.clj). + +# vary-meta / namespace-munge now live in the Clojure collection tier +# (core/20-coll.clj) — pure compositions of meta/with-meta and str/map. + +# Exceptions (ex-info / ex-data / ex-message) +(defn core-ex-info [msg data & more] + @{:jolt/type :jolt/ex-info :message msg :data data + :cause (if (> (length more) 0) (in more 0) nil)}) +# ex-data / ex-message / ex-cause now live in the Clojure collection tier +# (core/20-coll.clj) — pure over get on the tagged value the constructor builds. + +# String split/replace that accept either a literal string or a regex value. +(defn core-str-split [pat s] + (if (regex? pat) + (re-split pat s) + (string/split pat s))) +(defn core-str-replace-all [pat repl s] + (if (regex? pat) + (re-replace-all pat s repl) + (string/replace-all pat repl s))) +(defn core-str-replace-first [pat repl s] + (if (regex? pat) + (re-replace-first pat s repl) + (string/replace pat repl s))) + +(defn core-prn-str [& xs] (string (apply core-pr-str xs) "\n")) +(defn core-println-str [& xs] + (var parts @[]) (each x xs (array/push parts (str-render-one x))) + (string (string/join parts " ") "\n")) + +# Iterator/enumeration seqs — Jolt has no Java iterators, so adapt to plain seq. +(defn core-enumeration-seq [x] (core-seq x)) +(defn core-iterator-seq [x] (core-seq x)) +# xml-seq now lives in the Clojure collection tier (core/20-coll.clj). +(defn core-line-seq [rdr] + (if (string? rdr) (core-seq (string/split "\n" rdr)) nil)) +(defn core-re-matcher [re s] @{:jolt/type :jolt/matcher :re re :s s :pos 0}) + +# JVM reflection / proxies — not applicable on a Janet host; resolve-only. +(defn core-bean [x] (if (core-map? x) x {})) +(defn core-print-method [x writer] nil) +(defn core-print-dup [x writer] nil) +(defn core-proxy-call-with-super [f proxy meth] (f)) +(defn core-proxy-mappings [proxy] {}) +(defn core-update-proxy [proxy mappings] proxy) +(defn core-numeric= [& args] + (if (< (length args) 2) true + (do (var ok true) (var i 0) + (while (and ok (< i (dec (length args)))) + (unless (= (in args i) (in args (+ i 1))) (set ok false)) (++ i)) + ok))) +(defn core-print-str [& xs] + (var parts @[]) (each x xs (array/push parts (str-render-one x))) + (string/join parts " ")) +(defn core-memfn [& args] (error "memfn: JVM method handles are not supported in Jolt")) +(defn core-eduction [& args] + # (eduction xform* coll): apply the composed transducers eagerly to coll + (let [n (length args) + coll (in args (- n 1)) + xforms (array/slice args 0 (- n 1)) + xform (if (= 0 (length xforms)) (fn [rf] rf) (apply core-comp xforms))] + (core-into (make-vec @[]) xform coll))) +(defn core->Eduction [xform coll] (core-into (make-vec @[]) xform coll)) +(defn core-proxy-super [& args] (error "proxy-super: JVM proxies are not supported in Jolt")) +(defn core-construct-proxy [c & args] (error "construct-proxy: not supported in Jolt")) +(defn core-init-proxy [proxy mappings] proxy) +(defn core-get-proxy-class [& interfaces] (error "get-proxy-class: not supported in Jolt")) + +(def- char-escapes + {10 "\\n" 9 "\\t" 13 "\\r" 12 "\\f" 8 "\\b" 34 "\\\"" 92 "\\\\"}) +(def- char-names + {10 "newline" 9 "tab" 13 "return" 12 "formfeed" 8 "backspace" 32 "space"}) +(defn core-char-escape-string [c] + (get char-escapes (if (core-char? c) (char-code c) c))) +(defn core-char-name-string [c] + (get char-names (if (core-char? c) (char-code c) c))) + +# subseq / rsubseq over sorted collections +(defn- sorted-entries [sc] + (cond + (core-sorted-map? sc) (sorted-map-entries sc) + (core-sorted-set? sc) (map (fn [x] x) (sc :items)) + (realize-for-iteration sc))) +(defn- sorted-key-of [sc e] (if (core-sorted-map? sc) (in e 0) e)) +(defn core-subseq [sc & args] + (let [es (sorted-entries sc)] + (tuple ;(filter + (fn [e] (let [k (sorted-key-of sc e)] + (if (= 2 (length args)) + (truthy? ((args 0) k (args 1))) + (and (truthy? ((args 0) k (args 1))) (truthy? ((args 2) k (args 3))))))) + es)))) +(defn core-rsubseq [sc & args] + (tuple ;(reverse (apply core-subseq sc args)))) + +# ============================================================ +# Additional clojure.core functions +# ============================================================ + +# Integer-valued: a finite number equal to its floor. Infinity floors to itself +# but is NOT integer-valued (so float?/double? are true for ##Inf, and int?/ +# pos-int?/… are false), and NaN is excluded by the equality check. +(defn- intval? [x] (and (number? x) (< (math/abs x) math/inf) (= x (math/floor x)))) + +# Forcing lazy seqs +(defn core-doall [a & rest] + (let [coll (if (= 0 (length rest)) a (in rest 0))] + (realize-for-iteration coll) coll)) +(defn core-dorun [a & rest] + (let [coll (if (= 0 (length rest)) a (in rest 0))] + (realize-for-iteration coll) nil)) + +# Map entries (represented as 2-element vectors) +# key/val require a map entry (a 2-element vector/tuple in Jolt); Clojure throws +# otherwise. (Jolt can't distinguish a 2-vector from a real MapEntry.) +# A map entry is a 2-element tuple — Jolt produces tuples only from map +# iteration (first/seq/map over a map), while vector literals are pvecs and +# lists are arrays. So key/val/map-entry? accept a 2-tuple and reject a plain +# vector, matching Clojure (where a MapEntry is distinct from a vector). +(defn- entry-like? [x] (and (tuple? x) (= 2 (length x)))) +(defn core-key [e] (if (entry-like? e) (in e 0) (error "key requires a map entry"))) +(defn core-val [e] (if (entry-like? e) (in e 1) (error "val requires a map entry"))) +(defn core-map-entry? [x] (entry-like? x)) + +(defn core-rand-nth [coll] + (let [c (realize-for-iteration coll)] + (in c (math/floor (* (math/random) (length c)))))) + +(defn core-counted? [x] + (or (pvec? x) (plist? x) (phm? x) (set? x) (tuple? x) (array? x) (string? x))) +# Reversible (supports rseq) = vectors and sorted collections. +(defn core-reversible? [x] (or (pvec? x) (core-sorted-map? x) (core-sorted-set? x))) +(defn core-seqable? [x] + (or (nil? x) (tuple? x) (array? x) (pvec? x) (plist? x) (phm? x) (set? x) + (struct? x) (lazy-seq? x) (string? x) + (and (table? x) (or (get x :jolt/type) (get x :jolt/deftype))))) + +# Numeric predicates (Jolt has no ratios/bigdec). nat-int?/pos-int?/neg-int?/ +# ratio?/decimal?/rational? live in the Clojure collection tier (core/20-coll.clj). +(defn core-double? [x] (and (number? x) (not (intval? x)))) +(defn core-float? [x] (and (number? x) (not (intval? x)))) +(defn core-infinite? [x] (and (number? x) (= (math/abs x) math/inf))) +# Jolt has no ratio type, so numerator/denominator have no valid input (Clojure +# requires a Ratio and throws otherwise). +(defn core-numerator [x] (error "numerator requires a ratio (Jolt has no ratios)")) +(defn core-denominator [x] (error "denominator requires a ratio (Jolt has no ratios)")) + +(defn core-list* [& args] + (let [n (length args)] + (if (= 0 n) nil + (let [head (array/slice args 0 (- n 1)) + tail (realize-for-iteration (in args (- n 1)))] + (var r (if (array? tail) tail (array ;tail))) + (var i (- (length head) 1)) + (while (>= i 0) (set r (pl-cons (in head i) r)) (-- i)) + r)))) + +(def- special-syms + {"if" true "do" true "let*" true "fn*" true "quote" true "var" true "def" true + "loop*" true "recur" true "throw" true "try" true "catch" true "finally" true + "new" true "set!" true "." true "monitor-enter" true "monitor-exit" true}) +(defn core-special-symbol? [x] + (and (core-symbol? x) (= true (get special-syms (x :name))))) + +# record? now lives in the Clojure collection tier (tagged-value predicate). + +# Promise: single-threaded box backed by an atom (deref returns nil until set). +(defn core-promise [] (core-atom nil)) +(defn core-deliver [p v] (core-reset! p v) p) + +(defn core-tagged-literal [tag form] @{:jolt/type :jolt/tagged-literal :tag tag :form form}) +(defn core-ensure-reduced [x] (if (core-reduced? x) x (core-reduced x))) +(defn core-halt-when [pred & rest] + (let [retf (if (> (length rest) 0) (in rest 0) nil)] + (fn [rf] + (fn [& a] + (case (length a) + 0 (rf) + 1 (rf (in a 0)) + (if (truthy? (pred (in a 1))) + (core-reduced (if retf (retf (rf (in a 0)) (in a 1)) (in a 1))) + (rf (in a 0) (in a 1)))))))) +(defn core-re-groups [m] (error "re-groups: stateful matchers are not supported in Jolt")) + +# Transients — real mutable scratch collections backed by Janet's native arrays +# and tables (host interop): O(1) conj!/assoc!/dissoc!/disj!/pop!, frozen back to +# a persistent value by persistent!. A transient is a tagged table holding either +# a Janet array (vectors) or a Janet table keyed by canonical key (maps/sets, so +# collection keys still compare by value). The mutating ops return the transient. +(defn core-transient [coll] + (cond + (pvec? coll) + @{:jolt/type :jolt/transient :kind :vector :arr (pv->array coll)} + (set? coll) + (let [t @{}] (each e (phs-seq coll) (put t (canon-key e) e)) + @{:jolt/type :jolt/transient :kind :set :tbl t}) + (or (phm? coll) (and (struct? coll) (nil? (get coll :jolt/type)))) + (let [t @{}] + (each pair (realize-for-iteration coll) + (put t (canon-key (in pair 0)) @[(in pair 0) (in pair 1)])) + @{:jolt/type :jolt/transient :kind :map :tbl t}) + # mutable-build arrays (vectors/lists) — copy into a transient vector + (array? coll) @{:jolt/type :jolt/transient :kind :vector :arr (array/slice coll)} + (error (string "Don't know how to create a transient from " (type coll))))) + +# A transient is invalidated by persistent!; using it afterwards is a bug. +(defn- tr-check-active! [t] + (when (get t :jolt/persistent) + (error "Transient used after persistent! call"))) + +(defn- tr-conj! [t x] + (tr-check-active! t) + (case (t :kind) + :vector (array/push (t :arr) x) + :set (put (t :tbl) (canon-key x) x) + :map (cond + # a [k v] pair (map-entry / 2-vector) + (and (or (pvec? x) (tuple? x) (array? x)) + (= 2 (if (pvec? x) (pv-count x) (length x)))) + (put (t :tbl) (canon-key (vnth x 0)) @[(vnth x 0) (vnth x 1)]) + # a map: merge all its entries + (or (phm? x) (and (struct? x) (nil? (get x :jolt/type)))) + (each e (map-entries-of x) + (put (t :tbl) (canon-key (in e 0)) @[(in e 0) (in e 1)])) + (error "conj! on a transient map requires a [key value] pair or a map"))) + t) + +(defn- tr-assoc! [t k v] + (tr-check-active! t) + (case (t :kind) + :vector (let [a (t :arr)] + (when (not (and (number? k) (= k (math/floor k)) (>= k 0) (<= k (length a)))) + (error (string "Index " k " out of bounds for assoc! on a transient vector of length " (length a)))) + (if (= k (length a)) (array/push a v) (put a k v))) + :map (put (t :tbl) (canon-key k) @[k v]) + (error "assoc! expects a transient vector or map")) + t) + +# The bang ops require a transient (Clojure throws otherwise); no lenient +# fallback to the persistent op. +(defn core-conj! [& args] + (cond + (= 0 (length args)) (core-transient (make-vec @[])) # (conj!) -> (transient []) + (= 1 (length args)) (first args) # (conj! coll) -> coll, as-is + (let [t (first args) xs (tuple/slice args 1)] + (if (core-transient? t) + (do (each x xs (tr-conj! t x)) t) + (error "conj! requires a transient"))))) + +(defn core-assoc! [t & kvs] + # Unlike assoc, assoc! accepts an ODD number of args — a missing final value + # is taken as nil (so (get kvs (+ i 1)) rather than (in ...), which would + # error on the dangling key). + (if (core-transient? t) + (do (var i 0) (while (< i (length kvs)) (tr-assoc! t (in kvs i) (get kvs (+ i 1))) (+= i 2)) t) + (error "assoc! requires a transient"))) + +(defn core-dissoc! [t & ks] + (if (and (core-transient? t) (= :map (t :kind))) + (do (tr-check-active! t) (each k ks (put (t :tbl) (canon-key k) nil)) t) + (error "dissoc! requires a transient map"))) + +(defn core-disj! [t & xs] + (if (and (core-transient? t) (= :set (t :kind))) + (do (tr-check-active! t) (each x xs (put (t :tbl) (canon-key x) nil)) t) + (error "disj! requires a transient set"))) + +(defn core-pop! [t] + (if (and (core-transient? t) (= :vector (t :kind))) + (do (tr-check-active! t) + (when (= 0 (length (t :arr))) (error "Can't pop empty vector")) + (array/pop (t :arr)) t) + (error "pop! requires a transient vector"))) + +(defn core-persistent! [t] + (if (core-transient? t) + (do + (tr-check-active! t) + (def result + (case (t :kind) + :vector (make-vec (t :arr)) + :set (do (var s (make-phs)) (each [_ e] (pairs (t :tbl)) (set s (phs-conj s e))) s) + :map (do (var m (make-phm)) (each [_ pair] (pairs (t :tbl)) (set m (phm-assoc m (in pair 0) (in pair 1)))) m))) + # Invalidate: any further bang op (or a second persistent!) now throws. + (put t :jolt/persistent true) + result) + (error "persistent! requires a transient"))) + +# Unchecked arithmetic — Jolt numbers don't overflow, so these are plain ops. +(defn core-unchecked-add [a b] (+ a b)) +(defn core-unchecked-subtract [a b] (- a b)) +(defn core-unchecked-multiply [a b] (* a b)) +(defn core-unchecked-negate [a] (- a)) +(defn core-unchecked-inc [a] (+ a 1)) +(defn core-unchecked-dec [a] (- a 1)) +(defn core-unchecked-divide-int [a b] (math/trunc (/ a b))) +(defn core-unchecked-remainder-int [a b] (% a b)) +(defn core-unchecked-int [a] (math/trunc a)) + +# Hashing helpers +# Hashes are masked to 24 bits at each step so intermediate products stay within +# Janet's integer range (a float here would make band error). +(defn- h24 [x] (band (hash x) 0xffffff)) +(defn core-hash-combine [a b] (band (bxor (h24 a) (+ (h24 b) 0x9e3779)) 0xffffff)) +(defn core-hash-ordered-coll [coll] + (var h 1) (each x (realize-for-iteration coll) (set h (band (+ (* 31 h) (h24 x)) 0xffffff))) h) +(defn core-hash-unordered-coll [coll] + (var h 0) (each x (realize-for-iteration coll) (set h (band (+ h (h24 x)) 0xffffff))) h) + +(defn core-prefers [mm-var] (or (get mm-var :jolt/prefers) {})) + +(defn core-random-uuid [] + (defn hx [n] (string/format "%x" (math/floor (* (math/random) n)))) + (string (hx 0x10000) (hx 0x10000) "-" (hx 0x10000) "-4" (hx 0x1000) + "-" (hx 0x1000) "-" (hx 0x10000) (hx 0x10000) (hx 0x10000))) + +(def- core-bindings + "Map of symbol name → function for all core functions." + @{"nil?" core-nil? + "some?" core-some? + "string?" core-string? + "number?" core-number? + "fn?" core-fn? + "keyword?" core-keyword? + "symbol?" core-symbol? + "vector?" core-vector? + "map?" core-map? + "seq?" core-seq? + "coll?" core-coll? + "true?" core-true? + "false?" core-false? + "identical?" core-identical? + "zero?" core-zero? + "pos?" core-pos? + "neg?" core-neg? + "even?" core-even? + "odd?" core-odd? + "integer?" core-integer? + "boolean?" core-boolean? + "list?" core-list? + "empty?" core-empty? + "every?" core-every? + "+" core-+ + "-" core-sub + "*" core-* + "/" core-/ + "inc" core-inc + "dec" core-dec + # auto-promoting variants — Jolt numbers don't overflow, so these are the + # same as their non-quoted counterparts + "+'" core-+ + "-'" core-sub + "*'" core-* + "inc'" core-inc + "dec'" core-dec + "mod" core-mod + "rem" core-rem + "quot" core-quot + "max" core-max + "min" core-min + "rand" core-rand + "rand-int" core-rand-int + "=" core-= + "not=" core-not= + "<" core-< + ">" core-> + "<=" core-<= + ">=" core->= + "conj" core-conj + "assoc" core-assoc + "dissoc" core-dissoc + "get" core-get + "get-in" core-get-in + "contains?" core-contains? + "count" core-count + "pop" core-pop + "trampoline" core-trampoline + "format" core-format + "first" core-first + "rest" core-rest + "next" core-next + "cons" core-cons + "seq" core-seq + "vec" core-vec + "__sq1" core-sq1 + "__sqcat" core-sqcat + "__sqvec" core-sqvec + "__sqmap" core-sqmap + "__sqset" core-sqset + "into" core-into + "merge" core-merge + "merge-with" core-merge-with + "keys" core-keys + "vals" core-vals + "select-keys" core-select-keys + "with-meta" core-with-meta + "zipmap" core-zipmap + "map" core-map + "filter" core-filter + "remove" core-remove + "reduce" core-reduce + "apply" core-apply + "doall" core-doall + "dorun" core-dorun + "key" core-key + "val" core-val + "map-entry?" core-map-entry? + "rand-nth" core-rand-nth + "counted?" core-counted? + "reversible?" core-reversible? + "seqable?" core-seqable? + "double?" core-double? + "float?" core-float? + "infinite?" core-infinite? + "numerator" core-numerator + "denominator" core-denominator + "list*" core-list* + "special-symbol?" core-special-symbol? + "promise" core-promise + "deliver" core-deliver + "future-call" core-future-call + "future?" core-future? + "future-cancel" core-future-cancel + "tagged-literal" core-tagged-literal + "ensure-reduced" core-ensure-reduced + "unreduced" core-unreduced + "halt-when" core-halt-when + "re-groups" core-re-groups + "transient" core-transient + "transient?" core-transient? + "persistent!" core-persistent! + "conj!" core-conj! + "assoc!" core-assoc! + "dissoc!" core-dissoc! + "pop!" core-pop! + "unchecked-add" core-unchecked-add + "unchecked-add-int" core-unchecked-add + "unchecked-subtract" core-unchecked-subtract + "unchecked-subtract-int" core-unchecked-subtract + "unchecked-multiply" core-unchecked-multiply + "unchecked-multiply-int" core-unchecked-multiply + "unchecked-negate" core-unchecked-negate + "unchecked-negate-int" core-unchecked-negate + "unchecked-inc" core-unchecked-inc + "unchecked-inc-int" core-unchecked-inc + "unchecked-dec" core-unchecked-dec + "unchecked-dec-int" core-unchecked-dec + "unchecked-divide-int" core-unchecked-divide-int + "unchecked-remainder-int" core-unchecked-remainder-int + "unchecked-int" core-unchecked-int + "unchecked-long" core-unchecked-int + "hash-combine" core-hash-combine + "hash-ordered-coll" core-hash-ordered-coll + "hash-unordered-coll" core-hash-unordered-coll + "prefers" core-prefers + "random-uuid" core-random-uuid + "interpose" core-interpose + "mapcat" core-mapcat + "find" core-find + "transduce" core-transduce + "sequence" core-sequence + "eduction" core-sequence + "unreduced" core-unreduced + "keyword" core-keyword + "symbol" core-symbol + "namespace" core-namespace + "sorted-map" core-sorted-map + "sorted-set" core-sorted-set + "sorted?" core-sorted? + "reduced" core-reduced + "reduced?" core-reduced? + "take-nth" core-take-nth + "empty" core-empty + "rseq" core-rseq + "shuffle" core-shuffle + "sequential?" core-sequential? + "associative?" core-associative? + "ifn?" core-ifn? + "indexed?" core-indexed? + "ex-info" core-ex-info + "prn-str" core-prn-str + "println-str" core-println-str + "__with-out-str" core-with-out-str + "force" core-force + "realized?" core-realized? + "delay?" core-delay? + "make-delay" core-make-delay + "take" core-take + "drop" core-drop + "take-while" core-take-while + "drop-while" core-drop-while + "concat" core-concat + "reverse" core-reverse + "nth" core-nth + "sort" core-sort + "sort-by" core-sort-by + "partition" core-partition + "range" core-range + "identity" core-identity + "constantly" core-constantly + "complement" core-complement + "comp" core-comp + "partial" core-partial + "memoize" core-memoize + "vector" core-vector + "hash-map" core-hash-map + "array-map" core-array-map + "hash-set" core-hash-set + "set" core-set + "list" core-list + "set?" core-set? + "disj" core-disj + "coll->cells" coll->cells + "make-lazy-seq" make-lazy-seq + "lazy-cons" lazy-cons + "lazy-from" lazy-from + "str" core-str + "name" core-name + "subs" core-subs + "str-trim" string/trim + "str-upper" string/ascii-upper + "str-lower" string/ascii-lower + "str-find" string/find + "str-replace" core-str-replace-first + "str-replace-all" core-str-replace-all + "str-reverse-b" string/reverse + "str-join" core-str-join + "str-split" core-str-split + "re-pattern" re-pattern + "re-find" re-find + "re-matches" re-matches + "re-seq" re-seq + "regex?" regex? + "str-triml" string/triml + "str-trimr" string/trimr + "print" core-print + "println" core-println + "pr" core-pr + "prn" core-prn + "pr-str" core-pr-str + # Java-style arrays (buffers for bytes, arrays otherwise) + "aclone" core-aclone + "object-array" core-object-array + "int-array" core-int-array + "long-array" core-long-array + "short-array" core-short-array + "double-array" core-double-array + "float-array" core-float-array + "char-array" core-char-array + "boolean-array" core-boolean-array + "byte-array" core-byte-array + "aset-byte" core-aset-byte + "aset-int" core-aset-int + "aset-long" core-aset-long + "aset-short" core-aset-short + "aset-double" core-aset-double + "aset-float" core-aset-float + "aset-char" core-aset-char + "aset-boolean" core-aset-boolean + "make-array" core-make-array + "into-array" core-into-array + "to-array" core-to-array + "to-array-2d" core-to-array-2d + "bytes" core-bytes + "booleans" core-booleans + "ints" core-ints + "longs" core-longs + "shorts" core-shorts + "doubles" core-doubles + "floats" core-floats + "chars" core-chars + "byte" core-byte + "short" core-short + "unchecked-byte" core-unchecked-byte + "unchecked-short" core-unchecked-short + "unchecked-char" core-unchecked-char + "unchecked-float" core-unchecked-float + "unchecked-double" core-unchecked-double + "bigint" core-bigint + "biginteger" core-biginteger + "bigdec" core-bigdec + "chunk-buffer" core-chunk-buffer + "chunk-append" core-chunk-append + "chunk" core-chunk + "chunk-first" core-chunk-first + "chunk-rest" core-chunk-rest + "chunk-next" core-chunk-next + "chunk-cons" core-chunk-cons + "boolean" core-boolean + "cat" core-cat + "disj!" core-disj! + "random-sample" core-random-sample + "reader-conditional" core-reader-conditional + "sorted-map-by" core-sorted-map-by + "sorted-set-by" core-sorted-set-by + "array-seq" core-array-seq + "seque" core-seque + "supers" core-supers + "class" core-class + "clojure-version" core-clojure-version + "munge" core-munge + "test" core-test + "enumeration-seq" core-enumeration-seq + "iterator-seq" core-iterator-seq + "line-seq" core-line-seq + "re-matcher" core-re-matcher + "bean" core-bean + "print-method" core-print-method + "print-dup" core-print-dup + "proxy-call-with-super" core-proxy-call-with-super + "proxy-mappings" core-proxy-mappings + "update-proxy" core-update-proxy + "==" core-numeric= + "print-str" core-print-str + "memfn" core-memfn + "eduction" core-eduction + "->Eduction" core->Eduction + "proxy-super" core-proxy-super + "construct-proxy" core-construct-proxy + "init-proxy" core-init-proxy + "get-proxy-class" core-get-proxy-class + "char-escape-string" core-char-escape-string + "char-name-string" core-char-name-string + "subseq" core-subseq + "rsubseq" core-rsubseq + # Bit operations + "bit-and" core-bit-and + "bit-or" core-bit-or + "bit-xor" core-bit-xor + "bit-not" core-bit-not + "bit-shift-left" core-bit-shift-left + "bit-shift-right" core-bit-shift-right + "bit-clear" core-bit-clear + "bit-set" core-bit-set + "bit-flip" core-bit-flip + "bit-test" core-bit-test + "bit-and-not" core-bit-and-not + "unsigned-bit-shift-right" core-unsigned-bit-shift-right + # Integer coercion / unchecked math + "int" core-int + "long" core-long + "double" core-double + "float" core-float + "num" core-num + "char" core-char + "char?" core-char? + "unchecked-inc" core-unchecked-inc + "unchecked-dec" core-unchecked-dec + "unchecked-add" core-unchecked-add + "unchecked-subtract" core-unchecked-subtract + # Hash + "hash" core-hash + "atom" core-atom + "deref" core-deref + "reset!" core-reset! + "swap!" core-swap! + "not" core-not + "derive" core-derive + "isa?" core-isa? + "parents" core-parents + "ancestors" core-ancestors + "descendants" core-descendants + "make-hierarchy" core-make-hierarchy + "underive" core-underive + "get-method" core-get-method + "methods" core-methods + "remove-method" core-remove-method + "remove-all-methods" core-remove-all-methods + "prefer-method" core-prefer-method + "Object" core-Object + "make-protocol" core-make-protocol + "satisfies?" core-satisfies? + "extends?" core-extends? + "implements?" core-implements? + "type->str" core-type->str + "volatile!" core-volatile! + "Thread" core-Thread + "ThreadLocal" core-ThreadLocal + "IllegalStateException" core-IllegalStateException + "resolve" core-resolve + "update-in" core-update-in + "assoc-in" core-assoc-in + "fnil" core-fnil + "copy-core-var" core-copy-core-var + "copy-var" core-copy-var + "macrofy" core-macrofy + "new-var" core-new-var + "avoid-method-too-large" core-avoid-method-too-large + "qualified-symbol?" core-qualified-symbol? + "simple-symbol?" core-simple-symbol? + "qualified-keyword?" core-qualified-keyword? + "simple-keyword?" core-simple-keyword? + "inst?" core-inst? + "inst-ms" core-inst-ms + "uri?" core-uri? + "uuid?" core-uuid? + "bytes?" core-bytes? + "meta" core-meta + "var-get" core-var-get + "var-set" core-var-set + "var?" core-var? + "var-dynamic?" core-var-dynamic? + "alter-var-root" core-alter-var-root + "alter-meta!" core-alter-meta! + "reset-meta!" core-reset-meta! + "push-thread-bindings" core-push-thread-bindings + "pop-thread-bindings" core-pop-thread-bindings + # Dynamic vars — stubs for SCI bootstrap + "*unchecked-math*" false + "*clojure-version*" @{:major 1 :minor 11 :incremental 0 :qualifier nil} + "*1" :jolt/nil-sentinel + "*2" :jolt/nil-sentinel + "*3" :jolt/nil-sentinel + "*e" :jolt/nil-sentinel + "*assert" true}) + +(defn core-macro-names + "Set of core binding names that are macros. Empty now that every core macro + lives in the Clojure overlay (clojure.core.*-syntax / *-macros tiers)." + [] + @{}) + +(def init-core! + (fn [& args] + (case (length args) + 1 (let [ctx (args 0) + ns (ctx-find-ns ctx "clojure.core")] + (loop [[name fn] :pairs core-bindings] + (def v (ns-intern ns name (if (= fn :jolt/nil-sentinel) nil fn))) + (when (get (core-macro-names) name) + (put v :macro true))) + ns) + 2 (let [ctx (args 0) ns-name (args 1) + ns (ctx-find-ns ctx ns-name)] + (loop [[name fn] :pairs core-bindings] + (def v (ns-intern ns name (if (= fn :jolt/nil-sentinel) nil fn))) + (when (get (core-macro-names) name) + (put v :macro true))) + ns) + (error "Wrong number of args passed to: init-core!")))) diff --git a/src/jolt/deps.janet b/src/jolt/deps.janet new file mode 100644 index 0000000..49291f3 --- /dev/null +++ b/src/jolt/deps.janet @@ -0,0 +1,91 @@ +# deps.edn resolution for Jolt. +# +# Resolve git and :local/root dependencies from a deps.edn into a list of source +# directories, which the loader then searches (see evaluator/find-ns-file). We +# reuse jpm's git fetch + cache (jpm/pm) rather than shipping a package manager. +# Maven (:mvn/version) deps are ignored — git only, pure clj/cljc only. +# +# jpm is loaded lazily (require, not import) so it's needed only at resolve time +# (dev/build), never embedded in the shipped binary. + +(import ./reader :as reader) + +# Read deps.edn with Jolt's reader (not Janet's parse) so EDN `;` line comments +# are handled. It returns plain Janet data — structs with keyword keys, tuples — +# which we walk directly. (#{} sets and tagged literals aren't expected in the +# :deps/:paths we read.) +(defn read-edn [path] + (when (os/stat path) + (try (reader/parse-string (slurp path)) ([_] nil)))) + +(defn- jpm-fn [mod sym] + (get-in (require mod) [sym :value])) + +(defn- ensure-jpm-config [tree] + ((jpm-fn "jpm/config" 'load-default)) + (setdyn :modpath tree) + (setdyn :gitpath (dyn :gitpath "git"))) + +(defn- clone-git [spec] + # spec is a deps.edn dep value: {:git/url ... :git/sha/:git/tag ...} + (def resolve-bundle (jpm-fn "jpm/pm" 'resolve-bundle)) + (def download-bundle (jpm-fn "jpm/pm" 'download-bundle)) + (def b (resolve-bundle {:url (get spec :git/url) + :sha (get spec :git/sha) + :tag (get spec :git/tag) + :shallow false})) + (download-bundle (b :url) (b :type) (b :tag) (b :shallow))) + +(defn- src-roots + "Source dirs of a project/dep at `dir`: its deps.edn :paths joined to dir + (default [\"src\"])." + [dir edn] + (map |(string dir "/" $) (or (and edn (get edn :paths)) ["src"]))) + +(defn resolve-deps + "Resolve the git/:local deps of `deps-edn-path` into an ordered, de-duplicated + array of source dirs (the project's own :paths first, then each dependency's, + transitively). `tree` is where jpm's clone cache lives (default ./jpm_tree)." + [deps-edn-path &opt tree] + (default tree (string (os/cwd) "/jpm_tree")) + (os/mkdir tree) + (ensure-jpm-config tree) + (def roots @[]) + (def seen @{}) + (defn add-root [r] (unless (index-of r roots) (array/push roots r))) + (defn process [edn base-dir own-paths?] + (when (dictionary? edn) + (when own-paths? (each r (src-roots base-dir edn) (add-root r))) + (eachp [lib spec] (or (get edn :deps) {}) + (def k (string lib)) + (unless (get seen k) + (put seen k true) + (def dir + (cond + (and (dictionary? spec) (get spec :git/url)) (clone-git spec) + (and (dictionary? spec) (get spec :local/root)) + (let [lr (get spec :local/root)] + (if (string/has-prefix? "/" lr) lr (string base-dir "/" lr))) + nil)) # :mvn/* and anything else: skip + (when dir + (def dep-edn (read-edn (string dir "/deps.edn"))) + (each r (src-roots dir dep-edn) (add-root r)) + (process dep-edn dir false)))))) + (process (read-edn deps-edn-path) (os/cwd) true) + roots) + +(defn resolve-deps-cached + "Like resolve-deps, but caches the resolved roots in the tree keyed on a hash + of the deps.edn, so an unchanged deps.edn resolves without re-fetching." + [deps-edn-path &opt tree] + (default tree (string (os/cwd) "/jpm_tree")) + (when (os/stat deps-edn-path) + (os/mkdir tree) + (def cache-file (string tree "/.jolt-deps-roots.jdn")) + (def h (hash (slurp deps-edn-path))) + (def cached (when (os/stat cache-file) (try (parse (slurp cache-file)) ([_] nil)))) + (if (and cached (= h (get cached :hash))) + (get cached :roots) + (let [roots (resolve-deps deps-edn-path tree)] + (spit cache-file (string/format "%j" {:hash h :roots roots})) + roots)))) diff --git a/src/jolt/deps_cli.janet b/src/jolt/deps_cli.janet new file mode 100644 index 0000000..9c8308e --- /dev/null +++ b/src/jolt/deps_cli.janet @@ -0,0 +1,44 @@ +# jolt-deps — a separate tool that resolves a deps.edn into Jolt source roots. +# +# Mirrors how jpm is a tool beside the janet runtime: the jolt runtime knows +# nothing about deps.edn — it just searches the roots in JOLT_PATH (see +# api/init). This tool does the resolution (git + :local deps, via jpm's fetch +# cache) and either prints the roots or launches jolt with JOLT_PATH set. +# +# jolt-deps path print the resolved roots (':'-joined), e.g. for +# JOLT_PATH=$(jolt-deps path) jolt file.clj +# jolt-deps run FILE [args] resolve, then run `jolt FILE args` with JOLT_PATH set +# jolt-deps repl resolve, then start a jolt REPL with JOLT_PATH set +# jolt-deps -e EXPR [args] resolve, then `jolt -e EXPR ...` with JOLT_PATH set +# jolt-deps uberscript OUT -m NS +# resolve, then bundle NS + its deps into one .clj +# +# The jolt binary is found via $JOLT_BIN, else `jolt` on PATH. + +(import ./deps :as deps) + +(defn- roots [] + (if (os/stat "deps.edn") (deps/resolve-deps-cached "deps.edn") @[])) + +(defn- exec-jolt [extra-args] + # Set JOLT_PATH in our own env and let the child inherit it (os/execute's env + # arg isn't honored here; inheriting is reliable). + (def rs (string/join (roots) ":")) + (def existing (os/getenv "JOLT_PATH")) + (os/setenv "JOLT_PATH" (if (and existing (> (length existing) 0)) (string rs ":" existing) rs)) + (os/execute [(os/getenv "JOLT_BIN" "jolt") ;extra-args] :p)) + +(defn- usage [] + (print "usage: jolt-deps [path | run FILE [args] | repl | -e EXPR [args]]")) + +(defn main [&] + (def argv (tuple/slice (or (dyn :args) @[]) 1)) + (def cmd (get argv 0)) + (cond + (or (nil? cmd) (= cmd "help") (= cmd "-h") (= cmd "--help")) (usage) + (= cmd "path") (print (string/join (roots) ":")) + (= cmd "run") (os/exit (exec-jolt (tuple/slice argv 1))) + (= cmd "repl") (os/exit (exec-jolt [])) + (= cmd "-e") (os/exit (exec-jolt argv)) + (= cmd "uberscript") (os/exit (exec-jolt argv)) + (do (eprint "jolt-deps: unknown command " cmd) (usage) (os/exit 1)))) diff --git a/src/jolt/evaluator.janet b/src/jolt/evaluator.janet new file mode 100644 index 0000000..6bcc0a3 --- /dev/null +++ b/src/jolt/evaluator.janet @@ -0,0 +1,1616 @@ +# Jolt Evaluator +# Direct interpreter for Clojure forms on Janet. + +(use ./types) +(use ./phm) +(use ./pv) +(use ./plist) +(use ./config) +(use ./reader) +(use ./regex) + +(defn- sym-name? + [sym-s name-str] + (and (struct? sym-s) (= :symbol (sym-s :jolt/type)) (= name-str (sym-s :name)))) + +(defn- special-symbol? + [name] + (or (= name "quote") (= name "syntax-quote") (= name "unquote") + (= name "unquote-splicing") (= name "do") (= name "if") + (= name "def") (= name "defmacro") (= name "fn*") (= name "let*") (= name "loop*") + (= name "recur") (= name "throw") (= name "try") + (= name "set!") (= name "var") (= name "locking") + (= name "eval") + (= name "instance?") + (= name "new") (= name ".") + # var-get/var-set/var?/alter-var-root/alter-meta!/reset-meta! are plain + # clojure.core fns (core-bindings); find-var/intern are ctx-capturing fns + # (install-stateful-fns!) — no longer special forms (Stage 2 tier 6). + (= name "satisfies?") + (= name "prefer-method") (= name "remove-method") (= name "remove-all-methods") + (= name "get-method") (= name "methods"))) + +(var eval-form nil) + +# Macro expansion cache (interpreter): a macro CALL form expands ONCE and the +# result is reused — macroexpansion is a compile-time step with zero runtime cost, +# the proper Lisp model. Keyed by the call form's identity (a fn body re-evaluates +# the same form arrays each call). Also gives compile-once gensym semantics (a +# foo# auto-gensym is fixed across calls, unlike per-call re-expansion). Cleared +# when a macro is (re)defined so stale expansions don't linger. +(def macro-cache @{}) + +# Compile hook for macro expanders: set by the api to (fn [ctx args-form body] -> +# compiled-janet-fn | nil). When set and the body is compilable (no &env/&form, +# analyzer available), defmacro uses the compiled expander instead of the +# interpreted closure — macro expansion at native speed, zero runtime cost. +(var macro-compile-hook nil) + +(defn- form-uses-sym? [form nm] + (cond + (and (struct? form) (= :symbol (form :jolt/type))) (= nm (form :name)) + (or (array? form) (tuple? form)) + (do (var found false) (each x form (when (form-uses-sym? x nm) (set found true) (break))) found) + (and (struct? form) (nil? (form :jolt/type))) + (do (var found false) (each k (keys form) + (when (or (form-uses-sym? k nm) (form-uses-sym? (get form k) nm)) (set found true) (break))) found) + false)) + +# A transient is a tagged mutable table @{:jolt/type :jolt/transient :kind ...}. +(defn- jolt-transient? [x] + (and (table? x) (= :jolt/transient (get x :jolt/type)))) + +# Read-only lookup over a transient (vector index / map key / set membership), +# mirroring core-get. Map/set backing tables are keyed by the same canon used +# by phm, so canonicalize collection keys here too. +(defn- transient-lookup [t k default] + (case (t :kind) + :vector (let [a (t :arr)] + (if (and (number? k) (= k (math/floor k)) (>= k 0) (< k (length a))) + (in a k) default)) + :map (let [e (get (t :tbl) (canon k))] (if (nil? e) default (in e 1))) + :set (if (nil? (get (t :tbl) (canon k))) default k) + default)) + +(defn- coll-lookup + "Clojure `get` semantics over a jolt collection, used for collection-as-IFn." + [coll k default] + (cond + (jolt-transient? coll) (transient-lookup coll k default) + (phm? coll) (phm-get coll k default) + (set? coll) (if (phs-contains? coll k) k default) + (pvec? coll) + (if (and (number? k) (= k (math/floor k)) (>= k 0) (< k (pv-count coll))) + (pv-nth coll k) default) + (or (tuple? coll) (array? coll)) + (if (and (number? k) (= k (math/floor k)) (>= k 0) (< k (length coll))) + (in coll k) default) + (or (struct? coll) (table? coll)) + (let [v (get coll k :jolt/not-found)] + (if (= v :jolt/not-found) default v)) + (nil? coll) default + default)) + +(defn jolt-invoke + "Apply f to already-evaluated args. Handles real functions and Clojure's + IFn collections: vectors (index lookup), maps/sets/keywords/symbols (get), + and deftype/record values implementing IFn. `args` is an array." + [ctx f args] + (cond + (or (function? f) (cfunction? f)) (apply f args) + (jolt-transient? f) (transient-lookup f (get args 0) (get args 1)) + (keyword? f) (coll-lookup (get args 0) f (get args 1)) + (and (struct? f) (= :symbol (f :jolt/type))) + (coll-lookup (get args 0) f (get args 1)) + (and (table? f) (= :jolt/sorted-map (f :jolt/type))) + (let [v (get (f :map) (get args 0))] (if (nil? v) (get args 1) v)) + (and (table? f) (= :jolt/sorted-set (f :jolt/type))) + (if (some |(deep= $ (get args 0)) (f :items)) (get args 0) (get args 1)) + (phm? f) (phm-get f (get args 0) (get args 1)) + (set? f) (if (phs-contains? f (get args 0)) (get args 0) (get args 1)) + (pvec? f) + (let [k (get args 0)] + (if (and (number? k) (= k (math/floor k)) (>= k 0) (< k (pv-count f))) + (pv-nth f k) + (error (string "Index " k " out of bounds for vector of length " (pv-count f))))) + (or (tuple? f) (array? f)) + (let [k (get args 0)] + (if (and (number? k) (= k (math/floor k)) (>= k 0) (< k (length f))) + (in f k) + (error (string "Index " k " out of bounds for vector of length " (length f))))) + # Map literal only (struct with no :jolt/type). A tagged struct (char/etc.) + # is not callable — symbols are handled above; chars fall through to the error. + (and (struct? f) (nil? (get f :jolt/type))) + (let [v (get f (get args 0) :jolt/not-found)] + (if (= v :jolt/not-found) (get args 1) v)) + (and (table? f) (get f :jolt/deftype)) + (let [ifn-fn (find-protocol-method ctx (get f :jolt/deftype) "IFn" "-invoke")] + (if ifn-fn (apply ifn-fn f args) + (if (and (get f :jolt/protocol-methods) (get (f :jolt/protocol-methods) :-invoke)) + (apply (get (f :jolt/protocol-methods) :-invoke) f args) + # No IFn impl: fall back to map-like field access, e.g. (point :x) + (let [v (get f (get args 0) :jolt/not-found)] + (if (= v :jolt/not-found) (get args 1) v))))) + (and (table? f) (get f :jolt/protocol-methods)) + (let [invoke-fn (get (f :jolt/protocol-methods) :-invoke)] + (if invoke-fn (apply invoke-fn f args) + (error (string "Cannot call " (type f) " as a function")))) + (error (string "Cannot call " (type f) " as a function")))) + +(defn- sq-symbol + "Resolve a symbol inside syntax-quote. `foo#` becomes a stable auto-gensym + (per-expansion, via gsmap); special forms are left unqualified; a clojure.core + name is fully qualified to clojure.core/ (matching Clojure, for hygiene); other + symbols are qualified to the current namespace so they resolve when the macro is + used elsewhere." + [ctx form gsmap] + (if (nil? (form :ns)) + (let [nm (form :name)] + (cond + (string/has-suffix? "#" nm) + (or (get gsmap nm) + (let [g {:jolt/type :symbol :ns nil + :name (string (string/slice nm 0 -2) "__" (string (gensym)) "__auto")}] + (put gsmap nm g) g)) + (special-symbol? nm) form + (ns-find (ctx-find-ns ctx "clojure.core") nm) + {:jolt/type :symbol :ns "clojure.core" :name nm} + # Unresolved -> qualify to the namespace being COMPILED when set (the + # analyzer runs interpreted in jolt.analyzer, so ctx-current-ns is wrong + # mid-compile — the same seam resolve-var/h-current-ns use). Matters when + # a macro expander's template is lowered while a symbol it references is + # not yet defined (deftype's extend-type, defined later in the same tier): + # it must qualify to the macro's home ns, not jolt.analyzer. + {:jolt/type :symbol + :ns (or (get (ctx :env) :compile-ns) (ctx-current-ns ctx)) + :name nm})) + form)) + +(defn- d-realize + "Realize a lazy-seq to an array for positional destructuring / splicing; pass + others (pvec/plist coerced to array, everything else unchanged)." + [val] + (if (pvec? val) (pv->array val) + (if (plist? val) (pl->array val) + (if (lazy-seq? val) + (do + (var items @[]) (var cur val) (var go true) + (while go + (let [cell (realize-ls cur)] + (if (or (nil? cell) (= :jolt/pending cell) (= 0 (length cell))) + (set go false) + (do (array/push items (in cell 0)) + (let [rt (in cell 1)] + (if (nil? rt) (set go false) (set cur (make-lazy-seq rt)))))))) + items) + val)))) + +(defn- syntax-quote* + [ctx bindings form &opt gsmap] + (default gsmap @{}) + (cond + (and (array? form) (> (length form) 0) (sym-name? (first form) "unquote")) + (eval-form ctx bindings (in form 1)) + (and (array? form) (> (length form) 0) (sym-name? (first form) "unquote-splicing")) + (error "~@ used outside of a list or vector in syntax-quote") + (or (number? form) (string? form) (keyword? form) (nil? form) (= true form) (= false form)) + form + (and (struct? form) (= :symbol (form :jolt/type))) + (sq-symbol ctx form gsmap) + (tuple? form) + (do (var result @[]) (var i 0) (while (< i (length form)) + (let [item (in form i)] + (if (and (array? item) (> (length item) 0) (sym-name? (first item) "unquote-splicing")) + (let [sv (eval-form ctx bindings (in item 1))] + (each v (d-realize sv) (array/push result v))) + (array/push result (syntax-quote* ctx bindings item gsmap)))) + (++ i)) (tuple ;result)) + (array? form) + (do (var result @[]) (var i 0) (while (< i (length form)) + (let [item (in form i)] + (if (and (array? item) (> (length item) 0) (sym-name? (first item) "unquote-splicing")) + (let [sv (eval-form ctx bindings (in item 1))] + (each v (d-realize sv) (array/push result v))) + (array/push result (syntax-quote* ctx bindings item gsmap)))) + (++ i)) result) + # set literal: lower each element (processing ~/~@) and rebuild a set. + (and (struct? form) (= :jolt/set (form :jolt/type))) + (do (var result @[]) + (each item (form :value) + (if (and (array? item) (> (length item) 0) (sym-name? (first item) "unquote-splicing")) + (let [sv (eval-form ctx bindings (in item 1))] + (each v (d-realize sv) (array/push result v))) + (array/push result (syntax-quote* ctx bindings item gsmap)))) + (make-phs ;result)) + (and (struct? form) (get form :jolt/type)) form + (struct? form) + (do (var kvs @[]) (each k (keys form) + (array/push kvs (syntax-quote* ctx bindings k gsmap)) + (array/push kvs (syntax-quote* ctx bindings (get form k) gsmap))) (struct ;kvs)) + form)) + +# Syntax-quote LOWERING: instead of evaluating a `(...) form to a value (what +# syntax-quote* does), produce equivalent CONSTRUCTION CODE so a backtick body is +# plain compilable code (read -> macroexpand -> compile, zero runtime cost). +# Mirrors syntax-quote*/sq-symbol exactly; the canonical algorithm is +# tools.reader's syntax-quote*/expand-list. List forms build via __sqcat (-> array), +# vectors via __sqvec (-> tuple), maps via __sqmap; symbols become (quote resolved); +# ~ leaves the expr in place, ~@ passes the seq straight to __sqcat for splicing. +(defn- sqsym* [nm] {:jolt/type :symbol :ns nil :name nm}) + +(var syntax-quote-lower nil) + +(defn- sq-lower-part [ctx item gsmap] + (if (and (array? item) (> (length item) 0) (sym-name? (first item) "unquote-splicing")) + (in item 1) + @[(sqsym* "__sq1") (syntax-quote-lower ctx item gsmap)])) + +(set syntax-quote-lower + (fn syntax-quote-lower [ctx form &opt gsmap] + (default gsmap @{}) + (cond + (and (array? form) (> (length form) 0) (sym-name? (first form) "unquote")) + (in form 1) + (and (array? form) (> (length form) 0) (sym-name? (first form) "unquote-splicing")) + (error "~@ used outside of a list or vector in syntax-quote") + (or (number? form) (string? form) (keyword? form) (nil? form) (= true form) (= false form)) + form + (and (struct? form) (= :symbol (form :jolt/type))) + @[(sqsym* "quote") (sq-symbol ctx form gsmap)] + (array? form) + (array/concat @[(sqsym* "__sqcat")] (map (fn [it] (sq-lower-part ctx it gsmap)) form)) + (tuple? form) + (array/concat @[(sqsym* "__sqvec")] (map (fn [it] (sq-lower-part ctx it gsmap)) form)) + # set literal: lower each element (so ~/~@ are processed) and rebuild a set. + (and (struct? form) (= :jolt/set (form :jolt/type))) + (array/concat @[(sqsym* "__sqset")] (map (fn [it] (sq-lower-part ctx it gsmap)) (form :value))) + # other tagged structs (chars): returned as-is (no recursion) + (and (struct? form) (get form :jolt/type)) + @[(sqsym* "quote") form] + (struct? form) + (do (var parts @[(sqsym* "__sqmap")]) + (each k (keys form) + (array/push parts (syntax-quote-lower ctx k gsmap)) + (array/push parts (syntax-quote-lower ctx (get form k) gsmap))) + parts) + @[(sqsym* "quote") form]))) + +(defn resolve-var + [ctx bindings sym-s] + (let [name (sym-s :name) ns (sym-s :ns)] + (if (not (nil? ns)) + # Resolve ns aliases (e.g. `p/thrown?` where `p` is a require :as alias) so + # aliased refs/macros resolve. During compilation the analyzer (interpreted, + # in jolt.analyzer) rebinds ctx-current-ns to its own ns, so look up the alias + # against the COMPILE ns (:compile-ns, the user's ns) when set — otherwise an + # aliased ref like g/foo wouldn't resolve mid-compile. Same ns h-current-ns uses. + (let [cur-name (or (get (ctx :env) :compile-ns) (ctx-current-ns ctx)) + current-ns (ctx-find-ns ctx cur-name) + aliased-ns (ns-import-lookup current-ns ns) + target-ns (ctx-find-ns ctx (or aliased-ns ns))] + (ns-find target-ns name)) + (if (get bindings name) nil + (let [current-ns (ctx-current-ns ctx) + ns (ctx-find-ns ctx current-ns) + v (ns-find ns name)] + (if v v + (let [core-ns (ctx-find-ns ctx "clojure.core")] + (ns-find core-ns name)))))))) + +(defn- sym-name-str + [sym-s] + (if (sym-s :ns) (string (sym-s :ns) "/" (sym-s :name)) (sym-s :name))) + +(defn- ns->relpath + "Namespace name to its file-relative path (dots->dirs, dashes->_), no extension." + [ns-name] + (string/replace-all "." "/" (string/replace-all "-" "_" ns-name))) + +(defn- find-ns-file + "Search the context's source roots (stdlib first, then deps.edn dirs) for the + namespace's source, trying .clj then .cljc. Returns the path or nil." + [ctx ns-name] + (let [rel (ns->relpath ns-name) + roots (or (get (ctx :env) :source-paths) @["src/jolt"])] + (var found nil) + (each root roots + (each ext [".clj" ".cljc"] + (when (nil? found) + (let [p (string root "/" rel ext)] + (when (os/stat p) (set found p)))))) + found)) + +(defn- load-ns-source + "Parse and evaluate every form of a namespace's source in the given context." + [ctx src] + (var s src) + (while (> (length (string/trim s)) 0) + (def [f r] (parse-next s)) + (set s r) + (when (not (nil? f)) (eval-form ctx @{} f)))) + +(defn- maybe-require-ns + "If namespace ns-name isn't populated yet, load its source — from a file on the + context's source roots, else from the stdlib baked into the image. Restores the + current namespace afterwards (a library's own `ns` form, or our manual switch + for ns-form-less stdlib files, changes it). No-op for already-loaded namespaces." + [ctx ns-name] + (let [ns (ctx-find-ns ctx ns-name)] + (when (and (= 0 (length (ns :mappings))) (not= ns-name "clojure.core")) + (let [path (find-ns-file ctx ns-name) + embedded (get (get (ctx :env) :embedded-sources @{}) ns-name) + stdlib? (not (nil? embedded))] + (when (or path embedded) + (let [saved (ctx-current-ns ctx)] + # Stdlib files have no `ns` form, so switch into the target ns first + # (their defs intern there); a library's own `ns` form overrides this. + (ctx-set-current-ns ctx ns-name) + (if path (load-ns-source ctx (slurp path)) (load-ns-source ctx embedded)) + # Record load order for tooling (uberscript): a dependency finishes + # loading before its requirer, so this is topological. Skip the + # baked-in stdlib — it's part of the runtime, not something to bundle. + (when (and path (not stdlib?)) + (when-let [lf (get (ctx :env) :loaded-files)] (array/push lf path))) + (ctx-set-current-ns ctx saved))))))) + +(defn- eval-require + [ctx spec] + (let [ns-sym (in spec 0) + ns-name (sym-name-str ns-sym)] + (var alias nil) + (var refer-syms nil) + (var i 1) + (let [slen (length spec)] + # Scan ALL options — a spec may carry both :as and :refer, e.g. + # [clojure.string :as str :refer [blank?]]; don't stop at the first. + (while (< i slen) + (let [item (in spec i)] + (cond + (or (= item :as) (and (struct? item) (= :symbol (item :jolt/type)) (= "as" (item :name)))) + (do (set alias ((in spec (+ i 1)) :name)) (+= i 2)) + (or (= item :refer) (and (struct? item) (= :symbol (item :jolt/type)) (= "refer" (item :name)))) + (do (set refer-syms (in spec (+ i 1))) (+= i 2)) + (++ i))))) + (maybe-require-ns ctx ns-name) + (when alias + (let [current-ns (ctx-find-ns ctx (ctx-current-ns ctx))] + (ns-import current-ns alias ns-name))) + (when refer-syms + (let [source-ns (ctx-find-ns ctx ns-name) + target-ns (ctx-find-ns ctx (ctx-current-ns ctx))] + (each refer-sym refer-syms + (let [name (if (struct? refer-sym) (refer-sym :name) refer-sym) + v (ns-find source-ns name)] + (when v + # Preserve macro-ness: a referred macro must stay a macro, so copy + # the :macro flag onto the interned var (not just its value). + (let [nv (ns-intern target-ns name (var-get v))] + (when (get v :macro) (put nv :macro true)))))))) + nil)) + +(defn- bind-put + "Put a value into bindings. Uses :jolt/nil sentinel for nil values + because Janet's (put table key nil) silently drops the key." + [bindings key value] + (put bindings key (if (nil? value) :jolt/nil value))) + +(defn- binding-get + "Get a value from bindings, walking the prototype chain." + [bindings name] + (var result :jolt/not-found) + (var t bindings) + (while (not (nil? t)) + (when (in t name) + (set result (in t name)) + (break)) + (set t (table/getproto t))) + result) + +(def- math-statics + @{"sqrt" math/sqrt "pow" math/pow "floor" math/floor "ceil" math/ceil + "abs" (fn [x] (if (< x 0) (- x) x)) + "round" (fn [x] (math/round x)) + "sin" math/sin "cos" math/cos "tan" math/tan + "asin" math/asin "acos" math/acos "atan" math/atan + "log" math/log "log10" math/log10 "exp" math/exp + "max" (fn [a b] (if (> a b) a b)) "min" (fn [a b] (if (< a b) a b)) + "signum" (fn [x] (cond (< x 0) -1.0 (> x 0) 1.0 0.0)) + "PI" math/pi "E" math/e + "random" (fn [&] (math/random))}) + +(defn- resolve-sym + [ctx bindings sym-s] + (let [name (sym-s :name) ns (sym-s :ns)] + (if (= ns "Math") + (let [v (get math-statics name)] + (if (nil? v) (error (string "Unsupported Math member: Math/" name)) v)) + (if (not (nil? ns)) + (let [current-ns (ctx-find-ns ctx (ctx-current-ns ctx)) + aliased-ns (ns-import-lookup current-ns ns) + target-ns (ctx-find-ns ctx (or aliased-ns ns)) + v (and target-ns (ns-find target-ns name))] + (if v (var-get v) + # Explicit Janet interop. The `janet` namespace segment marks every + # crossing into host code, where Clojure semantics no longer hold: + # janet/ -> Janet root binding (janet/slurp, janet/type) + # janet./ -> Janet module binding (janet.net/server, + # janet.os/clock) + # This makes the whole Janet stdlib reachable from Clojure while keeping + # the interop boundary visible at the call site. + (if (or (= ns "janet") (string/has-prefix? "janet." ns)) + (let [jname (if (= ns "janet") name (string (string/slice ns 6) "/" name)) + entry (in (fiber/getenv (fiber/current)) (symbol jname))] + (if (not (nil? entry)) + (if (table? entry) (entry :value) entry) + (error (string "Unable to resolve Janet symbol: " jname)))) + (error (string "Unable to resolve symbol: " ns "/" name))))) + # Use :jolt/not-found sentinel to distinguish nil binding from absent binding + (let [local (get bindings name :jolt/not-found-1) + local (if (= local :jolt/not-found-1) (binding-get bindings name) local)] + (if (not= local :jolt/not-found) + (if (= local :jolt/nil) nil local) + (let [current-ns (ctx-current-ns ctx) ns (ctx-find-ns ctx current-ns) v (ns-find ns name)] + (if v (var-get v) + # Check clojure.core as auto-referred fallback + (let [core-ns (ctx-find-ns ctx "clojure.core") + core-v (ns-find core-ns name)] + (if core-v + (var-get core-v) + # Try class-name resolution: Foo.Bar.Baz -> ns "Foo.Bar", name "Baz" + (let [dot-idx (string/find "." name)] + (if dot-idx + (let [last-dot (do + (var idx dot-idx) + (var next-dot (string/find "." name (+ idx 1))) + (while (not (nil? next-dot)) + (set idx next-dot) + (set next-dot (string/find "." name (+ idx 1)))) + idx) + class-ns (string/slice name 0 last-dot) + class-name (string/slice name (+ last-dot 1))] + (let [target-ns (ctx-find-ns ctx class-ns) tv (ns-find target-ns class-name)] + (if tv (var-get tv) tv))) + # Fall back to Janet's global environment + (let [root-env (fiber/getenv (fiber/current)) + entry (in root-env (symbol name))] + (if (not (nil? entry)) + (if (table? entry) (entry :value) entry) + (error (string "Unable to resolve symbol: " name)))))))))))))))) + +(defn- parse-arg-names + "Parse a parameter vector, handling & rest args. + Returns {:fixed [names...] :rest name-or-nil :all [names...]}" + [args-form] + (var fixed @[]) + (var rest-name nil) + (var i 0) + (while (< i (length args-form)) + (let [a (in args-form i)] + (if (and (struct? a) (= :symbol (a :jolt/type)) (= "&" (a :name))) + (do + (+= i 1) + (if (< i (length args-form)) + (do + (set rest-name ((in args-form i) :name)) + (+= i 1)) + (error "& without argument in parameter list"))) + (do + (if (and (struct? a) (= :symbol (a :jolt/type))) + (array/push fixed (a :name)) + # destructuring form: recurse into it + (when (indexed? a) + (var di 0) + (while (< di (length a)) + (def inner (in a di)) + (if (and (struct? inner) (= :symbol (inner :jolt/type)) (= "&" (inner :name))) + (do + (+= di 1) + (if (< di (length a)) + (do + (set rest-name ((in a di) :name)) + (+= di 1)) + (error "& without argument in parameter list"))) + (do + (if (and (struct? inner) (= :symbol (inner :jolt/type))) + (array/push fixed (inner :name)) + # nested destructuring - extract names + (when (indexed? inner) + (each sym inner + (when (and (struct? sym) (= :symbol (sym :jolt/type))) + (array/push fixed (sym :name)))))) + (+= di 1)))))) + (+= i 1))))) + (var all @[]) + (each n fixed (array/push all n)) + (if rest-name (array/push all rest-name)) + {:fixed (tuple/slice (tuple ;fixed)) :rest rest-name :all (tuple/slice (tuple ;all))}) + +# ============================================================ +# Destructuring (Clojure-compatible, recursive) +# ============================================================ + +(defn- parse-params + "Parse a parameter vector into raw patterns: {:fixed [pat...] :rest pat-or-nil}. + Unlike parse-arg-names, patterns are kept intact (not flattened) so they can + be destructured against the corresponding argument." + [args-form] + (var fixed @[]) + (var rest-pat nil) + (var i 0) + (while (< i (length args-form)) + (let [a (in args-form i)] + (if (and (struct? a) (= :symbol (a :jolt/type)) (= "&" (a :name))) + (do (+= i 1) + (when (< i (length args-form)) (set rest-pat (in args-form i))) + (+= i 1)) + (do (array/push fixed a) (+= i 1))))) + {:fixed (tuple/slice (tuple ;fixed)) :rest rest-pat}) + +(defn- plain-sym? [p] (and (struct? p) (= :symbol (p :jolt/type)))) + +(defn- require-symbol-params + "fn* is a primitive: its params must be plain symbols. The fn/defn MACROS desugar + destructuring into plain params + a body let before emitting fn*, so fn* never + legitimately sees a pattern — matching Clojure, where (fn* [[a b]] ...) is the + compile error 'fn params must be Symbols'. Enforcing it here keeps the interpreter + consistent with the self-hosted analyzer (which also requires plain fn* params) + and with Clojure, instead of leniently destructuring a form Clojure rejects." + [param-info] + (each p (param-info :fixed) + (unless (plain-sym? p) (error "fn params must be Symbols"))) + (let [r (param-info :rest)] + (when (and r (not (plain-sym? r))) (error "fn params must be Symbols")))) + +(defn- d-get + "Look up key k in a map-like value (phm/struct/table/nil)." + [m k] + (cond + (phm? m) (phm-get m k) + (or (struct? m) (table? m)) (get m k) + true nil)) + +(defn- find-or-default + "Find the :or default expression for binding name nm, or :jolt/none." + [or-map nm] + (var result :jolt/none) + (when or-map + (each k (keys or-map) + (when (and (struct? k) (= :symbol (k :jolt/type)) (= nm (k :name))) + (set result (get or-map k))))) + result) + +(var destructure-bind nil) +(set destructure-bind + (fn dbind [ctx bindings pat val] + (cond + # plain symbol + (and (struct? pat) (= :symbol (pat :jolt/type))) + (bind-put bindings (pat :name) val) + # sequential pattern (vector of sub-patterns) + (indexed? pat) + (let [rv (d-realize val) + seqable? (indexed? rv)] + (var di 0) (var vi 0) + (def n (length pat)) + (while (< di n) + (let [elem (in pat di)] + (cond + # & rest + (and (struct? elem) (= :symbol (elem :jolt/type)) (= "&" (elem :name))) + (do + # rest binds a seq (jolt list = array), per Clojure semantics. + # For lazy-seqs, preserve laziness: walk vi steps via ls-rest + # instead of slicing the eagerly-realized array. + (destructure-bind ctx bindings (in pat (+ di 1)) + (if (lazy-seq? val) + (do + (var c val) (var i 0) + (while (< i vi) + (let [nxt (ls-rest c)] + (if (nil? nxt) (break) + (do (set c nxt) (++ i))))) + c) + (if (and seqable? (< vi (length rv))) + (array/slice (if (tuple? rv) (array/slice rv) rv) vi) + @[]))) + (set di (+ di 2))) + # :as whole + (= elem :as) + (do + (destructure-bind ctx bindings (in pat (+ di 1)) val) + (set di (+ di 2))) + # positional element + true + (do + (destructure-bind ctx bindings elem + (if (and seqable? (< vi (length rv))) (in rv vi) nil)) + (+= di 1) (+= vi 1)))))) + # map pattern (struct/table that isn't a symbol) + (or (struct? pat) (table? pat)) + (let [rv (d-realize val) + # Destructuring a sequential value as a map treats it as kwargs: + # alternating k/v pairs, or a single trailing map (Clojure's + # `[& {:keys ...}]`). A real map value is used as-is. + mval (if (and (indexed? rv) (not (or (struct? rv) (table? rv)))) + (if (and (= 1 (length rv)) + (let [e (in rv 0)] (or (struct? e) (table? e) (phm? e)))) + (in rv 0) + (let [m @{}] + (var i 0) + (while (< (+ i 1) (length rv)) + (put m (in rv i) (in rv (+ i 1))) + (+= i 2)) + m)) + val)] + (def or-map (get pat :or)) + (def as-sym (get pat :as)) + (when as-sym (destructure-bind ctx bindings as-sym mval)) + # :keys (keyword), :strs (string), :syms (symbol). A namespaced symbol + # in :keys/:syms (x/y) looks up the namespaced key but binds local y. + (each spec [[:keys :kw] [:strs :str] [:syms :sym]] + (let [kw (in spec 0) kind (in spec 1) names (get pat kw)] + (when (and names (indexed? names)) + (each s names + (let [sym? (and (struct? s) (= :symbol (s :jolt/type))) + local (if sym? (s :name) (string s)) + nsp (and sym? (s :ns)) + key (case kind + :kw (keyword (if nsp (string nsp "/" local) local)) + :str local + :sym {:jolt/type :symbol :ns nsp :name local}) + v (d-get mval key) + v (if (nil? v) + (let [d (find-or-default or-map local)] + (if (= d :jolt/none) nil (eval-form ctx bindings d))) + v)] + (bind-put bindings local v)))))) + # direct {local-pattern key-expr} entries (local may itself be a + # nested vector/map pattern). Special keys are keywords; skip them. + (each k (keys pat) + (when (not (keyword? k)) + (let [key-val (eval-form ctx bindings (get pat k)) + v (d-get mval key-val)] + (if (and (struct? k) (= :symbol (k :jolt/type))) + # symbol target: apply :or default if missing + (let [nm (k :name) + v (if (nil? v) + (let [d (find-or-default or-map nm)] + (if (= d :jolt/none) nil (eval-form ctx bindings d))) + v)] + (bind-put bindings nm v)) + # nested pattern target + (destructure-bind ctx bindings k v)))))) + true (error (string "Unsupported destructuring pattern: " (string/format "%q" pat)))))) + +# ---- host-type protocol extension (extend-protocol String/Number/... ) ---- +(def- host-type-names + {"Long" true "Integer" true "Short" true "Byte" true "BigInteger" true "BigInt" true + "Double" true "Float" true "Number" true "BigDecimal" true "Ratio" true + "String" true "CharSequence" true "Boolean" true "Character" true + "Keyword" true "Symbol" true "Object" true "IFn" true "Fn" true + "PersistentVector" true "PersistentList" true "PersistentHashMap" true + "PersistentHashSet" true "IPersistentMap" true "IPersistentVector" true + "IPersistentSet" true "IPersistentCollection" true "ISeq" true "Atom" true "nil" true}) + +(defn- canonical-host-tag + "If type-name names a host type (optionally java.*/clojure.lang.* qualified), + return its bare canonical name; else nil (it's a deftype/record name)." + [type-name] + (let [base (cond + (string/has-prefix? "java.lang." type-name) (string/slice type-name 10) + (string/has-prefix? "java.util." type-name) (string/slice type-name 10) + (string/has-prefix? "clojure.lang." type-name) (string/slice type-name 13) + type-name)] + (if (get host-type-names base) base nil))) + +(defn- value-host-tags + "Candidate host type-tags for a runtime value, most-specific first." + [obj] + (cond + (number? obj) ["Long" "Integer" "Number" "Double" "Object"] + (string? obj) ["String" "CharSequence" "Object"] + (or (= true obj) (= false obj)) ["Boolean" "Object"] + (keyword? obj) ["Keyword" "Object"] + (and (struct? obj) (= :jolt/char (get obj :jolt/type))) ["Character" "Object"] + (and (struct? obj) (= :symbol (get obj :jolt/type))) ["Symbol" "Object"] + (plist? obj) ["PersistentList" "IPersistentList" "IPersistentCollection" "ISeq" "Object"] + (or (tuple? obj) (array? obj) (pvec? obj)) ["PersistentVector" "IPersistentVector" "IPersistentCollection" "ISeq" "Object"] + (or (function? obj) (cfunction? obj)) ["IFn" "Fn" "Object"] + (nil? obj) ["nil" "Object"] + ["Object"])) + +# --------------------------------------------------------------------------- +# Stateful primitives as ordinary fns (Stage 2 jolt-eaa). These mutate/read the +# per-ctx protocol registry, so they need ctx. They're interned into clojure.core +# as closures over ctx (install-stateful-fns!), which makes them resolve + COMPILE +# as plain :var invokes — the back end embeds the per-ctx var cell, and the closure +# captures ctx so a compiled protocol dispatcher works even when called later. +# Both the interpreter and compiled code call these same closures; there is no +# longer a special-form handler for them. proto/method/type names arrive as +# STRINGS (the defprotocol/extend-type macros pass (name sym), not the symbol). +(defn protocol-dispatch-impl [ctx proto-name method-name obj rest-args] + (def type-tag (if (and (table? obj) (get obj :jolt/deftype)) + (get obj :jolt/deftype) + (if (get obj :jolt/protocol-methods) (get obj :jolt/deftype)))) + (if (and (table? obj) (get obj :jolt/protocol-methods)) + (let [reified-fns (get obj :jolt/protocol-methods) + f (get reified-fns (keyword method-name))] + (if f (apply f obj rest-args) + (error (string "No reified method " method-name " for " type-tag)))) + (if type-tag + (let [f (find-protocol-method ctx type-tag proto-name method-name)] + (if f (apply f obj rest-args) + (error (string "No method " method-name " in " proto-name " for " type-tag)))) + # host value: try candidate host type-tags (Long/String/Object/...), with a + # generation-guarded inline cache (same walk for every value of a host class). + (let [env (ctx :env) + reg-gen (or (get env :type-registry-gen) 0) + pc (let [c (get env :proto-dispatch-cache)] + (if (and c (= (c :gen) reg-gen)) c + (let [n @{:gen reg-gen :map @{}}] + (put env :proto-dispatch-cache n) n))) + cands (value-host-tags obj) + ckey [(first cands) proto-name method-name] + cached (get (pc :map) ckey) + found (if (nil? cached) + (let [f (do (var r nil) + (each tag cands + (when (nil? r) + (set r (find-protocol-method ctx tag proto-name method-name)))) + r)] + (put (pc :map) ckey (if f f :jolt/none)) + f) + (if (= cached :jolt/none) nil cached))] + (if found (apply found obj rest-args) + (error (string "No dispatch for " method-name " on " (type obj)))))))) + +(defn register-method-impl [ctx type-name proto-name method-name f] + # host types register under a bare canonical tag; deftype/record names stay + # namespace-qualified to the ns the (extend-)type form runs in. + (def host (canonical-host-tag type-name)) + (def type-tag (if host host (string (ctx-current-ns ctx) "." type-name))) + (register-protocol-method ctx type-tag proto-name method-name f)) + +(defn make-reified-impl [ctx proto-name methods-map] + # methods-map is the EVALUATED {keyword fn} map (a phm when compiled, a struct/ + # table when interpreted) — the fn* literals are already fns, just store them. + (def obj @{:jolt/deftype (string "reified-" proto-name) :jolt/protocol-methods @{}}) + (def pairs (if (phm? methods-map) + (phm-entries methods-map) + (map (fn [k] [k (get methods-map k)]) (keys methods-map)))) + (each p pairs (put (obj :jolt/protocol-methods) (in p 0) (in p 1))) + obj) + +(defn require-impl + "(require '[ns :as a :refer [...]] ...) — load + alias/refer each spec. A fn, so + the args (quoted specs) arrive evaluated. Varargs (Clojure-compatible); each spec + is a vector. eval-require does the namespace load + alias/refer into current-ns." + [ctx & specs] + (each spec specs + (let [s (if (pvec? spec) (pv->array spec) spec)] + (if (and (indexed? s) (> (length s) 0)) + (eval-require ctx s) + (error "require expects a vector spec")))) + nil) + +(defn in-ns-impl + "(in-ns 'foo) — switch the current namespace (creating it if needed). A fn; the + quoted symbol arrives evaluated." + [ctx sym] + (def ns-name (if (and (struct? sym) (= :symbol (sym :jolt/type))) (sym :name) (string sym))) + (ctx-find-ns ctx ns-name) + (ctx-set-current-ns ctx ns-name) + nil) + +(defn use-impl + "(use '[ns ...] ...) — refer ALL public vars of each used ns into the CURRENT ns. + A fn; quoted specs arrive evaluated. Each spec is a ns symbol or a [ns & opts] + vector (a pvec/tuple, not a Janet array — coerce, then take the head as the ns)." + [ctx & specs] + (def target-ns (ctx-find-ns ctx (ctx-current-ns ctx))) + (each s specs + (let [spec (if (pvec? s) (pv->array s) s) + ns-sym (if (indexed? spec) (in spec 0) spec) + src-name (sym-name-str ns-sym)] + (maybe-require-ns ctx src-name) + (let [source-ns (ctx-find-ns ctx src-name)] + (loop [[sym v] :pairs (source-ns :mappings)] + (let [nv (ns-intern target-ns sym (var-get v))] + (when (get v :macro) (put nv :macro true))))))) + nil) + +(defn import-impl + "(import 'pkg.Class ...) — register the short class name as an alias of the fully + qualified name in the current ns. A fn; quoted class symbols arrive evaluated." + [ctx & class-specs] + (def ns (ctx-find-ns ctx (ctx-current-ns ctx))) + (each class-spec class-specs + (let [class-name (if (and (struct? class-spec) (= :symbol (class-spec :jolt/type))) + (class-spec :name) (string class-spec)) + last-dot (do (var idx -1) (var pos 0) + (while (< pos (length class-name)) + (when (= (class-name pos) 46) (set idx pos)) (++ pos)) + idx) + short-name (if (>= last-dot 0) (string/slice class-name (+ last-dot 1)) class-name)] + (ns-import ns short-name class-name))) + nil) + +(defn refer-clojure-impl + "(refer-clojure :exclude [a b]) — currently only :exclude is honored: unmap the + excluded names from the current ns. A fn; quoted args arrive evaluated." + [ctx & args] + (when (and (>= (length args) 2) (= (in args 0) :exclude)) + (let [ns (ctx-find-ns ctx (ctx-current-ns ctx)) + excl (in args 1)] + (each sym excl + (ns-unmap ns (if (and (struct? sym) (= :symbol (sym :jolt/type))) (sym :name) (string sym)))))) + nil) + +(defn defmulti-setup + "(defmulti name dispatch & opts) — intern a multimethod var. A fn; name arrives + quoted, dispatch + opts (:default key, :hierarchy h) arrive evaluated. The + defmulti macro is the thin wrapper. Builds the dispatch closure over the method + table (shared with the var's :jolt/methods so defmethod adds to it)." + [ctx name-sym dispatch-raw & opts] + (def dispatch-fn (if (keyword? dispatch-raw) (fn [x] (get x dispatch-raw)) dispatch-raw)) + (def default-key + (do (var dv :default) (var i 0) + (while (< i (length opts)) + (if (= :default (in opts i)) (do (set dv (in opts (+ i 1))) (set i (length opts))) (+= i 2))) + dv)) + (def hierarchy + (do (var h nil) (var i 0) + (while (< i (length opts)) + (if (= :hierarchy (in opts i)) (do (set h (in opts (+ i 1))) (set i (length opts))) (+= i 2))) + h)) + (def ns (ctx-find-ns ctx (ctx-current-ns ctx))) + (def methods @{}) + (def dispatch-cache @{}) + (def mm-fn + (fn [& args] + (let [dv (apply dispatch-fn args) + method (get methods dv)] + (if method + (apply method args) + (let [cached (get dispatch-cache dv)] + (if cached + (apply cached args) + (let [h (or hierarchy the-global-hierarchy) + found (do (var f nil) (var i 0) + (let [ks (keys methods)] + (while (and (nil? f) (< i (length ks))) + (if (isa? h dv (in ks i)) (set f (get methods (in ks i)))) + (++ i))) + f)] + (if found + (do (put dispatch-cache dv found) (apply found args)) + (let [dm (get methods default-key)] + (if dm (apply dm args) + (error (string "No method in multimethod " (name-sym :name) + " for dispatch value: " dv)))))))))))) + (def v (ns-intern ns (name-sym :name) mm-fn)) + (put v :jolt/methods methods) + (put v :jolt/dispatch-cache dispatch-cache) + (put v :jolt/default default-key) + (when hierarchy (put v :jolt/hierarchy hierarchy)) + (var-get v)) + +(defn defmethod-setup + "(defmethod mm dispatch-val impl) — add a method to a multimethod. A fn; mm + arrives quoted, dispatch-val evaluated, impl is the COMPILED method fn (the + defmethod macro builds (fn …)). Auto-creates the multimethod if it's missing." + [ctx mm-sym dispatch-val impl] + (def mm-var + (or (resolve-var ctx @{} mm-sym) + (let [ns (ctx-find-ns ctx (ctx-current-ns ctx))] + (def v (ns-intern ns (mm-sym :name) (fn [& args] nil))) + (put v :jolt/methods @{}) + v))) + (def methods (or (get mm-var :jolt/methods) (let [m @{}] (put mm-var :jolt/methods m) m))) + (put methods dispatch-val impl) + (let [dc (get mm-var :jolt/dispatch-cache)] + (when dc (each k (keys dc) (put dc k nil)))) + mm-var) + +(defn make-deftype-ctor-impl + "Build a deftype constructor closure. The ns-qualified type tag is baked at + definition time (this runs during the deftype's (def …), in the type's ns), so + instances carry a stable tag matching what extend-type registers methods under. + field-kws is the [:f1 :f2 …] keyword vector; the ctor maps positional args to + those keys. A ctx-capturing closure (make-deftype-ctor) is the public handle." + [ctx type-name-sym field-kws] + (def type-tag (string (ctx-current-ns ctx) "." (type-name-sym :name))) + (def kws (d-realize field-kws)) + (fn [& args] + (var inst @{:jolt/deftype type-tag}) + (var i 0) + (each kw kws (put inst kw (in args i)) (++ i)) + inst)) + +(defn install-stateful-fns! + "Intern ctx-capturing closures for the stateful primitives into clojure.core, so + both the interpreter and the compiler reach them as ordinary fns. Called by + api/init after init-core! and before the overlay loads (the protocol macros + expand to calls of these)." + [ctx] + (def core (ctx-find-ns ctx "clojure.core")) + (ns-intern core "protocol-dispatch" + (fn [proto-name method-name obj rest-args] + (protocol-dispatch-impl ctx proto-name method-name obj rest-args))) + (ns-intern core "register-method" + (fn [type-name proto-name method-name f] + (register-method-impl ctx type-name proto-name method-name f))) + (ns-intern core "make-reified" + (fn [proto-name methods-map] (make-reified-impl ctx proto-name methods-map))) + (ns-intern core "require" (fn [& specs] (require-impl ctx ;specs))) + (ns-intern core "in-ns" (fn [sym] (in-ns-impl ctx sym))) + (ns-intern core "use" (fn [& specs] (use-impl ctx ;specs))) + (ns-intern core "import" (fn [& specs] (import-impl ctx ;specs))) + (ns-intern core "refer-clojure" (fn [& args] (refer-clojure-impl ctx ;args))) + (ns-intern core "defmulti-setup" (fn [name-sym dispatch & opts] (defmulti-setup ctx name-sym dispatch ;opts))) + (ns-intern core "defmethod-setup" (fn [mm-sym dval impl] (defmethod-setup ctx mm-sym dval impl))) + (ns-intern core "make-deftype-ctor" (fn [name-sym field-kws] (make-deftype-ctor-impl ctx name-sym field-kws))) + # Var/namespace lookups that need the ctx (the rest of the var fns — var-get/ + # var-set/var?/alter-var-root/alter-meta!/reset-meta! — are plain core-bindings). + (ns-intern core "find-var" (fn [sym] (find-var ctx sym))) + (ns-intern core "intern" + (fn [ns-name sym-name &opt val] + (def ns (ctx-find-ns ctx (if (struct? ns-name) (ns-name :name) ns-name))) + (ns-intern ns (if (struct? sym-name) (sym-name :name) sym-name) val))) + core) + +# Dispatch a special form by its string name. +(defn- unwrap-meta-name + "Recursively unwrap (with-meta sym meta) forms to extract the underlying symbol. + Returns the symbol struct, or the original form if it's not a with-meta wrapper." + [form] + (if (and (array? form) (> (length form) 0) + (struct? (in form 0)) + (= :symbol ((in form 0) :jolt/type)) + (= "with-meta" ((in form 0) :name))) + (unwrap-meta-name (in form 1)) + form)) + +(defn- eval-list + [ctx bindings form] + (def first-form (first form)) + # Safe name extraction: non-symbol heads (e.g. keywords) fall through to default. + # A head qualified to a NON-core namespace (e.g. clojure.edn/read-string) must + # resolve to that var, not the like-named clojure.core special form — so only + # unqualified or clojure.core-qualified heads dispatch as special forms. + (def name (if (and (struct? first-form) (= :symbol (first-form :jolt/type))) + (let [ns (first-form :ns)] + (if (or (nil? ns) (= ns "clojure.core")) (first-form :name) nil)) + nil)) + (match name + "quote" (in form 1) + # Interpreter builds the form directly (self-contained, no core dependency). + # The COMPILE path instead lowers syntax-quote to construction code (via + # syntax-quote-lower) so a backtick body is compilable; the two are kept in + # sync and cross-checked by conformance (interpret vs compile modes). + "syntax-quote" (syntax-quote* ctx bindings (in form 1)) + "unquote" (error "Unquote not valid outside of syntax-quote") + "unquote-splicing" (error "Unquote-splicing not valid outside of syntax-quote") + "eval" (eval-form ctx bindings (eval-form ctx bindings (in form 1))) + "read-string" (parse-string (eval-form ctx bindings (in form 1))) + "defonce" (let [name-sym (unwrap-meta-name (in form 1)) + ns (ctx-find-ns ctx (ctx-current-ns ctx)) + existing (ns-find ns (name-sym :name))] + (if (and existing (not (nil? (get existing :root)))) + existing + (eval-form ctx bindings @[{:jolt/type :symbol :ns nil :name "def"} + (in form 1) (in form 2)]))) + "macroexpand-1" (let [the-form (eval-form ctx bindings (in form 1))] + (if (and (array? the-form) (> (length the-form) 0) + (struct? (first the-form)) (= :symbol ((first the-form) :jolt/type))) + (let [v (resolve-var ctx bindings (first the-form))] + (if (and v (var-macro? v)) + (apply (var-get v) (tuple/slice the-form 1)) + the-form)) + the-form)) + "do" (do + (var result nil) + (var i 1) + (let [len (length form)] + (while (< i len) + (set result (eval-form ctx bindings (in form i))) + (++ i))) + result) + "if" (let [test-val (eval-form ctx bindings (in form 1))] + (if (and (not (nil? test-val)) (not (= false test-val))) + (eval-form ctx bindings (in form 2)) + (if (> (length form) 3) (eval-form ctx bindings (in form 3)) nil))) + "def" (let [raw-name (in form 1) + name-sym (unwrap-meta-name raw-name) + # Metadata on the name: keyword/type-hint metadata rides on the + # symbol (:meta); a ^{:map} reads as a with-meta form we evaluate. + sym-meta (or (and (struct? name-sym) (get name-sym :meta)) {}) + wm-meta (if (and (array? raw-name) (> (length raw-name) 0) + (sym-name? (first raw-name) "with-meta")) + (let [mv (protect (eval-form ctx bindings (last raw-name)))] + (if (and (mv 0) (or (table? (mv 1)) (struct? (mv 1)))) (mv 1) {})) + {}) + name-meta (merge wm-meta sym-meta) + dynamic? (truthy? (get name-meta :dynamic)) + ns-name (ctx-current-ns ctx) + ns (ctx-find-ns ctx ns-name) + # Create var first (unbound) so self-referencing defs resolve + v (ns-intern ns (name-sym :name)) + # (def name docstring value): docstring is form 2, value form 3 + has-doc (and (> (length form) 3) (string? (in form 2))) + val (eval-form ctx bindings (in form (if has-doc 3 2)))] + (bind-root v val) + (let [extra (if has-doc (merge name-meta {:doc (in form 2)}) name-meta)] + (when (not (empty? extra)) + (put v :meta (merge (or (get v :meta) {}) extra)))) + (when dynamic? + (put v :dynamic true)) + # def returns the var (Clojure semantics); REPL prints #'ns/name + v) + "defmacro" (let [name-sym (in form 1) + rest-form (tuple/slice form 2) + # optional docstring + has-doc? (and (> (length rest-form) 0) (string? (first rest-form))) + args-form (if has-doc? (in rest-form 1) (first rest-form)) + body (tuple/slice rest-form (if has-doc? 2 1)) + param-info (parse-params args-form) + fixed-pats (param-info :fixed) + rest-pat (param-info :rest) + defining-ns (ctx-current-ns ctx)] + (def interp-fn (fn [& macro-args] + (var new-bindings @{}) + (table/setproto new-bindings bindings) + (put new-bindings "&env" @{}) # implicit &env for macro bodies (table — nil-safe) + (var i 0) + # Destructure macro params (like fn), so [& [a & more :as all]] + # and {:keys …} rest forms work in macro arglists. + (each pat fixed-pats + (destructure-bind ctx new-bindings pat (macro-args i)) + (++ i)) + (when rest-pat + (destructure-bind ctx new-bindings rest-pat (tuple/slice macro-args i))) + # Use defining namespace for symbol resolution + (def saved-ns (ctx-current-ns ctx)) + (ctx-set-current-ns ctx defining-ns) + (var result nil) + (each bf body + (set result (eval-form ctx new-bindings bf))) + (ctx-set-current-ns ctx saved-ns) + result)) + # Prefer a COMPILED expander (native-speed expansion, zero runtime + # cost). Skip when the body uses &env/&form (the compiled fn has no + # such params) — those fall back to the interpreted closure. + (def uses-env (or (form-uses-sym? body "&env") (form-uses-sym? body "&form"))) + (def compiled-fn + (when (and macro-compile-hook (not uses-env)) + (macro-compile-hook ctx args-form body))) + (def macro-fn (or compiled-fn interp-fn)) + (let [ns-name (ctx-current-ns ctx) + ns (ctx-find-ns ctx ns-name)] + (def v (ns-intern ns (name-sym :name) macro-fn)) + (put v :macro true) + # Stash the expander source so backend/recompile-macros! can + # compile it once the analyzer is alive (staged bootstrap): a + # macro defined WHILE the analyzer is still being built gets an + # interpreted closure now, a compiled expander later. uses-env + # macros stay interpreted (the compiled fn* has no &env/&form). + (put v :macro-src @[args-form body]) + (put v :macro-uses-env uses-env) + (when compiled-fn (put v :macro-compiled true)) + # A (re)defined macro invalidates any cached expansions. + (table/clear macro-cache) + (var-get v))) + # ns is now a macro (clojure.core, 30-macros) expanding to in-ns + require/use/ + # import/refer-clojure calls — all ctx-capturing fns — so it compiles. No + # special-form arm; an (ns ...) head falls through to the macro-expansion path. + # require / in-ns are now ordinary clojure.core fns (install-stateful-fns!) — + # no special-form arm; they compile + interpret as plain invokes. + "all-ns" (all-ns ctx) + "the-ns" (the-ns ctx) + "create-ns" (create-ns ctx (sym-name-str (in form 1))) + "remove-ns" (remove-ns ctx (sym-name-str (in form 1))) + "ns-interns" (let [ns (ctx-find-ns ctx (ctx-current-ns ctx))] (ns :mappings)) + "ns-aliases" (let [ns (ctx-find-ns ctx (ctx-current-ns ctx))] (ns :aliases)) + "ns-imports" (let [ns (ctx-find-ns ctx (ctx-current-ns ctx))] (ns :imports)) + "ns-resolve" (ns-resolve (ctx-find-ns ctx (ctx-current-ns ctx)) (in form 1)) + "resolve" (let [sym (eval-form ctx bindings (in form 1))] + (if (and (struct? sym) (= :symbol (sym :jolt/type))) + (let [r (protect (resolve-var ctx bindings sym))] + (if (= (r 0) true) (r 1) nil)) + nil)) + "find-ns" (let [sym (eval-form ctx bindings (in form 1)) + nm (if (and (struct? sym) (= :symbol (sym :jolt/type))) (sym :name) (string sym))] + (get (get (ctx :env) :namespaces) nm)) + "fn*" (let [# optional name: (fn* name [args] ...) / (fn* name ([args] ...)...) + named? (and (struct? (in form 1)) (= :symbol ((in form 1) :jolt/type))) + fn-name (if named? ((in form 1) :name) nil) + form (if named? (array/concat @[(in form 0)] (tuple/slice form 2)) form)] + (if (array? (in form 1)) + # Multi-arity: (fn* ([args] body...) ([args] body...)...) + (let [pairs (tuple/slice form 1) + arities @{} + defining-ns (ctx-current-ns ctx)] + (var self nil) + # The (single) variadic clause is dispatched separately: it handles + # any arg count >= its fixed count. Storing it in `arities` by + # fixed-count would collide with a same-fixed-count fixed clause and + # only match that exact count. + (var variadic-fn nil) + (var variadic-min 0) + (each pair pairs + (let [args-form (in pair 0) + body (tuple/slice pair 1) + param-info (parse-params args-form) + _ (require-symbol-params param-info) + fixed-pats (param-info :fixed) + rest-pat (param-info :rest) + n-fixed (length fixed-pats) + f (fn [& fn-args] + (var fn-bindings @{}) + (table/setproto fn-bindings bindings) + (var i 0) + (each pat fixed-pats + (destructure-bind ctx fn-bindings pat (fn-args i)) + (++ i)) + (when rest-pat + (destructure-bind ctx fn-bindings rest-pat (tuple/slice fn-args i))) + (put fn-bindings :jolt/loop-fn self) + (when fn-name (bind-put fn-bindings fn-name self)) + # Use defining namespace for symbol resolution + (def saved-ns (ctx-current-ns ctx)) + (ctx-set-current-ns ctx defining-ns) + (var result nil) + (each body-form body + (set result (eval-form ctx fn-bindings body-form))) + (ctx-set-current-ns ctx saved-ns) + result)] + (if rest-pat + (do (set variadic-fn f) (set variadic-min n-fixed)) + (put arities n-fixed f)))) + (set self (fn [& fn-args] + (let [n (length fn-args) + f (get arities n)] + (cond + f (apply f fn-args) + (and variadic-fn (>= n variadic-min)) (apply variadic-fn fn-args) + (error (string "Wrong number of args (" n ") passed to fn")))))) + self) + # Single-arity: (fn* [args] body...) + (let [args-form (in form 1) + body (tuple/slice form 2) + param-info (parse-params args-form) + _ (require-symbol-params param-info) + fixed-pats (param-info :fixed) + rest-pat (param-info :rest) + defining-ns (ctx-current-ns ctx)] + (var self nil) + (set self (fn [& fn-args] + (var fn-bindings @{}) + (table/setproto fn-bindings bindings) + (var i 0) + (each pat fixed-pats + (destructure-bind ctx fn-bindings pat (fn-args i)) + (++ i)) + (when rest-pat + (destructure-bind ctx fn-bindings rest-pat (tuple/slice fn-args i))) + (put fn-bindings :jolt/loop-fn self) + (when fn-name (bind-put fn-bindings fn-name self)) + # Use defining namespace for symbol resolution + (def saved-ns (ctx-current-ns ctx)) + (ctx-set-current-ns ctx defining-ns) + (var result nil) + (each body-form body + (set result (eval-form ctx fn-bindings body-form))) + (ctx-set-current-ns ctx saved-ns) + result)) + self))) + "let*" (let [bind-vec (in form 1) + body (tuple/slice form 2)] + (var new-bindings @{}) + (table/setproto new-bindings bindings) + (var i 0) + (let [len (length bind-vec)] + (while (< i len) + (let [pat (bind-vec i)] + # let* is a primitive (the let macro desugars destructuring); + # its binding names must be plain symbols, as in Clojure. + (unless (plain-sym? pat) (error "Bad binding form, expected symbol")) + (def val (eval-form ctx new-bindings (bind-vec (+ i 1)))) + (destructure-bind ctx new-bindings pat val) + (+= i 2)))) + (var result nil) + (each body-form body + (set result (eval-form ctx new-bindings body-form))) + result) + "loop*" (let [bind-vec (in form 1) + body (tuple/slice form 2) + init-vals @[] + patterns @[] + # Inits are evaluated sequentially in an accumulating scope (like + # let*), so a later init can reference an earlier binding — + # matching Clojure's loop. + seq-bindings @{}] + (table/setproto seq-bindings bindings) + (var i 0) + (while (< i (length bind-vec)) + # loop* is a primitive (the loop macro desugars destructuring); + # its binding names must be plain symbols, as in Clojure. + (unless (plain-sym? (bind-vec i)) (error "Bad binding form, expected symbol")) + (def v (eval-form ctx seq-bindings (bind-vec (+ i 1)))) + (bind-put seq-bindings ((bind-vec i) :name) v) + (array/push init-vals v) + (array/push patterns (bind-vec i)) + (+= i 2)) + (var loop-fn nil) + (set loop-fn (fn [& args] + (var loop-bindings @{}) + (table/setproto loop-bindings bindings) + (var j 0) + (each pat patterns + (destructure-bind ctx loop-bindings pat (in args j)) + (++ j)) + (put loop-bindings :jolt/loop-fn loop-fn) + (var result nil) + (each body-form body + (set result (eval-form ctx loop-bindings body-form))) + result)) + (apply loop-fn init-vals)) + "recur" (let [loop-fn (get bindings :jolt/loop-fn)] + (if (nil? loop-fn) + (error "recur used outside of loop* or fn*") + (let [args (map |(eval-form ctx bindings $) (tuple/slice form 1))] + (apply loop-fn args)))) + "throw" (let [val (eval-form ctx bindings (in form 1))] + (error {:jolt/type :jolt/exception :value val})) + "try" (let [body-form (in form 1) + clauses (tuple/slice form 2) + n (length clauses) + # current-ns is dynamic state. The interpreter rebinds it to a + # fn's defining ns while that fn runs and restores it on normal + # return, but a fn that THROWS unwinds past its own restore — so + # the ns can leak. try is the unwind boundary: restore the ns that + # was current at try entry before running catch/finally, so caught + # code (and the harness's is/thrown?) sees the right namespace. + try-ns (ctx-current-ns ctx)] + (var catch-sym nil) + (var catch-body nil) + (var finally-body nil) + (var i 0) + (while (< i n) + (let [clause (in clauses i)] + (if (and (array? clause) (> (length clause) 0)) + (let [head (first clause)] + (if (and (struct? head) (= :symbol (head :jolt/type))) + (match (head :name) + "catch" (do + (set catch-sym (in clause 2)) + (set catch-body (tuple/slice clause 3))) + "finally" (set finally-body (tuple/slice clause 1))))))) + (++ i)) + (defn run-finally [f] + (when f + (each fb f (eval-form ctx bindings fb)))) + (if catch-sym + (try + (eval-form ctx bindings body-form) + ([err] + (ctx-set-current-ns ctx try-ns) + (var new-bindings @{}) + (table/setproto new-bindings bindings) + # bind the originally-thrown value (unwrap the :jolt/exception + # envelope) so (catch ... e (throw e)) rethrows the same value + # rather than nesting another envelope + (def caught + (if (and (or (table? err) (struct? err)) (= :jolt/exception (get err :jolt/type))) + (get err :value) + err)) + (put new-bindings (catch-sym :name) caught) + (var result nil) + (each cb catch-body + (set result (eval-form ctx new-bindings cb))) + (run-finally finally-body) + result)) + (if finally-body + (try + (do + (def result (eval-form ctx bindings body-form)) + (run-finally finally-body) + result) + ([err] + (ctx-set-current-ns ctx try-ns) + (run-finally finally-body) + (error err))) + (eval-form ctx bindings body-form)))) + "set!" (let [target (in form 1) + val (eval-form ctx bindings (in form 2))] + # Handle (set! (.-field obj) val) — .-field shorthand as a list + (if (and (array? target) (> (length target) 1) + (struct? (first target)) (= :symbol ((first target) :jolt/type)) + (> (length ((first target) :name)) 1) + (= (string/slice ((first target) :name) 0 2) ".-")) + (let [obj (eval-form ctx bindings (in target 1)) + field-name (string/slice ((first target) :name) 2) + field-key (keyword field-name)] + (if (get obj :jolt/deftype) + (do (put obj field-key val) val) + (error (string "Can't set! field on non-deftype: " (type obj))))) + # (set! (. obj -field) val) — instance field mutation + (if (and (array? target) (> (length target) 0) + (struct? (first target)) + (= :symbol ((first target) :jolt/type)) + (= "." ((first target) :name))) + (let [obj (eval-form ctx bindings (in target 1)) + field-sym (in target 2) + field-name (field-sym :name) + field-key (keyword (if (and (> (length field-name) 0) (= "-" (string/slice field-name 0 1))) + (string/slice field-name 1) + field-name))] + (if (get obj :jolt/deftype) + (do (put obj field-key val) val) + (error (string "Can't set! field on non-deftype: " (type obj))))) + # (set! var val) — normal var mutation + (let [target-sym target + v (resolve-var ctx bindings target-sym)] + (if v + (do (var-set v val) val) + # Auto-create var if it doesn't exist + (let [ns-name (ctx-current-ns ctx) + ns (ctx-find-ns ctx ns-name)] + (def new-v (ns-intern ns (target-sym :name) val)) + val)))))) + "var" (let [target-sym (in form 1) + v (resolve-var ctx bindings target-sym)] + (if v v (error (string "Unable to resolve var: " (sym-name-str target-sym) " in var")))) + # var-get/var-set/var?/alter-var-root/alter-meta!/reset-meta! are plain + # clojure.core fns; find-var/intern are ctx-capturing clojure.core fns + # (install-stateful-fns!) — they fall through to the function-call default + # and compile as ordinary invokes (Stage 2 tier 6). + # set?/disj are plain clojure.core fns now (core-set?/core-disj) — no longer + # special-cased here, the analyzer, or compiler.janet (jolt-g3h). + # protocol-dispatch / register-method / make-reified are now ordinary + # clojure.core fns (install-stateful-fns!) — the defprotocol/extend-type/reify + # macros call them with name STRINGS, so they compile + interpret as plain + # invokes (no special-form arms). + "satisfies?" (let [proto-sym (eval-form ctx bindings (in form 1)) + obj (eval-form ctx bindings (in form 2)) + type-tag (if (and (table? obj) (get obj :jolt/deftype)) + (get obj :jolt/deftype) + (if (get obj :jolt/protocol-methods) + (get obj :jolt/deftype)))] + (if type-tag + (let [pn (proto-sym :name) + pn-str (if (struct? pn) (pn :name) pn)] + (type-satisfies? ctx type-tag pn-str)) + false)) + "locking" (eval-form ctx bindings (in form 2)) + "instance?" (let [type-sym (in form 1) + val (eval-form ctx bindings (in form 2))] + (if (get val :jolt/deftype) + (let [type-tag (val :jolt/deftype) + type-name (type-sym :name)] + (or (= type-tag type-name) + (and (> (length type-tag) (length type-name)) + (= (string/slice type-tag (- (length type-tag) (length type-name))) + type-name)))) + (match (type-sym :name) + "Number" (number? val) + "java.lang.Number" (number? val) + "Long" (number? val) + "java.lang.Long" (number? val) + "Integer" (number? val) + "Double" (number? val) + "String" (string? val) + "java.lang.String" (string? val) + "Boolean" (or (= true val) (= false val)) + "Keyword" (keyword? val) + "clojure.lang.Atom" (and (table? val) (= :jolt/atom (val :jolt/type))) + "clojure.lang.Volatile" (and (table? val) (= :jolt/volatile (val :jolt/type))) + "clojure.lang.Delay" (and (table? val) (= :jolt/delay (val :jolt/type))) + "clojure.lang.IPersistentMap" (or (phm? val) (struct? val)) + "clojure.lang.IPersistentVector" (or (tuple? val) (pvec? val)) + "clojure.lang.IPersistentSet" (set? val) + "Object" true + false))) + # defmulti / defmethod are now macros (30-macros) over defmulti-setup / + # defmethod-setup (ctx-capturing clojure.core fns) — they compile as plain + # invokes; no special-form arms. defmethod's impl is a compiled (fn …). + "prefer-method" (let [mm-arg (in form 1) + mm-var (if (and (struct? mm-arg) (= :symbol (mm-arg :jolt/type))) + (resolve-var ctx bindings mm-arg) + (eval-form ctx bindings mm-arg)) + # Auto-create multimethod if it doesn't exist + mm-var (if mm-var mm-var + (let [ns (ctx-find-ns ctx (ctx-current-ns ctx)) + dummy-fn (fn [& args] nil)] + (def v (ns-intern ns (mm-arg :name) dummy-fn)) + (put v :jolt/methods @{}) + v)) + dispatch-val-a (eval-form ctx bindings (in form 2)) + dispatch-val-b (eval-form ctx bindings (in form 3)) + prefs (or (get mm-var :jolt/prefers) + (do (put mm-var :jolt/prefers @{}) (mm-var :jolt/prefers)))] + (put prefs dispatch-val-a dispatch-val-b) + (let [dc (get mm-var :jolt/dispatch-cache)] + (when dc (each k (keys dc) (put dc k nil)))) + mm-var) + # A multimethod's methods live on its VAR, but the value is the dispatch fn; + # so resolve the var from the symbol rather than evaluating it. + "get-method" (let [mm-arg (in form 1) + mm-var (if (and (struct? mm-arg) (= :symbol (mm-arg :jolt/type))) + (resolve-var ctx bindings mm-arg) + (eval-form ctx bindings mm-arg)) + dispatch-val (eval-form ctx bindings (in form 2))] + (when mm-var + (let [methods (get mm-var :jolt/methods)] + (or (get methods dispatch-val) (get methods :default))))) + "methods" (let [mm-arg (in form 1) + mm-var (if (and (struct? mm-arg) (= :symbol (mm-arg :jolt/type))) + (resolve-var ctx bindings mm-arg) + (eval-form ctx bindings mm-arg))] + (and mm-var (get mm-var :jolt/methods))) + "remove-method" (let [mm-arg (in form 1) + mm-var (if (and (struct? mm-arg) (= :symbol (mm-arg :jolt/type))) + (resolve-var ctx bindings mm-arg) + (eval-form ctx bindings mm-arg)) + dispatch-val (eval-form ctx bindings (in form 2))] + (when mm-var + (let [methods (get mm-var :jolt/methods)] + (when methods (put methods dispatch-val nil))) + (let [dc (get mm-var :jolt/dispatch-cache)] + (when dc (each k (keys dc) (put dc k nil))))) + mm-var) + "remove-all-methods" (let [mm-var (eval-form ctx bindings (in form 1))] + (when mm-var + (put mm-var :jolt/methods @{}) + (let [dc (get mm-var :jolt/dispatch-cache)] + (when dc (each k (keys dc) (put dc k nil))))) + mm-var) + # deftype is now a macro (30-macros) over make-deftype-ctor + extend-type — + # compiles as a plain (do …); no special-form arm. + "new" (let [type-sym (in form 1) + args (map |(eval-form ctx bindings $) (tuple/slice form 2)) + ctor (eval-form ctx bindings type-sym)] + (apply ctor args)) + "." (let [target (eval-form ctx bindings (in form 1)) + member-raw (in form 2) + # Resolve member name: symbols have :name, keywords use string, strings as-is + member-name (if (and (struct? member-raw) (= :symbol (member-raw :jolt/type))) + (member-raw :name) + (if (keyword? member-raw) + (string member-raw) + member-raw)) + field-name (if (and (string? member-name) (> (length member-name) 0) (= "-" (string/slice member-name 0 1))) + (string/slice member-name 1) + member-name)] + (if (> (length form) 3) + # method call: (. obj method args...) + (let [args (map |(eval-form ctx bindings $) (tuple/slice form 3))] + (if (target :jolt/deftype) + (let [method-key (keyword field-name)] + (apply (get target method-key) target ;args)) + # Janet-native interop: try field lookup + call + (if (or (table? target) (struct? target)) + (let [method (get target (keyword field-name))] + (if (or (function? method) (cfunction? method)) + (method target ;args) + # If stored as fn* form (array), compile to function then call + (if (array? method) + (let [method-fn (eval-form ctx bindings method)] + (if (or (function? method-fn) (cfunction? method-fn)) + (method-fn target ;args) + (error (string "Cannot call non-function " field-name " on " (type target))))) + (error (string "Cannot call non-function " field-name " on " (type target)))))) + (error (string "Cannot call method " field-name " on " (type target)))))) + # (. obj member) with no extra args: a symbol member naming a + # function is a zero-arg method call (receiver passed as self); + # a keyword or `-field` member is plain field access. + (let [v (get target (keyword field-name))] + (if (and (struct? member-raw) (= :symbol (member-raw :jolt/type)) + (not (string/has-prefix? "-" member-name))) + (cond + (or (function? v) (cfunction? v)) (v target) + # value stored as an unevaluated fn* form: compile then call + (array? v) (let [f (eval-form ctx bindings v)] + (if (or (function? f) (cfunction? f)) (f target) f)) + v) + v)))) + # default: function application — check for macros + (if (and (struct? first-form) (= :symbol (first-form :jolt/type))) + (let [sym-name (first-form :name)] + # Handle .-fieldName accessor: (.-cnt obj) → (. obj -cnt) + (if (and (> (length sym-name) 1) (= (string/slice sym-name 0 2) ".-") + (> (length form) 1)) + (let [field-name (string/slice sym-name 2) + target (eval-form ctx bindings (in form 1))] + (get target (keyword field-name))) + # Handle ClassName. constructor syntax + (if (and (> (length sym-name) 0) (= (sym-name (- (length sym-name) 1)) 46)) + (let [type-name (string/slice sym-name 0 (- (length sym-name) 1)) + type-sym {:jolt/type :symbol :ns (first-form :ns) :name type-name} + ctor (eval-form ctx bindings type-sym) + args (map |(eval-form ctx bindings $) (tuple/slice form 1))] + (apply ctor args)) + (let [v (resolve-var ctx bindings first-form)] + (if (and v (var-macro? v)) + # Expand once (cached by call-form identity), then evaluate the + # macro-free expansion with the current bindings each call. + (let [cached (in macro-cache form)] + (if (not (nil? cached)) + (eval-form ctx bindings cached) + (let [expanded (apply (var-get v) (tuple/slice form 1))] + (put macro-cache form expanded) + (eval-form ctx bindings expanded)))) + (let [f (eval-form ctx bindings first-form) + args (map |(eval-form ctx bindings $) (tuple/slice form 1))] + (jolt-invoke ctx f args))))))) + (let [f (eval-form ctx bindings first-form) + args (map |(eval-form ctx bindings $) (tuple/slice form 1))] + (jolt-invoke ctx f args))))) + +# Build a map value from an array of evaluated [k v k v ...]. A phm (not a Janet +# struct) is used when a key is a collection (value-based hashing) OR a key/value +# is nil (Janet structs drop nil; phm preserves it, matching Clojure). The common +# scalar/nil-free case stays a struct. +(defn- map-needs-phm? [kvs] + (var need false) (var i 0) + (while (< i (length kvs)) + (let [k (in kvs i) v (in kvs (+ i 1))] + (when (or (table? k) (array? k) (nil? k) (nil? v)) (set need true) (break))) + (+= i 2)) + need) + +(defn- build-eval-map [kvs] + (if (map-needs-phm? kvs) + (do (var m (make-phm)) (var j 0) + (while (< j (length kvs)) (set m (phm-assoc m (in kvs j) (in kvs (+ j 1)))) (+= j 2)) m) + (struct ;kvs))) + +(set eval-form (fn [ctx bindings form] + (cond + (nil? form) nil + (number? form) form + (string? form) form + (keyword? form) form + (bytes? form) form + (buffer? form) form + (tuple? form) + (let [els (map |(eval-form ctx bindings $) form)] + (if mutable? (array ;els) (pv-from-indexed els))) + (struct? form) + (if (= :symbol (form :jolt/type)) + (resolve-sym ctx bindings form) + (if (= :jolt/char (form :jolt/type)) + form + (if (= :jolt/set (form :jolt/type)) + # evaluate each element (set literals like #{(inc 1)} must compute) + (apply make-phs (map |(eval-form ctx bindings $) (form :value))) + (if (= :jolt/tagged (form :jolt/type)) + (let [tag (form :tag) + data-readers (get (ctx :env) :data-readers) + reader-fn (if data-readers (get data-readers tag))] + (cond + # #"..." regex literal -> a regex value (Janet PEG-backed) + (= tag :regex) (compile-regex (form :form)) + reader-fn (reader-fn (form :form)) + (error (string "No reader function for tag " tag)))) + (if (get form :jolt/type) + (error (string "Unexpected tagged form: " (form :jolt/type))) + # plain map literal: evaluate keys and values + (let [kvs @[]] + (each k (keys form) + (array/push kvs (eval-form ctx bindings k)) + (array/push kvs (eval-form ctx bindings (get form k)))) + (build-eval-map kvs))))))) + # A phm map-literal FORM (reader emits one for {:a nil} etc., which a struct + # would have dropped): evaluate its key/value forms and rebuild, preserving nil. + (phm? form) + (let [kvs @[]] + (each e (phm-entries form) + (array/push kvs (eval-form ctx bindings (in e 0))) + (array/push kvs (eval-form ctx bindings (in e 1)))) + (build-eval-map kvs)) + (array? form) + (if (= 0 (length form)) + @[] + (eval-list ctx bindings form)) + form))) diff --git a/src/jolt/host_iface.janet b/src/jolt/host_iface.janet new file mode 100644 index 0000000..cdad206 --- /dev/null +++ b/src/jolt/host_iface.janet @@ -0,0 +1,184 @@ +# Janet implementation of the Jolt host contract (ns `jolt.host`). +# +# This is the seam between the portable jolt-core (analyzer/IR/core, pure Clojure +# under jolt-core/) and the Janet runtime. jolt-core calls ONLY these functions — +# never Janet directly. Re-hosting Jolt to another runtime means reimplementing +# this contract (+ the back end and RT) for that runtime. +# +# Lives in src/jolt/ (with the rest of the Janet host) rather than a separate +# host/janet/ dir: Janet resolves relative imports per-file, so a host/janet +# module importing ../../src/jolt/* loads SECOND instances of compiler/types/core +# (inconsistent state). The portability boundary is the `jolt.host` namespace +# contract + jolt-core/, not the directory. +# +# Two groups: +# 1. Form introspection — reader forms are host-specific (the reader is the +# host's), so shape predicates/accessors live here. Returns jolt values the +# analyzer walks with ordinary Clojure. +# 2. Compile-time environment — resolve symbols to vars/macros, expand macros, +# the current namespace. These take ctx (an opaque host handle). + +(use ./types) +(use ./evaluator) +(use ./core) +(import ./phm :as phm) + +# --------------------------------------------------------------------------- +# Form introspection +# --------------------------------------------------------------------------- + +(defn h-sym? [form] (and (struct? form) (= :symbol (form :jolt/type)))) +(defn h-sym-name [form] (form :name)) +(defn h-sym-ns [form] (form :ns)) +# Reader metadata on a symbol (e.g. ^:dynamic / ^:redef / ^:private on a def +# name). Returns the meta map or nil. Lets the analyzer carry def metadata that +# the back end applies to the var — without it, compiled defs drop all var meta. +(defn h-sym-meta [form] (form :meta)) + +(defn h-list? [form] (array? form)) # a call / list (reader: array) +(defn h-vector? [form] (tuple? form)) # a vector literal (reader: tuple) +# A map-literal form is a plain struct, or a phm when the reader preserved a nil +# key/value (Janet structs drop nil). Sets/chars/symbols are tagged structs (have +# :jolt/type); phm carries :jolt/deftype, distinct from those. +(defn h-map? [form] + (or (and (struct? form) (nil? (form :jolt/type))) + (phm/phm? form))) +(defn h-set? [form] (and (struct? form) (= :jolt/set (form :jolt/type)))) +(defn h-char? [form] (and (struct? form) (= :jolt/char (form :jolt/type)))) + +(defn h-literal? [form] + (or (nil? form) (boolean? form) (number? form) (string? form) + (keyword? form) (h-char? form))) + +# Items of a list/vector as a jolt vector, so the analyzer walks them with Clojure. +(defn h-elements [form] (make-vec form)) +(defn h-vector-items [form] (make-vec form)) +(defn h-map-pairs [form] + (if (phm/phm? form) + (make-vec (map (fn [e] (make-vec [(in e 0) (in e 1)])) (phm/phm-entries form))) + (make-vec (map (fn [k] (make-vec [k (get form k)])) (keys form))))) +(defn h-set-items [form] (make-vec (form :value))) + +# --------------------------------------------------------------------------- +# Compile-time environment +# --------------------------------------------------------------------------- + +# Names the analyzer must NOT treat as a function call: interpreter special forms +# plus definitional/host macros the compiler doesn't lower. The analyzer handles +# a subset (quote/if/do/def/fn*/let*/loop*/recur/throw/try) and falls back to the +# interpreter for the rest. Kept in sync with evaluator/special-symbol? and +# compiler/uncompilable-heads. +(def- special-names + (let [t @{}] + (each n ["quote" "syntax-quote" "unquote" "unquote-splicing" "do" "if" "def" + "defmacro" "fn*" "let*" "loop*" "recur" "throw" "try" "set!" + # defmulti/defmethod/deftype now compile (macros over *-setup fns). + "locking" "eval" "instance?" "new" + # var-get/var-set/var?/alter-var-root/alter-meta!/reset-meta! are + # plain core fns; find-var/intern are ctx-capturing core fns — all + # compile as ordinary invokes now (Stage 2 tier 6). + "." "satisfies?" + # protocol-dispatch/register-method/make-reified are now clojure.core + # fns (compile as plain invokes). + "prefer-method" + "remove-method" "remove-all-methods" "get-method" "methods" + # ns-management forms dispatched by the interpreter (not core vars) + "create-ns" "remove-ns" "find-ns" "all-ns" "the-ns" "resolve" + "ns-resolve" "ns-aliases" "ns-imports" "ns-interns" + # ns/require/in-ns/use/import/refer-clojure are now clojure.core + # fns/macros (compile as plain invokes / expand to them). + "read-string" "macroexpand-1" "defonce" + "refer" + # defprotocol/extend-type/extend-protocol/reify/defrecord now expand to + # plain def + protocol-dispatch/register-method/make-reified/deftype. + "gen-class" + # letfn stays: its let* expansion needs letrec semantics (mutual + # recursion between the fns), which compiled sequential let* lacks. + "monitor-enter" "monitor-exit" "letfn"] + (put t n true)) + t)) + +# Interop-shaped heads the interpreter lowers but the back end doesn't model: +# (.method obj …) / (.-field obj) — member access (name starts with ".") +# (Foo. …) — constructor (name ends with "." ) +# Treated as special so the analyzer marks them uncompilable and falls back. +(defn- interop-head? [name] + (def n (length name)) + (and (> n 1) + (or (= (string/slice name 0 1) ".") + (= (string/slice name (- n 1)) ".")))) + +(defn h-special? [name] + (if (or (get special-names name) (interop-head? name)) true false)) + +# The namespace being compiled. NOT ctx-current-ns directly: the interpreter +# rebinds current-ns to a fn's defining ns while that fn runs, so an interpreted +# analyzer (defined in jolt.analyzer) would otherwise see jolt.analyzer. The back +# end stashes the real compile ns in :compile-ns before invoking the analyzer. +(defn h-current-ns [ctx] (or (get (ctx :env) :compile-ns) (ctx-current-ns ctx))) + +(defn h-macro? [ctx sym] + (let [v (resolve-var ctx @{} sym)] + (if (and v (var-macro? v)) true false))) + +(defn h-expand-1 [ctx form] + (let [head (in form 0) + v (resolve-var ctx @{} head) + macro-fn (var-get v)] + (apply macro-fn (tuple/slice form 1)))) + +# Classify a global (non-local) symbol reference: +# {:kind :var :ns NS :name NAME} — a Jolt var (current ns / clojure.core) +# {:kind :host :name NAME} — resolves only via the host env (+, int?, …), +# same fallback the interpreter's resolve-sym uses +# {:kind :unresolved :name NAME} — not yet defined (forward reference) +(defn h-resolve-global [ctx sym] + (let [v (resolve-var ctx @{} sym)] + (if v + {:kind :var :ns (var-ns v) :name (var-name v)} + (let [nm (sym :name) + entry (in (fiber/getenv (fiber/current)) (symbol nm))] + (if (not (nil? entry)) + {:kind :host :name nm} + {:kind :unresolved :name nm}))))) + +(defn h-intern! [ctx ns-name nm] + (ns-intern (ctx-find-ns ctx ns-name) nm) + nil) + +# --------------------------------------------------------------------------- +# Installation: bind these fns as vars in the `jolt.host` namespace so jolt-core +# can call them. Idempotent per context. +# --------------------------------------------------------------------------- + +# Form predicates use `form-*` names (not list?/vector?/map?/set?/char?) so the +# analyzer can refer them unqualified without the bootstrap's core-renames +# intercepting them as the value-level predicates. +# Lower a syntax-quote's inner form to construction code (so the analyzer can +# compile it). The portable analyzer calls this and analyzes the result. +(defn h-syntax-quote-lower [ctx inner] + (syntax-quote-lower ctx inner)) + +# Runtime host primitive: set a key on a mutable reference cell (an atom, the +# watches sub-table, ...). The minimal mutation kernel the overlay can't express +# over core fns — putting nil removes the key (Janet table semantics). Returns the +# table so callers can thread; overlay wrappers return the Clojure-meaningful value. +(defn h-ref-put! [tab key val] (put tab key val) tab) + +(def- exports + {"form-sym?" h-sym? "form-sym-name" h-sym-name "form-sym-ns" h-sym-ns + "ref-put!" h-ref-put! + "form-sym-meta" h-sym-meta + "form-list?" h-list? "form-vec?" h-vector? "form-map?" h-map? + "form-set?" h-set? "form-char?" h-char? "form-literal?" h-literal? + "form-elements" h-elements "form-vec-items" h-vector-items + "form-map-pairs" h-map-pairs "form-set-items" h-set-items + "form-special?" h-special? "compile-ns" h-current-ns "form-macro?" h-macro? + "form-expand-1" h-expand-1 "resolve-global" h-resolve-global + "form-syntax-quote-lower" h-syntax-quote-lower + "host-intern!" h-intern!}) + +(defn install! [ctx] + (def ns (ctx-find-ns ctx "jolt.host")) + (eachp [nm f] exports (ns-intern ns nm f)) + ns) diff --git a/src/jolt/jolt/http.clj b/src/jolt/jolt/http.clj new file mode 100644 index 0000000..cbbceb1 --- /dev/null +++ b/src/jolt/jolt/http.clj @@ -0,0 +1,12 @@ +; Jolt Standard Library: jolt.http +; HTTP client using Janet's net/ module. + +(defn get + [url & {:keys [headers]}] + (let [result (net/request url :get headers {})] + {:status (result :status) :body (result :body) :headers (result :headers)})) + +(defn post + [url body & {:keys [headers]}] + (let [result (net/request url :post headers body)] + {:status (result :status) :body (result :body) :headers (result :headers)})) diff --git a/src/jolt/jolt/interop.clj b/src/jolt/jolt/interop.clj new file mode 100644 index 0000000..92b9a54 --- /dev/null +++ b/src/jolt/jolt/interop.clj @@ -0,0 +1,26 @@ +; Jolt Standard Library: jolt.interop +; Janet interop helpers for Jolt. + +(defn janet-eval + [s] + (eval (parse s))) + +(defn janet-type + [x] + (type x)) + +(defn janet-describe + [x] + (describe x)) + +(defn janet-table-keys + [t] + (keys t)) + +(defn janet-table-vals + [t] + (vals t)) + +(defn janet-table->map + [t] + (into {} (map (fn [k] [k (get t k)]) (keys t)))) diff --git a/src/jolt/jolt/nrepl.clj b/src/jolt/jolt/nrepl.clj new file mode 100644 index 0000000..55bb4a6 --- /dev/null +++ b/src/jolt/jolt/nrepl.clj @@ -0,0 +1,236 @@ +; Jolt Standard Library: jolt.nrepl +; +; An nREPL (https://nrepl.org) server and client written in Clojure, on top of +; Jolt's Janet interop bridge (the `janet.*` namespace segment). The bencode +; codec follows nrepl.bencode and the op/response shapes follow babashka.nrepl +; (the SCI-targeted nREPL server). Because the whole thing is ordinary Clojure +; over `janet.net/*`, the networking it uses is reusable for anything else. +; +; Notes: +; - One Jolt runtime backs the server; sessions are tracked ids and share the +; runtime (defs persist across a connection, like a dev REPL). +; - eval uses Jolt's own `eval`/`read-string`; printed output is captured by +; rebinding Janet's :out dynamic. +; - No true interrupt: an in-flight synchronous eval can't be stopped. + +;; ───────────────────────── bencode ───────────────────────── + +(defn benc + "Encode `x` (integer, string, keyword, sequential, or map) to a bencode string." + [x] + (cond + (integer? x) (str "i" x "e") + (string? x) (str (count x) ":" x) + (keyword? x) (benc (name x)) + (symbol? x) (benc (name x)) + (map? x) (let [ks (sort (fn [a b] (compare (name a) (name b))) (keys x))] + (str "d" (apply str (mapcat (fn [k] [(benc (name k)) (benc (get x k))]) ks)) "e")) + (sequential? x) (str "l" (apply str (map benc x)) "e") + (nil? x) "le" + :else (throw (ex-info "bencode: cannot encode" {:value x})))) + +(defn encode [x] (benc x)) + +; A reader buffers bytes from a janet.net connection (or a preloaded string for +; tests) and refills via janet.net/read. +(defn reader [conn buf] (atom {:conn conn :buf (or buf "") :pos 0})) + +(defn- rd-ensure [r n] + (loop [] + (let [{:keys [conn buf pos]} @r] + (when (< (count buf) (+ pos n)) + (let [chunk (janet.net/read conn 4096)] + (when (nil? chunk) (throw (ex-info "eof" {}))) + (swap! r assoc :buf (str buf (str chunk))) + (recur)))))) + +(defn- take-n [r n] + (rd-ensure r n) + (let [{:keys [buf pos]} @r] + (swap! r assoc :pos (+ pos n)) + (subs buf pos (+ pos n)))) + +(defn- take-ch [r] (take-n r 1)) + +(def ^:private digits #{"0" "1" "2" "3" "4" "5" "6" "7" "8" "9"}) + +(defn decode + "Read one bencode value from reader `r`. Throws on EOF. Dict keys come back as + strings; the top-level nREPL message is a dict (map)." + [r] + (let [c (take-ch r)] + (cond + (= c "i") (loop [acc ""] (let [d (take-ch r)] (if (= d "e") (janet/scan-number acc) (recur (str acc d))))) + (= c "l") (loop [out []] (let [v (decode r)] (if (= v ::end) out (recur (conj out v))))) + (= c "d") (loop [out {}] (let [k (decode r)] (if (= k ::end) out (recur (assoc out k (decode r)))))) + (= c "e") ::end + (contains? digits c) + (loop [acc c] (let [d (take-ch r)] (if (= d ":") (take-n r (janet/scan-number acc)) (recur (str acc d))))) + :else (throw (ex-info "bad bencode byte" {:byte c}))))) + +;; ───────────────────────── server ───────────────────────── + +(def version "0.1.0") + +(def ^:private session-counter (atom 0)) +(defn- new-session [] + (str "jolt-" (swap! session-counter inc) "-" (janet.math/floor (* 1000000 (janet.math/random))))) + +(defn- resp-for + "Build a response by echoing the request's id/session (an nREPL requirement)." + [msg extra] + (assoc extra "session" (get msg "session" "none") "id" (get msg "id" "unknown"))) + +; Jolt resolves a function body's unqualified symbols against the *dynamic* +; current-ns, not the function's home ns. So evaluating user code (which switches +; ns) would break jolt.nrepl's own later symbol lookups. eval-in-ns confines the +; switch: it evaluates one form in `ns-str` and ALWAYS restores current-ns to +; jolt.nrepl before returning, reporting the form's value/error and resulting ns. +; It uses only special forms (in-ns/eval/the-ns/try) + keywords, so it resolves +; regardless of the ambient ns. +(defn- eval-in-ns [ns-str form] + (in-ns (symbol ns-str)) + ; Bind the value before reading the ns: jolt evaluates map-literal values + ; right-to-left, so the result ns must be captured *after* eval runs any in-ns. + (let [result (try (let [v (eval form)] {:val v :ns (:name (the-ns))}) + (catch Throwable e {:err e :ns (:name (the-ns))}))] + (in-ns 'jolt.nrepl) + result)) + +(defn- eval-handler [server msg send!] + ; current-ns is global ctx state shared by all fibers, so set the eval ns + ; explicitly each time: requested :ns, else the session's last ns, else user. + ; `respond` / `flush-out` are locals (lexical, ns-independent) on purpose. + (let [code (get msg "code" "") + out-buf (janet/buffer "") + old-out (janet/dyn :out) + respond (fn [extra] (send! (assoc extra "session" (get msg "session" "none") + "id" (get msg "id" "unknown")))) + flush-out (fn [] (when (pos? (count out-buf)) + (respond {"out" (str out-buf)}) + (janet.buffer/clear out-buf)))] + (try + (do + (janet/setdyn :out out-buf) + (loop [forms (seq (read-string (str "[" code "]"))) + cur-ns (or (get msg "ns") (:eval-ns @server) "user")] + (when forms + (let [{:keys [val ns err]} (eval-in-ns cur-ns (first forms))] + (flush-out) + (swap! server assoc :eval-ns ns) + (when err (throw err)) + (respond {"ns" ns "value" (pr-str val)}) + (recur (next forms) ns)))) + (janet/setdyn :out old-out) + (respond {"status" ["done"]})) + (catch Throwable e + (janet/setdyn :out old-out) + (flush-out) + (respond {"err" (str e "\n")}) + (respond {"ex" "class jolt/Exception" + "root-ex" "class jolt/Exception" + "status" ["eval-error"]}) + (respond {"status" ["done"]}))))) + +(def ^:private describe-ops + {"clone" {} "close" {} "describe" {} "eval" {} "load-file" {} + "ls-sessions" {} "interrupt" {} "eldoc" {}}) + +(defn- dispatch [server msg send!] + (case (get msg "op") + "clone" (let [id (new-session)] + (swap! server update :sessions conj id) + (send! (resp-for msg {"new-session" id "status" ["done"]}))) + "describe" (send! (resp-for msg {"ops" describe-ops + "versions" {"jolt" {"version-string" version} + "nrepl" {"version-string" version}} + "status" ["done"]})) + "eval" (eval-handler server msg send!) + "load-file" (eval-handler server (assoc msg "code" (get msg "file" "")) send!) + "close" (do (swap! server update :sessions disj (get msg "session")) + (send! (resp-for msg {"status" ["done" "session-closed"]}))) + "ls-sessions" (send! (resp-for msg {"sessions" (vec (:sessions @server)) "status" ["done"]})) + "interrupt" (send! (resp-for msg {"status" ["done"]})) + "eldoc" (send! (resp-for msg {"status" ["done" "no-eldoc"]})) + (send! (resp-for msg {"status" ["error" "unknown-op" "done"]})))) + +(defn- handle-conn [server conn] + (let [r (reader conn nil) + send! (fn [resp] (janet.net/write conn (encode resp)))] + (try + (loop [] + (let [msg (decode r)] + (when (map? msg) + (try (dispatch server msg send!) + (catch Throwable e + (send! (resp-for msg {"err" (str e "\n") "status" ["done"]})))) + (recur)))) + (catch Throwable _ nil)) + (try (janet.net/close conn) (catch Throwable _ nil)))) + +; We run the accept loop ourselves with janet.net/accept rather than passing a +; handler to janet.net/server: Janet's built-in accept loop arity-checks the +; handler, which a Jolt closure doesn't satisfy. janet.ev/call schedules each +; connection (and the loop itself) on a fiber. +(defn- accept-loop [server] + (loop [] + (let [conn (try (janet.net/accept (:sock @server)) (catch Throwable _ nil))] + (when conn + (janet.ev/call handle-conn server conn) + (recur))))) + +(defn start-server! + "Start an nREPL server. opts: :host (default \"127.0.0.1\"), :port (default + 7888). Returns a server handle (an atom). Non-blocking — connections are served + on the event loop." + [opts] + (let [host (get opts :host "127.0.0.1") + port (get opts :port 7888) + sock (janet.net/server host (str port)) + server (atom {:sessions #{} :host host :port port :sock sock :eval-ns "user"})] + (janet.ev/call accept-loop server) + server)) + +(defn stop-server! + "Stop accepting new connections." + [server] + (when-let [sock (:sock @server)] (janet.net/close sock)) + server) + +;; ───────────────────────── client ───────────────────────── + +(defn connect + "Connect to an nREPL server. opts: :host (default \"127.0.0.1\"), :port + (default 7888). Returns a client handle." + [opts] + (let [conn (janet.net/connect (get opts :host "127.0.0.1") (str (get opts :port 7888)))] + {:conn conn :reader (reader conn nil)})) + +(defn send-msg [client msg] (janet.net/write (:conn client) (encode msg))) +(defn read-msg [client] (decode (:reader client))) + +(defn- status-done? [resp] + (when-let [st (get resp "status")] + (and (sequential? st) (some (fn [s] (= "done" (str s))) st)))) + +(defn request + "Send `msg` (a map with at least an \"op\") and collect responses until one + carries the \"done\" status. Returns the vector of responses." + [client msg] + (send-msg client msg) + (loop [out []] + (let [resp (read-msg client) + out (conj out resp)] + (if (status-done? resp) out (recur out))))) + +(defn client-clone + "Send a clone op; return the new session id." + [client] + (some (fn [r] (get r "new-session")) (request client {"op" "clone"}))) + +(defn client-eval + "Eval `code`; returns the responses. Pass `session` to eval in a cloned session." + ([client code] (request client {"op" "eval" "code" code})) + ([client code session] (request client {"op" "eval" "code" code "session" session}))) + +(defn client-close [client] (janet.net/close (:conn client))) diff --git a/src/jolt/jolt/shell.clj b/src/jolt/jolt/shell.clj new file mode 100644 index 0000000..bb2caf1 --- /dev/null +++ b/src/jolt/jolt/shell.clj @@ -0,0 +1,12 @@ +; Jolt Standard Library: jolt.shell +; Shell command execution via Janet's os/shell. + +(defn sh + [& args] + (let [cmd (apply str (interpose " " args)) + result (os/shell cmd)] + {:exit (result 0) :out (result 1) :err (result 2)})) + +(defn shell + [& args] + (:out (apply sh args))) diff --git a/src/jolt/loader.janet b/src/jolt/loader.janet new file mode 100644 index 0000000..7df16ff --- /dev/null +++ b/src/jolt/loader.janet @@ -0,0 +1,78 @@ +# Jolt Loader +# Namespace loading with optional compilation. +# Supports in-memory bytecode caching when :compile? is enabled. + +(use ./reader) +(use ./evaluator) +(import ./backend :as backend) + +# Stateful / context-modifying forms always interpret: they mutate the context +# (namespaces, macros, types, multimethods, dynamic vars, …) in ways the compiler +# doesn't model. Kept here so the compile/interpret routing lives in one place, +# used by both load-ns and the public eval-one. Shrinking toward the frozen +# host-coupled set (Stage 2 jolt-eaa): forms move off this list as they gain a +# compile path; syntax-quote already compiles via the analyzer's `handled` set. +(defn- stateful-head? [head-name] + (or (= head-name "defmacro") + (= head-name "set!") + (= head-name ".") (= head-name "new") + (= head-name "eval"))) + +(defn- form-head-name [form] + (when (array? form) + (let [ff (first form)] + (when (and (struct? ff) (= :symbol (ff :jolt/type))) (ff :name))))) + +(defn eval-toplevel + "Evaluate one top-level form for ctx, honoring :compile?. Stateful forms always + interpret; otherwise the form runs through the self-hosted compile pipeline + (portable Clojure analyzer -> IR -> Janet back end), which falls back to the + interpreter for forms it can't compile. Only the compile step is guarded — + runtime errors in compiled code propagate (no double-eval, no hidden errors)." + [ctx form] + (defn try-compile [] (backend/compile-and-eval ctx form)) + (if (get (ctx :env) :compile?) + (if (array? form) + # A call/list: compile it unless its head is a stateful special form. + (let [hn (form-head-name form)] + (if (and hn (stateful-head? hn)) + (eval-form ctx @{} form) + (try-compile))) + # A bare symbol or vector literal compiles; anything else interprets. + (if (or (and (struct? form) (= :symbol (form :jolt/type))) (tuple? form)) + (try-compile) + (eval-form ctx @{} form))) + (eval-form ctx @{} form))) + +(defn load-ns + "Load a Clojure namespace from a .clj file. Per-form routing (compile-or- + interpret, stateful forms interpret) is shared with eval-one via eval-toplevel. + + (load-ns ctx filepath) → namespace symbol string" + [ctx filepath] + (def source (slurp filepath)) + (var ns-name nil) + (var remaining source) + (var forms @[]) + + # Parse all forms + (while (> (length (string/trim remaining)) 0) + (def [form rest] (parse-next remaining)) + (set remaining rest) + (when (not (nil? form)) + (array/push forms form) + # Extract ns name from the first ns form + (when (and (nil? ns-name) + (array? form) + (> (length form) 0) + (and (struct? (first form)) + (= :symbol ((first form) :jolt/type)) + (= "ns" ((first form) :name)))) + (let [name-form (in form 1)] + (set ns-name (if (struct? name-form) (name-form :name) (string name-form))))))) + + (when (nil? ns-name) + (error (string "No ns form found in " filepath))) + + (each form forms (eval-toplevel ctx form)) + ns-name) diff --git a/src/jolt/main.janet b/src/jolt/main.janet new file mode 100644 index 0000000..e80ea42 --- /dev/null +++ b/src/jolt/main.janet @@ -0,0 +1,393 @@ +# Jolt REPL +# Read-eval-print loop for Clojure expressions. + +(use ./api) +(use ./types) +(use ./phm) +(use ./pv) +(use ./plist) +(use ./config) +(use ./reader) + +(def jolt-version "0.1.0") + +# Compile by default: the shipped runtime runs each form through the self-hosted +# pipeline (portable Clojure analyzer -> IR -> Janet back end) to native bytecode +# (hybrid — forms the analyzer can't compile fall back to the interpreter, so the +# result always matches the interpreter; see backend.janet / loader/eval-toplevel). +# Set JOLT_INTERPRET=1 to force the tree-walking interpreter (debugging / A-B). +(def compile-default? (not (= "1" (os/getenv "JOLT_INTERPRET")))) +(def ctx (init {:compile? compile-default?})) +(ctx-set-current-ns ctx "user") + +(defn read-line [prompt] + (prin prompt) + (flush) + (let [line (file/read stdin :line)] + (if line (string/trim line) nil))) + +# Forward declaration for mutual recursion +(var write-value nil) + +(defn- push-str [buf s] + (buffer/push-string buf s)) + +(defn- write-collection [v buf] + (cond + (pvec? v) + (do + (push-str buf "[") + (let [a (pv->array v) n (pv-count v)] + (var i 0) + (while (< i n) + (write-value (in a i) buf) + (when (< (+ i 1) n) (push-str buf " ")) + (++ i))) + (push-str buf "]")) + + (plist? v) + (do + (push-str buf "(") + (let [a (pl->array v) n (length a)] + (var i 0) + (while (< i n) + (write-value (in a i) buf) + (when (< (+ i 1) n) (push-str buf " ")) + (++ i))) + (push-str buf ")")) + + (tuple? v) + (do + (push-str buf "[") + (var i 0) + (let [n (length v)] + (while (< i n) + (write-value (in v i) buf) + (when (< (+ i 1) n) (push-str buf " ")) + (++ i))) + (push-str buf "]")) + + # LazySeq — realize the cell chain and print as a list. Capped to avoid + # hanging on infinite sequences; prints "..." when truncated. + (and (table? v) (= :jolt/lazy-seq (v :jolt/type))) + (do + (push-str buf "(") + (var cur v) + (var i 0) + (var go true) + (while (and go (< i 1000)) + (let [cell (realize-ls cur)] + (if (or (nil? cell) (= :jolt/pending cell) (= 0 (length cell))) + (set go false) + (do + (when (> i 0) (push-str buf " ")) + (write-value (in cell 0) buf) + (++ i) + (let [rt (in cell 1)] + (if (nil? rt) (set go false) (set cur (make-lazy-seq rt)))))))) + (when (and go (>= i 1000)) (push-str buf " ...")) + (push-str buf ")")) + + (array? v) + (do + # mutable mode: arrays are vectors -> [] ; immutable: arrays are lists -> () + (push-str buf (if mutable? "[" "(")) + (var i 0) + (let [n (length v)] + (while (< i n) + (write-value (in v i) buf) + (when (< (+ i 1) n) (push-str buf " ")) + (++ i))) + (push-str buf (if mutable? "]" ")"))) + + (and (table? v) (= :jolt/set (v :jolt/type))) + (do + (push-str buf "#{") + (var first? true) + (each k (phs-seq v) + (if first? (set first? false) (push-str buf " ")) + (write-value k buf)) + (push-str buf "}")) + + (and (table? v) (= :jolt/transient (v :jolt/type))) + (push-str buf (string "#")) + + (and (table? v) (= :jolt/chan (v :jolt/type))) + (push-str buf "#") + + (phm? v) + (do + (push-str buf "{") + (var first? true) + (each pair (phm-entries v) + (if first? (set first? false) (push-str buf ", ")) + (write-value (in pair 0) buf) (push-str buf " ") (write-value (in pair 1) buf)) + (push-str buf "}")) + + (and (table? v) (= :jolt/regex (v :jolt/type))) + (do (push-str buf "#\"") (push-str buf (v :source)) (push-str buf "\"")) + + (and (table? v) (= :jolt/sorted-map (v :jolt/type))) + (do + (push-str buf "{") + (var first? true) + (each k (sort (array ;(keys (v :map)))) + (if first? (set first? false) (push-str buf ", ")) + (write-value k buf) (push-str buf " ") (write-value (get (v :map) k) buf)) + (push-str buf "}")) + + (and (table? v) (= :jolt/sorted-set (v :jolt/type))) + (do + (push-str buf "#{") + (var first? true) + (each x (v :items) + (if first? (set first? false) (push-str buf " ")) + (write-value x buf)) + (push-str buf "}")) + + (and (table? v) (get v :jolt/deftype)) + (do + (push-str buf "{") + (var first? true) + (each [k val] (pairs v) + (when (and (not= k :jolt/deftype) (not= k :cnt) (not= k :buckets) + (not= k :_meta) (not= k :jolt/type) (not= k :phm)) + (if first? (set first? false) (push-str buf " ")) + (write-value k buf) + (push-str buf " ") + (write-value val buf))) + (push-str buf "}")) + + (struct? v) + (do + (push-str buf "{") + (var first? true) + (each [k val] (pairs v) + (if first? (set first? false) (push-str buf " ")) + (write-value k buf) + (push-str buf " ") + (write-value val buf)) + (push-str buf "}")) + + (table? v) + (do + (push-str buf "{") + (var first? true) + (each [k val] (pairs v) + (when (not= k :jolt/type) + (if first? (set first? false) (push-str buf " ")) + (write-value k buf) + (push-str buf " ") + (write-value val buf))) + (push-str buf "}")))) + +(set write-value (fn [v buf] + (cond + (nil? v) (push-str buf "nil") + (= true v) (push-str buf "true") + (= false v) (push-str buf "false") + (number? v) (push-str buf (string v)) + (string? v) (push-str buf v) + (keyword? v) (do (push-str buf ":") (push-str buf (string v))) + (and (struct? v) (= :jolt/char (get v :jolt/type))) + (do (push-str buf "\\") + (push-str buf (case (v :ch) + 10 "newline" 32 "space" 9 "tab" 13 "return" + 12 "formfeed" 8 "backspace" 0 "nul" + (string/from-bytes (v :ch))))) + (and (struct? v) (= :symbol (get v :jolt/type))) + (let [ns (get v :ns) name (get v :name)] + (if ns + (push-str buf (string ns "/" name)) + (push-str buf name))) + (and (table? v) (= :jolt/var (v :jolt/type))) + (push-str buf (string "#'" (ctx-current-ns ctx) "/" (var-name v))) + (or (tuple? v) (array? v) (struct? v) (table? v)) + (write-collection v buf) + true (push-str buf (string v))))) + +(defn print-value [v] + (def buf @"") + (write-value v buf) + (print (string buf))) + +(defn- err-message [err] + (cond + (string? err) err + (and (or (table? err) (struct? err)) (= :jolt/exception (get err :jolt/type))) + (err-message (get err :value)) + (and (or (table? err) (struct? err)) (= :jolt/ex-info (get err :jolt/type))) + (let [m (get err :message) d (get err :data)] + (if (and d (not (empty? d))) (string m " " (string/format "%q" d)) (string m))) + (string? err) err + (string/format "%q" err))) + +(defn- report-error [err fib] + (eprint "Error: " (err-message err)) + # Janet-level stack trace of where evaluation failed + (when fib (debug/stacktrace fib ""))) + +(defn- run-repl [] + (print "Jolt — Clojure on Janet") + (print "Type (exit) to quit.\n") + (var running true) + (var pending "") # accumulates a form split across multiple input lines + (while running + (let [prompt (if (= pending "") (string (ctx-current-ns ctx) "=> ") " #_=> ") + line (read-line prompt)] + (cond + (nil? line) (set running false) + (let [input (if (= pending "") line (string pending "\n" line)) + trimmed (string/trim input)] + (cond + (= trimmed "(exit)") (set running false) + (= trimmed "") (set pending "") + # Try to parse the accumulated input; if it's an incomplete form + # (unterminated list/vector/map/string), keep reading more lines. + (let [parsed (protect (parse-string input))] + (if (and (= (parsed 0) false) + (string/find "nterminated" (string (parsed 1)))) + (set pending input) + (do + (set pending "") + (try + (print-value (eval-string ctx input)) + ([err fib] (report-error err fib)))))))))))) + +(defn- set-command-line-args [argv] + # bind clojure.core/*command-line-args* to a vector of the remaining args + (ns-intern (ctx-find-ns ctx "clojure.core") "*command-line-args*" + (tuple/slice (tuple ;argv)))) + +(defn- run-file [path argv] + (set-command-line-args argv) + (ns-intern (ctx-find-ns ctx "clojure.core") "*file*" path) + (if (not (os/stat path)) + (do (eprint "Error: file not found: " path) (os/exit 1)) + (let [src (slurp path)] + (try + (load-string ctx src) + ([err fib] (report-error err fib) (os/exit 1)))))) + +(defn- run-eval [expr argv] + (set-command-line-args argv) + (try + (let [v (load-string ctx expr)] + (when (not (nil? v)) (print-value v))) + ([err fib] (report-error err fib) (os/exit 1)))) + +(defn- ensure-nrepl-loaded [] + # jolt.nrepl is part of the baked-in stdlib, so require finds it anywhere. + (eval-string ctx "(require '[jolt.nrepl])")) + +(defn- run-nrepl [argv] + # addr is [host:]port; bare number is a port. Default 127.0.0.1:7888. + (def addr (get argv 0)) + (var host "127.0.0.1") + (var port 7888) + (when addr + (if-let [i (string/find ":" addr)] + (do (when (> i 0) (set host (string/slice addr 0 i))) + (set port (scan-number (string/slice addr (+ i 1))))) + (set port (scan-number addr)))) + (ensure-nrepl-loaded) + (eval-string ctx (string "(jolt.nrepl/start-server! {:host \"" host "\" :port " port "})")) + # Editors auto-discover the port from this file (nREPL convention). + (spit ".nrepl-port" (string port)) + # Remove .nrepl-port on exit — on a clean unwind (defer) and on Ctrl-C/SIGTERM + # (signal handlers). A hard SIGKILL can't be caught, so it may still be left. + (def cleanup (fn [&] (protect (os/rm ".nrepl-port")))) + (os/sigaction :int (fn [&] (cleanup) (os/exit 0)) true) + (os/sigaction :term (fn [&] (cleanup) (os/exit 0)) true) + (print "Jolt nREPL server started on " host ":" port) + (print "Wrote .nrepl-port — connect your editor; Ctrl-C to stop.") + (flush) + # Keep the main fiber alive so the event loop serves connections. + (defer (cleanup) + (forever (ev/sleep 60)))) + +(defn- print-version [] + (print "jolt v" jolt-version)) + +(defn- run-main [ns-name argv] + (when (nil? ns-name) (eprint "Error: -m/--main requires a namespace") (os/exit 1)) + (set-command-line-args argv) + (try + (do + (load-string ctx (string "(require '[" ns-name "])")) + (load-string ctx (string "(apply " ns-name "/-main *command-line-args*)"))) + ([err fib] (report-error err fib) (os/exit 1)))) + +(defn- run-uberscript [out main-ns] + # Bundle main-ns and everything it requires (from JOLT_PATH roots) into one + # .clj that runs on a plain jolt — no deps, no jpm. We require the entry and + # collect the load order the loader records (deps before dependents). + (when (or (nil? out) (nil? main-ns)) + (eprint "Usage: jolt uberscript OUT.clj -m NS") (os/exit 1)) + (put (ctx :env) :loaded-files @[]) + (try + (load-string ctx (string "(require '[" main-ns "])")) + ([err fib] (report-error err fib) (os/exit 1))) + (def seen @{}) + (def files @[]) + (each f (get (ctx :env) :loaded-files) + (unless (get seen f) (put seen f true) (array/push files f))) + (def buf @"") + (buffer/push-string buf (string ";; Generated by `jolt uberscript` — " (length files) " namespace(s)\n\n")) + (each f files + (buffer/push-string buf (string ";; --- " f " ---\n")) + (buffer/push-string buf (slurp f)) + (buffer/push-string buf "\n")) + (buffer/push-string buf (string "\n(apply " main-ns "/-main *command-line-args*)\n")) + (spit out (string buf)) + (print "Wrote " out " (" (length files) " namespace(s))")) + +(defn- print-help [] + (print "Jolt — a Clojure interpreter on Janet\n") + (print "Usage: jolt [opt] [args]\n") + (print " (no args), repl Start a REPL") + (print " FILE [args] Run a Clojure file (binds *command-line-args*, *file*)") + (print " - Run a program read from stdin") + (print " -e, --eval EXPR Evaluate EXPR and print the result") + (print " -f, --file FILE Run a Clojure file") + (print " -m, --main NS [args] Require NS and call its -main with the remaining args") + (print " nrepl-server [addr] Start an nREPL server (addr = [host:]port, default 7888)") + (print " (aliases: --nrepl-server, nrepl)") + (print " uberscript OUT -m NS Bundle NS + its required namespaces into one .clj") + (print " --version, version Print the Jolt version") + (print " -h, --help, help Show this help\n") + (print "Dependencies (deps.edn) are handled by the separate jolt-deps tool.")) + +(def- help-flags {"-h" true "--help" true "help" true "-?" true}) +(def- version-flags {"--version" true "version" true}) +(def- nrepl-flags {"nrepl-server" true "--nrepl-server" true "nrepl" true}) +(def- eval-flags {"-e" true "--eval" true}) +(def- file-flags {"-f" true "--file" true}) +(def- main-flags {"-m" true "--main" true}) + +(defn main [&] + (def args (or (dyn :args) @[])) # @["jolt" arg1 arg2 ...] + (def argv (if (> (length args) 1) (array/slice args 1) @[])) + (ctx-set-current-ns ctx "user") + # JOLT_PATH must be applied at runtime: this `ctx` is built into the image at + # build time, so its source-paths can't capture the runtime environment. + # `jolt-deps` sets JOLT_PATH to the resolved deps.edn source roots. + (when-let [jp (os/getenv "JOLT_PATH")] + (each p (string/split ":" jp) + (when (> (length p) 0) (array/push (get (ctx :env) :source-paths) p)))) + (cond + (empty? argv) (run-repl) + (help-flags (argv 0)) (print-help) + (version-flags (argv 0)) (print-version) + (= (argv 0) "repl") (run-repl) + (nrepl-flags (argv 0)) (run-nrepl (array/slice argv 1)) + (eval-flags (argv 0)) (run-eval (get argv 1 "") (array/slice argv 2)) + (file-flags (argv 0)) (run-file (get argv 1) (array/slice argv 2)) + (main-flags (argv 0)) (run-main (get argv 1) (array/slice argv 2)) + (= (argv 0) "uberscript") + (let [out (get argv 1) + rest (array/slice argv 2) + mi (or (index-of "-m" rest) (index-of "--main" rest))] + (run-uberscript out (if mi (get rest (+ mi 1)) nil))) + (= (argv 0) "-") (run-file "/dev/stdin" (array/slice argv 1)) + (run-file (argv 0) (array/slice argv 1)))) diff --git a/src/jolt/phm.janet b/src/jolt/phm.janet new file mode 100644 index 0000000..886f4a6 --- /dev/null +++ b/src/jolt/phm.janet @@ -0,0 +1,256 @@ +# PersistentHashMap implementation for Jolt +# Bucket-based hash map with copy-on-write semantics. + +(def- bucket-count 8) + +(defn phm? [x] + (and (table? x) + (= "jolt.lang.persistent-hash-map.PersistentHashMap" (x :jolt/deftype)))) + +# Keys are hashed and compared by VALUE. Scalars (keywords/strings/numbers) are +# value-hashable in Janet already, but collection keys (a phm/pvec/plist map or +# vector) are Janet tables hashed by identity — so they're canonicalized to a +# value-hashable struct/tuple first. `canonicalize-key` is injected by core (which +# knows the pvec/plist/phm types); phm stays dependency-free. Keys are still +# *stored* as-is, so retrieval and iteration return the original key objects. +(var canonicalize-key nil) +(defn set-canonicalize-key! + "Install the value-canonicalizer for collection keys (called by core)." + [f] + (set canonicalize-key f)) +(defn- ck [k] + (if (and canonicalize-key (or (table? k) (struct? k) (array? k) (tuple? k))) + (canonicalize-key k) + k)) +(defn canon + "Public canonicalizer: maps a key to its value-hashable form (identity for + scalars). Used by callers that index the same canonicalized tables phm uses + (e.g. transient maps/sets)." + [k] (ck k)) +(defn- key= [a b] (= (ck a) (ck b))) + +(defn phm-hash-key [k] + (if (nil? k) 0 (mod (hash (ck k)) bucket-count))) + +(defn- phm-bucket-find [bucket k] + (var i 0) (var n (length bucket)) (var found nil) + (while (< i n) + (if (key= k (in bucket i)) (do (set found (in bucket (+ i 1))) (break))) + (+= i 2)) + found) + +(defn phm-bucket-contains? [bucket k] + (var i 0) (var n (length bucket)) (var found false) + (while (< i n) + (if (key= k (in bucket i)) (do (set found true) (break))) + (+= i 2)) + found) + +(defn- phm-bucket-assoc [bucket k v] + (var i 0) (var n (length bucket)) (var found-i nil) + (while (< i n) + (if (key= k (in bucket i)) (do (set found-i i) (break))) + (+= i 2)) + (if (not (nil? found-i)) + (let [nb @[]] (var j 0) + (while (< j n) (array/push nb (if (= j (+ found-i 1)) v (in bucket j))) (++ j)) nb) + (let [nb @[]] (var j 0) + (while (< j n) (array/push nb (in bucket j)) (++ j)) + (array/push nb k) (array/push nb v) nb))) + +(defn- phm-bucket-dissoc [bucket k] + (var i 0) (var n (length bucket)) (var found-i nil) + (while (< i n) + (if (key= k (in bucket i)) (do (set found-i i) (break))) + (+= i 2)) + (if (nil? found-i) bucket + (if (= n 2) nil + (let [nb @[]] (var j 0) + (while (< j found-i) (array/push nb (in bucket j)) (++ j)) + (while (< j (- n 2)) (array/push nb (in bucket (+ j 2))) (++ j)) nb)))) + +(defn phm-get [m k &opt default] + (default default nil) + (let [bucket (get (m :buckets) (phm-hash-key k))] + # presence-check, not nil-of-value: a key mapped to nil is still present, + # so return nil (not the default) when the key exists with a nil value. + (if (and bucket (phm-bucket-contains? bucket k)) + (phm-bucket-find bucket k) + default))) + +(defn phm-assoc [m k v] + (let [cnt (m :cnt) idx (phm-hash-key k) + old-bucket (get (m :buckets) idx) + had-key (if old-bucket (phm-bucket-contains? old-bucket k) false) + new-bucket (phm-bucket-assoc (if old-bucket old-bucket @[]) k v) + new-cnt (if had-key cnt (+ cnt 1)) + new-buckets (array/new bucket-count)] + (var bi 0) + (while (< bi bucket-count) + (put new-buckets bi (if (= bi idx) new-bucket (get (m :buckets) bi))) (++ bi)) + @{:jolt/deftype "jolt.lang.persistent-hash-map.PersistentHashMap" + :cnt new-cnt :buckets new-buckets :_meta (m :_meta)})) + +(defn phm-dissoc [m k] + (let [idx (phm-hash-key k) old-bucket (get (m :buckets) idx)] + (if old-bucket + (let [new-bucket (phm-bucket-dissoc old-bucket k)] + (if (= new-bucket old-bucket) m + (let [new-cnt (- (m :cnt) 1) new-buckets (array/new bucket-count)] + (var bi 0) + (while (< bi bucket-count) + (put new-buckets bi (if (= bi idx) new-bucket (get (m :buckets) bi))) (++ bi)) + @{:jolt/deftype "jolt.lang.persistent-hash-map.PersistentHashMap" + :cnt new-cnt :buckets new-buckets :_meta (m :_meta)}))) + m))) + +(defn phm-entries [m] + (var result @[]) (var bi 0) + (while (< bi bucket-count) + (let [bucket (get (m :buckets) bi)] + (when bucket + (var i 0) (var n (length bucket)) + (while (< i n) (array/push result [(in bucket i) (in bucket (+ i 1))]) (+= i 2)))) + (++ bi)) + result) + +(defn phm-to-struct [m] + (var result @{}) (var bi 0) + (while (< bi bucket-count) + (let [bucket (get (m :buckets) bi)] + (when bucket + (var i 0) (var n (length bucket)) + (while (< i n) (put result (in bucket i) (in bucket (+ i 1))) (+= i 2)))) + (++ bi)) + (table/to-struct result)) + +(defn phm-count [m] (m :cnt)) + +(defn phm-contains? [m k] + (let [bucket (get (m :buckets) (phm-hash-key k))] + (if bucket (phm-bucket-contains? bucket k) false))) + +(defn make-phm [&opt kvs] + (default kvs nil) + (var m @{:jolt/deftype "jolt.lang.persistent-hash-map.PersistentHashMap" + :cnt 0 :buckets (array/new bucket-count) :_meta nil}) + (when kvs + (var i 0) (var n (length kvs)) + (while (< i n) (set m (phm-assoc m (kvs i) (kvs (+ i 1)))) (+= i 2))) + m) + +# ============================================================ +# LazySeq — cell-by-cell lazy sequence (Clojure-compatible) +# ============================================================ +# Model: thunk returns nil (empty) or [first-val, rest-thunk] pair. +# Each step produces one element + thunk for the rest. +# Supports self-referencing sequences like fib-seq. + +(defn lazy-seq? + "Check if x is a LazySeq." + [x] + (and (table? x) (= :jolt/lazy-seq (x :jolt/type)))) + +(defn make-lazy-seq [thunk] + @{:jolt/type :jolt/lazy-seq :fn thunk :realized false :val nil}) + +(defn realize-ls + "Force a LazySeq cell. Returns nil (empty) or [first-val, rest-thunk]. + If the thunk returns another lazy-seq, recursively realize it. + Uses :jolt/pending sentinel to detect self-referencing cycles." + [ls] + (if (get ls :realized) + (ls :val) + (do + (put ls :val :jolt/pending) + (put ls :realized true) + (let [raw ((ls :fn)) + v (if (lazy-seq? raw) (realize-ls raw) raw)] + (put ls :val v) + v)))) + +(defn ls-first [ls] + (let [cell (realize-ls ls)] + (if (or (nil? cell) (= :jolt/pending cell) (= 0 (length cell))) nil (in cell 0)))) + +(defn ls-rest [ls] + (let [cell (realize-ls ls)] + (if (or (nil? cell) (= 0 (length cell))) nil + (let [rt (in cell 1)] + (if (nil? rt) nil (make-lazy-seq rt)))))) + +(defn ls-seq [ls] + (var result @[]) + (var cur ls) + (while (not (nil? cur)) + (let [cell (realize-ls cur)] + (if (nil? cell) (break)) + (array/push result (in cell 0)) + (let [rt (in cell 1)] + (set cur (if (nil? rt) nil (make-lazy-seq rt)))))) + (if (= 0 (length result)) nil result)) + +(defn ls-count [ls] + (var cnt 0) + (var cur ls) + (while (not (nil? cur)) + (let [cell (realize-ls cur)] + (if (nil? cell) (break)) + (++ cnt) + (let [rt (in cell 1)] + (set cur (if (nil? rt) nil (make-lazy-seq rt)))))) + cnt) + +# ============================================================ +# Lazy combinator — primitive for building lazy sequences +# ============================================================ + +(defn lazy-cons + "Returns a LazySeq whose first element is x and whose rest is produced + by rest-thunk (a 0-arg function returning nil or a LazySeq)." + [x rest-thunk] + (make-lazy-seq (fn [] @[x rest-thunk]))) + +# ============================================================ +# PersistentHashSet — backed by PersistentHashMap +# ============================================================ + +(defn set? + "Check if x is a PersistentHashSet." + [x] + (and (table? x) (= :jolt/set (x :jolt/type)))) + +(defn make-phs [& xs] + "Create a PersistentHashSet from items." + (var m (make-phm)) + (each x xs (set m (phm-assoc m x true))) + @{:jolt/type :jolt/set :phm m :cnt (phm-count m)}) + +(defn phs-conj [s & xs] + (var m (s :phm)) + (each x xs (set m (phm-assoc m x true))) + @{:jolt/type :jolt/set :phm m :cnt (phm-count m)}) + +(defn phs-disj [s & xs] + (var m (s :phm)) + (each x xs (set m (phm-dissoc m x))) + @{:jolt/type :jolt/set :phm m :cnt (phm-count m)}) + +(defn phs-contains? [s x] + (phm-contains? (s :phm) x)) + +(defn phs-count [s] + (s :cnt)) + +(defn phs-empty? [s] + (= 0 (s :cnt))) + +(defn phs-seq [s] + (tuple ;(keys (phm-to-struct (s :phm))))) + +(defn phs-get [s x &opt default] + (default default nil) + (if (phm-contains? (s :phm) x) x default)) + +(defn phs-to-struct [s] + (phm-to-struct (s :phm))) diff --git a/src/jolt/plist.janet b/src/jolt/plist.janet new file mode 100644 index 0000000..066c8a2 --- /dev/null +++ b/src/jolt/plist.janet @@ -0,0 +1,73 @@ +# Persistent list — an immutable singly-linked cons cell, modeled on Clojure's +# PersistentList. The whole point is O(1) prepend (conj/cons): a new node simply +# points at the existing list as its tail, sharing all of it, so building a list +# with repeated conj is O(n) total instead of O(n²) array copies. +# +# A node is: +# @{:jolt/type :jolt/plist +# :first x head element +# :rest r tail: another plist, or a Janet array/tuple (a list that +# was conj'd onto), or nil for the empty tail +# :count n} element count, or nil when unknown (cons onto a lazy tail) +# +# `:rest` may be a plain array/tuple so `(conj some-list x)` needn't copy the +# original list — the node just references it. pl->array materializes the chain. + +(defn plist? [x] + (and (table? x) (= :jolt/plist (get x :jolt/type)))) + +(defn- counted + "Count of a tail value if known in O(1), else nil." + [r] + (cond + (nil? r) 0 + (plist? r) (get r :count) + (or (array? r) (tuple? r) (string? r) (buffer? r)) (length r) + nil)) + +(defn pl-cons + "Prepend x onto tail r (a plist / array / tuple / nil). O(1)." + [x r] + (def c (counted r)) + @{:jolt/type :jolt/plist :first x :rest r :count (if c (+ c 1) nil)}) + +(def EMPTY-PLIST @{:jolt/type :jolt/plist :first nil :rest nil :count 0}) + +(defn pl-empty? [p] (= 0 (get p :count))) +(defn pl-first [p] (get p :first)) + +(defn pl->array + "Materialize the cons chain to a fresh Janet array." + [p] + (def out @[]) + (var cur p) + (while (plist? cur) + (if (= 0 (get cur :count)) + (set cur nil) + (do (array/push out (get cur :first)) (set cur (get cur :rest))))) + # cur is now a non-plist tail (array/tuple) or nil + (when (and (not (nil? cur)) (or (array? cur) (tuple? cur))) + (each x cur (array/push out x))) + out) + +(defn pl-count [p] + (def c (get p :count)) + (if (nil? c) (length (pl->array p)) c)) + +(defn pl-rest + "The tail as a seqable (array). Returns an empty array for a one-element list." + [p] + (if (or (= 0 (get p :count)) (nil? (get p :rest))) + @[] + (let [r (get p :rest)] + (if (plist? r) r r)))) + +(defn pl-from-indexed + "Build a plist from a Janet array/tuple, preserving order. O(n)." + [xs] + (var p EMPTY-PLIST) + (var i (- (length xs) 1)) + (while (>= i 0) + (set p (pl-cons (in xs i) p)) + (-- i)) + p) diff --git a/src/jolt/pv.janet b/src/jolt/pv.janet new file mode 100644 index 0000000..8e643ed --- /dev/null +++ b/src/jolt/pv.janet @@ -0,0 +1,159 @@ +# Persistent vector — a 32-way branching trie with a tail buffer, modeled on +# Clojure's PersistentVector. Immutable: every update returns a new vector that +# structurally shares unchanged subtrees with the old one, so conj/assoc/pop are +# O(log32 n) and share memory instead of copying the whole vector. +# +# Layout: +# @{:jolt/type :jolt/pvec +# :cnt n number of elements +# :shift s bits to shift the index for the root level (5 * depth) +# :root node trie root: a tuple of up to 32 children +# :tail tail} a tuple of up to 32 trailing elements (append fast-path) +# +# Trie nodes are immutable tuples so unchanged subtrees are shared by identity. + +(def- bits 5) +(def- width 32) # 2^bits +(def- mask 31) # width - 1 + +(def empty-node []) + +(defn pvec? [x] + (and (table? x) (= :jolt/pvec (get x :jolt/type)))) + +(defn make-pv [cnt shift root tail] + @{:jolt/type :jolt/pvec :cnt cnt :shift shift :root root :tail tail}) + +(def EMPTY (make-pv 0 bits empty-node [])) + +(defn pv-count [pv] (get pv :cnt)) + +# Index of the first element held in the tail (everything before lives in the trie). +(defn- tail-offset [cnt] + (if (< cnt width) 0 (blshift (brshift (- cnt 1) bits) bits))) + +# Return the 32-element leaf array containing index i. +(defn- leaf-for [pv i] + (if (>= i (tail-offset (get pv :cnt))) + (get pv :tail) + (do + (var node (get pv :root)) + (var level (get pv :shift)) + (while (> level 0) + (set node (get node (band (brshift i level) mask))) + (set level (- level bits))) + node))) + +(defn pv-nth [pv i &opt dflt] + (if (and (>= i 0) (< i (get pv :cnt))) + (get (leaf-for pv i) (band i mask)) + dflt)) + +# --- conj ------------------------------------------------------------------- + +# Push the full tail down into the trie, returning a new root node array. +(defn- push-tail [level parent tail cnt] + (def sub-idx (band (brshift (- cnt 1) level) mask)) + (def child + (if (= level bits) + tail + (let [c (get parent sub-idx)] + (if c + (push-tail (- level bits) c tail cnt) + (push-tail (- level bits) empty-node tail cnt))))) + (def arr (array/slice parent)) + (put arr sub-idx child) + (tuple/slice arr)) + +(defn pv-conj [pv val] + (def cnt (get pv :cnt)) + (def tail (get pv :tail)) + (if (< (length tail) width) + # Room in the tail: just append to it. + (make-pv (+ cnt 1) (get pv :shift) + (get pv :root) + (tuple/slice (tuple ;tail val))) + # Tail is full: push it into the trie, start a fresh tail with val. + (let [shift (get pv :shift) + root (get pv :root)] + (if (> (brshift cnt bits) (blshift 1 shift)) + # Root overflow: grow the trie one level taller. + (let [new-root (tuple root (push-tail shift empty-node tail cnt))] + (make-pv (+ cnt 1) (+ shift bits) new-root [val])) + (make-pv (+ cnt 1) shift (push-tail shift root tail cnt) [val]))))) + +# --- assoc ------------------------------------------------------------------ + +(defn- assoc-in-node [level node i val] + (def arr (array/slice node)) + (if (= level 0) + (put arr (band i mask) val) + (let [sub-idx (band (brshift i level) mask)] + (put arr sub-idx (assoc-in-node (- level bits) (get node sub-idx) i val)))) + (tuple/slice arr)) + +(defn pv-assoc [pv i val] + (def cnt (get pv :cnt)) + (cond + (= i cnt) (pv-conj pv val) + (and (>= i 0) (< i cnt)) + (if (>= i (tail-offset cnt)) + (let [tail (array/slice (get pv :tail))] + (put tail (band i mask) val) + (make-pv cnt (get pv :shift) (get pv :root) (tuple/slice tail))) + (make-pv cnt (get pv :shift) + (assoc-in-node (get pv :shift) (get pv :root) i val) + (get pv :tail))) + (error (string "Index " i " out of bounds for vector of length " cnt)))) + +# --- pop -------------------------------------------------------------------- + +(defn- pop-tail [level node cnt] + (def sub-idx (band (brshift (- cnt 2) level) mask)) + (cond + (> level bits) + (let [child (pop-tail (- level bits) (get node sub-idx) cnt)] + (if (and (nil? child) (= sub-idx 0)) + nil + (let [arr (array/slice node)] (put arr sub-idx child) (tuple/slice arr)))) + (= sub-idx 0) nil + (let [arr (array/slice node)] (put arr sub-idx nil) (tuple/slice arr)))) + +(defn pv-pop [pv] + (def cnt (get pv :cnt)) + (cond + (= cnt 0) (error "Can't pop empty vector") + (= cnt 1) EMPTY + (> (- cnt (tail-offset cnt)) 1) + # More than one element in the tail: drop the last tail element. + (let [tail (get pv :tail)] + (make-pv (- cnt 1) (get pv :shift) (get pv :root) + (tuple/slice tail 0 (- (length tail) 1)))) + # Tail has one element: the new tail is the last leaf of the trie. + (let [shift (get pv :shift) + new-tail (leaf-for pv (- cnt 2)) + new-root-raw (pop-tail shift (get pv :root) cnt) + new-root (if (nil? new-root-raw) empty-node new-root-raw)] + (if (and (> shift bits) (nil? (get new-root 1))) + # Trie lost a level: promote the single remaining child to root. + (make-pv (- cnt 1) (- shift bits) (get new-root 0) new-tail) + (make-pv (- cnt 1) shift new-root new-tail))))) + +# --- conversions ------------------------------------------------------------ + +(defn pv->array [pv] + (def out @[]) + (def cnt (get pv :cnt)) + (var i 0) + (while (< i cnt) + (array/push out (pv-nth pv i)) + (++ i)) + out) + +(defn pv-from-indexed [xs] + # Build a pvec from any Janet-indexed collection (tuple/array). + (var pv EMPTY) + (def n (length xs)) + (var i 0) + (while (< i n) (set pv (pv-conj pv (in xs i))) (++ i)) + pv) diff --git a/src/jolt/reader.janet b/src/jolt/reader.janet new file mode 100644 index 0000000..64232a6 --- /dev/null +++ b/src/jolt/reader.janet @@ -0,0 +1,604 @@ +# Jolt Clojure Reader +# Recursive descent parser for Clojure source text. +# Output convention: +# Symbols foo, foo/bar → {:jolt/type :symbol :ns "foo" :name "bar"} +# Keywords :foo, :foo/bar → Janet keyword :foo, :foo/bar +# Lists (a b c) → Janet array @[a b c] +# Vectors [a b c] → Janet tuple [a b c] +# Maps {:a 1} → Janet struct {:a 1} +# Sets #{1 2} → tagged struct {:jolt/type :jolt/set :value [1 2]} + +(use ./types) +(import ./phm :as phm) + +# Forward declaration for mutual recursion +(var read-form nil) + +(def whitespace-chars " \t\n\r,") + +(defn whitespace? [c] + (or (= c 32) # space + (= c 10) # \n + (= c 9) # \t + (= c 13) # \r + (= c 44))) # comma + +(defn skip-whitespace [s pos] + (if (and (< pos (length s)) + (whitespace? (s pos))) + (skip-whitespace s (+ pos 1)) + pos)) + +(defn digit? [c] + (and (>= c 48) (<= c 57))) + +(defn hex-digit? [c] + (or (and (>= c 48) (<= c 57)) + (and (>= c 65) (<= c 70)) + (and (>= c 97) (<= c 102)))) + +(defn symbol-start? [c] + (or (and (>= c 65) (<= c 90)) # A-Z + (and (>= c 97) (<= c 122)) # a-z + (= c 42) # * + (= c 43) # + + (= c 33) # ! + (= c 95) # _ + (= c 45) # - + (= c 63) # ? + (= c 46) # . + (= c 60) # < + (= c 62) # > + (= c 61) # = + (= c 38) # & + (= c 124) # | + (= c 36) # $ + (= c 37) # % + (= c 47))) # / + +(defn symbol-char? [c] + (or (symbol-start? c) + (digit? c) + (= c 35) # # + (= c 39) # ' + (= c 58))) # : + +(defn read-symbol-name [s pos end] + (if (and (< end (length s)) + (symbol-char? (s end))) + (read-symbol-name s pos (+ end 1)) + end)) + +(defn make-symbol + "Create a Jolt symbol struct." + [name] + (let [slash (string/find "/" name)] + (if (and slash (> slash 0)) + {:jolt/type :symbol + :ns (string/slice name 0 slash) + :name (string/slice name (+ slash 1))} + {:jolt/type :symbol + :ns nil + :name name}))) + +(defn sym + "Convenience to create a symbol during testing." + [name] + (make-symbol name)) + +(defn read-symbol [s pos] + (let [end (read-symbol-name s pos pos)] + (if (= end pos) + (error (string "Unrecognized character at " pos ": " (string/from-bytes (s pos)))) + (let [name (string/slice s pos end)] + (if (= name "nil") [nil end] + (if (= name "true") [true end] + (if (= name "false") [false end] + [(make-symbol name) end]))))))) + +(defn read-keyword-name [s pos end] + (if (and (< end (length s)) + (symbol-char? (s end))) + (read-keyword-name s pos (+ end 1)) + end)) + +(defn read-keyword [s pos] + # pos is at the first colon + (if (and (< (+ pos 1) (length s)) (= (s (+ pos 1)) 58)) + # ::foo/bar — auto-resolved keyword + (let [start (+ pos 2) + end (read-keyword-name s start start) + name (string/slice s start end)] + [(keyword name) end]) + # :foo or :foo/bar + (let [start (+ pos 1) + end (read-keyword-name s start start) + name (string/slice s start end)] + [(keyword name) end]))) + +(defn escape-char [c] + (if (= c 110) "\n" + (if (= c 116) "\t" + (if (= c 114) "\r" + (if (= c 92) "\\" + (if (= c 34) "\"" + (string/from-bytes c))))))) + +(defn read-string-chars [s pos end chars] + (if (>= pos end) + (error "Unterminated string") + (let [c (s pos)] + (if (= c 92) # backslash + (let [next-pos (+ pos 1)] + (if (>= next-pos end) + (error "Unterminated escape") + (read-string-chars s (+ pos 2) end + (array/push chars (escape-char (s next-pos)))))) + (if (= c 34) # closing quote + [pos chars] + (read-string-chars s (+ pos 1) end + (array/push chars (string/from-bytes c)))))))) + +(defn read-string [s pos] + # pos is at opening double-quote + (let [end (length s) + [new-pos chars] (read-string-chars s (+ pos 1) end @[])] + [(string/join chars "") (+ new-pos 1)])) + +(defn read-hex-digits [s pos end] + (if (and (< end (length s)) (hex-digit? (s end))) + (read-hex-digits s pos (+ end 1)) + end)) + +(defn read-digits [s pos end] + (if (and (< end (length s)) (digit? (s end))) + (read-digits s pos (+ end 1)) + end)) + +(defn read-fractional [s pos end] + (if (and (< end (length s)) (digit? (s end))) + (read-fractional s pos (+ end 1)) + end)) + +# Value of an alphanumeric digit for radix parsing (0-9, a-z/A-Z = 10-35). +(defn- radix-digit-val [c] + (cond + (and (>= c 48) (<= c 57)) (- c 48) # 0-9 + (and (>= c 97) (<= c 122)) (+ 10 (- c 97)) # a-z + (and (>= c 65) (<= c 90)) (+ 10 (- c 65)) # A-Z + nil)) +(defn- read-alnum [s pos end] + (if (and (< end (length s)) (not (nil? (radix-digit-val (s end))))) + (read-alnum s pos (+ end 1)) + end)) +(defn- read-exponent + "If s[end] is e/E (optionally with sign) followed by digits, return the index + past the exponent; else end." + [s end] + (let [len (length s)] + (if (and (< end len) (or (= (s end) 101) (= (s end) 69))) # e / E + (let [p (if (and (< (+ end 1) len) (or (= (s (+ end 1)) 43) (= (s (+ end 1)) 45))) (+ end 2) (+ end 1)) + de (read-digits s p p)] + (if (> de p) de end)) + end))) + +# Jolt has no true bignum/ratio types (see README): an integer/float literal +# suffixed N (bigint) or M (bigdec) reads as the plain number, a ratio a/b reads +# as the double quotient, and radixed integers (2r101, 16rFF) are parsed by base. +(defn read-number [s pos] + (var start pos) # start is mutable for sign handling + (var neg false) + (def len (length s)) + # optional sign + (if (and (< pos len) (= (s pos) 45)) + (do (set start (+ pos 1)) (set neg true))) + + (let [pos start + hex? (and (< (+ pos 1) len) + (= (s pos) 48) (or (= (s (+ pos 1)) 120) (= (s (+ pos 1)) 88)))] # 0x / 0X + (if hex? + (let [hs (+ pos 2) he (read-hex-digits s hs hs)] + (if (= he hs) (error (string "Expected hex digits at " pos))) + (let [he2 (if (and (< he len) (= (s he) 78)) (+ he 1) he) # trailing N + val (scan-number (string "0x" (string/slice s hs he)))] + [(if neg (- val) val) he2])) + (let [iend (read-digits s pos pos)] + (if (= iend pos) (error (string "Expected number at " pos))) + (cond + # radix integer: r, e.g. 2r1010, 16rFF, 36rZ + (and (< iend len) (or (= (s iend) 114) (= (s iend) 82))) + (let [base (scan-number (string/slice s pos iend)) + ds (+ iend 1) + de (read-alnum s ds ds)] + (if (= de ds) (error (string "Expected radix digits at " ds))) + (var acc 0) + (var i ds) + (while (< i de) (set acc (+ (* acc base) (radix-digit-val (s i)))) (++ i)) + [(if neg (- acc) acc) de]) + # ratio: / (only when a digit follows the slash) + (and (< (+ iend 1) len) (= (s iend) 47) (digit? (s (+ iend 1)))) + (let [ds (+ iend 1) de (read-digits s ds ds) + numr (scan-number (string/slice s pos iend)) + den (scan-number (string/slice s ds de))] + [(if neg (- (/ numr den)) (/ numr den)) de]) + # fractional and/or exponent, optional trailing N/M + (let [frac-end (if (and (< iend len) (= (s iend) 46)) + (let [fs (+ iend 1) fe (read-fractional s fs fs)] + (if (= fe fs) (error "Expected digit after .")) fe) + iend) + exp-end (read-exponent s frac-end) + val (scan-number (string/slice s start exp-end)) + # consume a trailing N (bigint) or M (bigdec) suffix + fin (if (and (< exp-end len) (or (= (s exp-end) 78) (= (s exp-end) 77))) + (+ exp-end 1) exp-end)] + [(if neg (- val) val) fin])))))) + +(defn read-list [s pos] + # pos is at opening paren + (defn read-list-items [s pos items] + (let [pos (skip-whitespace s pos)] + (if (>= pos (length s)) + (error "Unterminated list")) + (if (= (s pos) 41) # ) + [items (+ pos 1)] + (let [[form new-pos] (read-form s pos)] + # skip #_ discarded forms + (if (and (struct? form) (= :jolt/skip (form :jolt/type))) + (read-list-items s new-pos items) + # splice #?@ items into the list + (if (and (struct? form) (= :jolt/splice (form :jolt/type))) + (read-list-items s new-pos (array/concat items (form :items))) + (read-list-items s new-pos (array/push items form)))))))) + (read-list-items s (+ pos 1) @[])) + +(defn read-vector [s pos] + # pos is at opening bracket + (defn read-vec-items [s pos items] + (let [pos (skip-whitespace s pos)] + (if (>= pos (length s)) + (error "Unterminated vector")) + (if (= (s pos) 93) # ] + [(tuple/slice (tuple ;items)) (+ pos 1)] + (let [[form new-pos] (read-form s pos)] + (if (and (struct? form) (= :jolt/skip (form :jolt/type))) + (read-vec-items s new-pos items) + (if (and (struct? form) (= :jolt/splice (form :jolt/type))) + (read-vec-items s new-pos (array/concat items (form :items))) + (read-vec-items s new-pos (array/push items form)))))))) + (read-vec-items s (+ pos 1) @[])) + +# A map-literal form. Janet structs drop nil keys/values, so when a key or value +# is nil (e.g. {:a nil}) build a phm — it preserves nil, matching Clojure. The +# common nil-free case stays a struct: fast, and what the downstream map-form +# handling (evaluator/analyzer) already expects. Collection keys are left to +# eval-time construction (build-map-literal/eval-form), which phm-ifies them. +(defn- reader-map [kvs] + (var has-nil false) (var i 0) + (while (< i (length kvs)) (when (nil? (in kvs i)) (set has-nil true) (break)) (++ i)) + (if has-nil (phm/make-phm kvs) (struct ;kvs))) + +(defn read-map [s pos] + # pos is at opening brace + (defn read-kvs [s pos kvs] + (let [pos (skip-whitespace s pos)] + (if (>= pos (length s)) + (error "Unterminated map")) + (if (= (s pos) 125) # } + [(reader-map kvs) (+ pos 1)] + (let [[key new-pos] (read-form s pos)] + (if (and (struct? key) (= :jolt/skip (key :jolt/type))) + (read-kvs s new-pos kvs) + (if (and (struct? key) (= :jolt/splice (key :jolt/type))) + (read-kvs s new-pos (array/concat kvs (key :items))) + (let [pos (skip-whitespace s new-pos) + [val new-pos2] (read-form s pos)] + (if (and (struct? val) (= :jolt/skip (val :jolt/type))) + (read-kvs s new-pos2 kvs) + (if (and (struct? val) (= :jolt/splice (val :jolt/type))) + # Only push key if splice contributes items + (if (> (length (val :items)) 0) + (do (array/push kvs key) (read-kvs s new-pos2 (array/concat kvs (val :items)))) + (read-kvs s new-pos2 kvs)) + (read-kvs s new-pos2 (-> kvs (array/push key) (array/push val)))))))))))) + (read-kvs s (+ pos 1) @[])) + +(defn read-set [s pos] + # pos is at #, next char is { + (defn read-set-items [s pos items] + (let [pos (skip-whitespace s pos)] + (if (>= pos (length s)) + (error "Unterminated set")) + (if (= (s pos) 125) # } + [{:jolt/type :jolt/set :value (tuple/slice (tuple ;items))} (+ pos 1)] + (let [[form new-pos] (read-form s pos)] + (if (and (struct? form) (= :jolt/skip (form :jolt/type))) + (read-set-items s new-pos items) + (if (and (struct? form) (= :jolt/splice (form :jolt/type))) + (read-set-items s new-pos (array/concat items (form :items))) + (read-set-items s new-pos (array/push items form)))))))) + (read-set-items s (+ pos 2) @[])) + +(defn read-char-name-end [s pos] + (if (and (< pos (length s)) (symbol-char? (s pos))) + (read-char-name-end s (+ pos 1)) + pos)) + +(defn read-char [s pos] + # pos is at backslash; produce a char value directly (self-evaluating) + (when (>= (+ pos 1) (length s)) + (error "unexpected end of input after \\")) + (let [end (read-char-name-end s (+ pos 1))] + (if (= end (+ pos 1)) + # The char right after \ isn't a symbol char (e.g. \{ \( \, \% \" ): it's a + # one-character literal of that character itself. + [(make-char (s (+ pos 1))) (+ pos 2)] + (let [char-name (string/slice s (+ pos 1) end)] + [(char-from-name char-name) end])))) + +(defn read-anon-fn [s pos] + # pos is at #, next char is ( + (let [[form new-pos] (read-form s (+ pos 1))] + # Positional index of a %-symbol name: % and %1 are both 1, %N is N, %& is the + # rest param (:rest); anything else is not a positional (nil). The fixed arity + # is the MAX index used (Clojure semantics: #(do %2 %&) -> [p1 p2 & rest], so + # unused lower positions still get a placeholder param and %& starts after %2). + (defn- pct-index [nm] + (cond + (= nm "%") 1 + (= nm "%&") :rest + (and (> (length nm) 1) (= "%" (string/slice nm 0 1))) + (let [n (scan-number (string/slice nm 1))] + (if (and n (= n (math/floor n)) (>= n 1)) n nil)) + nil)) + # Pass 1: max positional index + whether %& is used. + (var max-n 0) + (var has-rest false) + (defn- scan-pct [f] + (cond + (and (struct? f) (= :symbol (f :jolt/type))) + (let [i (pct-index (f :name))] + (cond (= i :rest) (set has-rest true) + (and i (> i max-n)) (set max-n i))) + (or (array? f) (tuple? f)) (each x f (scan-pct x)) + nil)) + (scan-pct form) + # One canonical gensym per slot 1..max-n (placeholders for unused), plus rest. + (def slot-syms @{}) + (var i 1) + (while (<= i max-n) (put slot-syms i (sym (string (gensym)))) (++ i)) + (def rest-sym (if has-rest (sym (string (gensym))) nil)) + # Pass 2: replace each %-symbol with its slot's gensym. + (defn- replace-pct [f] + (cond + (and (struct? f) (= :symbol (f :jolt/type))) + (let [idx (pct-index (f :name))] + (cond (= idx :rest) rest-sym + idx (get slot-syms idx) + f)) + (array? f) (array ;(map replace-pct f)) + (tuple? f) (tuple ;(map replace-pct f)) + f)) + (def replaced (replace-pct form)) + (def arg-names @[]) + (set i 1) + (while (<= i max-n) (array/push arg-names (get slot-syms i)) (++ i)) + (when has-rest + (array/push arg-names (sym "&")) + (array/push arg-names rest-sym)) + [@[(sym "fn*") (tuple ;arg-names) replaced] new-pos])) + +(defn read-reader-conditional [s pos] + # pos is at #, next char is ? or ?@ + (def splice? (and (< (+ pos 2) (length s)) (= (s (+ pos 2)) 64))) # @ = 64 + (def form-start (if splice? (+ pos 3) (+ pos 2))) + (let [[form new-pos] (read-form s form-start)] + (if (array? form) + (do + (var result nil) + (var i 0) + (while (< i (length form)) + (if (= (in form i) :clj) + (do + (set result (in form (+ i 1))) + (set i (length form))) + (++ i))) + # Fallback to :default if :clj not matched + (when (nil? result) + (set i 0) + (while (< i (length form)) + (if (= (in form i) :default) + (do + (set result (in form (+ i 1))) + (set i (length form))) + (++ i)))) + (if splice? + # #?@ splicing: resolve :clj branch, wrap for splice + (let [items (if (nil? result) + @[] + (if (or (array? result) (tuple? result)) + result + @[result]))] + [{:jolt/type :jolt/splice :items items} new-pos]) + # #? non-splicing: skip nil results (from :cljs branches on CLJ) + (if (nil? result) + [{:jolt/type :jolt/skip} new-pos] + [result new-pos]))) + [{:jolt/type :jolt/reader-conditional :clauses form} new-pos]))) + +(defn read-var-quote [s pos] + # pos is at #, next char is ' + (let [[form new-pos] (read-form s (+ pos 2))] + [(array (sym "var") form) new-pos])) + +(defn read-regex [s pos] + # pos is at #, next char is " + # Read until unescaped closing " + (var i (+ pos 2)) + (var done nil) + (while (and (< i (length s)) (not done)) + (if (= (s i) 92) # backslash — skip next char + (+= i 2) + (if (= (s i) 34) # closing quote + (set done [(struct ;[:jolt/type :jolt/tagged :tag :regex :form (string/slice s (+ pos 2) i)]) + (+ i 1)]) + (++ i)))) + (if done done (error "Unterminated regex literal"))) + +(defn read-dispatch [s pos] + # pos is at # + (if (>= (+ pos 1) (length s)) + (error "Unexpected end after #")) + (let [c (s (+ pos 1))] + (cond + (= c 123) (read-set s pos) # #{ + (= c 40) (read-anon-fn s pos) # #( + (= c 63) (read-reader-conditional s pos) # #? + (= c 95) (let [[_ new-pos] (read-form s (+ pos 2))] # #_ + [{:jolt/type :jolt/skip} new-pos]) + (= c 39) (read-var-quote s pos) # #' + (= c 34) (read-regex s pos) # #"regex + (= c 35) # ## symbolic value: ##Inf ##-Inf ##NaN + (let [end (read-symbol-name s (+ pos 2) (+ pos 2)) + name (string/slice s (+ pos 2) end)] + (cond + (= name "Inf") [math/inf end] + (= name "-Inf") [(- math/inf) end] + (= name "NaN") [math/nan end] + (error (string "Invalid symbolic value: ##" name)))) + # unknown dispatch — tagged literal + (let [end (read-symbol-name s pos pos) + tag (string/slice s pos end) + [form new-pos] (read-form s end)] + [{:jolt/type :jolt/tagged :tag (keyword tag) :form form} new-pos])))) + +(defn read-quote [s pos new-pos token-sym] + (let [[form final-pos] (read-form s new-pos)] + [(array token-sym form) final-pos])) + +(defn- meta-form->map + "Normalize a metadata reader form (Clojure semantics): a symbol or string is a + :tag, a keyword is {kw true}. Returns a metadata table, or nil if it isn't one + of those simple shapes (e.g. a map literal — handled via with-meta instead)." + [meta-form] + (cond + (keyword? meta-form) {meta-form true} + (and (struct? meta-form) (= :symbol (meta-form :jolt/type))) {:tag (meta-form :name)} + (string? meta-form) {:tag meta-form} + nil)) + +(defn read-meta [s pos] + # pos is at ^ + (let [[meta-form new-pos] (read-form s (+ pos 1)) + [form new-pos2] (read-form s new-pos) + m (meta-form->map meta-form)] + (if (and m (struct? form) (= :symbol (form :jolt/type))) + # Attach the metadata to the symbol itself and keep it a bare symbol, so + # type hints (^String x) and ^:dynamic etc. are transparent in every + # position (params, lets, bodies) — the evaluator reads :name and ignores + # :meta. This is what makes type hints "parse and otherwise do nothing". + [(struct ;(kvs form) :meta (merge (or (form :meta) {}) m)) new-pos2] + # Non-symbol targets (collections etc.) keep a runtime with-meta form. Use the + # NORMALIZED metadata map (:kw -> {:kw true}, tag -> {:tag …}); a map-literal + # meta-form (m is nil) is already a map, so pass it through. + [(array (sym "with-meta") form (if m m meta-form)) new-pos2]))) + +(defn read-until-newline [s pos] + (if (or (>= pos (length s)) (= (s pos) 10)) + pos + (read-until-newline s (+ pos 1)))) + +(set read-form (fn [s pos] + (let [pos (skip-whitespace s pos)] + (if (>= pos (length s)) + [nil pos] + (let [c (s pos)] + (cond + # comment + (= c 59) + (let [line-end (read-until-newline s pos)] + [{:jolt/type :jolt/skip} line-end]) + + # dispatch + (= c 35) + (read-dispatch s pos) + + # string + (= c 34) + (read-string s pos) + + # list + (= c 40) + (read-list s pos) + + # unmatched closing delimiters + (= c 41) + (error (string "Unmatched closing paren at " pos)) + + (= c 93) + (error (string "Unmatched closing bracket at " pos)) + + (= c 125) + (error (string "Unmatched closing brace at " pos)) + + # vector + (= c 91) + (read-vector s pos) + + # map + (= c 123) + (read-map s pos) + + # keyword + (= c 58) + (read-keyword s pos) + + # quote + (= c 39) + (read-quote s pos (+ pos 1) (sym "quote")) + + # syntax-quote / backtick + (= c 96) + (read-quote s pos (+ pos 1) (sym "syntax-quote")) + + # unquote ~ + (= c 126) + (if (and (< (+ pos 1) (length s)) (= (s (+ pos 1)) 64)) + (read-quote s pos (+ pos 2) (sym "unquote-splicing")) + (read-quote s pos (+ pos 1) (sym "unquote"))) + + # deref + (= c 64) + (read-quote s pos (+ pos 1) (sym "deref")) + + # metadata + (= c 94) + (read-meta s pos) + + # character + (= c 92) + (read-char s pos) + + # number or symbol + (if (or (digit? c) + (and (= c 45) (< (+ pos 1) (length s)) (digit? (s (+ pos 1)))) + (and (= c 43) (< (+ pos 1) (length s)) (digit? (s (+ pos 1))))) + (read-number s pos) + (read-symbol s pos)))))))) + +(defn parse-string + "Parse a Clojure source string and return the first form." + [s] + (let [[form pos] (read-form s 0)] + (if (and (struct? form) (= :jolt/skip (form :jolt/type))) + (parse-string (string/slice s pos)) + form))) + +(defn parse-next + "Parse the first form from a string. Returns [form remaining-string]." + [s] + (defn- parse-next-loop [pos] + (let [[form new-pos] (read-form s pos)] + (if (and (struct? form) (= :jolt/skip (form :jolt/type))) + (parse-next-loop new-pos) + [form (string/slice s new-pos)]))) + (parse-next-loop 0)) diff --git a/src/jolt/regex.janet b/src/jolt/regex.janet new file mode 100644 index 0000000..05b3e29 --- /dev/null +++ b/src/jolt/regex.janet @@ -0,0 +1,406 @@ +# Regex support for Jolt, compiled to Janet's PEG engine. +# +# Path A: a real regex parser -> AST -> PEG grammar with continuation passing +# and position-based group captures. This gives genuine backtracking (greedy and +# lazy) that threads through capturing groups, plus capturing groups returned in +# Clojure's [whole g1 g2 ...] order, lookahead, anchors, classes, flags. +# +# Supported: literals, `.`, char classes `[...]`/`[^...]` (ranges, POSIX, +# `\d \w \s` etc.), quantifiers `* + ? {n} {n,} {n,m}` (greedy + lazy `?`), +# groups `(...)` (numbered), non-capturing `(?:...)`, lookahead `(?=...)`/`(?!...)`, +# alternation `|`, anchors `^ $ \b \B`, escapes, inline flag `(?i)`. +# Not supported: lookbehind, backreferences, named groups (rare; documented). + +(defn- chr [s] (get s 0)) +(defn regex? [x] (and (table? x) (= :jolt/regex (x :jolt/type)))) + +# ============================================================ +# Parser: regex source -> AST +# ============================================================ +# AST nodes (structs): {:op ...} +# :char {:b byte :ci bool} :any {:dotall bool} +# :class {:peg :neg bool} :pred {:peg } +# :seq {:items [...]} :alt {:items [...]} +# :star/:plus/:quest {:item ast :greedy bool} +# :rep {:item ast :min n :max m-or-nil :greedy bool} +# :group {:n num :item ast} :ncgroup {:item ast} +# :look {:neg bool :item ast} +# :anchor {:kind :start/:end/:wordb/:nwordb} + +(defn- lower-b [b] (if (and (>= b 65) (<= b 90)) (+ b 32) b)) +(defn- upper-b [b] (if (and (>= b 97) (<= b 122)) (- b 32) b)) + +(defn- pred-frag [c] + (case c + (chr "d") '(range "09") + (chr "D") '(if-not (range "09") 1) + (chr "w") '(choice (range "az" "AZ" "09") (set "_")) + (chr "W") '(if-not (choice (range "az" "AZ" "09") (set "_")) 1) + (chr "s") '(set " \t\n\r\f\v") + (chr "S") '(if-not (set " \t\n\r\f\v") 1) + nil)) + +(defn- esc-byte [c] + (case c + (chr "n") 10 (chr "t") 9 (chr "r") 13 (chr "f") 12 (chr "v") 11 (chr "0") 0 + c)) + +# Parse a [...] character class body, returns a PEG fragment + negation flag. +(defn- parse-class [s start ci] + (var i start) + (def neg (and (< i (length s)) (= (s i) (chr "^")))) + (when neg (++ i)) + (def alts @[]) + (while (and (< i (length s)) (not= (s i) (chr "]"))) + (cond + # POSIX class [:alpha:] etc. + (and (= (s i) (chr "[")) (< (+ i 1) (length s)) (= (s (+ i 1)) (chr ":"))) + (let [close (string/find ":]" s i) + name (string/slice s (+ i 2) close)] + (array/push alts (case name + "alpha" '(range "az" "AZ") + "digit" '(range "09") + "alnum" '(range "az" "AZ" "09") + "space" '(set " \t\n\r\f\v") + "upper" '(range "AZ") + "lower" '(range "az") + '(set ""))) + (set i (+ close 2))) + # escape inside class + (= (s i) (chr "\\")) + (let [c (s (+ i 1)) p (pred-frag c)] + (if p (array/push alts p) + (array/push alts ~(set ,(string/from-bytes (esc-byte c))))) + (set i (+ i 2))) + # range a-z + (and (< (+ i 2) (length s)) (= (s (+ i 1)) (chr "-")) (not= (s (+ i 2)) (chr "]"))) + (do + (if ci + (array/push alts ~(range ,(string/from-bytes (lower-b (s i)) (lower-b (s (+ i 2))) + (upper-b (s i)) (upper-b (s (+ i 2)))))) + (array/push alts ~(range ,(string/from-bytes (s i) (s (+ i 2)))))) + (set i (+ i 3))) + # single char + (do + (if ci + (array/push alts ~(set ,(string/from-bytes (lower-b (s i)) (upper-b (s i))))) + (array/push alts ~(set ,(string/from-bytes (s i))))) + (++ i)))) + (def frag (if (= 1 (length alts)) (alts 0) ~(choice ,;alts))) + [(if neg ~(if-not ,frag 1) frag) (+ i 1)]) # i is at ], skip it + +(var parse-alt nil) + +(defn- parse-atom [st] + # returns ast; advances (st :pos) + (def s (st :s)) + (def c (s (st :pos))) + (def ci (st :ci)) + (cond + (= c (chr "(")) + (let [nx (if (< (+ (st :pos) 1) (length s)) (s (+ (st :pos) 1)) 0)] + (if (= nx (chr "?")) + (let [k (s (+ (st :pos) 2))] + (cond + (= k (chr ":")) (do (+= (st :pos) 3) + (let [inner (parse-alt st)] (+= (st :pos) 1) {:op :ncgroup :item inner})) + (= k (chr "=")) (do (+= (st :pos) 3) + (let [inner (parse-alt st)] (+= (st :pos) 1) {:op :look :neg false :item inner})) + (= k (chr "!")) (do (+= (st :pos) 3) + (let [inner (parse-alt st)] (+= (st :pos) 1) {:op :look :neg true :item inner})) + # inline flags (?i) / (?i:...) — set case-insensitive + (do + (var j (+ (st :pos) 2)) + (var seti false) + (while (and (< j (length s)) (not= (s j) (chr ")")) (not= (s j) (chr ":"))) + (when (= (s j) (chr "i")) (set seti true)) + (++ j)) + (if (= (s j) (chr ":")) + (do (set (st :pos) (+ j 1)) + (def saved (st :ci)) + (when seti (set (st :ci) true)) + (def inner (parse-alt st)) + (set (st :ci) saved) + (+= (st :pos) 1) + {:op :ncgroup :item inner}) + (do (set (st :pos) (+ j 1)) # (?i) — flag for rest of pattern + (when seti (set (st :ci) true)) + {:op :seq :items @[]}))))) + # capturing group + (let [n (++ (st :ngroup))] + (+= (st :pos) 1) + (let [inner (parse-alt st)] + (+= (st :pos) 1) # skip ) + {:op :group :n n :item inner})))) + (= c (chr "[")) + (let [[frag np] (parse-class s (+ (st :pos) 1) ci)] + (set (st :pos) np) + {:op :class :peg frag}) + (= c (chr ".")) + (do (++ (st :pos)) {:op :any :dotall (st :dotall)}) + (= c (chr "\\")) + (let [nc (s (+ (st :pos) 1)) p (pred-frag nc)] + (+= (st :pos) 2) + (cond + p {:op :pred :peg p} + (= nc (chr "b")) {:op :anchor :kind :wordb} + (= nc (chr "B")) {:op :anchor :kind :nwordb} + {:op :char :b (esc-byte nc) :ci ci})) + (= c (chr "^")) (do (++ (st :pos)) {:op :anchor :kind :start}) + (= c (chr "$")) (do (++ (st :pos)) {:op :anchor :kind :end}) + (do (++ (st :pos)) {:op :char :b c :ci ci}))) + +(defn- parse-quant [st] + (def atom (parse-atom st)) + (def s (st :s)) + (if (>= (st :pos) (length s)) + atom + (let [q (s (st :pos))] + # called after advancing past the quantifier char: a trailing `?` -> lazy + (defn lazy? [] + (if (and (< (st :pos) (length s)) (= (s (st :pos)) (chr "?"))) + (do (++ (st :pos)) false) # lazy -> greedy=false + true)) + (cond + (= q (chr "*")) (do (++ (st :pos)) {:op :star :item atom :greedy (lazy?)}) + (= q (chr "+")) (do (++ (st :pos)) {:op :plus :item atom :greedy (lazy?)}) + (= q (chr "?")) (do (++ (st :pos)) {:op :quest :item atom :greedy (lazy?)}) + (= q (chr "{")) + (let [close (string/find "}" s (st :pos)) + spec (string/slice s (+ (st :pos) 1) close) + comma (string/find "," spec)] + (set (st :pos) (+ close 1)) + (def greedy (lazy?)) + (if comma + (let [lo (scan-number (string/slice spec 0 comma)) + hs (string/slice spec (+ comma 1)) + hi (if (= 0 (length hs)) nil (scan-number hs))] + {:op :rep :item atom :min lo :max hi :greedy greedy}) + {:op :rep :item atom :min (scan-number spec) :max (scan-number spec) :greedy greedy})) + atom)))) + +(defn- parse-seq [st] + (def s (st :s)) + (def items @[]) + (while (and (< (st :pos) (length s)) + (not= (s (st :pos)) (chr "|")) + (not= (s (st :pos)) (chr ")"))) + (array/push items (parse-quant st))) + (if (= 1 (length items)) (items 0) {:op :seq :items items})) + +(set parse-alt (fn [st] + (def branches @[(parse-seq st)]) + (def s (st :s)) + (while (and (< (st :pos) (length s)) (= (s (st :pos)) (chr "|"))) + (++ (st :pos)) + (array/push branches (parse-seq st))) + (if (= 1 (length branches)) (branches 0) {:op :alt :items branches}))) + +(defn- parse [source] + (def st @{:s source :pos 0 :ngroup 0 :ci false :dotall false}) + (def ast (parse-alt st)) + [ast (st :ngroup)]) + +# ============================================================ +# Emit: AST -> PEG grammar (continuation passing) +# ============================================================ + +(def- word-frag '(choice (range "az" "AZ" "09") (set "_"))) + +(defn- char-peg [b ci] + (if (and ci (not= (lower-b b) (upper-b b))) + ~(set ,(string/from-bytes (lower-b b) (upper-b b))) + ~(set ,(string/from-bytes b)))) + +(defn- make-emitter [grammar] + (var ctr 0) + (defn fresh [] (++ ctr) (keyword (string "r" ctr))) + (var emit nil) + (set emit (fn [ast k] + (case (ast :op) + :char ~(sequence ,(char-peg (ast :b) (ast :ci)) ,k) + :any ~(sequence ,(if (ast :dotall) 1 ~(if-not "\n" 1)) ,k) + :class ~(sequence ,(ast :peg) ,k) + :pred ~(sequence ,(ast :peg) ,k) + :seq (do (var acc k) (var i (dec (length (ast :items)))) + (while (>= i 0) (set acc (emit (in (ast :items) i) acc)) (-- i)) acc) + :alt (let [kr (fresh)] + (put grammar kr k) + ~(choice ,;(map (fn [a] (emit a (keyword kr))) (ast :items)))) + :star (let [r (fresh)] + (put grammar r (if (ast :greedy) + ~(choice ,(emit (ast :item) (keyword r)) ,k) + ~(choice ,k ,(emit (ast :item) (keyword r))))) + (keyword r)) + :plus (let [r (fresh)] + (put grammar r (if (ast :greedy) + ~(choice ,(emit (ast :item) (keyword r)) ,k) + ~(choice ,k ,(emit (ast :item) (keyword r))))) + (emit (ast :item) (keyword r))) + :quest (if (ast :greedy) + ~(choice ,(emit (ast :item) k) ,k) + ~(choice ,k ,(emit (ast :item) k))) + :rep (let [lo (ast :min) hi (ast :max) item (ast :item) greedy (ast :greedy)] + # desugar: lo required, then (hi-lo) optional, or star if hi is nil + (var tail (if (nil? hi) + (let [r (fresh)] + (put grammar r (if greedy + ~(choice ,(emit item (keyword r)) ,k) + ~(choice ,k ,(emit item (keyword r))))) + (keyword r)) + (do (var acc k) (var c (- hi lo)) + (while (> c 0) + (set acc (if greedy ~(choice ,(emit item acc) ,acc) + ~(choice ,acc ,(emit item acc)))) + (-- c)) + acc))) + (var acc tail) (var c lo) + (while (> c 0) (set acc (emit item acc)) (-- c)) + acc) + :group (let [n (ast :n)] + ~(sequence (/ (position) ,(fn [p] [n :s p])) + ,(emit (ast :item) + ~(sequence (/ (position) ,(fn [p] [n :e p])) ,k)))) + :ncgroup (emit (ast :item) k) + :look (if (ast :neg) + ~(sequence (not ,(emit (ast :item) 0)) ,k) + ~(sequence (not (not ,(emit (ast :item) 0))) ,k)) + :anchor (case (ast :kind) + :start ~(sequence (not (look -1 1)) ,k) + :end ~(sequence (not 1) ,k) + :wordb ~(sequence (choice (sequence (look -1 ,word-frag) (not ,word-frag)) + (sequence (not (look -1 ,word-frag)) (not (not ,word-frag)))) + ,k) + :nwordb ~(sequence (choice (sequence (look -1 ,word-frag) (not (not ,word-frag))) + (sequence (not (look -1 ,word-frag)) (not ,word-frag))) + ,k) + ~(sequence 0 ,k)) + (error (string "regex emit: unhandled op " (ast :op)))))) + emit) + +(defn compile-regex [source] + (def [ast ngroups] (parse source)) + (def grammar @{}) + (def emit (make-emitter grammar)) + # group 0 = whole match: mark start, body, mark end + (def body (emit ast ~(sequence (/ (position) ,(fn [p] [0 :e p])) 0))) + (put grammar :main ~(sequence (/ (position) ,(fn [p] [0 :s p])) ,body)) + (def gstruct (table/to-struct grammar)) + # anchored variant for re-matches: whole input must be consumed + (def anchored (table/to-struct (merge grammar {:main ~(sequence ,(grammar :main) -1)}))) + @{:jolt/type :jolt/regex + :source source + :ngroups ngroups + :peg (peg/compile gstruct) + :anchored (peg/compile anchored)}) + +(defn re-pattern [source] + (if (regex? source) source (compile-regex source))) + +# ============================================================ +# Matching +# ============================================================ + +(defn- marks->groups [marks s ngroups] + # marks: array of [n :s pos] / [n :e pos]; build [g0 g1 ... gN], slicing input + (def starts (array/new-filled (+ ngroups 1))) + (def ends (array/new-filled (+ ngroups 1))) + (each m marks + (let [n (m 0)] + (if (= (m 1) :s) (put starts n (m 2)) (put ends n (m 2))))) + (def groups (array/new-filled (+ ngroups 1))) + (var n 0) + (while (<= n ngroups) + (if (and (not (nil? (in starts n))) (not (nil? (in ends n)))) + (put groups n (string/slice s (in starts n) (in ends n))) + (put groups n nil)) + (++ n)) + groups) + +(defn- match-at [re s start] + # returns groups array or nil + (def marks (peg/match (re :peg) s start)) + (if marks (marks->groups marks s (re :ngroups)) nil)) + +(defn- groups->result [groups ngroups] + # 0 groups -> whole-match string; else tuple [whole g1 ...] + (if (= ngroups 0) (in groups 0) (tuple/slice groups))) + +(defn re-find [re s] + (def re (re-pattern re)) + (var result nil) (var pos 0) + (while (and (nil? result) (<= pos (length s))) + (def g (match-at re s pos)) + (if g (set result (groups->result g (re :ngroups))) (++ pos))) + result) + +(defn re-matches [re s] + (def re (re-pattern re)) + (def marks (peg/match (re :anchored) s 0)) + (if marks (groups->result (marks->groups marks s (re :ngroups)) (re :ngroups)) nil)) + +(defn re-seq [re s] + (def re (re-pattern re)) + (def out @[]) (var pos 0) + (while (<= pos (length s)) + (def g (match-at re s pos)) + (if g + (let [whole (in g 0)] + (array/push out (groups->result g (re :ngroups))) + (set pos (+ pos (max 1 (length whole))))) + (++ pos))) + out) + +(defn re-split [re s] + (def re (re-pattern re)) + (def out @[]) (var pos 0) (var last 0) + (while (<= pos (length s)) + (def g (match-at re s pos)) + (if (and g (> (length (in g 0)) 0)) + (do (array/push out (string/slice s last pos)) + (set pos (+ pos (length (in g 0)))) + (set last pos)) + (++ pos))) + (array/push out (string/slice s last)) + out) + +(defn- expand-replacement [repl groups] + # $0 / $1 ... substitution in replacement string + (def buf @"") (var i 0) + (while (< i (length repl)) + (let [c (repl i)] + (if (and (= c (chr "$")) (< (+ i 1) (length repl)) (>= (repl (+ i 1)) 48) (<= (repl (+ i 1)) 57)) + (let [n (- (repl (+ i 1)) 48)] + (when (and (< n (length groups)) (in groups n)) (buffer/push-string buf (in groups n))) + (set i (+ i 2))) + (do (buffer/push-string buf (string/from-bytes c)) (++ i))))) + (string buf)) + +(defn re-replace-all [re s replacement] + (def re (re-pattern re)) + (def buf @"") (var pos 0) (var last 0) + (while (<= pos (length s)) + (def g (match-at re s pos)) + (if (and g (> (length (in g 0)) 0)) + (do (buffer/push-string buf (string/slice s last pos)) + (buffer/push-string buf (if (string? replacement) (expand-replacement replacement g) replacement)) + (set pos (+ pos (length (in g 0)))) + (set last pos)) + (++ pos))) + (buffer/push-string buf (string/slice s last)) + (string buf)) + +(defn re-replace-first [re s replacement] + (def re (re-pattern re)) + (var pos 0) (var done nil) + (while (and (nil? done) (<= pos (length s))) + (def g (match-at re s pos)) + (if (and g (> (length (in g 0)) 0)) + (set done [pos g]) + (++ pos))) + (if done + (let [[p g] done] + (string (string/slice s 0 p) + (if (string? replacement) (expand-replacement replacement g) replacement) + (string/slice s (+ p (length (in g 0)))))) + s)) diff --git a/src/jolt/stdlib_embed.janet b/src/jolt/stdlib_embed.janet new file mode 100644 index 0000000..6dd5eb6 --- /dev/null +++ b/src/jolt/stdlib_embed.janet @@ -0,0 +1,35 @@ +# Bakes the Clojure stdlib (.clj/.cljc under src/jolt/clojure and src/jolt/jolt) +# into the image at build time, so the runtime can load clojure.string, jolt.http, +# jolt.nrepl, etc. from any directory — not just when run from the repo. +# +# `sources` is built at module-load time. During `jpm build` that's the build +# (cwd = repo), so the map is captured into the image and frozen; in the shipped +# binary the files are never read from disk. Running from source rebuilds it. + +(defn- relpath->ns [rel] + # string/replace-all takes the string LAST, so thread with ->> + (->> rel (string/replace-all "/" ".") (string/replace-all "_" "-"))) + +(defn- strip-ext [name] + (cond + (string/has-suffix? ".cljc" name) (string/slice name 0 (- (length name) 5)) + (string/has-suffix? ".clj" name) (string/slice name 0 (- (length name) 4)) + name)) + +(defn- collect [root prefix acc] + (when (os/stat root) + (each e (os/dir root) + (def p (string root "/" e)) + (cond + (= :directory (os/stat p :mode)) (collect p (string prefix e "/") acc) + (or (string/has-suffix? ".clj" e) (string/has-suffix? ".cljc" e)) + (put acc (relpath->ns (string prefix (strip-ext e))) (slurp p))))) + acc) + +(def sources + (let [acc @{}] + (collect "src/jolt/clojure" "clojure/" acc) + (collect "src/jolt/jolt" "jolt/" acc) + # Portable Clojure core (analyzer/IR/…): jolt-core/jolt/foo.clj -> jolt.foo + (collect "jolt-core" "" acc) + acc)) diff --git a/src/jolt/types.janet b/src/jolt/types.janet new file mode 100644 index 0000000..11746b6 --- /dev/null +++ b/src/jolt/types.janet @@ -0,0 +1,528 @@ +# Jolt Types +# Core types for the Clojure-on-Janet interpreter. +# +# Types: +# JoltVar — mutable container with metadata (like Clojure Var) +# JoltNamespace — namespace with symbol→var mappings and imports +# JoltContext — evaluation context (env atom, namespaces) +# +# Symbols are represented as {:jolt/type :symbol :ns :name } +# as produced by the reader. + +# Characters are {:jolt/type :jolt/char :ch }, distinct from strings. +(defn make-char [code] {:jolt/type :jolt/char :ch code}) + +(def- char-named @{"newline" 10 "space" 32 "tab" 9 "return" 13 + "formfeed" 12 "backspace" 8 "newpage" 12 "nul" 0}) + +(defn char-from-name + "Resolve a reader char-literal name (\\a, \\newline, \\uNNNN, \\oNNN) to a char value." + [name] + (cond + (= 1 (length name)) (make-char (in name 0)) + (get char-named name) (make-char (get char-named name)) + (and (> (length name) 1) (= (in name 0) (get "u" 0))) + (make-char (scan-number (string "16r" (string/slice name 1)))) + (and (> (length name) 1) (= (in name 0) (get "o" 0))) + (make-char (scan-number (string "8r" (string/slice name 1)))) + (error (string "Unsupported character: \\" name)))) + +# ============================================================ +# Symbol helpers +# ============================================================ + +(defn sym? + "Check if x is a Jolt symbol struct." + [x] + (and (struct? x) (= :symbol (x :jolt/type)))) + +# ============================================================ +# Var +# ============================================================ + +# Dynamic-var binding stack. Stored fiber-locally (via Janet's dyn), so that +# concurrent go blocks — each a Janet fiber — don't interleave each other's +# dynamic bindings, and a go block conveys the bindings in effect when it was +# spawned (see snapshot-bindings/install-bindings). Each fiber lazily gets its +# own array on first use. +(defn cur-binding-stack [] + (or (dyn :jolt/binding-stack) + (let [s @[]] (setdyn :jolt/binding-stack s) s))) + +(defn push-thread-bindings + "Push a frame of dynamic var bindings. Takes a struct of var→value." + [bindings] + (array/push (cur-binding-stack) bindings)) + +(defn pop-thread-bindings + "Pop the most recent frame of dynamic var bindings." + [] + (array/pop (cur-binding-stack))) + +(defn snapshot-bindings + "Shallow copy of the current binding stack (frames are immutable value maps). + Captured by a go block at spawn time for binding conveyance." + [] + (array/slice (cur-binding-stack))) + +(defn install-bindings + "Install a snapshot as this fiber's binding stack (a fresh copy, so the + fiber's own push/pop/var-set don't mutate the snapshot's frames array)." + [snap] + (setdyn :jolt/binding-stack (array/slice snap))) + +(defn make-var + "Create a new Jolt Var. + (make-var name) — unbound var + (make-var name init-val) — var with root binding + (make-var name init-val meta) — var with root and metadata + + name is a symbol struct {:jolt/type :symbol ...}" + [name &opt init-val meta] + (default init-val nil) + (default meta nil) + (let [m (if meta meta {:name name}) + result @{:jolt/type :jolt/var + :name name + :root init-val + :meta m + # Generation: bumped on every root change (redefinition). Call + # sites / dispatch caches keyed on this can detect a redef and + # invalidate; direct-linked (sealed) sites can detect staleness. + :gen 0 + :dynamic (if meta (get meta :dynamic) false) + :macro (if meta (get meta :macro) false) + :ns (if meta (get meta :ns) nil)}] + result)) + +(defn var? + "Check if x is a Jolt Var." + [x] + (and (table? x) (= :jolt/var (x :jolt/type)))) + +(defn var-dynamic? + "Check if var is marked :dynamic." + [v] + (v :dynamic)) + +(defn var-macro? + "Check if var is marked :macro." + [v] + (v :macro)) + +(defn var-name + "Return the symbol name of the var." + [v] + (v :name)) + +(defn var-meta + "Return the metadata of the var." + [v] + (v :meta)) + +(defn var-ns + "Return the namespace of the var." + [v] + (v :ns)) + +(defn var-get + "Deref the var. If the var is dynamic and has a thread-local binding, return that. + Otherwise return the root binding." + [v] + # Fast path: no dynamic bindings are active (the common case — the stack is + # only non-empty inside a `binding` block), so the value is just the root. This + # is the hot path for every global deref; skip building the walk otherwise. + (def bs (cur-binding-stack)) + (if (= 0 (length bs)) + (v :root) + # walk binding stack top-down for this var + (do + (var result nil) + (var i (dec (length bs))) + (while (>= i 0) + (let [frame (in bs i) + val (get frame v)] + (if (not (nil? val)) + (do + (set result (if (var? val) (var-get val) val)) + (set i -1)) + (-- i)))) + (if (not (nil? result)) result (v :root))))) + +(defn var-set + "Set a var's value. If the var has a thread-local binding on the stack, update + the innermost frame that binds it (matching Clojure, where var-set targets the + current binding); otherwise set the root." + [v val] + (def bs (cur-binding-stack)) + (var i (dec (length bs))) + (var done false) + (while (and (not done) (>= i 0)) + (let [frame (in bs i)] + (if (not (nil? (get frame v))) + (do (put bs i (merge frame {v val})) (set done true)) + (-- i)))) + (unless done (do (put v :root val) (put v :gen (+ 1 (or (v :gen) 0))))) + val) + +(defn alter-var-root + "Atomically alter the root binding of v by applying f to current value plus args." + [v f & args] + (let [new-val (f (v :root) ;args)] + (put v :root new-val) + (put v :gen (+ 1 (or (v :gen) 0))) + new-val)) + +(defn alter-meta! + "Atomically update a var's metadata via (apply f args)." + [v f & args] + (let [new-meta (apply f (var-meta v) args)] + (put v :meta new-meta) + new-meta)) + +(defn reset-meta! + "Reset a var's metadata to the given value." + [v meta] + (put v :meta meta) + meta) + +(defn make-hierarchy + "Create a new empty hierarchy for multimethod dispatch." + [] + {:parents @{} :descendants @{} :ancestors @{}}) + +# The global hierarchy used by the 1/2-arg derive/isa?/parents/ancestors/ +# descendants and by multimethod dispatch when no explicit hierarchy is given. +(def the-global-hierarchy (make-hierarchy)) + +(defn derive* + "Add a parent relationship to a hierarchy." + [h tag parent] + (put (h :parents) tag parent) + (let [d (get (h :descendants) parent)] + (if d (array/push d tag) (put (h :descendants) parent @[tag]))) + (let [a (get (h :ancestors) tag)] + (if a (array/push a parent) (put (h :ancestors) tag @[parent]))) + h) + +(defn- ancestors* + "Internal: get all ancestors of a tag via iterative graph walk." + [h tag visited] + (var stack @[tag]) + (while (> (length stack) 0) + (let [t (array/pop stack)] + (when (not (get visited t)) + (put visited t true) + (let [p (get (h :parents) t)] + (when (and p (not= p t)) + (array/push stack p)))))) + visited) + +(defn ancestors + "Return all transitive ancestors of a tag in the given hierarchy." + [h tag] + (let [visited (ancestors* h tag @{})] + (var result @[]) + (loop [[k _] :pairs visited] + (when (not= k tag) (array/push result k))) + result)) + +(defn descendants + "Return the descendants of a tag in the given hierarchy." + [h tag] + (let [d (get (h :descendants) tag)] (if d d @[]))) + +(defn isa? + "Check if child is derived from parent in the given hierarchy." + [h child parent] + (if (= child parent) true + (let [p (get (h :parents) child)] + (if p (isa? h p parent) false)))) + +(defn underive + "Remove a parent relationship from a hierarchy." + [h tag parent] + (put (h :parents) tag nil) + h) + +(defn with-meta + "Return a new var with updated metadata. The original var is unchanged." + [v meta] + # build new meta as a table first (to allow adding keys), then convert + (let [new-meta-table (merge @{} (v :meta) meta) + # convert to struct by extracting all keys + new-meta (table/to-struct new-meta-table)] + @{:jolt/type :jolt/var + :name (v :name) + :root (v :root) + :meta new-meta + :gen (or (v :gen) 0) + :dynamic (v :dynamic) + :macro (v :macro) + :ns (v :ns)})) + +(defn bind-root + "Set the root binding and bump the var's generation (the redefinition + chokepoint: def, ns-intern-with-val, and the root-set paths all route here)." + [v val] + (put v :root val) + (put v :gen (+ 1 (or (v :gen) 0))) + val) + +# ============================================================ +# Namespace +# ============================================================ + +(defn make-ns + "Create a new namespace. + (make-ns name) — empty namespace + name is a symbol struct {:jolt/type :symbol ...}" + [name] + (struct + :jolt/type :jolt/namespace + :name name + :mappings @{} + :imports @{} + :aliases @{})) + +(defn ns? + "Check if x is a Jolt Namespace." + [x] + (and (or (struct? x) (table? x)) (= :jolt/namespace (x :jolt/type)))) + +(defn ns-name + "Return the name symbol of a namespace." + [ns] + (ns :name)) + +(defn ns-map + "Return the mappings table (symbol → var) for a namespace." + [ns] + (ns :mappings)) + +(defn ns-intern + "Find or create a var named by sym in namespace ns, setting root binding to val if given. + (ns-intern ns sym) — find or create unbound var + (ns-intern ns sym val) — find or create with root binding" + [ns sym &opt val] + (default val nil) + (let [mappings (ns :mappings) + existing (get mappings sym)] + (if existing + (do + (when (not (nil? val)) + (bind-root existing val)) + existing) + # Store the namespace *name*, not the ns table: a back-pointer to the ns + # would make the var cyclic (ns -> mappings -> var -> ns), and the compiler + # embeds var cells as constants, which can't be cyclic. + (let [v (make-var sym val {:ns (get ns :name) :name sym})] + (put mappings sym v) + v)))) + +(defn ns-find + "Find a var by symbol in the namespace. Returns nil if not found." + [ns sym] + (get (ns :mappings) sym)) + +(defn ns-unmap + "Remove a mapping by symbol from the namespace." + [ns sym] + (put (ns :mappings) sym nil)) + +(defn ns-resolve + "Resolve a symbol in a namespace. Looks in own mappings first, + then aliases. Returns the var or nil." + [ns sym] + (or (ns-find ns sym) + (let [qualified? (sym? sym)] + (when qualified? + # qualified symbol: look up via alias + (let [alias-ns (get (ns :aliases) (sym :ns))] + (when alias-ns + (ns-find alias-ns (sym :name)))))))) + +(defn ns-import + "Add an import to the namespace. class-name is local symbol, fq-class-name is the full qualified name." + [ns class-name fq-class-name] + (put (ns :imports) class-name fq-class-name)) + +(defn ns-import-lookup + "Look up an import in the namespace. Returns the full qualified name or nil." + [ns class-name] + (get (ns :imports) class-name)) + +(defn ns-add-alias + "Add an alias from alias-sym to target-ns." + [ns alias-sym target-ns] + (put (ns :aliases) alias-sym target-ns)) + +# ============================================================ +# Context +# ============================================================ + +(defn ctx-find-ns + "Find or create a namespace in the context by name symbol." + [ctx ns-sym] + (let [env (ctx :env) + namespaces (env :namespaces)] + (or (get namespaces ns-sym) + (let [ns (make-ns ns-sym)] + (put namespaces ns-sym ns) + ns)))) + +(defn make-ctx + "Create a new evaluation context. + (make-ctx) — empty context with 'user namespace + (make-ctx opts) — context with initial namespaces from opts + + opts may contain: + :namespaces — struct of {ns-symbol → {sym → value, ...}, ...}" + [&opt opts] + (default opts nil) + (let [compile? (if opts (get opts :compile?) false) + # Direct-linking (call-site/unit property, like Clojure). :aot-core? + # (default true; JOLT_AOT_CORE=0 disables) compiles the core tiers + + # compiler with direct-linking on. :direct-linking? is the per-unit flag + # the back end reads while emitting; it defaults to the user-code setting + # (off unless opted in) and load-core-overlay! flips it on around core. + aot-core? (let [o (if opts (get opts :aot-core?) nil)] + (if (nil? o) (not (= "0" (os/getenv "JOLT_AOT_CORE"))) o)) + env @{:namespaces @{} + :class->opts @{} + :current-ns "user" + :compile? compile? + :aot-core? aot-core? + :direct-linking? (if opts (get opts :direct-linking?) nil) + # Ordered roots searched (after the stdlib) to resolve a namespace + # to a .clj/.cljc file. jolt-core holds the portable Clojure layer + # (analyzer/IR/core); deps.edn resolution appends dep src dirs. + :source-paths @["jolt-core" "src/jolt"] + :type-registry @{} + :data-readers (let [dr @{}] + (put dr (keyword "#inst") (fn [s] s)) + (put dr (keyword "#uuid") (fn [s] s)) + dr)} + # create the user namespace via a partial context + _ (ctx-find-ns {:env env} "user")] + # initialize from opts + (when opts + (when-let [ns-opts (get opts :namespaces)] + (loop [[ns-sym mappings] :pairs ns-opts] + (let [ns (ctx-find-ns {:env env} ns-sym)] + (loop [[sym val] :pairs mappings] + (ns-intern ns sym val)))))) + {:jolt/type :jolt/context + :env env})) + +(defn ctx? + "Check if x is a Jolt Context." + [x] + (and (struct? x) (= :jolt/context (x :jolt/type)))) + +(defn ctx-env + "Return the env atom from the context." + [ctx] + (ctx :env)) + +(defn ctx-current-ns + "Get the current namespace symbol." + [ctx] + (get (ctx :env) :current-ns)) + +(defn ctx-set-current-ns + "Set the current namespace symbol." + [ctx ns-sym] + (put (ctx :env) :current-ns ns-sym)) + +(defn all-ns + "Return a list of all namespaces in the context." + [ctx] + (let [namespaces (get (ctx :env) :namespaces) + result @[]] + (loop [[_ ns] :pairs namespaces] + (array/push result ns)) + result)) + +(defn remove-ns + "Remove a namespace from the context by name string." + [ctx ns-name] + (put (get (ctx :env) :namespaces) ns-name nil) nil) + +(defn create-ns + "Create a new namespace." + [ctx ns-name] + (ctx-find-ns ctx ns-name)) + +(defn the-ns + "Return the current namespace object." + [ctx] + (ctx-find-ns ctx (ctx-current-ns ctx))) + +(defn ns-interns + "Return the map of all interned vars in the current namespace." + [ctx] + (let [ns (ctx-find-ns ctx (ctx-current-ns ctx))] + (ns :mappings))) + +(defn ns-aliases + "Return the alias map of the current namespace." + [ctx] + (let [ns (ctx-find-ns ctx (ctx-current-ns ctx))] + (ns :aliases))) + +(defn ns-imports-fn + "Return the import map of the current namespace." + [ctx] + (let [ns (ctx-find-ns ctx (ctx-current-ns ctx))] + (ns :imports))) + +(defn find-var + "Resolve a symbol to a var in the current context. + Looks in current namespace first, then clojure.core." + [ctx sym-s] + (let [name (sym-s :name) + ns-sym (sym-s :ns)] + (if ns-sym + (let [ns (ctx-find-ns ctx ns-sym)] + (ns-find ns name)) + (let [current-ns (ctx-find-ns ctx (ctx-current-ns ctx)) + v (ns-find current-ns name)] + (if v v + (let [core-ns (ctx-find-ns ctx "clojure.core")] + (ns-find core-ns name))))))) + + +# ============================================================ +# Protocol type registry +# ============================================================ + +(defn register-protocol-method + "Register a protocol method implementation for a type." + [ctx type-tag protocol-name method-name fn] + (let [env (ctx :env) + registry (get env :type-registry) + type-impls (or (get registry type-tag) + (do (put registry type-tag @{}) (get registry type-tag))) + proto-impls (or (get type-impls protocol-name) + (do (put type-impls protocol-name @{}) (get type-impls protocol-name)))] + (put proto-impls method-name fn) + # Bump the registry generation so any dispatch cache keyed on it invalidates. + (put env :type-registry-gen (+ 1 (or (get env :type-registry-gen) 0))))) + +(defn find-protocol-method + "Find a protocol method implementation for a type." + [ctx type-tag protocol-name method-name] + (let [registry (get (ctx :env) :type-registry) + type-impls (get registry type-tag)] + (when type-impls + (let [proto-impls (get type-impls protocol-name)] + (when proto-impls + (get proto-impls method-name)))))) + +(defn type-satisfies? + "Check if a type satisfies a protocol." + [ctx type-tag protocol-name] + (let [registry (get (ctx :env) :type-registry) + type-impls (get registry type-tag)] + (if (and type-impls (get type-impls protocol-name)) true false))) diff --git a/stdlib/clojure/core/async.clj b/stdlib/clojure/core/async.clj deleted file mode 100644 index 5965100..0000000 --- a/stdlib/clojure/core/async.clj +++ /dev/null @@ -1,667 +0,0 @@ -;; clojure.core.async — higher-level dataflow API over the channel primitives. -;; -;; The primitives (chan, !, !!, close!, put!, take!, offer!, timeout, -;; promise-chan, buffer/dropping-buffer/sliding-buffer, go/go-loop/thread, go-spawn) -;; are provided natively (host/chez/java/async.ss) on real OS threads. This overlay -;; adds the portable dataflow operators — alts!, pipe, pipeline, split, reduce, -;; transduce, mult, mix, pub/sub, map, merge, and the deprecated map/… — -;; ported from clojure.core.async over those primitives. Because go blocks are real -;; threads, parking ops are ordinary blocking ops and work anywhere; this is a -;; superset of the JVM model (no fixed thread pool, no pending-op limit). - -(ns clojure.core.async - (:refer-clojure :exclude [reduce transduce into merge map take partition partition-by])) - -;; --- alts ------------------------------------------------------------------- -;; do-alts polls each port non-blockingly under its own channel lock; the first -;; ready op wins. A take port is ready when a value (or closed nil) is available; -;; a put spec [ch val] is ready when the value can be offered. Polls with a 1ms -;; backoff (no cross-channel wait-set). - -(defn- alt-attempt [port] - (if (vector? port) - (let [ch (nth port 0) v (nth port 1)] - (assert (some? v) "Can't put nil on channel") - (let [r (clojure.core.async/__offer! ch v)] ; true | false (closed) | nil (would block) - (when (some? r) [r ch]))) - (let [r (clojure.core.async/__poll! port)] ; value | nil (closed) | ::none - (when (not= r ::none) [r port])))) - -(defn do-alts - "Returns [val port] for the first ready op among ports. ports is a vector of - take ports and/or [channel val] put specs. opts may include :priority true - (try in order) and :default val (return [val :default] if none ready)." - [ports opts] - (assert (pos? (count ports)) "alts must have at least one channel operation") - (let [ports (vec ports) - n (count ports) - priority (:priority opts) - has-default (contains? opts :default)] - ;; Scan ports from a random start (sequential, wrapping) so a non-priority alts - ;; is fair without allocating a fresh shuffle every poll. With :priority the scan - ;; starts at 0 (declared order). Returns the first ready op. - (loop [first? true] - (let [start (if priority 0 (rand-int n)) - hit (loop [k 0] - (when (< k n) - (let [j (+ start k) i (if (< j n) j (- j n))] - (or (alt-attempt (nth ports i)) - (recur (inc k))))))] - (cond - hit hit - (and first? has-default) [(:default opts) :default] - :else (do (Thread/sleep 1) (recur false))))))) - -(defn alts!! - "Completes at most one of several channel operations. ports is a vector of take - ports and/or [channel val] put specs. Returns [val port]. Blocks until ready." - [ports & {:as opts}] - (do-alts ports opts)) - -(defn alts! - "Like alts!!. In jolt a go block is a real thread, so parking and blocking alts - are the same operation." - [ports & {:as opts}] - (do-alts ports opts)) - -(defn poll! - "Takes a val from port if possible immediately. Never blocks. Returns the value - or nil." - [port] - (let [r (clojure.core.async/__poll! port)] - (when (not= r ::none) r))) - -;; --- thread variants -------------------------------------------------------- - -(defn thread-call - "Executes f in another thread, returning a channel that receives f's result then - closes." - ([f] (clojure.core.async/go-spawn f)) - ([f _workload] (clojure.core.async/go-spawn f))) - -(defmacro io-thread - "Executes body in another thread, returning a channel that receives the result - then closes." - [& body] - `(thread-call (fn [] ~@body) :io)) - -;; --- pipe / pipeline -------------------------------------------------------- - -(defn pipe - "Takes elements from the from channel and supplies them to the to channel. - Closes to when from closes unless close? is false." - ([from to] (pipe from to true)) - ([from to close?] - (go-loop [] - (let [v (! to v) - (recur))))) - to)) - -(defn- pipeline* - [n to xf from close? ex-handler type] - (assert (pos? n)) - (let [jobs (chan n) - results (chan n) - process (fn [job] - (if (nil? job) - (do (close! results) nil) - (let [v (nth job 0) p (nth job 1) - res (chan 1 xf ex-handler)] - (>!! res v) - (close! res) - (put! p res) - true))) - afn (fn [job] - (if (nil? job) - (do (close! results) nil) - (let [v (nth job 0) p (nth job 1) - res (chan 1)] - (xf v res) - (put! p res) - true)))] - (dotimes [_ n] - (case type - (:blocking :compute) (thread - (loop [] - (let [job (! jobs [v p]) - (>! results p) - (recur))))) - (go-loop [] - (let [p (! to v)) - (recur)))) - (recur))))))) - -(defn pipeline - "Takes elements from from, applies transducer xf with parallelism n, supplies to - to. Outputs are ordered relative to inputs." - ([n to xf from] (pipeline n to xf from true)) - ([n to xf from close?] (pipeline n to xf from close? nil)) - ([n to xf from close? ex-handler] (pipeline* n to xf from close? ex-handler :compute))) - -(defn pipeline-blocking - "Like pipeline, for blocking operations." - ([n to xf from] (pipeline-blocking n to xf from true)) - ([n to xf from close?] (pipeline-blocking n to xf from close? nil)) - ([n to xf from close? ex-handler] (pipeline* n to xf from close? ex-handler :blocking))) - -(defn pipeline-async - "Like pipeline, for async fns af of two args [input result-channel]." - ([n to af from] (pipeline-async n to af from true)) - ([n to af from close?] (pipeline* n to af from close? nil :async))) - -(defn split - "Splits ch by predicate p into [true-chan false-chan]." - ([p ch] (split p ch nil nil)) - ([p ch t-buf-or-n f-buf-or-n] - (let [tc (chan t-buf-or-n) - fc (chan f-buf-or-n)] - (go-loop [] - (let [v (! (if (p v) tc fc) v) - (recur))))) - [tc fc]))) - -;; --- reduce / transduce / collection sinks ---------------------------------- - -(defn reduce - "Returns a channel with the single result of reducing ch with f from init." - [f init ch] - (go-loop [ret init] - (let [v (! ch (first vs))) - (recur (next vs)) - (when close? - (close! ch)))))) - -(defn to-chan! - "Returns a channel containing the contents of coll, closing when exhausted." - [coll] - (let [c (bounded-count 100 coll)] - (if (pos? c) - (let [ch (chan c)] - (onto-chan! ch coll) - ch) - (let [ch (chan)] - (close! ch) - ch)))) - -(defn onto-chan!! - "Like onto-chan! for use when accessing coll might block." - ([ch coll] (onto-chan!! ch coll true)) - ([ch coll close?] - (thread - (loop [vs (seq coll)] - (if (and vs (>!! ch (first vs))) - (recur (next vs)) - (when close? - (close! ch))))))) - -(defn to-chan!! - "Like to-chan! for use when accessing coll might block." - [coll] - (let [c (bounded-count 100 coll)] - (if (pos? c) - (let [ch (chan c)] - (onto-chan!! ch coll) - ch) - (let [ch (chan)] - (close! ch) - ch)))) - -(defn onto-chan - "Deprecated - use onto-chan! or onto-chan!!" - ([ch coll] (onto-chan! ch coll true)) - ([ch coll close?] (onto-chan! ch coll close?))) - -(defn to-chan - "Deprecated - use to-chan! or to-chan!!" - [coll] - (to-chan! coll)) - -(defn into - "Returns a channel with the single collection result of conjoining items from ch - onto coll. ch must close first." - [coll ch] - (reduce conj coll ch)) - -(defn take - "Returns a channel that returns at most n items from ch, then closes." - ([n ch] (take n ch nil)) - ([n ch buf-or-n] - (let [out (chan buf-or-n)] - (go (loop [x 0] - (when (< x n) - (let [v (! out v) - (recur (inc x)))))) - (close! out)) - out))) - -;; --- mult / tap ------------------------------------------------------------- - -(defprotocol Mux - (muxch* [_])) - -(defprotocol Mult - (tap* [m ch close?]) - (untap* [m ch]) - (untap-all* [m])) - -(defn mult - "Creates a mult of ch. Copies can be created with tap and removed with untap. - Each item is distributed to all taps synchronously." - [ch] - (let [cs (atom {}) - m (reify - Mux - (muxch* [_] ch) - Mult - (tap* [_ ch close?] (swap! cs assoc ch close?) nil) - (untap* [_ ch] (swap! cs dissoc ch) nil) - (untap-all* [_] (reset! cs {}) nil)) - dchan (chan 1) - dctr (atom nil) - done (fn [_] (when (zero? (swap! dctr dec)) - (put! dchan true)))] - (go-loop [] - (let [val (! out v) - (recur state)) - (recur state))))) - m)) - -(defn admix - "Adds ch as an input to the mix." - [mix ch] - (admix* mix ch)) - -(defn unmix - "Removes ch as an input to the mix." - [mix ch] - (unmix* mix ch)) - -(defn unmix-all - "Removes all inputs from the mix." - [mix] - (unmix-all* mix)) - -(defn toggle - "Atomically sets the state of one or more channels in a mix." - [mix state-map] - (toggle* mix state-map)) - -(defn solo-mode - "Sets the solo mode of the mix (:mute or :pause)." - [mix mode] - (solo-mode* mix mode)) - -;; --- pub / sub -------------------------------------------------------------- - -(defprotocol Pub - (sub* [p v ch close?]) - (unsub* [p v ch]) - (unsub-all* [p] [p v])) - -(defn pub - "Creates a pub of ch partitioned by topic-fn. Subscribe with sub." - ([ch topic-fn] (pub ch topic-fn (constantly nil))) - ([ch topic-fn buf-fn] - (let [mults (atom {}) - ensure-mult (fn [topic] - (or (get @mults topic) - (get (swap! mults - #(if (% topic) % (assoc % topic (mult (chan (buf-fn topic)))))) - topic))) - p (reify - Mux - (muxch* [_] ch) - Pub - (sub* [_p topic ch close?] - (let [m (ensure-mult topic)] - (tap m ch close?))) - (unsub* [_p topic ch] - (when-let [m (get @mults topic)] - (untap m ch))) - (unsub-all* [_] (reset! mults {})) - (unsub-all* [_ topic] (swap! mults dissoc topic)))] - (go-loop [] - (let [val (! (muxch* m) val) - (swap! mults dissoc topic))) - (recur))))) - p))) - -(defn sub - "Subscribes ch to a topic of pub p." - ([p topic ch] (sub p topic ch true)) - ([p topic ch close?] (sub* p topic ch close?))) - -(defn unsub - "Unsubscribes ch from a topic of pub p." - [p topic ch] - (unsub* p topic ch)) - -(defn unsub-all - "Unsubscribes all channels from a pub, or from a topic." - ([p] (unsub-all* p)) - ([p topic] (unsub-all* p topic))) - -;; --- map / merge ------------------------------------------------------------ - -(defn map - "Applies f to the set of first items from each source channel, then second, etc. - Closes the output channel when any source closes." - ([f chs] (map f chs nil)) - ([f chs buf-or-n] - (let [chs (vec chs) - out (chan buf-or-n) - cnt (count chs) - rets (atom (vec (repeat cnt nil))) - dchan (chan 1) - dctr (atom nil) - done (mapv (fn [i] - (fn [ret] - (swap! rets assoc i ret) - (when (zero? (swap! dctr dec)) - (put! dchan @rets)))) - (range cnt))] - (if (zero? cnt) - (close! out) - (go-loop [] - (reset! dctr cnt) - (dotimes [i cnt] - (take! (nth chs i) (nth done i))) - (let [rets (! out (apply f rets)) - (recur)))))) - out))) - -(defn merge - "Returns a channel with all values taken from the source channels chs. Closes - after all sources close." - ([chs] (merge chs nil)) - ([chs buf-or-n] - (let [out (chan buf-or-n)] - (go-loop [cs (vec chs)] - (if (pos? (count cs)) - (let [[v c] (alts! cs)] - (if (nil? v) - (recur (filterv #(not= c %) cs)) - (do (>! out v) - (recur cs)))) - (close! out))) - out))) - -;; --- deprecated channel ops (rewritten as go-loops) ------------------------- - -(defn map< - "Deprecated - use a transducer. Returns a read-side channel mapping f over ch." - [f ch] - (let [out (chan)] - (go-loop [] - (let [v (! out (f v)) (recur))))) - out)) - -(defn map> - "Deprecated - use a transducer. Returns a write-side channel mapping f into out." - [f out] - (let [in (chan)] - (go-loop [] - (let [v (! out (f v)) (recur))))) - in)) - -(defn filter< - "Deprecated - use a transducer." - ([p ch] (filter< p ch nil)) - ([p ch buf-or-n] - (let [out (chan buf-or-n)] - (go-loop [] - (let [val (! out val)) - (recur))))) - out))) - -(defn remove< - "Deprecated - use a transducer." - ([p ch] (remove< p ch nil)) - ([p ch buf-or-n] (filter< (complement p) ch buf-or-n))) - -(defn filter> - "Deprecated - use a transducer." - [p out] - (let [in (chan)] - (go-loop [] - (let [v (! out v)) - (recur))))) - in)) - -(defn remove> - "Deprecated - use a transducer." - [p out] - (filter> (complement p) out)) - -(defn- mapcat* [f in out] - (go-loop [] - (let [val (! out v)) - (recur)))))) - -(defn mapcat< - "Deprecated - use a transducer." - ([f in] (mapcat< f in nil)) - ([f in buf-or-n] - (let [out (chan buf-or-n)] - (mapcat* f in out) - out))) - -(defn mapcat> - "Deprecated - use a transducer." - ([f out] (mapcat> f out nil)) - ([f out buf-or-n] - (let [in (chan buf-or-n)] - (mapcat* f in out) - in))) - -(defn unique - "Deprecated - use a transducer. Drops consecutive duplicates." - ([ch] (unique ch nil)) - ([ch buf-or-n] - (let [out (chan buf-or-n)] - (go (loop [last nil] - (let [v (! out v) - (recur v)))))) - (close! out)) - out))) - -(defn partition - "Deprecated - use a transducer. Partitions ch into vectors of n." - ([n ch] (partition n ch nil)) - ([n ch buf-or-n] - (let [out (chan buf-or-n)] - (go-loop [arr [] idx 0] - (let [v (! out arr) (recur [] 0)))) - (do (when (> idx 0) (>! out arr)) - (close! out))))) - out))) - -(defn partition-by - "Deprecated - use a transducer. Partitions ch by runs of (f v)." - ([f ch] (partition-by f ch nil)) - ([f ch buf-or-n] - (let [out (chan buf-or-n)] - (go-loop [lst [] last ::nothing] - (let [v (! out lst) (recur [v] new-itm)))) - (do (when (> (count lst) 0) (>! out lst)) - (close! out))))) - out))) diff --git a/stdlib/clojure/core/async/lab.clj b/stdlib/clojure/core/async/lab.clj deleted file mode 100644 index b8c8890..0000000 --- a/stdlib/clojure/core/async/lab.clj +++ /dev/null @@ -1,34 +0,0 @@ -;; clojure.core.async.lab — experimental features over the channel primitives. -;; -;; multiplex/broadcast are ported as go-loops over jolt's primitives (the JVM -;; versions reify the impl handler protocol, which jolt does not expose). - -(ns clojure.core.async.lab - (:require [clojure.core.async :as async])) - -(defn multiplex - "Returns a read port that yields values from whichever of ports is ready. A - closed port is dropped; the multiplex port closes once all ports have closed." - [& ports] - (let [out (async/chan)] - (async/go-loop [cs (vec ports)] - (if (pos? (count cs)) - (let [[v c] (async/alts! cs)] - (if (nil? v) - (recur (filterv #(not= c %) cs)) - (do (async/>! out v) - (recur cs)))) - (async/close! out))) - out)) - -(defn broadcast - "Returns a write port that writes each value to all of ports. A write parks until - the value has been written to every port." - [& ports] - (let [in (async/chan)] - (async/go-loop [] - (let [v (async/! p v)) - (recur)))) - in)) diff --git a/stdlib/clojure/edn.clj b/stdlib/clojure/edn.clj deleted file mode 100644 index 823a6a4..0000000 --- a/stdlib/clojure/edn.clj +++ /dev/null @@ -1,93 +0,0 @@ -;; clojure.edn — reading EDN data. Delegates to the Jolt reader via -;; clojure.core/read-string (which parses, never evaluates — safe for EDN), and -;; adds the opts-map arity with :eof plus nil/blank-input handling. -(ns clojure.edn - "Reading EDN data." - (:require [clojure.string :as cstr])) - -;; The reader yields set literals as a FORM ({:jolt/type :jolt/set :value [...]}) -;; rather than a constructed set, so build the actual values, recursing into -;; maps/vectors/lists. (Lists stay lists — EDN never evaluates them as code.) -;; Re-attach the source value's metadata to each rebuilt collection — read-string -;; preserves reader metadata (^:ref […]) but this rebuild would otherwise drop it, -;; which a metadata-driven config lib (aero/integrant) relies on. -(defn- edn->value [opts x] - (cond - ;; Reader FORMS are detected by :jolt/type tag, never by map? — strict map? - ;; (correctly) excludes tagged structs, so the old (and (map? x) ...) guard - ;; would skip them. - (= :jolt/set (get x :jolt/type)) - (let [vs (map (fn [v] (edn->value opts v)) (get x :value)) - st (set vs)] - ;; duplicate literal elements are invalid edn - (when (< (count st) (count vs)) - (throw (new IllegalArgumentException - (str "Duplicate key: " (pr-str (some (fn [[k n]] (when (< 1 n) k)) - (frequencies vs))))))) - (with-meta st (edn->value opts (meta x)))) - ;; Tagged elements: a reader from the :readers opt wins, then the built-in - ;; data readers (#uuid/#inst + registered); an unknown tag falls to the - ;; :default opt fn (called with tag and value, as in Clojure) or throws. - (= :jolt/tagged (get x :jolt/type)) - (let [tag (get x :tag) - v (edn->value opts (get x :form)) - ;; the reader stores the tag as a :#name keyword; :readers maps are - ;; keyed by the SYMBOL (Clojure's shape) — normalize for lookup - tag-sym (let [n (name tag)] - (symbol (if (= "#" (subs n 0 1)) (subs n 1) n))) - custom (get (get opts :readers) tag-sym)] - (cond - custom (custom v) - ;; the built-in edn tags win over :default (a :readers entry can - ;; override them; an unknown-tag :default never sees #inst/#uuid) - (contains? #{'inst 'uuid 'bigdec} tag-sym) (__read-tagged tag v) - ;; Clojure calls :default with the tag as a SYMBOL and the value. - (get opts :default) ((get opts :default) tag-sym v) - :else (__read-tagged tag v))) - (map? x) - (with-meta (into {} (map (fn [e] [(edn->value opts (key e)) (edn->value opts (val e))]) x)) (edn->value opts (meta x))) - (vector? x) (with-meta (mapv (fn [v] (edn->value opts v)) x) (edn->value opts (meta x))) - ;; a constructed set: recurse into its elements too, so a tagged literal - ;; inside #{…} gets the :readers/:default treatment (aero's #ref in a set). - (set? x) (with-meta (set (map (fn [v] (edn->value opts v)) x)) (edn->value opts (meta x))) - ;; edn lists are lists (list? holds), not lazy seqs - (seq? x) (with-meta (apply list (map (fn [v] (edn->value opts v)) x)) (edn->value opts (meta x))) - :else x)) - -;; Private helper, NOT named read-string: an unqualified (read-string …) call -;; dispatches the core read-string SPECIAL FORM (by name, regardless of ns), so -;; the 1-arity can't delegate to the 2-arity through that name. -(defn- read-edn [opts s] - ;; the strict edn seam: no auto-resolved keywords, invalid tokens throw, and - ;; each #_ discard is validated through the same :readers/:default pipeline. - ;; EOF (blank/comment-only/nil input) honors :eof; an opts map WITHOUT :eof - ;; makes end-of-input an error, like the reference. - (let [v (__read-form-edn s (fn [form] (edn->value opts form) nil))] - (if (= v :jolt/reader-eof) - (if (contains? opts :eof) - (get opts :eof) - (throw (ex-info "EOF while reading" {}))) - (edn->value opts v)))) - -(defn read-string - "Reads one object from the string s. The no-opts arity returns nil at end of - input; with an opts map, :eof sets the value returned at end of input and its - absence makes end-of-input an error." - ([s] (read-edn {:eof nil} s)) - ([opts s] (read-edn opts s))) - -(defn- drain-reader - "All remaining content of a reader as a string. Shim readers (StringReader, - PushbackReader, io/reader results) expose char-wise .read; a raw file - handle is read whole." - [reader] - (loop [acc (transient []) c (.read reader)] - (if (== -1 c) - (apply str (map char (persistent! acc))) - (recur (conj! acc c) (.read reader))))) - -(defn read - "Reads one EDN object from reader (a PushbackReader or any jolt reader). - Returns the :eof option value (default nil) at end of input." - ([reader] (read {} reader)) - ([opts reader] (read-edn opts (drain-reader reader)))) diff --git a/stdlib/clojure/pprint.clj b/stdlib/clojure/pprint.clj deleted file mode 100644 index a315256..0000000 --- a/stdlib/clojure/pprint.clj +++ /dev/null @@ -1,1881 +0,0 @@ -;; clojure.pprint — a column-aware pretty printer and a Common Lisp compatible -;; cl-format. The writer accumulates into a StringBuilder; pprint/write/cl-format -;; bind *out* (this ns's own dynamic binding) to a pretty-writer over it and emit -;; the result through clojure.core/print, so with-out-str captures it. -;; -;; Native print is not involved: this ns defines its own print/pr/prn/println -;; that route through (-write *out* ...). -(ns clojure.pprint - (:refer-clojure :exclude [deftype print println pr prn])) - -;;====================================================================== -;; Macros (must precede their first use) -;;====================================================================== - -(defmacro getf - "Get the value of the field named by the keyword sym from *out*'s field atom." - [sym] - `(~sym (deref (.-fields ~'this)))) - -(defmacro setf - "Set the value of field sym in *out*'s field atom." - [sym new-val] - `(swap! (.-fields ~'this) assoc ~sym ~new-val)) - -(defmacro deftype - "Builds a defrecord plus make-X / X? helpers (a tagged record used as a - pretty-printer buffer token)." - [type-name & fields] - (let [name-str (name type-name) - fields (map (comp symbol name) fields)] - `(do - (defrecord ~type-name [~'type-tag ~@fields]) - (defn- ~(symbol (str "make-" name-str)) - ~(vec fields) - (~(symbol (str "->" type-name)) ~(keyword name-str) ~@fields)) - (defn- ~(symbol (str name-str "?")) [x#] (= (:type-tag x#) ~(keyword name-str)))))) - -(defmacro pprint-logical-block - "Execute body as a pretty-printing logical block, output to *out* which must be - a pretty-printing writer. Options :prefix, :per-line-prefix and :suffix may - precede the body." - [& args] - (let [[options body] (loop [body args acc []] - (if (#{:prefix :per-line-prefix :suffix} (first body)) - (recur (drop 2 body) (concat acc (take 2 body))) - [(apply hash-map acc) body]))] - `(do (if (clojure.pprint/level-exceeded) - (-write clojure.core/*out* "#") - (clojure.core/binding [clojure.pprint/*current-level* (inc clojure.pprint/*current-level*) - clojure.pprint/*current-length* 0] - (clojure.pprint/start-block clojure.core/*out* - ~(:prefix options) - ~(:per-line-prefix options) - ~(:suffix options)) - ~@body - (clojure.pprint/end-block clojure.core/*out*))) - nil))) - -(defmacro print-length-loop - "A loop for pretty-printer dispatch functions. (Length limiting via - *print-length* is enforced by write-out, not by truncating the loop.)" - [bindings & body] - `(loop ~bindings ~@body)) - -(defmacro formatter-out - "Returns a function (fn [& args]) that runs the compiled format against *out*. - format-in is a control string or a previously compiled format." - [format-in] - `(let [format-in# ~format-in - cf# (if (string? format-in#) (clojure.pprint/cached-compile format-in#) format-in#)] - (fn [& args#] - (let [navigator# (clojure.pprint/init-navigator args#)] - (clojure.pprint/execute-format cf# navigator#))))) - -(defmacro formatter - "Returns a function (fn [stream & args]) that runs the compiled format." - [format-in] - `(let [format-in# ~format-in - cf# (if (string? format-in#) (clojure.pprint/cached-compile format-in#) format-in#)] - (fn [stream# & args#] - (let [navigator# (clojure.pprint/init-navigator args#)] - (clojure.pprint/execute-format stream# cf# navigator#))))) - -(defmacro with-pprint-dispatch - "Execute body with the pretty-print dispatch function bound to function. A - non-function dispatch (e.g. a keyword) is accepted and ignored." - [function & body] - `(clojure.core/binding [clojure.pprint/*print-pprint-dispatch* ~function] - ~@body)) - -(defmacro pp - "Pretty print the last REPL result. (jolt has no *1, so this is a no-op stub.)" - [] `nil) - -;;====================================================================== -;; print fns that route through *out* -;;====================================================================== - -(defn- print [& more] - (-write *out* (apply print-str more))) - -(defn- println [& more] - (apply print more) - (-write *out* "\n")) - -(defn- print-char [c] - (-write *out* (condp = c - \backspace "\\backspace" - \space "\\space" - \tab "\\tab" - \newline "\\newline" - \formfeed "\\formfeed" - \return "\\return" - \" "\\\"" - \\ "\\\\" - (str "\\" c)))) - -(defn- ^:dynamic pr [& more] - (-write *out* (apply pr-str more))) - -(defn- prn [& more] - (apply pr more) - (-write *out* "\n")) - -;;====================================================================== -;; utils -;;====================================================================== - -(defn- float? [n] - (and (number? n) - (not (integer? n)))) - -(defn- char-code [c] - (cond - (number? c) c - (char? c) (int c) - (and (string? c) (= (count c) 1)) (int (.charAt c 0)) - :else (throw (Exception. "Argument to char must be a character or number")))) - -(defn- map-passing-context [func initial-context lis] - (loop [context initial-context - lis lis - acc []] - (if (empty? lis) - [acc context] - (let [this (first lis) - remainder (next lis) - [result new-context] (apply func [this context])] - (recur new-context remainder (conj acc result)))))) - -(defn- consume [func initial-context] - (loop [context initial-context - acc []] - (let [[result new-context] (apply func [context])] - (if (not result) - [acc new-context] - (recur new-context (conj acc result)))))) - -(defn- unzip-map [m] - [(into {} (for [[k [v1 v2]] m] [k v1])) - (into {} (for [[k [v1 v2]] m] [k v2]))]) - -(defn- tuple-map [m v1] - (into {} (for [[k v] m] [k [v v1]]))) - -(defn- rtrim [s c] - (let [len (count s)] - (if (and (pos? len) (= (nth s (dec (count s))) c)) - (loop [n (dec len)] - (cond - (neg? n) "" - (not (= (nth s n) c)) (subs s 0 (inc n)) - true (recur (dec n)))) - s))) - -(defn- ltrim [s c] - (let [len (count s)] - (if (and (pos? len) (= (nth s 0) c)) - (loop [n 0] - (if (or (= n len) (not (= (nth s n) c))) - (subs s n) - (recur (inc n)))) - s))) - -(defn- prefix-count [aseq val] - (let [test (if (coll? val) (set val) #{val})] - (loop [pos 0] - (if (or (= pos (count aseq)) (not (test (nth aseq pos)))) - pos - (recur (inc pos)))))) - -(defprotocol IPrettyFlush - (-ppflush [pp])) - -(defprotocol IPrettyWriter - (-write [w x]) - (-pflush [w])) - -;;====================================================================== -;; column writer -;;====================================================================== - -(def ^:dynamic ^{:private true} *default-page-width* 72) - -(defn- get-field [this sym] - (sym (deref (.-fields this)))) - -(defn- set-field [this sym new-val] - (swap! (.-fields this) assoc sym new-val)) - -(defn- get-column [this] - (get-field this :cur)) - -(defn- get-line [this] - (get-field this :line)) - -(defn- get-max-column [this] - (get-field this :max)) - -(defn- set-max-column [this new-max] - (set-field this :max new-max) - nil) - -(defn- get-writer [this] - (get-field this :base)) - -(defn- c-write-char [this c] - (if (= c \newline) - (do - (set-field this :cur 0) - (set-field this :line (inc (get-field this :line)))) - (set-field this :cur (inc (get-field this :cur)))) - (-write (get-field this :base) c)) - -;; the base sink: accumulates into a StringBuilder. Columns are tracked by the -;; column-writer that wraps it; this just appends. -(defrecord StringBufferWriter [sb] - IPrettyWriter - (-write [_ x] - (.append sb (if (char? x) (str x) x)) - nil) - (-pflush [_] nil) - IPrettyFlush - (-ppflush [_] nil)) - -(defrecord ColumnWriter [fields] - IPrettyWriter - (-write [this x] - (cond - (string? x) - (let [s x - nl (.lastIndexOf s "\n")] - (if (neg? nl) - (set-field this :cur (+ (get-field this :cur) (count s))) - (do - (set-field this :cur (- (count s) nl 1)) - (set-field this :line (+ (get-field this :line) - (count (filter #(= % \newline) s)))))) - (-write (get-field this :base) s)) - (or (char? x) (number? x)) - (c-write-char this x))) - (-pflush [this] (-pflush (get-field this :base))) - IPrettyFlush - (-ppflush [_] nil)) - -(defn- column-writer - ([writer] (column-writer writer *default-page-width*)) - ([writer max-columns] - (->ColumnWriter (atom {:max max-columns :cur 0 :line 0 :base writer})))) - -;;====================================================================== -;; pretty writer -;;====================================================================== - -(declare ^{:arglists '([this])} get-miser-width) - -(defrecord logical-block - [parent section start-col indent - done-nl intra-block-nl - prefix per-line-prefix suffix - logical-block-callback]) - -(defn- ancestor? [parent child] - (loop [child (:parent child)] - (cond - (nil? child) false - (identical? parent child) true - :else (recur (:parent child))))) - -(defn- buffer-length [l] - (let [l (seq l)] - (if l - (- (:end-pos (last l)) (:start-pos (first l))) - 0))) - -(deftype buffer-blob :data :trailing-white-space :start-pos :end-pos) -(deftype nl-t :type :logical-block :start-pos :end-pos) -(deftype start-block-t :logical-block :start-pos :end-pos) -(deftype end-block-t :logical-block :start-pos :end-pos) -(deftype indent-t :logical-block :relative-to :offset :start-pos :end-pos) - -(def ^:private pp-newline (fn [] "\n")) - -(declare emit-nl) - -(defmulti ^{:private true} write-token (fn [this token] (:type-tag token))) - -(defmethod write-token :start-block-t [this token] - (when-let [cb (getf :logical-block-callback)] (cb :start)) - (let [lb (:logical-block token)] - (when-let [prefix (:prefix lb)] - (-write (getf :base) prefix)) - (let [col (get-column (getf :base))] - (reset! (:start-col lb) col) - (reset! (:indent lb) col)))) - -(defmethod write-token :end-block-t [this token] - (when-let [cb (getf :logical-block-callback)] (cb :end)) - (when-let [suffix (:suffix (:logical-block token))] - (-write (getf :base) suffix))) - -(defmethod write-token :indent-t [this token] - (let [lb (:logical-block token)] - (reset! (:indent lb) - (+ (:offset token) - (condp = (:relative-to token) - :block @(:start-col lb) - :current (get-column (getf :base))))))) - -(defmethod write-token :buffer-blob [this token] - (-write (getf :base) (:data token))) - -(defmethod write-token :nl-t [this token] - (if (or (= (:type token) :mandatory) - (and (not (= (:type token) :fill)) - @(:done-nl (:logical-block token)))) - (emit-nl this token) - (if-let [tws (getf :trailing-white-space)] - (-write (getf :base) tws))) - (setf :trailing-white-space nil)) - -(defn- write-tokens [this tokens force-trailing-whitespace] - (doseq [token tokens] - (if-not (= (:type-tag token) :nl-t) - (if-let [tws (getf :trailing-white-space)] - (-write (getf :base) tws))) - (write-token this token) - (setf :trailing-white-space (:trailing-white-space token)) - (let [tws (getf :trailing-white-space)] - (when (and force-trailing-whitespace tws) - (-write (getf :base) tws) - (setf :trailing-white-space nil))))) - -(defn- tokens-fit? [this tokens] - (let [maxcol (get-max-column (getf :base))] - (or - (nil? maxcol) - (< (+ (get-column (getf :base)) (buffer-length tokens)) maxcol)))) - -(defn- linear-nl? [this lb section] - (or @(:done-nl lb) - (not (tokens-fit? this section)))) - -(defn- miser-nl? [this lb section] - (let [miser-width (get-miser-width this) - maxcol (get-max-column (getf :base))] - (and miser-width maxcol - (>= @(:start-col lb) (- maxcol miser-width)) - (linear-nl? this lb section)))) - -(defmulti ^{:private true} emit-nl? (fn [t _ _ _] (:type t))) - -(defmethod emit-nl? :linear [newl this section _] - (let [lb (:logical-block newl)] - (linear-nl? this lb section))) - -(defmethod emit-nl? :miser [newl this section _] - (let [lb (:logical-block newl)] - (miser-nl? this lb section))) - -(defmethod emit-nl? :fill [newl this section subsection] - (let [lb (:logical-block newl)] - (or @(:intra-block-nl lb) - (not (tokens-fit? this subsection)) - (miser-nl? this lb section)))) - -(defmethod emit-nl? :mandatory [_ _ _ _] - true) - -(defn- get-section [buffer] - (let [nl (first buffer) - lb (:logical-block nl) - section (seq (take-while #(not (and (nl-t? %) (ancestor? (:logical-block %) lb))) - (next buffer)))] - [section (seq (drop (inc (count section)) buffer))])) - -(defn- get-sub-section [buffer] - (let [nl (first buffer) - lb (:logical-block nl) - section (seq (take-while #(let [nl-lb (:logical-block %)] - (not (and (nl-t? %) (or (= nl-lb lb) (ancestor? nl-lb lb))))) - (next buffer)))] - section)) - -(defn- update-nl-state [lb] - (reset! (:intra-block-nl lb) true) - (reset! (:done-nl lb) true) - (loop [lb (:parent lb)] - (if lb - (do (reset! (:done-nl lb) true) - (reset! (:intra-block-nl lb) true) - (recur (:parent lb)))))) - -(defn- emit-nl [this nl] - (-write (getf :base) (pp-newline)) - (setf :trailing-white-space nil) - (let [lb (:logical-block nl) - prefix (:per-line-prefix lb)] - (if prefix - (-write (getf :base) prefix)) - (let [istr (apply str (repeat (- @(:indent lb) (count prefix)) \space))] - (-write (getf :base) istr)) - (update-nl-state lb))) - -(defn- split-at-newline [tokens] - (let [pre (seq (take-while #(not (nl-t? %)) tokens))] - [pre (seq (drop (count pre) tokens))])) - -(defn- write-token-string [this tokens] - (let [[a b] (split-at-newline tokens)] - (if a (write-tokens this a false)) - (if b - (let [[section remainder] (get-section b) - newl (first b)] - (let [do-nl (emit-nl? newl this section (get-sub-section b)) - result (if do-nl - (do - (emit-nl this newl) - (next b)) - b) - long-section (not (tokens-fit? this result)) - result (if long-section - (let [rem2 (write-token-string this section)] - (if (= rem2 section) - (do - (write-tokens this section false) - remainder) - (into [] (concat rem2 remainder)))) - result)] - result))))) - -(defn- write-line [this] - (loop [buffer (getf :buffer)] - (setf :buffer (into [] buffer)) - (if (not (tokens-fit? this buffer)) - (let [new-buffer (write-token-string this buffer)] - (if-not (identical? buffer new-buffer) - (recur new-buffer)))))) - -(defn- add-to-buffer [this token] - (setf :buffer (conj (getf :buffer) token)) - (if (not (tokens-fit? this (getf :buffer))) - (write-line this))) - -(defn- write-buffered-output [this] - (write-line this) - (if-let [buf (getf :buffer)] - (do - (write-tokens this buf true) - (setf :buffer [])))) - -(defn- write-white-space [this] - (when-let [tws (getf :trailing-white-space)] - (-write (getf :base) tws) - (setf :trailing-white-space nil))) - -(defn- write-initial-lines [this s] - (let [lines (clojure.string/split s #"\n" -1)] - (if (= (count lines) 1) - s - (let [prefix (:per-line-prefix (first (getf :logical-blocks))) - l (first lines)] - (if (= :buffering (getf :mode)) - (let [oldpos (getf :pos) - newpos (+ oldpos (count l))] - (setf :pos newpos) - (add-to-buffer this (make-buffer-blob l nil oldpos newpos)) - (write-buffered-output this)) - (do - (write-white-space this) - (-write (getf :base) l))) - (-write (getf :base) "\n") - (doseq [l (next (butlast lines))] - (-write (getf :base) l) - (-write (getf :base) (pp-newline)) - (if prefix - (-write (getf :base) prefix))) - (setf :buffering :writing) - (last lines))))) - -(defn- p-write-char [this c] - (if (= (getf :mode) :writing) - (do - (write-white-space this) - (-write (getf :base) c)) - (if (= c \newline) - (write-initial-lines this "\n") - (let [oldpos (getf :pos) - newpos (inc oldpos)] - (setf :pos newpos) - (add-to-buffer this (make-buffer-blob (str c) nil oldpos newpos)))))) - -(defrecord PrettyWriter [fields] - IPrettyWriter - (-write [this x] - (cond - (string? x) - (let [s0 (write-initial-lines this x) - s (clojure.string/replace-first s0 #"\s+$" "") - white-space (subs s0 (count s)) - mode (getf :mode)] - (if (= mode :writing) - (do - (write-white-space this) - (-write (getf :base) s) - (setf :trailing-white-space white-space)) - (let [oldpos (getf :pos) - newpos (+ oldpos (count s0))] - (setf :pos newpos) - (add-to-buffer this (make-buffer-blob s white-space oldpos newpos))))) - (or (char? x) (number? x)) - (p-write-char this x))) - (-pflush [this] - (-ppflush this) - (-pflush (getf :base))) - IPrettyFlush - (-ppflush [this] - (if (= (getf :mode) :buffering) - (do - (write-tokens this (getf :buffer) true) - (setf :buffer [])) - (write-white-space this)))) - -(defn- pretty-writer [writer max-columns miser-width] - (let [lb (->logical-block nil nil (atom 0) (atom 0) (atom false) (atom false) - nil nil nil nil)] - (->PrettyWriter - (atom {:pretty-writer true - :base (column-writer writer max-columns) - :logical-blocks lb - :sections nil - :mode :writing - :buffer [] - :buffer-block lb - :buffer-level 1 - :miser-width miser-width - :trailing-white-space nil - :pos 0})))) - -(defn- start-block - [this prefix per-line-prefix suffix] - (let [lb (->logical-block (getf :logical-blocks) nil (atom 0) (atom 0) - (atom false) (atom false) - prefix per-line-prefix suffix nil)] - (setf :logical-blocks lb) - (if (= (getf :mode) :writing) - (do - (write-white-space this) - (when-let [cb (getf :logical-block-callback)] (cb :start)) - (if prefix - (-write (getf :base) prefix)) - (let [col (get-column (getf :base))] - (reset! (:start-col lb) col) - (reset! (:indent lb) col))) - (let [oldpos (getf :pos) - newpos (+ oldpos (if prefix (count prefix) 0))] - (setf :pos newpos) - (add-to-buffer this (make-start-block-t lb oldpos newpos)))))) - -(defn- end-block [this] - (let [lb (getf :logical-blocks) - suffix (:suffix lb)] - (if (= (getf :mode) :writing) - (do - (write-white-space this) - (if suffix - (-write (getf :base) suffix)) - (when-let [cb (getf :logical-block-callback)] (cb :end))) - (let [oldpos (getf :pos) - newpos (+ oldpos (if suffix (count suffix) 0))] - (setf :pos newpos) - (add-to-buffer this (make-end-block-t lb oldpos newpos)))) - (setf :logical-blocks (:parent lb)))) - -(defn- nl [this type] - (setf :mode :buffering) - (let [pos (getf :pos)] - (add-to-buffer this (make-nl-t type (getf :logical-blocks) pos pos)))) - -(defn- indent [this relative-to offset] - (let [lb (getf :logical-blocks)] - (if (= (getf :mode) :writing) - (do - (write-white-space this) - (reset! (:indent lb) - (+ offset (condp = relative-to - :block @(:start-col lb) - :current (get-column (getf :base)))))) - (let [pos (getf :pos)] - (add-to-buffer this (make-indent-t lb relative-to offset pos pos)))))) - -(defn- get-miser-width [this] - (getf :miser-width)) - -;;====================================================================== -;; pprint base -;;====================================================================== - -(def ^:dynamic *print-pretty* true) -(def ^:dynamic *print-pprint-dispatch* nil) -(def ^:dynamic *print-right-margin* 72) -(def ^:dynamic *print-miser-width* 40) -(def ^:dynamic ^{:private true} *print-lines* nil) -(def ^:dynamic ^{:private true} *print-circle* nil) -(def ^:dynamic ^{:private true} *print-shared* nil) -(def ^:dynamic *print-suppress-namespaces* nil) -(def ^:dynamic *print-radix* nil) -(def ^:dynamic *print-base* 10) -(def ^:dynamic ^{:private true} *current-level* 0) -(def ^:dynamic ^{:private true} *current-length* nil) - -;; jolt has no bindable clojure.core/*print-length* / *print-level* vars; define -;; them here so the printer-control machinery can bind and read them. -(def ^:dynamic *print-length* nil) -(def ^:dynamic *print-level* nil) - -(declare ^{:arglists '([n])} format-simple-number) - -(defn- pretty-writer? [x] - (and (instance? PrettyWriter x) (:pretty-writer (deref (.-fields x))))) - -(defn- make-pretty-writer [base-writer right-margin miser-width] - (pretty-writer base-writer right-margin miser-width)) - -(defmacro ^{:private true} with-pretty-writer [base-writer & body] - `(let [base-writer# ~base-writer - new-writer# (not (pretty-writer? base-writer#))] - (clojure.core/binding [clojure.core/*out* (if new-writer# - (make-pretty-writer base-writer# *print-right-margin* *print-miser-width*) - base-writer#)] - ;; route core print into this pretty-writer even under an outer - ;; with-out-str; nested pr-str/print-str re-suppress so their captures work - (clojure.core/__with-pprint-routing - (fn [] - ~@body - (-ppflush clojure.core/*out*)))))) - -(defn write-out - "Write an object to *out* subject to the current bindings of the printer control - variables. *out* must be a PrettyWriter when pretty printing is enabled." - [object] - (let [length-reached (and *current-length* - *print-length* - (>= *current-length* *print-length*))] - (if-not *print-pretty* - (pr object) - (if length-reached - (-write *out* "...") - (do - (if *current-length* (set! *current-length* (inc *current-length*))) - (*print-pprint-dispatch* object)))) - length-reached)) - -(defn write - "Write an object subject to the current bindings of the printer control - variables. Returns the string result if :stream is nil, nil otherwise." - [object & kw-args] - (let [options (merge {:stream true} (apply hash-map kw-args))] - (binding [clojure.pprint/*print-base* (get options :base clojure.pprint/*print-base*) - clojure.pprint/*print-circle* (get options :circle clojure.pprint/*print-circle*) - clojure.pprint/*print-length* (get options :length clojure.pprint/*print-length*) - clojure.pprint/*print-level* (get options :level clojure.pprint/*print-level*) - clojure.pprint/*print-lines* (get options :lines clojure.pprint/*print-lines*) - clojure.pprint/*print-miser-width* (get options :miser-width clojure.pprint/*print-miser-width*) - clojure.pprint/*print-pprint-dispatch* (get options :dispatch clojure.pprint/*print-pprint-dispatch*) - clojure.pprint/*print-pretty* (get options :pretty clojure.pprint/*print-pretty*) - clojure.pprint/*print-radix* (get options :radix clojure.pprint/*print-radix*) - clojure.core/*print-readably* (get options :readably clojure.core/*print-readably*) - clojure.pprint/*print-right-margin* (get options :right-margin clojure.pprint/*print-right-margin*) - clojure.pprint/*print-suppress-namespaces* (get options :suppress-namespaces clojure.pprint/*print-suppress-namespaces*)] - (let [sb (StringBuilder.) - optval (if (contains? options :stream) - (:stream options) - true) - base-writer (if (or (true? optval) (nil? optval)) - (->StringBufferWriter sb) - optval)] - (if *print-pretty* - (with-pretty-writer base-writer - (write-out object)) - (binding [*out* base-writer] - (pr object))) - (if (true? optval) - (clojure.core/print (str sb))) - (if (nil? optval) - (str sb)))))) - -(defn pprint - "Pretty print object. With one arg, prints to *out* (captured by with-out-str). - The 2-arg form writes to the supplied pretty-writer." - ([object] - (let [sb (StringBuilder.)] - (binding [*out* (->StringBufferWriter sb)] - (pprint object *out*) - (clojure.core/print (str sb))))) - ([object writer] - (with-pretty-writer writer - (binding [*print-pretty* true] - (write-out object)) - (if (not (= 0 (get-column *out*))) - (-write *out* "\n"))))) - -(defn set-pprint-dispatch [function] - (set! *print-pprint-dispatch* function) - nil) - -(defn- check-enumerated-arg [arg choices] - (if-not (choices arg) - (throw (Exception. (str "Bad argument: " arg ". It must be one of " choices))))) - -(defn- level-exceeded [] - (and *print-level* (>= *current-level* *print-level*))) - -(defn pprint-newline - "Print a conditional newline (:linear :miser :fill or :mandatory) to *out*, - which must be a pretty-printing writer." - [kind] - (check-enumerated-arg kind #{:linear :miser :fill :mandatory}) - (nl *out* kind)) - -(defn pprint-indent - "Create an indent at this point in the pretty-printing stream. relative-to is - :block or :current; n is an offset." - [relative-to n] - (check-enumerated-arg relative-to #{:block :current}) - (indent *out* relative-to n)) - -(defn pprint-tab - [kind colnum colinc] - (check-enumerated-arg kind #{:line :section :line-relative :section-relative}) - (throw (Exception. "pprint-tab is not yet implemented"))) - -;;====================================================================== -;; cl-format -;;====================================================================== - -(declare ^{:arglists '([format-str])} compile-format) -(declare ^{:arglists '([stream format args] [format args])} execute-format) -(declare ^{:arglists '([s])} init-navigator) - -(defn cl-format - "A Common Lisp compatible format function. If writer is nil, returns the - formatted string; if true, prints to *out*; otherwise writes to writer." - [writer format-in & args] - (let [compiled-format (if (string? format-in) (compile-format format-in) format-in) - navigator (init-navigator args)] - (execute-format writer compiled-format navigator))) - -(def ^:dynamic ^{:private true} *format-str* nil) - -(defn- format-error [message offset] - (let [full-message (str message "\n" *format-str* "\n" - (apply str (repeat offset \space)) "^" "\n")] - (throw (Exception. full-message)))) - -(defrecord ^{:private true} arg-navigator [seq rest pos]) - -(defn- init-navigator [s] - (let [s (seq s)] - (->arg-navigator s s 0))) - -(defn- next-arg [navigator] - (let [rst (:rest navigator)] - (if rst - [(first rst) (->arg-navigator (:seq navigator) (next rst) (inc (:pos navigator)))] - (throw (Exception. "Not enough arguments for format definition"))))) - -(defn- next-arg-or-nil [navigator] - (let [rst (:rest navigator)] - (if rst - [(first rst) (->arg-navigator (:seq navigator) (next rst) (inc (:pos navigator)))] - [nil navigator]))) - -(defn- get-format-arg [navigator] - (let [[raw-format navigator] (next-arg navigator) - compiled-format (if (string? raw-format) - (compile-format raw-format) - raw-format)] - [compiled-format navigator])) - -(declare relative-reposition) - -(defn- absolute-reposition [navigator position] - (if (>= position (:pos navigator)) - (relative-reposition navigator (- (:pos navigator) position)) - (->arg-navigator (:seq navigator) (drop position (:seq navigator)) position))) - -(defn- relative-reposition [navigator position] - (let [newpos (+ (:pos navigator) position)] - (if (neg? position) - (absolute-reposition navigator newpos) - (->arg-navigator (:seq navigator) (drop position (:rest navigator)) newpos)))) - -(defrecord ^{:private true} compiled-directive [func dirdef params offset]) - -(defn- realize-parameter [[param [raw-val offset]] navigator] - (let [[real-param new-navigator] - (cond - (contains? #{:at :colon} param) - [raw-val navigator] - - (= raw-val :parameter-from-args) - (next-arg navigator) - - (= raw-val :remaining-arg-count) - [(count (:rest navigator)) navigator] - - true - [raw-val navigator])] - [[param [real-param offset]] new-navigator])) - -(defn- realize-parameter-list [parameter-map navigator] - (let [[pairs new-navigator] - (map-passing-context realize-parameter navigator parameter-map)] - [(into {} pairs) new-navigator])) - -(declare ^{:arglists '([base val])} opt-base-str) - -(def ^{:private true} - special-radix-markers {2 "#b" 8 "#o" 16 "#x"}) - -(defn- format-simple-number [n] - (cond - (integer? n) (if (= *print-base* 10) - (str n (if *print-radix* ".")) - (str - (if *print-radix* (or (get special-radix-markers *print-base*) (str "#" *print-base* "r"))) - (opt-base-str *print-base* n))) - :else nil)) - -(defn- format-ascii [print-func params arg-navigator offsets] - (let [[arg arg-navigator] (next-arg arg-navigator) - base-output (or (format-simple-number arg) (print-func arg)) - base-width (count base-output) - min-width (+ base-width (:minpad params)) - width (if (>= min-width (:mincol params)) - min-width - (+ min-width - (* (+ (quot (- (:mincol params) min-width 1) - (:colinc params)) - 1) - (:colinc params)))) - chars (apply str (repeat (- width base-width) (:padchar params)))] - (if (:at params) - (print (str chars base-output)) - (print (str base-output chars))) - arg-navigator)) - -(defn- integral? [x] - (cond - (integer? x) true - (float? x) (= x (Math/floor x)) - :else false)) - -(defn- remainders [base val] - (reverse - (first - (consume #(if (pos? %) - [(rem % base) (quot % base)] - [nil nil]) - val)))) - -(defn- base-str [base val] - (if (zero? val) - "0" - (apply str - (map - #(if (< % 10) (char (+ (char-code \0) %)) (char (+ (char-code \a) (- % 10)))) - (remainders base val))))) - -(defn- opt-base-str [base val] - (base-str base val)) - -(defn- group-by* [unit lis] - (reverse - (first - (consume (fn [x] [(seq (reverse (take unit x))) (seq (drop unit x))]) (reverse lis))))) - -(defn- format-integer [base params arg-navigator offsets] - (let [[arg arg-navigator] (next-arg arg-navigator)] - (if (integral? arg) - (let [neg (neg? arg) - pos-arg (if neg (- arg) arg) - raw-str (opt-base-str base pos-arg) - group-str (if (:colon params) - (let [groups (map #(apply str %) (group-by* (:commainterval params) raw-str)) - commas (repeat (count groups) (:commachar params))] - (apply str (next (interleave commas groups)))) - raw-str) - signed-str (cond - neg (str "-" group-str) - (:at params) (str "+" group-str) - true group-str) - padded-str (if (< (count signed-str) (:mincol params)) - (str (apply str (repeat (- (:mincol params) (count signed-str)) - (:padchar params))) - signed-str) - signed-str)] - (print padded-str)) - (format-ascii print-str {:mincol (:mincol params) :colinc 1 :minpad 0 - :padchar (:padchar params) :at true} - (init-navigator [arg]) nil)) - arg-navigator)) - -;; Check to see if a result is an abort (~^) construct -(defn- abort? [context] - (let [token (first context)] - (or (= :up-arrow token) (= :colon-up-arrow token)))) - -(defn- execute-sub-format [format args base-args] - (second - (map-passing-context - (fn [element context] - (if (abort? context) - [nil context] - (let [[params args] (realize-parameter-list (:params element) context) - [params offsets] (unzip-map params) - params (assoc params :base-args base-args)] - [nil (apply (:func element) [params args offsets])]))) - args - format))) - -;;---------------------------------------------------------------------- -;; conditional ~[...~] -;;---------------------------------------------------------------------- - -(defn- choice-conditional [params arg-navigator offsets] - (let [arg (:selector params) - [arg navigator] (if arg [arg arg-navigator] (next-arg arg-navigator)) - clauses (:clauses params) - clause (if (or (neg? arg) (>= arg (count clauses))) - (first (:else params)) - (nth clauses arg))] - (if clause - (execute-sub-format clause navigator (:base-args params)) - navigator))) - -(defn- boolean-conditional [params arg-navigator offsets] - (let [[arg navigator] (next-arg arg-navigator) - clauses (:clauses params) - clause (if arg - (second clauses) - (first clauses))] - (if clause - (execute-sub-format clause navigator (:base-args params)) - navigator))) - -(defn- check-arg-conditional [params arg-navigator offsets] - (let [[arg navigator] (next-arg arg-navigator) - clauses (:clauses params) - clause (if arg (first clauses))] - (if arg - (if clause - (execute-sub-format clause arg-navigator (:base-args params)) - arg-navigator) - navigator))) - -;;---------------------------------------------------------------------- -;; iteration ~{...~} -;;---------------------------------------------------------------------- - -(defn- iterate-sublist [params navigator offsets] - (let [max-count (:max-iterations params) - param-clause (first (:clauses params)) - [clause navigator] (if (empty? param-clause) - (get-format-arg navigator) - [param-clause navigator]) - [arg-list navigator] (next-arg navigator) - args (init-navigator arg-list)] - (loop [count 0 - args args - last-pos -1] - (if (and (not max-count) (= (:pos args) last-pos) (> count 1)) - (throw (Exception. "~{ construct not consuming any arguments: Infinite loop!"))) - (if (or (and (empty? (:rest args)) - (or (not (:colon (:right-params params))) (> count 0))) - (and max-count (>= count max-count))) - navigator - (let [iter-result (execute-sub-format clause args (:base-args params))] - (if (= :up-arrow (first iter-result)) - navigator - (recur (inc count) iter-result (:pos args)))))))) - -(defn- iterate-list-of-sublists [params navigator offsets] - (let [max-count (:max-iterations params) - param-clause (first (:clauses params)) - [clause navigator] (if (empty? param-clause) - (get-format-arg navigator) - [param-clause navigator]) - [arg-list navigator] (next-arg navigator)] - (loop [count 0 - arg-list arg-list] - (if (or (and (empty? arg-list) - (or (not (:colon (:right-params params))) (> count 0))) - (and max-count (>= count max-count))) - navigator - (let [iter-result (execute-sub-format - clause - (init-navigator (first arg-list)) - (init-navigator (next arg-list)))] - (if (= :colon-up-arrow (first iter-result)) - navigator - (recur (inc count) (next arg-list)))))))) - -(defn- iterate-main-list [params navigator offsets] - (let [max-count (:max-iterations params) - param-clause (first (:clauses params)) - [clause navigator] (if (empty? param-clause) - (get-format-arg navigator) - [param-clause navigator])] - (loop [count 0 - navigator navigator - last-pos -1] - (if (and (not max-count) (= (:pos navigator) last-pos) (> count 1)) - (throw (Exception. "~@{ construct not consuming any arguments: Infinite loop!"))) - (if (or (and (empty? (:rest navigator)) - (or (not (:colon (:right-params params))) (> count 0))) - (and max-count (>= count max-count))) - navigator - (let [iter-result (execute-sub-format clause navigator (:base-args params))] - (if (= :up-arrow (first iter-result)) - (second iter-result) - (recur - (inc count) iter-result (:pos navigator)))))))) - -(defn- iterate-main-sublists [params navigator offsets] - (let [max-count (:max-iterations params) - param-clause (first (:clauses params)) - [clause navigator] (if (empty? param-clause) - (get-format-arg navigator) - [param-clause navigator])] - (loop [count 0 - navigator navigator] - (if (or (and (empty? (:rest navigator)) - (or (not (:colon (:right-params params))) (> count 0))) - (and max-count (>= count max-count))) - navigator - (let [[sublist navigator] (next-arg-or-nil navigator) - iter-result (execute-sub-format clause (init-navigator sublist) navigator)] - (if (= :colon-up-arrow (first iter-result)) - navigator - (recur (inc count) navigator))))))) - -;;---------------------------------------------------------------------- -;; ~< ... ~> justification / logical block -;;---------------------------------------------------------------------- - -(declare ^{:arglists '([params navigator offsets])} format-logical-block) -(declare ^{:arglists '([params navigator offsets])} justify-clauses) - -(defn- logical-block-or-justify [params navigator offsets] - (if (:colon (:right-params params)) - (format-logical-block params navigator offsets) - (justify-clauses params navigator offsets))) - -(defn- render-clauses [clauses navigator base-navigator] - (loop [clauses clauses - acc [] - navigator navigator] - (if (empty? clauses) - [acc navigator] - (let [clause (first clauses) - [iter-result result-str] (let [sb (StringBuilder.)] - (binding [*out* (->StringBufferWriter sb)] - [(execute-sub-format clause navigator base-navigator) - (str sb)]))] - (if (= :up-arrow (first iter-result)) - [acc (second iter-result)] - (recur (next clauses) (conj acc result-str) iter-result)))))) - -(defn- justify-clauses [params navigator offsets] - (let [[[eol-str] new-navigator] (when-let [else (:else params)] - (render-clauses else navigator (:base-args params))) - navigator (or new-navigator navigator) - [else-params new-navigator] (when-let [p (:else-params params)] - (realize-parameter-list p navigator)) - navigator (or new-navigator navigator) - min-remaining (or (first (:min-remaining else-params)) 0) - max-columns (or (first (:max-columns else-params)) - (get-max-column *out*)) - clauses (:clauses params) - [strs navigator] (render-clauses clauses navigator (:base-args params)) - slots (max 1 - (+ (dec (count strs)) (if (:colon params) 1 0) (if (:at params) 1 0))) - chars (reduce + (map count strs)) - mincol (:mincol params) - minpad (:minpad params) - colinc (:colinc params) - minout (+ chars (* slots minpad)) - result-columns (if (<= minout mincol) - mincol - (+ mincol (* colinc - (+ 1 (quot (- minout mincol 1) colinc))))) - total-pad (- result-columns chars) - pad (max minpad (quot total-pad slots)) - extra-pad (- total-pad (* pad slots)) - pad-str (apply str (repeat pad (:padchar params)))] - (if (and eol-str (> (+ (get-column (:base (deref (.-fields *out*)))) min-remaining result-columns) - max-columns)) - (print eol-str)) - (loop [slots slots - extra-pad extra-pad - strs strs - pad-only (or (:colon params) - (and (= (count strs) 1) (not (:at params))))] - (if (seq strs) - (do - (print (str (if (not pad-only) (first strs)) - (if (or pad-only (next strs) (:at params)) pad-str) - (if (pos? extra-pad) (:padchar params)))) - (recur - (dec slots) - (dec extra-pad) - (if pad-only strs (next strs)) - false)))) - navigator)) - -;;---------------------------------------------------------------------- -;; ~T tabulation, ~& fresh-line, get-pretty-writer -;;---------------------------------------------------------------------- - -(defn get-pretty-writer - "Returns writer wrapped in a pretty writer unless it already is one." - [writer] - (if (pretty-writer? writer) - writer - (pretty-writer writer *print-right-margin* *print-miser-width*))) - -(defn fresh-line [] - (if (instance? PrettyWriter *out*) - (if (not (= 0 (get-column (:base (deref (.-fields *out*)))))) - (prn)) - (prn))) - -(defn- absolute-tabulation [params navigator offsets] - (let [colnum (:colnum params) - colinc (:colinc params) - current (get-column (:base (deref (.-fields *out*)))) - space-count (cond - (< current colnum) (- colnum current) - (= colinc 0) 0 - :else (- colinc (rem (- current colnum) colinc)))] - (print (apply str (repeat space-count \space)))) - navigator) - -(defn- relative-tabulation [params navigator offsets] - (let [colrel (:colnum params) - colinc (:colinc params) - start-col (+ colrel (get-column (:base (deref (.-fields *out*))))) - offset (if (pos? colinc) (rem start-col colinc) 0) - space-count (+ colrel (if (= 0 offset) 0 (- colinc offset)))] - (print (apply str (repeat space-count \space)))) - navigator) - -;;---------------------------------------------------------------------- -;; ~< ... ~:> logical block, ~_ newline, ~I indent -;;---------------------------------------------------------------------- - -(defn- format-logical-block [params navigator offsets] - (let [clauses (:clauses params) - clause-count (count clauses) - prefix (cond - (> clause-count 1) (:string (:params (first (first clauses)))) - (:colon params) "(") - body (nth clauses (if (> clause-count 1) 1 0)) - suffix (cond - (> clause-count 2) (:string (:params (first (nth clauses 2)))) - (:colon params) ")") - [arg navigator] (next-arg navigator)] - (pprint-logical-block :prefix prefix :suffix suffix - (execute-sub-format - body - (init-navigator arg) - (:base-args params))) - navigator)) - -(defn- set-indent [params navigator offsets] - (let [relative-to (if (:colon params) :current :block)] - (pprint-indent relative-to (:n params)) - navigator)) - -(defn- conditional-newline [params navigator offsets] - (let [kind (if (:colon params) - (if (:at params) :mandatory :fill) - (if (:at params) :miser :linear))] - (pprint-newline kind) - navigator)) - -;;---------------------------------------------------------------------- -;; directive table -;;---------------------------------------------------------------------- - -(defmacro ^{:private true} defdirectives [& directives] - (let [process (fn [[char params flags bracket-info & generator-fn]] - [char - {:directive char - :params `(array-map ~@params) - :flags flags - :bracket-info bracket-info - :generator-fn (concat '(fn [params offset]) generator-fn)}])] - `(def ^{:private true} - ~'directive-table (hash-map ~@(mapcat process directives))))) - -(defdirectives - (\A - [:mincol [0 Long] :colinc [1 Long] :minpad [0 Long] :padchar [\space Character]] - #{:at :colon :both} {} - #(format-ascii print-str %1 %2 %3)) - - (\S - [:mincol [0 Long] :colinc [1 Long] :minpad [0 Long] :padchar [\space Character]] - #{:at :colon :both} {} - #(format-ascii pr-str %1 %2 %3)) - - (\D - [:mincol [0 Long] :padchar [\space Character] :commachar [\, Character] - :commainterval [3 Long]] - #{:at :colon :both} {} - #(format-integer 10 %1 %2 %3)) - - (\B - [:mincol [0 Long] :padchar [\space Character] :commachar [\, Character] - :commainterval [3 Long]] - #{:at :colon :both} {} - #(format-integer 2 %1 %2 %3)) - - (\O - [:mincol [0 Long] :padchar [\space Character] :commachar [\, Character] - :commainterval [3 Long]] - #{:at :colon :both} {} - #(format-integer 8 %1 %2 %3)) - - (\X - [:mincol [0 Long] :padchar [\space Character] :commachar [\, Character] - :commainterval [3 Long]] - #{:at :colon :both} {} - #(format-integer 16 %1 %2 %3)) - - (\% - [:count [1 Long]] - #{} {} - (fn [params arg-navigator offsets] - (dotimes [i (:count params)] - (prn)) - arg-navigator)) - - (\& - [:count [1 Long]] - #{:pretty} {} - (fn [params arg-navigator offsets] - (let [cnt (:count params)] - (if (pos? cnt) (fresh-line)) - (dotimes [i (dec cnt)] - (prn))) - arg-navigator)) - - (\| - [:count [1 Long]] - #{} {} - (fn [params arg-navigator offsets] - (dotimes [i (:count params)] - (print \formfeed)) - arg-navigator)) - - (\~ - [:n [1 Long]] - #{} {} - (fn [params arg-navigator offsets] - (let [n (:n params)] - (print (apply str (repeat n \~))) - arg-navigator))) - - (\newline - [] - #{:colon :at} {} - (fn [params arg-navigator offsets] - (if (:at params) - (prn)) - arg-navigator)) - - (\T - [:colnum [1 Long] :colinc [1 Long]] - #{:at :pretty} {} - (if (:at params) - #(relative-tabulation %1 %2 %3) - #(absolute-tabulation %1 %2 %3))) - - (\* - [:n [1 Long]] - #{:colon :at} {} - (fn [params navigator offsets] - (let [n (:n params)] - (if (:at params) - (absolute-reposition navigator n) - (relative-reposition navigator (if (:colon params) (- n) n)))))) - - (\? - [] - #{:at} {} - (if (:at params) - (fn [params navigator offsets] - (let [[subformat navigator] (get-format-arg navigator)] - (execute-sub-format subformat navigator (:base-args params)))) - (fn [params navigator offsets] - (let [[subformat navigator] (get-format-arg navigator) - [subargs navigator] (next-arg navigator) - sub-navigator (init-navigator subargs)] - (execute-sub-format subformat sub-navigator (:base-args params)) - navigator)))) - - (\) [] #{} {} nil) - - (\[ - [:selector [nil Long]] - #{:colon :at} {:right \], :allows-separator true, :else :last} - (cond - (:colon params) - boolean-conditional - - (:at params) - check-arg-conditional - - true - choice-conditional)) - - (\; [:min-remaining [nil Long] :max-columns [nil Long]] - #{:colon} {:separator true} nil) - - (\] [] #{} {} nil) - - (\{ - [:max-iterations [nil Long]] - #{:colon :at :both} {:right \}, :allows-separator false} - (cond - (and (:at params) (:colon params)) - iterate-main-sublists - - (:colon params) - iterate-list-of-sublists - - (:at params) - iterate-main-list - - true - iterate-sublist)) - - (\} [] #{:colon} {} nil) - - (\< - [:mincol [0 Long] :colinc [1 Long] :minpad [0 Long] :padchar [\space Character]] - #{:colon :at :both :pretty} {:right \>, :allows-separator true, :else :first} - logical-block-or-justify) - - (\> [] #{:colon} {} nil) - - (\^ [:arg1 [nil Long] :arg2 [nil Long] :arg3 [nil Long]] - #{:colon} {} - (fn [params navigator offsets] - (let [arg1 (:arg1 params) - arg2 (:arg2 params) - arg3 (:arg3 params) - exit (if (:colon params) :colon-up-arrow :up-arrow)] - (cond - (and arg1 arg2 arg3) - (if (<= arg1 arg2 arg3) [exit navigator] navigator) - - (and arg1 arg2) - (if (= arg1 arg2) [exit navigator] navigator) - - arg1 - (if (= arg1 0) [exit navigator] navigator) - - true - (if (if (:colon params) - (empty? (:rest (:base-args params))) - (empty? (:rest navigator))) - [exit navigator] navigator))))) - - (\W - [] - #{:at :colon :both :pretty} {} - (if (or (:at params) (:colon params)) - (let [bindings (concat - (if (:at params) [:level nil :length nil] []) - (if (:colon params) [:pretty true] []))] - (fn [params navigator offsets] - (let [[arg navigator] (next-arg navigator)] - (if (apply write arg bindings) - [:up-arrow navigator] - navigator)))) - (fn [params navigator offsets] - (let [[arg navigator] (next-arg navigator)] - (if (write-out arg) - [:up-arrow navigator] - navigator))))) - - (\_ - [] - #{:at :colon :both} {} - conditional-newline) - - (\I - [:n [0 Long]] - #{:colon} {} - set-indent)) - -;;---------------------------------------------------------------------- -;; compiling format strings -;;---------------------------------------------------------------------- - -(def ^{:private true} - param-pattern #"^([vV]|#|('.)|([+-]?\d+)|(?=,))") - -(def ^{:private true} - special-params #{:parameter-from-args :remaining-arg-count}) - -(defn- extract-param [[s offset saw-comma]] - ;; param-pattern is ^-anchored; re-find returns [whole g1 g2 g3] (groups nil) - ;; or nil. The whole match (possibly empty, from the comma lookahead) is the - ;; token; its length advances the cursor. - (let [param (re-find param-pattern s) - token-str (if (vector? param) (first param) param)] - (if token-str - (let [len (count token-str) - remainder (subs s len) - new-offset (+ offset len)] - (if (not (= \, (nth remainder 0 nil))) - [[token-str offset] [remainder new-offset false]] - [[token-str offset] [(subs remainder 1) (inc new-offset) true]])) - (if saw-comma - (format-error "Badly formed parameters in format directive" offset) - [nil [s offset]])))) - -(defn- extract-params [s offset] - (consume extract-param [s offset false])) - -(defn- translate-param [[p offset]] - [(cond - (= (count p) 0) nil - (and (= (count p) 1) (contains? #{\v \V} (nth p 0))) :parameter-from-args - (and (= (count p) 1) (= \# (nth p 0))) :remaining-arg-count - (and (= (count p) 2) (= \' (nth p 0))) (nth p 1) - true (Long/parseLong p)) - offset]) - -(def ^{:private true} flag-defs {\: :colon, \@ :at}) - -(defn- extract-flags [s offset] - (consume - (fn [[s offset flags]] - (if (empty? s) - [nil [s offset flags]] - (let [flag (get flag-defs (first s))] - (if flag - (if (contains? flags flag) - (format-error - (str "Flag \"" (first s) "\" appears more than once in a directive") - offset) - [true [(subs s 1) (inc offset) (assoc flags flag [true offset])]]) - [nil [s offset flags]])))) - [s offset {}])) - -(defn- check-flags [dirdef flags] - (let [allowed (:flags dirdef)] - (if (and (not (:at allowed)) (:at flags)) - (format-error (str "\"@\" is an illegal flag for format directive \"" (:directive dirdef) "\"") - (nth (:at flags) 1))) - (if (and (not (:colon allowed)) (:colon flags)) - (format-error (str "\":\" is an illegal flag for format directive \"" (:directive dirdef) "\"") - (nth (:colon flags) 1))) - (if (and (not (:both allowed)) (:at flags) (:colon flags)) - (format-error (str "Cannot combine \"@\" and \":\" flags for format directive \"" - (:directive dirdef) "\"") - (min (nth (:colon flags) 1) (nth (:at flags) 1)))))) - -(defn- map-params [dirdef params flags offset] - (check-flags dirdef flags) - (if (> (count params) (count (:params dirdef))) - (format-error - (cl-format - nil - "Too many parameters for directive \"~C\": ~D~:* ~[were~;was~:;were~] specified but only ~D~:* ~[are~;is~:;are~] allowed" - (:directive dirdef) (count params) (count (:params dirdef))) - (second (first params)))) - (doall - (map #(let [val (first %1)] - (if (not (or (nil? val) (contains? special-params val))) - nil)) - params (:params dirdef))) - - (merge - (into {} - (reverse (for [[name [default]] (:params dirdef)] [name [default offset]]))) - (reduce #(apply assoc %1 %2) {} (filter #(first (nth % 1)) (zipmap (keys (:params dirdef)) params))) - flags)) - -(defn- compile-directive [s offset] - (let [[raw-params [rest offset]] (extract-params s offset) - [_ [rest offset flags]] (extract-flags rest offset) - directive (first rest) - dirdef (if directive - (or (get directive-table (first (clojure.string/upper-case (str directive)))) - (get directive-table directive))) - params (if dirdef (map-params dirdef (map translate-param raw-params) flags offset))] - (if (not directive) - (format-error "Format string ended in the middle of a directive" offset)) - (if (not dirdef) - (format-error (str "Directive \"" directive "\" is undefined") offset)) - [(->compiled-directive ((:generator-fn dirdef) params offset) dirdef params offset) - (let [remainder (subs rest 1) - offset (inc offset) - trim? (and (= \newline (:directive dirdef)) - (not (:colon params))) - trim-count (if trim? (prefix-count remainder [\space \tab]) 0) - remainder (subs remainder trim-count) - offset (+ offset trim-count)] - [remainder offset])])) - -(defn- compile-raw-string [s offset] - (->compiled-directive (fn [_ a _] (print s) a) nil {:string s} offset)) - -(defn- right-bracket [this] (:right (:bracket-info (:dirdef this)))) -(defn- separator? [this] (:separator (:bracket-info (:dirdef this)))) -(defn- else-separator? [this] - (and (:separator (:bracket-info (:dirdef this))) - (:colon (:params this)))) - -(declare ^{:arglists '([bracket-info offset remainder])} collect-clauses) - -(defn- process-bracket [this remainder] - (let [[subex remainder] (collect-clauses (:bracket-info (:dirdef this)) - (:offset this) remainder)] - [(->compiled-directive - (:func this) (:dirdef this) - (merge (:params this) (tuple-map subex (:offset this))) - (:offset this)) - remainder])) - -(defn- process-clause [bracket-info offset remainder] - (consume - (fn [remainder] - (if (empty? remainder) - (format-error "No closing bracket found." offset) - (let [this (first remainder) - remainder (next remainder)] - (cond - (right-bracket this) - (process-bracket this remainder) - - (= (:right bracket-info) (:directive (:dirdef this))) - [nil [:right-bracket (:params this) nil remainder]] - - (else-separator? this) - [nil [:else nil (:params this) remainder]] - - (separator? this) - [nil [:separator nil nil remainder]] - - true - [this remainder])))) - remainder)) - -(defn- collect-clauses [bracket-info offset remainder] - (second - (consume - (fn [[clause-map saw-else remainder]] - (let [[clause [type right-params else-params remainder]] - (process-clause bracket-info offset remainder)] - (cond - (= type :right-bracket) - [nil [(merge-with concat clause-map - {(if saw-else :else :clauses) [clause] - :right-params right-params}) - remainder]] - - (= type :else) - (cond - (:else clause-map) - (format-error "Two else clauses (\"~:;\") inside bracket construction." offset) - - (not (:else bracket-info)) - (format-error "An else clause (\"~:;\") is in a bracket type that doesn't support it." - offset) - - (and (= :first (:else bracket-info)) (seq (:clauses clause-map))) - (format-error - "The else clause (\"~:;\") is only allowed in the first position for this directive." - offset) - - true - (if (= :first (:else bracket-info)) - [true [(merge-with concat clause-map {:else [clause] :else-params else-params}) - false remainder]] - [true [(merge-with concat clause-map {:clauses [clause]}) - true remainder]])) - - (= type :separator) - (cond - saw-else - (format-error "A plain clause (with \"~;\") follows an else clause (\"~:;\") inside bracket construction." offset) - - (not (:allows-separator bracket-info)) - (format-error "A separator (\"~;\") is in a bracket type that doesn't support it." - offset) - - true - [true [(merge-with concat clause-map {:clauses [clause]}) - false remainder]])))) - [{:clauses []} false remainder]))) - -(defn- process-nesting [format] - (first - (consume - (fn [remainder] - (let [this (first remainder) - remainder (next remainder) - bracket (:bracket-info (:dirdef this))] - (if (:right bracket) - (process-bracket this remainder) - [this remainder]))) - format))) - -(defn- compile-format [format-str] - (binding [*format-str* format-str] - (process-nesting - (first - (consume - (fn [[s offset]] - (if (empty? s) - [nil s] - (let [tilde (.indexOf s "~")] - (cond - (neg? tilde) [(compile-raw-string s offset) ["" (+ offset (count s))]] - (zero? tilde) (compile-directive (subs s 1) (inc offset)) - true - [(compile-raw-string (subs s 0 tilde) offset) [(subs s tilde) (+ tilde offset)]])))) - [format-str 0]))))) - -(defn- needs-pretty [format] - (loop [format format] - (if (empty? format) - false - (if (or (:pretty (:flags (:dirdef (first format)))) - (some needs-pretty (first (:clauses (:params (first format))))) - (some needs-pretty (first (:else (:params (first format)))))) - true - (recur (next format)))))) - -(defn- execute-format - ([stream format args] - (let [sb (StringBuilder.) - real-stream (if (or (not stream) (true? stream)) - (->StringBufferWriter sb) - stream) - wrapped-stream (if (and (needs-pretty format) - (not (pretty-writer? real-stream))) - (get-pretty-writer real-stream) - real-stream)] - (binding [*out* wrapped-stream] - (try - (execute-format format args) - (finally - (if-not (identical? real-stream wrapped-stream) - (-pflush wrapped-stream)))) - (cond - (not stream) (str sb) - (true? stream) (clojure.core/print (str sb)) - :else nil)))) - ([format args] - (map-passing-context - (fn [element context] - (if (abort? context) - [nil context] - (let [[params args] (realize-parameter-list - (:params element) context) - [params offsets] (unzip-map params) - params (assoc params :base-args args)] - [nil (apply (:func element) [params args offsets])]))) - args - format) - nil)) - -(def ^{:private true} cached-compile (memoize compile-format)) - -;;====================================================================== -;; dispatch -;;====================================================================== - -(def ^{:private true} reader-macros - {'quote "'" - 'var "#'" - 'clojure.core/deref "@" - 'clojure.core/unquote "~"}) - -(defn- pprint-reader-macro [alis] - (let [macro-char (reader-macros (first alis))] - (when (and macro-char (= 2 (count alis))) - (-write *out* macro-char) - (write-out (second alis)) - true))) - -;;; simple dispatch - -(defn- pprint-simple-list [alis] - (pprint-logical-block :prefix "(" :suffix ")" - (print-length-loop [alis (seq alis)] - (when alis - (write-out (first alis)) - (when (next alis) - (-write *out* " ") - (pprint-newline :linear) - (recur (next alis))))))) - -(defn- pprint-list [alis] - (if-not (pprint-reader-macro alis) - (pprint-simple-list alis))) - -(defn- pprint-vector [avec] - (pprint-logical-block :prefix "[" :suffix "]" - (print-length-loop [aseq (seq avec)] - (when aseq - (write-out (first aseq)) - (when (next aseq) - (-write *out* " ") - (pprint-newline :linear) - (recur (next aseq))))))) - -(def ^{:private true} pprint-array (formatter-out "~<[~;~@{~w~^, ~:_~}~;]~:>")) - -(defn- pprint-map [amap] - (pprint-logical-block :prefix "{" :suffix "}" - (print-length-loop [aseq (seq amap)] - (when aseq - (pprint-logical-block - (write-out (ffirst aseq)) - (-write *out* " ") - (pprint-newline :linear) - (set! *current-length* 0) - (write-out (fnext (first aseq)))) - (when (next aseq) - (-write *out* ", ") - (pprint-newline :linear) - (recur (next aseq))))))) - -(defn- pprint-simple-default [obj] - (-write *out* (pr-str obj))) - -(def pprint-set (formatter-out "~<#{~;~@{~w~^ ~:_~}~;}~:>")) - -(defn- type-dispatcher [obj] - (cond - (symbol? obj) :symbol - (seq? obj) :list - (map? obj) :map - (vector? obj) :vector - (set? obj) :set - (nil? obj) nil - :else :default)) - -;; simple-dispatch / code-dispatch are plain functions rather than multimethods: -;; a multimethod baked into the seed can't capture this namespace's load context, -;; and the printer never extends these tables externally. -(defn simple-dispatch - "The pretty print dispatch function for simple data structure format." - [obj] - (case (type-dispatcher obj) - :list (pprint-list obj) - :vector (pprint-vector obj) - :map (pprint-map obj) - :set (pprint-set obj) - nil (-write *out* (pr-str nil)) - (pprint-simple-default obj))) - -;;; code dispatch - -(declare ^{:arglists '([alis])} pprint-simple-code-list) - -(defn- brackets [form] - (if (vector? form) - ["[" "]"] - ["(" ")"])) - -(defn- pprint-simple-code-list [alis] - (pprint-logical-block :prefix "(" :suffix ")" - (pprint-indent :block 1) - (print-length-loop [alis (seq alis)] - (when alis - (write-out (first alis)) - (when (next alis) - (-write *out* " ") - (pprint-newline :linear) - (recur (next alis))))))) - -(defn- pprint-code-list [alis] - (if-not (pprint-reader-macro alis) - (pprint-simple-code-list alis))) - -(defn- pprint-code-symbol [sym] - (if *print-suppress-namespaces* - (print (name sym)) - (pr sym))) - -(defn code-dispatch - "The pretty print dispatch function for pretty printing Clojure code." - [obj] - (case (type-dispatcher obj) - :list (pprint-code-list obj) - :symbol (pprint-code-symbol obj) - :vector (pprint-vector obj) - :map (pprint-map obj) - :set (pprint-set obj) - nil (pr obj) - (pprint-simple-default obj))) - -(alter-var-root (var *print-pprint-dispatch*) (constantly simple-dispatch)) - -;;====================================================================== -;; print-table -;;====================================================================== - -(defn- add-padding [width s] - (let [padding (max 0 (- width (count s)))] - (apply str (clojure.string/join (repeat padding \space)) s))) - -(defn print-table - "Prints a collection of maps in a textual table." - ([ks rows] - (when (seq rows) - (let [widths (map - (fn [k] - (apply max (count (str k)) (map #(count (str (get % k))) rows))) - ks) - spacers (map #(apply str (repeat % "-")) widths) - fmt-row (fn [leader divider trailer row] - (str leader - (apply str (interpose divider - (for [[col width] (map vector (map #(get row %) ks) widths)] - (add-padding width (str col))))) - trailer))] - (clojure.core/println) - (clojure.core/println (fmt-row "| " " | " " |" (zipmap ks ks))) - (clojure.core/println (fmt-row "|-" "-+-" "-|" (zipmap ks spacers))) - (doseq [row rows] - (clojure.core/println (fmt-row "| " " | " " |" row)))))) - ([rows] (print-table (keys (first rows)) rows))) - -;;====================================================================== -;; core print routing -;;====================================================================== - -;; Route clojure.core/print et al. into the active pretty-writer when *out* is -;; bound to one, matching JVM Clojure where core print honours *out*. Custom -;; dispatch fns (e.g. clojure.data.json's, which calls clojure.core/print and -;; (PrintWriter. *out*)) depend on this. Declines (nil) when *out* is anything -;; else, so the string falls through to the normal output seam. -(clojure.core/__set-pprint-write-hook! - (fn [s] - (let [o clojure.core/*out*] - (when (instance? PrettyWriter o) - (-write o s) - true)))) diff --git a/stdlib/clojure/string.clj b/stdlib/clojure/string.clj deleted file mode 100644 index c211650..0000000 --- a/stdlib/clojure/string.clj +++ /dev/null @@ -1,154 +0,0 @@ -; Jolt Standard Library: clojure.string -; String manipulation functions using Jolt core string interop. - -(defn blank? - [s] - (if (nil? s) true - (= 0 (count (str-trim s))))) - -;; The case fns and the searches take any Object s through its toString, like -;; the reference ((upper-case :kw) is ":KW", (capitalize 1) is "1"); nil throws -;; like calling a method on null. -(defn- to-str [s] - (if (nil? s) - (throw (new NullPointerException "s")) - (.toString s))) -(defn capitalize - [s] - (let [s (to-str s)] - (if (< 1 (count s)) - (str (str-upper (subs s 0 1)) - (str-lower (subs s 1))) - (str-upper s)))) - -(defn lower-case - [s] - (str-lower (to-str s))) - -(defn upper-case - [s] - (str-upper (to-str s))) - -(defn includes? - [s substr] - (not (nil? (str-find substr (to-str s))))) - -(defn join - - ([coll] (str-join coll)) - ([separator coll] (str-join coll separator))) - -(defn replace - [s match replacement] - (str-replace-all match replacement (to-str s))) - -(defn replace-first - [s match replacement] - (str-replace match replacement (to-str s))) - -(defn reverse - [s] - (str-reverse-b s)) - -(defn str-reverse - [s] - (str-reverse-b s)) - -(defn split - ([s re] (split s re 0)) - ([s re limit] - ;; Java Pattern.split semantics: limit > 0 caps the parts (trailing empties - ;; kept); limit < 0 splits fully and keeps trailing empties; limit 0 (the - ;; default) splits fully then drops trailing empty strings — but a no-match - ;; result ([input], the only 1-element case) is returned as-is. - (let [parts (vec (str-split re s (if (pos? limit) limit nil)))] - (if (and (zero? limit) (> (count parts) 1)) - (loop [v parts] (if (and (seq v) (= "" (peek v))) (recur (pop v)) v)) - parts)))) - -(defn split-lines - "Split s on \\n or \\r\\n, returning a vector of lines." - [s] - (vec (str-split #"\r?\n" s))) - -(defn starts-with? - [s substr] - (when (nil? substr) (throw (new NullPointerException "substr"))) - (let [s (to-str s) - slen (count s) slen2 (count substr)] - (and (>= slen slen2) - (= (subs s 0 slen2) substr)))) - -(defn ends-with? - [s substr] - (when (nil? substr) (throw (new NullPointerException "substr"))) - (let [s (to-str s) - slen (count s) slen2 (count substr)] - (and (>= slen slen2) - (= (subs s (- slen slen2)) substr)))) - -(defn trim - - [s] - (str-trim s)) - -(defn triml - - [s] - (str-triml s)) - -(defn trimr - - [s] - (str-trimr s)) - -(defn escape - [s cmap] - (when (nil? s) (throw (new NullPointerException "s"))) - (apply str - (map (fn [ch] - (if-let [rep (cmap ch)] rep (str ch))) - s))) - -(defn index-of - "0-based index of the first occurrence of value in s, or nil." - ([s value] - (str-find value (to-str s))) - ([s value from] - (let [idx (str-find value (subs (to-str s) from))] - (when idx (+ from idx))))) - -(defn last-index-of - - ([s value] - (let [r (str-reverse-b s) sval (str-reverse-b value) - idx (str-find sval r)] - (when idx (- (count s) (+ idx (count value)))))) - ([s value from] - (let [sub (subs s 0 from) r (str-reverse-b sub) sval (str-reverse-b value) - idx (str-find sval r)] - (when idx (- from (+ idx (count value))))))) - -(defn re-quote-replacement - "Escape special characters (backslash and dollar) in a regex replacement - string so it is used literally rather than interpreted." - [replacement] - (apply str - (map (fn [ch] - (let [c (str ch)] - (if (or (= c "\\") (= c "$")) (str "\\" c) c))) - (seq replacement)))) - -;; Ported from clojure.string/trim-newline (CharSequence interop replaced with -;; portable count/subs). Removes all trailing \n or \r characters. -(defn trim-newline - "Removes all trailing newline \\n or return \\r characters from - string. Similar to Perl's chomp." - [s] - (loop [index (count s)] - (if (zero? index) - "" - (let [c (subs s (dec index) index)] - (if (or (= c "\n") (= c "\r")) - (recur (dec index)) - (subs s 0 index)))))) diff --git a/stdlib/clojure/template.clj b/stdlib/clojure/template.clj deleted file mode 100644 index 42eac96..0000000 --- a/stdlib/clojure/template.clj +++ /dev/null @@ -1,33 +0,0 @@ -;; Verbatim from clojure.template (Stuart Sierra) — pure Clojure over -;; clojure.walk, which jolt ships. Added so honeysql's :clj branch (which -;; requires clojure.template) loads. -(ns clojure.template - "Macros that expand to repeated copies of a template expression." - (:require [clojure.walk :as walk])) - -(defn apply-template - "For use in macros. argv is an argument list, as in defn. expr is - a quoted expression using the symbols in argv. values is a sequence - of values to be used for the arguments. - - apply-template will recursively replace argument symbols in expr - with their corresponding values, returning a modified expr. - - Example: (apply-template '[x] '(+ x x) '[2]) - ;=> (+ 2 2)" - [argv expr values] - (assert (vector? argv)) - (assert (every? symbol? argv)) - (walk/postwalk-replace (zipmap argv values) expr)) - -(defmacro do-template - "Repeatedly copies expr (in a do block) for each group of arguments - in values. values are automatically partitioned by the number of - arguments in argv, an argument vector as in defn. - - Example: (macroexpand '(do-template [x y] (+ y x) 2 4 3 5)) - ;=> (do (+ 4 2) (+ 5 3))" - [argv expr & values] - (let [c (count argv)] - `(do ~@(map (fn [a] (apply-template argv expr a)) - (partition c values))))) diff --git a/stdlib/clojure/test.clj b/stdlib/clojure/test.clj deleted file mode 100644 index 17eef32..0000000 --- a/stdlib/clojure/test.clj +++ /dev/null @@ -1,292 +0,0 @@ -; Jolt Standard Library: clojure.test -; -; A practical subset of clojure.test for running real test suites under Jolt: -; deftest / is / testing / are / use-fixtures / run-tests, with class-aware -; (thrown? Class body) and (thrown-with-msg? Class re body) inside `is`. Class -; matching is by simple-name (last dotted segment), since Jolt has no JVM class -; objects — Exception/Throwable match any thrown value. -; -; Also exposes the counter/registry API the internal clojure-test-suite harness -; uses (reset-report!, run-registered, n-pass/n-fail/n-error, failures), so this -; is a drop-in superset. - -(ns clojure.test - (:require [clojure.string :as str] - [clojure.template :as temp])) - -;; --- state ----------------------------------------------------------------- - -(def counters (atom {:test 0 :pass 0 :fail 0 :error 0 :fails []})) -(def jolt-report counters) ;; alias used by the suite harness -(def ctx-stack (atom [])) -(def registry (atom [])) ;; [{:name sym :fn thunk}] -(def once-fixtures (atom {})) ;; ns-sym -> [fixture-fns] -(def each-fixtures (atom {})) ;; ns-sym -> [fixture-fns] - -;; clojure.test/*testing-vars* — the stack of vars under test. Real clojure.test -;; binds it around each test var; test.check's default reporter reads it, so a -;; defspec run through its :test metadata doesn't blow up on an unbound var. -(def ^:dynamic *testing-vars* (list)) -(def ^:dynamic *report-counters* nil) - -(defn reset-report! [] - (reset! counters {:test 0 :pass 0 :fail 0 :error 0 :fails []}) - (reset! ctx-stack []) - (reset! registry []) - (reset! once-fixtures {}) - (reset! each-fixtures {})) - -(defn- ctx-str [] (str/join " " @ctx-stack)) - -(defn inc-pass! [] (swap! counters update :pass inc)) -(defn fail! [form] - (let [line (str (ctx-str) (when (seq @ctx-stack) " ") "FAIL: " form)] - (swap! counters (fn [r] (-> r (update :fail inc) (update :fails conj line)))) - (println line))) -(defn err! [form] - (let [line (str (ctx-str) (when (seq @ctx-stack) " ") "ERROR: " form)] - (swap! counters (fn [r] (-> r (update :error inc) (update :fails conj line)))) - (println line))) - -(defn n-pass [] (:pass @counters)) -(defn n-fail [] (:fail @counters)) -(defn n-error [] (:error @counters)) -(defn failures [] (:fails @counters)) - -;; Message of a thrown value: ex-info's message, else a raw host condition's text -;; (ex-message is nil for those), else its printed form — so a crash is never -;; reported with a blank message. -(defn err-text [e] - (or (ex-message e) - (jolt.host/condition-message e) - (str e))) - -;; clojure.test/report multimethod — present so suites that add reporting -;; methods (defmethod clojure.test/report :begin-test-var ...) load. The runner -;; below does its own console output and doesn't dispatch through it. -(defmulti report :type) -(defmethod report :default [_m] nil) - -;; do-report routes a {:type …} report map through the report multimethod — the -;; seam clojure.test assertions emit through. The built-in :pass/:fail/:error -;; methods feed jolt's counters; a library can add report types (test.check's -;; ::trial/::shrunk/::complete) and they dispatch here. -(defn- report-line [m] - (str (when (:message m) (str (:message m) - (when (or (:form m) (contains? m :expected) (contains? m :actual)) " "))) - (when (:form m) (pr-str (:form m))) - (when (contains? m :expected) (str " expected: " (pr-str (:expected m)))) - (when (contains? m :actual) (str " actual: " (pr-str (:actual m)))))) -(defmethod report :pass [_m] (inc-pass!)) -(defmethod report :fail [m] (fail! (report-line m))) -(defmethod report :error [m] (err! (report-line m))) -(defn do-report [m] (report m)) - -;; assert-expr is the macro-level extension point: `is` expands a form by calling -;; (assert-expr msg form), dispatched on the form's first symbol (or :default / -;; :always-fail). A library registers a custom assertion via -;; (defmethod assert-expr 'my-pred [msg form] ). -;; 2-arg [msg form] signature matches clojure.test. `is` routes here only for a -;; symbol with an explicitly registered method, so built-in forms are unaffected. -(defmulti assert-expr (fn [_msg form] - (cond (nil? form) :always-fail - (and (seq? form) (symbol? (first form))) (first form) - :else :default))) -(defmethod assert-expr :always-fail [msg form] - `(clojure.test/do-report {:type :fail :message ~msg :form '~form})) -(defmethod assert-expr :default [msg form] - `(try - (if ~form - (clojure.test/do-report {:type :pass}) - (clojure.test/do-report {:type :fail :message ~msg :form '~form})) - (catch Throwable e# - (clojure.test/do-report {:type :error :message ~msg :form '~form - :actual (clojure.test/err-text e#)})))) - -;; The common pure predicates whose args `is` evaluates so a failure shows the -;; actual values — (is (= expected got)) prints `got`, not just the form. A macro -;; head (not in this set) keeps the plain form-only path. -(def ^:private reported-preds - '#{= not= == < > <= >= identical? contains? instance? nil? some? empty? even? odd? pos? neg? zero?}) - -;; --- class matching for thrown? -------------------------------------------- - -(defn- last-seg [s] - (let [s (str s) - i (str/last-index-of s ".")] - (if i (subs s (inc i)) s))) - -(defn class-match? - "True if thrown value `e` matches the wanted class simple-name `wanted`. - Exception/Throwable match anything." - [e wanted] - (let [w (last-seg wanted)] - (if (or (= w "Exception") (= w "Throwable")) - true - (let [c (class e) - cn (cond (nil? c) nil (string? c) c :else (.getName c))] - (and cn (= (last-seg cn) w)))))) - -;; --- assertion macros ------------------------------------------------------ - -(defn- thrown-form? [form sym] - (and (seq? form) (symbol? (first form)) (= sym (name (first form))))) - -(defmacro is - ([form] `(is ~form nil)) - ([form msg] - (cond - ;; a library-registered custom assertion (the assert-expr extension point) - ;; wins over every inline path, like clojure.test, where each `is` dispatches - ;; assert-expr on the exact head symbol and the built-ins are just - ;; pre-registered methods. In particular a registered alias-qualified - ;; `p/thrown?` must not be captured by the by-name thrown? path below. - (and (seq? form) (symbol? (first form)) - (contains? (methods clojure.test/assert-expr) (first form))) - (clojure.test/assert-expr msg form) - - ;; (is (thrown? Class body...)) - (thrown-form? form "thrown?") - (let [klass-sym (second form) - klass (name klass-sym) - body (nthrest form 2)] - `(try - ~@body - (clojure.test/fail! (str "expected " '~form " to throw" (when ~msg (str " — " ~msg)))) - (catch Throwable e# - ;; instance? honors the exception hierarchy (a literal class symbol), so - ;; (thrown? IllegalArgumentException …) matches an ArityException subclass - ;; like the JVM; class-match? is the simple-name fallback for a class jolt - ;; models only by name. - (if (or (clojure.core/instance? ~klass-sym e#) - (clojure.test/class-match? e# ~klass)) - (clojure.test/inc-pass!) - (clojure.test/fail! (str "expected throw of " ~klass " but got " (clojure.core/class e#))))))) - - ;; (is (thrown-with-msg? Class re body...)) - (thrown-form? form "thrown-with-msg?") - (let [klass-sym (second form) - klass (name klass-sym) - re (nth form 2) - body (nthrest form 3)] - `(try - ~@body - (clojure.test/fail! (str "expected " '~form " to throw")) - (catch Throwable e# - (let [m# (or (clojure.core/ex-message e#) (str e#))] - ;; honor the class hierarchy (ExceptionInfo IS a RuntimeException), - ;; then fall back to a simple-name match like thrown? does. - (if (and (or (clojure.core/instance? ~klass-sym e#) - (clojure.test/class-match? e# ~klass)) - (re-find ~re m#)) - (clojure.test/inc-pass!) - (clojure.test/fail! (str "expected throw of " ~klass " matching " ~re " but got " (clojure.core/class e#) ": " m#))))))) - - ;; a predicate call — (= a b), (< x y), (pred? v): evaluate the args so a - ;; failure shows the actual values, like clojure.test's assert-predicate. - (and (seq? form) (contains? clojure.test/reported-preds (first form))) - `(try - (let [vs# (list ~@(rest form))] - (if (apply ~(first form) vs#) - (clojure.test/inc-pass!) - (clojure.test/fail! (str (pr-str (list '~'not (cons '~(first form) vs#))) - (when ~msg (str " — " ~msg)))))) - (catch Throwable e# - (clojure.test/err! (str (pr-str '~form) " threw: " (clojure.test/err-text e#))))) - - :else - `(try - (if ~form - (clojure.test/inc-pass!) - (clojure.test/fail! (str (pr-str '~form) (when ~msg (str " — " ~msg))))) - (catch Throwable e# - (clojure.test/err! (str (pr-str '~form) " threw: " (clojure.test/err-text e#)))))))) - -(defmacro testing [s & body] - `(do - (swap! clojure.test/ctx-stack conj ~s) - (try - (do ~@body) - (finally (swap! clojure.test/ctx-stack pop))))) - -(defmacro deftest [name & body] - `(do - (defn ~name [] ~@body) - (swap! clojure.test/registry conj {:name '~name - :ns (clojure.core/ns-name clojure.core/*ns*) - :fn ~name}) - (var ~name))) - -;; Template substitution (not let-binding), so argv symbols substitute inside -;; quote and nested forms: (are [x] (special-symbol? 'x) if def) tests 'if. -(defmacro are [argv expr & args] - (if (or (and (empty? argv) (empty? args)) - (and (pos? (count argv)) - (pos? (count args)) - (zero? (mod (count args) (count argv))))) - `(clojure.template/do-template ~argv (clojure.test/is ~expr) ~@args) - (throw (IllegalArgumentException. - "The number of args doesn't match are's argv or neither are empty")))) - -;; --- fixtures + run -------------------------------------------------------- - -;; Fixtures are per-namespace, like clojure.test (which stores them in ns -;; metadata): use-fixtures records them under the calling ns, and only that -;; ns's tests run through them — a suite loading many test namespaces into one -;; process doesn't cross-apply or clobber another ns's fixtures. -(defn use-fixtures [kind & fns] - (let [n (ns-name *ns*)] - (cond - (= kind :once) (swap! once-fixtures assoc n (vec fns)) - (= kind :each) (swap! each-fixtures assoc n (vec fns))))) - -(defn- wrap-fixtures [fixtures body-fn] - (if (empty? fixtures) - (body-fn) - ((first fixtures) (fn [] (wrap-fixtures (rest fixtures) body-fn))))) - -(defn- run-one [t] - (swap! counters update :test inc) - (wrap-fixtures (get @each-fixtures (:ns t) []) - (fn [] - (try - ((:fn t)) - (catch Throwable e - (err! (str (:name t) " crashed: " (err-text e)))))))) - -;; Run the registered tests grouped by namespace (registration order preserved -;; within each ns), each group wrapped in its ns's :once fixtures. ns-set nil -;; means all. -(defn- run-selected [ns-set] - (let [ts (if ns-set (filter (fn [t] (contains? ns-set (:ns t))) @registry) @registry)] - (doseq [n (distinct (map :ns ts))] - (wrap-fixtures (get @once-fixtures n []) - (fn [] (doseq [t ts :when (= n (:ns t))] (run-one t)))))) - nil) - -(defn run-registered [] (run-selected nil)) - -;; (run-tests 'ns1 'ns2 …) runs only those namespaces' tests, like clojure.test. -;; With no args it runs everything registered (a deliberate superset of the -;; JVM's current-ns default — jolt's harnesses load then run whole suites). -;; Prints and returns THIS call's summary; the global counters stay cumulative -;; for the n-pass/n-fail harness API. -(defn run-tests [& nses] - (let [before @counters - ns-set (when (seq nses) - (set (map (fn [n] (if (symbol? n) n (ns-name n))) nses)))] - (run-selected ns-set) - (let [r @counters - d {:type :summary - :test (- (:test r) (:test before)) - :pass (- (:pass r) (:pass before)) - :fail (- (:fail r) (:fail before)) - :error (- (:error r) (:error before))}] - (println) - (println (str "Ran " (:test d) " tests. " - (:pass d) " assertions passed, " - (:fail d) " failures, " (:error d) " errors.")) - d))) - -(defn run-test [& _] nil) -(defn test-var [& _] nil) diff --git a/stdlib/clojure/walk.clj b/stdlib/clojure/walk.clj deleted file mode 100644 index 7a1b1f1..0000000 --- a/stdlib/clojure/walk.clj +++ /dev/null @@ -1,67 +0,0 @@ -; Jolt Standard Library: clojure.walk -; Tree walking for Clojure data structures. - -(defn walk - [inner outer form] - (cond - ; vectors/maps first so seq? can't swallow them (a vector is not seq? on - ; jolt, but keep the concrete branches authoritative). Re-attach the form's - ; metadata to the rebuilt collection, as Clojure does — a metadata-driven walk - ; (aero/spec) needs ^:ref and friends to survive the rebuild. - (vector? form) (outer (with-meta (vec (map inner form)) (meta form))) - ; a record is also map?, but (empty record) yields a plain map — rebuild by - ; conj-ing the walked entries back onto the original so the record TYPE - ; survives. Type-dispatched walks depend on it (e.g. integrant resolves - ; #ig/ref by detecting its Ref record while postwalking the config). - (record? form) (outer (reduce (fn [r x] (conj r (inner x))) form form)) - (map? form) (outer (with-meta (into (empty form) (map inner form)) (meta form))) - ; lists rebuild as lists, other seqs (incl. macro/template output: cons/ - ; concat/lazy-seq) walk too — without this, postwalk-replace silently no-op'd - ; a quoted list, breaking clojure.template/apply-template - (list? form) (outer (with-meta (apply list (map inner form)) (meta form))) - ; doall like Clojure: walk must be eager so an `inner` with side effects - ; (rewrite-clj's #() reader bumps an arg-count atom during the walk, read right - ; after) runs now, not lazily when the result is later realized. - (seq? form) (outer (with-meta (doall (map inner form)) (meta form))) - :else (outer form))) - -(defn postwalk - [f form] - (walk (partial postwalk f) f form)) - -(defn prewalk - [f form] - (walk (partial prewalk f) identity (f form))) - -(defn postwalk-demo - "Demonstrates the behavior of postwalk by printing each form as it is walked." - [form] - (postwalk (fn [x] (print "Walked: ") (prn x) x) form)) - -(defn prewalk-demo - "Demonstrates the behavior of prewalk by printing each form as it is walked." - [form] - (prewalk (fn [x] (print "Walked: ") (prn x) x) form)) - -(defn postwalk-replace - [smap form] - (postwalk (fn [x] (if (contains? smap x) (get smap x) x)) form)) - -(defn prewalk-replace - [smap form] - (prewalk (fn [x] (if (contains? smap x) (get smap x) x)) form)) - -(defn macroexpand-all - "Recursively performs all possible macroexpansions in form." - [form] - (prewalk (fn [x] (if (seq? x) (macroexpand x) x)) form)) - -(defn keywordize-keys - [m] - (let [f (fn [[k v]] (if (string? k) [(keyword k) v] [k v]))] - (postwalk (fn [x] (if (map? x) (into {} (map f x)) x)) m))) - -(defn stringify-keys - [m] - (let [f (fn [[k v]] (if (keyword? k) [(name k) v] [k v]))] - (postwalk (fn [x] (if (map? x) (into {} (map f x)) x)) m))) diff --git a/stdlib/jolt/ffi.clj b/stdlib/jolt/ffi.clj deleted file mode 100644 index ef20bcd..0000000 --- a/stdlib/jolt/ffi.clj +++ /dev/null @@ -1,53 +0,0 @@ -(ns jolt.ffi - "Foreign-function interface for jolt libraries. A library loads a shared object - and declares typed foreign functions, then exposes a Clojure API over them — no - jolt built-in required. - - (require '[jolt.ffi :as ffi]) - (ffi/load-library {:darwin \"libsqlite3.0.dylib\" :linux \"libsqlite3.so.0\"}) - (ffi/defcfn sqlite3-open \"sqlite3_open\" [:string :pointer] :int) - (let [pp (ffi/alloc (ffi/sizeof :pointer))] - (sqlite3-open \"x.db\" pp) - (let [db (ffi/read pp :pointer)] ...) - (ffi/free pp)) - - Types (keywords): :int :uint :long :ulong :int64 :uint64 :size_t :ssize_t - :iptr :uptr :double :float :pointer :string :void :uint8 :char. - - The memory/library primitives (alloc/free/read/write/sizeof/load-library/ - ptr->string/string->ptr/null/null?) are provided by the host. foreign-fn lowers - a compile-time-typed signature to a real Chez foreign-procedure. foreign-callable - is the inverse — it wraps a jolt fn as a C-callable function pointer so C can - call back into jolt (e.g. GTK signal handlers); free-callable releases it.") - -;; foreign-fn binds C symbol `csym` to a typed callable. Expands to the __cfn -;; special form (always fully-qualified, so an :as alias on jolt.ffi resolves): -;; the analyzer/back end turn it into a Chez foreign-procedure. -;; An optional trailing :blocking marks a call that may block (accept/recv/...), -;; so it's emitted collect-safe and won't pin the garbage collector. -(defmacro foreign-fn [csym argtypes rettype & [opt]] - (if (= opt :blocking) - (list 'jolt.ffi/__cfn csym argtypes rettype :blocking) - (list 'jolt.ffi/__cfn csym argtypes rettype))) - -;; (defcfn name "c_symbol" [argtypes] rettype [:blocking]) — def a foreign function. -(defmacro defcfn [name csym argtypes rettype & [opt]] - (list 'def name (if (= opt :blocking) - (list 'jolt.ffi/__cfn csym argtypes rettype :blocking) - (list 'jolt.ffi/__cfn csym argtypes rettype)))) - -;; foreign-callable wraps a jolt fn `f` as a C-callable function pointer — the -;; inverse of foreign-fn, so C can call back INTO jolt (GTK signal handlers, a -;; qsort comparator, any C API that takes a callback). Returns the pointer; pass -;; it where C expects a function pointer. argtypes/rettype use the same keywords -;; as foreign-fn; the args C passes arrive as jolt values and the jolt return is -;; marshaled back. The callback stays live until free-callable is called on the -;; pointer. Pass a trailing :collect-safe when C invokes the callback from a -;; thread parked in a :blocking foreign call (e.g. a GTK main loop): -;; (g-signal-connect button "clicked" -;; (ffi/foreign-callable on-click [:pointer :pointer] :void :collect-safe) -;; (ffi/null)) -(defmacro foreign-callable [f argtypes rettype & [opt]] - (if (= opt :collect-safe) - (list 'jolt.ffi/__ccallable f argtypes rettype :collect-safe) - (list 'jolt.ffi/__ccallable f argtypes rettype))) diff --git a/test/bench/core-bench.janet b/test/bench/core-bench.janet new file mode 100644 index 0000000..d995b10 --- /dev/null +++ b/test/bench/core-bench.janet @@ -0,0 +1,42 @@ +# Performance baseline for the clojure.core migration (jolt-1j0). +# +# Times representative core operations end-to-end (compile path) so a phase that +# moves fns from native Janet to the self-hosted Clojure overlay can be checked +# for regressions. Same programs before/after a phase -> relative delta is the +# migration's perf impact. Run: janet test/bench/core-bench.janet +# +# Each program carries its own internal iteration so the measured work dominates +# parse/compile overhead. Reports the min of N runs (least noisy). + +(import ../../src/jolt/api :as api) + +(def runs 5) + +(def benches + [[:fib "(defn fib [n] (if (< n 2) n (+ (fib (- n 1)) (fib (- n 2))))) (fib 28)"] + [:seq-pipe "(loop [i 0 a 0] (if (< i 300) (recur (inc i) (+ a (reduce + 0 (map inc (filter even? (range 200)))))) a))"] + [:reduce "(loop [i 0 a 0] (if (< i 2000) (recur (inc i) (+ a (reduce + 0 (range 500)))) a))"] + [:into-vec "(loop [i 0 a 0] (if (< i 1000) (recur (inc i) (+ a (count (into [] (map inc (range 100)))))) a))"] + [:map-build "(loop [i 0 a 0] (if (< i 2000) (recur (inc i) (+ a (count (reduce (fn [m k] (assoc m k k)) {} (range 50))))) a))"] + [:map-read "(let [m (zipmap (range 100) (range 100))] (loop [i 0 a 0] (if (< i 5000) (recur (inc i) (+ a (get m (mod i 100) 0))) a)))"] + [:str-join "(loop [i 0 a 0] (if (< i 1000) (recur (inc i) (+ a (count (apply str (map str (range 100)))))) a))"] + [:hof "(loop [i 0 a 0] (if (< i 2000) (recur (inc i) (+ a (reduce + 0 (map (comp inc inc) (range 200))))) a))"]]) + +(defn time-bench [ctx src] + (var best math/inf) + (for _ 0 runs + (def t0 (os/clock)) + (api/load-string ctx src) + (def dt (* 1000 (- (os/clock) t0))) + (when (< dt best) (set best dt))) + best) + +(defn main [&] + (def ctx (api/init {:compile? true})) + (print "bench (compile mode), min of " runs " runs, ms:") + (var total 0) + (each [name src] benches + (def ms (time-bench ctx src)) + (+= total ms) + (printf " %-10s %8.2f ms" name ms)) + (printf " %-10s %8.2f ms" "TOTAL" total)) diff --git a/test/chez/README.md b/test/chez/README.md deleted file mode 100644 index 8f8b4d5..0000000 --- a/test/chez/README.md +++ /dev/null @@ -1,51 +0,0 @@ -# Chez test harness - -The correctness gate for jolt. Pure Chez (+ Clojure for the JVM oracle). -Correctness is judged against the JVM-sourced conformance spec; the spec itself -lives in `test/conformance/` (see its `SPEC.md`). Run the whole gate with `make -test` from the repo root. - -## The spec corpus - -`corpus.edn` is the contract: ~3570 rows `{:suite :label :expected :actual :portability}`, with -`:expected` sourced from reference JVM Clojure by `test/conformance/regen-corpus.clj`. -It is frozen (the canonical source) — add or change cases here, then re-source the -answers with `regen-corpus.clj` and re-certify with `test/conformance/certify.clj`. - -## The gate runners (`host/chez/`) - -- `run-corpus.ss` — runs every corpus case through the spine (read → analyze → IR → - emit → eval, all on Chez), comparing each result by value-equality against the JVM - `:expected`. A `known-fail` allowlist covers cases jolt can't match because Chez has - no JVM host (Java classes, arrays, `BigDecimal`, opaque host-object printers, …); - the gate fails only on a NEW divergence or if the pass count drops below the floor. - - chez --script host/chez/run-corpus.ss - JOLT_CORPUS_LIMIT=200 … # every-Nth stride, fast iteration - JOLT_CHEZ_ZJ_FLOOR=N … # override the floor (see run-corpus.ss) - -- `run-unit.ss` — host-specific unit cases (`test/chez/unit.edn`) that aren't in the - JVM-portable corpus: dot-forms, java statics, io, reader, walk, vars/namespaces, - refs. Each `:expr` is evaluated in-process and its printed value compared to a baked - `:expected` (`:throws` asserts a raise). - -- `selfcheck.sh` — self-host fixpoint: `bootstrap.ss` rebuild byte-equals the - checked-in seed (`host/chez/seed/`). -- `smoke.sh` — real `bin/joltc -e` CLI smoke. -- `cts.sh` — the vendored [jank-lang/clojure-test-suite](https://github.com/jank-lang/clojure-test-suite) - (`vendor/clojure-test-suite`, a per-core-fn clojure.test suite shared across - Clojure dialects), run one namespace per `joltc` process (a hang or crash is - contained) through the `test/chez/cts-app` project and `cts-run` runner. - Per-namespace fail/error counts must exactly match the checked-in baseline - `test/chez/cts-known-failures.txt` — a namespace doing worse fails the gate, - and one doing better fails as stale until the baseline is updated in the same - change. `make cts`; - `JOLT_CTS_NS=ns1,ns2` runs a subset verbosely, - `JOLT_CTS_WRITE_BASELINE=1` regenerates the baseline. - -## Other Chez tests - -- `values-test.ss` — the value model (nil/truthiness/collections). `make values`. -- `bench-chez.ss` — compute bench through the pipeline (opt-in; not in the gate). - -All runners assume `chez` on PATH. diff --git a/test/chez/alias-leak-app/deps.edn b/test/chez/alias-leak-app/deps.edn deleted file mode 100644 index ccd9a31..0000000 --- a/test/chez/alias-leak-app/deps.edn +++ /dev/null @@ -1 +0,0 @@ -{:paths ["src"]} diff --git a/test/chez/alias-leak-app/src/fix/lib.clj b/test/chez/alias-leak-app/src/fix/lib.clj deleted file mode 100644 index 17a8208..0000000 --- a/test/chez/alias-leak-app/src/fix/lib.clj +++ /dev/null @@ -1,3 +0,0 @@ -(ns fix.lib - (:require [clojure.set :as ss])) -(defn u [] (ss/union #{1} #{2})) diff --git a/test/chez/alias-leak-app/src/fix/main.clj b/test/chez/alias-leak-app/src/fix/main.clj deleted file mode 100644 index 9bf744b..0000000 --- a/test/chez/alias-leak-app/src/fix/main.clj +++ /dev/null @@ -1,5 +0,0 @@ -(ns fix.main - (:require [clojure.string :as ss] - [fix.lib :as lib])) -(defn -main [& _] - (println (ss/upper-case "hi") (lib/u))) diff --git a/test/chez/bench-chez.ss b/test/chez/bench-chez.ss deleted file mode 100644 index 777950a..0000000 --- a/test/chez/bench-chez.ss +++ /dev/null @@ -1,40 +0,0 @@ -;; bench-chez.ss — perf probe for the Chez compute path. Loads the runtime ONCE, -;; then times compile+run of each program (min of N) over the -;; analyze->Scheme->Chez eval pipeline. Run: -;; chez --script test/chez/bench-chez.ss -(import (chezscheme)) -(load "host/chez/rt.ss") -(set-chez-ns! "clojure.core") -(load "host/chez/seed/prelude.ss") -(load "host/chez/post-prelude.ss") -(set-chez-ns! "user") -(load "host/chez/host-contract.ss") -(load "host/chez/seed/image.ss") -(load "host/chez/compile-eval.ss") - -(define runs 5) -(define benches - (list - (cons "fib" "(defn fib [n] (if (< n 2) n (+ (fib (- n 1)) (fib (- n 2))))) (fib 28)") - (cons "seq-pipe" "(loop [i 0 a 0] (if (< i 300) (recur (inc i) (+ a (reduce + 0 (map inc (filter even? (range 200)))))) a))") - (cons "reduce" "(loop [i 0 a 0] (if (< i 2000) (recur (inc i) (+ a (reduce + 0 (range 500)))) a))") - (cons "into-vec" "(loop [i 0 a 0] (if (< i 1000) (recur (inc i) (+ a (count (into [] (map inc (range 100)))))) a))") - (cons "map-build" "(loop [i 0 a 0] (if (< i 2000) (recur (inc i) (+ a (count (reduce (fn [m k] (assoc m k k)) {} (range 50))))) a))") - (cons "map-read" "(let [m (zipmap (range 100) (range 100))] (loop [i 0 a 0] (if (< i 5000) (recur (inc i) (+ a (get m (mod i 100) 0))) a)))") - (cons "str-join" "(loop [i 0 a 0] (if (< i 1000) (recur (inc i) (+ a (count (apply str (map str (range 100)))))) a))") - (cons "hof" "(loop [i 0 a 0] (if (< i 2000) (recur (inc i) (+ a (reduce + 0 (map (comp inc inc) (range 200))))) a))"))) - -(define (now-ms) - (let ((t (current-time 'time-monotonic))) - (+ (* 1000.0 (time-second t)) (/ (time-nanosecond t) 1000000.0)))) - -(for-each - (lambda (b) - (let ((name (car b)) (src (string-append "(do " (cdr b) ")"))) - (let loop ((i 0) (best +inf.0)) - (if (>= i runs) - (printf "~a\t~a ms\n" name (/ (round (* 100 best)) 100.0)) - (let ((t0 (now-ms))) - (jolt-compile-eval src "user") - (loop (+ i 1) (min best (- (now-ms) t0)))))))) - benches) diff --git a/test/chez/build-app/deps.edn b/test/chez/build-app/deps.edn deleted file mode 100644 index fff0290..0000000 --- a/test/chez/build-app/deps.edn +++ /dev/null @@ -1,8 +0,0 @@ -{:paths ["src" "resources"] - - ;; exercise the build's native-lib loading: a :process spec loads the running - ;; binary's own symbols (libc) at startup — no external file, always succeeds. - :jolt/native [{:name "libc" :process true}] - - ;; bake resources/ into the binary so io/resource resolves with no file on disk. - :jolt/build {:embed ["resources"]}} diff --git a/test/chez/build-app/resources/greeting.txt b/test/chez/build-app/resources/greeting.txt deleted file mode 100644 index 835112d..0000000 --- a/test/chez/build-app/resources/greeting.txt +++ /dev/null @@ -1 +0,0 @@ -embedded resource ok \ No newline at end of file diff --git a/test/chez/build-app/src/app/core.clj b/test/chez/build-app/src/app/core.clj deleted file mode 100644 index f9f0f34..0000000 --- a/test/chez/build-app/src/app/core.clj +++ /dev/null @@ -1,27 +0,0 @@ -(ns app.core - (:require [app.util :as util :refer [greet]] - [clojure.java.io :as io])) - -;; An aliased cross-ns defmethod: 'util/greet is passed quoted to defmethod-setup, -;; so the AOT build must register the `util` alias for app.core or it resolves to -;; ns "util" and never reaches app.util/greet (the dispatch falls to :default). -(defmethod util/greet :loud [_] "greet:loud") - -;; A defmethod on a REFERRED multifn (bare `greet`): the AOT build must register -;; the :refer so the bare name resolves to app.util/greet, not a shadow. -(defmethod greet :soft [_] "greet:soft") - -(defn -main [& args] - ;; --boom: throw through a two-deep call chain so build-smoke can assert the - ;; native stack trace. Off the normal path, so default output is unchanged. - (when (= (first args) "--boom") - (util/mid-boom "not-a-number")) - ;; the resource is baked into the binary (deps.edn :jolt/build :embed), so this - ;; resolves with no resources/ dir on disk, run from any cwd. - (println (slurp (io/resource "greeting.txt"))) - (util/twice (println (util/shout "hello from a built binary"))) - (println "args:" (vec args)) - (println "sum:" (reduce + (map count args))) - (println "greet-default:" (util/greet :unknown)) - (println "greet-loud:" (util/greet :loud)) - (println "greet-soft:" (util/greet :soft))) diff --git a/test/chez/build-app/src/app/util.clj b/test/chez/build-app/src/app/util.clj deleted file mode 100644 index ff524cb..0000000 --- a/test/chez/build-app/src/app/util.clj +++ /dev/null @@ -1,28 +0,0 @@ -(ns app.util - (:require [clojure.string :as str])) - -(defn shout [s] - (str/upper-case (str s "!"))) - -;; A two-deep non-tail call chain that throws — exercises native stack traces in a -;; direct-link build (build-smoke runs -main with a --boom sentinel arg). deep-boom -;; is defined through a USER macro: its source registration only gets a real line -;; if the reader position survives macroexpansion (so the trace frame maps). -(defmacro defguarded [name args & body] - `(defn ~name ~args (assert (number? ~(first args)) "needs a number") ~@body)) - -(defguarded deep-boom [x] - (* x 2)) - -(defn mid-boom [x] - (inc (deep-boom x))) - -(defmacro twice [x] - `(do ~x ~x)) - -;; A multimethod with a :default method. The AOT build must set the per-ns -;; current ns before these forms run, or the defmethod registers app.util/greet -;; under the wrong ns and a dispatch to :default crashes (not a fn nil). app.core -;; adds an aliased method (util/greet :loud) — see there. -(defmulti greet (fn [kind] kind)) -(defmethod greet :default [_] "greet:default") diff --git a/test/chez/clojure-test.clj b/test/chez/clojure-test.clj deleted file mode 100644 index a323dc9..0000000 --- a/test/chez/clojure-test.clj +++ /dev/null @@ -1,69 +0,0 @@ -;; Self-checking regression for clojure.test: the assert-expr / do-report / report -;; extension points plus the built-in is/are/testing/thrown?/use-fixtures surface. -;; Run via bin/joltc; prints a single sentinel line the smoke gate greps for. -(ns clojure-test-selfcheck - (:require [clojure.test :as t :refer [deftest is are testing use-fixtures run-tests]])) - -;; a library-style custom assertion registered through the assert-expr seam -(defmethod t/assert-expr 'near? [msg form] - (let [[_ a b] form] - `(if (< (let [d# (- ~a ~b)] (if (neg? d#) (- d#) d#)) 0.01) - (clojure.test/do-report {:type :pass}) - (clojure.test/do-report {:type :fail :message ~msg :form '~form})))) - -;; an ALIAS-QUALIFIED registered assertion whose simple name collides with the -;; built-in thrown? — the registered method must win over the by-name inline -;; path (clojure-test-suite's portability/thrown? registers exactly this shape). -(defmethod t/assert-expr 'p/thrown? [msg form] - `(try - (do ~@(rest form)) - (clojure.test/do-report {:type :fail :message ~msg :form '~form}) - (catch Throwable e# - (clojure.test/do-report {:type :pass}) - e#))) - -;; a custom report type (how test.check surfaces trial/shrink progress) -(def trials (atom 0)) -(defmethod t/report ::trial [_m] (swap! trials inc)) - -(def setups (atom 0)) -(use-fixtures :each (fn [f] (swap! setups inc) (f))) - -(deftest builtins - (testing "equality + predicate" - (is (= 1 1)) - (is (vector? [1]))) - (are [x y] (= x y) - 2 (+ 1 1) - 6 (* 2 3)) - ;; template vars substitute inside quote (are is clojure.template, not let) - (are [x] (special-symbol? 'x) - if - def) - (is (thrown? clojure.lang.ExceptionInfo (throw (ex-info "x" {})))) - (is (thrown-with-msg? Exception #"bad" (throw (ex-info "bad" {})))) - (is (near? 1.0 1.005)) - (is (p/thrown? (throw (ex-info "boom" {}))))) - -(deftest expected-fail - (is (= 1 2)) - (is (near? 1.0 5.0))) - -;; run-tests returns THIS call's summary; with explicit nses it runs only their -;; tests (an unknown ns runs nothing). -(def r1 (run-tests)) -(def r2 (run-tests 'no.such.test-ns)) -(t/do-report {:type ::trial}) -(t/do-report {:type ::trial}) - -;; 10 pass (= + vector? + 4 are rows + thrown? + thrown-with-msg? + near? + p/thrown?), -;; 2 fail (= 1 2, near? 1.0 5.0), 0 error, 2 fixture runs, 2 custom reports -(let [ok (and (= (t/n-pass) 10) (= (t/n-fail) 2) (= (t/n-error) 0) - (= 2 (:test r1)) (= 10 (:pass r1)) (= 2 (:fail r1)) - (= 0 (:test r2)) (= 0 (:pass r2)) - (= @setups 2) (= @trials 2))] - (println (if ok - "CLOJURE-TEST OK" - (str "CLOJURE-TEST FAIL pass=" (t/n-pass) " fail=" (t/n-fail) - " error=" (t/n-error) " r1=" (pr-str r1) " r2=" (pr-str r2) - " setups=" @setups " trials=" @trials)))) diff --git a/test/chez/corpus.edn b/test/chez/corpus.edn deleted file mode 100644 index c4117b4..0000000 --- a/test/chez/corpus.edn +++ /dev/null @@ -1,3587 +0,0 @@ -[ - {:suite "host-interop / reify ILookup" :label "(get reify k) / (:k reify) / (get reify k d) route to valAt" :expected "[1 1 :dflt]" :actual "(let [r (reify clojure.lang.ILookup (valAt [_ k] (get {:a 1} k)) (valAt [_ k d] (get {:a 1} k d)))] [(:a r) (get r :a) (get r :z :dflt)])" :portability :jvm} - {:suite "regex / alternation submatch" :label "a non-participating alternation group is nil, not a stale capture" :expected "[\"2r11\" nil \"2\" \"11\"]" :actual "(re-matches #\"(?:([0-9])|([0-9])r([0-9]+))\" \"2r11\")" :portability :common} - {:suite "regex / radix read" :label "tools.reader-style radix parse: winning branch's groups, not the losing one's" :expected "[12 255]" :actual "[(read-string \"2r1100\") (read-string \"16rFF\")]" :portability :common} - {:suite "numbers / comparison error class" :label "nil operand is NPE, non-number is CCE" :expected "[\"java.lang.NullPointerException\" \"java.lang.ClassCastException\"]" :actual "[(try (> nil 5) (catch Throwable e (.getName (class e)))) (try (> :k 5) (catch Throwable e (.getName (class e))))]" :portability :jvm} - {:suite "reader / quoted #inst constructs a value" :label "a quoted #inst literal is the constructed Date, not a tagged form" :expected "\"(f #inst \\\"1939-01-01T00:00:00.000-00:00\\\")\"" :actual "(pr-str (quote (f #inst \"1939\")))" :portability :common} - {:suite "fn / kwargs trailing map" :label "(f :k v {map}) and (f {map}) both bind & {:as m}" :expected "[{:x 1 :y 2} {:x 1 :y 2}]" :actual "[((fn [a & {:as m}] m) 1 :x 1 {:y 2}) ((fn [a & {:as m}] m) 1 {:x 1 :y 2})]" :portability :common} - {:suite "destructure / :or" :label "map default when key absent" :expected "9" :actual "(let [{x :x :or {x 9}} {}] x)" :portability :common} - {:suite "destructure / :or" :label "kwargs default when key absent" :expected "9" :actual "((fn [& {x :x :or {x 9}}] x))" :portability :common} - {:suite "destructure / :or" :label "default not used when key present" :expected "5" :actual "(let [{x :x :or {x 9}} {:x 5}] x)" :portability :common} - {:suite "destructure / for :let" :label "a for/doseq :let binding may itself destructure" :expected "[10 20]" :actual "(vec (for [x [1 2] :let [{:keys [y]} {:y (* x 10)}]] y))" :portability :common} - {:suite "deftype / method param shadows field" :label "a method param named like a field shadows it (Clojure scope)" :expected "9" :actual "(do (defprotocol P (setm [this q])) (defrecord R [k m] P (setm [this m] (assoc this :m m))) (:m (setm (->R 1 nil) 9)))" :portability :common} - {:suite "walk / eager" :label "clojure.walk is eager over a lazy seq (side effects run now)" :expected "3" :actual "(let [a (atom 0)] (clojure.walk/postwalk (fn [x] (when (number? x) (swap! a inc)) x) (map inc (list 1 2 3))) @a)" :portability :common} - {:suite "chars / isWhitespace" :label "Character/isWhitespace matches the JVM (Unicode line-sep yes, no-break space no)" :expected "[true true false false]" :actual "(mapv (fn [c] (Character/isWhitespace (char c))) [0x2028 32 0x00A0 65])" :portability :jvm} - {:suite "deftype / field access" :label ".field reads a deftype field" :expected "7" :actual "(do (deftype FldT [q]) (.q (->FldT 7)))" :portability :jvm} - {:suite "fn / pre-post" :label ":pre + :post pass" :expected "5" :actual "(do (defn ppf [x] {:pre [(pos? x)] :post [(= % x)]} x) (ppf 5))" :portability :common} - {:suite "fn / pre-post" :label ":pre failure throws" :expected ":blocked" :actual "(do (defn ppg [x] {:pre [(pos? x)]} x) (try (ppg -1) (catch Throwable _ :blocked)))" :portability :common} - {:suite "deftype / map-like dispatch" :label "dissoc + keys via IPersistentMap/Seqable methods" :expected "[:b]" :actual "(do (deftype MapT [m] clojure.lang.Seqable (seq [_] (seq m)) clojure.lang.IPersistentMap (without [_ k] (->MapT (dissoc m k))) (assoc [_ k v] (->MapT (assoc m k v)))) (vec (keys (dissoc (->MapT {:a 1 :b 2}) :a))))" :portability :jvm} - {:suite "delay / exception memoization" :label "throwing body runs once, stays realized, re-throws" :expected "[1 true]" :actual "(let [n (atom 0) d (delay (swap! n inc) (throw (ex-info \"e\" {})))] (dotimes [_ 3] (try (deref d) (catch Throwable _ nil))) [(deref n) (realized? d)])" :portability :common} - {:suite "queue / pop" :label "pop of empty PersistentQueue returns empty" :expected "nil" :actual "(seq (pop clojure.lang.PersistentQueue/EMPTY))" :portability :jvm} - {:suite "interop / iterator-seq" :label "iterator-seq over .iterator" :expected "[:a :b]" :actual "(vec (iterator-seq (.iterator [:a :b])))" :portability :jvm} - {:suite "deftype / IPersistentStack" :label "peek/pop dispatch" :expected "[1 [2 3]]" :actual "(do (deftype Stk [v] clojure.lang.IPersistentStack (peek [_] (first v)) (pop [_] (->Stk (rest v)))) [(peek (->Stk [1 2 3])) (vec (.v (pop (->Stk [1 2 3]))))])" :portability :jvm} - {:suite "deftype / equiv" :label "(= deftype other) uses equiv method" :expected "true" :actual "(do (deftype EqT [m] clojure.lang.IPersistentCollection (equiv [_ o] (= o m)) clojure.lang.Seqable (seq [_] (seq m))) (= (->EqT {:a 1}) {:a 1}))" :portability :jvm} - {:suite "deftype / IDeref" :label "@ dispatches to the deref method" :expected "7" :actual "(do (deftype Box [v] clojure.lang.IDeref (deref [_] v)) (deref (->Box 7)))" :portability :jvm} - {:suite "reify / IDeref" :label "@ dispatches to the deref method" :expected "7" :actual "(deref (reify clojure.lang.IDeref (deref [_] 7)))" :portability :jvm} - {:suite "deftype / mutable field" :label "set! is observed by a later read in the same method" :expected "9" :actual "(do (deftype B [^:unsynchronized-mutable v] clojure.lang.IDeref (deref [_] (set! v 9) v)) (deref (->B 0)))" :portability :jvm} - {:suite "def / metadata evaluation" :label "a symbol metadata value evaluates to its var" :expected "true" :actual "(do (def ^{:af rest} mv 1) (fn? (:af (meta (var mv)))))" :portability :common} - {:suite "def / metadata evaluation" :label "an expression metadata value is evaluated" :expected "3" :actual "(do (def ^{:k (+ 1 2)} mv2 1) (:k (meta (var mv2))))" :portability :common} - {:suite "interop / class ancestry" :label "(ancestors (class fn)) includes a callable interface" :expected "true" :actual "(boolean (some #{java.lang.Runnable java.util.concurrent.Callable} (ancestors (class identity))))" :portability :jvm} - {:suite "interop / AssertionError" :label "construct + catch as Throwable" :expected "\"boom\"" :actual "(try (throw (AssertionError. \"boom\")) (catch Throwable e (.getMessage e)))" :portability :jvm} - {:suite "try / multi-catch" :label "dispatches to the matching class clause, not the first" :expected ":rte" :actual "(try (throw (RuntimeException. \"x\")) (catch NullPointerException _ :npe) (catch RuntimeException _ :rte) (catch Exception _ :exc))" :portability :jvm} - {:suite "try / multi-catch" :label "Error is not caught by an Exception clause" :expected ":thr" :actual "(try (throw (Error. \"e\")) (catch Exception _ :exc) (catch Throwable _ :thr))" :portability :jvm} - {:suite "try / multi-catch" :label "no matching clause re-throws to an outer catch" :expected ":outer" :actual "(try (try (throw (RuntimeException. \"x\")) (catch NullPointerException _ :npe)) (catch Exception _ :outer))" :portability :jvm} - {:suite "try / multi-catch" :label "a host condition is caught by its RuntimeException subclass" :expected ":arith" :actual "(try (/ 1 0) (catch ArithmeticException _ :arith) (catch Throwable _ :other))" :portability :common} - {:suite "locking" :label "returns the body value" :expected "42" :actual "(let [o (Object.)] (locking o 42))" :portability :common} - {:suite "locking" :label "reentrant on the same object" :expected "42" :actual "(let [o (Object.)] (locking o (locking o 42)))" :portability :common} - {:suite "defn / docstring" :label "leading docstring becomes :doc metadata" :expected "\"the docs\"" :actual "(do (defn dd \"the docs\" [x] x) (:doc (meta (var dd))))" :portability :common} - {:suite "assert" :label "failed assert throws AssertionError" :expected ":ae" :actual "(try (assert false) (catch AssertionError _ :ae))" :portability :common} - {:suite "fn / pre-post" :label ":pre failure throws AssertionError" :expected ":caught" :actual "(do (defn pp [x] {:pre [(pos? x)]} x) (try (pp -1) (catch AssertionError _ :caught)))" :portability :common} - {:suite "interop / Seqable" :label "a vector is Seqable but not an ISeq" :expected "[true false]" :actual "[(instance? clojure.lang.Seqable [1 2 3]) (instance? clojure.lang.ISeq [1 2 3])]" :portability :jvm} - {:suite "interop / Seqable" :label "a map is Seqable" :expected "true" :actual "(instance? clojure.lang.Seqable {:a 1})" :portability :jvm} - {:suite "extend-protocol / class value" :label "extend to (Class/forName \"[B\") dispatches a byte-array" :expected "[:ba :str]" :actual "(do (defprotocol P (m [x])) (extend-protocol P (Class/forName \"[B\") (m [bs] :ba) String (m [s] :str)) [(m (byte-array 1)) (m \"x\")])" :portability :jvm} - {:suite "interop / ByteBuffer" :label "wrap then remaining + array" :expected "[3 [1 2 3]]" :actual "(let [bb (java.nio.ByteBuffer/wrap (byte-array [1 2 3]))] [(.remaining bb) (vec (.array bb))])" :portability :jvm} - {:suite "interop / ByteBuffer" :label "get drains into a byte-array" :expected "[1 2]" :actual "(let [bb (java.nio.ByteBuffer/wrap (byte-array [1 2])) d (byte-array 2)] (.get bb d) (vec d))" :portability :jvm} - {:suite "interop / Arrays" :label "equals on byte arrays" :expected "true" :actual "(java.util.Arrays/equals (byte-array [1 2 3]) (byte-array [1 2 3]))" :portability :jvm} - {:suite "interop / Arrays" :label "equals on unequal byte arrays" :expected "false" :actual "(java.util.Arrays/equals (byte-array [1 2]) (byte-array [1 9]))" :portability :jvm} - {:suite "interop / URI" :label "URI/create static factory" :expected "\"x.com\"" :actual "(.getHost (java.net.URI/create \"http://x.com/p\"))" :portability :jvm} - {:suite "interop / Thread" :label "start + join runs the thunk" :expected "7" :actual "(let [a (atom 0) t (Thread. (fn [] (reset! a 7)))] (.start t) (.join t) (deref a))" :portability :jvm} - {:suite "interop / CountDownLatch" :label "countDown to zero, await returns" :expected "0" :actual "(let [l (java.util.concurrent.CountDownLatch. 1)] (.countDown l) (.await l) (.getCount l))" :portability :jvm} - {:suite "interop / SoftReference" :label "get returns the referent" :expected ":v" :actual "(.get (java.lang.ref.SoftReference. :v))" :portability :jvm} - {:suite "interop / System.gc" :label "gc runs and returns" :expected "42" :actual "(do (System/gc) 42)" :portability :jvm} - {:suite "interop / ConcurrentHashMap" :label "put + get/count/contains?" :expected "[1 1 true]" :actual "(let [m (java.util.concurrent.ConcurrentHashMap.)] (.put m :a 1) [(get m :a) (count m) (contains? m :a)])" :portability :jvm} - {:suite "interop / Class.forName" :label "unknown class throws ClassNotFoundException" :expected ":nf" :actual "(try (Class/forName \"no.such.Klass\") (catch ClassNotFoundException _ :nf))" :portability :jvm} - {:suite "interop / Class.forName" :label "known class resolves" :expected "\"java.lang.String\"" :actual "(.getName (Class/forName \"java.lang.String\"))" :portability :jvm} - {:suite "clojure.string / replace" :label "char match and replacement" :expected "\"a-b-c\"" :actual "(clojure.string/replace \"a/b/c\" \\/ \\-)" :portability :common} - {:suite "clojure.string / replace" :label "char match, string replacement" :expected "\"x_y\"" :actual "(clojure.string/replace \"x.y\" \\. \"_\")" :portability :common} - {:suite "interop-fixes / deprecated #^ metadata reader" :label "#^ type hint on a param" :expected "\"x\"" :actual "(do (defn f1 [#^String s] s) (f1 \"x\"))" :portability :common} - {:suite "interop-fixes / deprecated #^ metadata reader" :label "#^\"[B\" array hint" :expected "[1 2]" :actual "(do (defn f2 [#^\"[B\" b] b) (f2 [1 2]))" :portability :common} - {:suite "interop-fixes / deprecated #^ metadata reader" :label "#^ is equivalent to ^" :expected "true" :actual "(= (meta (with-meta [] {:tag (quote String)})) {:tag (quote String)})" :portability :common} - {:suite "interop-fixes / (str pattern) yields raw source" :label "str of a regex" :expected "\"abc\"" :actual "(str #\"abc\")" :portability :common} - {:suite "interop-fixes / (str pattern) yields raw source" :label "compose patterns via str" :expected "true" :actual "(boolean (re-matches (re-pattern (str #\"<\" \"(.*)\" \">\")) \"\"))" :portability :common} - {:suite "interop-fixes / into onto a map" :label "merges map items" :expected "true" :actual "(= {:a 1 :b 2} (into {} [{:a 1} {:b 2}]))" :portability :common} - {:suite "interop-fixes / into onto a map" :label "accepts [k v] pairs" :expected "true" :actual "(= {:a 1} (into {} [[:a 1]]))" :portability :common} - {:suite "interop-fixes / into onto a map" :label "map item onto empty {}" :expected "true" :actual "(= {:x 1} (into {} (list {:x 1})))" :portability :common} - {:suite "interop-fixes / into onto a map" :label "conj a map onto {}" :expected "true" :actual "(= {:a 1} (conj {} {:a 1}))" :portability :common} - {:suite "interop-fixes / a var is callable as its value" :label "call a var directly" :expected "42" :actual "(do (def vf (fn [x] (inc x))) ((var vf) 41))" :portability :common} - {:suite "interop-fixes / a var is callable as its value" :label "var bound as a client fn" :expected "\"ok\"" :actual "(do (def base (fn [_] \"ok\")) (def mw (fn [client] (fn [req] (client req)))) ((mw (var base)) {}))" :portability :common} - {:suite "control / conditionals" :label "if true" :expected "1" :actual "(if true 1 2)" :portability :common} - {:suite "control / conditionals" :label "if false" :expected "2" :actual "(if false 1 2)" :portability :common} - {:suite "control / conditionals" :label "if nil is false" :expected "2" :actual "(if nil 1 2)" :portability :common} - {:suite "control / conditionals" :label "if no else" :expected "nil" :actual "(if false 1)" :portability :common} - {:suite "control / conditionals" :label "when true" :expected "3" :actual "(when true 1 2 3)" :portability :common} - {:suite "control / conditionals" :label "when false" :expected "nil" :actual "(when false 1)" :portability :common} - {:suite "control / conditionals" :label "when-not" :expected "1" :actual "(when-not false 1)" :portability :common} - {:suite "control / conditionals" :label "cond" :expected ":b" :actual "(cond false :a true :b :else :c)" :portability :common} - {:suite "control / conditionals" :label "cond :else" :expected ":c" :actual "(cond false :a false :b :else :c)" :portability :common} - {:suite "control / conditionals" :label "cond no match" :expected "nil" :actual "(cond false :a)" :portability :common} - {:suite "control / conditionals" :label "condp" :expected "\"two\"" :actual "(condp = 2 1 \"one\" 2 \"two\" \"other\")" :portability :common} - {:suite "control / conditionals" :label "case" :expected ":b" :actual "(case 2 1 :a 2 :b :default)" :portability :common} - {:suite "control / conditionals" :label "case default" :expected ":d" :actual "(case 9 1 :a 2 :b :d)" :portability :common} - {:suite "control / conditionals" :label "case multi" :expected ":ab" :actual "(case 2 (1 2) :ab 3 :c)" :portability :common} - {:suite "control / conditionals" :label "case symbol const" :expected ":s" :actual "(case 'foo foo :s :default)" :portability :common} - {:suite "control / conditionals" :label "case vector const" :expected ":v" :actual "(case [1 2] [1 2] :v :default)" :portability :common} - {:suite "control / conditionals" :label "case map const" :expected ":m" :actual "(case {:a 1} {:a 1} :m :default)" :portability :common} - {:suite "control / conditionals" :label "case list const" :expected ":l" :actual "(case '(a b) (quote (a b)) :l :default)" :portability :common} - {:suite "control / conditionals" :label "case keyword" :expected ":k" :actual "(case :x :x :k :default)" :portability :common} - {:suite "control / logic" :label "and all true" :expected "3" :actual "(and 1 2 3)" :portability :common} - {:suite "control / logic" :label "and short circuits" :expected "nil" :actual "(and 1 nil 3)" :portability :common} - {:suite "control / logic" :label "and empty" :expected "true" :actual "(and)" :portability :common} - {:suite "control / logic" :label "or first truthy" :expected "1" :actual "(or nil 1 2)" :portability :common} - {:suite "control / logic" :label "or all false" :expected "false" :actual "(or nil false)" :portability :common} - {:suite "control / logic" :label "or empty" :expected "nil" :actual "(or)" :portability :common} - {:suite "control / logic" :label "not" :expected "false" :actual "(not true)" :portability :common} - {:suite "control / let & loop" :label "let" :expected "3" :actual "(let [a 1 b 2] (+ a b))" :portability :common} - {:suite "control / let & loop" :label "let sequential" :expected "3" :actual "(let [a 1 b (+ a 2)] b)" :portability :common} - {:suite "control / let & loop" :label "let shadowing" :expected "2" :actual "(let [a 1] (let [a 2] a))" :portability :common} - {:suite "control / let & loop" :label "letfn mutual" :expected "true" :actual "(letfn [(ev? [n] (if (zero? n) true (od? (dec n)))) (od? [n] (if (zero? n) false (ev? (dec n))))] (ev? 10))" :portability :common} - {:suite "control / let & loop" :label "loop/recur" :expected "15" :actual "(loop [i 1 acc 0] (if (> i 5) acc (recur (inc i) (+ acc i))))" :portability :common} - {:suite "control / let & loop" :label "when-let" :expected "2" :actual "(when-let [x 1] (inc x))" :portability :common} - {:suite "control / let & loop" :label "when-let nil" :expected "nil" :actual "(when-let [x nil] (inc x))" :portability :common} - {:suite "control / let & loop" :label "if-let" :expected "2" :actual "(if-let [x 1] (inc x) :none)" :portability :common} - {:suite "control / let & loop" :label "if-let else" :expected ":none" :actual "(if-let [x nil] (inc x) :none)" :portability :common} - {:suite "control / let & loop" :label "if-some zero" :expected "1" :actual "(if-some [x 0] (inc x) :none)" :portability :common} - {:suite "control / let & loop" :label "when-some nil" :expected "nil" :actual "(when-some [x nil] x)" :portability :common} - {:suite "control / conditional-binding scope" :label "if-let else sees outer" :expected "5" :actual "(let [x 5] (if-let [x nil] :then x))" :portability :common} - {:suite "control / conditional-binding scope" :label "if-let then binds" :expected "7" :actual "(let [x 5] (if-let [x 7] x :else))" :portability :common} - {:suite "control / conditional-binding scope" :label "if-some else sees outer" :expected "5" :actual "(let [x 5] (if-some [x nil] :then x))" :portability :common} - {:suite "control / conditional-binding scope" :label "if-some binds false" :expected "false" :actual "(if-some [x false] x :else)" :portability :common} - {:suite "control / conditional-binding scope" :label "when-let else via or" :expected "5" :actual "(let [x 5] (or (when-let [x nil] x) x))" :portability :common} - {:suite "control / conditional-binding scope" :label "when-let multi-form body" :expected "14" :actual "(when-let [x 7] (inc x) (* x 2))" :portability :common} - {:suite "control / conditional-binding scope" :label "if-let in fn param" :expected "9" :actual "((fn [xs] (if-let [xs nil] :then xs)) 9)" :portability :common} - {:suite "control / conditional-binding scope" :label "when-some binds zero" :expected "1" :actual "(when-some [x 0] (inc x))" :portability :common} - {:suite "control / conditional-binding scope" :label "if-let evals test once" :expected "1" :actual "(let [c (atom 0)] (if-let [v (do (swap! c inc) :v)] @c :none))" :portability :common} - {:suite "control / loop lowering" :label "closure captures per-iter binding" :expected "[0 1 2]" :actual "(mapv (fn [g] (g)) (loop [i 0 fs []] (if (< i 3) (recur (inc i) (conj fs (fn [] i))) fs)))" :portability :common} - {:suite "control / loop lowering" :label "fib via loop" :expected "55" :actual "(loop [a 0 b 1 i 0] (if (= i 10) a (recur b (+ a b) (inc i))))" :portability :common} - {:suite "control / loop lowering" :label "recur args no clobber" :expected "[2 1]" :actual "(loop [a 1 b 2 n 0] (if (= n 1) [a b] (recur b a (inc n))))" :portability :common} - {:suite "control / loop lowering" :label "nested loops" :expected "9" :actual "(loop [i 0 s 0] (if (= i 3) s (recur (inc i) (loop [j 0 t s] (if (= j 3) t (recur (inc j) (inc t)))))))" :portability :common} - {:suite "control / loop lowering" :label "loop sequential init" :expected "12" :actual "(loop [a 1 b (+ a 10)] (+ a b))" :portability :common} - {:suite "control / loop lowering" :label "recur through let" :expected "6" :actual "(loop [i 0 acc 0] (let [x (* i 2)] (if (< i 3) (recur (inc i) (+ acc x)) acc)))" :portability :common} - {:suite "control / loop lowering" :label "fn-arity recur intact" :expected "15" :actual "((fn f [n acc] (if (zero? n) acc (recur (dec n) (+ acc n)))) 5 0)" :portability :common} - {:suite "control / iteration" :label "dotimes side-effect" :expected "5" :actual "(let [a (atom 0)] (dotimes [i 5] (swap! a inc)) @a)" :portability :common} - {:suite "control / iteration" :label "while" :expected "5" :actual "(let [a (atom 0)] (while (< @a 5) (swap! a inc)) @a)" :portability :common} - {:suite "control / iteration" :label "for" :expected "[0 1 2]" :actual "(for [x (range 3)] x)" :portability :common} - {:suite "control / iteration" :label "for nested" :expected "[[0 :a] [0 :b] [1 :a] [1 :b]]" :actual "(for [x (range 2) y [:a :b]] [x y])" :portability :common} - {:suite "control / iteration" :label "for :when" :expected "[0 2 4]" :actual "(for [x (range 6) :when (even? x)] x)" :portability :common} - {:suite "control / iteration" :label "for :while" :expected "[0 1 2]" :actual "(for [x (range 10) :while (< x 3)] x)" :portability :common} - {:suite "control / iteration" :label "for :let" :expected "[0 1 4]" :actual "(for [x (range 3) :let [sq (* x x)]] sq)" :portability :common} - {:suite "control / iteration" :label "for :let+:when" :expected "[4 6 8]" :actual "(for [x (range 5) :let [y (* x 2)] :when (> y 3)] y)" :portability :common} - {:suite "control / iteration" :label "for multi :when" :expected "[[1 :a] [1 :b]]" :actual "(for [x [0 1] :when (odd? x) y [:a :b]] [x y])" :portability :common} - {:suite "control / iteration" :label "for destructure" :expected "[3 7]" :actual "(for [[a b] [[1 2] [3 4]]] (+ a b))" :portability :common} - {:suite "control / iteration" :label "doseq side-effect" :expected "6" :actual "(let [a (atom 0)] (doseq [x [1 2 3]] (swap! a (fn [v] (+ v x)))) @a)" :portability :common} - {:suite "control / iteration" :label "doseq nested" :expected "4" :actual "(let [c (atom 0)] (doseq [x [1 2] y [10 20]] (swap! c inc)) @c)" :portability :common} - {:suite "control / iteration" :label "doseq :when" :expected "[1 3]" :actual "(let [a (atom [])] (doseq [x [1 2 3] :when (odd? x)] (swap! a conj x)) @a)" :portability :common} - {:suite "control / iteration" :label "doseq :while" :expected "6" :actual "(let [a (atom 0)] (doseq [x (range 10) :while (< x 4)] (swap! a + x)) @a)" :portability :common} - {:suite "control / iteration" :label "doseq :let" :expected "[0 1 4]" :actual "(let [a (atom [])] (doseq [x (range 3) :let [sq (* x x)]] (swap! a conj sq)) @a)" :portability :common} - {:suite "control / iteration" :label "doseq returns nil" :expected "nil" :actual "(doseq [x [1 2 3]] x)" :portability :common} - {:suite "control / threading" :label "->" :expected "6" :actual "(-> 1 inc (+ 4))" :portability :common} - {:suite "control / threading" :label "-> with forms" :expected "[1 2 3]" :actual "(-> [] (conj 1) (conj 2) (conj 3))" :portability :common} - {:suite "control / threading" :label "->>" :expected "9" :actual "(->> [1 2 3] (map inc) (reduce +))" :portability :common} - {:suite "control / threading" :label "as->" :expected "2" :actual "(as-> [0 1] x (map inc x) (reverse x) (first x))" :portability :common} - {:suite "control / threading" :label "some->" :expected "2" :actual "(some-> 1 inc)" :portability :common} - {:suite "control / threading" :label "some-> nil stops" :expected "nil" :actual "(some-> nil inc)" :portability :common} - {:suite "control / threading" :label "some->>" :expected "[2 3]" :actual "(some->> [1 2] (map inc))" :portability :common} - {:suite "control / threading" :label "cond->" :expected "2" :actual "(cond-> 1 true inc false inc)" :portability :common} - {:suite "control / threading" :label "cond->>" :expected "[1 2]" :actual "(cond->> [2] true (cons 1))" :portability :common} - {:suite "control / threading" :label "doto returns subject" :expected "5" :actual "(let [a (doto (atom 0) (reset! 5))] @a)" :portability :common} - {:suite "deftype / custom toString" :label ".toString uses the method" :expected "\"hi\"" :actual "(do (deftype Foo [s] Object (toString [_] s)) (.toString (->Foo \"hi\")))" :portability :jvm} - {:suite "deftype / custom toString" :label "str uses the method" :expected "\"hi\"" :actual "(do (deftype Foo [s] Object (toString [_] s)) (str (->Foo \"hi\")))" :portability :common} - {:suite "deftype / custom toString" :label "str concatenation uses it" :expected "\"\"" :actual "(do (deftype Foo [s] Object (toString [_] s)) (str \"<\" (->Foo \"hi\") \">\"))" :portability :common} - {:suite "deftype / custom toString" :label "computed toString" :expected "\"v=7\"" :actual "(do (deftype Boxed [v] Object (toString [_] (str \"v=\" v))) (str (->Boxed 7)))" :portability :common} - {:suite "deftype / custom toString" :label "defrecord without toString keeps repr" :expected "true" :actual "(do (defrecord Bar [x]) (boolean (re-find #\"Bar\" (str (->Bar 1)))))" :portability :common} - {:suite "deftype / custom toString" :label "pr-str of a defrecord is the repr" :expected "true" :actual "(do (defrecord Baz [x]) (boolean (re-find #\"\\{\" (pr-str (->Baz 1)))))" :portability :common} - {:suite "destructure / sequential" :label "basic vector" :expected "3" :actual "(let [[a b] [1 2]] (+ a b))" :portability :common} - {:suite "destructure / sequential" :label "skip with _" :expected "3" :actual "(let [[_ b] [1 2]] (+ b 1))" :portability :common} - {:suite "destructure / sequential" :label "rest with &" :expected "[3 4]" :actual "(let [[a & more] [1 3 4]] more)" :portability :common} - {:suite "destructure / sequential" :label ":as whole" :expected "[1 2]" :actual "(let [[a :as v] [1 2]] v)" :portability :common} - {:suite "destructure / sequential" :label "nested" :expected "3" :actual "(let [[[a b]] [[1 2]]] (+ a b))" :portability :common} - {:suite "destructure / sequential" :label "fewer values nil" :expected "nil" :actual "(let [[a b c] [1 2]] c)" :portability :common} - {:suite "destructure / sequential" :label "over a list" :expected "1" :actual "(let [[a] (list 1 2)] a)" :portability :common} - {:suite "destructure / sequential" :label "over a seq" :expected "2" :actual "(let [[a b] (rest [9 1 2])] b)" :portability :common} - {:suite "destructure / sequential" :label "string chars" :expected "\\a" :actual "(let [[a] (seq \"ab\")] a)" :portability :common} - {:suite "destructure / associative" :label "keys" :expected "3" :actual "(let [{:keys [a b]} {:a 1 :b 2}] (+ a b))" :portability :common} - {:suite "destructure / associative" :label ":as map" :expected "{:a 1}" :actual "(let [{:as m} {:a 1}] m)" :portability :common} - {:suite "destructure / associative" :label ":or default" :expected "9" :actual "(let [{:keys [a] :or {a 9}} {}] a)" :portability :common} - {:suite "destructure / associative" :label ":or present" :expected "1" :actual "(let [{:keys [a] :or {a 9}} {:a 1}] a)" :portability :common} - {:suite "destructure / associative" :label "explicit binding" :expected "1" :actual "(let [{x :a} {:a 1}] x)" :portability :common} - {:suite "destructure / associative" :label "nested map" :expected "2" :actual "(let [{{b :b} :a} {:a {:b 2}}] b)" :portability :common} - {:suite "destructure / associative" :label "keys + as" :expected "[1 {:a 1}]" :actual "(let [{:keys [a] :as m} {:a 1}] [a m])" :portability :common} - {:suite "destructure / associative" :label "map in vector" :expected "1" :actual "(let [[{:keys [a]}] [{:a 1}]] a)" :portability :common} - {:suite "destructure / in forms" :label "fn params" :expected "3" :actual "((fn [[a b]] (+ a b)) [1 2])" :portability :common} - {:suite "destructure / in forms" :label "fn map param" :expected "1" :actual "((fn [{:keys [a]}] a) {:a 1})" :portability :common} - {:suite "destructure / in forms" :label "defn destructure" :expected "3" :actual "(do (defn f [[a b]] (+ a b)) (f [1 2]))" :portability :common} - {:suite "destructure / in forms" :label "loop destructure" :expected "3" :actual "(loop [[a b] [1 2]] (+ a b))" :portability :common} - {:suite "destructure / in forms" :label "doseq destructure" :expected "12" :actual "(let [s (atom 0)] (doseq [[k v] {:a 4 :b 8}] (swap! s (fn [x] (+ x v)))) @s)" :portability :common} - {:suite "destructure / in forms" :label "for destructure" :expected "[3 7]" :actual "(for [[a b] [[1 2] [3 4]]] (+ a b))" :portability :common} - {:suite "destructure / in forms" :label "& rest in fn" :expected "[2 3]" :actual "((fn [a & more] more) 1 2 3)" :portability :common} - {:suite "destructure / associative extras" :label ":strs" :expected "7" :actual "(let [{:strs [a]} {\"a\" 7}] a)" :portability :common} - {:suite "destructure / associative extras" :label ":syms" :expected "8" :actual "(let [{:syms [a]} {(quote a) 8}] a)" :portability :common} - {:suite "destructure / associative extras" :label "namespaced :keys" :expected "3" :actual "(let [{:keys [x/y]} {:x/y 3}] y)" :portability :common} - {:suite "destructure / associative extras" :label "namespaced :syms" :expected "4" :actual "(let [{:syms [p/q]} {(quote p/q) 4}] q)" :portability :common} - {:suite "destructure / associative extras" :label "keyword :keys" :expected "3" :actual "(let [{:keys [:a :b]} {:a 1 :b 2}] (+ a b))" :portability :common} - {:suite "destructure / associative extras" :label "keyword :keys ns" :expected "3" :actual "(let [{:keys [:x/y]} {:x/y 3}] y)" :portability :common} - {:suite "destructure / keyword args (& {:keys})" :label "fn kwargs" :expected "[1 2]" :actual "(do (defn f [& {:keys [a b]}] [a b]) (f :a 1 :b 2))" :portability :common} - {:suite "destructure / keyword args (& {:keys})" :label "fn kwargs + fixed" :expected "[0 5]" :actual "(do (defn g [x & {:keys [a]}] [x a]) (g 0 :a 5))" :portability :common} - {:suite "destructure / keyword args (& {:keys})" :label "fn kwargs :or" :expected "9" :actual "(do (defn h [& {:keys [a] :or {a 9}}] a) (h))" :portability :common} - {:suite "destructure / keyword args (& {:keys})" :label "fn kwargs trailing map" :expected "7" :actual "(do (defn k [& {:keys [a]}] a) (k {:a 7}))" :portability :common} - {:suite "destructure / fn params & loop" :label "fn vector param" :expected "7" :actual "((fn [[a b]] (+ a b)) [3 4])" :portability :common} - {:suite "destructure / fn params & loop" :label "fn map param" :expected "30" :actual "((fn [{:keys [x y]}] (* x y)) {:x 5 :y 6})" :portability :common} - {:suite "destructure / fn params & loop" :label "fn :or param" :expected "7" :actual "((fn [{:keys [x] :or {x 7}}] x) {})" :portability :common} - {:suite "destructure / fn params & loop" :label "fn multi-arity destr" :expected "15" :actual "((fn ([[a]] a) ([[a] b] (+ a b))) [10] 5)" :portability :common} - {:suite "destructure / fn params & loop" :label "loop vector binding" :expected "[4 2]" :actual "(loop [[a b] [1 2] n 0] (if (< n 3) (recur [(inc a) b] (inc n)) [a b]))" :portability :common} - {:suite "destructure / fn params & loop" :label "loop map binding" :expected "4" :actual "(loop [{:keys [v]} {:v 1} n 0] (if (< n 2) (recur {:v (* v 2)} (inc n)) v))" :portability :common} - {:suite "destructure / fn params & loop" :label "loop init sees destr" :expected "[1 2 3]" :actual "(loop [[a b] [1 2] c (+ a b)] [a b c])" :portability :common} - {:suite "destructure / primitives reject patterns" :label "fn* fixed pattern" :expected :throws :actual "((fn* [[a b]] a) [1 2])" :portability :common} - {:suite "destructure / primitives reject patterns" :label "fn* rest pattern" :expected :throws :actual "((fn* [a & [b]] b) 1 2 3)" :portability :common} - {:suite "destructure / primitives reject patterns" :label "let* pattern" :expected :throws :actual "(let* [[a b] [1 2]] a)" :portability :common} - {:suite "destructure / primitives reject patterns" :label "loop* pattern" :expected :throws :actual "(loop* [[a b] [1 2]] a)" :portability :common} - {:suite "destructure / primitives reject patterns" :label "fn desugars" :expected "[1 2]" :actual "((fn [[a b]] [a b]) [1 2])" :portability :common} - {:suite "destructure / primitives reject patterns" :label "let desugars" :expected "[1 2]" :actual "(let [[a b] [1 2]] [a b])" :portability :common} - {:suite "destructure / macro params" :label "macro & [a & more :as all]" :expected "[1 [2 3] [1 2 3]]" :actual "(do (defmacro m [& [a & more :as all]] (list (quote quote) [a (vec more) (vec all)])) (m 1 2 3))" :portability :common} - {:suite "destructure / macro params" :label "macro fixed destructure" :expected "[2 1]" :actual "(do (defmacro mm [[a b]] (list (quote quote) [b a])) (mm [1 2]))" :portability :common} - {:suite "destructure / macro params" :label "macro & {:keys}" :expected "5" :actual "(do (defmacro mk [& {:keys [x]}] (list (quote quote) x)) (mk :x 5))" :portability :common} - {:suite "exceptions / try-catch" :label "catch :default" :expected ":caught" :actual "(try (throw (ex-info \"boom\" {})) (catch :default e :caught))" :portability :common} - {:suite "exceptions / try-catch" :label "catch by class" :expected ":caught" :actual "(try (throw (ex-info \"boom\" {})) (catch Exception e :caught))" :portability :common} - {:suite "exceptions / try-catch" :label "catch binds error" :expected "\"boom\"" :actual "(try (throw (ex-info \"boom\" {})) (catch :default e (ex-message e)))" :portability :common} - {:suite "exceptions / try-catch" :label "no throw -> body" :expected "1" :actual "(try 1 (catch :default e :caught))" :portability :common} - {:suite "exceptions / try-catch" :label "finally runs on ok" :expected "2" :actual "(let [a (atom 0)] (try 2 (finally (reset! a 9))) )" :portability :common} - {:suite "exceptions / try-catch" :label "finally runs on throw" :expected "9" :actual "(let [a (atom 0)] (try (throw (ex-info \"x\" {})) (catch :default e nil) (finally (reset! a 9))) @a)" :portability :common} - {:suite "exceptions / try-catch" :label "catch value of body" :expected "5" :actual "(try (+ 2 3) (catch :default e 0))" :portability :common} - {:suite "exceptions / try-catch" :label "malformed catch: non-symbol binding" :expected :throws :actual "(try 1 (catch e (* e 10)))" :portability :common} - {:suite "exceptions / try-catch" :label "malformed catch: literal binding" :expected :throws :actual "(try 1 (catch e 5))" :portability :common} - {:suite "exceptions / try-catch" :label "malformed catch: too short" :expected :throws :actual "(try 1 (catch Exception))" :portability :common} - {:suite "exceptions / assert" :label "assert true -> ok" :expected ":ok" :actual "(do (assert true) :ok)" :portability :common} - {:suite "exceptions / assert" :label "assert expr -> ok" :expected ":ok" :actual "(do (assert (= 1 1)) :ok)" :portability :common} - {:suite "exceptions / assert" :label "assert false throws" :expected :throws :actual "(assert false)" :portability :common} - {:suite "exceptions / assert" :label "assert nil throws" :expected :throws :actual "(assert nil)" :portability :common} - {:suite "exceptions / ex-info" :label "ex-message" :expected "\"oops\"" :actual "(ex-message (ex-info \"oops\" {}))" :portability :common} - {:suite "exceptions / ex-info" :label "ex-data" :expected "{:k 1}" :actual "(ex-data (ex-info \"oops\" {:k 1}))" :portability :common} - {:suite "exceptions / ex-info" :label "ex-data via catch" :expected "{:code 42}" :actual "(try (throw (ex-info \"e\" {:code 42})) (catch :default e (ex-data e)))" :portability :common} - {:suite "exceptions / ex-info" :label "ex-cause" :expected "true" :actual "(let [c (ex-info \"root\" {})] (= c (ex-cause (ex-info \"outer\" {} c))))" :portability :common} - {:suite "exceptions / ex-info" :label "propagates to outer" :expected "\"inner\"" :actual "(try (try (throw (ex-info \"inner\" {})) (finally nil)) (catch :default e (ex-message e)))" :portability :common} - {:suite "exceptions / ex-info" :label "catch binds thrown value" :expected "42" :actual "(try (throw 42) (catch :default e e))" :portability :common} - {:suite "exceptions / ex-info" :label "rethrow preserves ex" :expected "\"inner\"" :actual "(try (try (throw (ex-info \"inner\" {})) (catch :default e (throw e))) (catch :default e (ex-message e)))" :portability :common} - {:suite "exceptions / ex-info" :label "ex-data on non-ex" :expected "nil" :actual "(ex-data 42)" :portability :common} - {:suite "exceptions / ex-info" :label "ex-cause on non-ex" :expected "nil" :actual "(ex-cause {:k 1})" :portability :common} - {:suite "exceptions / ex-info" :label "ex-message of string" :expected "nil" :actual "(ex-message \"hi\")" :portability :common} - {:suite "forms / case" :label "bool" :expected ":yes" :actual "(case true true :yes false :no :default)" :portability :common} - {:suite "forms / case" :label "keyword match" :expected ":b" :actual "(case :a :x :wrong :a :b :default)" :portability :common} - {:suite "forms / case" :label "number match" :expected ":two" :actual "(case 2 1 :one 2 :two :default)" :portability :common} - {:suite "forms / case" :label "string match" :expected ":hit" :actual "(case \"x\" \"y\" :miss \"x\" :hit :default)" :portability :common} - {:suite "forms / case" :label "nil match" :expected ":nada" :actual "(case nil nil :nada :default)" :portability :common} - {:suite "forms / case" :label "default" :expected ":def" :actual "(case 99 1 :one 2 :two :def)" :portability :common} - {:suite "forms / case" :label "list of consts" :expected ":vowel" :actual "(case \\a (\\a \\e \\i \\o \\u) :vowel :consonant)" :portability :common} - {:suite "forms / case" :label "no match no default" :expected :throws :actual "(case 5 1 :one)" :portability :common} - {:suite "forms / case" :label "duplicate keys" :expected :throws :actual "(case 1 1 :one 1 :dup :default)" :portability :common} - {:suite "forms / case" :label "duplicate in or-group" :expected :throws :actual "(case 2 (1 2) :a (2 3) :b :default)" :portability :common} - {:suite "forms / fn" :label "named fn nil" :expected "nil" :actual "((fn* foo-bar []))" :portability :common} - {:suite "forms / fn" :label "immediate call" :expected "1" :actual "((fn* [] 1))" :portability :common} - {:suite "forms / fn" :label "args" :expected "[:a :b]" :actual "((fn* [a b] [a b]) :a :b)" :portability :common} - {:suite "forms / fn" :label "multi-arity 0" :expected "0" :actual "(do (def add (fn* ([] 0) ([a] a) ([a b] (+ a b)))) (add))" :portability :common} - {:suite "forms / fn" :label "multi-arity 1" :expected "-500" :actual "(do (def add (fn* ([] 0) ([a] a) ([a b] (+ a b)))) (add -500))" :portability :common} - {:suite "forms / fn" :label "multi-arity 2" :expected "-450" :actual "(do (def add (fn* ([] 0) ([a] a) ([a b] (+ a b)))) (add -500 50))" :portability :common} - {:suite "forms / fn" :label "variadic rest" :expected "[3 4]" :actual "(do (def v (fn* ([a b & args] args) ([] 0))) (v 1 2 3 4))" :portability :common} - {:suite "forms / fn" :label "variadic empty" :expected "0" :actual "(do (def v (fn* ([a b & args] args) ([] 0))) (v))" :portability :common} - {:suite "forms / fn" :label "variadic collect" :expected "[{} nil :m]" :actual "((fn* [a b & args] args) 'w 't {} nil :m)" :portability :common} - {:suite "forms / fn" :label "closure capture" :expected "8" :actual "(do (def adder (fn* [n] (fn* [x] (+ x n)))) ((adder 5) 3))" :portability :common} - {:suite "forms / fn" :label "recur countdown" :expected "0" :actual "(do (def cd (fn* [n] (if (< 0 n) (recur (+ n -1)) n))) (cd 10))" :portability :common} - {:suite "forms / fn" :label "named self-recur" :expected "120" :actual "(do (def f (fn* fact [n] (if (= n 0) 1 (* n (fact (dec n)))))) (f 5))" :portability :common} - {:suite "forms / fn" :label "no param vector" :expected :throws :actual "(fn* foo)" :portability :common} - {:suite "forms / fn" :label "non-symbol param" :expected :throws :actual "(fn* [1] 1)" :portability :common} - {:suite "forms / let" :label "literal" :expected "1" :actual "(let* [a 1] a)" :portability :common} - {:suite "forms / let" :label "multiple" :expected "[1 2]" :actual "(let* [a 1 b 2] [a b])" :portability :common} - {:suite "forms / let" :label "previous ref" :expected ":bee" :actual "(let* [a 1 b (if (= 1 a) :bee :uh-oh)] b)" :portability :common} - {:suite "forms / let" :label "nested let" :expected "3" :actual "(let* [a 5 b (let* [c -2] (+ a c))] b)" :portability :common} - {:suite "forms / let" :label "fn value bound" :expected "\":foo\"" :actual "(let* [kw->str (fn* [kw] (str kw))] (kw->str :foo))" :portability :common} - {:suite "forms / let" :label "shadowing" :expected "2" :actual "(let* [a 1 a 2] a)" :portability :common} - {:suite "forms / letfn" :label "mutual top" :expected "[1 2]" :actual "(letfn [(a [] 1) (b [] 2)] [(a) (b)])" :portability :common} - {:suite "forms / letfn" :label "mutual recursion" :expected ":done" :actual "(letfn [(ev? [n] (if (= 0 n) :done (od? (dec n)))) (od? [n] (ev? n))] (ev? 4))" :portability :common} - {:suite "forms / letfn" :label "nested letfn" :expected "3" :actual "(letfn [(a [] 5) (b [] (letfn [(c [] -2)] (+ (a) (c))))] (b))" :portability :common} - {:suite "forms / loop" :label "sum" :expected "55" :actual "(loop* [sum 0 cnt 10] (if (= cnt 0) sum (recur (+ cnt sum) (dec cnt))))" :portability :common} - {:suite "forms / loop" :label "multi binding" :expected "[4 2]" :actual "(loop* [a 1 b 2 n 0] (if (< n 3) (recur (inc a) b (inc n)) [a b]))" :portability :common} - {:suite "forms / loop" :label "init sees prior" :expected "[1 2 3]" :actual "(loop* [a 1 b (+ a 1) c (+ b 1)] [a b c])" :portability :common} - {:suite "forms / try" :label "immediate throw caught" :expected ":caught" :actual "(try (throw :boom) (catch :default e :caught))" :portability :common} - {:suite "forms / try" :label "first throw wins" :expected "\"a\"" :actual "(try (throw (ex-info \"a\" {})) (throw (ex-info \"b\" {})) (catch :default e (ex-message e)))" :portability :common} - {:suite "forms / try" :label "catch ex-data" :expected "7" :actual "(try (throw (ex-info \"e\" {:v 7})) (catch :default e (:v (ex-data e))))" :portability :common} - {:suite "forms / try" :label "finally runs" :expected "9" :actual "(let [a (atom 0)] (try 1 (finally (reset! a 9))) @a)" :portability :common} - {:suite "forms / try" :label "body value w/ finally" :expected "1" :actual "(try 1 (finally 2))" :portability :common} - {:suite "forms / try" :label "catch value w/ finally" :expected ":h" :actual "(try (throw (ex-info \"x\" {})) (catch :default e :h) (finally :ignored))" :portability :common} - {:suite "forms / try" :label "no throw skips catch" :expected "5" :actual "(try 5 (catch :default e :nope))" :portability :common} - {:suite "forms / if-do-def-call" :label "if truthy vec" :expected ":fine" :actual "(if [:ok] :fine :no)" :portability :common} - {:suite "forms / if-do-def-call" :label "if truthy str" :expected ":fine" :actual "(if \"good?\" :fine :no)" :portability :common} - {:suite "forms / if-do-def-call" :label "if nil = false" :expected ":else" :actual "(if nil :then :else)" :portability :common} - {:suite "forms / if-do-def-call" :label "if no else" :expected "nil" :actual "(if false 1)" :portability :common} - {:suite "forms / if-do-def-call" :label "do nested" :expected "1" :actual "(do (do (do (do 1))))" :portability :common} - {:suite "forms / if-do-def-call" :label "do returns last" :expected "3" :actual "(do 1 2 3)" :portability :common} - {:suite "forms / if-do-def-call" :label "def + deref var" :expected "true" :actual "(var? (def one 1))" :portability :common} - {:suite "forms / if-do-def-call" :label "def no init interns var" :expected "true" :actual "(var? (def no-init))" :portability :common} - {:suite "forms / if-do-def-call" :label "def no init keeps existing root" :expected "7" :actual "(do (def kept 7) (def kept) kept)" :portability :common} - {:suite "forms / if-do-def-call" :label "declare interns var" :expected "true" :actual "(do (declare fwd-declared) (var? (var fwd-declared)))" :portability :common} - {:suite "forms / if-do-def-call" :label "def redefine" :expected "100" :actual "(do (def one 1) (def one 100) one)" :portability :common} - {:suite "forms / if-do-def-call" :label "def in fn mutates" :expected "[:default :meow]" :actual "(do (def a :default) (def set-a (fn* [v] (def a v))) (let* [before a] (set-a :meow) [before a]))" :portability :common} - {:suite "forms / if-do-def-call" :label "call literal fn" :expected "1" :actual "((fn* [] 1))" :portability :common} - {:suite "forms / if-do-def-call" :label "call nested" :expected "6" :actual "(+ ((fn* [] 1)) ((fn* [] 2)) ((fn* [] 3)))" :portability :common} - {:suite "forms / if-do-def-call" :label "call nil" :expected :throws :actual "(nil)" :portability :common} - {:suite "forms / if arity (X1)" :label "bare if throws" :expected :throws :actual "(if)" :portability :common} - {:suite "forms / if arity (X1)" :label "one-arg if throws" :expected :throws :actual "(if true)" :portability :common} - {:suite "forms / if arity (X1)" :label "four-arg if throws" :expected :throws :actual "(if true 1 2 3)" :portability :common} - {:suite "forms / if arity (X1)" :label "two-arg if ok" :expected "nil" :actual "(if false 1)" :portability :common} - {:suite "forms / if arity (X1)" :label "three-arg if ok" :expected "2" :actual "(if false 1 2)" :portability :common} - {:suite "functions / definition" :label "fn literal" :expected "3" :actual "((fn [a b] (+ a b)) 1 2)" :portability :common} - {:suite "functions / definition" :label "fn shorthand" :expected "3" :actual "(#(+ %1 %2) 1 2)" :portability :common} - {:suite "functions / definition" :label "fn shorthand %" :expected "2" :actual "(#(inc %) 1)" :portability :common} - {:suite "functions / definition" :label "defn" :expected "5" :actual "(do (defn f [x] (+ x 2)) (f 3))" :portability :common} - {:suite "functions / definition" :label "multi-arity" :expected "[1 5]" :actual "(do (defn f ([x] x) ([x y] (+ x y))) [(f 1) (f 2 3)])" :portability :common} - {:suite "functions / definition" :label "variadic" :expected "[1 2 3]" :actual "(do (defn f [& xs] xs) (f 1 2 3))" :portability :common} - {:suite "functions / definition" :label "variadic with fixed" :expected "[1 [2 3]]" :actual "(do (defn f [a & xs] [a xs]) (f 1 2 3))" :portability :common} - {:suite "functions / definition" :label "named fn-literal self-recursion (direct self-call)" :expected "3628800" :actual "((fn fact [n] (if (< n 2) 1 (* n (fact (dec n))))) 10)" :portability :common} - {:suite "functions / definition" :label "defn self-recursion" :expected "832040" :actual "(do (defn fib [n] (if (< n 2) n (+ (fib (- n 1)) (fib (- n 2))))) (fib 30))" :portability :common} - {:suite "functions / definition" :label "multi-arity self-recursion" :expected "15" :actual "(do (defn sum ([xs] (sum xs 0)) ([xs a] (if (seq xs) (sum (rest xs) (+ a (first xs))) a))) (sum [1 2 3 4 5]))" :portability :common} - {:suite "functions / definition" :label "variadic self-recursion" :expected "10" :actual "(do (defn g [& xs] (if (next xs) (apply g (cons (+ (first xs) (second xs)) (nnext xs))) (first xs))) (g 1 2 3 4))" :portability :common} - {:suite "functions / definition" :label "closure captures" :expected "8" :actual "(do (defn adder [n] (fn [x] (+ x n))) ((adder 5) 3))" :portability :common} - {:suite "functions / definition" :label "recursion" :expected "120" :actual "(do (defn fact [n] (if (< n 2) 1 (* n (fact (dec n))))) (fact 5))" :portability :common} - {:suite "functions / definition" :label "named fn self-ref" :expected "120" :actual "((fn fact [n] (if (< n 2) 1 (* n (fact (dec n))))) 5)" :portability :common} - {:suite "functions / definition" :label "param named `in`" :expected "1" :actual "((fn [in] (first in)) [1 2 3])" :portability :common} - {:suite "functions / definition" :label "param `in` via core fn" :expected "3" :actual "((fn [in] (count in)) [1 2 3])" :portability :common} - {:suite "functions / definition" :label "local `in` in let body" :expected "2" :actual "(let [in [2 3]] (first in))" :portability :common} - {:suite "functions / application" :label "apply" :expected "6" :actual "(apply + [1 2 3])" :portability :common} - {:suite "functions / application" :label "apply with leading" :expected "10" :actual "(apply + 1 2 [3 4])" :portability :common} - {:suite "functions / application" :label "apply keyword" :expected "1" :actual "(apply :a [{:a 1}])" :portability :common} - {:suite "functions / application" :label "partial" :expected "7" :actual "((partial + 5) 2)" :portability :common} - {:suite "functions / application" :label "partial multi" :expected "10" :actual "((partial + 1 2) 3 4)" :portability :common} - {:suite "functions / application" :label "comp" :expected "4" :actual "((comp inc inc) 2)" :portability :common} - {:suite "functions / application" :label "comp order" :expected "5" :actual "((comp inc (fn [x] (* x 2))) 2)" :portability :common} - {:suite "functions / application" :label "comp identity" :expected "3" :actual "((comp) 3)" :portability :common} - {:suite "functions / application" :label "complement" :expected "true" :actual "((complement even?) 3)" :portability :common} - {:suite "functions / application" :label "constantly" :expected "5" :actual "((constantly 5) 1 2 3)" :portability :common} - {:suite "functions / application" :label "identity" :expected "7" :actual "(identity 7)" :portability :common} - {:suite "functions / combinators" :label "juxt" :expected "[1 3]" :actual "((juxt first last) [1 2 3])" :portability :common} - {:suite "functions / combinators" :label "fnil" :expected "1" :actual "((fnil inc 0) nil)" :portability :common} - {:suite "functions / combinators" :label "fnil passes value" :expected "6" :actual "((fnil inc 0) 5)" :portability :common} - {:suite "functions / combinators" :label "every-pred true" :expected "true" :actual "((every-pred pos? even?) 4)" :portability :common} - {:suite "functions / combinators" :label "every-pred false" :expected "false" :actual "((every-pred pos? even?) 3)" :portability :common} - {:suite "functions / combinators" :label "some-fn" :expected "true" :actual "((some-fn even? neg?) 3 4)" :portability :common} - {:suite "functions / combinators" :label "memoize" :expected "2" :actual "(do (def c (atom 0)) (def f (memoize (fn [x] (swap! c inc) x))) (f 1) (f 1) (f 2) @c)" :portability :common} - {:suite "functions / combinators" :label "trampoline" :expected "10" :actual "(trampoline (fn f [n acc] (if (zero? n) acc (fn [] (f (dec n) (+ acc 2))))) 5 0)" :portability :common} - {:suite "clojure.core / leaf batch (complement fnil munge etc.)" :label "complement true" :expected "true" :actual "((complement pos?) -1)" :portability :common} - {:suite "clojure.core / leaf batch (complement fnil munge etc.)" :label "complement false" :expected "false" :actual "((complement pos?) 1)" :portability :common} - {:suite "clojure.core / leaf batch (complement fnil munge etc.)" :label "complement multi" :expected "true" :actual "((complement <) 3 2)" :portability :common} - {:suite "clojure.core / leaf batch (complement fnil munge etc.)" :label "fnil patches nil" :expected "1" :actual "((fnil inc 0) nil)" :portability :common} - {:suite "clojure.core / leaf batch (complement fnil munge etc.)" :label "fnil passes non-nil" :expected "6" :actual "((fnil inc 0) 5)" :portability :common} - {:suite "clojure.core / leaf batch (complement fnil munge etc.)" :label "fnil two defaults" :expected "8" :actual "((fnil + 1 2) nil nil 5)" :portability :common} - {:suite "clojure.core / leaf batch (complement fnil munge etc.)" :label "fnil only first 3" :expected "[:a :b :c nil]" :actual "((fnil vector :a :b :c) nil nil nil nil)" :portability :common} - {:suite "clojure.core / leaf batch (complement fnil munge etc.)" :label "fnil in update" :expected "{:k 1}" :actual "(update {} :k (fnil inc 0))" :portability :common} - {:suite "clojure.core / leaf batch (complement fnil munge etc.)" :label "clojure-version" :expected "true" :actual "(string? (clojure-version))" :portability :common} - {:suite "clojure.core / leaf batch (complement fnil munge etc.)" :label "bigdec" :expected "3M" :actual "(bigdec 3)" :portability :common} - {:suite "clojure.core / leaf batch (complement fnil munge etc.)" :label "numerator throws" :expected :throws :actual "(numerator 1)" :portability :common} - {:suite "clojure.core / leaf batch (complement fnil munge etc.)" :label "denominator throws" :expected :throws :actual "(denominator 1)" :portability :common} - {:suite "clojure.core / leaf batch (complement fnil munge etc.)" :label "supers empty set" :expected "#{}" :actual "(supers 1)" :portability :common} - {:suite "clojure.core / leaf batch (complement fnil munge etc.)" :label "munge dashes" :expected "\"a_b\"" :actual "(munge \"a-b\")" :portability :common} - {:suite "clojure.core / leaf batch (complement fnil munge etc.)" :label "munge symbol" :expected "(quote x_y)" :actual "(munge (quote x-y))" :portability :common} - {:suite "clojure.core / leaf batch (complement fnil munge etc.)" :label "test no-test" :expected ":no-test" :actual "(test (quote foo))" :portability :common} - {:suite "clojure.core / leaf batch 2" :label "key" :expected "1" :actual "(key (first {1 :a}))" :portability :common} - {:suite "clojure.core / leaf batch 2" :label "val" :expected ":a" :actual "(val (first {1 :a}))" :portability :common} - {:suite "clojure.core / leaf batch 2" :label "key non-entry throws" :expected :throws :actual "(key 5)" :portability :common} - {:suite "clojure.core / leaf batch 2" :label "find hit" :expected "[:a 1]" :actual "(find {:a 1} :a)" :portability :common} - {:suite "clojure.core / leaf batch 2" :label "find miss" :expected "nil" :actual "(find {:a 1} :b)" :portability :common} - {:suite "clojure.core / leaf batch 2" :label "find nil value" :expected "[:a nil]" :actual "(find {:a nil} :a)" :portability :common} - {:suite "clojure.core / leaf batch 2" :label "find on vector" :expected "[0 :x]" :actual "(find [:x :y] 0)" :portability :common} - {:suite "clojure.core / leaf batch 2" :label "select-keys" :expected "{:a 1}" :actual "(select-keys {:a 1 :b 2} [:a])" :portability :common} - {:suite "clojure.core / leaf batch 2" :label "select-keys nil val" :expected "{:a nil}" :actual "(select-keys {:a nil :b 2} [:a])" :portability :common} - {:suite "clojure.core / leaf batch 2" :label "select-keys missing" :expected "{}" :actual "(select-keys {:a 1} [:z])" :portability :common} - {:suite "clojure.core / leaf batch 2" :label "zipmap" :expected "{:a 1, :b 2}" :actual "(zipmap [:a :b] [1 2])" :portability :common} - {:suite "clojure.core / leaf batch 2" :label "zipmap uneven" :expected "{:a 1}" :actual "(zipmap [:a :b] [1])" :portability :common} - {:suite "clojure.core / leaf batch 2" :label "zipmap nil val" :expected "{:a nil}" :actual "(zipmap [:a] [nil])" :portability :common} - {:suite "clojure.core / leaf batch 2" :label "merge" :expected "{:a 1, :b 2}" :actual "(merge {:a 1} {:b 2})" :portability :common} - {:suite "clojure.core / leaf batch 2" :label "merge later wins" :expected "{:a 2}" :actual "(merge {:a 1} {:a 2})" :portability :common} - {:suite "clojure.core / leaf batch 2" :label "merge nil arg" :expected "{:a 1}" :actual "(merge {:a 1} nil)" :portability :common} - {:suite "clojure.core / leaf batch 2" :label "merge nil first" :expected "{:a 1}" :actual "(merge nil {:a 1})" :portability :common} - {:suite "clojure.core / leaf batch 2" :label "merge all nil" :expected "nil" :actual "(merge nil nil)" :portability :common} - {:suite "clojure.core / leaf batch 2" :label "merge empty" :expected "nil" :actual "(merge)" :portability :common} - {:suite "clojure.core / leaf batch 2" :label "merge entry pair" :expected "{:a 1, :b 2}" :actual "(merge {:a 1} [:b 2])" :portability :common} - {:suite "clojure.core / leaf batch 2" :label "merge-with" :expected "{:a 3}" :actual "(merge-with + {:a 1} {:a 2})" :portability :common} - {:suite "clojure.core / leaf batch 2" :label "merge-with disjoint" :expected "{:a 1, :b 2}" :actual "(merge-with + {:a 1} {:b 2})" :portability :common} - {:suite "clojure.core / leaf batch 2" :label "merge-with nil-val present" :expected "{:a 1}" :actual "(merge-with (fn [a b] (or a b)) {:a nil} {:a 1})" :portability :common} - {:suite "clojure.core / leaf batch 2" :label "get-in" :expected "1" :actual "(get-in {:a {:b 1}} [:a :b])" :portability :common} - {:suite "clojure.core / leaf batch 2" :label "get-in missing" :expected ":nf" :actual "(get-in {:a 1} [:z :y] :nf)" :portability :common} - {:suite "clojure.core / leaf batch 2" :label "get-in nil value present" :expected "nil" :actual "(get-in {:a {:b nil}} [:a :b] :nf)" :portability :common} - {:suite "clojure.core / leaf batch 2" :label "get-in empty path" :expected "{:a 1}" :actual "(get-in {:a 1} [])" :portability :common} - {:suite "clojure.core / leaf batch 2" :label "memoize" :expected "2" :actual "(do (def c (atom 0)) (def f (memoize (fn [x] (swap! c inc) x))) (f 1) (f 1) (f 2) (deref c))" :portability :common} - {:suite "clojure.core / leaf batch 2" :label "memoize caches nil" :expected "1" :actual "(do (def c (atom 0)) (def f (memoize (fn [x] (swap! c inc) nil))) (f 1) (f 1) (deref c))" :portability :common} - {:suite "clojure.core / leaf batch 2" :label "partial" :expected "6" :actual "((partial + 1 2) 3)" :portability :common} - {:suite "clojure.core / leaf batch 2" :label "partial no extra" :expected "3" :actual "((partial + 1 2))" :portability :common} - {:suite "clojure.core / leaf batch 2" :label "partial many fixed" :expected "15" :actual "((partial + 1 2 3 4) 5)" :portability :common} - {:suite "clojure.core / leaf batch 2" :label "trampoline" :expected "10" :actual "(trampoline (fn f [n acc] (if (zero? n) acc (fn [] (f (dec n) (+ acc 2))))) 5 0)" :portability :common} - {:suite "clojure.core / leaf batch 2" :label "some? true" :expected "true" :actual "(some? 0)" :portability :common} - {:suite "clojure.core / leaf batch 2" :label "some? false" :expected "false" :actual "(some? nil)" :portability :common} - {:suite "clojure.core / leaf batch 2" :label "true?/false?" :expected "[true false false]" :actual "[(true? true) (true? 1) (false? nil)]" :portability :common} - {:suite "clojure.core / leaf batch 2" :label "max" :expected "3" :actual "(max 1 3 2)" :portability :common} - {:suite "clojure.core / leaf batch 2" :label "min" :expected "1" :actual "(min 3 1 2)" :portability :common} - {:suite "clojure.core / leaf batch 2" :label "max single" :expected "5" :actual "(max 5)" :portability :common} - {:suite "clojure.core / leaf batch 2" :label "max non-number throws" :expected :throws :actual "(max 1 :a)" :portability :common} - {:suite "clojure.core / leaf batch 2" :label "reverse" :expected "[3 2 1]" :actual "(reverse [1 2 3])" :portability :common} - {:suite "clojure.core / leaf batch 2" :label "reverse empty" :expected "[]" :actual "(reverse nil)" :portability :common} - {:suite "clojure.core / leaf batch 2" :label "conj nil onto map" :expected "{:a 1}" :actual "(conj {:a 1} nil)" :portability :common} - {:suite "clojure.core / leaf batch 3" :label "empty vector" :expected "[]" :actual "(empty [1 2])" :portability :common} - {:suite "clojure.core / leaf batch 3" :label "empty list" :expected "[]" :actual "(empty (list 1))" :portability :common} - {:suite "clojure.core / leaf batch 3" :label "empty map" :expected "{}" :actual "(empty {:a 1})" :portability :common} - {:suite "clojure.core / leaf batch 3" :label "empty set" :expected "#{}" :actual "(empty #{1})" :portability :common} - {:suite "clojure.core / leaf batch 3" :label "empty nil" :expected "nil" :actual "(empty nil)" :portability :common} - {:suite "clojure.core / leaf batch 3" :label "empty string" :expected "nil" :actual "(empty \"abc\")" :portability :common} - {:suite "clojure.core / leaf batch 3" :label "empty lazy is ()" :expected "[]" :actual "(empty (map inc [1 2]))" :portability :common} - {:suite "clojure.core / leaf batch 3" :label "empty sorted keeps cmp" :expected "[3 1]" :actual "(vec (seq (into (empty (sorted-set-by > 1 2)) [1 3])))" :portability :common} - {:suite "clojure.core / leaf batch 3" :label "assoc-in" :expected "{:a {:b 1}}" :actual "(assoc-in {} [:a :b] 1)" :portability :common} - {:suite "clojure.core / leaf batch 3" :label "assoc-in deep" :expected "{:a {:b {:c 2}}}" :actual "(assoc-in {:a {:b {:c 1}}} [:a :b :c] 2)" :portability :common} - {:suite "clojure.core / leaf batch 3" :label "assoc-in keeps siblings" :expected "{:a {:b 1, :c 2}}" :actual "(assoc-in {:a {:b 1}} [:a :c] 2)" :portability :common} - {:suite "clojure.core / leaf batch 3" :label "assoc-in vector idx" :expected "[1 9]" :actual "(assoc-in [1 2] [1] 9)" :portability :common} - {:suite "clojure.core / leaf batch 3" :label "assoc-in nested vec" :expected "[{:a 9}]" :actual "(assoc-in [{:a 1}] [0 :a] 9)" :portability :common} - {:suite "clojure.core / leaf batch 3" :label "update-in" :expected "{:a {:b 2}}" :actual "(update-in {:a {:b 1}} [:a :b] inc)" :portability :common} - {:suite "clojure.core / leaf batch 3" :label "update-in extra args" :expected "{:a {:b 111}}" :actual "(update-in {:a {:b 1}} [:a :b] + 10 100)" :portability :common} - {:suite "clojure.core / leaf batch 3" :label "update-in fnil" :expected "{:a {:b 1}}" :actual "(update-in {} [:a :b] (fnil inc 0))" :portability :common} - {:suite "clojure.core / leaf batch 3" :label "update-in single key" :expected "{:a 2}" :actual "(update-in {:a 1} [:a] inc)" :portability :common} - {:suite "clojure.core / leaf batch 3" :label "interpose" :expected "[1 :s 2 :s 3]" :actual "(interpose :s [1 2 3])" :portability :common} - {:suite "clojure.core / leaf batch 3" :label "interpose empty" :expected "[]" :actual "(interpose :s [])" :portability :common} - {:suite "clojure.core / leaf batch 3" :label "interpose one" :expected "[1]" :actual "(interpose :s [1])" :portability :common} - {:suite "clojure.core / leaf batch 3" :label "interpose is lazy" :expected "[0 :s 1]" :actual "(take 3 (interpose :s (range)))" :portability :common} - {:suite "clojure.core / leaf batch 3" :label "interpose xform" :expected "[\"a\" \",\" \"b\"]" :actual "(vec (sequence (interpose \",\") [\"a\" \"b\"]))" :portability :common} - {:suite "clojure.core / leaf batch 3" :label "take-nth" :expected "[1 3 5]" :actual "(take-nth 2 [1 2 3 4 5 6])" :portability :common} - {:suite "clojure.core / leaf batch 3" :label "take-nth lazy" :expected "[0 3 6]" :actual "(take 3 (take-nth 3 (range)))" :portability :common} - {:suite "clojure.core / leaf batch 3" :label "take-nth xform" :expected "[1 3 5]" :actual "(vec (sequence (take-nth 2) [1 2 3 4 5 6]))" :portability :common} - {:suite "clojure.core / leaf batch 3" :label "take-nth into" :expected "[1 4]" :actual "(into [] (take-nth 3) [1 2 3 4 5])" :portability :common} - {:suite "clojure.core / leaf batch 4" :label "sort-by keyfn" :expected "[[1 :b] [2 :a]]" :actual "(sort-by first [[2 :a] [1 :b]])" :portability :common} - {:suite "clojure.core / leaf batch 4" :label "sort-by string keys" :expected "[\"a\" \"bb\" \"ccc\"]" :actual "(sort-by count [\"ccc\" \"a\" \"bb\"])" :portability :common} - {:suite "clojure.core / leaf batch 4" :label "sort-by comparator" :expected "[3 2 1]" :actual "(sort-by identity > [1 3 2])" :portability :common} - {:suite "clojure.core / leaf batch 4" :label "sort-by 3way cmp" :expected "[3 2 1]" :actual "(sort-by identity (fn [a b] (- b a)) [1 3 2])" :portability :common} - {:suite "clojure.core / leaf batch 4" :label "sort-by mixed nil" :expected "[nil 1 2]" :actual "(sort-by identity [2 nil 1])" :portability :common} - {:suite "clojure.core / leaf batch 4" :label "sort-by empty" :expected "[]" :actual "(sort-by first [])" :portability :common} - {:suite "clojure.core / leaf batch 4" :label "sort-by nil coll" :expected "[]" :actual "(sort-by first nil)" :portability :common} - {:suite "clojure.core / leaf batch 4" :label "rand-int range" :expected "true" :actual "(every? (fn [_] (let [r (rand-int 5)] (and (int? r) (<= 0 r 4)))) (range 50))" :portability :common} - {:suite "clojure.core / leaf batch 4" :label "rand-int zero" :expected "0" :actual "(rand-int 1)" :portability :common} - {:suite "clojure.core / leaf batch 4" :label "shuffle is permutation" :expected "true" :actual "(= (sort (shuffle [5 3 1 4 2])) [1 2 3 4 5])" :portability :common} - {:suite "clojure.core / leaf batch 4" :label "shuffle returns vector" :expected "true" :actual "(vector? (shuffle [1 2 3]))" :portability :common} - {:suite "clojure.core / leaf batch 4" :label "shuffle empty" :expected "[]" :actual "(shuffle [])" :portability :common} - {:suite "clojure.core / leaf batch 4" :label "shuffle non-coll throws" :expected :throws :actual "(shuffle 5)" :portability :common} - {:suite "clojure.core / leaf batch 4" :label "random-uuid is uuid" :expected "true" :actual "(uuid? (random-uuid))" :portability :common} - {:suite "clojure.core / leaf batch 4" :label "random-uuid v4 shape" :expected "true" :actual "(boolean (re-matches #\"[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\" (str (random-uuid))))" :portability :common} - {:suite "clojure.core / leaf batch 4" :label "random-uuid distinct" :expected "true" :actual "(not= (random-uuid) (random-uuid))" :portability :common} - {:suite "clojure.core / leaf batch 4" :label "char-escape newline" :expected "\"\\\\n\"" :actual "(char-escape-string \\newline)" :portability :common} - {:suite "clojure.core / leaf batch 4" :label "char-escape quote" :expected "true" :actual "(= 2 (count (char-escape-string \\\")))" :portability :common} - {:suite "clojure.core / leaf batch 4" :label "char-escape none" :expected "nil" :actual "(char-escape-string \\a)" :portability :common} - {:suite "clojure.core / leaf batch 4" :label "char-name space" :expected "\"space\"" :actual "(char-name-string \\space)" :portability :common} - {:suite "clojure.core / leaf batch 4" :label "char-name newline" :expected "\"newline\"" :actual "(char-name-string \\newline)" :portability :common} - {:suite "clojure.core / leaf batch 4" :label "char-name none" :expected "nil" :actual "(char-name-string \\a)" :portability :common} - {:suite "functions / recur into variadic arity" :label "counts rest via recur" :expected "3" :actual "((fn cnt [acc & xs] (if (seq xs) (recur (inc acc) (rest xs)) acc)) 0 :a :b :c)" :portability :common} - {:suite "functions / recur into variadic arity" :label "zero-fixed variadic" :expected "4" :actual "((fn f [& xs] (if (< (count xs) 4) (recur (cons :x xs)) (count xs))) :a)" :portability :common} - {:suite "functions / recur into variadic arity" :label "rest empties to nil" :expected "[:done]" :actual "((fn f [& xs] (if xs (recur (next xs)) (list :done))) 1 2)" :portability :common} - {:suite "functions / recur into variadic arity" :label "multi-arity variadic recur" :expected "6" :actual "((fn ma ([a] a) ([a & xs] (if (seq xs) (recur (+ a (first xs)) (rest xs)) a))) 1 2 3)" :portability :common} - {:suite "functions / recur into variadic arity" :label "recur passes nil rest" :expected ":empty" :actual "((fn f [acc & xs] (if (seq xs) (recur acc (rest xs)) :empty)) 0 1)" :portability :common} - {:suite "functions / recur into variadic arity" :label "fixed-arity recur untouched" :expected "10" :actual "((fn f [n acc] (if (pos? n) (recur (dec n) (+ acc 2)) acc)) 5 0)" :portability :common} - {:suite "functions / empty rest arg is nil" :label "no args" :expected ":nil" :actual "((fn [& r] (if r :truthy :nil)))" :portability :common} - {:suite "functions / empty rest arg is nil" :label "after fixed" :expected ":nil" :actual "((fn [a & r] (if r :truthy :nil)) 1)" :portability :common} - {:suite "functions / empty rest arg is nil" :label "via apply" :expected ":nil" :actual "(apply (fn [& r] (if r :truthy :nil)) [])" :portability :common} - {:suite "functions / empty rest arg is nil" :label "defn no args" :expected ":nil" :actual "(do (defn er-f [& r] (if r :truthy :nil)) (er-f))" :portability :common} - {:suite "functions / empty rest arg is nil" :label "non-empty unchanged" :expected "[1 2]" :actual "((fn [& r] r) 1 2)" :portability :common} - {:suite "functions / empty rest arg is nil" :label "one extra" :expected "[2]" :actual "((fn [a & r] r) 1 2)" :portability :common} - {:suite "functions / empty rest arg is nil" :label "rest destructure with no args" :expected ":nil" :actual "((fn [& [a]] (if a :truthy :nil)))" :portability :common} - {:suite "functions / arity enforcement" :label "fixed extra args" :expected :throws :actual "((fn [x] x) 1 2)" :portability :common} - {:suite "functions / arity enforcement" :label "fixed missing args" :expected :throws :actual "((fn [x y] x) 1)" :portability :common} - {:suite "functions / arity enforcement" :label "fixed zero of one" :expected :throws :actual "((fn [x] x))" :portability :common} - {:suite "functions / arity enforcement" :label "named defn extra" :expected :throws :actual "(do (defn af1 [x] x) (af1 1 2))" :portability :common} - {:suite "functions / arity enforcement" :label "overlay fn extra" :expected :throws :actual "(identity 1 2)" :portability :common} - {:suite "functions / arity enforcement" :label "through apply" :expected :throws :actual "(apply (fn [x] x) [1 2])" :portability :common} - {:suite "functions / arity enforcement" :label "through update" :expected :throws :actual "(update {:k 1} :k identity 1 2 3 4)" :portability :common} - {:suite "functions / arity enforcement" :label "variadic below min" :expected :throws :actual "((fn [x & r] x))" :portability :common} - {:suite "functions / arity enforcement" :label "variadic at min" :expected "nil" :actual "((fn [x & r] r) 1)" :portability :common} - {:suite "functions / arity enforcement" :label "variadic above min" :expected "[2 3]" :actual "((fn [x & r] r) 1 2 3)" :portability :common} - {:suite "functions / arity enforcement" :label "multi-arity no match" :expected :throws :actual "((fn ([x] x) ([x y] y)) 1 2 3)" :portability :common} - {:suite "functions / arity enforcement" :label "multi-arity variadic below min" :expected :throws :actual "((fn ([x] x) ([x y & r] r)))" :portability :common} - {:suite "functions / arity enforcement" :label "destructured param counts as one" :expected "3" :actual "((fn [[a b] c] c) [1 2] 3)" :portability :common} - {:suite "functions / arity enforcement" :label "destructured extra throws" :expected :throws :actual "((fn [[a b]] a) [1 2] [3 4])" :portability :common} - {:suite "functions / arity enforcement" :label "hof exact arity ok" :expected "[2 4]" :actual "(mapv (fn [x] (* 2 x)) [1 2])" :portability :common} - {:suite "functions / arity enforcement" :label "zero-arity fn ok" :expected "7" :actual "((fn [] 7))" :portability :common} - {:suite "clojure.core / futures — deref" :label "future + deref" :expected "3" :actual "(deref (future (+ 1 2)))" :portability :common} - {:suite "clojure.core / futures — deref" :label "@ reader macro derefs" :expected "42" :actual "@(future (* 6 7))" :portability :common} - {:suite "clojure.core / futures — deref" :label "future returns collection" :expected "[2 3 4]" :actual "(deref (future (mapv inc [1 2 3])))" :portability :common} - {:suite "clojure.core / futures — deref" :label "future returns a map" :expected "{:a 1}" :actual "(deref (future {:a 1}))" :portability :common} - {:suite "clojure.core / futures — deref" :label "deref is cached/idempotent" :expected "[2 2]" :actual "(let [f (future (+ 1 1))] [(deref f) (deref f)])" :portability :common} - {:suite "clojure.core / futures — deref" :label "timed deref of ready future" :expected "42" :actual "(let [f (future 42)] (deref f) (deref f 1000 :nope))" :portability :common} - {:suite "clojure.core / futures — deref" :label "body error re-raised on deref" :expected :throws :actual "(deref (future (throw \"boom\")))" :portability :common} - {:suite "clojure.core / futures — deref" :label "timed deref times out" :expected ":timed-out" :actual "(deref (future (do (Thread/sleep 300) :late)) 10 :timed-out)" :portability :jvm} - {:suite "clojure.core / futures — deref" :label "Thread/sleep in body" :expected ":slept" :actual "(deref (future (do (Thread/sleep 5) :slept)))" :portability :jvm} - {:suite "clojure.core / futures — deref" :label "timed-out future still completes" :expected ":late" :actual "(let [f (future (do (Thread/sleep 30) :late))] (deref f 5 :early) (deref f))" :portability :jvm} - {:suite "clojure.core / futures — predicates" :label "future? true" :expected "true" :actual "(future? (future 1))" :portability :common} - {:suite "clojure.core / futures — predicates" :label "future? false" :expected "false" :actual "(future? 42)" :portability :common} - {:suite "clojure.core / futures — predicates" :label "future-done? after deref" :expected "true" :actual "(let [f (future 1)] (deref f) (future-done? f))" :portability :common} - {:suite "clojure.core / futures — predicates" :label "realized? after deref" :expected "true" :actual "(let [f (future 1)] (deref f) (realized? f))" :portability :common} - {:suite "clojure.core / futures — predicates" :label "cancel an in-flight future returns true" :expected "true" :actual "(let [f (future (do (Thread/sleep 100) 1))] (future-cancel f))" :portability :jvm} - {:suite "clojure.core / futures — predicates" :label "future-cancelled? after cancel" :expected "true" :actual "(let [f (future (do (Thread/sleep 100) 1))] (future-cancel f) (future-cancelled? f))" :portability :jvm} - {:suite "clojure.core / futures — predicates" :label "future-done? after cancel" :expected "true" :actual "(let [f (future 1)] (future-cancel f) (future-done? f))" :portability :common} - {:suite "clojure.core / futures — predicates" :label "cancel an already-completed future returns false" :expected "false" :actual "(let [f (future 1)] (deref f) (future-cancel f))" :portability :common} - {:suite "clojure.core / futures — predicates" :label "future-cancelled? fresh is false" :expected "false" :actual "(future-cancelled? (future 1))" :portability :common} - {:suite "clojure.core / futures — snapshot (copy) semantics" :label "captured atom is snapshotted, not shared" :expected "1" :actual "(let [a (atom 0)] (deref (future (swap! a inc))) @a)" :portability :common} - {:suite "clojure.core / futures — snapshot (copy) semantics" :label "future sees its own mutation" :expected "1" :actual "(let [a (atom 0)] (deref (future (swap! a inc))))" :portability :common} - {:suite "clojure.core / pmap family" :label "pmap values in order" :expected "[2 3 4]" :actual "(vec (pmap inc [1 2 3]))" :portability :common} - {:suite "clojure.core / pmap family" :label "pmap multi-coll" :expected "[5 7 9]" :actual "(vec (pmap + [1 2 3] [4 5 6]))" :portability :common} - {:suite "clojure.core / pmap family" :label "pmap empty" :expected "[]" :actual "(pmap inc [])" :portability :common} - {:suite "clojure.core / pmap family" :label "pmap is parallel" :expected "true" :actual "(do (deref (future :warmup)) (let [t0 (System/currentTimeMillis)] (dorun (pmap (fn [_] (Thread/sleep 200)) [1 2 3 4])) (< (- (System/currentTimeMillis) t0) 700)))" :portability :jvm} - {:suite "clojure.core / pmap family" :label "pcalls" :expected "[1 2]" :actual "(vec (pcalls (fn [] 1) (fn [] 2)))" :portability :common} - {:suite "clojure.core / pmap family" :label "pvalues" :expected "[3 7]" :actual "(vec (pvalues (+ 1 2) (+ 3 4)))" :portability :common} - {:suite "clojure.core / pmap family" :label "snapshot semantics" :expected "2" :actual "(let [a (atom 0)] (dorun (pmap (fn [_] (swap! a inc)) [1 2])) (deref a))" :portability :common} - {:suite "hierarchy / pure 3-arity" :label "derive returns new h" :expected "true" :actual "(let [h (derive (make-hierarchy) :rect :shape)] (and (map? h) (isa? h :rect :shape)))" :portability :common} - {:suite "hierarchy / pure 3-arity" :label "original unchanged" :expected "false" :actual "(let [h0 (make-hierarchy) h1 (derive h0 :rect :shape)] (isa? h0 :rect :shape))" :portability :common} - {:suite "hierarchy / pure 3-arity" :label "isa? self" :expected "true" :actual "(isa? (make-hierarchy) :a :a)" :portability :common} - {:suite "hierarchy / pure 3-arity" :label "isa? transitive" :expected "true" :actual "(let [h (-> (make-hierarchy) (derive :square :rect) (derive :rect :shape))] (isa? h :square :shape))" :portability :common} - {:suite "hierarchy / pure 3-arity" :label "multi-parent" :expected "[true true]" :actual "(let [h (-> (make-hierarchy) (derive :sq :rect) (derive :sq :rhombus))] [(isa? h :sq :rect) (isa? h :sq :rhombus)])" :portability :common} - {:suite "hierarchy / pure 3-arity" :label "parents set" :expected "true" :actual "(let [h (-> (make-hierarchy) (derive :sq :rect) (derive :sq :rhombus))] (= #{:rect :rhombus} (parents h :sq)))" :portability :common} - {:suite "hierarchy / pure 3-arity" :label "ancestors transitive" :expected "true" :actual "(let [h (-> (make-hierarchy) (derive :square :rect) (derive :rect :shape))] (= #{:rect :shape} (ancestors h :square)))" :portability :common} - {:suite "hierarchy / pure 3-arity" :label "descendants transitive" :expected "true" :actual "(let [h (-> (make-hierarchy) (derive :square :rect) (derive :rect :shape))] (= #{:rect :square} (descendants h :shape)))" :portability :common} - {:suite "hierarchy / pure 3-arity" :label "underive removes" :expected "false" :actual "(let [h (-> (make-hierarchy) (derive :a :b) (underive :a :b))] (isa? h :a :b))" :portability :common} - {:suite "hierarchy / pure 3-arity" :label "vector isa?" :expected "true" :actual "(let [h (-> (make-hierarchy) (derive :rect :shape))] (isa? h [:rect :rect] [:shape :shape]))" :portability :common} - {:suite "hierarchy / pure 3-arity" :label "vector isa? length" :expected "false" :actual "(isa? (make-hierarchy) [:a] [:a :a])" :portability :common} - {:suite "hierarchy / pure 3-arity" :label "cyclic derive throws" :expected :throws :actual "(-> (make-hierarchy) (derive :a :b) (derive :b :a))" :portability :common} - {:suite "hierarchy / pure 3-arity" :label "duplicate derive ok" :expected "true" :actual "(let [h (-> (make-hierarchy) (derive :a :b) (derive :a :b))] (isa? h :a :b))" :portability :common} - {:suite "hierarchy / pure 3-arity" :label "parents nil when none" :expected "nil" :actual "(parents (make-hierarchy) :x)" :portability :common} - {:suite "hierarchy / global + multimethod dispatch" :label "global derive + isa?" :expected "true" :actual "(do (derive :g/sq :g/rect) (isa? :g/sq :g/rect))" :portability :common} - {:suite "hierarchy / global + multimethod dispatch" :label "global ancestors" :expected "true" :actual "(do (derive :g/a :g/b) (derive :g/b :g/c) (contains? (ancestors :g/a) :g/c))" :portability :common} - {:suite "hierarchy / global + multimethod dispatch" :label "global underive" :expected "false" :actual "(do (derive :g/u :g/v) (underive :g/u :g/v) (isa? :g/u :g/v))" :portability :common} - {:suite "hierarchy / global + multimethod dispatch" :label "dispatch via hierarchy" :expected ":is-shape" :actual "(do (derive :h/sq :h/shape) (defmulti hmm identity) (defmethod hmm :h/shape [_] :is-shape) (hmm :h/sq))" :portability :common} - {:suite "hierarchy / global + multimethod dispatch" :label "dispatch custom hierarchy" :expected ":parent" :actual "(do (def hh (atom (derive (make-hierarchy) :c :p))) (defmulti cmm identity :hierarchy hh) (defmethod cmm :p [_] :parent) (cmm :c))" :portability :common} - {:suite "hierarchy / global + multimethod dispatch" :label "dispatch exact beats isa" :expected ":exact" :actual "(do (derive :de/e1 :de/e2) (defmulti emm identity) (defmethod emm :de/e2 [_] :parent) (defmethod emm :de/e1 [_] :exact) (emm :de/e1))" :portability :common} - {:suite "interop / dot forms" :label "method call" :expected "\"v=41\"" :actual "(. {:value 41 :describe (fn [self] (str \"v=\" (:value self)))} describe)" :portability :jvm} - {:suite "interop / dot forms" :label "method with args" :expected "\"Hello Alice\"" :actual "(. {:greet (fn [self n] (str \"Hello \" n))} greet \"Alice\")" :portability :jvm} - {:suite "interop / dot forms" :label "field access .-" :expected "41" :actual "(.-value {:value 41})" :portability :jvm} - {:suite "interop / dot forms" :label "dot field keyword" :expected "41" :actual "(. {:value 41} :value)" :portability :jvm} - {:suite "interop / dot dispatch arms" :label "zero-arg coll-interop .count" :expected "3" :actual "(.count [1 2 3])" :portability :jvm} - {:suite "interop / dot dispatch arms" :label "zero-arg coll-interop .seq" :expected "[1 2]" :actual "(.seq [1 2])" :portability :jvm} - {:suite "interop / dot dispatch arms" :label "explicit dot zero-arg interop" :expected "3" :actual "(. [1 2 3] count)" :portability :jvm} - {:suite "interop / dot dispatch arms" :label "with-arg coll-interop .nth" :expected "2" :actual "(.nth [1 2 3] 1)" :portability :jvm} - {:suite "interop / dot dispatch arms" :label "record zero-arg method" :expected "10" :actual "(do (defprotocol Pd (gm [this])) (defrecord Rd [x] Pd (gm [this] (* 2 x))) (.gm (->Rd 5)))" :portability :jvm} - {:suite "interop / dot dispatch arms" :label "record method with args" :expected "15" :actual "(do (defprotocol Pa (am [this y])) (defrecord Ra [x] Pa (am [this y] (+ x y))) (.am (->Ra 5) 10))" :portability :jvm} - {:suite "interop / dot dispatch arms" :label "deftype method with args" :expected "7" :actual "(do (defprotocol Pq (qq [this y])) (deftype Tq [x] Pq (qq [this y] (+ x y))) (.qq (Tq. 3) 4))" :portability :jvm} - {:suite "interop / dot dispatch arms" :label "record -field is field access" :expected "7" :actual "(do (defrecord Rf [x]) (.-x (->Rf 7)))" :portability :jvm} - {:suite "interop / dot dispatch arms" :label "object-method with args .equals" :expected "true" :actual "(.equals \"a\" \"a\")" :portability :jvm} - {:suite "interop / arrays (aget/aset/alength)" :label "alength" :expected "3" :actual "(alength (object-array [1 2 3]))" :portability :jvm} - {:suite "interop / arrays (aget/aset/alength)" :label "aget" :expected "20" :actual "(aget (object-array [10 20 30]) 1)" :portability :jvm} - {:suite "interop / arrays (aget/aset/alength)" :label "aset returns val" :expected "9" :actual "(aset (object-array [1 2 3]) 1 9)" :portability :jvm} - {:suite "interop / arrays (aget/aset/alength)" :label "aset mutates" :expected "[7 2 3]" :actual "(let [a (object-array [1 2 3])] (aset a 0 7) (vec a))" :portability :jvm} - {:suite "interop / arrays (aget/aset/alength)" :label "aget 2d" :expected "4" :actual "(aget (to-array-2d [[1 2] [3 4]]) 1 1)" :portability :jvm} - {:suite "interop / String methods" :label ".toLowerCase" :expected "\"hi\"" :actual "(.toLowerCase \"HI\")" :portability :jvm} - {:suite "interop / String methods" :label ".toUpperCase" :expected "\"HI\"" :actual "(.toUpperCase \"hi\")" :portability :jvm} - {:suite "interop / String methods" :label "dot-form" :expected "\"hi\"" :actual "(. \"HI\" toLowerCase)" :portability :jvm} - {:suite "interop / String methods" :label ".trim" :expected "\"x\"" :actual "(.trim \" x \")" :portability :jvm} - {:suite "interop / String methods" :label ".length" :expected "3" :actual "(.length \"abc\")" :portability :jvm} - {:suite "interop / String methods" :label ".isEmpty" :expected "[true false]" :actual "[(.isEmpty \"\") (.isEmpty \"a\")]" :portability :jvm} - {:suite "interop / String methods" :label ".indexOf hit" :expected "1" :actual "(.indexOf \"abc\" \"b\")" :portability :jvm} - {:suite "interop / String methods" :label ".indexOf miss is -1" :expected "-1" :actual "(.indexOf \"abc\" \"z\")" :portability :jvm} - {:suite "interop / String methods" :label ".lastIndexOf" :expected "3" :actual "(.lastIndexOf \"abab\" \"b\")" :portability :jvm} - {:suite "interop / String methods" :label ".substring" :expected "\"bc\"" :actual "(.substring \"abc\" 1)" :portability :jvm} - {:suite "interop / String methods" :label ".substring end" :expected "\"b\"" :actual "(.substring \"abc\" 1 2)" :portability :jvm} - {:suite "interop / String methods" :label ".startsWith" :expected "true" :actual "(.startsWith \"abc\" \"ab\")" :portability :jvm} - {:suite "interop / String methods" :label ".endsWith" :expected "true" :actual "(.endsWith \"abc\" \"bc\")" :portability :jvm} - {:suite "interop / String methods" :label ".contains" :expected "true" :actual "(.contains \"abc\" \"b\")" :portability :jvm} - {:suite "interop / String methods" :label ".replace" :expected "\"axc\"" :actual "(.replace \"abc\" \"b\" \"x\")" :portability :jvm} - {:suite "interop / String methods" :label ".charAt" :expected "\\b" :actual "(.charAt \"abc\" 1)" :portability :jvm} - {:suite "interop / String methods" :label ".equalsIgnoreCase" :expected "true" :actual "(.equalsIgnoreCase \"AbC\" \"aBc\")" :portability :jvm} - {:suite "interop / String methods" :label "Long/MAX_VALUE" :expected "true" :actual "(pos? Long/MAX_VALUE)" :portability :jvm} - {:suite "interop / String methods" :label "String/valueOf num" :expected "\"42\"" :actual "(String/valueOf 42)" :portability :jvm} - {:suite "interop / String methods" :label "String/valueOf str" :expected "\"hi\"" :actual "(String/valueOf \"hi\")" :portability :jvm} - {:suite "interop / String methods" :label "String/valueOf kw" :expected "\":k\"" :actual "(String/valueOf :k)" :portability :jvm} - {:suite "interop / String methods" :label "String/valueOf nil" :expected "\"null\"" :actual "(String/valueOf nil)" :portability :jvm} - {:suite "interop / String methods" :label "instance? CharSequence" :expected "true" :actual "(instance? CharSequence \"aaa\")" :portability :common} - {:suite "interop / String methods" :label "instance? CharSequence non-str" :expected "false" :actual "(instance? CharSequence 42)" :portability :common} - {:suite "interop / String methods" :label "unsupported method throws" :expected :throws :actual "(.frobnicate \"abc\")" :portability :jvm} - {:suite "interop / java.time shims" :label "ofPattern formats #inst" :expected "true" :actual "(string? (.format (DateTimeFormatter/ofPattern \"yyyy-MM-dd\") #inst \"2020-03-05T13:45:30Z\"))" :portability :jvm} - {:suite "interop / java.time shims" :label "pattern shape" :expected "true" :actual "(boolean (re-matches #\"\\d{4}-\\d{2}-\\d{2}\" (.format (DateTimeFormatter/ofPattern \"yyyy-MM-dd\") #inst \"2020-03-05T13:45:30Z\")))" :portability :jvm} - {:suite "interop / java.time shims" :label "month name + ampm" :expected "true" :actual "(boolean (re-matches #\"[A-Z][a-z]{2} \\d{1,2}, 2020 \\d{1,2}:\\d{2} [AP]M\" (.format (DateTimeFormatter/ofPattern \"MMM d, yyyy h:mm a\") #inst \"2020-03-05T13:45:30Z\")))" :portability :jvm} - {:suite "interop / java.time shims" :label "quoted literal" :expected "true" :actual "(boolean (re-matches #\"\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\" (.format DateTimeFormatter/ISO_LOCAL_DATE_TIME #inst \"2020-03-05T13:45:30Z\")))" :portability :jvm} - {:suite "interop / java.time shims" :label "localized style" :expected "true" :actual "(string? (.format (DateTimeFormatter/ofLocalizedDate FormatStyle/MEDIUM) #inst \"2020-03-05T13:45:30Z\"))" :portability :jvm} - {:suite "interop / java.time shims" :label "withLocale chain" :expected "true" :actual "(string? (.format (.withLocale (DateTimeFormatter/ofPattern \"yyyy\") (java.util.Locale. \"en\")) #inst \"2020-01-01T00:00:00Z\"))" :portability :jvm} - {:suite "interop / java.time shims" :label "fix-date chain" :expected "true" :actual "(instance? LocalDateTime (-> #inst \"2020-03-05T13:45:30Z\" (.toInstant) (.atZone (ZoneId/systemDefault)) (.toLocalDateTime)))" :portability :jvm} - {:suite "interop / java.time shims" :label "inst is java.util.Date" :expected "true" :actual "(instance? java.util.Date #inst \"2020-01-01T00:00:00Z\")" :portability :jvm} - {:suite "interop / java.time shims" :label "Instant instance" :expected "true" :actual "(instance? java.time.Instant (Instant/ofEpochMilli 0))" :portability :jvm} - {:suite "interop / java.time shims" :label "getTime epoch ms" :expected "0" :actual "(.getTime #inst \"1970-01-01T00:00:00Z\")" :portability :jvm} - {:suite "interop / java.time shims" :label "toEpochMilli round trip" :expected "1234" :actual "(.toEpochMilli (Instant/ofEpochMilli 1234))" :portability :jvm} - {:suite "interop / java.time chrono-fields" :label "CLOCK_HOUR_OF_DAY midnight is 24" :expected "24" :actual "(.getLong (java.time.LocalTime/of 0 30) java.time.temporal.ChronoField/CLOCK_HOUR_OF_DAY)" :portability :jvm} - {:suite "interop / java.time chrono-fields" :label "HOUR_OF_AMPM" :expected "2" :actual "(.getLong (java.time.LocalTime/of 14 0) java.time.temporal.ChronoField/HOUR_OF_AMPM)" :portability :jvm} - {:suite "interop / java.time chrono-fields" :label "CLOCK_HOUR_OF_AMPM noon is 12" :expected "12" :actual "(.getLong (java.time.LocalTime/of 12 0) java.time.temporal.ChronoField/CLOCK_HOUR_OF_AMPM)" :portability :jvm} - {:suite "interop / java.time chrono-fields" :label "ALIGNED_DAY_OF_WEEK_IN_MONTH" :expected "3" :actual "(.getLong (java.time.LocalDate/of 2020 3 17) java.time.temporal.ChronoField/ALIGNED_DAY_OF_WEEK_IN_MONTH)" :portability :jvm} - {:suite "interop / java.time chrono-fields" :label "ALIGNED_WEEK_OF_MONTH" :expected "3" :actual "(.getLong (java.time.LocalDate/of 2020 3 17) java.time.temporal.ChronoField/ALIGNED_WEEK_OF_MONTH)" :portability :jvm} - {:suite "interop / java.time chrono-fields" :label "Year isSupported + getLong" :expected "2020" :actual "(.getLong (java.time.Year/of 2020) java.time.temporal.ChronoField/YEAR)" :portability :jvm} - {:suite "interop / java.time chrono-fields" :label "YearMonth PROLEPTIC_MONTH" :expected "24244" :actual "(.getLong (java.time.YearMonth/of 2020 5) java.time.temporal.ChronoField/PROLEPTIC_MONTH)" :portability :jvm} - {:suite "interop / java.time chrono-fields" :label "ISO_OFFSET_DATE_TIME keeps fractional seconds" :expected "1594033153417" :actual "(.toEpochMilli (.toInstant (java.time.ZonedDateTime/parse \"2020-07-06T10:59:13.417Z\" java.time.format.DateTimeFormatter/ISO_OFFSET_DATE_TIME)))" :portability :jvm} - {:suite "interop / java.time chrono-fields" :label "ISO_OFFSET_DATE_TIME without fraction" :expected "1594033153000" :actual "(.toEpochMilli (.toInstant (java.time.ZonedDateTime/parse \"2020-07-06T10:59:13Z\" java.time.format.DateTimeFormatter/ISO_OFFSET_DATE_TIME)))" :portability :jvm} - {:suite "interop / java.util Optional" :label "of + get" :expected "42" :actual "(.get (java.util.Optional/of 42))" :portability :jvm} - {:suite "interop / java.util Optional" :label "empty isPresent" :expected "false" :actual "(.isPresent (java.util.Optional/empty))" :portability :jvm} - {:suite "interop / java.util Optional" :label "value equality" :expected "true" :actual "(= (java.util.Optional/of 5) (java.util.Optional/of 5))" :portability :jvm} - {:suite "interop / java.util Optional" :label "empty orElse" :expected "7" :actual "(.orElse (java.util.Optional/empty) 7)" :portability :jvm} - {:suite "interop / java.util Optional" :label "ofNullable nil is empty" :expected "true" :actual "(= (java.util.Optional/empty) (java.util.Optional/ofNullable nil))" :portability :jvm} - {:suite "interop / class + isa?" :label "forName throws for unknown class" :expected ":cnfe" :actual "(try (do (Class/forName \"totally.Bogus.Class\") :found) (catch ClassNotFoundException e :cnfe))" :portability :jvm} - {:suite "interop / class + isa?" :label "PersistentHashSet isa java.util.Set" :expected "true" :actual "(isa? clojure.lang.PersistentHashSet java.util.Set)" :portability :jvm} - {:suite "interop / class + isa?" :label "String isa Object" :expected "true" :actual "(isa? java.lang.String java.lang.Object)" :portability :jvm} - {:suite "interop / class + isa?" :label "IFn isa Object" :expected "true" :actual "(isa? clojure.lang.IFn java.lang.Object)" :portability :jvm} - {:suite "interop / class + isa?" :label "class of vector" :expected "true" :actual "(= clojure.lang.PersistentVector (class [1]))" :portability :jvm} - {:suite "interop / class + isa?" :label "isa? class keyword Object" :expected "true" :actual "(isa? (class :k) java.lang.Object)" :portability :jvm} - {:suite "interop / java.time shims" :label "Instant/now is current" :expected "true" :actual "(> (.toEpochMilli (Instant/now)) 1500000000000)" :portability :jvm} - {:suite "interop / java.time shims" :label "sql types are not" :expected "false" :actual "(instance? java.sql.Timestamp #inst \"2020-01-01T00:00:00Z\")" :portability :jvm} - {:suite "interop / StringReader & StringBuilder" :label "StringReader read" :expected "[97 98 -1]" :actual "(let [r (java.io.StringReader. \"ab\")] [(.read r) (.read r) (.read r)])" :portability :jvm} - {:suite "interop / StringReader & StringBuilder" :label "mark/reset" :expected "[97 97]" :actual "(let [r (StringReader. \"ab\")] (.mark r 1) [(.read r) (do (.reset r) (.read r))])" :portability :jvm} - {:suite "interop / StringReader & StringBuilder" :label "StringBuilder append" :expected "\"ab1\"" :actual "(.toString (-> (StringBuilder.) (.append \"a\") (.append \\b) (.append 1)))" :portability :jvm} - {:suite "interop / StringReader & StringBuilder" :label "capacity arg is not content" :expected "\"x\"" :actual "(.toString (.append (StringBuilder. 16) \"x\"))" :portability :jvm} - {:suite "interop / StringReader & StringBuilder" :label "setLength truncates" :expected "\"ab\"" :actual "(let [sb (StringBuilder.)] (.append sb \"abcd\") (.setLength sb 2) (.toString sb))" :portability :jvm} - {:suite "interop / StringReader & StringBuilder" :label "char-array of string" :expected "true" :actual "(instance? (Class/forName \"[C\") (char-array \"ab\"))" :portability :jvm} - {:suite "interop / StringReader & StringBuilder" :label "reader over char[]" :expected "97" :actual "(do (require (quote clojure.java.io)) (.read (clojure.java.io/reader (char-array \"abc\"))))" :portability :jvm} - {:suite "interop / StringReader & StringBuilder" :label "with-open closes shim" :expected "97" :actual "(with-open [r (StringReader. \"a\")] (.read r))" :portability :jvm} - {:suite "interop / StringReader & StringBuilder" :label "File.toURL methods read it back" :expected "\"file:/tmp/x\"" :actual "(do (require (quote clojure.java.io)) (.toString (.toURL (clojure.java.io/file \"/tmp/x\"))))" :portability :jvm} - {:suite "interop / StringReader & StringBuilder" :label "vector :import shares deftype ctor" :expected "\"hi!\"" :actual "(do (ns spec.nodea) (defprotocol SpecP (spec-pm [this])) (deftype SpecTN [t] SpecP (spec-pm [this] (str t \"!\"))) (ns spec.nodeb (:import [spec.nodea SpecTN])) (.spec-pm (SpecTN. \"hi\")))" :portability :jvm} - {:suite "interop / PushbackReader & parse statics" :label "PushbackReader read" :expected "[97 98]" :actual "(let [r (java.io.PushbackReader. (java.io.StringReader. \"ab\"))] [(.read r) (.read r)])" :portability :jvm} - {:suite "interop / PushbackReader & parse statics" :label "unread pushes back" :expected "[97 97 98]" :actual "(let [r (PushbackReader. (StringReader. \"ab\")) a (.read r)] (.unread r a) [a (.read r) (.read r)])" :portability :jvm} - {:suite "interop / PushbackReader & parse statics" :label "unread accepts a char" :expected "[120 97]" :actual "(let [r (PushbackReader. (StringReader. \"a\"))] (.unread r \\x) [(.read r) (.read r)])" :portability :jvm} - {:suite "interop / PushbackReader & parse statics" :label "edn/read from reader" :expected "5432" :actual "(do (require (quote clojure.edn)) (clojure.edn/read (java.io.PushbackReader. (java.io.StringReader. \"{:db {:port 5432}}\\nrest\"))) (get-in (clojure.edn/read-string \"{:db {:port 5432}}\") [:db :port]))" :portability :jvm} - {:suite "interop / PushbackReader & parse statics" :label "edn/read multi-line" :expected "true" :actual "(do (require (quote clojure.edn)) (= {:a 1 :b 2} (clojure.edn/read (PushbackReader. (StringReader. \"{:a 1\\n :b 2}\")))))" :portability :jvm} - {:suite "interop / PushbackReader & parse statics" :label "Long/parseLong" :expected "42" :actual "(Long/parseLong \"42\")" :portability :jvm} - {:suite "interop / PushbackReader & parse statics" :label "parseLong rejects non-numeric" :expected :throws :actual "(Long/parseLong \"4x\")" :portability :jvm} - {:suite "interop / PushbackReader & parse statics" :label "BigInteger." :expected "123" :actual "(BigInteger. \"123\")" :portability :jvm} - {:suite "interop / PushbackReader & parse statics" :label "Boolean/parseBoolean" :expected "[true false false]" :actual "[(Boolean/parseBoolean \"true\") (Boolean/parseBoolean \"false\") (Boolean/parseBoolean \"yes\")]" :portability :jvm} - {:suite "interop / PushbackReader & parse statics" :label "System/getenv is a map" :expected "true" :actual "(string? (get (System/getenv) \"HOME\"))" :portability :jvm} - {:suite "interop / PushbackReader & parse statics" :label "System/exit resolves" :expected "true" :actual "(fn? System/exit)" :portability :jvm} - {:suite "interop / PushbackReader & parse statics" :label "getenv entries destructure (non-empty)" :expected "true" :actual "(let [es (map (fn [[k v]] [k v]) (System/getenv))] (and (pos? (count es)) (every? vector? es)))" :portability :jvm} - {:suite "interop / PushbackReader & parse statics" :label "seq over a raw host table" :expected "true" :actual "(pos? (count (seq (System/getenv))))" :portability :jvm} - {:suite "interop / PushbackReader & parse statics" :label "into {} from host table" :expected "true" :actual "(string? (get (into {} (map (fn [[k v]] [k v]) (System/getenv))) \"HOME\"))" :portability :jvm} - {:suite "interop / PushbackReader & parse statics" :label "System/getProperties" :expected "true" :actual "(string? (get (System/getProperties) \"os.name\"))" :portability :jvm} - {:suite "host-interop / ring-codec surface" :label "URLEncoder www form" :expected "\"a+b%3Dc\"" :actual "(URLEncoder/encode \"a b=c\")" :portability :jvm} - {:suite "host-interop / ring-codec surface" :label "URLDecoder www form" :expected "\"a b=c\"" :actual "(URLDecoder/decode \"a+b%3Dc\" (Charset/forName \"UTF-8\"))" :portability :jvm} - {:suite "host-interop / ring-codec surface" :label "url round trip" :expected "\"x &=%?\"" :actual "(URLDecoder/decode (URLEncoder/encode \"x &=%?\"))" :portability :jvm} - {:suite "host-interop / ring-codec surface" :label "Base64 encode" :expected "\"aGVsbG8=\"" :actual "(String. (.encode (Base64/getEncoder) (.getBytes \"hello\")))" :portability :jvm} - {:suite "host-interop / ring-codec surface" :label "Base64 round trip" :expected "\"hello\"" :actual "(String. (.decode (Base64/getDecoder) (String. (.encode (Base64/getEncoder) (.getBytes \"hello\")))))" :portability :jvm} - {:suite "host-interop / ring-codec surface" :label "Integer radix + byteValue" :expected "-1" :actual "(.byteValue (Integer/valueOf \"ff\" 16))" :portability :jvm} - {:suite "host-interop / ring-codec surface" :label "Integer parseInt" :expected "255" :actual "(Integer/parseInt \"ff\" 16)" :portability :jvm} - {:suite "host-interop / ring-codec surface" :label "StringTokenizer" :expected "[\"a=1\" \"b=2\"]" :actual "(let [t (StringTokenizer. \"a=1&b=2\" \"&\")] [(.nextToken t) (.nextToken t)])" :portability :jvm} - {:suite "host-interop / ring-codec surface" :label "MapEntry key/val" :expected "[:a 1]" :actual "(let [e (MapEntry. :a 1)] [(key e) (val e)])" :portability :jvm} - {:suite "host-interop / ring-codec surface" :label "String ctor from bytes" :expected "\"hi\"" :actual "(String. (.getBytes \"hi\"))" :portability :jvm} - {:suite "host-interop / ring-codec surface" :label "extend-protocol Map" :expected ":map" :actual "(do (defprotocol Pe (pe [x])) (extend-protocol Pe Map (pe [m] :map) Object (pe [o] :obj)) (pe {:a 1}))" :portability :common} - {:suite "host-interop / ring-codec surface" :label "extend-protocol nil" :expected ":nil" :actual "(do (defprotocol Pn (pn [x])) (extend-protocol Pn nil (pn [n] :nil) Object (pn [o] :obj)) (pn nil))" :portability :common} - {:suite "host-interop / ring-codec surface" :label "extend-protocol Map covers sorted" :expected ":map" :actual "(do (defprotocol Ps (ps [x])) (extend-protocol Ps Map (ps [m] :map) Object (ps [o] :obj)) (ps (sorted-map 1 2)))" :portability :common} - {:suite "host-interop / ring-codec surface" :label "reduce over reified IReduceInit" :expected "42" :actual "(reduce + 0 (reify clojure.lang.IReduceInit (reduce [_ f init] (f (f init 40) 2))))" :portability :jvm} - {:suite "core / reify" :label "multi-arity method dispatches by arg count" :expected "[:z 9]" :actual "(do (defprotocol P (m [_] [_ a])) (let [r (reify P (m [_] :z) (m [_ x] x))] [(m r) (m r 9)]))" :portability :common} - {:suite "core / reify" :label "reify implements IObj and carries metadata" :expected "[true 2]" :actual "(do (defprotocol Q (qq [_])) (let [r (reify Q (qq [_] 1))] [(instance? clojure.lang.IObj r) (:k (meta (with-meta r {:k 2})))]))" :portability :jvm} - {:suite "core / reify" :label "with-meta leaves the original untouched and keeps dispatch" :expected "[nil {:k 2} 1]" :actual "(do (defprotocol Q (qq [_])) (let [r (reify Q (qq [_] 1)) r2 (with-meta r {:k 2})] [(meta r) (meta r2) (qq r2)]))" :portability :common} - {:suite "host-interop / class tokens & readers" :label "class name evaluates to canonical string" :expected "java.lang.String" :actual "String" :portability :common} - {:suite "host-interop / class tokens & readers" :label "dispatch-only class name" :expected "\"java.io.InputStream\"" :actual "InputStream" :portability :common} - {:suite "host-interop / class tokens & readers" :label "(class x) matches the token" :expected "true" :actual "(= String (class \"abc\"))" :portability :common} - {:suite "host-interop / class tokens & readers" :label "defmulti on class dispatches" :expected ":str" :actual "(do (defmulti cm (fn [x] (class x))) (defmethod cm String [x] :str) (cm \"a\"))" :portability :common} - {:suite "host-interop / class tokens & readers" :label "defmethod on nil dispatch value" :expected ":nil" :actual "(do (defmulti cn (fn [x] (class x))) (defmethod cn nil [x] :nil) (defmethod cn String [x] :str) (cn nil))" :portability :common} - {:suite "host-interop / class tokens & readers" :label "Class str is class-prefixed" :expected "\"class java.lang.String\"" :actual "(str (class \"\"))" :portability :common} - {:suite "host-interop / class tokens & readers" :label "Class getName" :expected "\"java.lang.String\"" :actual "(.getName (class \"\"))" :portability :jvm} - {:suite "host-interop / class tokens & readers" :label "Class getSimpleName" :expected "\"Long\"" :actual "(.getSimpleName (class 5))" :portability :jvm} - {:suite "host-interop / class tokens & readers" :label "Class of equal-typed values is =" :expected "true" :actual "(= (class 5) (class 6))" :portability :common} - {:suite "host-interop / class tokens & readers" :label "Class in a thrown message" :expected "\"of class java.lang.String\"" :actual "(try (throw (Exception. (str \"of \" (class \"\")))) (catch Exception e (.getMessage e)))" :portability :jvm} - {:suite "host-interop / class tokens & readers" :label "ctor sugar still constructs" :expected "\"x\"" :actual "(.toString (StringBuilder. \"x\"))" :portability :jvm} - {:suite "host-interop / class tokens & readers" :label "return-hinted defn parses" :expected "7" :actual "(do (defn- hb ^bytes [b] b) (hb 7))" :portability :common} - {:suite "host-interop / class tokens & readers" :label "hinted multi-arity parses" :expected ":two" :actual "((fn ([x] :one) (^String [x y] :two)) 1 2)" :portability :common} - {:suite "host-interop / class tokens & readers" :label "slurp drains a StringReader" :expected "\"a=1\"" :actual "(slurp (StringReader. \"a=1\"))" :portability :jvm} - {:suite "host-interop / class tokens & readers" :label "slurp accepts :encoding opts" :expected "\"b\"" :actual "(slurp (StringReader. \"b\") :encoding \"UTF-8\")" :portability :jvm} - {:suite "host-interop / class tokens & readers" :label "replace with fn replacement is literal" :expected "\"$0\"" :actual "(do (require (quote [clojure.string :as s9])) (s9/replace \"x\" #\".\" (fn [m] \"$0\")))" :portability :common} - {:suite "host-interop / class tokens & readers" :label "replace fn gets group vector" :expected "\"v=k\"" :actual "(do (require (quote [clojure.string :as s9])) (s9/replace \"k=v\" #\"(\\w+)=(\\w+)\" (fn [[_ k v]] (str v \"=\" k))))" :portability :common} - {:suite "host-interop / class tokens & readers" :label "indexOf int needle is a char code" :expected "1" :actual "(.indexOf \"a=b\" 61)" :portability :jvm} - {:suite "host-interop / exception + HashMap shims" :label "getMessage on a thrown string" :expected "\"class java.lang.String cannot be cast to class java.lang.Throwable (java.lang.String and java.lang.Throwable are in module java.base of loader 'bootstrap')\"" :actual "(try (throw \"boom\") (catch Throwable e (.getMessage e)))" :portability :jvm} - {:suite "host-interop / exception + HashMap shims" :label "getMessage on ex-info" :expected "\"bad\"" :actual "(try (throw (ex-info \"bad\" {})) (catch Throwable e (.getMessage e)))" :portability :jvm} - {:suite "host-interop / exception + HashMap shims" :label "calling a non-fn throws ClassCastException" :expected ":ccx" :actual "(try (1 2) (catch ClassCastException _ :ccx))" :portability :common} - {:suite "host-interop / exception + HashMap shims" :label "non-fn cast is a RuntimeException too" :expected ":rt" :actual "(try ((identity 5)) (catch RuntimeException _ :rt))" :portability :common} - {:suite "host-interop / exception + HashMap shims" :label "HashMap get" :expected "2" :actual "(let [m (HashMap. {:a 1 :b 2})] (.get m :b))" :portability :jvm} - {:suite "host-interop / exception + HashMap shims" :label "HashMap put + size" :expected "2" :actual "(let [m (HashMap. {})] (.put m :x 1) (.put m :y 2) (.size m))" :portability :jvm} - {:suite "host-interop / reader-feature toggle" :label "features default to jolt+default" :expected "true" :actual "(contains? (set (__reader-features)) \"jolt\")" :portability :common} - {:suite "host-interop / reader-feature toggle" :label "set + read back" :expected "true" :actual "(do (def prev (__reader-features)) (__reader-features-set! [\"clj\" \"jolt\" \"default\"]) (def r (contains? (set (__reader-features)) \"clj\")) (__reader-features-set! prev) r)" :portability :common} - {:suite "host-interop / reader-feature toggle" :label "restore returns to default" :expected "false" :actual "(do (def prev (__reader-features)) (__reader-features-set! [\"clj\"]) (__reader-features-set! prev) (contains? (set (__reader-features)) \"clj\"))" :portability :common} - {:suite "host-interop / migratus class shims" :label "Exception. message" :expected "\"boom\"" :actual "(try (throw (Exception. \"boom\")) (catch Throwable e (.getMessage e)))" :portability :jvm} - {:suite "host-interop / migratus class shims" :label "IllegalArgumentException." :expected "\"bad\"" :actual "(try (throw (IllegalArgumentException. \"bad\")) (catch Exception e (.getMessage e)))" :portability :jvm} - {:suite "host-interop / migratus class shims" :label "InterruptedException." :expected "\"stop\"" :actual "(try (throw (InterruptedException. \"stop\")) (catch Throwable e (.getMessage e)))" :portability :jvm} - {:suite "host-interop / migratus class shims" :label "Character/isUpperCase" :expected "true" :actual "(Character/isUpperCase \\A)" :portability :jvm} - {:suite "host-interop / migratus class shims" :label "Character/isLowerCase" :expected "true" :actual "(Character/isLowerCase \\a)" :portability :jvm} - {:suite "host-interop / migratus class shims" :label "Character/isUpperCase neg" :expected "false" :actual "(Character/isUpperCase \\a)" :portability :jvm} - {:suite "host-interop / migratus class shims" :label "Thread/interrupted" :expected "false" :actual "(Thread/interrupted)" :portability :jvm} - {:suite "host-interop / migratus class shims" :label "Long/valueOf" :expected "42" :actual "(Long/valueOf \"42\")" :portability :jvm} - {:suite "host-interop / migratus class shims" :label "Timestamp is millis" :expected "1000" :actual "(.getTime (java.util.Date. (java.sql.Timestamp. 1000)))" :portability :jvm} - {:suite "host-interop / migratus class shims" :label "SimpleDateFormat UTC" :expected "\"19700101000000\"" :actual "(let [f (doto (java.text.SimpleDateFormat. \"yyyyMMddHHmmss\") (.setTimeZone (java.util.TimeZone/getTimeZone \"UTC\")))] (.format f (java.util.Date. 0)))" :portability :jvm} - {:suite "host-interop / java.io.File" :label "instance? File" :expected "true" :actual "(do (require '[clojure.java.io :as io]) (instance? java.io.File (io/file \"/a/b\")))" :portability :jvm} - {:suite "host-interop / java.io.File" :label "str is the path" :expected "\"/a/b\"" :actual "(do (require '[clojure.java.io :as io]) (str (io/file \"/a/b\")))" :portability :jvm} - {:suite "host-interop / java.io.File" :label "getName" :expected "\"c.txt\"" :actual "(do (require '[clojure.java.io :as io]) (.getName (io/file \"/a/b/c.txt\")))" :portability :jvm} - {:suite "host-interop / java.io.File" :label "getPath joins" :expected "\"/a/b\"" :actual "(do (require '[clojure.java.io :as io]) (.getPath (io/file \"/a\" \"b\")))" :portability :jvm} - {:suite "host-interop / java.io.File" :label "isDirectory of repo dir" :expected "true" :actual "(do (require '[clojure.java.io :as io]) (.isDirectory (io/file \"docs\")))" :portability :jvm} - {:suite "host-interop / java.io.File" :label "isFile of repo file" :expected "true" :actual "(do (require '[clojure.java.io :as io]) (.isFile (io/file \"README.md\")))" :portability :jvm} - {:suite "host-interop / java.io.File" :label "exists is false off-disk" :expected "false" :actual "(do (require '[clojure.java.io :as io]) (.exists (io/file \"/no/such/path/xyz\")))" :portability :jvm} - {:suite "host-interop / java.io.File" :label "file-seq yields File values" :expected "true" :actual "(do (require '[clojure.java.io :as io]) (every? (fn [f] (instance? java.io.File f)) (file-seq (io/file \"docs\"))))" :portability :jvm} - {:suite "host-interop / java.io.File" :label "file-seq finds files" :expected "true" :actual "(do (require '[clojure.java.io :as io]) (pos? (count (filter (fn [f] (.isFile f)) (file-seq (io/file \"docs\"))))))" :portability :jvm} - {:suite "host-interop / logging host shims" :label "LockingTransaction/isRunning" :expected "false" :actual "(clojure.lang.LockingTransaction/isRunning)" :portability :jvm} - {:suite "host-interop / logging host shims" :label "pprint writes value" :expected "\"[1 2 3]\\n\"" :actual "(do (require '[clojure.pprint :as pp]) (with-out-str (pp/pprint [1 2 3])))" :portability :common} - {:suite "host-interop / logging host shims" :label "with-pprint-dispatch runs body" :expected "42" :actual "(do (require '[clojure.pprint :as pp]) (pp/with-pprint-dispatch pp/code-dispatch 42))" :portability :common} - {:suite "host-interop / macro dispatch & short-circuit patterns" :label "conditional-eval suppresses" :expected "0" :actual "(do (def ^:dynamic *enabled* false) (defmacro when-on [& body] `(when *enabled* ~@body)) (let [a (atom 0)] (when-on (reset! a 9)) @a))" :portability :common} - {:suite "host-interop / macro dispatch & short-circuit patterns" :label "conditional-eval fires" :expected "9" :actual "(do (def ^:dynamic *enabled* true) (defmacro when-on [& body] `(when *enabled* ~@body)) (let [a (atom 0)] (when-on (reset! a 9)) @a))" :portability :common} - {:suite "host-interop / macro dispatch & short-circuit patterns" :label "spy-like eval+print+return" :expected "3" :actual "(do (defmacro spylog [expr] `(let [v# ~expr] (println v#) v#)) (spylog (+ 1 2)))" :portability :common} - {:suite "host-interop / macro dispatch & short-circuit patterns" :label "multi-arity 4 dispatch" :expected "[:single :double :triple :quad]" :actual "(do (defmacro ml ([a] :single) ([a b] :double) ([a b c] :triple) ([a b c d] :quad)) [(ml 1) (ml 1 2) (ml 1 2 3) (ml 1 2 3 4)])" :portability :common} - {:suite "inst / reading & identity" :label "reads to inst" :expected "true" :actual "(inst? #inst \"2020-01-01T00:00:00Z\")" :portability :common} - {:suite "inst / reading & identity" :label "inst? false on string" :expected "false" :actual "(inst? \"2020-01-01\")" :portability :common} - {:suite "inst / reading & identity" :label "epoch zero" :expected "0" :actual "(inst-ms #inst \"1970-01-01T00:00:00Z\")" :portability :common} - {:suite "inst / reading & identity" :label "one second" :expected "1000" :actual "(inst-ms #inst \"1970-01-01T00:00:01Z\")" :portability :common} - {:suite "inst / reading & identity" :label "millis" :expected "123" :actual "(inst-ms #inst \"1970-01-01T00:00:00.123Z\")" :portability :common} - {:suite "inst / reading & identity" :label "a real date" :expected "1577836800000" :actual "(inst-ms #inst \"2020-01-01T00:00:00Z\")" :portability :common} - {:suite "inst / reading & identity" :label "inst-ms throws on non-inst" :expected :throws :actual "(inst-ms 42)" :portability :common} - {:suite "inst / partial timestamps & offsets" :label "year only" :expected "true" :actual "(= #inst \"2020\" #inst \"2020-01-01T00:00:00.000Z\")" :portability :common} - {:suite "inst / partial timestamps & offsets" :label "year-month" :expected "true" :actual "(= #inst \"2020-03\" #inst \"2020-03-01T00:00:00Z\")" :portability :common} - {:suite "inst / partial timestamps & offsets" :label "date only" :expected "true" :actual "(= #inst \"2020-03-15\" #inst \"2020-03-15T00:00:00Z\")" :portability :common} - {:suite "inst / partial timestamps & offsets" :label "positive offset" :expected "true" :actual "(= #inst \"2020-01-01T01:00:00+01:00\" #inst \"2020-01-01T00:00:00Z\")" :portability :common} - {:suite "inst / partial timestamps & offsets" :label "negative offset" :expected "true" :actual "(= #inst \"2019-12-31T23:00:00-01:00\" #inst \"2020-01-01T00:00:00Z\")" :portability :common} - {:suite "inst / partial timestamps & offsets" :label "-00:00 offset" :expected "true" :actual "(= #inst \"2020-01-01T00:00:00-00:00\" #inst \"2020-01-01T00:00:00Z\")" :portability :common} - {:suite "inst / partial timestamps & offsets" :label "bad timestamp throws" :expected :throws :actual "#inst \"garbage\"" :portability :common} - {:suite "inst / value semantics & printing" :label "equal by instant" :expected "true" :actual "(= #inst \"2020-01-01T00:00:00Z\" #inst \"2020-01-01T00:00:00.000Z\")" :portability :common} - {:suite "inst / value semantics & printing" :label "unequal instants" :expected "false" :actual "(= #inst \"2020-01-01T00:00:00Z\" #inst \"2020-01-01T00:00:01Z\")" :portability :common} - {:suite "inst / value semantics & printing" :label "works as map key" :expected ":v" :actual "(get {#inst \"2020-01-01T00:00:00Z\" :v} #inst \"2020-01-01T00:00:00.000Z\")" :portability :common} - {:suite "inst / value semantics & printing" :label "pr-str round-trips" :expected "\"#inst \\\"2020-01-01T00:00:00.000-00:00\\\"\"" :actual "(pr-str #inst \"2020-01-01T00:00:00Z\")" :portability :common} - {:suite "io / with-out-str captures" :label "println" :expected "\"hi\\n\"" :actual "(with-out-str (println \"hi\"))" :portability :common} - {:suite "io / with-out-str captures" :label "print spaces" :expected "\"a b\"" :actual "(with-out-str (print \"a\" \"b\"))" :portability :common} - {:suite "io / with-out-str captures" :label "prn quotes" :expected "\"[1 2]\\n\"" :actual "(with-out-str (prn [1 2]))" :portability :common} - {:suite "io / with-out-str captures" :label "pr no newline" :expected "\"5\"" :actual "(with-out-str (pr 5))" :portability :common} - {:suite "io / with-out-str captures" :label "multiple writes" :expected "\"12\"" :actual "(with-out-str (print 1) (print 2))" :portability :common} - {:suite "io / with-out-str captures" :label "no output" :expected "\"\"" :actual "(with-out-str 42)" :portability :common} - {:suite "io / with-out-str captures" :label "println no args" :expected "\"\\n\"" :actual "(with-out-str (println))" :portability :common} - {:suite "io / *-str builders" :label "print-str" :expected "\"a b\"" :actual "(print-str \"a\" \"b\")" :portability :common} - {:suite "io / *-str builders" :label "println-str" :expected "\"x\\n\"" :actual "(println-str \"x\")" :portability :common} - {:suite "io / *-str builders" :label "prn-str" :expected "\"[1 2]\\n\"" :actual "(prn-str [1 2])" :portability :common} - {:suite "io / *-str builders" :label "pr-str quotes" :expected "\"\\\"s\\\"\"" :actual "(pr-str \"s\")" :portability :common} - {:suite "io / *-str builders" :label "pr-str keyword" :expected "\":a\"" :actual "(pr-str :a)" :portability :common} - {:suite "io / str & format" :label "str concat" :expected "\"1:ab\"" :actual "(str 1 :a \"b\")" :portability :common} - {:suite "io / str & format" :label "str nil" :expected "\"\"" :actual "(str nil)" :portability :common} - {:suite "io / str & format" :label "str of coll" :expected "\"[1 2]\"" :actual "(str [1 2])" :portability :common} - {:suite "io / str & format" :label "format d/s" :expected "\"5-x\"" :actual "(format \"%d-%s\" 5 \"x\")" :portability :common} - {:suite "io / str & format" :label "format float" :expected "\"3.14\"" :actual "(format \"%.2f\" 3.14159)" :portability :common} - {:suite "io / *in* + with-in-str + read-line" :label "read-line one line" :expected "\"hello\"" :actual "(with-in-str \"hello\" (read-line))" :portability :common} - {:suite "io / *in* + with-in-str + read-line" :label "read-line strips nl" :expected "\"a\"" :actual "(with-in-str \"a\\nb\" (read-line))" :portability :common} - {:suite "io / *in* + with-in-str + read-line" :label "read-line sequential" :expected "[\"a\" \"b\"]" :actual "(with-in-str \"a\\nb\" [(read-line) (read-line)])" :portability :common} - {:suite "io / *in* + with-in-str + read-line" :label "read-line EOF nil" :expected "nil" :actual "(with-in-str \"\" (read-line))" :portability :common} - {:suite "io / *in* + with-in-str + read-line" :label "read-line after last" :expected "[\"x\" nil]" :actual "(with-in-str \"x\" [(read-line) (read-line)])" :portability :common} - {:suite "io / *in* + with-in-str + read-line" :label "empty line" :expected "[\"\" \"y\"]" :actual "(with-in-str \"\\ny\" [(read-line) (read-line)])" :portability :common} - {:suite "io / *in* + with-in-str + read-line" :label "*in* is bound" :expected "false" :actual "(with-in-str \"\" (map? *in*))" :portability :common} - {:suite "io / read" :label "read a form" :expected "42" :actual "(with-in-str \"42\" (read))" :portability :common} - {:suite "io / read" :label "read a list form" :expected "(quote (+ 1 2))" :actual "(with-in-str \"(+ 1 2)\" (read))" :portability :common} - {:suite "io / read" :label "read two forms" :expected "[1 2]" :actual "(with-in-str \"1 2\" [(read) (read)])" :portability :common} - {:suite "io / read" :label "read then read-line" :expected "[1 \" rest\"]" :actual "(with-in-str \"1 rest\\nnext\" [(read) (read-line)])" :portability :common} - {:suite "io / read" :label "read vector" :expected "[1 2]" :actual "(with-in-str \"[1 2]\" (read))" :portability :common} - {:suite "io / read" :label "read nil literal" :expected "nil" :actual "(with-in-str \"nil\" (read))" :portability :common} - {:suite "io / read" :label "read EOF throws" :expected :throws :actual "(with-in-str \"\" (read))" :portability :common} - {:suite "io / read" :label "read EOF value" :expected ":done" :actual "(with-in-str \"\" (read *in* false :done))" :portability :common} - {:suite "io / read" :label "read eval data" :expected "3" :actual "(with-in-str \"(+ 1 2)\" (eval (read)))" :portability :common} - {:suite "io / line-seq" :label "line-seq" :expected "[\"a\" \"b\" \"c\"]" :actual "(with-in-str \"a\\nb\\nc\" (vec (line-seq *in*)))" :portability :common} - {:suite "io / line-seq" :label "line-seq empty" :expected "nil" :actual "(with-in-str \"\" (seq (line-seq *in*)))" :portability :common} - {:suite "io / line-seq" :label "line-seq is lazy seq" :expected "true" :actual "(with-in-str \"a\\nb\" (seq? (line-seq *in*)))" :portability :common} - {:suite "io / line-seq" :label "line-seq count" :expected "3" :actual "(with-in-str \"1\\n2\\n3\" (count (line-seq *in*)))" :portability :common} - {:suite "io / print family (overlay)" :label "pr-str multi-arg spacing" :expected "\"\\\"a\\\" [1 2] :k\"" :actual "(pr-str \"a\" [1 2] :k)" :portability :common} - {:suite "io / print family (overlay)" :label "pr-str zero args" :expected "\"\"" :actual "(pr-str)" :portability :common} - {:suite "io / print family (overlay)" :label "pr-str escapes" :expected "\"\\\"a\\\\\\\"b\\\"\"" :actual "(pr-str \"a\\\"b\")" :portability :common} - {:suite "io / print family (overlay)" :label "print is unreadable" :expected "\"a b\"" :actual "(with-out-str (print \"a\" \"b\"))" :portability :common} - {:suite "io / print family (overlay)" :label "println appends newline" :expected "\"x 1\\n\"" :actual "(with-out-str (println \"x\" 1))" :portability :common} - {:suite "io / print family (overlay)" :label "prn is readable + newline" :expected "\"[1 \\\"s\\\"]\\n\"" :actual "(with-out-str (prn [1 \"s\"]))" :portability :common} - {:suite "io / print family (overlay)" :label "pr writes no newline" :expected "\"\\\\a\"" :actual "(with-out-str (pr \\a))" :portability :common} - {:suite "io / print family (overlay)" :label "print nil arg" :expected "\"nil\"" :actual "(with-out-str (print nil))" :portability :common} - {:suite "io / print family (overlay)" :label "prn keyword" :expected "\":k\\n\"" :actual "(with-out-str (prn :k))" :portability :common} - {:suite "io / print-method multimethod" :label "records print canonically" :expected "\"#user.Pt{:x 1, :y 2}\"" :actual "(do (defrecord Pt [x y]) (pr-str (->Pt 1 2)))" :portability :common} - {:suite "io / print-method multimethod" :label "records nested in colls" :expected "\"[#user.Pt{:x 1, :y 2}]\"" :actual "(do (defrecord Pt [x y]) (pr-str [(->Pt 1 2)]))" :portability :common} - {:suite "io / print-method multimethod" :label "defmethod overrides a record, top level" :expected "\"#user.Pt{:x 3, :y 4}\"" :actual "(do (defrecord Pt [x y]) (defmethod print-method (quote user.Pt) [r w] (.write w (str \"<\" (:x r) \",\" (:y r) \">\"))) (pr-str (->Pt 3 4)))" :portability :jvm} - {:suite "io / print-method multimethod" :label "defmethod fires nested in a map" :expected "\"{:p #user.Pt{:x 5, :y 6}}\"" :actual "(do (defrecord Pt [x y]) (defmethod print-method (quote user.Pt) [r w] (.write w (str \"<\" (:x r) \",\" (:y r) \">\"))) (pr-str {:p (->Pt 5 6)}))" :portability :jvm} - {:suite "io / print-method multimethod" :label "defmethod fires through prn" :expected "\"[#user.Pt{:x 1, :y 2}]\\n\"" :actual "(do (defrecord Pt [x y]) (defmethod print-method (quote user.Pt) [r w] (.write w (str \"<\" (:x r) \",\" (:y r) \">\"))) (with-out-str (prn [(->Pt 1 2)])))" :portability :jvm} - {:suite "io / print-method multimethod" :label "direct call uses :default" :expected "\"42\"" :actual "(let [w (StringWriter.)] (print-method 42 w) (.toString w))" :portability :jvm} - {:suite "io / print-method multimethod" :label "direct builtin override" :expected "\"#42#\"" :actual "(do (defmethod print-method :number [n w] (.write w (str \"#\" n \"#\"))) (let [w (StringWriter.)] (print-method 42 w) (.toString w)))" :portability :jvm} - {:suite "io / print-method multimethod" :label "print-dup routes to print-method" :expected "\"[1 2]\"" :actual "(let [w (StringWriter.)] (print-dup [1 2] w) (.toString w))" :portability :jvm} - {:suite "io / print-method multimethod" :label "StringWriter accumulates" :expected "\"ab\"" :actual "(let [w (StringWriter.)] (.write w \"a\") (.append w \\b) (.toString w))" :portability :jvm} - {:suite "io / print-method multimethod" :label "methods table inspectable" :expected "true" :actual "(do (defrecord Pt [x y]) (defmethod print-method (quote user.Pt) [r w] r) (contains? (methods print-method) (quote user.Pt)))" :portability :common} - {:suite "io / cold tagged types via print-method" :label "uuid" :expected "\"#uuid \\\"b6883c0a-0342-4007-9966-bc2dfa6b109e\\\"\"" :actual "(pr-str (parse-uuid \"b6883c0a-0342-4007-9966-bc2dfa6b109e\"))" :portability :common} - {:suite "io / cold tagged types via print-method" :label "uuid nested" :expected "\"[#uuid \\\"b6883c0a-0342-4007-9966-bc2dfa6b109e\\\"]\"" :actual "(pr-str [(parse-uuid \"b6883c0a-0342-4007-9966-bc2dfa6b109e\")])" :portability :common} - {:suite "io / cold tagged types via print-method" :label "regex" :expected "\"#\\\"a+b\\\"\"" :actual "(pr-str #\"a+b\")" :portability :common} - {:suite "io / cold tagged types via print-method" :label "transient vector" :expected "\"#object[clojure.lang.PersistentVector$TransientVector 0xa4ac20b \\\"clojure.lang.PersistentVector$TransientVector@a4ac20b\\\"]\"" :actual "(pr-str (transient [1]))" :portability :common} - {:suite "io / cold tagged types via print-method" :label "transient map" :expected "\"#object[clojure.lang.PersistentArrayMap$TransientArrayMap 0x79939c8 \\\"clojure.lang.PersistentArrayMap$TransientArrayMap@79939c8\\\"]\"" :actual "(pr-str (transient {:a 1}))" :portability :common} - {:suite "io / cold tagged types via print-method" :label "atom override fires nested" :expected "\"{:a #object[clojure.lang.Atom 0x2bb39d6c {:status :ready, :val 7}]}\"" :actual "(do (defmethod print-method :jolt/atom [a w] (.write w (str \"#atom[\" (deref a) \"]\"))) (pr-str {:a (atom 7)}))" :portability :jvm} - {:suite "io / cold tagged types via print-method" :label "uuid through str unchanged" :expected "\"b6883c0a-0342-4007-9966-bc2dfa6b109e\"" :actual "(str (parse-uuid \"b6883c0a-0342-4007-9966-bc2dfa6b109e\"))" :portability :common} - {:suite "ISeq call forms" :label "eval a cons'd call" :expected "3" :actual "(eval (cons (quote +) (quote (1 2))))" :portability :common} - {:suite "ISeq call forms" :label "eval a list-built call" :expected "6" :actual "(eval (list (quote +) 1 2 3))" :portability :common} - {:suite "ISeq call forms" :label "eval a concat'd call" :expected "10" :actual "(eval (concat (list (quote +)) (list 1 2 3 4)))" :portability :common} - {:suite "ISeq call forms" :label "nested cons'd subform" :expected "7" :actual "(eval (list (quote +) 3 (cons (quote +) (quote (1 3)))))" :portability :common} - {:suite "ISeq call forms" :label "empty list self-evals" :expected "[]" :actual "(eval (list))" :portability :common} - {:suite "ISeq call forms" :label "macro output via cons" :expected "3" :actual "(do (defmacro mc [] (cons (quote +) (quote (1 2)))) (mc))" :portability :common} - {:suite "ISeq call forms" :label "macro output via concat" :expected "6" :actual "(do (defmacro mk [] (concat (list (quote +)) (list 1 2 3))) (mk))" :portability :common} - {:suite "ISeq call forms" :label "vector value self-evals" :expected "[1 2 3]" :actual "(eval (vec [1 2 3]))" :portability :common} - {:suite "ISeq call forms" :label "quoted list of data" :expected "[1 2 3]" :actual "(quote (1 2 3))" :portability :common} - {:suite "lazy / construction & laziness" :label "lazy-seq value" :expected "[1 2 3]" :actual "(take 3 (lazy-seq (cons 1 (lazy-seq (cons 2 (lazy-seq (cons 3 nil)))))))" :portability :common} - {:suite "lazy / construction & laziness" :label "not eagerly evaluated" :expected "0" :actual "(let [c (atom 0)] (lazy-seq (swap! c inc) nil) @c)" :portability :common} - {:suite "lazy / construction & laziness" :label "realized on demand" :expected "1" :actual "(let [c (atom 0) s (lazy-seq (swap! c inc) [1])] (first s) @c)" :portability :common} - {:suite "lazy / construction & laziness" :label "lazy-cat" :expected "[0 1 2 3]" :actual "(lazy-cat [0 1] [2 3])" :portability :common} - {:suite "lazy / seq fns are lazy (no side effect at construction)" :label "map" :expected "0" :actual "(let [a (atom 0)] (map (fn [x] (swap! a inc) x) (range 5)) @a)" :portability :common} - {:suite "lazy / seq fns are lazy (no side effect at construction)" :label "filter" :expected "0" :actual "(let [a (atom 0)] (filter (fn [x] (swap! a inc) true) (range 5)) @a)" :portability :common} - {:suite "lazy / seq fns are lazy (no side effect at construction)" :label "remove" :expected "0" :actual "(let [a (atom 0)] (remove (fn [x] (swap! a inc) false) (range 5)) @a)" :portability :common} - {:suite "lazy / seq fns are lazy (no side effect at construction)" :label "take over a lazy source" :expected "0" :actual "(let [a (atom 0)] (take 3 (map (fn [x] (swap! a inc) x) (range 100))) @a)" :portability :common} - {:suite "lazy / seq fns are lazy (no side effect at construction)" :label "drop over a lazy source" :expected "0" :actual "(let [a (atom 0)] (drop 2 (map (fn [x] (swap! a inc) x) (range 100))) @a)" :portability :common} - {:suite "lazy / seq fns are lazy (no side effect at construction)" :label "concat over lazy sources" :expected "0" :actual "(let [a (atom 0)] (concat (map (fn [x] (swap! a inc) x) [1 2]) (map (fn [x] (swap! a inc) x) [3 4])) @a)" :portability :common} - {:suite "lazy / seq fns are lazy (no side effect at construction)" :label "take-while" :expected "0" :actual "(let [a (atom 0)] (take-while (fn [x] (swap! a inc) true) (range 5)) @a)" :portability :common} - {:suite "lazy / seq fns are lazy (no side effect at construction)" :label "partition over a lazy source" :expected "0" :actual "(let [a (atom 0)] (partition 2 (map (fn [x] (swap! a inc) x) (range 6))) @a)" :portability :common} - {:suite "lazy / result type is LazySeq" :label "map/filter/take/concat/mapcat are LazySeq" :expected "[true true true true true]" :actual "(mapv #(instance? clojure.lang.LazySeq %) [(map inc [1]) (filter odd? [1]) (take 1 [1]) (concat [1]) (mapcat list [1])])" :portability :jvm} - {:suite "lazy / construction & laziness" :label "doall forces" :expected "[2 3 4]" :actual "(doall (map inc [1 2 3]))" :portability :common} - {:suite "lazy / construction & laziness" :label "dorun returns nil" :expected "nil" :actual "(dorun (map inc [1 2 3]))" :portability :common} - {:suite "lazy / infinite" :label "take from repeat" :expected "[7 7 7]" :actual "(take 3 (repeat 7))" :portability :common} - {:suite "lazy / infinite" :label "take from iterate" :expected "[1 2 4 8]" :actual "(take 4 (iterate (fn [x] (* 2 x)) 1))" :portability :common} - {:suite "lazy / infinite" :label "take from cycle" :expected "[1 2 1 2]" :actual "(take 4 (cycle [1 2]))" :portability :common} - {:suite "lazy / infinite" :label "take from range" :expected "[0 1 2]" :actual "(take 3 (range))" :portability :common} - {:suite "lazy / infinite" :label "drop then take" :expected "[5 6 7]" :actual "(take 3 (drop 5 (range)))" :portability :common} - {:suite "lazy / infinite" :label "filter infinite" :expected "[0 2 4]" :actual "(take 3 (filter even? (range)))" :portability :common} - {:suite "lazy / infinite" :label "map infinite" :expected "[0 1 4]" :actual "(take 3 (map (fn [x] (* x x)) (range)))" :portability :common} - {:suite "lazy / infinite" :label "nth of infinite" :expected "100" :actual "(nth (range) 100)" :portability :common} - {:suite "lazy / self-referential" :label "self-ref ones" :expected "[1 1 1 1 1]" :actual "(do (def ones (lazy-seq (cons 1 ones))) (take 5 ones))" :portability :common} - {:suite "lazy / self-referential" :label "self-ref nats" :expected "[0 1 2 3 4]" :actual "(do (def nats (lazy-cat [0] (map inc nats))) (take 5 nats))" :portability :common} - {:suite "lazy / self-referential" :label "self-ref fib" :expected "[0 1 1 2 3 5 8 13 21 34]" :actual "(do (def fib (lazy-cat [0 1] (map + (rest fib) fib))) (take 10 fib))" :portability :common} - {:suite "lazy / realized?" :label "unrealized" :expected "false" :actual "(realized? (lazy-seq (cons 1 nil)))" :portability :common} - {:suite "lazy / realized?" :label "realized after" :expected "true" :actual "(let [s (lazy-seq (cons 1 nil))] (first s) (realized? s))" :portability :common} - {:suite "lazy / realized?" :label "body runs once" :expected "1" :actual "(let [c (atom 0) s (lazy-seq (do (swap! c inc) [1 2 3]))] (seq s) (seq s) @c)" :portability :common} - {:suite "lazy-seq / realization is shared across walks" :label "effects run once across three walks" :expected "3" :actual "(let [a (atom 0) s (map (fn [x] (swap! a inc) x) [1 2 3])] (doall s) (dorun s) (vec s) (deref a))" :portability :common} - {:suite "lazy-seq / realization is shared across walks" :label "values stable across walks" :expected "true" :actual "(let [s (map inc [1 2 3])] (= (vec s) (vec s) [2 3 4]))" :portability :common} - {:suite "lazy-seq / realization is shared across walks" :label "filter effects once" :expected "4" :actual "(let [a (atom 0) s (filter (fn [x] (swap! a inc) (odd? x)) [1 2 3 4])] (dorun s) (count s) (deref a))" :portability :common} - {:suite "lazy / realization order & count" :label "map realizes left-to-right" :expected "[1 2 3]" :actual "(let [log (atom [])] (dorun (map (fn [x] (swap! log conj x) x) (list 1 2 3))) @log)" :portability :common} - {:suite "lazy / realization order & count" :label "filter realizes left-to-right" :expected "[1 2 3]" :actual "(let [log (atom [])] (dorun (filter (fn [x] (swap! log conj x) true) (list 1 2 3))) @log)" :portability :common} - {:suite "lazy / realization order & count" :label "take realizes exactly n, no over-realization" :expected "3" :actual "(let [a (atom 0)] (dorun (take 3 (map (fn [x] (swap! a inc) x) (iterate inc 0)))) @a)" :portability :common} - {:suite "lazy / realization order & count" :label "nth realizes exactly index+1" :expected "3" :actual "(let [a (atom 0)] (nth (map (fn [x] (swap! a inc) x) (iterate inc 0)) 2) @a)" :portability :common} - {:suite "lazy / realization order & count" :label "drop+first realizes through the index" :expected "3" :actual "(let [a (atom 0)] (first (drop 2 (map (fn [x] (swap! a inc) x) (iterate inc 0)))) @a)" :portability :common} - {:suite "lazy / realization is memoized" :label "first twice realizes once" :expected "1" :actual "(let [a (atom 0) s (map (fn [x] (swap! a inc) x) (iterate inc 0))] (first s) (first s) @a)" :portability :common} - {:suite "lazy / realization is memoized" :label "wider take extends, does not re-realize" :expected "4" :actual "(let [a (atom 0) s (map (fn [x] (swap! a inc) x) (iterate inc 0))] (doall (take 2 s)) (doall (take 4 s)) @a)" :portability :common} - {:suite "lazy / family is lazy at construction (no side effect)" :label "keep" :expected "0" :actual "(let [a (atom 0)] (keep (fn [x] (swap! a inc) x) (range 5)) @a)" :portability :common} - {:suite "lazy / family is lazy at construction (no side effect)" :label "keep-indexed" :expected "0" :actual "(let [a (atom 0)] (keep-indexed (fn [i x] (swap! a inc) x) (range 5)) @a)" :portability :common} - {:suite "lazy / family is lazy at construction (no side effect)" :label "map-indexed" :expected "0" :actual "(let [a (atom 0)] (map-indexed (fn [i x] (swap! a inc) x) (range 5)) @a)" :portability :common} - {:suite "lazy / family is lazy at construction (no side effect)" :label "distinct" :expected "0" :actual "(let [a (atom 0)] (distinct (map (fn [x] (swap! a inc) x) (range 5))) @a)" :portability :common} - {:suite "lazy / family is lazy at construction (no side effect)" :label "partition-by" :expected "0" :actual "(let [a (atom 0)] (partition-by (fn [x] (swap! a inc) x) (range 5)) @a)" :portability :common} - {:suite "lazy / family is lazy at construction (no side effect)" :label "partition-all" :expected "0" :actual "(let [a (atom 0)] (partition-all 2 (map (fn [x] (swap! a inc) x) (range 5))) @a)" :portability :common} - {:suite "lazy / family is lazy at construction (no side effect)" :label "interpose" :expected "0" :actual "(let [a (atom 0)] (interpose 0 (map (fn [x] (swap! a inc) x) (range 5))) @a)" :portability :common} - {:suite "lazy / family is lazy at construction (no side effect)" :label "interleave" :expected "0" :actual "(let [a (atom 0)] (interleave (map (fn [x] (swap! a inc) x) (range 5)) (range 5)) @a)" :portability :common} - {:suite "lazy / family is lazy at construction (no side effect)" :label "take-nth" :expected "0" :actual "(let [a (atom 0)] (take-nth 2 (map (fn [x] (swap! a inc) x) (range 5))) @a)" :portability :common} - {:suite "lazy / family is lazy at construction (no side effect)" :label "reductions" :expected "0" :actual "(let [a (atom 0)] (reductions + (map (fn [x] (swap! a inc) x) (range 5))) @a)" :portability :common} - {:suite "lazy / family is lazy at construction (no side effect)" :label "tree-seq" :expected "0" :actual "(let [a (atom 0)] (tree-seq (fn [x] (swap! a inc) false) identity [1 [2]]) @a)" :portability :common} - {:suite "lazy / family is lazy at construction (no side effect)" :label "replace over a seq" :expected "0" :actual "(let [a (atom 0)] (replace {} (map (fn [x] (swap! a inc) x) (range 5))) @a)" :portability :common} - {:suite "lazy / realization timing" :label "sequence realizes the first element" :expected "1" :actual "(let [a (atom 0)] (sequence (map (fn [x] (swap! a inc) x)) (range 5)) @a)" :portability :common} - {:suite "lazy / realization timing" :label "next realizes head + one lookahead" :expected "2" :actual "(let [a (atom 0) s (map (fn [x] (swap! a inc) x) (iterate inc 0))] (next s) @a)" :portability :common} - {:suite "lazy / realization timing" :label "rest realizes only the head" :expected "1" :actual "(let [a (atom 0) s (map (fn [x] (swap! a inc) x) (iterate inc 0))] (rest s) @a)" :portability :common} - {:suite "list / construct & predicate" :label "list" :expected "[1 2 3]" :actual "(list 1 2 3)" :portability :common} - {:suite "list / construct & predicate" :label "empty list" :expected "[]" :actual "(list)" :portability :common} - {:suite "list / construct & predicate" :label "quoted list" :expected "[1 2 3]" :actual "(quote (1 2 3))" :portability :common} - {:suite "list / construct & predicate" :label "list? true" :expected "true" :actual "(list? (list 1 2))" :portability :common} - {:suite "list / construct & predicate" :label "list? on conj result" :expected "true" :actual "(list? (conj (list 1) 0))" :portability :common} - {:suite "list / construct & predicate" :label "count" :expected "3" :actual "(count (list 1 2 3))" :portability :common} - {:suite "list / construct & predicate" :label "empty? true" :expected "true" :actual "(empty? (list))" :portability :common} - {:suite "list / construct & predicate" :label "list = vector elts" :expected "true" :actual "(= (list 1 2 3) [1 2 3])" :portability :common} - {:suite "list / access & update" :label "first" :expected "1" :actual "(first (list 1 2 3))" :portability :common} - {:suite "list / access & update" :label "rest" :expected "[2 3]" :actual "(rest (list 1 2 3))" :portability :common} - {:suite "list / access & update" :label "peek is first" :expected "1" :actual "(peek (list 1 2 3))" :portability :common} - {:suite "list / access & update" :label "pop drops first" :expected "[2 3]" :actual "(pop (list 1 2 3))" :portability :common} - {:suite "list / access & update" :label "conj prepends" :expected "[0 1 2]" :actual "(conj (list 1 2) 0)" :portability :common} - {:suite "list / access & update" :label "conj many prepends" :expected "[4 3 1 2]" :actual "(conj (list 1 2) 3 4)" :portability :common} - {:suite "list / access & update" :label "cons prepends" :expected "[0 1 2]" :actual "(cons 0 (list 1 2))" :portability :common} - {:suite "list / access & update" :label "nth" :expected "20" :actual "(nth (list 10 20 30) 1)" :portability :common} - {:suite "list / immutability & performance" :label "conj does not mutate" :expected "true" :actual "(let [l (list 1 2 3) m (conj l 0)] (and (= l [1 2 3]) (= m [0 1 2 3])))" :portability :common} - {:suite "list / immutability & performance" :label "reduce conj builds" :expected "[2 1 0]" :actual "(reduce conj (list) (range 3))" :portability :common} - {:suite "list / immutability & performance" :label "O(1) conj at scale" :expected "200000" :actual "(count (reduce conj (list) (range 200000)))" :portability :common} - {:suite "list / immutability & performance" :label "scale head correct" :expected "199999" :actual "(first (reduce conj (list) (range 200000)))" :portability :common} - {:suite "macros / quoting" :label "quote symbol" :expected "(quote a)" :actual "(quote a)" :portability :common} - {:suite "macros / quoting" :label "quote list" :expected "[1 2 3]" :actual "(quote (1 2 3))" :portability :common} - {:suite "macros / quoting" :label "quote nested" :expected "[1 [2 3]]" :actual "(quote (1 (2 3)))" :portability :common} - {:suite "macros / quoting" :label "quote sugar" :expected "'a" :actual "'a" :portability :common} - {:suite "macros / quoting" :label "syntax-quote literal" :expected "[1 2]" :actual "`[1 2]" :portability :common} - {:suite "macros / quoting" :label "unquote" :expected "[1 2 3]" :actual "(let [x 2] `[1 ~x 3])" :portability :common} - {:suite "macros / quoting" :label "unquote-splicing" :expected "[1 2 3 4]" :actual "(let [xs [2 3]] `[1 ~@xs 4])" :portability :common} - {:suite "macros / quoting" :label "unquote in list" :expected "[3]" :actual "(let [x 3] `(~x))" :portability :common} - {:suite "macros / quoting" :label "syntax-quote symbol qualifies" :expected "true" :actual "(symbol? `foo)" :portability :common} - {:suite "macros / defmacro" :label "simple macro" :expected "3" :actual "(do (defmacro m [a b] `(+ ~a ~b)) (m 1 2))" :portability :common} - {:suite "macros / defmacro" :label "macro unless" :expected "1" :actual "(do (defmacro unless [c body] `(if ~c nil ~body)) (unless false 1))" :portability :common} - {:suite "macros / defmacro" :label "macro with body splice" :expected "6" :actual "(do (defmacro msum [& xs] `(+ ~@xs)) (msum 1 2 3))" :portability :common} - {:suite "macros / defmacro" :label "macroexpand-1" :expected "false" :actual "(do (defmacro m [x] `(inc ~x)) (list? (macroexpand-1 '(m 5))))" :portability :common} - {:suite "macros / defmacro" :label "gensym unique" :expected "false" :actual "(= (gensym) (gensym))" :portability :common} - {:suite "macros / defmacro" :label "gensym# in template" :expected "true" :actual "(do (defmacro m [] `(let [x# 1] x#)) (= 1 (m)))" :portability :common} - {:suite "macros / defmacro" :label "#() inside syntax-quote" :expected "[2 4 6]" :actual "(do (defmacro m [] `(mapv #(* % 2) [1 2 3])) (m))" :portability :common} - {:suite "macros / defmacro" :label "#() + auto-gensym share in template" :expected "\"ab\"" :actual "(do (defmacro m [] `(let [sb# (StringBuilder.)] (mapv #(.append sb# %) [\"a\" \"b\"]) (.toString sb#))) (m))" :portability :jvm} - {:suite "macros / core-overlay" :label "if-not true branch" :expected ":then" :actual "(if-not false :then :else)" :portability :common} - {:suite "macros / core-overlay" :label "if-not else branch" :expected ":else" :actual "(if-not true :then :else)" :portability :common} - {:suite "macros / core-overlay" :label "if-not no else" :expected "nil" :actual "(if-not true :then)" :portability :common} - {:suite "macros / core-overlay" :label "if-not no else hit" :expected ":then" :actual "(if-not false :then)" :portability :common} - {:suite "macros / core-overlay" :label "comment -> nil" :expected "nil" :actual "(comment a b c)" :portability :common} - {:suite "macros / core-overlay" :label "comment in do" :expected "42" :actual "(do (comment ignored) 42)" :portability :common} - {:suite "macros / core-overlay" :label "if-let then" :expected "6" :actual "(if-let [x 5] (inc x) :none)" :portability :common} - {:suite "macros / core-overlay" :label "if-let else" :expected ":none" :actual "(if-let [x nil] (inc x) :none)" :portability :common} - {:suite "macros / core-overlay" :label "if-let else scope" :expected "9" :actual "(let [x 9] (if-let [x nil] :t x))" :portability :common} - {:suite "macros / core-overlay" :label "if-some zero" :expected "1" :actual "(if-some [x 0] (inc x) :none)" :portability :common} - {:suite "macros / core-overlay" :label "if-some nil" :expected ":none" :actual "(if-some [x nil] x :none)" :portability :common} - {:suite "macros / core-overlay" :label "when-some multi" :expected "14" :actual "(when-some [x 7] (inc x) (* x 2))" :portability :common} - {:suite "macros / core-overlay" :label "when-some nil" :expected "nil" :actual "(when-some [x nil] x)" :portability :common} - {:suite "macros / core-overlay" :label "while loop" :expected "3" :actual "(let [a (atom 0)] (while (< @a 3) (swap! a inc)) @a)" :portability :common} - {:suite "macros / core-overlay" :label "dotimes sum" :expected "10" :actual "(let [a (atom 0)] (dotimes [i 5] (swap! a + i)) @a)" :portability :common} - {:suite "macros / core-overlay" :label "as-> threads" :expected "12" :actual "(as-> 5 x (+ x 1) (* x 2))" :portability :common} - {:suite "macros / core-overlay" :label "as-> no forms" :expected "5" :actual "(as-> 5 x)" :portability :common} - {:suite "macros / core-overlay" :label "some-> through" :expected "6" :actual "(some-> {:a {:b 5}} :a :b inc)" :portability :common} - {:suite "macros / core-overlay" :label "some-> short-circuit" :expected "nil" :actual "(some-> {:a nil} :a :b)" :portability :common} - {:suite "macros / core-overlay" :label "some->> through" :expected "9" :actual "(some->> [1 2 3] (map inc) (reduce +))" :portability :common} - {:suite "macros / core-overlay" :label "some->> nil" :expected "nil" :actual "(some->> nil (map inc))" :portability :common} - {:suite "macros / core-overlay" :label "doto returns obj" :expected "[1 2]" :actual "(deref (doto (atom []) (swap! conj 1) (swap! conj 2)))" :portability :common} - {:suite "macros / core-overlay" :label "when-first" :expected "20" :actual "(when-first [x [10 20 30]] (* x 2))" :portability :common} - {:suite "macros / core-overlay" :label "when-first empty" :expected "nil" :actual "(when-first [x []] :body)" :portability :common} - {:suite "macros / core-overlay" :label "when-first nil coll" :expected "nil" :actual "(when-first [x nil] :body)" :portability :common} - {:suite "macros / core-overlay" :label "when-first range" :expected "0" :actual "(when-first [x (range 5)] x)" :portability :common} - {:suite "macros / core-overlay" :label "cond->> threads" :expected "12" :actual "(cond->> 5 true (+ 1) false (* 100) true (* 2))" :portability :common} - {:suite "macros / core-overlay" :label "cond->> skip" :expected "10" :actual "(cond->> 10 false (+ 1))" :portability :common} - {:suite "macros / core-overlay" :label "assert pass" :expected ":ok" :actual "(do (assert (= 1 1)) :ok)" :portability :common} - {:suite "macros / core-overlay" :label "assert throws" :expected ":threw" :actual "(try (assert (= 1 2)) (catch :default e :threw))" :portability :common} - {:suite "macros / core-overlay" :label "assert message" :expected "\"Assert failed: nope\\nfalse\"" :actual "(try (assert false \"nope\") (catch AssertionError e (ex-message e)))" :portability :common} - {:suite "macros / core-overlay" :label "delay value" :expected "42" :actual "(deref (delay 42))" :portability :common} - {:suite "macros / core-overlay" :label "delay forces once" :expected "1" :actual "(let [c (atom 0) d (delay (swap! c inc))] @d @d @c)" :portability :common} - {:suite "macros / core-overlay" :label "future deref" :expected "9" :actual "(deref (future (* 3 3)))" :portability :common} - {:suite "macros / core-overlay" :label "letfn simple" :expected "25" :actual "(letfn [(sq [x] (* x x))] (sq 5))" :portability :common} - {:suite "macros / core-overlay" :label "letfn mutual" :expected "true" :actual "(letfn [(ev? [n] (if (zero? n) true (od? (dec n)))) (od? [n] (if (zero? n) false (ev? (dec n))))] (ev? 8))" :portability :common} - {:suite "macros / core-overlay" :label "condp match" :expected ":two" :actual "(condp = 2 1 :one 2 :two 3 :three)" :portability :common} - {:suite "macros / core-overlay" :label "condp default" :expected ":else" :actual "(condp = 9 1 :one 2 :two :else)" :portability :common} - {:suite "macros / core-overlay" :label "condp :>> form" :expected "\"got 2\"" :actual "(condp some [1 2 3] #{0 9} :>> (fn [x] (str \"got \" x)) #{2 6} :>> (fn [x] (str \"got \" x)))" :portability :common} - {:suite "macros / core-overlay" :label "condp no match" :expected ":threw" :actual "(try (condp = 9 1 :one) (catch :default e :threw))" :portability :common} - {:suite "macros / core-overlay" :label "binding rebinds" :expected "99" :actual "(do (def ^:dynamic *bx* 10) (binding [*bx* 99] *bx*))" :portability :common} - {:suite "macros / core-overlay" :label "binding restores" :expected "10" :actual "(do (def ^:dynamic *by* 10) (binding [*by* 99] *by*) *by*)" :portability :common} - {:suite "macros / core-overlay" :label "binding seen by fn" :expected "7" :actual "(do (def ^:dynamic *bz* 0) (defn rdz [] *bz*) (binding [*bz* 7] (rdz)))" :portability :common} - {:suite "macros / time, with-redefs, macroexpand" :label "time returns value" :expected "3" :actual "(time (+ 1 2))" :portability :common} - {:suite "macros / time, with-redefs, macroexpand" :label "with-redefs rebinds" :expected "42" :actual "(do (defn wr-f [] 1) (with-redefs [wr-f (fn [] 42)] (wr-f)))" :portability :common} - {:suite "macros / time, with-redefs, macroexpand" :label "with-redefs restores" :expected "1" :actual "(do (defn wr-g [] 1) (with-redefs [wr-g (fn [] 42)]) (wr-g))" :portability :common} - {:suite "macros / time, with-redefs, macroexpand" :label "with-redefs restores on throw" :expected "1" :actual "(do (defn wr-h [] 1) (try (with-redefs [wr-h (fn [] 42)] (throw (ex-info \"x\" {}))) (catch :default e nil)) (wr-h))" :portability :common} - {:suite "macros / time, with-redefs, macroexpand" :label "with-redefs-fn" :expected "42" :actual "(do (defn wr-i [] 1) (with-redefs-fn {(var wr-i) (fn [] 42)} (fn [] (wr-i))))" :portability :common} - {:suite "macros / time, with-redefs, macroexpand" :label "macroexpand full" :expected "true" :actual "(let [e (macroexpand (quote (when-not false 1)))] (= (quote if) (first e)))" :portability :common} - {:suite "macros / time, with-redefs, macroexpand" :label "macroexpand non-macro" :expected "[1 2]" :actual "(macroexpand (quote [1 2]))" :portability :common} - {:suite "macros / defmacro arity-clause & name metadata" :label "arity-clause form" :expected "10" :actual "(do (defmacro tw ([x] (list (quote *) x 2))) (tw 5))" :portability :common} - {:suite "macros / defmacro arity-clause & name metadata" :label "docstring + arity" :expected "15" :actual "(do (defmacro th \"triple\" ([x] (list (quote *) x 3))) (th 5))" :portability :common} - {:suite "macros / defmacro arity-clause & name metadata" :label "^{:map} name meta" :expected "7" :actual "(do (defmacro ^{:private true} pm [] 7) (pm))" :portability :common} - {:suite "macros / defmacro arity-clause & name metadata" :label "multi-form body" :expected "6" :actual "(do (defmacro mb ([a b] (list (quote +) a b))) (mb 2 4))" :portability :common} - {:suite "macros / defmacro multi-arity & attr-map" :label "multi-arity 1" :expected "6" :actual "(do (defmacro ma ([a] (list (quote +) a 1)) ([a b] (list (quote +) a b))) (ma 5))" :portability :common} - {:suite "macros / defmacro multi-arity & attr-map" :label "multi-arity 2" :expected "5" :actual "(do (defmacro ma ([a] (list (quote +) a 1)) ([a b] (list (quote +) a b))) (ma 2 3))" :portability :common} - {:suite "macros / defmacro multi-arity & attr-map" :label "arity delegates" :expected "[:d nil 9]" :actual "(do (defmacro lg ([m] `(lg :d nil ~m)) ([l t m] (list (quote vector) l t m))) (lg 9))" :portability :common} - {:suite "macros / defmacro multi-arity & attr-map" :label "doc + attr-map + params" :expected "10" :actual "(do (defmacro am \"doc\" {:arglists (quote ([x]))} [x] (list (quote inc) x)) (am 9))" :portability :common} - {:suite "macros / defmacro multi-arity & attr-map" :label "doc + attr-map + variadic" :expected "6" :actual "(do (defmacro vg \"d\" {:arglists (quote ([& a]))} [& xs] `(+ ~@xs)) (vg 1 2 3))" :portability :common} - {:suite "maps / keyword invoke" :label "hit" :expected "1" :actual "(:a {:a 1 :b 2})" :portability :common} - {:suite "maps / keyword invoke" :label "miss" :expected "nil" :actual "(:z {:a 1})" :portability :common} - {:suite "maps / keyword invoke" :label "miss with default" :expected ":d" :actual "(:z {:a 1} :d)" :portability :common} - {:suite "maps / keyword invoke" :label "hit with default" :expected "1" :actual "(:a {:a 1} :d)" :portability :common} - {:suite "maps / keyword invoke" :label "on nil" :expected "nil" :actual "(:a nil)" :portability :common} - {:suite "maps / keyword invoke" :label "on nil with default" :expected ":d" :actual "(:a nil :d)" :portability :common} - {:suite "maps / keyword invoke" :label "nil value is present" :expected "nil" :actual "(:a {:a nil} :d)" :portability :common} - {:suite "maps / keyword invoke" :label "false value is present" :expected "false" :actual "(:a {:a false} :d)" :portability :common} - {:suite "maps / keyword invoke" :label "on a vector" :expected "nil" :actual "(:a [1 2 3])" :portability :common} - {:suite "maps / keyword invoke" :label "on a number" :expected "nil" :actual "(:a 42)" :portability :common} - {:suite "maps / keyword invoke" :label "on a sorted map" :expected "2" :actual "(:b (sorted-map :a 1 :b 2))" :portability :common} - {:suite "maps / keyword invoke" :label "on assoc result" :expected "3" :actual "(:c (assoc {:a 1} :c 3))" :portability :common} - {:suite "maps / keyword invoke" :label "on a record field" :expected "5" :actual "(do (defrecord KFP [x]) (:x (->KFP 5)))" :portability :common} - {:suite "maps / keyword invoke" :label "qualified keyword" :expected "1" :actual "(:n/a {:n/a 1})" :portability :common} - {:suite "maps / keyword invoke" :label "nested in expr" :expected "6" :actual "(+ (:a {:a 1}) (:b {:b 2}) (:c {:c 3}))" :portability :common} - {:suite "maps / keyword invoke" :label "evaluates map expr once" :expected "[2 1]" :actual "(do (def cnt (atom 0)) (let [v (:a (do (swap! cnt inc) {:a 2}))] [v @cnt]))" :portability :common} - {:suite "maps / literal construction" :label "basic" :expected "{:a 1, :b 2}" :actual "{:a 1 :b 2}" :portability :common} - {:suite "maps / literal construction" :label "empty" :expected "{}" :actual "{}" :portability :common} - {:suite "maps / literal construction" :label "computed values" :expected "{:a 3}" :actual "{:a (+ 1 2)}" :portability :common} - {:suite "maps / literal construction" :label "nil value kept" :expected "true" :actual "(contains? {:a nil} :a)" :portability :common} - {:suite "maps / literal construction" :label "nil value lookup" :expected "nil" :actual "(get {:a nil} :a :d)" :portability :common} - {:suite "maps / literal construction" :label "string key" :expected "1" :actual "(get {\"k\" 1} \"k\")" :portability :common} - {:suite "maps / literal construction" :label "number key" :expected ":one" :actual "(get {1 :one} 1)" :portability :common} - {:suite "maps / literal construction" :label "collection key" :expected ":v" :actual "(get {[1 2] :v} [1 2])" :portability :common} - {:suite "maps / literal construction" :label "collection value-equal key" :expected ":v" :actual "(get {[1 2] :v} (vector 1 2))" :portability :common} - {:suite "maps / literal construction" :label "computed key" :expected "1" :actual "(get {(keyword \"a\") 1} :a)" :portability :common} - {:suite "maps / literal construction" :label "values evaluate in source order" :expected "[1 2 3]" :actual "(do (def log (atom [])) {:a (swap! log conj 1) :b (swap! log conj 2) :c (swap! log conj 3)} (deref log))" :portability :common} - {:suite "maps / literal construction" :label "keys evaluate before their values, pairwise" :expected "[:k1 :v1 :k2 :v2]" :actual "(do (def log (atom [])) {(do (swap! log conj :k1) :a) (do (swap! log conj :v1) 1) (do (swap! log conj :k2) :b) (do (swap! log conj :v2) 2)} (deref log))" :portability :common} - {:suite "maps / literal construction" :label "source order with a nil value (phm form)" :expected "[1 2 3]" :actual "(do (def log (atom [])) {:a (do (swap! log conj 1) nil) :b (swap! log conj 2) :c (swap! log conj 3)} (deref log))" :portability :common} - {:suite "maps / literal construction" :label "source order through syntax-quote" :expected "[2 1]" :actual "(do (def log (atom [])) (defmacro m-p3c [] `{:a ~(list 'swap! 'log 'conj 1) :b ~(list 'swap! 'log 'conj 2)}) (m-p3c) (deref log))" :portability :common} - {:suite "maps / literal construction" :label "count" :expected "3" :actual "(count {:a 1 :b 2 :c 3})" :portability :common} - {:suite "maps / literal construction" :label "equality with phm" :expected "true" :actual "(= {:a 1 :b 2} (assoc {:a 1} :b 2))" :portability :common} - {:suite "maps / literal construction" :label "keys work after assoc" :expected "2" :actual "(:b (assoc {:a 1 :b 2} :c 3))" :portability :common} - {:suite "maps / literal construction" :label "literal in fn body" :expected "12" :actual "(do (defn mfp-mk [x] {:v (* x 2)}) (:v (mfp-mk 6)))" :portability :common} - {:suite "maps / insertion order" :label "small literal keys" :expected "[:c :a :b]" :actual "(vec (keys {:c 3 :a 1 :b 2}))" :portability :common} - {:suite "maps / insertion order" :label "small literal vals" :expected "[3 1 2]" :actual "(vec (vals {:c 3 :a 1 :b 2}))" :portability :common} - {:suite "maps / insertion order" :label "seq follows keys" :expected "[:c :a :b]" :actual "(mapv key (seq {:c 3 :a 1 :b 2}))" :portability :common} - {:suite "maps / insertion order" :label "array-map any size" :expected "[:z :y :x :w :v :u :t :s :r :q]" :actual "(vec (keys (array-map :z 1 :y 2 :x 3 :w 4 :v 5 :u 6 :t 7 :s 8 :r 9 :q 10)))" :portability :common} - {:suite "maps / insertion order" :label "assoc appends new key" :expected "[:c :a :z]" :actual "(vec (keys (assoc {:c 3 :a 1} :z 9)))" :portability :common} - {:suite "maps / insertion order" :label "assoc replace keeps position" :expected "[:c :a]" :actual "(vec (keys (assoc {:c 3 :a 1} :c 9)))" :portability :common} - {:suite "maps / insertion order" :label "dissoc preserves order" :expected "[:c :b]" :actual "(vec (keys (dissoc {:c 3 :a 1 :b 2} :a)))" :portability :common} - {:suite "maps / insertion order" :label "into onto empty (<=8)" :expected "[:c :a :b]" :actual "(vec (keys (into {} [[:c 3] [:a 1] [:b 2]])))" :portability :common} - {:suite "maps / insertion order" :label "reduce assoc" :expected "[:e :d :c :b :a]" :actual "(vec (keys (reduce (fn [m k] (assoc m k k)) {} [:e :d :c :b :a])))" :portability :common} - {:suite "maps / insertion order" :label "conj a map merges in order" :expected "[:a :b :c]" :actual "(vec (keys (conj {:a 1} {:b 2 :c 3})))" :portability :common} - {:suite "maps / insertion order" :label "merge keeps right-hand order" :expected "[:a :c :b]" :actual "(vec (keys (merge {:a 1} {:c 3 :b 2})))" :portability :common} - {:suite "maps / insertion order" :label "assoc stays ordered through 8 entries" :expected "true" :actual "(= (vec (keys (reduce (fn [m i] (assoc m (keyword (str \"k\" i)) i)) {} (range 8)))) (mapv (fn [i] (keyword (str \"k\" i))) (range 8)))" :portability :common} - {:suite "maps / insertion order" :label "assoc promotes to hash past 8 entries" :expected "9" :actual "(count (reduce (fn [m i] (assoc m (keyword (str \"k\" i)) i)) {} (range 9)))" :portability :common} - {:suite "maps / insertion order" :label "array-map keeps order past 8" :expected "[:k0 :k1 :k2 :k3 :k4 :k5 :k6 :k7 :k8 :k9 :k10 :k11]" :actual "(vec (keys (apply array-map (mapcat (fn [i] [(keyword (str \"k\" i)) i]) (range 12)))))" :portability :common} - {:suite "maps / insertion order" :label "update-keys preserves order" :expected "[:a :b :c]" :actual "(vec (keys (update-vals (array-map :a 1 :b 2 :c 3) inc)))" :portability :common} - {:suite "maps / insertion order" :label "zipmap from ordered keys/vals" :expected "[:c :a :b]" :actual "(vec (keys (zipmap (keys {:c 3 :a 1 :b 2}) (vals {:c 3 :a 1 :b 2}))))" :portability :common} - {:suite "maps / insertion order" :label "select-keys follows keyseq" :expected "[:c :a]" :actual "(vec (keys (select-keys {:a 1 :b 2 :c 3} [:c :a])))" :portability :common} - {:suite "maps / insertion order" :label "frequencies first-occurrence order" :expected "[:c :a :b]" :actual "(vec (keys (frequencies [:c :a :b :a])))" :portability :common} - {:suite "maps / insertion order" :label "group-by first-occurrence order" :expected "[:c :a :b]" :actual "(vec (keys (group-by identity [:c :a :b :a])))" :portability :common} - {:suite "clojure.math" :label "sqrt" :expected "true" :actual "(< 1.4142 (clojure.math/sqrt 2) 1.4143)" :portability :common} - {:suite "clojure.math" :label "pow" :expected "1024" :actual "(long (clojure.math/pow 2 10))" :portability :common} - {:suite "clojure.math" :label "tan of 0" :expected "0" :actual "(long (clojure.math/tan 0))" :portability :common} - {:suite "clojure.math" :label "round" :expected "3" :actual "(clojure.math/round 2.6)" :portability :common} - {:suite "clojure.math" :label "floor" :expected "2.0" :actual "(clojure.math/floor 2.9)" :portability :common} - {:suite "clojure.math" :label "signum" :expected "-1.0" :actual "(clojure.math/signum -7.2)" :portability :common} - {:suite "clojure.math" :label "to-radians" :expected "true" :actual "(< 3.14 (clojure.math/to-radians 180) 3.15)" :portability :common} - {:suite "clojure.math" :label "PI" :expected "true" :actual "(< 3.14 clojure.math/PI 3.15)" :portability :common} - {:suite "clojure.math" :label "require + alias" :expected "5" :actual "(do (require '[clojure.math :as m]) (long (m/hypot 3 4)))" :portability :common} - {:suite "clojure.math" :label "as a value" :expected "[1 2]" :actual "(mapv (comp long clojure.math/sqrt) [1 4])" :portability :common} - {:suite "calls / locals named like core macros" :label "local fn named repeat" :expected "[1 1]" :actual "(let [repeat (fn [x] [x x])] (repeat 1))" :portability :common} - {:suite "calls / locals named like core macros" :label "local fn named seq" :expected ":end" :actual "((fn seq [n] (if (pos? n) (seq (dec n)) :end)) 2)" :portability :common} - {:suite "calls / locals named like core macros" :label "local fn named loop2" :expected "[2 1]" :actual "(let [with (fn [a b] [b a])] (with 1 2))" :portability :common} - {:suite "calls / locals named like core macros" :label "overlay repeat self-call (regression)" :expected "[0 0 0]" :actual "(take 3 (repeat 0))" :portability :common} - {:suite "calls / locals named like core macros" :label "closure param called" :expected "42" :actual "((fn [f] (f 41)) inc)" :portability :common} - {:suite "calls / locals named like core macros" :label "param holding a keyword (IFn leftover)" :expected "1" :actual "((fn [f] (f {:a 1})) :a)" :portability :common} - {:suite "map / construct & predicate" :label "literal" :expected "{:a 1}" :actual "{:a 1}" :portability :common} - {:suite "map / construct & predicate" :label "hash-map" :expected "{:b 2, :a 1}" :actual "(hash-map :a 1 :b 2)" :portability :common} - {:suite "map / construct & predicate" :label "empty" :expected "{}" :actual "{}" :portability :common} - {:suite "map / construct & predicate" :label "map? true" :expected "true" :actual "(map? {:a 1})" :portability :common} - {:suite "map / construct & predicate" :label "map? false on vector" :expected "false" :actual "(map? [1 2])" :portability :common} - {:suite "map / construct & predicate" :label "count" :expected "2" :actual "(count {:a 1 :b 2})" :portability :common} - {:suite "map / construct & predicate" :label "empty? true" :expected "true" :actual "(empty? {})" :portability :common} - {:suite "map / construct & predicate" :label "equality order-indep" :expected "true" :actual "(= {:a 1 :b 2} {:b 2 :a 1})" :portability :common} - {:suite "map / access" :label "get" :expected "1" :actual "(get {:a 1} :a)" :portability :common} - {:suite "map / access" :label "get missing nil" :expected "nil" :actual "(get {:a 1} :z)" :portability :common} - {:suite "map / access" :label "get default" :expected ":x" :actual "(get {:a 1} :z :x)" :portability :common} - {:suite "map / access" :label "keyword as fn" :expected "1" :actual "(:a {:a 1})" :portability :common} - {:suite "map / access" :label "keyword fn default" :expected ":x" :actual "(:z {:a 1} :x)" :portability :common} - {:suite "map / access" :label "map as fn" :expected "1" :actual "({:a 1} :a)" :portability :common} - {:suite "map / access" :label "get-in" :expected "2" :actual "(get-in {:a {:b 2}} [:a :b])" :portability :common} - {:suite "map / access" :label "get-in missing" :expected "nil" :actual "(get-in {:a {}} [:a :b])" :portability :common} - {:suite "map / access" :label "contains? key" :expected "true" :actual "(contains? {:a 1} :a)" :portability :common} - {:suite "map / access" :label "contains? missing" :expected "false" :actual "(contains? {:a 1} :z)" :portability :common} - {:suite "map / access" :label "find returns entry" :expected "[:a 1]" :actual "(find {:a 1} :a)" :portability :common} - {:suite "map / access" :label "keys" :expected "true" :actual "(= #{:a :b} (set (keys {:a 1 :b 2})))" :portability :common} - {:suite "map / access" :label "vals" :expected "true" :actual "(= #{1 2} (set (vals {:a 1 :b 2})))" :portability :common} - {:suite "map / update" :label "assoc adds" :expected "{:a 1, :b 2}" :actual "(assoc {:a 1} :b 2)" :portability :common} - {:suite "map / update" :label "assoc overwrites" :expected "{:a 9}" :actual "(assoc {:a 1} :a 9)" :portability :common} - {:suite "map / update" :label "assoc many" :expected "{:a 1, :b 2}" :actual "(assoc {} :a 1 :b 2)" :portability :common} - {:suite "map / update" :label "dissoc" :expected "{:a 1}" :actual "(dissoc {:a 1 :b 2} :b)" :portability :common} - {:suite "map / update" :label "dissoc many" :expected "{:a 1}" :actual "(dissoc {:a 1 :b 2 :c 3} :b :c)" :portability :common} - {:suite "map / update" :label "merge" :expected "{:a 1, :b 2}" :actual "(merge {:a 1} {:b 2})" :portability :common} - {:suite "map / update" :label "merge overwrites" :expected "{:a 2}" :actual "(merge {:a 1} {:a 2})" :portability :common} - {:suite "map / update" :label "merge lattermost wins" :expected "{:a 3}" :actual "(merge {:a 1} {:a 2} {:a 3})" :portability :common} - {:suite "map / update" :label "merge no args -> nil" :expected "nil" :actual "(merge)" :portability :common} - {:suite "map / update" :label "merge all nil -> nil" :expected "nil" :actual "(merge nil nil)" :portability :common} - {:suite "map / update" :label "merge nil arg no-op" :expected "{:a 1}" :actual "(merge {:a 1} nil)" :portability :common} - {:suite "map / update" :label "merge nil then map" :expected "{:a 1}" :actual "(merge nil {:a 1})" :portability :common} - {:suite "map / update" :label "merge empty + nil" :expected "{}" :actual "(merge {} nil)" :portability :common} - {:suite "map / update" :label "merge map-entry (conj)" :expected "{:a 1}" :actual "(merge {} (first {:a 1}))" :portability :common} - {:suite "map / update" :label "merge [k v] vector" :expected "{:foo 1}" :actual "(merge {} [:foo 1])" :portability :common} - {:suite "map / update" :label "merge collection key" :expected "true" :actual "(= {[2 3] :foo} (merge {[2 3] :foo} nil {}))" :portability :common} - {:suite "map / update" :label "merge-with" :expected "{:a 3}" :actual "(merge-with + {:a 1} {:a 2})" :portability :common} - {:suite "map / update" :label "update" :expected "{:a 2}" :actual "(update {:a 1} :a inc)" :portability :common} - {:suite "map / update" :label "update missing w/ fnil" :expected "{:a 1}" :actual "(update {} :a (fnil inc 0))" :portability :common} - {:suite "map / update" :label "update-in" :expected "{:a {:b 2}}" :actual "(update-in {:a {:b 1}} [:a :b] inc)" :portability :common} - {:suite "map / update" :label "assoc-in" :expected "{:a {:b 1}}" :actual "(assoc-in {} [:a :b] 1)" :portability :common} - {:suite "map / update" :label "select-keys" :expected "{:a 1}" :actual "(select-keys {:a 1 :b 2} [:a])" :portability :common} - {:suite "map / update" :label "into onto map" :expected "{:a 1, :b 2}" :actual "(into {:a 1} [[:b 2]])" :portability :common} - {:suite "map / update" :label "zipmap" :expected "{:a 1, :b 2}" :actual "(zipmap [:a :b] [1 2])" :portability :common} - {:suite "map / iteration & entries" :label "map over entries" :expected "true" :actual "(= #{1 2} (set (map val {:a 1 :b 2})))" :portability :common} - {:suite "map / iteration & entries" :label "map keys" :expected "true" :actual "(= #{:a :b} (set (map key {:a 1 :b 2})))" :portability :common} - {:suite "map / iteration & entries" :label "reduce over entries" :expected "6" :actual "(reduce (fn [a e] (+ a (val e))) 0 {:a 1 :b 2 :c 3})" :portability :common} - {:suite "map / iteration & entries" :label "reduce-kv" :expected "6" :actual "(reduce-kv (fn [a k v] (+ a v)) 0 {:a 1 :b 2 :c 3})" :portability :common} - {:suite "map / iteration & entries" :label "destructure entry" :expected "true" :actual "(= [[:a 2]] (into [] (map (fn [[k v]] [k (inc v)]) {:a 1})))" :portability :common} - {:suite "map / iteration & entries" :label "first of map is entry" :expected "true" :actual "(let [e (first {:a 1})] (and (= (key e) :a) (= (val e) 1)))" :portability :common} - {:suite "map / iteration & entries" :label "map-entry?" :expected "true" :actual "(map-entry? (first {:a 1}))" :portability :common} - {:suite "map / iteration & entries" :label "count of nil map" :expected "0" :actual "(count nil)" :portability :common} - {:suite "map / iteration & entries" :label "get from nil" :expected "nil" :actual "(get nil :a)" :portability :common} - {:suite "map / iteration & entries" :label "immutability" :expected "true" :actual "(let [m {:a 1} n (assoc m :b 2)] (and (= m {:a 1}) (= n {:a 1 :b 2})))" :portability :common} - {:suite "map / collection keys (by value)" :label "vector key literal" :expected ":v" :actual "(get {[1 2] :v} [1 2])" :portability :common} - {:suite "map / collection keys (by value)" :label "map key literal" :expected ":v" :actual "(get {(hash-map :a 1) :v} {:a 1})" :portability :common} - {:suite "map / collection keys (by value)" :label "assoc vector key" :expected ":v" :actual "(get (assoc {} [1 2] :v) [1 2])" :portability :common} - {:suite "map / collection keys (by value)" :label "key across repr" :expected ":v" :actual "(get (assoc {} (vec [1 2]) :v) [1 2])" :portability :common} - {:suite "map / collection keys (by value)" :label "frequencies of maps" :expected "2" :actual "(get (frequencies [{:a 1} (hash-map :a 1)]) {:a 1})" :portability :common} - {:suite "map / collection keys (by value)" :label "group-by collection key" :expected "1" :actual "(count (group-by identity [{:a 1} (hash-map :a 1)]))" :portability :common} - {:suite "map / nil inside a collection key" :label "set key w/ nil distinct" :expected "2" :actual "(count {#{nil 1} :a, #{1} :b})" :portability :common} - {:suite "map / nil inside a collection key" :label "set key w/ nil neg lookup" :expected "nil" :actual "(get {#{nil 1} :a} #{1})" :portability :common} - {:suite "map / nil inside a collection key" :label "set key w/ nil pos lookup" :expected ":a" :actual "(get {#{nil 1} :a} #{nil 1})" :portability :common} - {:suite "map / nil inside a collection key" :label "set key just nil distinct" :expected "false" :actual "(= {#{nil} :x} {#{} :x})" :portability :common} - {:suite "map / nil inside a collection key" :label "map nil-value key distinct" :expected "2" :actual "(count {{:a nil} 1, {} 2})" :portability :common} - {:suite "map / nil inside a collection key" :label "map nil-value key neg" :expected "nil" :actual "(get {{:a nil} 1} {})" :portability :common} - {:suite "map / nil inside a collection key" :label "map nil-value key pos" :expected "1" :actual "(get {{:a nil} 1} {:a nil})" :portability :common} - {:suite "map / nil inside a collection key" :label "map nil-key key distinct" :expected "2" :actual "(count {{nil :a} 1, {} 2})" :portability :common} - {:suite "map / nil inside a collection key" :label "map nil-key key pos" :expected "1" :actual "(get {{nil :a} 1} {nil :a})" :portability :common} - {:suite "map / strictness (throws like Clojure)" :label "assoc vec out of bounds" :expected :throws :actual "(assoc [0 1 2] 4 4)" :portability :common} - {:suite "map / strictness (throws like Clojure)" :label "assoc vec negative" :expected :throws :actual "(assoc [] -1 0)" :portability :common} - {:suite "map / strictness (throws like Clojure)" :label "assoc vec at count ok" :expected "[1 2 3]" :actual "(assoc [1 2] 2 3)" :portability :common} - {:suite "map / strictness (throws like Clojure)" :label "dissoc on number" :expected :throws :actual "(dissoc 42 :a)" :portability :common} - {:suite "map / strictness (throws like Clojure)" :label "dissoc on vector" :expected :throws :actual "(dissoc [1 2] 0)" :portability :common} - {:suite "map / strictness (throws like Clojure)" :label "dissoc on set" :expected :throws :actual "(dissoc #{:a} :a)" :portability :common} - {:suite "map / strictness (throws like Clojure)" :label "dissoc nil ok" :expected "nil" :actual "(dissoc nil :a)" :portability :common} - {:suite "map / strictness (throws like Clojure)" :label "count on number" :expected :throws :actual "(count 1)" :portability :common} - {:suite "map / strictness (throws like Clojure)" :label "count on keyword" :expected :throws :actual "(count :a)" :portability :common} - {:suite "map / strictness (throws like Clojure)" :label "count string ok" :expected "3" :actual "(count \"abc\")" :portability :common} - {:suite "map / strictness (throws like Clojure)" :label "numerator throws" :expected :throws :actual "(numerator 1)" :portability :common} - {:suite "map / strictness (throws like Clojure)" :label "denominator throws" :expected :throws :actual "(denominator 2)" :portability :common} - {:suite "map / strictness (throws like Clojure)" :label "subvec out of range" :expected :throws :actual "(subvec [0 1 2 3] 1 5)" :portability :common} - {:suite "map / strictness (throws like Clojure)" :label "subvec start>end" :expected :throws :actual "(subvec [0 1 2 3] 3 2)" :portability :common} - {:suite "map / strictness (throws like Clojure)" :label "subvec ok" :expected "[1 2]" :actual "(subvec [0 1 2 3] 1 3)" :portability :common} - {:suite "map / strictness (throws like Clojure)" :label "min-key empty" :expected :throws :actual "(apply min-key identity [])" :portability :common} - {:suite "map / strictness (throws like Clojure)" :label "merge empty vector" :expected :throws :actual "(merge {} [])" :portability :common} - {:suite "map / strictness (throws like Clojure)" :label "merge 1-elem vector" :expected :throws :actual "(merge {} [:foo])" :portability :common} - {:suite "map / strictness (throws like Clojure)" :label "merge atomic arg" :expected :throws :actual "(merge {} :foo)" :portability :common} - {:suite "map / strictness (throws like Clojure)" :label "merge [k v] ok" :expected "{:foo 1}" :actual "(merge {} [:foo 1])" :portability :common} - {:suite "map / strictness (throws like Clojure)" :label "merge maps ok" :expected "{:a 1, :b 2}" :actual "(merge {:a 1} {:b 2})" :portability :common} - {:suite "map / map-entry & key ordering" :label "key of entry" :expected ":a" :actual "(key (first {:a 1}))" :portability :common} - {:suite "map / map-entry & key ordering" :label "val of entry" :expected "1" :actual "(val (first {:a 1}))" :portability :common} - {:suite "map / map-entry & key ordering" :label "key rejects vector" :expected :throws :actual "(key [:a 1])" :portability :common} - {:suite "map / map-entry & key ordering" :label "val rejects vector" :expected :throws :actual "(val [:a 1])" :portability :common} - {:suite "map / map-entry & key ordering" :label "map-entry? entry" :expected "true" :actual "(map-entry? (first {:a 1}))" :portability :common} - {:suite "map / map-entry & key ordering" :label "map-entry? vector" :expected "false" :actual "(map-entry? [:a 1])" :portability :common} - {:suite "map / map-entry & key ordering" :label "min-key NaN first" :expected "1" :actual "(min-key identity ##NaN 1)" :portability :common} - {:suite "map / map-entry & key ordering" :label "min-key NaN last" :expected "true" :actual "(NaN? (min-key identity 1 ##NaN))" :portability :common} - {:suite "map / map-entry & key ordering" :label "min-key NaN three" :expected "true" :actual "(infinite? (min-key identity ##NaN ##-Inf 1))" :portability :common} - {:suite "map / map-entry & key ordering" :label "min-key keys nonnum" :expected :throws :actual "(min-key identity \"x\" \"y\")" :portability :common} - {:suite "map / map-entry & key ordering" :label "max-key picks max" :expected "[1 2 3]" :actual "(max-key count [1] [1 2 3] [1 2])" :portability :common} - {:suite "map / map-entry & key ordering" :label "subvec float trunc" :expected "[0]" :actual "(subvec [0 1 2] 0.5 1.33)" :portability :common} - {:suite "map / map-entry & key ordering" :label "subvec NaN start" :expected "[0 1 2]" :actual "(subvec [0 1 2] ##NaN 3)" :portability :common} - {:suite "map / map-entry & key ordering" :label "subvec NaN end" :expected "[]" :actual "(subvec [0 1 2] 0 ##NaN)" :portability :common} - {:suite "map / nil values preserved" :label "literal contains" :expected "true" :actual "(contains? {:b nil} :b)" :portability :common} - {:suite "map / nil values preserved" :label "literal not= empty" :expected "false" :actual "(= {:b nil} {})" :portability :common} - {:suite "map / nil values preserved" :label "literal get nil" :expected "nil" :actual "(get {:b nil} :b :x)" :portability :common} - {:suite "map / nil values preserved" :label "literal keys incl nil" :expected "true" :actual "(= #{:a :b} (set (keys {:a nil :b 1})))" :portability :common} - {:suite "map / nil values preserved" :label "literal count" :expected "2" :actual "(count {:a nil :b 1})" :portability :common} - {:suite "map / nil values preserved" :label "literal vals incl nil" :expected "2" :actual "(count (vals {:a nil :b 1}))" :portability :common} - {:suite "map / nil values preserved" :label "eval values w/ nil" :expected "3" :actual "(:a {:a (+ 1 2) :b nil})" :portability :common} - {:suite "map / nil values preserved" :label "nil key present" :expected "true" :actual "(contains? {nil :v} nil)" :portability :common} - {:suite "map / nil values preserved" :label "assoc nil present" :expected "true" :actual "(contains? (assoc {:a 1} :b nil) :b)" :portability :common} - {:suite "map / nil values preserved" :label "assoc nil get" :expected "nil" :actual "(get (assoc {:a 1} :b nil) :b :x)" :portability :common} - {:suite "map / nil values preserved" :label "assoc overwrite nil" :expected "nil" :actual "(get (assoc {:a 1} :a nil) :a :x)" :portability :common} - {:suite "map / nil values preserved" :label "hash-map nil" :expected "true" :actual "(contains? (hash-map :b nil) :b)" :portability :common} - {:suite "map / nil values preserved" :label "merge new nil" :expected "true" :actual "(contains? (merge {:a 1} {:b nil}) :b)" :portability :common} - {:suite "map / nil values preserved" :label "merge overwrite nil" :expected "nil" :actual "(get (merge {:a 1} {:a nil}) :a :x)" :portability :common} - {:suite "map / nil values preserved" :label "merge-with present nil" :expected "true" :actual "(= [nil 1] (get (merge-with (fn [a b] [a b]) {:a nil} {:a 1}) :a))" :portability :common} - {:suite "map / nil values preserved" :label "into nil val" :expected "true" :actual "(contains? (into {} [[:a nil]]) :a)" :portability :common} - {:suite "map / nil values preserved" :label "conj map nil" :expected "true" :actual "(contains? (conj {:x 1} {:a nil}) :a)" :portability :common} - {:suite "map / nil values preserved" :label "zipmap nil" :expected "true" :actual "(contains? (zipmap [:a] [nil]) :a)" :portability :common} - {:suite "map / nil values preserved" :label "select-keys nil" :expected "true" :actual "(contains? (select-keys {:a nil} [:a]) :a)" :portability :common} - {:suite "map / nil values preserved" :label "get-in present nil" :expected "nil" :actual "(get-in {:a nil} [:a] :x)" :portability :common} - {:suite "map / nil values preserved" :label "get-in through nil" :expected ":x" :actual "(get-in {:a nil} [:a :b] :x)" :portability :common} - {:suite "map / nil values preserved" :label "dissoc keeps nil" :expected "true" :actual "(contains? (dissoc {:a nil :b 1} :b) :a)" :portability :common} - {:suite "map / nil values preserved" :label "reduce-kv sees nil" :expected "true" :actual "(= #{:a :b} (reduce-kv (fn [acc k v] (conj acc k)) #{} {:a nil :b 2}))" :portability :common} - {:suite "map / nil values preserved" :label "nil-free stays fast" :expected "true" :actual "(= {:a 1 :b 2} {:b 2 :a 1})" :portability :common} - {:suite "map / update-keys & update-vals (1.11)" :label "update-keys" :expected "{\"a\" 1, \"b\" 2}" :actual "(update-keys {:a 1 :b 2} name)" :portability :common} - {:suite "map / update-keys & update-vals (1.11)" :label "update-keys empty" :expected "{}" :actual "(update-keys {} inc)" :portability :common} - {:suite "map / update-keys & update-vals (1.11)" :label "update-keys nil" :expected "{}" :actual "(update-keys nil str)" :portability :common} - {:suite "map / update-keys & update-vals (1.11)" :label "update-keys collide last wins" :expected "1" :actual "(count (update-keys {:a 1 :b 2} (fn [_] :k)))" :portability :common} - {:suite "map / update-keys & update-vals (1.11)" :label "update-vals" :expected "{:a 2, :b 3}" :actual "(update-vals {:a 1 :b 2} inc)" :portability :common} - {:suite "map / update-keys & update-vals (1.11)" :label "update-vals empty" :expected "{}" :actual "(update-vals {} inc)" :portability :common} - {:suite "map / update-keys & update-vals (1.11)" :label "update-vals nil" :expected "{}" :actual "(update-vals nil inc)" :portability :common} - {:suite "map / update-keys & update-vals (1.11)" :label "update-vals keeps keys" :expected "[:a :b]" :actual "(sort (keys (update-vals {:a 1 :b 2} inc)))" :portability :common} - {:suite "maps / keys-vals-empty? as overlay fns" :label "keys" :expected "[:a]" :actual "(keys {:a 1})" :portability :common} - {:suite "maps / keys-vals-empty? as overlay fns" :label "keys empty map" :expected "nil" :actual "(keys {})" :portability :common} - {:suite "maps / keys-vals-empty? as overlay fns" :label "keys nil" :expected "nil" :actual "(keys nil)" :portability :common} - {:suite "maps / keys-vals-empty? as overlay fns" :label "vals" :expected "[1]" :actual "(vals {:a 1})" :portability :common} - {:suite "maps / keys-vals-empty? as overlay fns" :label "vals empty" :expected "nil" :actual "(vals {})" :portability :common} - {:suite "maps / keys-vals-empty? as overlay fns" :label "keys sorted order" :expected "[1 2 3]" :actual "(vec (keys (sorted-map 2 :b 1 :a 3 :c)))" :portability :common} - {:suite "maps / keys-vals-empty? as overlay fns" :label "vals sorted order" :expected "[:a :b :c]" :actual "(vec (vals (sorted-map 2 :b 1 :a 3 :c)))" :portability :common} - {:suite "maps / keys-vals-empty? as overlay fns" :label "keys/vals zip" :expected "{:a 1, :b 2}" :actual "(zipmap (keys {:a 1 :b 2}) (vals {:a 1 :b 2}))" :portability :common} - {:suite "maps / keys-vals-empty? as overlay fns" :label "empty? map" :expected "true" :actual "(empty? {})" :portability :common} - {:suite "maps / keys-vals-empty? as overlay fns" :label "empty? vec" :expected "[true false]" :actual "[(empty? []) (empty? [1])]" :portability :common} - {:suite "maps / keys-vals-empty? as overlay fns" :label "empty? list" :expected "[true false]" :actual "[(empty? ()) (empty? (list 1))]" :portability :common} - {:suite "maps / keys-vals-empty? as overlay fns" :label "empty? string" :expected "[true false]" :actual "[(empty? \"\") (empty? \"a\")]" :portability :common} - {:suite "maps / keys-vals-empty? as overlay fns" :label "empty? nil" :expected "true" :actual "(empty? nil)" :portability :common} - {:suite "maps / keys-vals-empty? as overlay fns" :label "empty? set" :expected "[true false]" :actual "[(empty? #{}) (empty? #{1})]" :portability :common} - {:suite "maps / keys-vals-empty? as overlay fns" :label "empty? lazy" :expected "[true false]" :actual "[(empty? (filter pos? [-1])) (empty? (map inc [1]))]" :portability :common} - {:suite "maps / keys-vals-empty? as overlay fns" :label "empty? lazy nil elem" :expected "false" :actual "(empty? (cons nil nil))" :portability :common} - {:suite "maps / keys-vals-empty? as overlay fns" :label "empty? sorted" :expected "[true false]" :actual "[(empty? (sorted-map)) (empty? (sorted-set 1))]" :portability :common} - {:suite "maps / keys-vals-empty? as overlay fns" :label "empty? number throws" :expected :throws :actual "(empty? 5)" :portability :common} - {:suite "map / assoc on nil" :label "assoc nil is a map" :expected "{:a 1}" :actual "(assoc nil :a 1)" :portability :common} - {:suite "map / assoc on nil" :label "count of assoc nil" :expected "1" :actual "(count (assoc nil :a 1))" :portability :common} - {:suite "map / assoc on nil" :label "assoc-in nested countable" :expected "1" :actual "(count (:a (assoc-in {} [:a :b] 1)))" :portability :common} - {:suite "map / assoc on nil" :label "assoc-in deep get" :expected "9" :actual "(get-in (assoc-in {} [:a :b :c] 9) [:a :b :c])" :portability :common} - {:suite "map / assoc on nil" :label "seq over assoc-nil map" :expected ":a" :actual "(ffirst (seq (assoc nil :a 1)))" :portability :common} - {:suite "map / assoc on nil" :label "keys of assoc-nil map" :expected "[:a]" :actual "(vec (keys (assoc nil :a 1)))" :portability :common} - {:suite "map / bulk build boundaries" :label "into = incr at 17" :expected "true" :actual "(= (into {} (map (fn [i] [i (* i 2)]) (range 17))) (reduce (fn [m p] (assoc m (first p) (second p))) {} (map (fn [i] [i (* i 2)]) (range 17))))" :portability :common} - {:suite "map / bulk build boundaries" :label "into = incr at 1000" :expected "true" :actual "(= (into {} (map (fn [i] [i (* i 2)]) (range 1000))) (reduce (fn [m p] (assoc m (first p) (second p))) {} (map (fn [i] [i (* i 2)]) (range 1000))))" :portability :common} - {:suite "map / bulk build boundaries" :label "into count 1000" :expected "1000" :actual "(count (into {} (map (fn [i] [i i]) (range 1000))))" :portability :common} - {:suite "map / bulk build boundaries" :label "into reads back" :expected "999" :actual "(get (into {} (map (fn [i] [i (* i 3)]) (range 1000))) 333)" :portability :common} - {:suite "map / bulk build boundaries" :label "into onto non-empty" :expected "9" :actual "(get (into {:a 1} [[:a 9] [:b 2]]) :a)" :portability :common} - {:suite "map / bulk build boundaries" :label "into dup last wins" :expected "9" :actual "(get (into {} [[:k 1] [:k 9]]) :k)" :portability :common} - {:suite "map / bulk build boundaries" :label "into nil key" :expected ":x" :actual "(get (into {} [[nil :x] [:a 1]]) nil)" :portability :common} - {:suite "map / bulk build boundaries" :label "assoc after bulk" :expected "7" :actual "(get (assoc (into {} (map (fn [i] [i i]) (range 100))) :new 7) :new)" :portability :common} - {:suite "map / bulk build boundaries" :label "dissoc after bulk" :expected "nil" :actual "(get (dissoc (into {} (map (fn [i] [i i]) (range 100))) 50) 50)" :portability :common} - {:suite "map / bulk build boundaries" :label "frequencies count" :expected "3" :actual "(get (frequencies [1 2 2 1 2 1]) 1)" :portability :common} - {:suite "map / bulk build boundaries" :label "frequencies coll-key" :expected "2" :actual "(get (frequencies [[1 2] [1 2] [3 4]]) [1 2])" :portability :common} - {:suite "map / bulk build boundaries" :label "frequencies nil key" :expected "2" :actual "(get (frequencies [nil nil 1]) nil)" :portability :common} - {:suite "map / bulk build boundaries" :label "group-by nil key" :expected "[nil nil]" :actual "(get (group-by identity [nil nil 1]) nil)" :portability :common} - {:suite "map / bulk build boundaries" :label "group-by nil count" :expected "2" :actual "(count (group-by identity [nil nil 1]))" :portability :common} - {:suite "map / bulk build boundaries" :label "transient nil key" :expected ":x" :actual "(let [t (transient {})] (assoc! t nil :x) (get (persistent! t) nil))" :portability :common} - {:suite "map / bulk build boundaries" :label "transient nil get" :expected "true" :actual "(let [t (transient {})] (assoc! t nil :x) (contains? t nil))" :portability :common} - {:suite "map / bulk build boundaries" :label "transient nil dissoc" :expected ":gone" :actual "(let [t (transient {})] (assoc! t nil :x) (dissoc! t nil) (get (persistent! t) nil :gone))" :portability :common} - {:suite "map / bulk build boundaries" :label "group-by bucket" :expected "[1 3 5]" :actual "(get (group-by odd? (range 1 6)) true)" :portability :common} - {:suite "map / bulk build boundaries" :label "group-by big bucket" :expected "true" :actual "(= (group-by even? (range 200)) {true (vec (filter even? (range 200))) false (vec (filter odd? (range 200)))})" :portability :common} - {:suite "map / bulk build boundaries" :label "group-by order" :expected "[0 3 6 9]" :actual "(get (group-by (fn [x] (mod x 3)) (range 10)) 0)" :portability :common} - {:suite "map / bulk build boundaries" :label "hash-map bulk = incr" :expected "true" :actual "(= (apply hash-map (mapcat (fn [i] [i i]) (range 50))) (reduce (fn [m i] (assoc m i i)) {} (range 50)))" :portability :common} - {:suite "metadata / with-meta & meta" :label "meta of bare value" :expected "nil" :actual "(meta [1 2 3])" :portability :common} - {:suite "metadata / with-meta & meta" :label "with-meta then meta" :expected "{:a 1}" :actual "(meta (with-meta [1 2 3] {:a 1}))" :portability :common} - {:suite "metadata / with-meta & meta" :label "with-meta preserves value" :expected "true" :actual "(= [1 2 3] (with-meta [1 2 3] {:a 1}))" :portability :common} - {:suite "metadata / with-meta & meta" :label "with-meta on map" :expected "{:doc \"x\"}" :actual "(meta (with-meta {:k 1} {:doc \"x\"}))" :portability :common} - {:suite "metadata / with-meta & meta" :label "vary-meta" :expected "{:a 2}" :actual "(meta (vary-meta (with-meta [1] {:a 1}) update :a inc))" :portability :common} - {:suite "metadata / with-meta & meta" :label "vary-meta extra args" :expected "{:a 1, :b 2}" :actual "(meta (vary-meta (with-meta [1] {:a 1}) assoc :b 2))" :portability :common} - {:suite "metadata / with-meta & meta" :label "meta reader ^" :expected "{:tag :int}" :actual "(meta ^{:tag :int} [1 2])" :portability :common} - {:suite "metadata / with-meta & meta" :label "with-meta on fn ok" :expected "true" :actual "(fn? (with-meta inc {:a 1}))" :portability :common} - {:suite "metadata / with-meta & meta" :label "with-meta nil clears" :expected "nil" :actual "(meta (with-meta [1 2 3] nil))" :portability :common} - {:suite "metadata / type hints" :label "type hint on param" :expected "\"hi\"" :actual "(do (defn f [^String s] s) (f \"hi\"))" :portability :common} - {:suite "metadata / type hints" :label "type hint, extra params" :expected "[1 2]" :actual "(do (defn g [^String x y] [x y]) (g 1 2))" :portability :common} - {:suite "metadata / type hints" :label "type hint in let" :expected "6" :actual "(let [^long x 5] (inc x))" :portability :common} - {:suite "metadata / type hints" :label "type hint in body" :expected "2" :actual "(let [s \"ab\"] (count ^String s))" :portability :common} - {:suite "metadata / type hints" :label "type hint in destructure" :expected "3" :actual "(let [{:keys [^long a]} {:a 3}] a)" :portability :common} - {:suite "metadata / type hints" :label "symbol hint -> :tag is a symbol" :expected "true" :actual "(symbol? (:tag (meta (read-string \"^String x\"))))" :portability :common} - {:suite "metadata / type hints" :label "symbol hint -> :tag name" :expected "\"String\"" :actual "(name (:tag (meta (read-string \"^String x\"))))" :portability :common} - {:suite "metadata / type hints" :label "keyword hint -> true" :expected "true" :actual "(:foo (meta (read-string \"^:foo x\")))" :portability :common} - {:suite "metadata / read data metadata" :label "vector data meta" :expected "{:ref true}" :actual "(meta (read-string \"^:ref [:greeting]\"))" :portability :common} - {:suite "metadata / read data metadata" :label "map data meta" :expected "{:k 1}" :actual "(meta (read-string \"^{:k 1} {:a 2}\"))" :portability :common} - {:suite "metadata / read data metadata" :label "set data meta" :expected "{:s true}" :actual "(meta (read-string \"^:s #{1 2}\"))" :portability :common} - {:suite "metadata / read data metadata" :label "nested vector data meta" :expected "{:x true}" :actual "(meta (second (read-string \"[1 ^:x {:a 2}]\")))" :portability :common} - {:suite "metadata / read data metadata" :label "collection value unchanged" :expected "[:greeting]" :actual "(read-string \"^:ref [:greeting]\")" :portability :common} - {:suite "metadata / coll literal in code keeps meta" :label "vector literal meta" :expected "{:foo true}" :actual "(meta ^:foo [1 2])" :portability :common} - {:suite "metadata / coll literal in code keeps meta" :label "map literal meta with expr" :expected "{:a 3}" :actual "(meta ^{:a (+ 1 2)} [1])" :portability :common} - {:suite "metadata / coll literal in code keeps meta" :label "map literal value-eval order" :expected "[1 2]" :actual "(let [a (atom [])] ^:t {(do (swap! a conj 1) :a) 1 (do (swap! a conj 2) :b) 2} @a)" :portability :common} - {:suite "metadata / *print-meta*" :label "pr-str prefixes ^meta" :expected "\"^{:ref true} [:g]\"" :actual "(binding [*print-meta* true] (pr-str (with-meta [:g] {:ref true})))" :portability :common} - {:suite "metadata / *print-meta*" :label "off by default" :expected "\"[:g]\"" :actual "(pr-str (with-meta [:g] {:ref true}))" :portability :common} - {:suite "metadata / *print-meta*" :label "symbol meta prefixed" :expected "\"^{:k 1} x\"" :actual "(binding [*print-meta* true] (pr-str (with-meta (quote x) {:k 1})))" :portability :common} - {:suite "metadata / *print-meta*" :label "print then read round-trips" :expected "{:ref true}" :actual "(meta (read-string (binding [*print-meta* true] (pr-str (with-meta [:g] {:ref true})))))" :portability :common} - {:suite "metadata / clojure.walk preserves meta" :label "postwalk keeps vector meta" :expected "{:ref true}" :actual "(do (require (quote [clojure.walk :as w])) (meta (w/postwalk identity (with-meta [:b] {:ref true}))))" :portability :common} - {:suite "metadata / clojure.walk preserves meta" :label "postwalk keeps map meta" :expected "{:m 1}" :actual "(do (require (quote [clojure.walk :as w])) (meta (w/postwalk identity (with-meta {:a 2} {:m 1}))))" :portability :common} - {:suite "metadata / clojure.edn preserves meta" :label "edn vector meta" :expected "{:ref true}" :actual "(do (require (quote [clojure.edn :as e1])) (meta (e1/read-string \"^:ref [:greeting]\")))" :portability :common} - {:suite "metadata / clojure.edn preserves meta" :label "edn map meta" :expected "{:m true}" :actual "(do (require (quote [clojure.edn :as e1])) (meta (e1/read-string \"^:m {:a 1}\")))" :portability :common} - {:suite "metadata / clojure.edn preserves meta" :label "edn set meta" :expected "{:s true}" :actual "(do (require (quote [clojure.edn :as e1])) (meta (e1/read-string \"^:s #{1}\")))" :portability :common} - {:suite "metadata / collection ops preserve meta" :label "empty keeps vector meta" :expected "{:k 9}" :actual "(meta (empty (with-meta [1] {:k 9})))" :portability :common} - {:suite "metadata / collection ops preserve meta" :label "empty keeps map meta" :expected "{:k 9}" :actual "(meta (empty (with-meta {:a 1} {:k 9})))" :portability :common} - {:suite "metadata / collection ops preserve meta" :label "empty keeps set meta" :expected "{:k 9}" :actual "(meta (empty (with-meta #{1} {:k 9})))" :portability :common} - {:suite "metadata / collection ops preserve meta" :label "empty keeps list meta" :expected "{:k 9}" :actual "(meta (empty (with-meta (list 1) {:k 9})))" :portability :common} - {:suite "metadata / collection ops preserve meta" :label "into empty keeps meta" :expected "{:k 9}" :actual "(meta (into (empty (with-meta {:a 1} {:k 9})) {:b 2}))" :portability :common} - {:suite "metadata / collection ops preserve meta" :label "into target meta" :expected "{:k 9}" :actual "(meta (into (with-meta [] {:k 9}) [1 2]))" :portability :common} - {:suite "metadata / collection ops preserve meta" :label "conj on vector" :expected "{:k 9}" :actual "(meta (conj (with-meta [1] {:k 9}) 2))" :portability :common} - {:suite "metadata / collection ops preserve meta" :label "conj on list" :expected "{:k 9}" :actual "(meta (conj (with-meta (list 1) {:k 9}) 2))" :portability :common} - {:suite "metadata / collection ops preserve meta" :label "assoc on map" :expected "{:k 9}" :actual "(meta (assoc (with-meta {:a 1} {:k 9}) :b 2))" :portability :common} - {:suite "metadata / collection ops preserve meta" :label "dissoc on map" :expected "{:k 9}" :actual "(meta (dissoc (with-meta {:a 1 :c 3} {:k 9}) :c))" :portability :common} - {:suite "metadata / collection ops preserve meta" :label "disj on set" :expected "{:k 9}" :actual "(meta (disj (with-meta #{1 2} {:k 9}) 2))" :portability :common} - {:suite "metadata / collection ops preserve meta" :label "pop on vector" :expected "{:k 9}" :actual "(meta (pop (with-meta [1 2] {:k 9})))" :portability :common} - {:suite "metadata / collection ops preserve meta" :label "op without meta is nil" :expected "nil" :actual "(meta (conj [1] 2))" :portability :common} - {:suite "metadata / collection ops preserve meta" :label "value preserved through conj" :expected "[1 2]" :actual "(conj (with-meta [1] {:k 9}) 2)" :portability :common} - {:suite "metadata / collection ops preserve meta" :label "empty list singleton unaffected" :expected "nil" :actual "(do (with-meta () {:leak 1}) (meta ()))" :portability :common} - {:suite "metadata / collection ops preserve meta" :label "empty vector literal unaffected" :expected "nil" :actual "(do (with-meta [] {:leak 1}) (meta []))" :portability :common} - {:suite "metadata / def metadata" :label "^:dynamic var binds" :expected "9" :actual "(do (def ^:dynamic *d* 1) (binding [*d* 9] *d*))" :portability :common} - {:suite "metadata / def metadata" :label "^:private on var" :expected "true" :actual "(do (def ^:private pv 1) (:private (meta (var pv))))" :portability :common} - {:suite "metadata / def metadata" :label "^Type tag on var" :expected "java.lang.String" :actual "(do (def ^String tv \"a\") (:tag (meta (var tv))))" :portability :common} - {:suite "metadata / def metadata" :label "^{:doc} on var" :expected "\"hi\"" :actual "(do (def ^{:doc \"hi\"} dv 1) (:doc (meta (var dv))))" :portability :common} - {:suite "metadata / def metadata" :label "(def name doc val) doc" :expected "\"d\"" :actual "(do (def dd \"d\" 5) (:doc (meta (var dd))))" :portability :common} - {:suite "core / find-keyword + inst-ms*" :label "find-keyword" :expected ":a" :actual "(find-keyword \"a\")" :portability :common} - {:suite "core / find-keyword + inst-ms*" :label "find-keyword 2-arity" :expected ":n/a" :actual "(find-keyword \"n\" \"a\")" :portability :common} - {:suite "core / find-keyword + inst-ms*" :label "find-keyword = keyword" :expected "true" :actual "(= (find-keyword \"x\") :x)" :portability :common} - {:suite "core / find-keyword + inst-ms*" :label "inst-ms*" :expected "true" :actual "(= (inst-ms* #inst \"2020-01-01T00:00:00Z\") (inst-ms #inst \"2020-01-01T00:00:00Z\"))" :portability :common} - {:suite "core / find-keyword + inst-ms*" :label "inst-ms* value" :expected "0" :actual "(inst-ms* #inst \"1970-01-01T00:00:00Z\")" :portability :common} - {:suite "core / with-local-vars" :label "var-get initial" :expected "1" :actual "(with-local-vars [x 1] (var-get x))" :portability :common} - {:suite "core / with-local-vars" :label "var-set" :expected "2" :actual "(with-local-vars [x 1] (var-set x 2) (var-get x))" :portability :common} - {:suite "core / with-local-vars" :label "two vars" :expected "[1 2]" :actual "(with-local-vars [a 1 b 2] [(var-get a) (var-get b)])" :portability :common} - {:suite "core / with-local-vars" :label "vars are values" :expected "5" :actual "(with-local-vars [x 0] (let [bump (fn [v] (var-set v (+ 5 (var-get v))))] (bump x) (var-get x)))" :portability :common} - {:suite "core / with-local-vars" :label "init sees outer" :expected "3" :actual "(let [y 3] (with-local-vars [x y] (var-get x)))" :portability :common} - {:suite "core / with-local-vars" :label "body result" :expected ":done" :actual "(with-local-vars [x 1] :done)" :portability :common} - {:suite "core / with-open" :label "body result" :expected ":r" :actual "(let [log (atom [])] (with-open [c {:close (fn [] (swap! log conj :closed))}] :r))" :portability :common} - {:suite "core / with-open" :label "close runs" :expected "[:closed]" :actual "(let [log (atom [])] (with-open [c {:close (fn [] (swap! log conj :closed))}] :r) (deref log))" :portability :common} - {:suite "core / with-open" :label "close on throw" :expected "[]" :actual "(let [log (atom [])] (try (with-open [c {:close (fn [] (swap! log conj :closed))}] (throw (ex-info \"boom\" {}))) (catch Exception e nil)) (deref log))" :portability :common} - {:suite "core / with-open" :label "nested close order" :expected "[:inner :outer]" :actual "(let [log (atom [])] (with-open [a {:close (fn [] (swap! log conj :outer))} b {:close (fn [] (swap! log conj :inner))}] :r) (deref log))" :portability :common} - {:suite "core / with-open" :label "zero bindings" :expected ":r" :actual "(with-open [] :r)" :portability :common} - {:suite "core / with-open" :label "binding visible" :expected "5" :actual "(with-open [c {:close (fn [] nil) :v 5}] (:v c))" :portability :common} - {:suite "core / with-precision" :label "body evaluates" :expected "3.14" :actual "(with-precision 3 3.14)" :portability :common} - {:suite "core / with-precision" :label "multiple body forms" :expected "2" :actual "(with-precision 10 1 2)" :portability :common} - {:suite "core / with-precision" :label "rounding arg accepted" :expected "1.5" :actual "(with-precision 4 :rounding :half-up 1.5)" :portability :common} - {:suite "core / with-precision" :label "arithmetic" :expected "2" :actual "(with-precision 5 (+ 1 1))" :portability :common} - {:suite "core / read+string" :label "form and text" :expected "true" :actual "(let [[v s] (with-in-str \"42 rest\" (read+string))] (and (= v 42) (string? s)))" :portability :common} - {:suite "core / read+string" :label "form value" :expected "(quote (+ 1 2))" :actual "(first (with-in-str \"(+ 1 2)\" (read+string)))" :portability :common} - {:suite "core / read+string" :label "text covers the form" :expected "true" :actual "(let [[v s] (with-in-str \" [1 2] tail\" (read+string))] (and (= v [1 2]) (> (count s) 3)))" :portability :common} - {:suite "core / read+string" :label "advances the stream" :expected "[1 2]" :actual "(with-in-str \"1 2\" [(first (read+string)) (first (read+string))])" :portability :common} - {:suite "core / read+string" :label "EOF throws" :expected :throws :actual "(with-in-str \"\" (read+string))" :portability :common} - {:suite "core / read+string" :label "eof-value arity" :expected ":done" :actual "(first (with-in-str \"\" (read+string *in* false :done)))" :portability :common} - {:suite "core / extenders" :label "lists extended type" :expected "[]" :actual "(do (defprotocol Px (pm [x])) (defrecord Rx [] Px (pm [x] 1)) (mapv str (extenders Px)))" :portability :common} - {:suite "core / extenders" :label "nil when none" :expected "nil" :actual "(do (defprotocol Py (pn [x])) (extenders Py))" :portability :common} - {:suite "core / extenders" :label "seq of tags" :expected "nil" :actual "(do (defprotocol Pz (pz [x])) (defrecord Rz [] Pz (pz [x] 1)) (and (seq (extenders Pz)) (= 1 (count (extenders Pz)))))" :portability :common} - {:suite "multimethods / dispatch" :label "dispatch on value" :expected "\"two\"" :actual "(do (defmulti f identity) (defmethod f 1 [_] \"one\") (defmethod f 2 [_] \"two\") (f 2))" :portability :common} - {:suite "multimethods / dispatch" :label "dispatch on keyword fn" :expected "\"circle\"" :actual "(do (defmulti area :shape) (defmethod area :circle [_] \"circle\") (area {:shape :circle}))" :portability :common} - {:suite "multimethods / dispatch" :label ":default method" :expected "\"other\"" :actual "(do (defmulti f identity) (defmethod f 1 [_] \"one\") (defmethod f :default [_] \"other\") (f 99))" :portability :common} - {:suite "multimethods / dispatch" :label "no match throws" :expected :throws :actual "(do (defmulti f identity) (defmethod f 1 [_] \"one\") (f 99))" :portability :common} - {:suite "multimethods / dispatch" :label "multiple args" :expected "5" :actual "(do (defmulti g (fn [a b] a)) (defmethod g :add [_ b] b) (g :add 5))" :portability :common} - {:suite "multimethods / dispatch" :label "get-method" :expected "\"one\"" :actual "(do (defmulti f identity) (defmethod f 1 [_] \"one\") ((get-method f 1) 1))" :portability :common} - {:suite "multimethods / dispatch" :label "remove-method" :expected :throws :actual "(do (defmulti f identity) (defmethod f 1 [_] \"one\") (remove-method f 1) (f 1))" :portability :common} - {:suite "multimethods / dispatch" :label "methods" :expected "\"one\"" :actual "(do (defmulti f identity) (defmethod f 1 [_] \"one\") ((get (methods f) 1) 1))" :portability :common} - {:suite "multimethods / dispatch" :label "methods count" :expected "2" :actual "(do (defmulti f identity) (defmethod f 1 [_] \"one\") (defmethod f 2 [_] \"two\") (count (methods f)))" :portability :common} - {:suite "multimethods / dispatch" :label "remove-all-methods" :expected :throws :actual "(do (defmulti f identity) (defmethod f 1 [_] \"one\") (defmethod f 2 [_] \"two\") (remove-all-methods f) (f 1))" :portability :common} - {:suite "multimethods / dispatch" :label "remove-all-methods empties the table" :expected "0" :actual "(do (defmulti f identity) (defmethod f 1 [_] \"one\") (remove-all-methods f) (count (methods f)))" :portability :common} - {:suite "multimethods / hierarchies" :label "derive + isa?" :expected "true" :actual "(do (derive ::child ::parent) (isa? ::child ::parent))" :portability :common} - {:suite "multimethods / hierarchies" :label "isa? reflexive" :expected "true" :actual "(isa? ::x ::x)" :portability :common} - {:suite "multimethods / hierarchies" :label "isa? unrelated" :expected "false" :actual "(do (derive ::a ::b) (isa? ::a ::c))" :portability :common} - {:suite "multimethods / hierarchies" :label "parents" :expected "true" :actual "(do (derive ::c ::p) (contains? (parents ::c) ::p))" :portability :common} - {:suite "multimethods / hierarchies" :label "ancestors" :expected "true" :actual "(do (derive ::c ::p) (derive ::p ::g) (contains? (ancestors ::c) ::g))" :portability :common} - {:suite "multimethods / hierarchies" :label "descendants" :expected "true" :actual "(do (derive ::c ::p) (contains? (descendants ::p) ::c))" :portability :common} - {:suite "multimethods / hierarchies" :label "dispatch via hierarchy" :expected "\"animal\"" :actual "(do (derive ::dog ::animal) (defmulti speak identity) (defmethod speak ::animal [_] \"animal\") (speak ::dog))" :portability :common} - {:suite "multimethods / hierarchies" :label "custom :default key" :expected ":unknown" :actual "(do (defmulti classify :type :default :other) (defmethod classify :a [_] :alpha) (defmethod classify :other [_] :unknown) (classify {:type :zzz}))" :portability :common} - {:suite "multimethods / hierarchies" :label "explicit :hierarchy" :expected "\"a\"" :actual "(do (def h (derive (make-hierarchy) ::dog ::animal)) (defmulti snd identity :hierarchy h) (defmethod snd ::animal [_] \"a\") (snd ::dog))" :portability :common} - {:suite "multimethods / prefer-method" :label "preference picks the winner" :expected ":rect" :actual "(do (derive :p/sq :p/rect) (derive :p/sq :p/shape) (defmulti pm1 identity) (defmethod pm1 :p/rect [x] :rect) (defmethod pm1 :p/shape [x] :shape) (prefer-method pm1 :p/rect :p/shape) (pm1 :p/sq))" :portability :common} - {:suite "multimethods / prefer-method" :label "reverse preference" :expected ":shape" :actual "(do (derive :q/sq :q/rect) (derive :q/sq :q/shape) (defmulti pm2 identity) (defmethod pm2 :q/rect [x] :rect) (defmethod pm2 :q/shape [x] :shape) (prefer-method pm2 :q/shape :q/rect) (pm2 :q/sq))" :portability :common} - {:suite "multimethods / prefer-method" :label "ambiguity throws" :expected :throws :actual "(do (derive :r/sq :r/rect) (derive :r/sq :r/shape) (defmulti pm3 identity) (defmethod pm3 :r/rect [x] :rect) (defmethod pm3 :r/shape [x] :shape) (pm3 :r/sq))" :portability :common} - {:suite "multimethods / prefer-method" :label "isa dominance needs no preference" :expected ":child" :actual "(do (derive :s/c :s/p) (defmulti pm4 identity) (defmethod pm4 :s/c [x] :child) (defmethod pm4 :s/p [x] :parent) (pm4 :s/c))" :portability :common} - {:suite "multimethods / prefer-method" :label "prefers map shape" :expected "true" :actual "(do (defmulti pm5 identity) (defmethod pm5 :a [x] 1) (defmethod pm5 :b [x] 2) (prefer-method pm5 :a :b) (contains? (get (prefers pm5) :a) :b))" :portability :common} - {:suite "multimethods / prefer-method" :label "exact match needs no preference" :expected ":exact" :actual "(do (derive :t/sq :t/rect) (defmulti pm6 identity) (defmethod pm6 :t/sq [x] :exact) (defmethod pm6 :t/rect [x] :parent) (pm6 :t/sq))" :portability :common} - {:suite "multimethods / docstring & value-based table ops" :label "defmulti docstring" :expected "\"A\"" :actual "(do (defmulti gd \"the dispatcher\" identity) (defmethod gd :a [_] \"A\") (gd :a))" :portability :common} - {:suite "multimethods / docstring & value-based table ops" :label "defmulti doc+default" :expected "\"d\"" :actual "(do (defmulti gx \"doc\" identity) (defmethod gx :default [_] \"d\") (gx :anything))" :portability :common} - {:suite "multimethods / docstring & value-based table ops" :label "methods on value" :expected "2" :actual "(do (defmulti gm identity) (defmethod gm 1 [_] :one) (defmethod gm 2 [_] :two) (count (methods gm)))" :portability :common} - {:suite "multimethods / docstring & value-based table ops" :label "get-method on value" :expected "true" :actual "(do (defmulti gg identity) (defmethod gg :a [_] :x) (fn? (get-method gg :a)))" :portability :common} - {:suite "namespaces / def & vars" :label "def + deref" :expected "5" :actual "(do (def x 5) x)" :portability :common} - {:suite "namespaces / def & vars" :label "def returns var" :expected "true" :actual "(var? (def y 1))" :portability :common} - {:suite "namespaces / def & vars" :label "declare then def" :expected "2" :actual "(do (declare z) (def z 2) z)" :portability :common} - {:suite "namespaces / def & vars" :label "var special form" :expected "true" :actual "(var? (var +))" :portability :common} - {:suite "namespaces / def & vars" :label "var sugar #'" :expected "true" :actual "(var? #'+)" :portability :common} - {:suite "namespaces / def & vars" :label "var-get" :expected "5" :actual "(do (def w 5) (var-get #'w))" :portability :common} - {:suite "namespaces / def & vars" :label "defn defines fn" :expected "3" :actual "(do (defn f [x] (inc x)) (f 2))" :portability :common} - {:suite "namespaces / def & vars" :label "def with docstring" :expected "7" :actual "(do (def d \"a doc\" 7) d)" :portability :common} - {:suite "namespaces / def & vars" :label "dynamic var binding" :expected "2" :actual "(do (def ^:dynamic *x* 1) (binding [*x* 2] *x*))" :portability :common} - {:suite "namespaces / def & vars" :label "binding restores" :expected "1" :actual "(do (def ^:dynamic *y* 1) (binding [*y* 9] nil) *y*)" :portability :common} - {:suite "namespaces / def & vars" :label "var-set in binding" :expected "5" :actual "(do (def ^:dynamic *z* 1) (binding [*z* 0] (var-set (var *z*) 5) *z*))" :portability :common} - {:suite "namespaces / ns operations" :label "in-ns switches" :expected "true" :actual "(do (in-ns 'my.ns) (symbol? 'x))" :portability :common} - {:suite "namespaces / ns operations" :label "ns form + alias" :expected "\"HI\"" :actual "(do (ns my.app (:require [clojure.string :as s])) (s/upper-case \"hi\"))" :portability :common} - {:suite "namespaces / ns operations" :label "ns :use refers all" :expected "9" :actual "(do (ns src.lib) (def helper 9) (ns dst.app (:use [src.lib])) helper)" :portability :common} - {:suite "namespaces / ns operations" :label "standalone use" :expected "7" :actual "(do (ns src.l2) (def k 7) (in-ns 'dst.a2) (use '[src.l2]) k)" :portability :common} - {:suite "namespaces / ns operations" :label "ns-name" :expected "true" :actual "(do (require (quote [clojure.string])) (= 'clojure.string (ns-name (find-ns 'clojure.string))))" :portability :common} - {:suite "namespaces / ns operations" :label "find-ns existing" :expected "true" :actual "(some? (find-ns 'clojure.core))" :portability :common} - {:suite "namespaces / ns operations" :label "find-ns missing" :expected "nil" :actual "(find-ns 'does.not.exist)" :portability :common} - {:suite "namespaces / ns operations" :label "resolve var" :expected "true" :actual "(var? (resolve '+))" :portability :common} - {:suite "namespaces / ns operations" :label "resolve missing" :expected "nil" :actual "(resolve 'totally-undefined-xyz)" :portability :common} - {:suite "namespaces / require & refer" :label "require :as" :expected "\"AB\"" :actual "(do (require '[clojure.string :as s]) (s/upper-case \"ab\"))" :portability :common} - {:suite "namespaces / require & refer" :label "require :refer" :expected "true" :actual "(do (require '[clojure.string :refer [blank?]]) (blank? \"\"))" :portability :common} - {:suite "namespaces / require & refer" :label "require :as + :refer" :expected "true" :actual "(do (require '[clojure.string :as s :refer [blank?]]) (and (blank? \"\") (= \"X\" (s/upper-case \"x\"))))" :portability :common} - {:suite "namespaces / require & refer" :label "require clojure.set" :expected "#{1 3 2}" :actual "(do (require '[clojure.set :as set]) (set/union #{1 2} #{3}))" :portability :common} - {:suite "namespaces / require & refer" :label "require clojure.walk" :expected "{:a 2}" :actual "(do (require '[clojure.walk :as w]) (w/postwalk (fn [x] (if (number? x) (inc x) x)) {:a 1}))" :portability :common} - {:suite "namespaces / require & refer" :label "walk keywordize-keys" :expected "{:a 1}" :actual "(do (require '[clojure.walk :as w]) (w/keywordize-keys {\"a\" 1}))" :portability :common} - {:suite "namespaces / require & refer" :label "walk stringify-keys" :expected "true" :actual "(do (require '[clojure.walk :as w]) (= {\"a\" 1} (w/stringify-keys {:a 1})))" :portability :common} - {:suite "namespaces / require & refer" :label "require missing lib throws" :expected :throws :actual "(require '[no.such.lib])" :portability :common} - {:suite "namespaces / require & refer" :label "use missing lib throws" :expected :throws :actual "(use 'no.such.lib)" :portability :common} - {:suite "namespaces / require & refer" :label "require of in-session ns ok" :expected "1" :actual "(do (ns made.here) (def x 1) (require '[made.here]) made.here/x)" :portability :common} - {:suite "namespaces / alias, ns-unalias, ns-publics" :label "alias + use" :expected "\"1,2\"" :actual "(do (require (quote clojure.string)) (alias (quote st) (quote clojure.string)) (st/join \",\" [1 2]))" :portability :common} - {:suite "namespaces / alias, ns-unalias, ns-publics" :label "ns-unalias removes" :expected "true" :actual "(do (require (quote clojure.string)) (alias (quote st2) (quote clojure.string)) (ns-unalias (quote user) (quote st2)) (nil? (get (ns-aliases (quote user)) (quote st2))))" :portability :common} - {:suite "namespaces / alias, ns-unalias, ns-publics" :label "ns-publics has var" :expected "true" :actual "(do (def npv 1) (some? (get (ns-publics (quote user)) (quote npv))))" :portability :common} - {:suite "namespaces / alias, ns-unalias, ns-publics" :label "newline returns nil" :expected "nil" :actual "(newline)" :portability :common} - {:suite "namespaces / error inside a fn must not leak its defining ns" :label "alias survives a throwing stdlib call" :expected "\"A\"" :actual "(do (require (quote [clojure.string :as s9])) (try (s9/join nil nil nil) (catch Exception e nil)) (s9/upper-case \"a\"))" :portability :common} - {:suite "namespaces / error inside a fn must not leak its defining ns" :label "*ns* restored after throw" :expected "\"user\"" :actual "(do (require (quote [clojure.walk :as w9])) (try (w9/postwalk nil nil nil) (catch Exception e nil)) (str *ns*))" :portability :common} - {:suite "namespaces / unified alias store" :label "require :as registers the alias" :expected "1" :actual "(do (require (quote [clojure.string :as st1])) (count (filter (fn [[a n]] (= (str a) \"st1\")) (ns-aliases))))" :portability :common} - {:suite "namespaces / unified alias store" :label "aliased call resolves" :expected "\"A\"" :actual "(do (require (quote [clojure.string :as st2])) (st2/upper-case \"a\"))" :portability :common} - {:suite "namespaces / unified alias store" :label "alias fn registers + resolves" :expected "\"B\"" :actual "(do (require (quote [clojure.string])) (alias (quote st3) (quote clojure.string)) (st3/upper-case \"b\"))" :portability :common} - {:suite "namespaces / unified alias store" :label "alias fn visible to ns-aliases" :expected "true" :actual "(do (require (quote [clojure.string])) (alias (quote st4) (quote clojure.string)) (pos? (count (filter (fn [[a n]] (= (str a) \"st4\")) (ns-aliases)))))" :portability :common} - {:suite "namespaces / unified alias store" :label "ns-unalias removes both views" :expected "[0 false]" :actual "(do (require (quote [clojure.string :as st5])) (ns-unalias (quote user) (quote st5)) [(count (filter (fn [[a n]] (= (str a) \"st5\")) (ns-aliases))) (boolean (resolve (quote st5/upper-case)))])" :portability :common} - {:suite "namespaces / unified alias store" :label "ns-resolve through alias" :expected "true" :actual "(do (require (quote [clojure.string :as st6])) (var? (ns-resolve (quote user) (quote st6/upper-case))))" :portability :common} - {:suite "namespaces / unified alias store" :label "empty ns-aliases is a map" :expected "true" :actual "(map? (ns-aliases (quote clojure.core)))" :portability :common} - {:suite "*ns* / identity & printing" :label "str of *ns*" :expected "\"user\"" :actual "(str *ns*)" :portability :common} - {:suite "*ns* / identity & printing" :label "ns-name of *ns*" :expected "(quote user)" :actual "(ns-name *ns*)" :portability :common} - {:suite "*ns* / identity & printing" :label "*ns* is find-ns" :expected "true" :actual "(= (ns-name *ns*) (ns-name (find-ns (quote user))))" :portability :common} - {:suite "*ns* / identity & printing" :label "*ns* not a map" :expected "false" :actual "(map? *ns*)" :portability :common} - {:suite "*ns* / identity & printing" :label "tracks in-ns" :expected "\"jolt.test-ns-a\"" :actual "(do (in-ns (quote jolt.test-ns-a)) (str *ns*))" :portability :common} - {:suite "*ns* / identity & printing" :label "in-ns returns ns" :expected "\"jolt.test-ns-b\"" :actual "(str (in-ns (quote jolt.test-ns-b)))" :portability :common} - {:suite "*ns* / identity & printing" :label "usable with ns fns" :expected "true" :actual "(do (require (quote clojure.string)) (alias (quote nsv) (quote clojure.string)) (some? (get (ns-aliases *ns*) (quote nsv))))" :portability :common} - {:suite "*ns* / identity & printing" :label "ns-unalias via *ns*" :expected "true" :actual "(do (require (quote clojure.string)) (alias (quote nsw) (quote clojure.string)) (ns-unalias *ns* (quote nsw)) (nil? (get (ns-aliases *ns*) (quote nsw))))" :portability :common} - {:suite "numbers / arithmetic" :label "add" :expected "6" :actual "(+ 1 2 3)" :portability :common} - {:suite "numbers / arithmetic" :label "add zero args" :expected "0" :actual "(+)" :portability :common} - {:suite "numbers / arithmetic" :label "subtract" :expected "5" :actual "(- 10 3 2)" :portability :common} - {:suite "numbers / arithmetic" :label "negate" :expected "-5" :actual "(- 5)" :portability :common} - {:suite "numbers / arithmetic" :label "multiply" :expected "24" :actual "(* 2 3 4)" :portability :common} - {:suite "numbers / arithmetic" :label "multiply zero args" :expected "1" :actual "(*)" :portability :common} - {:suite "numbers / arithmetic" :label "divide" :expected "2" :actual "(/ 10 5)" :portability :common} - {:suite "numbers / arithmetic" :label "divide to fraction" :expected "1/2" :actual "(/ 1 2)" :portability :common} - {:suite "numbers / arithmetic" :label "inc" :expected "6" :actual "(inc 5)" :portability :common} - {:suite "numbers / arithmetic" :label "dec" :expected "4" :actual "(dec 5)" :portability :common} - {:suite "numbers / arithmetic" :label "quot" :expected "3" :actual "(quot 10 3)" :portability :common} - {:suite "numbers / arithmetic" :label "rem" :expected "1" :actual "(rem 10 3)" :portability :common} - {:suite "numbers / arithmetic" :label "mod" :expected "2" :actual "(mod -1 3)" :portability :common} - {:suite "numbers / arithmetic" :label "rem negative" :expected "-1" :actual "(rem -1 3)" :portability :common} - {:suite "numbers / arithmetic" :label "max" :expected "9" :actual "(max 3 9 1)" :portability :common} - {:suite "numbers / arithmetic" :label "min" :expected "1" :actual "(min 3 9 1)" :portability :common} - {:suite "numbers / arithmetic" :label "abs" :expected "5" :actual "(abs -5)" :portability :common} - {:suite "numbers / arithmetic" :label "promoting + alias" :expected "3" :actual "(+' 1 2)" :portability :common} - {:suite "numbers / arithmetic" :label "inc' alias" :expected "6" :actual "(inc' 5)" :portability :common} - {:suite "numbers / comparison" :label "less than" :expected "true" :actual "(< 1 2 3)" :portability :common} - {:suite "numbers / comparison" :label "less than false" :expected "false" :actual "(< 1 3 2)" :portability :common} - {:suite "numbers / comparison" :label "greater than" :expected "true" :actual "(> 3 2 1)" :portability :common} - {:suite "numbers / comparison" :label "<=" :expected "true" :actual "(<= 1 1 2)" :portability :common} - {:suite "numbers / comparison" :label ">=" :expected "true" :actual "(>= 3 3 2)" :portability :common} - {:suite "numbers / comparison" :label "= numbers" :expected "true" :actual "(= 2 2)" :portability :common} - {:suite "numbers / comparison" :label "= different" :expected "false" :actual "(= 2 3)" :portability :common} - {:suite "numbers / comparison" :label "== numeric" :expected "true" :actual "(== 2 2)" :portability :common} - {:suite "numbers / comparison" :label "not=" :expected "true" :actual "(not= 1 2)" :portability :common} - {:suite "numbers / comparison" :label "compare less" :expected "-1" :actual "(compare 1 2)" :portability :common} - {:suite "numbers / comparison" :label "compare equal" :expected "0" :actual "(compare 1 1)" :portability :common} - {:suite "numbers / comparison" :label "compare greater" :expected "1" :actual "(compare 2 1)" :portability :common} - {:suite "numbers / predicates" :label "zero?" :expected "true" :actual "(zero? 0)" :portability :common} - {:suite "numbers / predicates" :label "pos?" :expected "true" :actual "(pos? 5)" :portability :common} - {:suite "numbers / predicates" :label "neg?" :expected "true" :actual "(neg? -5)" :portability :common} - {:suite "numbers / predicates" :label "even?" :expected "true" :actual "(even? 4)" :portability :common} - {:suite "numbers / predicates" :label "odd?" :expected "true" :actual "(odd? 3)" :portability :common} - {:suite "numbers / predicates" :label "number?" :expected "true" :actual "(number? 5)" :portability :common} - {:suite "numbers / predicates" :label "number? false" :expected "false" :actual "(number? :a)" :portability :common} - {:suite "numbers / predicates" :label "int?" :expected "true" :actual "(int? 5)" :portability :common} - {:suite "numbers / predicates" :label "pos-int?" :expected "true" :actual "(pos-int? 5)" :portability :common} - {:suite "numbers / predicates" :label "neg-int?" :expected "true" :actual "(neg-int? -5)" :portability :common} - {:suite "numbers / predicates" :label "nat-int? zero" :expected "true" :actual "(nat-int? 0)" :portability :common} - {:suite "numbers / predicates" :label "nat-int? neg" :expected "false" :actual "(nat-int? -1)" :portability :common} - {:suite "numbers / predicates" :label "ratio? false" :expected "false" :actual "(ratio? 5)" :portability :common} - {:suite "numbers / floats & symbolic values" :label "read ##Inf" :expected "true" :actual "(= ##Inf (/ 1.0 0.0))" :portability :common} - {:suite "numbers / floats & symbolic values" :label "read ##-Inf" :expected "true" :actual "(< ##-Inf 0)" :portability :common} - {:suite "numbers / floats & symbolic values" :label "##NaN not= itself" :expected "true" :actual "(not (== ##NaN ##NaN))" :portability :common} - {:suite "numbers / floats & symbolic values" :label "float? fractional" :expected "true" :actual "(float? 1.5)" :portability :common} - {:suite "numbers / floats & symbolic values" :label "double? fractional" :expected "true" :actual "(double? 0.25)" :portability :common} - {:suite "numbers / floats & symbolic values" :label "float? integer" :expected "false" :actual "(float? 3)" :portability :common} - {:suite "numbers / floats & symbolic values" :label "float? ##Inf" :expected "true" :actual "(float? ##Inf)" :portability :common} - {:suite "numbers / floats & symbolic values" :label "double? ##NaN" :expected "true" :actual "(double? ##NaN)" :portability :common} - {:suite "numbers / floats & symbolic values" :label "infinite? ##Inf" :expected "true" :actual "(infinite? ##Inf)" :portability :common} - {:suite "numbers / floats & symbolic values" :label "infinite? ##-Inf" :expected "true" :actual "(infinite? ##-Inf)" :portability :common} - {:suite "numbers / floats & symbolic values" :label "infinite? finite" :expected "false" :actual "(infinite? 1.5)" :portability :common} - {:suite "numbers / floats & symbolic values" :label "NaN? ##NaN" :expected "true" :actual "(NaN? ##NaN)" :portability :common} - {:suite "numbers / floats & symbolic values" :label "NaN? number" :expected "false" :actual "(NaN? 1.0)" :portability :common} - {:suite "numbers / floats & symbolic values" :label "int? ##Inf false" :expected "false" :actual "(int? ##Inf)" :portability :common} - {:suite "numbers / floats & symbolic values" :label "pos-int? ##Inf" :expected "false" :actual "(pos-int? ##Inf)" :portability :common} - {:suite "numbers / literal syntax" :label "bigint suffix N" :expected "42N" :actual "42N" :portability :common} - {:suite "numbers / literal syntax" :label "bigint zero" :expected "0N" :actual "0N" :portability :common} - {:suite "numbers / literal syntax" :label "bigdec suffix M" :expected "1.5M" :actual "1.5M" :portability :common} - {:suite "numbers / literal syntax" :label "bigdec int M" :expected "0.0M" :actual "0.0M" :portability :common} - {:suite "numbers / bigdec arithmetic" :label "add (value position)" :expected "4.0M" :actual "(reduce + [1.5M 2.5M])" :portability :common} - {:suite "numbers / bigdec arithmetic" :label "add preserves max scale" :expected "\"4.00\"" :actual "(str (reduce + [1.50M 2.5M]))" :portability :common} - {:suite "numbers / bigdec arithmetic" :label "add three" :expected "7.0M" :actual "(reduce + [1.5M 2.5M 3.0M])" :portability :common} - {:suite "numbers / bigdec arithmetic" :label "subtract (apply)" :expected "3.5M" :actual "(apply - [5M 1.5M])" :portability :common} - {:suite "numbers / bigdec arithmetic" :label "multiply adds scales" :expected "\"3.0000\"" :actual "(str (reduce * [1.50M 2.00M]))" :portability :common} - {:suite "numbers / bigdec arithmetic" :label "long contagion stays bigdec" :expected "3.5M" :actual "(reduce + [1.5M 2])" :portability :common} - {:suite "numbers / bigdec arithmetic" :label "double contagion -> double" :expected "3.5" :actual "(reduce + [1.5M 2.0])" :portability :common} - {:suite "numbers / bigdec arithmetic" :label "exact divide minimal scale" :expected "\"0.25\"" :actual "(str (reduce / [1M 4M]))" :portability :common} - {:suite "numbers / bigdec arithmetic" :label "exact divide whole" :expected "5M" :actual "(reduce / [10M 2M])" :portability :common} - {:suite "numbers / bigdec arithmetic" :label "non-terminating divide throws" :expected ":nonterm" :actual "(try (reduce / [1M 3M]) (catch ArithmeticException _ :nonterm))" :portability :common} - {:suite "numbers / bigdec arithmetic" :label "compare is scale-independent" :expected "0" :actual "(compare 1.0M 1.00M)" :portability :common} - {:suite "numbers / bigdec arithmetic" :label "compare orders by value" :expected "-1" :actual "(compare 1.5M 2.5M)" :portability :common} - {:suite "numbers / bigdec arithmetic" :label "sort uses bigdec compare" :expected "[1M 2M 3M]" :actual "(vec (sort [3M 1M 2M]))" :portability :common} - {:suite "numbers / bigdec call position" :label "add" :expected "4.0M" :actual "(+ 1.5M 2.5M)" :portability :common} - {:suite "numbers / bigdec call position" :label "multiply adds scales" :expected "\"3.0000\"" :actual "(str (* 1.50M 2.00M))" :portability :common} - {:suite "numbers / bigdec call position" :label "subtract" :expected "3.5M" :actual "(- 5M 1.5M)" :portability :common} - {:suite "numbers / bigdec call position" :label "negate" :expected "-1.5M" :actual "(- 1.5M)" :portability :common} - {:suite "numbers / bigdec call position" :label "long contagion" :expected "3.5M" :actual "(+ 1.5M 2)" :portability :common} - {:suite "numbers / bigdec call position" :label "exact divide" :expected "0.25M" :actual "(/ 1M 4M)" :portability :common} - {:suite "numbers / bigdec call position" :label "less-than" :expected "true" :actual "(< 1.5M 2.5M)" :portability :common} - {:suite "numbers / bigdec call position" :label "greater-than false" :expected "false" :actual "(> 1.5M 2.5M)" :portability :common} - {:suite "numbers / bigdec call position" :label "zero?" :expected "true" :actual "(zero? 0M)" :portability :common} - {:suite "numbers / bigdec call position" :label "pos?" :expected "true" :actual "(pos? 1.5M)" :portability :common} - {:suite "numbers / bigdec call position" :label "neg? false" :expected "false" :actual "(neg? 1.5M)" :portability :common} - {:suite "numbers / bigdec call position" :label "quot truncates to scale 0" :expected "3M" :actual "(quot 7M 2M)" :portability :common} - {:suite "numbers / bigdec call position" :label "rem" :expected "1M" :actual "(rem 7M 2M)" :portability :common} - {:suite "numbers / bigdec call position" :label "let-bound operands" :expected "4.0M" :actual "(let [a 1.5M b 2.5M] (+ a b))" :portability :common} - {:suite "numbers / bigdec call position" :label "nested arithmetic propagates" :expected "6.0M" :actual "(+ (* 1.5M 2M) 3M)" :portability :common} - {:suite "numbers / bigdec call position" :label "non-terminating divide throws" :expected ":nonterm" :actual "(try (/ 1M 3M) (catch ArithmeticException _ :nonterm))" :portability :common} - {:suite "numbers / bigdec call position" :label "min" :expected "1M" :actual "(min 1M 2M)" :portability :common} - {:suite "numbers / bigdec call position" :label "max of three" :expected "3M" :actual "(max 1M 2M 3M)" :portability :common} - {:suite "numbers / bigdec call position" :label "min returns the operand, scale intact" :expected "\"1.50\"" :actual "(str (min 1.50M 2M))" :portability :common} - {:suite "numbers / bigdec call position" :label "max tie keeps second operand" :expected "\"1.50\"" :actual "(str (max 1.5M 1.50M))" :portability :common} - {:suite "numbers / bigdec arithmetic" :label "max (value position)" :expected "3M" :actual "(reduce max [1M 3M 2M])" :portability :common} - {:suite "numbers / bigdec arithmetic" :label "min (apply)" :expected "1M" :actual "(apply min [3M 1M 2M])" :portability :common} - {:suite "numbers / literal syntax" :label "ratio -> double" :expected "1/2" :actual "1/2" :portability :common} - {:suite "numbers / literal syntax" :label "ratio 3/4" :expected "3/4" :actual "3/4" :portability :common} - {:suite "numbers / literal syntax" :label "neg ratio" :expected "-1/2" :actual "-1/2" :portability :common} - {:suite "numbers / literal syntax" :label "radix binary" :expected "10" :actual "2r1010" :portability :common} - {:suite "numbers / literal syntax" :label "radix hex-ish" :expected "255" :actual "16rFF" :portability :common} - {:suite "numbers / literal syntax" :label "radix base36" :expected "35" :actual "36rZ" :portability :common} - {:suite "numbers / literal syntax" :label "hex" :expected "255" :actual "0xFF" :portability :common} - {:suite "numbers / literal syntax" :label "exponent" :expected "1000.0" :actual "1e3" :portability :common} - {:suite "numbers / literal syntax" :label "exponent neg" :expected "0.015" :actual "1.5e-2" :portability :common} - {:suite "numbers / strictness (throws like Clojure)" :label "odd? nil" :expected :throws :actual "(odd? nil)" :portability :common} - {:suite "numbers / strictness (throws like Clojure)" :label "odd? fractional" :expected :throws :actual "(odd? 1.5)" :portability :common} - {:suite "numbers / strictness (throws like Clojure)" :label "even? inf" :expected :throws :actual "(even? ##Inf)" :portability :common} - {:suite "numbers / strictness (throws like Clojure)" :label "zero? nil" :expected :throws :actual "(zero? nil)" :portability :common} - {:suite "numbers / strictness (throws like Clojure)" :label "pos? false" :expected :throws :actual "(pos? false)" :portability :common} - {:suite "numbers / strictness (throws like Clojure)" :label "neg? keyword" :expected :throws :actual "(neg? :a)" :portability :common} - {:suite "numbers / strictness (throws like Clojure)" :label "< nil" :expected :throws :actual "(< nil 1)" :portability :common} - {:suite "numbers / strictness (throws like Clojure)" :label "> with nil" :expected :throws :actual "(> 1 nil)" :portability :common} - {:suite "numbers / strictness (throws like Clojure)" :label "max non-number" :expected :throws :actual "(max 1 nil)" :portability :common} - {:suite "numbers / strictness (throws like Clojure)" :label "quot by zero" :expected :throws :actual "(quot 10 0)" :portability :common} - {:suite "numbers / strictness (throws like Clojure)" :label "quot inf" :expected :throws :actual "(quot ##Inf 1)" :portability :common} - {:suite "numbers / strictness (throws like Clojure)" :label "< arity-1 any" :expected "true" :actual "(< :anything)" :portability :common} - {:suite "numbers / strictness (throws like Clojure)" :label "odd? ok" :expected "true" :actual "(odd? 3)" :portability :common} - {:suite "numbers / strictness (throws like Clojure)" :label "< ok" :expected "true" :actual "(< 1 2 3)" :portability :common} - {:suite "numbers / strictness (throws like Clojure)" :label "quot ok" :expected "3" :actual "(quot 10 3)" :portability :common} - {:suite "numbers / printing of inf & nan" :label "str Infinity" :expected "\"Infinity\"" :actual "(str ##Inf)" :portability :common} - {:suite "numbers / printing of inf & nan" :label "str -Infinity" :expected "\"-Infinity\"" :actual "(str ##-Inf)" :portability :common} - {:suite "numbers / printing of inf & nan" :label "str NaN" :expected "\"NaN\"" :actual "(str ##NaN)" :portability :common} - {:suite "numbers / printing of inf & nan" :label "pr-str Infinity" :expected "\"##Inf\"" :actual "(pr-str ##Inf)" :portability :common} - {:suite "numbers / printing of inf & nan" :label "inf inside coll" :expected "\"[##Inf]\"" :actual "(str [##Inf])" :portability :common} - {:suite "numbers / bit-ops & math" :label "bit-and" :expected "4" :actual "(bit-and 12 6)" :portability :common} - {:suite "numbers / bit-ops & math" :label "bit-or" :expected "14" :actual "(bit-or 12 6)" :portability :common} - {:suite "numbers / bit-ops & math" :label "bit-xor" :expected "10" :actual "(bit-xor 12 6)" :portability :common} - {:suite "numbers / bit-ops & math" :label "bit-shift-left" :expected "8" :actual "(bit-shift-left 1 3)" :portability :common} - {:suite "numbers / bit-ops & math" :label "bit-shift-right" :expected "2" :actual "(bit-shift-right 8 2)" :portability :common} - {:suite "numbers / bit-ops & math" :label "bit-set" :expected "8" :actual "(bit-set 0 3)" :portability :common} - {:suite "numbers / bit-ops & math" :label "bit-clear" :expected "13" :actual "(bit-clear 15 1)" :portability :common} - {:suite "numbers / bit-ops & math" :label "bit-test true" :expected "true" :actual "(bit-test 4 2)" :portability :common} - {:suite "numbers / bit-ops & math" :label "bigint 64-bit" :expected "\"9000000000\"" :actual "(str (bigint 9000000000))" :portability :common} - {:suite "numbers / random (invariants — non-deterministic)" :label "rand-int in range" :expected "true" :actual "(let [r (rand-int 5)] (and (integer? r) (>= r 0) (< r 5)))" :portability :common} - {:suite "numbers / random (invariants — non-deterministic)" :label "rand-int zero" :expected "0" :actual "(rand-int 1)" :portability :common} - {:suite "numbers / random (invariants — non-deterministic)" :label "rand in [0,1)" :expected "true" :actual "(let [r (rand)] (and (>= r 0) (< r 1)))" :portability :common} - {:suite "numbers / random (invariants — non-deterministic)" :label "rand n in [0,n)" :expected "true" :actual "(let [r (rand 10)] (and (>= r 0) (< r 10)))" :portability :common} - {:suite "numbers / random (invariants — non-deterministic)" :label "rand-nth member" :expected "true" :actual "(contains? #{:a :b :c} (rand-nth [:a :b :c]))" :portability :common} - {:suite "numbers / random (invariants — non-deterministic)" :label "rand-nth single" :expected ":x" :actual "(rand-nth [:x])" :portability :common} - {:suite "numbers / parse fns (1.11)" :label "parse-long" :expected "42" :actual "(parse-long \"42\")" :portability :common} - {:suite "numbers / parse fns (1.11)" :label "parse-long negative" :expected "-7" :actual "(parse-long \"-7\")" :portability :common} - {:suite "numbers / parse fns (1.11)" :label "parse-long plus" :expected "7" :actual "(parse-long \"+7\")" :portability :common} - {:suite "numbers / parse fns (1.11)" :label "parse-long float nil" :expected "nil" :actual "(parse-long \"1.5\")" :portability :common} - {:suite "numbers / parse fns (1.11)" :label "parse-long hex nil" :expected "nil" :actual "(parse-long \"0x10\")" :portability :common} - {:suite "numbers / parse fns (1.11)" :label "parse-long empty nil" :expected "nil" :actual "(parse-long \"\")" :portability :common} - {:suite "numbers / parse fns (1.11)" :label "parse-long junk nil" :expected "nil" :actual "(parse-long \"12ab\")" :portability :common} - {:suite "numbers / parse fns (1.11)" :label "parse-long throws" :expected :throws :actual "(parse-long 42)" :portability :common} - {:suite "numbers / parse fns (1.11)" :label "parse-double" :expected "1.5" :actual "(parse-double \"1.5\")" :portability :common} - {:suite "numbers / parse fns (1.11)" :label "parse-double int" :expected "4.0" :actual "(parse-double \"4\")" :portability :common} - {:suite "numbers / parse fns (1.11)" :label "parse-double sci" :expected "1500.0" :actual "(parse-double \"1.5e3\")" :portability :common} - {:suite "numbers / parse fns (1.11)" :label "parse-double neg" :expected "-0.5" :actual "(parse-double \"-0.5\")" :portability :common} - {:suite "numbers / parse fns (1.11)" :label "parse-double junk" :expected "nil" :actual "(parse-double \"abc\")" :portability :common} - {:suite "numbers / parse fns (1.11)" :label "parse-double trail" :expected "nil" :actual "(parse-double \"1.5x\")" :portability :common} - {:suite "numbers / parse fns (1.11)" :label "parse-double throws" :expected :throws :actual "(parse-double :k)" :portability :common} - {:suite "numbers / parse fns (1.11)" :label "parse-boolean true" :expected "true" :actual "(parse-boolean \"true\")" :portability :common} - {:suite "numbers / parse fns (1.11)" :label "parse-boolean false" :expected "false" :actual "(parse-boolean \"false\")" :portability :common} - {:suite "numbers / parse fns (1.11)" :label "parse-boolean case" :expected "nil" :actual "(parse-boolean \"True\")" :portability :common} - {:suite "numbers / parse fns (1.11)" :label "parse-boolean junk" :expected "nil" :actual "(parse-boolean \"yes\")" :portability :common} - {:suite "numbers / parse fns (1.11)" :label "parse-boolean throws" :expected :throws :actual "(parse-boolean true)" :portability :common} - {:suite "numbers / promoting & unchecked aliases" :label "+'" :expected "3" :actual "(+' 1 2)" :portability :common} - {:suite "numbers / promoting & unchecked aliases" :label "-'" :expected "3" :actual "(-' 5 2)" :portability :common} - {:suite "numbers / promoting & unchecked aliases" :label "*'" :expected "12" :actual "(*' 3 4)" :portability :common} - {:suite "numbers / promoting & unchecked aliases" :label "inc'" :expected "6" :actual "(inc' 5)" :portability :common} - {:suite "numbers / promoting & unchecked aliases" :label "dec'" :expected "4" :actual "(dec' 5)" :portability :common} - {:suite "numbers / promoting & unchecked aliases" :label "unchecked-add" :expected "5" :actual "(unchecked-add 2 3)" :portability :common} - {:suite "numbers / promoting & unchecked aliases" :label "unchecked-add-int" :expected "5" :actual "(unchecked-add-int 2 3)" :portability :common} - {:suite "numbers / promoting & unchecked aliases" :label "unchecked-subtract" :expected "3" :actual "(unchecked-subtract 5 2)" :portability :common} - {:suite "numbers / promoting & unchecked aliases" :label "unchecked-subtract-int" :expected "3" :actual "(unchecked-subtract-int 5 2)" :portability :common} - {:suite "numbers / promoting & unchecked aliases" :label "unchecked-multiply" :expected "12" :actual "(unchecked-multiply 3 4)" :portability :common} - {:suite "numbers / promoting & unchecked aliases" :label "unchecked-multiply-int" :expected "12" :actual "(unchecked-multiply-int 3 4)" :portability :common} - {:suite "numbers / promoting & unchecked aliases" :label "unchecked-negate" :expected "-5" :actual "(unchecked-negate 5)" :portability :common} - {:suite "numbers / promoting & unchecked aliases" :label "unchecked-negate-int" :expected "-5" :actual "(unchecked-negate-int 5)" :portability :common} - {:suite "numbers / promoting & unchecked aliases" :label "unchecked-inc" :expected "2" :actual "(unchecked-inc 1)" :portability :common} - {:suite "numbers / promoting & unchecked aliases" :label "unchecked-inc-int" :expected "2" :actual "(unchecked-inc-int 1)" :portability :common} - {:suite "numbers / promoting & unchecked aliases" :label "unchecked-dec" :expected "0" :actual "(unchecked-dec 1)" :portability :common} - {:suite "numbers / promoting & unchecked aliases" :label "unchecked-dec-int" :expected "0" :actual "(unchecked-dec-int 1)" :portability :common} - {:suite "numbers / promoting & unchecked aliases" :label "unchecked-divide-int" :expected "3" :actual "(unchecked-divide-int 7 2)" :portability :common} - {:suite "numbers / promoting & unchecked aliases" :label "unchecked-divide-int negative truncates toward zero" :expected "-3" :actual "(unchecked-divide-int -7 2)" :portability :common} - {:suite "numbers / promoting & unchecked aliases" :label "unchecked-divide-int by zero throws" :expected :throws :actual "(unchecked-divide-int 1 0)" :portability :common} - {:suite "numbers / promoting & unchecked aliases" :label "unchecked-remainder-int" :expected "1" :actual "(unchecked-remainder-int 7 2)" :portability :common} - {:suite "numbers / promoting & unchecked aliases" :label "unchecked-remainder-int negative" :expected "-1" :actual "(unchecked-remainder-int -7 2)" :portability :common} - {:suite "numbers / promoting & unchecked aliases" :label "unchecked-int truncates" :expected "3" :actual "(unchecked-int 3.7)" :portability :common} - {:suite "numbers / promoting & unchecked aliases" :label "unchecked-int negative" :expected "-3" :actual "(unchecked-int -3.7)" :portability :common} - {:suite "numbers / promoting & unchecked aliases" :label "unchecked-add on ratios does not wrap to long" :expected "4/3" :actual "(unchecked-add 2/3 2/3)" :portability :common} - {:suite "numbers / promoting & unchecked aliases" :label "unchecked-multiply ratio by int" :expected "4/3" :actual "(unchecked-multiply 2/3 2)" :portability :common} - {:suite "numbers / promoting & unchecked aliases" :label "unchecked-negate ratio" :expected "-2/3" :actual "(unchecked-negate 2/3)" :portability :common} - {:suite "numbers / promoting & unchecked aliases" :label "unchecked-add ratios summing to zero" :expected "0" :actual "(unchecked-add 1/2 -1/2)" :portability :common} - {:suite "numbers / promoting & unchecked aliases" :label "unchecked-inc ratio" :expected "3/2" :actual "(unchecked-inc 1/2)" :portability :common} - {:suite "numbers / promoting & unchecked aliases" :label "unchecked-long" :expected "3" :actual "(unchecked-long 3.7)" :portability :common} - {:suite "numbers / promoting & unchecked aliases" :label "int? on integer" :expected "true" :actual "(int? 5)" :portability :common} - {:suite "numbers / promoting & unchecked aliases" :label "int? on double" :expected "false" :actual "(int? 5.5)" :portability :common} - {:suite "numbers / promoting & unchecked aliases" :label "int? on non-number" :expected "false" :actual "(int? \"5\")" :portability :common} - {:suite "numbers / promoting & unchecked aliases" :label "num passes a number through" :expected "5" :actual "(num 5)" :portability :common} - {:suite "numbers / promoting & unchecked aliases" :label "num on a double" :expected "5.5" :actual "(num 5.5)" :portability :common} - {:suite "numbers / promoting & unchecked aliases" :label "num throws on non-number" :expected :throws :actual "(num \"x\")" :portability :common} - {:suite "numbers / == numeric equality" :label "== single arg" :expected "true" :actual "(== :a)" :portability :common} - {:suite "numbers / == numeric equality" :label "== equal" :expected "true" :actual "(== 2 2)" :portability :common} - {:suite "numbers / == numeric equality" :label "== unequal" :expected "false" :actual "(== 2 3)" :portability :common} - {:suite "numbers / == numeric equality" :label "== chained" :expected "true" :actual "(== 2 2 2)" :portability :common} - {:suite "numbers / == numeric equality" :label "== chained unequal" :expected "false" :actual "(== 2 2 3)" :portability :common} - {:suite "numbers / == numeric equality" :label "== int and double" :expected "true" :actual "(== 1 1.0)" :portability :common} - {:suite "numbers / == numeric equality" :label "== throws on non-number" :expected :throws :actual "(== 1 :a)" :portability :common} - {:suite "numbers / == numeric equality" :label "== throws on two keywords" :expected :throws :actual "(== :a :a)" :portability :common} - {:suite "numbers / variadic bit ops" :label "bit-and 2" :expected "4" :actual "(bit-and 12 6)" :portability :common} - {:suite "numbers / variadic bit ops" :label "bit-and 3" :expected "4" :actual "(bit-and 12 6 7)" :portability :common} - {:suite "numbers / variadic bit ops" :label "bit-and 4" :expected "0" :actual "(bit-and 12 6 7 3)" :portability :common} - {:suite "numbers / variadic bit ops" :label "bit-or 3" :expected "7" :actual "(bit-or 1 2 4)" :portability :common} - {:suite "numbers / variadic bit ops" :label "bit-xor 3" :expected "7" :actual "(bit-xor 1 2 4)" :portability :common} - {:suite "numbers / variadic bit ops" :label "bit-xor folds left" :expected "1" :actual "(bit-xor 5 6 2)" :portability :common} - {:suite "numbers / variadic bit ops" :label "bit-and-not 2" :expected "8" :actual "(bit-and-not 12 6)" :portability :common} - {:suite "numbers / variadic bit ops" :label "bit-and-not 3" :expected "8" :actual "(bit-and-not 12 6 3)" :portability :common} - {:suite "numbers / variadic bit ops" :label "bit-and single arg throws" :expected :throws :actual "(bit-and 5)" :portability :common} - {:suite "numbers / variadic bit ops" :label "bit-or keeps binary fast path" :expected "3" :actual "(bit-or 1 2)" :portability :common} - {:suite "numbers / variadic bit ops" :label "bit-not" :expected "-6" :actual "(bit-not 5)" :portability :common} - {:suite "numbers / variadic bit ops" :label "bit-and in value position" :expected "8" :actual "(reduce bit-and [15 9 12])" :portability :common} - {:suite "numbers / variadic bit ops" :label "bit-xor in value position" :expected "0" :actual "(reduce bit-xor 0 [1 2 3])" :portability :common} - {:suite "numbers / variadic bit ops" :label "bit-or via apply" :expected "7" :actual "(apply bit-or [1 2 4])" :portability :common} - {:suite "numbers / variadic bit ops" :label "unsigned-shift over a full 64-bit value" :expected "17179869183" :actual "(unsigned-bit-shift-right -1 30)" :portability :common} - ;; var-reference cell caching (runtime path): a ref inside a fn caches the - ;; resolved cell, but stays correct under redefinition (cell root mutated in - ;; place) and dynamic binding (read goes through the binding-aware path). - {:suite "vars / cached reference stays correct" :label "redefinition is seen through a cached ref" :expected "2" :actual "(do (def x 1) (defn f [] x) (def x 2) (f))" :portability :common} - {:suite "vars / cached reference stays correct" :label "dynamic binding is seen through a cached ref" :expected "[1 9 1]" :actual "(do (def ^:dynamic *d* 1) (defn g [] *d*) [(g) (binding [*d* 9] (g)) (g)])" :portability :common} - {:suite "vars / cached reference stays correct" :label "forward reference resolves once the var is defined" :expected "42" :actual "(do (defn a [] (b)) (defn b [] 42) (a))" :portability :common} - {:suite "predicates / nil & boolean" :label "nil? true" :expected "true" :actual "(nil? nil)" :portability :common} - {:suite "predicates / nil & boolean" :label "nil? false" :expected "false" :actual "(nil? 0)" :portability :common} - {:suite "predicates / nil & boolean" :label "some? true" :expected "true" :actual "(some? 0)" :portability :common} - {:suite "predicates / nil & boolean" :label "some? on nil" :expected "false" :actual "(some? nil)" :portability :common} - {:suite "predicates / nil & boolean" :label "true?" :expected "true" :actual "(true? true)" :portability :common} - {:suite "predicates / nil & boolean" :label "false?" :expected "true" :actual "(false? false)" :portability :common} - {:suite "predicates / nil & boolean" :label "boolean? true" :expected "true" :actual "(boolean? false)" :portability :common} - {:suite "predicates / nil & boolean" :label "not nil" :expected "true" :actual "(not nil)" :portability :common} - {:suite "predicates / nil & boolean" :label "not 0 is false" :expected "false" :actual "(not 0)" :portability :common} - {:suite "predicates / nil & boolean" :label "boolean of nil" :expected "false" :actual "(boolean nil)" :portability :common} - {:suite "predicates / nil & boolean" :label "boolean of value" :expected "true" :actual "(boolean 5)" :portability :common} - {:suite "predicates / types" :label "string?" :expected "true" :actual "(string? \"x\")" :portability :common} - {:suite "predicates / types" :label "number?" :expected "true" :actual "(number? 1)" :portability :common} - {:suite "predicates / types" :label "keyword?" :expected "true" :actual "(keyword? :a)" :portability :common} - {:suite "predicates / types" :label "symbol?" :expected "true" :actual "(symbol? (quote a))" :portability :common} - {:suite "predicates / types" :label "char?" :expected "true" :actual "(char? \\a)" :portability :common} - {:suite "predicates / types" :label "fn? on fn" :expected "true" :actual "(fn? inc)" :portability :common} - {:suite "predicates / types" :label "ifn? on keyword" :expected "true" :actual "(ifn? :a)" :portability :common} - {:suite "predicates / types" :label "vector?" :expected "true" :actual "(vector? [1])" :portability :common} - {:suite "predicates / types" :label "list?" :expected "true" :actual "(list? (list 1))" :portability :common} - {:suite "predicates / types" :label "map?" :expected "true" :actual "(map? {:a 1})" :portability :common} - {:suite "predicates / types" :label "set?" :expected "true" :actual "(set? #{1})" :portability :common} - {:suite "predicates / types" :label "coll? vector" :expected "true" :actual "(coll? [1])" :portability :common} - {:suite "predicates / types" :label "coll? map" :expected "true" :actual "(coll? {:a 1})" :portability :common} - {:suite "predicates / types" :label "coll? on number" :expected "false" :actual "(coll? 1)" :portability :common} - {:suite "predicates / types" :label "seq? list" :expected "true" :actual "(seq? (list 1))" :portability :common} - {:suite "predicates / types" :label "seq? vector" :expected "false" :actual "(seq? [1])" :portability :common} - {:suite "predicates / types" :label "sequential? vector" :expected "true" :actual "(sequential? [1])" :portability :common} - {:suite "predicates / types" :label "associative? map" :expected "true" :actual "(associative? {:a 1})" :portability :common} - {:suite "predicates / types" :label "associative? vec" :expected "true" :actual "(associative? [1])" :portability :common} - {:suite "predicates / types" :label "associative? list" :expected "false" :actual "(associative? '(1 2))" :portability :common} - {:suite "predicates / types" :label "associative? set" :expected "false" :actual "(associative? #{1})" :portability :common} - {:suite "predicates / types" :label "reversible? vec" :expected "true" :actual "(reversible? [1 2])" :portability :common} - {:suite "predicates / types" :label "reversible? list" :expected "false" :actual "(reversible? '(1 2))" :portability :common} - {:suite "predicates / types" :label "reversible? smap" :expected "true" :actual "(reversible? (sorted-map :a 1))" :portability :common} - {:suite "predicates / types" :label "reversible? hmap" :expected "false" :actual "(reversible? (hash-map :a 1))" :portability :common} - {:suite "predicates / types" :label "indexed? vector" :expected "true" :actual "(indexed? [1])" :portability :common} - {:suite "predicates / types" :label "counted? vector" :expected "true" :actual "(counted? [1])" :portability :common} - {:suite "predicates / idents" :label "ident? keyword" :expected "true" :actual "(ident? :a)" :portability :common} - {:suite "predicates / idents" :label "ident? symbol" :expected "true" :actual "(ident? (quote a))" :portability :common} - {:suite "predicates / idents" :label "simple-keyword?" :expected "true" :actual "(simple-keyword? :a)" :portability :common} - {:suite "predicates / idents" :label "qualified-keyword?" :expected "true" :actual "(qualified-keyword? :a/b)" :portability :common} - {:suite "predicates / idents" :label "simple-symbol?" :expected "true" :actual "(simple-symbol? (quote a))" :portability :common} - {:suite "predicates / idents" :label "qualified-symbol?" :expected "true" :actual "(qualified-symbol? (quote a/b))" :portability :common} - {:suite "predicates / idents" :label "name of keyword" :expected "\"a\"" :actual "(name :a)" :portability :common} - {:suite "predicates / idents" :label "name of qualified" :expected "\"b\"" :actual "(name :a/b)" :portability :common} - {:suite "predicates / idents" :label "namespace" :expected "\"a\"" :actual "(namespace :a/b)" :portability :common} - {:suite "predicates / idents" :label "namespace simple" :expected "nil" :actual "(namespace :a)" :portability :common} - {:suite "predicates / idents" :label "keyword constructor" :expected ":foo" :actual "(keyword \"foo\")" :portability :common} - {:suite "predicates / idents" :label "keyword ns + name" :expected ":a/b" :actual "(keyword \"a\" \"b\")" :portability :common} - {:suite "predicates / idents" :label "symbol constructor" :expected "(quote x)" :actual "(symbol \"x\")" :portability :common} - {:suite "predicates / idents" :label "name of string" :expected "\"s\"" :actual "(name \"s\")" :portability :common} - {:suite "predicates / overlay-migrated" :label "not-any? true" :expected "true" :actual "(not-any? even? [1 3 5])" :portability :common} - {:suite "predicates / overlay-migrated" :label "not-any? false" :expected "false" :actual "(not-any? even? [1 2 3])" :portability :common} - {:suite "predicates / overlay-migrated" :label "not-every? true" :expected "true" :actual "(not-every? even? [2 4 5])" :portability :common} - {:suite "predicates / overlay-migrated" :label "not-every? false" :expected "false" :actual "(not-every? even? [2 4 6])" :portability :common} - {:suite "predicates / overlay-migrated" :label "ident? number" :expected "false" :actual "(ident? 1)" :portability :common} - {:suite "predicates / overlay-migrated" :label "qualified-ident?" :expected "true" :actual "(qualified-ident? :a/b)" :portability :common} - {:suite "predicates / overlay-migrated" :label "qualified-ident? no" :expected "false" :actual "(qualified-ident? :a)" :portability :common} - {:suite "predicates / overlay-migrated" :label "simple-ident?" :expected "true" :actual "(simple-ident? :a)" :portability :common} - {:suite "predicates / overlay-migrated" :label "ratio?" :expected "false" :actual "(ratio? 3)" :portability :common} - {:suite "predicates / overlay-migrated" :label "decimal?" :expected "false" :actual "(decimal? 3)" :portability :common} - {:suite "predicates / overlay-migrated" :label "class? of value" :expected "false" :actual "(class? \"s\")" :portability :common} - {:suite "predicates / overlay-migrated" :label "class? of symbol" :expected "false" :actual "(class? 'java.lang.String)" :portability :jvm} - {:suite "predicates / overlay-migrated" :label "rational? int" :expected "true" :actual "(rational? 3)" :portability :common} - {:suite "predicates / overlay-migrated" :label "rational? float" :expected "false" :actual "(rational? 3.5)" :portability :common} - {:suite "predicates / overlay-migrated" :label "nat-int? zero" :expected "true" :actual "(nat-int? 0)" :portability :common} - {:suite "predicates / overlay-migrated" :label "nat-int? neg" :expected "false" :actual "(nat-int? -1)" :portability :common} - {:suite "predicates / overlay-migrated" :label "pos-int?" :expected "true" :actual "(pos-int? 5)" :portability :common} - {:suite "predicates / overlay-migrated" :label "neg-int?" :expected "true" :actual "(neg-int? -3)" :portability :common} - {:suite "predicates / overlay-migrated" :label "NaN? on nan" :expected "true" :actual "(NaN? (/ 0.0 0.0))" :portability :common} - {:suite "predicates / overlay-migrated" :label "NaN? on number" :expected "false" :actual "(NaN? 5)" :portability :common} - {:suite "predicates / overlay-migrated" :label "abs negative" :expected "3" :actual "(abs -3)" :portability :common} - {:suite "predicates / overlay-migrated" :label "abs positive" :expected "2.5" :actual "(abs 2.5)" :portability :common} - {:suite "predicates / overlay-migrated" :label "object?" :expected "false" :actual "(object? 1)" :portability :common} - {:suite "predicates / overlay-migrated" :label "undefined?" :expected "false" :actual "(undefined? 1)" :portability :common} - {:suite "predicates / overlay-migrated" :label "keyword-identical?" :expected "true" :actual "(keyword-identical? :a :a)" :portability :common} - {:suite "predicates / overlay-migrated" :label "keyword-identical? no" :expected "false" :actual "(keyword-identical? :a :b)" :portability :common} - {:suite "predicates / map? & coll? strictness" :label "map? symbol" :expected "false" :actual "(map? (quote sym))" :portability :common} - {:suite "predicates / map? & coll? strictness" :label "map? char" :expected "false" :actual "(map? \\a)" :portability :common} - {:suite "predicates / map? & coll? strictness" :label "map? uuid" :expected "false" :actual "(map? (random-uuid))" :portability :common} - {:suite "predicates / map? & coll? strictness" :label "map? literal" :expected "true" :actual "(map? {:a 1})" :portability :common} - {:suite "predicates / map? & coll? strictness" :label "map? hash-map" :expected "true" :actual "(map? (hash-map :a 1))" :portability :common} - {:suite "predicates / map? & coll? strictness" :label "map? sorted-map" :expected "true" :actual "(map? (sorted-map :a 1))" :portability :common} - {:suite "predicates / map? & coll? strictness" :label "map? record" :expected "true" :actual "(do (defrecord Mr [a]) (map? (->Mr 1)))" :portability :common} - {:suite "predicates / map? & coll? strictness" :label "map? sorted-set" :expected "false" :actual "(map? (sorted-set 1))" :portability :common} - {:suite "predicates / map? & coll? strictness" :label "map? vector" :expected "false" :actual "(map? [1])" :portability :common} - {:suite "predicates / map? & coll? strictness" :label "coll? symbol" :expected "false" :actual "(coll? (quote sym))" :portability :common} - {:suite "predicates / map? & coll? strictness" :label "coll? char" :expected "false" :actual "(coll? \\a)" :portability :common} - {:suite "predicates / map? & coll? strictness" :label "coll? uuid" :expected "false" :actual "(coll? (random-uuid))" :portability :common} - {:suite "predicates / map? & coll? strictness" :label "coll? keyword" :expected "false" :actual "(coll? :k)" :portability :common} - {:suite "predicates / map? & coll? strictness" :label "coll? string" :expected "false" :actual "(coll? \"s\")" :portability :common} - {:suite "predicates / map? & coll? strictness" :label "coll? map literal" :expected "true" :actual "(coll? {:a 1})" :portability :common} - {:suite "predicates / map? & coll? strictness" :label "coll? sorted-map" :expected "true" :actual "(coll? (sorted-map :a 1))" :portability :common} - {:suite "predicates / map? & coll? strictness" :label "coll? sorted-set" :expected "true" :actual "(coll? (sorted-set 1))" :portability :common} - {:suite "predicates / map? & coll? strictness" :label "coll? record" :expected "true" :actual "(do (defrecord Cr [a]) (coll? (->Cr 1)))" :portability :common} - {:suite "predicates / map? & coll? strictness" :label "coll? vector" :expected "true" :actual "(coll? [1])" :portability :common} - {:suite "predicates / map? & coll? strictness" :label "coll? list" :expected "true" :actual "(coll? (list 1))" :portability :common} - {:suite "predicates / map? & coll? strictness" :label "coll? set" :expected "true" :actual "(coll? #{1})" :portability :common} - {:suite "predicates / map? & coll? strictness" :label "coll? lazy seq" :expected "true" :actual "(coll? (map inc [1]))" :portability :common} - {:suite "predicates / tagged-value" :label "atom? yes" :expected "true" :actual "(atom? (atom 1))" :portability :common} - {:suite "predicates / tagged-value" :label "atom? no" :expected "false" :actual "(atom? 1)" :portability :common} - {:suite "predicates / tagged-value" :label "volatile? yes" :expected "true" :actual "(volatile? (volatile! 1))" :portability :common} - {:suite "predicates / tagged-value" :label "volatile? no" :expected "false" :actual "(volatile? (atom 1))" :portability :common} - {:suite "predicates / tagged-value" :label "record? yes" :expected "true" :actual "(do (defrecord Rp [a]) (record? (->Rp 1)))" :portability :common} - {:suite "predicates / tagged-value" :label "record? no map" :expected "false" :actual "(record? {:a 1})" :portability :common} - {:suite "predicates / tagged-value" :label "record? no nil" :expected "false" :actual "(record? nil)" :portability :common} - {:suite "predicates / tagged-value" :label "tagged-literal? yes" :expected "true" :actual "(tagged-literal? (tagged-literal (quote inst) \"2020\"))" :portability :common} - {:suite "predicates / tagged-value" :label "tagged-literal? no" :expected "false" :actual "(tagged-literal? 1)" :portability :common} - {:suite "predicates / tagged-value" :label "reader-conditional? no" :expected "false" :actual "(reader-conditional? 1)" :portability :common} - {:suite "predicates / tagged-value" :label "chunked-seq? true for a vector seq" :expected "true" :actual "(chunked-seq? (seq [1 2 3]))" :portability :common} - {:suite "predicates / equality & identity" :label "= same" :expected "true" :actual "(= 1 1)" :portability :common} - {:suite "predicates / equality & identity" :label "= vectors" :expected "true" :actual "(= [1 2] [1 2])" :portability :common} - {:suite "predicates / equality & identity" :label "= vector & list" :expected "true" :actual "(= [1 2] (list 1 2))" :portability :common} - {:suite "predicates / equality & identity" :label "= maps" :expected "true" :actual "(= {:a 1} {:a 1})" :portability :common} - {:suite "predicates / equality & identity" :label "= sets" :expected "true" :actual "(= #{1 2} #{2 1})" :portability :common} - {:suite "predicates / equality & identity" :label "= nested" :expected "true" :actual "(= {:a [1 2]} {:a [1 2]})" :portability :common} - {:suite "predicates / equality & identity" :label "not= differs" :expected "true" :actual "(not= [1 2] [1 3])" :portability :common} - {:suite "predicates / equality & identity" :label "identical? same kw" :expected "true" :actual "(identical? :a :a)" :portability :common} - {:suite "predicates / equality & identity" :label "compare strings" :expected "-1" :actual "(compare \"a\" \"b\")" :portability :common} - {:suite "predicates / seqable, reduced & emptiness" :label "seqable? vector" :expected "true" :actual "(seqable? [1])" :portability :common} - {:suite "predicates / seqable, reduced & emptiness" :label "seqable? map" :expected "true" :actual "(seqable? {:a 1})" :portability :common} - {:suite "predicates / seqable, reduced & emptiness" :label "seqable? string" :expected "true" :actual "(seqable? \"s\")" :portability :common} - {:suite "predicates / seqable, reduced & emptiness" :label "seqable? nil" :expected "true" :actual "(seqable? nil)" :portability :common} - {:suite "predicates / seqable, reduced & emptiness" :label "seqable? number" :expected "false" :actual "(seqable? 5)" :portability :common} - {:suite "predicates / seqable, reduced & emptiness" :label "integer? int" :expected "true" :actual "(integer? 5)" :portability :common} - {:suite "predicates / seqable, reduced & emptiness" :label "integer? fraction" :expected "false" :actual "(integer? 5.5)" :portability :common} - {:suite "predicates / seqable, reduced & emptiness" :label "reduced? wrapped" :expected "true" :actual "(reduced? (reduced 1))" :portability :common} - {:suite "predicates / seqable, reduced & emptiness" :label "reduced? plain" :expected "false" :actual "(reduced? 1)" :portability :common} - {:suite "predicates / seqable, reduced & emptiness" :label "deref reduced" :expected "9" :actual "(deref (reduced 9))" :portability :common} - {:suite "predicates / seqable, reduced & emptiness" :label "unreduced wrapped" :expected "9" :actual "(unreduced (reduced 9))" :portability :common} - {:suite "predicates / seqable, reduced & emptiness" :label "unreduced plain" :expected "9" :actual "(unreduced 9)" :portability :common} - {:suite "predicates / seqable, reduced & emptiness" :label "not-empty full" :expected "[1]" :actual "(not-empty [1])" :portability :common} - {:suite "predicates / seqable, reduced & emptiness" :label "not-empty empty" :expected "nil" :actual "(not-empty [])" :portability :common} - {:suite "predicates / seqable, reduced & emptiness" :label "not-empty string" :expected "nil" :actual "(not-empty \"\")" :portability :common} - {:suite "predicates / compare, type, any? (stage 3)" :label "compare =" :expected "0" :actual "(compare 1 1)" :portability :common} - {:suite "predicates / compare, type, any? (stage 3)" :label "compare <" :expected "-1" :actual "(compare 1 2)" :portability :common} - {:suite "predicates / compare, type, any? (stage 3)" :label "compare nil first" :expected "-1" :actual "(compare nil 1)" :portability :common} - {:suite "predicates / compare, type, any? (stage 3)" :label "compare nil nil" :expected "0" :actual "(compare nil nil)" :portability :common} - {:suite "predicates / compare, type, any? (stage 3)" :label "compare strings" :expected "-1" :actual "(compare \"a\" \"b\")" :portability :common} - {:suite "predicates / compare, type, any? (stage 3)" :label "compare keywords" :expected "-1" :actual "(compare :a :b)" :portability :common} - {:suite "predicates / compare, type, any? (stage 3)" :label "compare symbols" :expected "-1" :actual "(compare (quote a) (quote b))" :portability :common} - {:suite "predicates / compare, type, any? (stage 3)" :label "compare bools" :expected "-1" :actual "(compare false true)" :portability :common} - {:suite "predicates / compare, type, any? (stage 3)" :label "compare vec length" :expected "-1" :actual "(compare [1 2] [1 2 3])" :portability :common} - {:suite "predicates / compare, type, any? (stage 3)" :label "compare vec elems" :expected "-1" :actual "(compare [1 2] [1 3])" :portability :common} - {:suite "predicates / compare, type, any? (stage 3)" :label "compare cross-type throws" :expected :throws :actual "(compare 1 \"a\")" :portability :common} - {:suite "predicates / compare, type, any? (stage 3)" :label "sort with compare" :expected "[nil 1 3]" :actual "(sort compare [3 nil 1])" :portability :common} - {:suite "predicates / compare, type, any? (stage 3)" :label "type meta override" :expected ":custom" :actual "(type (with-meta [1] {:type :custom}))" :portability :common} - {:suite "predicates / compare, type, any? (stage 3)" :label "type of record" :expected "false" :actual "(do (defrecord TyR [a]) (= (symbol (str (type (->TyR 1)))) (type (->TyR 1))))" :portability :common} - {:suite "predicates / compare, type, any? (stage 3)" :label "any? value" :expected "true" :actual "(any? 5)" :portability :common} - {:suite "predicates / compare, type, any? (stage 3)" :label "any? nil" :expected "true" :actual "(any? nil)" :portability :common} - {:suite "predicates / compare, type, any? (stage 3)" :label "gensym is symbol" :expected "true" :actual "(symbol? (gensym))" :portability :common} - {:suite "predicates / compare, type, any? (stage 3)" :label "gensym prefix" :expected "true" :actual "(do (require (quote [clojure.string :as s])) (s/starts-with? (str (gensym \"p_\")) \"p_\"))" :portability :common} - {:suite "predicates / compare, type, any? (stage 3)" :label "gensym distinct" :expected "false" :actual "(= (gensym) (gensym))" :portability :common} - {:suite "predicates / compare, type, any? (stage 3)" :label "int? Inf false" :expected "false" :actual "(int? ##Inf)" :portability :common} - {:suite "predicates / compare, type, any? (stage 3)" :label "integer? Inf false" :expected "false" :actual "(integer? ##Inf)" :portability :common} - {:suite "predicates / compare, type, any? (stage 3)" :label "integer? NaN false" :expected "false" :actual "(integer? ##NaN)" :portability :common} - {:suite "predicates / ifn?" :label "fn" :expected "true" :actual "(ifn? inc)" :portability :common} - {:suite "predicates / ifn?" :label "keyword" :expected "true" :actual "(ifn? :k)" :portability :common} - {:suite "predicates / ifn?" :label "symbol" :expected "true" :actual "(ifn? (quote s))" :portability :common} - {:suite "predicates / ifn?" :label "map" :expected "true" :actual "(ifn? {})" :portability :common} - {:suite "predicates / ifn?" :label "sorted map" :expected "true" :actual "(ifn? (sorted-map))" :portability :common} - {:suite "predicates / ifn?" :label "set" :expected "true" :actual "(ifn? #{1})" :portability :common} - {:suite "predicates / ifn?" :label "vector" :expected "true" :actual "(ifn? [1])" :portability :common} - {:suite "predicates / ifn?" :label "var" :expected "true" :actual "(ifn? (var first))" :portability :common} - {:suite "predicates / ifn?" :label "list NOT" :expected "false" :actual "(ifn? (list 1 2))" :portability :common} - {:suite "predicates / ifn?" :label "lazy NOT" :expected "false" :actual "(ifn? (map inc [1]))" :portability :common} - {:suite "predicates / ifn?" :label "string NOT" :expected "false" :actual "(ifn? \"s\")" :portability :common} - {:suite "predicates / ifn?" :label "number NOT" :expected "false" :actual "(ifn? 5)" :portability :common} - {:suite "predicates / ifn?" :label "nil NOT" :expected "false" :actual "(ifn? nil)" :portability :common} - {:suite "predicates / numeric guards & every? (overlay moves)" :label "zero? zero" :expected "true" :actual "(zero? 0)" :portability :common} - {:suite "predicates / numeric guards & every? (overlay moves)" :label "zero? nonzero" :expected "false" :actual "(zero? 3)" :portability :common} - {:suite "predicates / numeric guards & every? (overlay moves)" :label "zero? throws" :expected :throws :actual "(zero? :a)" :portability :common} - {:suite "predicates / numeric guards & every? (overlay moves)" :label "zero? throws on nil" :expected :throws :actual "(zero? nil)" :portability :common} - {:suite "predicates / numeric guards & every? (overlay moves)" :label "pos? positive" :expected "true" :actual "(pos? 2)" :portability :common} - {:suite "predicates / numeric guards & every? (overlay moves)" :label "pos? zero" :expected "false" :actual "(pos? 0)" :portability :common} - {:suite "predicates / numeric guards & every? (overlay moves)" :label "pos? throws" :expected :throws :actual "(pos? \"x\")" :portability :common} - {:suite "predicates / numeric guards & every? (overlay moves)" :label "neg? throws" :expected :throws :actual "(neg? \"x\")" :portability :common} - {:suite "predicates / numeric guards & every? (overlay moves)" :label "every? all pass" :expected "true" :actual "(every? odd? [1 3 5])" :portability :common} - {:suite "predicates / numeric guards & every? (overlay moves)" :label "every? one fails" :expected "false" :actual "(every? odd? [1 2 5])" :portability :common} - {:suite "predicates / numeric guards & every? (overlay moves)" :label "every? vacuous" :expected "true" :actual "(every? odd? [])" :portability :common} - {:suite "predicates / numeric guards & every? (overlay moves)" :label "every? nil coll" :expected "true" :actual "(every? odd? nil)" :portability :common} - {:suite "predicates / numeric guards & every? (overlay moves)" :label "every? infinite short-circuit" :expected "false" :actual "(every? pos? (range))" :portability :common} - {:suite "predicates / numeric guards & every? (overlay moves)" :label "char? char" :expected "true" :actual "(char? \\x)" :portability :common} - {:suite "predicates / numeric guards & every? (overlay moves)" :label "char? string" :expected "false" :actual "(char? \"x\")" :portability :common} - {:suite "predicates / numeric guards & every? (overlay moves)" :label "char? number" :expected "false" :actual "(char? 97)" :portability :common} - {:suite "predicates / numeric guards & every? (overlay moves)" :label "char? nil" :expected "false" :actual "(char? nil)" :portability :common} - {:suite "protocols / defprotocol & dispatch" :label "protocol on record" :expected "16" :actual "(do (defprotocol Shape (area [s])) (defrecord Sq [side] Shape (area [_] (* side side))) (area (->Sq 4)))" :portability :common} - {:suite "protocols / defprotocol & dispatch" :label "protocol on deftype" :expected "16" :actual "(do (defprotocol Shape (area [s])) (deftype Sq [side] Shape (area [_] (* side side))) (area (->Sq 4)))" :portability :common} - {:suite "protocols / defprotocol & dispatch" :label "multiple methods" :expected "[1 2]" :actual "(do (defprotocol P (m [s]) (n [s])) (defrecord R [a b] P (m [_] a) (n [_] b)) [(m (->R 1 2)) (n (->R 1 2))])" :portability :common} - {:suite "protocols / defprotocol & dispatch" :label "multiple protocols" :expected "[:a :b]" :actual "(do (defprotocol P1 (p1 [s])) (defprotocol P2 (p2 [s])) (deftype T [] P1 (p1 [_] :a) P2 (p2 [_] :b)) [(p1 (->T)) (p2 (->T))])" :portability :common} - {:suite "protocols / defprotocol & dispatch" :label "method args" :expected "7" :actual "(do (defprotocol P (add [s x])) (defrecord R [n] P (add [_ x] (+ n x))) (add (->R 5) 2))" :portability :common} - {:suite "protocols / defprotocol & dispatch" :label "extend-type" :expected "10" :actual "(do (defprotocol P (twice [s])) (extend-type Number P (twice [n] (* n 2))) (twice 5))" :portability :common} - {:suite "protocols / defprotocol & dispatch" :label "extend-protocol" :expected "[2 4]" :actual "(do (defprotocol P (dbl [s])) (extend-protocol P Number (dbl [n] (* n 2))) [(dbl 1) (dbl 2)])" :portability :common} - {:suite "protocols / records" :label "record field access" :expected "1" :actual "(do (defrecord R [a b]) (:a (->R 1 2)))" :portability :common} - {:suite "protocols / records" :label "record map access" :expected "2" :actual "(do (defrecord R [a b]) (get (->R 1 2) :b))" :portability :common} - {:suite "protocols / records" :label "record equality" :expected "true" :actual "(do (defrecord R [a b]) (= (->R 1 2) (->R 1 2)))" :portability :common} - {:suite "protocols / records" :label "record inequality" :expected "false" :actual "(do (defrecord R [a b]) (= (->R 1 2) (->R 3 4)))" :portability :common} - {:suite "protocols / records" :label "map-> factory" :expected "1" :actual "(do (defrecord R [a b]) (:a (map->R {:a 1 :b 2})))" :portability :common} - {:suite "protocols / records" :label "record? true" :expected "true" :actual "(do (defrecord R [a]) (record? (->R 1)))" :portability :common} - {:suite "protocols / records" :label "assoc on record" :expected "9" :actual "(do (defrecord R [a]) (:a (assoc (->R 1) :a 9)))" :portability :common} - {:suite "protocols / reify & satisfies" :label "reify dispatch" :expected "42" :actual "(do (defprotocol P (m [_])) (m (reify P (m [_] 42))))" :portability :common} - {:suite "protocols / reify & satisfies" :label "reify multi-method" :expected "[1 2]" :actual "(do (defprotocol P (a [_]) (b [_])) (let [r (reify P (a [_] 1) (b [_] 2))] [(a r) (b r)]))" :portability :common} - {:suite "protocols / reify & satisfies" :label "satisfies? true" :expected "true" :actual "(do (defprotocol P (m [_])) (defrecord R [] P (m [_] 1)) (satisfies? P (->R)))" :portability :common} - {:suite "protocols / reify & satisfies" :label "satisfies? false" :expected "false" :actual "(do (defprotocol P (m [_])) (defrecord R []) (satisfies? P (->R)))" :portability :common} - {:suite "protocols / reify & satisfies" :label "satisfies? reify" :expected "true" :actual "(do (defprotocol P (m [_])) (satisfies? P (reify P (m [_] 1))))" :portability :common} - {:suite "protocols / reify & satisfies" :label "satisfies? reify multi-protocol" :expected "[true true]" :actual "(do (defprotocol P (m [_])) (defprotocol Q (n [_])) (let [r (reify P (m [_] 1) Q (n [_] 2))] [(satisfies? P r) (satisfies? Q r)]))" :portability :common} - {:suite "protocols / reify & satisfies" :label "satisfies? reify other proto" :expected "false" :actual "(do (defprotocol P (m [_])) (defprotocol Q (n [_])) (satisfies? Q (reify P (m [_] 1))))" :portability :common} - {:suite "protocols / reify & satisfies" :label "instance? record" :expected "true" :actual "(do (defrecord R [a]) (instance? R (->R 1)))" :portability :common} - {:suite "protocols / reify & satisfies" :label "dot constructor" :expected "5" :actual "(do (deftype P [n]) (.-n (P. 5)))" :portability :jvm} - {:suite "protocols / reify & satisfies" :label "dot ctor + method" :expected "5" :actual "(do (defprotocol G (val-of [_])) (deftype P [n] G (val-of [_] n)) (val-of (P. 5)))" :portability :jvm} - {:suite "protocols / defprotocol options" :label "docstring + option + method" :expected ":hi" :actual "(do (defprotocol Pdoc \"docs\" :extend-via-metadata true (greet [x])) (extend-protocol Pdoc String (greet [s] :hi)) (greet \"x\"))" :portability :common} - {:suite "protocols / defprotocol options" :label "option only" :expected "3" :actual "(do (defprotocol Popt :extend-via-metadata true (plus2 [x])) (extend-protocol Popt Long (plus2 [n] (+ n 2))) (plus2 1))" :portability :common} - {:suite "reader / anonymous fn #()" :label "no args" :expected "3" :actual "(#(+ 1 2))" :portability :common} - {:suite "reader / anonymous fn #()" :label "one arg %" :expected "6" :actual "(#(* % 2) 3)" :portability :common} - {:suite "reader / anonymous fn #()" :label "positional %1 %2" :expected "[1 2]" :actual "(#(do [%1 %2]) 1 2)" :portability :common} - {:suite "reader / anonymous fn #()" :label "rest %&" :expected "[1 2 3]" :actual "(#(do %&) 1 2 3)" :portability :common} - {:suite "reader / anonymous fn #()" :label "fixed + rest" :expected "[2 3]" :actual "(#(do % %&) 1 2 3)" :portability :common} - {:suite "reader / anonymous fn #()" :label "%2 + rest" :expected "[3]" :actual "(#(do %2 %&) 1 2 3)" :portability :common} - {:suite "reader / anonymous fn #()" :label "%2 only (placeholder p1)" :expected "20" :actual "(#(* %2 2) 1 10)" :portability :common} - {:suite "reader / anonymous fn #()" :label "% and %1 same" :expected "10" :actual "(#(+ % %1) 5)" :portability :common} - {:suite "reader / var-quote #'" :label "var-quote = var" :expected "true" :actual "(= (var str) #'str)" :portability :common} - {:suite "reader / var-quote #'" :label "is a var" :expected "true" :actual "(var? #'str)" :portability :common} - {:suite "reader / var-quote #'" :label "deref var-quote" :expected "5" :actual "(do (def w 5) (deref #'w))" :portability :common} - {:suite "reader / metadata ^" :label "meta on map" :expected "true" :actual "(:foo (meta ^:foo {}))" :portability :common} - {:suite "reader / metadata ^" :label "meta on vector" :expected "true" :actual "(:foo (meta ^:foo [1 2]))" :portability :common} - {:suite "reader / metadata ^" :label "meta on set" :expected "true" :actual "(:foo (meta ^:foo #{}))" :portability :common} - {:suite "reader / metadata ^" :label "meta map form" :expected "1" :actual "(:a (meta ^{:a 1} {}))" :portability :common} - {:suite "reader / metadata ^" :label "meta on quoted sym" :expected "true" :actual "(:foo (meta (quote ^:foo bar)))" :portability :common} - {:suite "reader / metadata ^" :label "with-meta map" :expected "true" :actual "(:k (meta (with-meta {} {:k true})))" :portability :common} - {:suite "reader / metadata ^" :label "with-meta vector" :expected "true" :actual "(:k (meta (with-meta [] {:k true})))" :portability :common} - {:suite "reader / metadata ^" :label "non-metadatable num" :expected "nil" :actual "(meta 100)" :portability :common} - {:suite "reader / metadata ^" :label "non-metadatable str" :expected "nil" :actual "(meta \"\")" :portability :common} - {:suite "reader / metadata ^" :label "non-metadatable bool" :expected "nil" :actual "(meta true)" :portability :common} - {:suite "reader / syntax-quote" :label "plain literal" :expected "[1 2 3]" :actual "`[1 2 3]" :portability :common} - {:suite "reader / syntax-quote" :label "gensym distinct" :expected "true" :actual "(not= `meow# `meow#)" :portability :common} - {:suite "reader / syntax-quote" :label "gensym stable" :expected "true" :actual "(let [s `[meow# meow#]] (= (first s) (second s)))" :portability :common} - {:suite "reader / syntax-quote" :label "qualifies unresolved" :expected "(quote user/foo)" :actual "`foo" :portability :common} - {:suite "reader / syntax-quote" :label "qualifies core sym" :expected "(quote clojure.core/str)" :actual "`str" :portability :common} - {:suite "reader / syntax-quote" :label "unquote value" :expected "[1 2 3]" :actual "(let [a [1 2 3]] `~a)" :portability :common} - {:suite "reader / syntax-quote" :label "unquote in call" :expected "(quote (clojure.core/str [1 2 3]))" :actual "(let [a [1 2 3]] `(str ~a))" :portability :common} - {:suite "reader / syntax-quote" :label "splice empty" :expected "(quote (clojure.core/str))" :actual "(let [e []] `(str ~@e))" :portability :common} - {:suite "reader / syntax-quote" :label "splice values" :expected "(quote (clojure.core/str 1 2 3))" :actual "(let [a [1 2 3]] `(str ~@a))" :portability :common} - {:suite "reader / syntax-quote" :label "splice in vector" :expected "[1 2 3 0 1 2 3]" :actual "(let [b [0] a [1 2 3] e []] `[~@e ~@a ~@b ~@a ~@e])" :portability :common} - {:suite "reader / syntax-quote" :label "splice in set" :expected "#{0 1 3 2}" :actual "(let [b [0] a [1 2 3] e []] `#{~@e ~@a ~@b})" :portability :common} - {:suite "reader / syntax-quote" :label "unquote in set" :expected "#{9 5}" :actual "(let [x 5] `#{~x 9})" :portability :common} - {:suite "reader / discard, symbolic values, conditionals (spec 2.3)" :label "discard simple" :expected "2" :actual "(do #_1 2)" :portability :common} - {:suite "reader / discard, symbolic values, conditionals (spec 2.3)" :label "discard in vector" :expected "[1 3]" :actual "[1 #_2 3]" :portability :common} - {:suite "reader / discard, symbolic values, conditionals (spec 2.3)" :label "discard stacks" :expected "3" :actual "(do #_ #_ 1 2 3)" :portability :common} - {:suite "reader / discard, symbolic values, conditionals (spec 2.3)" :label "##Inf" :expected "true" :actual "(= ##Inf (/ 1.0 0.0))" :portability :common} - {:suite "reader / discard, symbolic values, conditionals (spec 2.3)" :label "##-Inf" :expected "true" :actual "(= ##-Inf (/ -1.0 0.0))" :portability :common} - {:suite "reader / discard, symbolic values, conditionals (spec 2.3)" :label "##NaN not self-equal" :expected "false" :actual "(= ##NaN ##NaN)" :portability :common} - {:suite "reader / discard, symbolic values, conditionals (spec 2.3)" :label "##NaN is NaN?" :expected "true" :actual "(NaN? ##NaN)" :portability :common} - {:suite "reader / discard, symbolic values, conditionals (spec 2.3)" :label "conditional :default reachable" :expected "2" :actual "#?(:no-such-dialect 1 :default 2)" :portability :common} - {:suite "reader / discard, symbolic values, conditionals (spec 2.3)" :label "var-quote qualified" :expected "true" :actual "(= (var clojure.core/str) #'clojure.core/str)" :portability :common} - {:suite "reader / discard, symbolic values, conditionals (spec 2.3)" :label "gensym stable in template" :expected "true" :actual "(let [syms `[meow# meow#]] (= (first syms) (second syms)))" :portability :common} - {:suite "reader / discard, symbolic values, conditionals (spec 2.3)" :label "gensym fresh across templates" :expected "false" :actual "(= `meow# `meow#)" :portability :common} - {:suite "reader / syntax-quote literal collapse (spec 2.4 S25)" :label "string once" :expected "true" :actual "(= \"meow\" `\"meow\")" :portability :common} - {:suite "reader / syntax-quote literal collapse (spec 2.4 S25)" :label "string nested" :expected "true" :actual "(= \"meow\" ``\"meow\")" :portability :common} - {:suite "reader / syntax-quote literal collapse (spec 2.4 S25)" :label "string triple" :expected "true" :actual "(= \"meow\" ```\"meow\")" :portability :common} - {:suite "reader / syntax-quote literal collapse (spec 2.4 S25)" :label "number nested" :expected "true" :actual "(= 42 ``42)" :portability :common} - {:suite "reader / syntax-quote literal collapse (spec 2.4 S25)" :label "keyword nested" :expected "true" :actual "(= :k ``:k)" :portability :common} - {:suite "reader / syntax-quote literal collapse (spec 2.4 S25)" :label "nil nested" :expected "false" :actual "(nil? ``nil)" :portability :common} - {:suite "reader / syntax-quote literal collapse (spec 2.4 S25)" :label "char nested" :expected "true" :actual "(= \\a ``\\a)" :portability :common} - {:suite "reader / syntax-quote literal collapse (spec 2.4 S25)" :label "bool nested" :expected "false" :actual "(= true ``true)" :portability :common} - {:suite "reader / syntax-quote literal collapse (spec 2.4 S25)" :label "symbol still qualifies" :expected "true" :actual "(= (quote clojure.core/map) `map)" :portability :common} - {:suite "reader / syntax-quote literal collapse (spec 2.4 S25)" :label "vector still templates" :expected "true" :actual "(= [1 2] `[1 ~(inc 1)])" :portability :common} - {:suite "reader / scalar literals" :label "integer" :expected "42" :actual "42" :portability :common} - {:suite "reader / scalar literals" :label "negative" :expected "-7" :actual "-7" :portability :common} - {:suite "reader / scalar literals" :label "float" :expected "1.5" :actual "1.5" :portability :common} - {:suite "reader / scalar literals" :label "string" :expected "\"hi\"" :actual "\"hi\"" :portability :common} - {:suite "reader / scalar literals" :label "boolean true" :expected "true" :actual "true" :portability :common} - {:suite "reader / scalar literals" :label "nil" :expected "nil" :actual "nil" :portability :common} - {:suite "reader / scalar literals" :label "keyword" :expected ":a" :actual ":a" :portability :common} - {:suite "reader / scalar literals" :label "namespaced keyword" :expected "true" :actual "(= :a/b :a/b)" :portability :common} - {:suite "reader / scalar literals" :label "char" :expected "\\a" :actual "\\a" :portability :common} - {:suite "reader / scalar literals" :label "char newline" :expected "true" :actual "(= \\newline (first \"\\n\"))" :portability :common} - {:suite "reader / scalar literals" :label "char open-brace" :expected "123" :actual "(int \\{)" :portability :common} - {:suite "reader / scalar literals" :label "char open-paren" :expected "40" :actual "(int \\()" :portability :common} - {:suite "reader / scalar literals" :label "char comma" :expected "44" :actual "(int \\,)" :portability :common} - {:suite "reader / scalar literals" :label "char percent" :expected "37" :actual "(int \\%)" :portability :common} - {:suite "reader / scalar literals" :label "char unicode" :expected "65" :actual "(int \\u0041)" :portability :common} - {:suite "reader / scalar literals" :label "hex literal" :expected "255" :actual "0xff" :portability :common} - {:suite "reader / scalar literals" :label "hex uppercase" :expected "31" :actual "0X1F" :portability :common} - {:suite "reader / scalar literals" :label "bigint suffix N" :expected "42N" :actual "42N" :portability :common} - {:suite "reader / scalar literals" :label "bigdec suffix M" :expected "1.5M" :actual "1.5M" :portability :common} - {:suite "reader / scalar literals" :label "ratio -> double" :expected "3/4" :actual "3/4" :portability :common} - {:suite "reader / scalar literals" :label "radix integer" :expected "255" :actual "16rFF" :portability :common} - {:suite "reader / scalar literals" :label "exponent" :expected "1500.0" :actual "1.5e3" :portability :common} - {:suite "reader / scalar literals" :label "symbolic Infinity" :expected "true" :actual "(infinite? ##Inf)" :portability :common} - {:suite "reader / scalar literals" :label "symbolic NaN" :expected "true" :actual "(NaN? ##NaN)" :portability :common} - {:suite "reader / scalar literals" :label "symbol via quote" :expected "'foo" :actual "'foo" :portability :common} - {:suite "reader / collection literals" :label "vector" :expected "[1 2 3]" :actual "[1 2 3]" :portability :common} - {:suite "reader / collection literals" :label "list quoted" :expected "[1 2 3]" :actual "'(1 2 3)" :portability :common} - {:suite "reader / collection literals" :label "map" :expected "{:a 1}" :actual "{:a 1}" :portability :common} - {:suite "reader / collection literals" :label "set" :expected "#{1 3 2}" :actual "#{1 2 3}" :portability :common} - {:suite "reader / collection literals" :label "nested" :expected "{:a [1 {:b 2}]}" :actual "{:a [1 {:b 2}]}" :portability :common} - {:suite "reader / collection literals" :label "empty vector" :expected "[]" :actual "[]" :portability :common} - {:suite "reader / collection literals" :label "empty map" :expected "{}" :actual "{}" :portability :common} - {:suite "reader / collection literals" :label "empty set" :expected "#{}" :actual "#{}" :portability :common} - {:suite "reader / dispatch & sugar" :label "anon fn #()" :expected "3" :actual "(#(+ %1 %2) 1 2)" :portability :common} - {:suite "reader / dispatch & sugar" :label "anon fn single %" :expected "2" :actual "(#(inc %) 1)" :portability :common} - {:suite "reader / dispatch & sugar" :label "anon fn %&" :expected "[2 3]" :actual "(#(vec %&) 2 3)" :portability :common} - {:suite "reader / dispatch & sugar" :label "discard #_" :expected "[1 3]" :actual "[1 #_2 3]" :portability :common} - {:suite "reader / dispatch & sugar" :label "regex literal" :expected "true" :actual "(= \"abc\" (re-find #\"abc\" \"xabcx\"))" :portability :common} - {:suite "reader / dispatch & sugar" :label "reader conditional" :expected "1" :actual "#?(:clj 1 :cljs 2 :default 3)" :portability :common} - {:suite "reader / dispatch & sugar" :label "reader cond :jolt" :expected "1" :actual "#?(:clj 1 :jolt 4 :default 3)" :portability :common} - {:suite "reader / dispatch & sugar" :label "reader cond clause order" :expected "5" :actual "#?(:default 5 :jolt 6)" :portability :common} - {:suite "reader / dispatch & sugar" :label "reader cond no match" :expected "[1]" :actual "[#?(:clj 1 :cljs 2)]" :portability :common} - {:suite "reader / dispatch & sugar" :label "reader cond splice" :expected "[]" :actual "[#?@(:jolt [1 2 3] :cljs [4 5])]" :portability :common} - {:suite "reader / dispatch & sugar" :label "reader cond splice no match" :expected "[1 2 3]" :actual "[#?@(:clj [1 2 3] :cljs [4 5])]" :portability :common} - {:suite "reader / dispatch & sugar" :label "inst literal reads" :expected "true" :actual "(some? #inst \"2020-01-01T00:00:00Z\")" :portability :common} - {:suite "reader / dispatch & sugar" :label "uuid literal" :expected "\"550e8400-e29b-41d4-a716-446655440000\"" :actual "(str #uuid \"550e8400-e29b-41d4-a716-446655440000\")" :portability :common} - {:suite "reader / dispatch & sugar" :label "tagged literal var" :expected "true" :actual "(var? #'+)" :portability :common} - {:suite "reader / dispatch & sugar" :label "deref sugar" :expected "5" :actual "(let [a (atom 5)] @a)" :portability :common} - {:suite "reader / dispatch & sugar" :label "meta sugar" :expected "{:t 1}" :actual "(meta ^{:t 1} [])" :portability :common} - {:suite "reader / comments inside maps" :label "comment in value slot" :expected "{:a 1}" :actual "{:a ; note\n 1}" :portability :common} - {:suite "reader / comments inside maps" :label "comment before key" :expected "{:a 1}" :actual "{; lead\n :a 1}" :portability :common} - {:suite "reader / comments inside maps" :label "comment between entries" :expected "{:a 1, :b 2}" :actual "{:a 1 ; mid\n :b 2}" :portability :common} - {:suite "reader / comments inside maps" :label "discard in value slot" :expected "{:a 1}" :actual "{:a #_9 1}" :portability :common} - {:suite "reader / comments inside maps" :label "comment with parens" :expected "{:a {:b 1}}" :actual "{:a ; dev (REPL, etc)\n {:b 1}}" :portability :common} - {:suite "reader / comments inside maps" :label "nested with comments" :expected "{:x {:y 2}}" :actual "{:x ; outer\n {:y ; inner\n 2}}" :portability :common} - {:suite "regex / literals & predicate" :label "regex? literal" :expected "true" :actual "(regex? #\"\\d+\")" :portability :common} - {:suite "regex / literals & predicate" :label "regex? non-regex" :expected "false" :actual "(regex? \"\\\\d+\")" :portability :common} - {:suite "regex / literals & predicate" :label "escaped digits" :expected "\"42\"" :actual "(re-find #\"\\d+\" \"x42y\")" :portability :common} - {:suite "regex / literals & predicate" :label "escaped ws/non-ws" :expected "\"x a\"" :actual "(re-find #\"\\S\\s\\S\" \"x a b y\")" :portability :common} - {:suite "regex / re-find" :label "match" :expected "\"123\"" :actual "(re-find #\"\\d+\" \"abc123def\")" :portability :common} - {:suite "regex / re-find" :label "no match nil" :expected "nil" :actual "(re-find #\"\\d+\" \"abc\")" :portability :common} - {:suite "regex / re-find" :label "with groups" :expected "[\"a1\" \"a\" \"1\"]" :actual "(re-find #\"([a-z])(\\d)\" \"--a1--\")" :portability :common} - {:suite "regex / re-find" :label "first match only" :expected "\"1\"" :actual "(re-find #\"\\d\" \"1 2 3\")" :portability :common} - {:suite "regex / re-matches" :label "full match" :expected "\"123\"" :actual "(re-matches #\"\\d+\" \"123\")" :portability :common} - {:suite "regex / re-matches" :label "partial = nil" :expected "nil" :actual "(re-matches #\"\\d+\" \"123abc\")" :portability :common} - {:suite "regex / re-matches" :label "groups" :expected "[\"12\" \"1\" \"2\"]" :actual "(re-matches #\"(\\d)(\\d)\" \"12\")" :portability :common} - {:suite "regex / re-matches" :label "no match nil" :expected "nil" :actual "(re-matches #\"x+\" \"yyy\")" :portability :common} - {:suite "regex / re-seq" :label "all matches" :expected "[\"1\" \"22\" \"333\"]" :actual "(re-seq #\"\\d+\" \"a1b22c333\")" :portability :common} - {:suite "regex / re-seq" :label "empty when none" :expected "nil" :actual "(seq (re-seq #\"z\" \"abc\"))" :portability :common} - {:suite "regex / re-seq" :label "words" :expected "[\"foo\" \"bar\"]" :actual "(re-seq #\"\\w+\" \"foo bar\")" :portability :common} - {:suite "regex / char-class dash" :label "dash after \\w is literal" :expected "\"a_b-c\"" :actual "(re-matches #\"[\\w-_]+\" \"a_b-c\")" :portability :common} - {:suite "regex / char-class dash" :label "dash + escaped dot in class" :expected "\"a.b_c-d\"" :actual "(re-matches #\"[\\w-_\\.]+\" \"a.b_c-d\")" :portability :common} - {:suite "regex / char-class dash" :label "trailing dash in class" :expected "[\"a-b\" \"c-d\"]" :actual "(vec (re-seq #\"[\\w-]+\" \"a-b c-d\"))" :portability :common} - {:suite "regex / nested quantifier" :label "(X+)* parses and matches" :expected "true" :actual "(boolean (re-matches #\"([^%]+)*(%(d))?\" \"abc\"))" :portability :common} - {:suite "regex / matcher" :label "re-find over a matcher" :expected "\"1\"" :actual "(re-find (re-matcher #\"\\d+\" \"a1b22\"))" :portability :common} - {:suite "regex / matcher" :label "stateful step + re-groups" :expected "[[\"12-34\" \"12\" \"34\"] [\"12-34\" \"12\" \"34\"] [\"56-78\" \"56\" \"78\"] nil]" :actual "(let [m (re-matcher #\"(\\d+)-(\\d+)\" \"12-34 56-78\")] [(re-find m) (re-groups m) (re-find m) (re-find m)])" :portability :common} - {:suite "regex / matcher" :label "re-groups before a match throws" :expected :throws :actual "(re-groups (re-matcher #\"\\d\" \"abc\"))" :portability :common} - {:suite "dynamic vars / portable defaults" :label "default reads" :expected "[true false true false]" :actual "[*read-eval* *print-dup* *flush-on-newline* *compile-files*]" :portability :common} - {:suite "dynamic vars / portable defaults" :label "binding *read-eval*" :expected "false" :actual "(binding [*read-eval* false] *read-eval*)" :portability :common} - {:suite "special forms / letfn" :label "mutual recursion" :expected "true" :actual "(letfn [(e? [n] (if (zero? n) true (o? (dec n)))) (o? [n] (if (zero? n) false (e? (dec n))))] (e? 10))" :portability :common} - {:suite "core vars / present and callable" :label "*out* *err* *warn-on-reflection* await restart-agent" :expected "[true true false true true]" :actual "[(boolean *out*) (boolean *err*) *warn-on-reflection* (ifn? await) (ifn? restart-agent)]" :portability :common} - {:suite "exceptions / runtime error classes" :label "arity error is ArityException" :expected "true" :actual "(instance? clojure.lang.ArityException (try ((fn [a b] a) 1) (catch Throwable e e)))" :portability :jvm} - {:suite "exceptions / runtime error classes" :label "ArityException is an IllegalArgumentException" :expected "true" :actual "(instance? IllegalArgumentException (try ((fn [a b] a) 1) (catch Throwable e e)))" :portability :common} - {:suite "exceptions / runtime error classes" :label "non-seqable is IllegalArgumentException" :expected "true" :actual "(instance? IllegalArgumentException (try (doall (mapcat identity 0)) (catch Throwable e e)))" :portability :common} - {:suite "dynamic vars / portable defaults" :label "*data-readers* map, *math-context* nil" :expected "[true true]" :actual "[(map? *data-readers*) (nil? *math-context*)]" :portability :common} - {:suite "regex / re-pattern & string ops" :label "re-pattern build" :expected "\"hi\"" :actual "(re-find (re-pattern \"\\\\w+\") \"hi!\")" :portability :common} - {:suite "regex / re-pattern & string ops" :label "re-pattern is regex?" :expected "true" :actual "(regex? (re-pattern \"a\"))" :portability :common} - {:suite "regex / re-pattern & string ops" :label "split on regex" :expected "[\"a\" \"b\" \"c\"]" :actual "(do (require '[clojure.string :as s]) (s/split \"a1b2c\" #\"\\d\"))" :portability :common} - {:suite "regex / re-pattern & string ops" :label "replace regex" :expected "\"X-X\"" :actual "(do (require '[clojure.string :as s]) (s/replace \"a-b\" #\"[a-z]\" \"X\"))" :portability :common} - {:suite "regex / re-pattern & string ops" :label "replace $1" :expected "\"[a][b]\"" :actual "(do (require '[clojure.string :as s]) (s/replace \"ab\" #\"([a-z])\" \"[$1]\"))" :portability :common} - {:suite "regex / \\p property classes" :label "p{L} ascii" :expected "\"hello\"" :actual "(re-matches #\"^\\p{L}+$\" \"hello\")" :portability :common} - {:suite "regex / \\p property classes" :label "p{L} utf-8" :expected "true" :actual "(boolean (re-matches #\"^\\p{L}+$\" \"héllo\"))" :portability :common} - {:suite "regex / \\p property classes" :label "p{L} rejects digits" :expected "false" :actual "(boolean (re-matches #\"^\\p{L}+$\" \"ab1\"))" :portability :common} - {:suite "regex / \\p property classes" :label "p{N}" :expected "[\"12\" \"345\"]" :actual "(re-seq #\"\\p{N}+\" \"a12b345\")" :portability :common} - {:suite "regex / \\p property classes" :label "P{N} negation" :expected "\"abc\"" :actual "(re-matches #\"^\\P{N}+$\" \"abc\")" :portability :common} - {:suite "regex / \\p property classes" :label "inside class" :expected "\"a-1_b\"" :actual "(re-matches #\"^[\\p{N}\\p{L}_-]+$\" \"a-1_b\")" :portability :common} - {:suite "regex / \\p property classes" :label "p{Lu}/p{Ll}" :expected "\"aB\"" :actual "(re-matches #\"^\\p{Ll}\\p{Lu}$\" \"aB\")" :portability :common} - {:suite "regex / \\p property classes" :label "p{Z} space" :expected "\" \"" :actual "(re-matches #\"(?u)^[\\s\\p{Z}]+$\" \" \")" :portability :common} - {:suite "regex / \\p property classes" :label "p{Ps}/p{Pe}" :expected "\"(x)\"" :actual "(re-matches #\"^\\p{Ps}x\\p{Pe}$\" \"(x)\")" :portability :common} - {:suite "regex / \\p property classes" :label "(?u) accepted" :expected "\"hi\"" :actual "(re-matches #\"(?u)^hi$\" \"hi\")" :portability :common} - {:suite "regex / \\p property classes" :label "unknown class throws" :expected :throws :actual "(re-pattern \"\\p{Greek}\")" :portability :common} - {:suite "regex / Pattern statics & String regex methods" :label "Pattern/compile is a regex" :expected "true" :actual "(regex? (Pattern/compile \"a.c\"))" :portability :jvm} - {:suite "regex / Pattern statics & String regex methods" :label "compiled .split" :expected "[\"a\" \"b\" \"c\"]" :actual "(.split (Pattern/compile \",\") \"a,b,c\")" :portability :jvm} - {:suite "regex / Pattern statics & String regex methods" :label "str/replace w/ Pattern" :expected "\"ab\"" :actual "(do (require '[clojure.string :as s]) (s/replace \"a1b2\" (Pattern/compile \"[0-9]\") \"\"))" :portability :jvm} - {:suite "regex / Pattern statics & String regex methods" :label "Pattern/MULTILINE ^" :expected "true" :actual "(boolean (re-find (Pattern/compile \"^x\" Pattern/MULTILINE) \"y\\nx\"))" :portability :jvm} - {:suite "regex / Pattern statics & String regex methods" :label "Pattern/quote literal" :expected "true" :actual "(boolean (re-find (re-pattern (Pattern/quote \"a.c\")) \"za.cy\"))" :portability :jvm} - {:suite "regex / Pattern statics & String regex methods" :label "Pattern/quote not meta" :expected "false" :actual "(boolean (re-find (re-pattern (Pattern/quote \"a.c\")) \"zabcy\"))" :portability :jvm} - {:suite "regex / Pattern statics & String regex methods" :label ".matches whole string" :expected "true" :actual "(.matches \"abc\" \"a.c\")" :portability :jvm} - {:suite "regex / Pattern statics & String regex methods" :label ".matches partial -> false" :expected "false" :actual "(.matches \"abcd\" \"a.c\")" :portability :jvm} - {:suite "regex / Pattern statics & String regex methods" :label ".replaceAll regex" :expected "\"a-b-c\"" :actual "(.replaceAll \"a_b_c\" \"_\" \"-\")" :portability :jvm} - {:suite "regex / Pattern statics & String regex methods" :label ".replaceFirst regex" :expected "\"a-b_c\"" :actual "(.replaceFirst \"a_b_c\" \"_\" \"-\")" :portability :jvm} - {:suite "regex / bounded quantifiers" :label "exact {n}" :expected "\"aaa\"" :actual "(re-matches #\"a{3}\" \"aaa\")" :portability :common} - {:suite "regex / bounded quantifiers" :label "range {n,m} max" :expected "\"aaaa\"" :actual "(re-find #\"a{2,4}\" \"aaaaa\")" :portability :common} - {:suite "regex / bounded quantifiers" :label "zero lower {0,n}" :expected "\"aa\"" :actual "(re-find #\"a{0,3}\" \"aa\")" :portability :common} - {:suite "regex / bounded quantifiers" :label "{n,} unbounded" :expected "\"aaaa\"" :actual "(re-find #\"a{2,}\" \"aaaa\")" :portability :common} - {:suite "regex / bounded quantifiers" :label "nested bounds compile" :expected "true" :actual "(boolean (re-matches #\"[a-z](?:[a-z]{0,61}[a-z])?(?:-[a-z]{0,61}[a-z])*\" \"abc-def\"))" :portability :common} - {:suite "regex / backreferences" :label "repeated char" :expected "true" :actual "(boolean (re-find #\"(.)\\1\" \"abba\"))" :portability :common} - {:suite "regex / backreferences" :label "no repeat = nil" :expected "nil" :actual "(re-find #\"(.)\\1\" \"abc\")" :portability :common} - {:suite "regex / backreferences" :label "thematic-break run" :expected "true" :actual "(boolean (re-matches #\"([-*_])\\1\\1\" \"---\"))" :portability :common} - {:suite "regex / backreferences" :label "mismatched run" :expected "nil" :actual "(re-matches #\"([-*_])\\1\\1\" \"-*_\")" :portability :common} - {:suite "regex / backreferences" :label "repeated word" :expected "[\"the the\" \"the\"]" :actual "(re-find #\"(\\w+) \\1\" \"say the the word\")" :portability :common} - {:suite "regex / backreferences" :label "group still captures" :expected "[\"x=x\" \"x\"]" :actual "(re-matches #\"(\\w+)=\\1\" \"x=x\")" :portability :common} - {:suite "regex / backreferences" :label "html tag pair" :expected "true" :actual "(boolean (re-matches #\"<(\\w+)>.*\" \"hi\"))" :portability :common} - {:suite "seq / access" :label "first of vector" :expected "1" :actual "(first [1 2 3])" :portability :common} - {:suite "seq / access" :label "first of list" :expected "1" :actual "(first (list 1 2 3))" :portability :common} - {:suite "seq / access" :label "first of empty is nil" :expected "nil" :actual "(first [])" :portability :common} - {:suite "seq / access" :label "first of nil is nil" :expected "nil" :actual "(first nil)" :portability :common} - {:suite "seq / access" :label "second" :expected "2" :actual "(second [1 2 3])" :portability :common} - {:suite "seq / access" :label "last" :expected "3" :actual "(last [1 2 3])" :portability :common} - {:suite "seq / access" :label "rest of vector" :expected "[2 3]" :actual "(rest [1 2 3])" :portability :common} - {:suite "seq / access" :label "rest of single" :expected "[]" :actual "(rest [1])" :portability :common} - {:suite "seq / access" :label "rest of empty" :expected "[]" :actual "(rest [])" :portability :common} - {:suite "seq / access" :label "next of single is nil" :expected "nil" :actual "(next [1])" :portability :common} - {:suite "seq / access" :label "next of empty is nil" :expected "nil" :actual "(next [])" :portability :common} - {:suite "seq / access" :label "nth" :expected "30" :actual "(nth [10 20 30] 2)" :portability :common} - {:suite "seq / access" :label "nth with default" :expected "99" :actual "(nth [10] 5 99)" :portability :common} - {:suite "seq / access" :label "nth out of range" :expected :throws :actual "(nth [10] 5)" :portability :common} - {:suite "seq / access" :label "ffirst" :expected "1" :actual "(ffirst [[1 2] [3 4]])" :portability :common} - {:suite "seq / access" :label "fnext" :expected "2" :actual "(fnext [1 2 3])" :portability :common} - {:suite "seq / access" :label "nnext" :expected "[3 4]" :actual "(nnext [1 2 3 4])" :portability :common} - {:suite "seq / construction" :label "cons onto list" :expected "[0 1 2]" :actual "(cons 0 (list 1 2))" :portability :common} - {:suite "seq / construction" :label "cons onto vector" :expected "[0 1 2]" :actual "(cons 0 [1 2])" :portability :common} - {:suite "seq / construction" :label "cons onto nil" :expected "[0]" :actual "(cons 0 nil)" :portability :common} - {:suite "seq / construction" :label "conj vector appends" :expected "[1 2 3]" :actual "(conj [1 2] 3)" :portability :common} - {:suite "seq / construction" :label "conj list prepends" :expected "[0 1 2]" :actual "(conj (list 1 2) 0)" :portability :common} - {:suite "seq / construction" :label "conj multiple on vec" :expected "[1 2 3 4]" :actual "(conj [1 2] 3 4)" :portability :common} - {:suite "seq / construction" :label "conj multiple on list" :expected "[4 3 1 2]" :actual "(conj (list 1 2) 3 4)" :portability :common} - {:suite "seq / construction" :label "seq of empty is nil" :expected "nil" :actual "(seq [])" :portability :common} - {:suite "seq / construction" :label "seq of nil is nil" :expected "nil" :actual "(seq nil)" :portability :common} - {:suite "seq / construction" :label "seq of string" :expected "[\\a \\b]" :actual "(seq \"ab\")" :portability :common} - {:suite "seq / construction" :label "empty?" :expected "true" :actual "(empty? [])" :portability :common} - {:suite "seq / construction" :label "not empty?" :expected "false" :actual "(empty? [1])" :portability :common} - {:suite "seq / construction" :label "count" :expected "3" :actual "(count [1 2 3])" :portability :common} - {:suite "seq / construction" :label "count of nil" :expected "0" :actual "(count nil)" :portability :common} - {:suite "seq / construction" :label "count of string" :expected "3" :actual "(count \"abc\")" :portability :common} - {:suite "seq / map filter reduce" :label "map" :expected "[2 3 4]" :actual "(map inc [1 2 3])" :portability :common} - {:suite "seq / map filter reduce" :label "map two colls" :expected "[5 7 9]" :actual "(map + [1 2 3] [4 5 6])" :portability :common} - {:suite "seq / map filter reduce" :label "map stops at shortest" :expected "[5 7]" :actual "(map + [1 2] [4 5 6])" :portability :common} - {:suite "seq / map filter reduce" :label "map keeps nil elements" :expected "[[1 :a] [nil :b] [3 nil]]" :actual "(map vector [1 nil 3] [:a :b nil])" :portability :common} - {:suite "seq / map filter reduce" :label "map 3 colls" :expected "[12 15 18]" :actual "(map + [1 2 3] [4 5 6] [7 8 9])" :portability :common} - {:suite "seq / map filter reduce" :label "map 3 colls shortest" :expected "[12 15]" :actual "(map + [1 2] [4 5 6] [7 8 9])" :portability :common} - {:suite "seq / map filter reduce" :label "map 4 colls" :expected "[16 20]" :actual "(map + [1 2] [3 4] [5 6] [7 8])" :portability :common} - {:suite "seq / map filter reduce" :label "map 3 colls nils" :expected "[[1 :a 10] [nil :b 20] [3 nil 30]]" :actual "(map vector [1 nil 3] [:a :b nil] [10 20 30])" :portability :common} - {:suite "seq / map filter reduce" :label "map empty coll" :expected "[]" :actual "(map + [] [1 2 3] [4 5 6])" :portability :common} - {:suite "seq / map filter reduce" :label "map lazy+concrete" :expected "[11 22 33]" :actual "(map + (map identity [1 2 3]) [10 20 30])" :portability :common} - {:suite "seq / map filter reduce" :label "map-indexed" :expected "[[0 :a] [1 :b]]" :actual "(map-indexed vector [:a :b])" :portability :common} - {:suite "seq / map filter reduce" :label "mapv" :expected "[2 3 4]" :actual "(mapv inc [1 2 3])" :portability :common} - {:suite "seq / map filter reduce" :label "filter" :expected "[2 4]" :actual "(filter even? [1 2 3 4])" :portability :common} - {:suite "seq / map filter reduce" :label "filterv" :expected "[2 4]" :actual "(filterv even? [1 2 3 4])" :portability :common} - {:suite "seq / map filter reduce" :label "remove" :expected "[1 3]" :actual "(remove even? [1 2 3 4])" :portability :common} - {:suite "seq / map filter reduce" :label "reduce" :expected "10" :actual "(reduce + [1 2 3 4])" :portability :common} - {:suite "seq / map filter reduce" :label "reduce with init" :expected "20" :actual "(reduce + 10 [1 2 3 4])" :portability :common} - {:suite "seq / map filter reduce" :label "reduce empty with init" :expected "0" :actual "(reduce + 0 [])" :portability :common} - {:suite "seq / map filter reduce" :label "reduce single no init" :expected "5" :actual "(reduce + [5])" :portability :common} - {:suite "seq / map filter reduce" :label "reduced short-circuits" :expected "3" :actual "(reduce (fn [a x] (if (> a 2) (reduced a) (+ a x))) 0 [1 2 3 4 5])" :portability :common} - {:suite "seq / map filter reduce" :label "reduce-kv" :expected "6" :actual "(reduce-kv (fn [a k v] (+ a v)) 0 {:a 1 :b 2 :c 3})" :portability :common} - {:suite "seq / map filter reduce" :label "reduce-kv on vector" :expected "[[0 :a] [1 :b]]" :actual "(reduce-kv (fn [a i v] (conj a [i v])) [] [:a :b])" :portability :common} - {:suite "seq / map filter reduce" :label "reduce-kv honors reduced" :expected "[:a]" :actual "(reduce-kv (fn [a i v] (if (= i 1) (reduced a) (conj a v))) [] [:a :b :c])" :portability :common} - {:suite "seq / map filter reduce" :label "reduce-kv on nil" :expected "0" :actual "(reduce-kv (fn [a k v] (+ a v)) 0 nil)" :portability :common} - {:suite "seq / map filter reduce" :label "reductions" :expected "[1 3 6]" :actual "(reductions + [1 2 3])" :portability :common} - {:suite "seq / map filter reduce" :label "mapcat" :expected "[1 1 2 2]" :actual "(mapcat (fn [x] [x x]) [1 2])" :portability :common} - {:suite "seq / map filter reduce" :label "mapcat two colls" :expected "[1 3 2 4]" :actual "(mapcat vector [1 2] [3 4])" :portability :common} - {:suite "seq / map filter reduce" :label "mapcat three colls" :expected "[1 2 3]" :actual "(mapcat vector [1] [2] [3])" :portability :common} - {:suite "seq / map filter reduce" :label "mapcat empty coll" :expected "[]" :actual "(mapcat vector [] [1 2] [3 4])" :portability :common} - {:suite "seq / map filter reduce" :label "mapcat seqs" :expected "[1 2 3 4]" :actual "(mapcat identity [[1 2] [3 4]])" :portability :common} - {:suite "seq / lazy over infinite" :label "mapcat is lazy over an infinite source" :expected "[1 2 1 2]" :actual "(take 4 (mapcat identity (repeat [1 2])))" :portability :common} - {:suite "seq / lazy over infinite" :label "mapcat single coll lazy" :expected "[0 1 2]" :actual "(take 3 (mapcat vector (range)))" :portability :common} - {:suite "seq / lazy over infinite" :label "apply concat lazy over infinite" :expected "[1 1 1]" :actual "(take 3 (apply concat (repeat [1])))" :portability :common} - {:suite "seq / lazy over infinite" :label "apply concat fixed + infinite tail" :expected "[9 0 0 0 0]" :actual "(take 5 (apply concat [9] (repeat [0])))" :portability :common} - {:suite "seq / lazy over infinite" :label "sequence is lazy over an infinite source" :expected "[1 2 3]" :actual "(take 3 (sequence (map inc) (range)))" :portability :common} - {:suite "seq / lazy over infinite" :label "sequence first of infinite" :expected "2" :actual "(first (sequence (map inc) (range 1 100000000000)))" :portability :common} - {:suite "seq / lazy over infinite" :label "sequence stateful xform lazy" :expected "[[0 1] [2 3]]" :actual "(take 2 (sequence (partition-all 2) (range)))" :portability :common} - {:suite "seq / lazy over infinite" :label "sequence value + completion flush" :expected "[[0 1] [2 3] [4]]" :actual "(sequence (partition-all 2) (range 5))" :portability :common} - {:suite "seq / lazy over infinite" :label "sequence empty stays a seq" :expected "true" :actual "(seq? (sequence (filter even?) [1 3 5]))" :portability :common} - {:suite "seq / lazy over infinite" :label "sequence empty prints as empty" :expected "()" :actual "(sequence (filter even?) [1 3 5])" :portability :common} - {:suite "seq / lazy over infinite" :label "eduction is lazy over infinite" :expected "1" :actual "(first (eduction (map inc) (range)))" :portability :common} - {:suite "seq / lazy over infinite" :label "eduction reduces" :expected "9" :actual "(reduce + (eduction (filter odd?) [1 2 3 4 5]))" :portability :common} - {:suite "seq / lazy over infinite" :label "eduction into" :expected "[2 3 4]" :actual "(into [] (eduction (map inc) [1 2 3]))" :portability :common} - {:suite "seq / lazy over infinite" :label "eduction multiple xforms compose left-to-right" :expected "[2 4]" :actual "(into [] (eduction (filter odd?) (map inc) [1 2 3 4]))" :portability :common} - {:suite "seq / map filter reduce" :label "keep" :expected "[1 3]" :actual "(keep (fn [x] (if (odd? x) x nil)) [1 2 3 4])" :portability :common} - {:suite "seq / map filter reduce" :label "some truthy" :expected "true" :actual "(some even? [1 2 3])" :portability :common} - {:suite "seq / map filter reduce" :label "some nil" :expected "nil" :actual "(some even? [1 3 5])" :portability :common} - {:suite "seq / map filter reduce" :label "every? true" :expected "true" :actual "(every? pos? [1 2 3])" :portability :common} - {:suite "seq / map filter reduce" :label "every? false" :expected "false" :actual "(every? pos? [1 -2 3])" :portability :common} - {:suite "seq / take drop slice" :label "take" :expected "[1 2 3]" :actual "(take 3 [1 2 3 4 5])" :portability :common} - {:suite "seq / take drop slice" :label "take more than size" :expected "[1 2]" :actual "(take 5 [1 2])" :portability :common} - {:suite "seq / take drop slice" :label "drop" :expected "[4 5]" :actual "(drop 3 [1 2 3 4 5])" :portability :common} - {:suite "seq / take drop slice" :label "take-while" :expected "[1 2]" :actual "(take-while (fn [x] (< x 3)) [1 2 3 1])" :portability :common} - {:suite "seq / take drop slice" :label "drop-while" :expected "[3 1]" :actual "(drop-while (fn [x] (< x 3)) [1 2 3 1])" :portability :common} - {:suite "seq / take drop slice" :label "take-last" :expected "[4 5]" :actual "(take-last 2 [1 2 3 4 5])" :portability :common} - {:suite "seq / take drop slice" :label "drop-last" :expected "[1 2 3]" :actual "(drop-last [1 2 3 4])" :portability :common} - {:suite "seq / take drop slice" :label "take-nth" :expected "[1 3 5]" :actual "(take-nth 2 [1 2 3 4 5])" :portability :common} - {:suite "seq / take drop slice" :label "partition" :expected "[[1 2] [3 4]]" :actual "(partition 2 [1 2 3 4 5])" :portability :common} - {:suite "seq / take drop slice" :label "partition-all" :expected "[[1 2] [3]]" :actual "(partition-all 2 [1 2 3])" :portability :common} - {:suite "seq / take drop slice" :label "partition elems are seqs" :expected "true" :actual "(every? seq? (partition 2 [1 2 3 4]))" :portability :common} - {:suite "seq / take drop slice" :label "partition-all elems are seqs not vectors" :expected "true" :actual "(every? seq? (partition-all 2 (range 5)))" :portability :common} - {:suite "seq / take drop slice" :label "partition-all elem is not a vector" :expected "false" :actual "(vector? (first (partition-all 2 [1 2 3])))" :portability :common} - {:suite "seq / take drop slice" :label "partition-all [n step coll] elems are seqs" :expected "true" :actual "(every? seq? (partition-all 2 2 [1 2 3 4]))" :portability :common} - {:suite "seq / take drop slice" :label "partition-by elems are seqs" :expected "true" :actual "(every? seq? (partition-by odd? [1 3 2 4]))" :portability :common} - {:suite "seq / take drop slice" :label "split-at" :expected "[[1 2] [3 4]]" :actual "(split-at 2 [1 2 3 4])" :portability :common} - {:suite "seq / transform" :label "reverse" :expected "[3 2 1]" :actual "(reverse [1 2 3])" :portability :common} - {:suite "seq / transform" :label "sort" :expected "[1 2 3]" :actual "(sort [3 1 2])" :portability :common} - {:suite "seq / transform" :label "sort with comparator" :expected "[3 2 1]" :actual "(sort > [1 3 2])" :portability :common} - {:suite "seq / transform" :label "sort-by" :expected "[[1] [2 2]]" :actual "(sort-by count [[2 2] [1]])" :portability :common} - {:suite "seq / transform" :label "distinct" :expected "[1 2 3]" :actual "(distinct [1 1 2 3 3])" :portability :common} - {:suite "seq / transform" :label "dedupe" :expected "[1 2 1]" :actual "(dedupe [1 1 2 1])" :portability :common} - {:suite "seq / transform" :label "interpose" :expected "[1 0 2 0 3]" :actual "(interpose 0 [1 2 3])" :portability :common} - {:suite "seq / transform" :label "interleave" :expected "[1 :a 2 :b]" :actual "(interleave [1 2] [:a :b])" :portability :common} - {:suite "seq / transform" :label "flatten" :expected "[1 2 3 4]" :actual "(flatten [1 [2 [3 [4]]]])" :portability :common} - {:suite "seq / transform" :label "concat" :expected "[1 2 3 4]" :actual "(concat [1 2] [3 4])" :portability :common} - {:suite "seq / transform" :label "into vector" :expected "[1 2 3 4]" :actual "(into [1 2] [3 4])" :portability :common} - {:suite "seq / transform" :label "into list" :expected "[3 2 1]" :actual "(into (list) [1 2 3])" :portability :common} - {:suite "seq / transform" :label "frequencies" :expected "{1 2, 2 1}" :actual "(frequencies [1 1 2])" :portability :common} - {:suite "seq / transform" :label "group-by" :expected "{false [1 3], true [2 4]}" :actual "(group-by even? [1 2 3 4])" :portability :common} - {:suite "seq / transform" :label "zipmap" :expected "{:a 1, :b 2}" :actual "(zipmap [:a :b] [1 2])" :portability :common} - {:suite "seq / transform" :label "mapcat seqs" :expected "[1 2 3 4]" :actual "(mapcat identity [[1 2] [3 4]])" :portability :common} - {:suite "seq / generators" :label "range n" :expected "[0 1 2 3]" :actual "(range 4)" :portability :common} - {:suite "seq / generators" :label "range from to" :expected "[2 3 4]" :actual "(range 2 5)" :portability :common} - {:suite "seq / generators" :label "range with step" :expected "[0 2 4]" :actual "(range 0 6 2)" :portability :common} - {:suite "seq / generators" :label "take repeat" :expected "[:x :x :x]" :actual "(take 3 (repeat :x))" :portability :common} - {:suite "seq / generators" :label "repeat n" :expected "[5 5]" :actual "(repeat 2 5)" :portability :common} - {:suite "seq / generators" :label "take iterate" :expected "[1 2 4 8]" :actual "(take 4 (iterate (fn [x] (* x 2)) 1))" :portability :common} - {:suite "seq / generators" :label "take cycle" :expected "[1 2 1 2 1]" :actual "(take 5 (cycle [1 2]))" :portability :common} - {:suite "seq / generators" :label "take repeatedly" :expected "3" :actual "(count (take 3 (repeatedly (fn [] 1))))" :portability :common} - {:suite "seq / generators" :label "take-last of range" :expected "[8 9]" :actual "(take-last 2 (range 10))" :portability :common} - {:suite "seq / IFn values as functions" :label "map keyword" :expected "[1 2 3]" :actual "(map :a [{:a 1} {:a 2} {:a 3}])" :portability :common} - {:suite "seq / IFn values as functions" :label "filter keyword" :expected "[{:ok true}]" :actual "(filter :ok [{:ok true} {:ok false}])" :portability :common} - {:suite "seq / IFn values as functions" :label "remove keyword" :expected "[{:ok false}]" :actual "(remove :ok [{:ok true} {:ok false}])" :portability :common} - {:suite "seq / IFn values as functions" :label "sort-by keyword" :expected "[{:a 1} {:a 2} {:a 3}]" :actual "(sort-by :a [{:a 3} {:a 1} {:a 2}])" :portability :common} - {:suite "seq / IFn values as functions" :label "sort-by key + cmp" :expected "[{:a 3} {:a 2} {:a 1}]" :actual "(sort-by :a > [{:a 3} {:a 1} {:a 2}])" :portability :common} - {:suite "seq / IFn values as functions" :label "filter set" :expected "[2 4]" :actual "(filter #{2 4} [1 2 3 4 5])" :portability :common} - {:suite "seq / IFn values as functions" :label "remove set" :expected "[1 3 5]" :actual "(remove #{2 4} [1 2 3 4 5])" :portability :common} - {:suite "seq / IFn values as functions" :label "group-by keyword" :expected "{1 [{:n 1}], 2 [{:n 2}]}" :actual "(group-by :n [{:n 1} {:n 2}])" :portability :common} - {:suite "seq / IFn values as functions" :label "map a map" :expected "[1 nil 2]" :actual "(map {:a 1 :b 2} [:a :z :b])" :portability :common} - {:suite "seq / IFn values as functions" :label "take-nth transducer" :expected "[0 2 4 6 8]" :actual "(into [] (take-nth 2) (range 10))" :portability :common} - {:suite "seq / IFn values as functions" :label "interpose transducer" :expected "[1 :x 2]" :actual "(into [] (interpose :x) [1 2])" :portability :common} - {:suite "seq / conj edge cases" :label "conj no args" :expected "[]" :actual "(conj)" :portability :common} - {:suite "seq / conj edge cases" :label "conj nil one" :expected "[3]" :actual "(conj nil 3)" :portability :common} - {:suite "seq / conj edge cases" :label "conj nil many" :expected "[2 1]" :actual "(conj nil 1 2)" :portability :common} - {:suite "seq / conj edge cases" :label "conj vector" :expected "[1 2 3]" :actual "(conj [1 2] 3)" :portability :common} - {:suite "seq / conj edge cases" :label "conj list prepend" :expected "[0 1 2]" :actual "(conj '(1 2) 0)" :portability :common} - {:suite "seq / conj edge cases" :label "conj map + map" :expected "{:a 0, :b 1}" :actual "(conj {:a 0} {:b 1})" :portability :common} - {:suite "seq / conj edge cases" :label "conj map + pair" :expected "{:a 0, :b 1}" :actual "(conj {:a 0} [:b 1])" :portability :common} - {:suite "seq / conj edge cases" :label "conj map merge wins" :expected "{:a 2}" :actual "(conj {:a 0} {:a 1} {:a 2})" :portability :common} - {:suite "seq / strictness (throws like Clojure)" :label "cons non-seqable num" :expected :throws :actual "(cons 1 42)" :portability :common} - {:suite "seq / strictness (throws like Clojure)" :label "cons non-seqable kw" :expected :throws :actual "(cons 1 :k)" :portability :common} - {:suite "seq / strictness (throws like Clojure)" :label "cons onto nil ok" :expected "[1]" :actual "(cons 1 nil)" :portability :common} - {:suite "seq / strictness (throws like Clojure)" :label "cons onto seq ok" :expected "[0 1 2]" :actual "(cons 0 [1 2])" :portability :common} - {:suite "seq / strictness (throws like Clojure)" :label "num non-number" :expected :throws :actual "(num \"x\")" :portability :common} - {:suite "seq / strictness (throws like Clojure)" :label "num ok" :expected "5" :actual "(num 5)" :portability :common} - {:suite "seq / strictness (throws like Clojure)" :label "realized? on number" :expected :throws :actual "(realized? 1)" :portability :common} - {:suite "seq / strictness (throws like Clojure)" :label "realized? on nil" :expected :throws :actual "(realized? nil)" :portability :common} - {:suite "seq / strictness (throws like Clojure)" :label "symbol from nil" :expected :throws :actual "(symbol nil)" :portability :common} - {:suite "seq / strictness (throws like Clojure)" :label "symbol bad 2-arg" :expected :throws :actual "(symbol :a \"b\")" :portability :common} - {:suite "seq / strictness (throws like Clojure)" :label "symbol from keyword" :expected "\"x\"" :actual "(name (symbol :x))" :portability :common} - {:suite "seq / strictness (throws like Clojure)" :label "keyword bad 2-arg" :expected :throws :actual "(keyword \"abc\" nil)" :portability :common} - {:suite "seq / strictness (throws like Clojure)" :label "keyword from symbol" :expected "\"x\"" :actual "(name (keyword 'x))" :portability :common} - {:suite "seq / accessor strictness" :label "peek vector" :expected "3" :actual "(peek [1 2 3])" :portability :common} - {:suite "seq / accessor strictness" :label "peek list" :expected "1" :actual "(peek '(1 2 3))" :portability :common} - {:suite "seq / accessor strictness" :label "peek empty vec" :expected "nil" :actual "(peek [])" :portability :common} - {:suite "seq / accessor strictness" :label "peek on set" :expected :throws :actual "(peek #{1 2})" :portability :common} - {:suite "seq / accessor strictness" :label "peek on number" :expected :throws :actual "(peek 42)" :portability :common} - {:suite "seq / accessor strictness" :label "pop empty vec" :expected :throws :actual "(pop [])" :portability :common} - {:suite "seq / accessor strictness" :label "pop on number" :expected :throws :actual "(pop 0)" :portability :common} - {:suite "seq / accessor strictness" :label "pop vector" :expected "[1 2]" :actual "(pop [1 2 3])" :portability :common} - {:suite "seq / accessor strictness" :label "vec on number" :expected :throws :actual "(vec 42)" :portability :common} - {:suite "seq / accessor strictness" :label "vec on keyword" :expected :throws :actual "(vec :a)" :portability :common} - {:suite "seq / accessor strictness" :label "vec ok" :expected "[1 2]" :actual "(vec '(1 2))" :portability :common} - {:suite "seq / accessor strictness" :label "key on nil" :expected :throws :actual "(key nil)" :portability :common} - {:suite "seq / accessor strictness" :label "key on map" :expected :throws :actual "(key {})" :portability :common} - {:suite "seq / accessor strictness" :label "val on number" :expected :throws :actual "(val 0)" :portability :common} - {:suite "seq / accessor strictness" :label "key of entry" :expected ":a" :actual "(key (first {:a 1}))" :portability :common} - {:suite "seq / accessor strictness" :label "val of entry" :expected "1" :actual "(val (first {:a 1}))" :portability :common} - {:suite "seq / more strictness" :label "first on number" :expected :throws :actual "(first 42)" :portability :common} - {:suite "seq / more strictness" :label "first on keyword" :expected :throws :actual "(first :a)" :portability :common} - {:suite "seq / more strictness" :label "first ok vec" :expected "1" :actual "(first [1 2])" :portability :common} - {:suite "seq / more strictness" :label "first ok nil" :expected "nil" :actual "(first nil)" :portability :common} - {:suite "seq / more strictness" :label "rseq vector" :expected "[3 2 1]" :actual "(rseq [1 2 3])" :portability :common} - {:suite "seq / more strictness" :label "rseq on string" :expected :throws :actual "(rseq \"ab\")" :portability :common} - {:suite "seq / more strictness" :label "rseq on map" :expected :throws :actual "(rseq {:a 1})" :portability :common} - {:suite "seq / more strictness" :label "rseq on number" :expected :throws :actual "(rseq 0)" :portability :common} - {:suite "seq / more strictness" :label "assoc odd args" :expected :throws :actual "(assoc {:a 1} :b)" :portability :common} - {:suite "seq / more strictness" :label "assoc on number" :expected :throws :actual "(assoc 5 :a 1)" :portability :common} - {:suite "seq / more strictness" :label "assoc on set" :expected :throws :actual "(assoc #{} :a 1)" :portability :common} - {:suite "seq / strictness round 3" :label "seq on number" :expected :throws :actual "(seq 1)" :portability :common} - {:suite "seq / strictness round 3" :label "seq on fn" :expected :throws :actual "(seq (fn [] 1))" :portability :common} - {:suite "seq / strictness round 3" :label "seq vector ok" :expected "[1 2]" :actual "(seq [1 2])" :portability :common} - {:suite "seq / strictness round 3" :label "NaN? on nil" :expected :throws :actual "(NaN? nil)" :portability :common} - {:suite "seq / strictness round 3" :label "NaN? on number ok" :expected "false" :actual "(NaN? 1.0)" :portability :common} - {:suite "seq / strictness round 3" :label "shuffle on number" :expected :throws :actual "(shuffle 1)" :portability :common} - {:suite "seq / strictness round 3" :label "shuffle on string" :expected :throws :actual "(shuffle \"abc\")" :portability :common} - {:suite "seq / strictness round 3" :label "shuffle vec ok" :expected "3" :actual "(count (shuffle [1 2 3]))" :portability :common} - {:suite "seq / strictness round 3" :label "nthrest nil count" :expected :throws :actual "(nthrest [0 1 2] nil)" :portability :common} - {:suite "seq / strictness round 3" :label "nthrest negative" :expected "[0 1 2]" :actual "(nthrest [0 1 2] -1)" :portability :common} - {:suite "seq / strictness round 3" :label "nthrest nil coll" :expected "nil" :actual "(nthrest nil 0)" :portability :common} - {:suite "seq / strictness round 3" :label "nthnext nil count" :expected :throws :actual "(nthnext [0 1 2] nil)" :portability :common} - {:suite "seq / strictness round 3" :label "update vec oob" :expected :throws :actual "(update [] 1 identity)" :portability :common} - {:suite "seq / strictness round 3" :label "update vec kw key" :expected :throws :actual "(update [1 2 3] :k identity)" :portability :common} - {:suite "seq / overlay-migrated fns" :label "nthrest exhausted -> ()" :expected "[]" :actual "(nthrest nil 100)" :portability :common} - {:suite "seq / overlay-migrated fns" :label "nthrest vec exhausted" :expected "[]" :actual "(nthrest [1 2 3] 100)" :portability :common} - {:suite "seq / overlay-migrated fns" :label "nthrest n<=0 keeps coll" :expected "[1 2 3]" :actual "(nthrest [1 2 3] 0)" :portability :common} - {:suite "seq / overlay-migrated fns" :label "nthrest drops n" :expected "[3 4 5]" :actual "(nthrest [1 2 3 4 5] 2)" :portability :common} - {:suite "seq / overlay-migrated fns" :label "nthnext exhausted -> nil" :expected "nil" :actual "(nthnext [1 2] 5)" :portability :common} - {:suite "seq / overlay-migrated fns" :label "nthnext surprising nil" :expected "nil" :actual "(nthnext nil nil)" :portability :common} - {:suite "seq / overlay-migrated fns" :label "nthnext drops n" :expected "[3 4]" :actual "(nthnext [1 2 3 4] 2)" :portability :common} - {:suite "seq / overlay-migrated fns" :label "distinct? distinct" :expected "true" :actual "(distinct? 1 2 3)" :portability :common} - {:suite "seq / overlay-migrated fns" :label "distinct? dup" :expected "false" :actual "(distinct? 1 2 1)" :portability :common} - {:suite "seq / overlay-migrated fns" :label "distinct? equal colls" :expected "false" :actual "(distinct? [1 2] [1 2])" :portability :common} - {:suite "seq / overlay-migrated fns" :label "distinct? single" :expected "true" :actual "(distinct? 5)" :portability :common} - {:suite "seq / overlay-migrated fns" :label "replace maps elements" :expected "[:a 2 :c 2]" :actual "(replace {1 :a 3 :c} [1 2 3 2])" :portability :common} - {:suite "seq / overlay-migrated fns" :label "replace preserves nil val" :expected "[1 nil 3]" :actual "(replace {2 nil} [1 2 3])" :portability :common} - {:suite "seq / overlay-migrated fns" :label "replace on a vector stays a vector" :expected "true" :actual "(vector? (replace {1 :a} [1 2 1]))" :portability :common} - {:suite "seq / overlay-migrated fns" :label "replace on a seq returns a seq" :expected "true" :actual "(seq? (replace {1 :a} (list 1 2 1)))" :portability :common} - {:suite "seq / overlay-migrated fns" :label "replace on a seq is lazy" :expected "[0 :a 2]" :actual "(take 3 (replace {1 :a} (range)))" :portability :common} - {:suite "seq / overlay-migrated fns" :label "take-last" :expected "[3 4]" :actual "(take-last 2 [1 2 3 4])" :portability :common} - {:suite "seq / overlay-migrated fns" :label "take-last empty -> nil" :expected "nil" :actual "(take-last 2 [])" :portability :common} - {:suite "seq / overlay-migrated fns" :label "take-last n>len" :expected "[1 2]" :actual "(take-last 9 [1 2])" :portability :common} - {:suite "seq / overlay-migrated fns" :label "drop-last default 1" :expected "[1 2]" :actual "(drop-last [1 2 3])" :portability :common} - {:suite "seq / overlay-migrated fns" :label "drop-last n" :expected "[1 2]" :actual "(drop-last 2 [1 2 3 4])" :portability :common} - {:suite "seq / overlay-migrated fns" :label "split-with" :expected "[[2 4] [5 6]]" :actual "(split-with even? [2 4 5 6])" :portability :common} - {:suite "seq / overlay-migrated fns" :label "replicate" :expected "[:x :x :x]" :actual "(replicate 3 :x)" :portability :common} - {:suite "seq / overlay-migrated fns" :label "bounded-count" :expected "5" :actual "(bounded-count 3 [1 2 3 4 5])" :portability :common} - {:suite "seq / overlay-migrated fns" :label "bounded-count uncounted" :expected "3" :actual "(bounded-count 3 (filter odd? (range 100)))" :portability :common} - {:suite "seq / overlay-migrated fns" :label "run! side effects" :expected "6" :actual "(let [a (atom 0)] (run! (fn [x] (swap! a + x)) [1 2 3]) @a)" :portability :common} - {:suite "seq / overlay-migrated fns" :label "completing wraps rf" :expected "3" :actual "((completing +) 1 2)" :portability :common} - {:suite "seq / overlay-migrated fns" :label "comparator <" :expected "[1 2 3]" :actual "(sort (comparator <) [3 1 2])" :portability :common} - {:suite "seq / overlay-migrated fns" :label "comparator >" :expected "[3 2 1]" :actual "(sort (comparator >) [3 1 2])" :portability :common} - {:suite "seq / overlay-migrated fns" :label "reductions" :expected "[1 3 6 10]" :actual "(reductions + [1 2 3 4])" :portability :common} - {:suite "seq / overlay-migrated fns" :label "reductions with init" :expected "[10 11 13 16]" :actual "(reductions + 10 [1 2 3])" :portability :common} - {:suite "seq / overlay-migrated fns" :label "reductions empty calls f" :expected "[0]" :actual "(reductions + [])" :portability :common} - {:suite "seq / overlay-migrated fns" :label "reductions empty + init" :expected "[5]" :actual "(reductions + 5 [])" :portability :common} - {:suite "seq / overlay-migrated fns" :label "tree-seq pre-order" :expected "[[1 [2] 3] 1 [2] 2 3]" :actual "(tree-seq sequential? seq [1 [2] 3])" :portability :common} - {:suite "seq / overlay-migrated fns" :label "some found" :expected "true" :actual "(some even? [1 3 4])" :portability :common} - {:suite "seq / overlay-migrated fns" :label "some none -> nil" :expected "nil" :actual "(some even? [1 3 5])" :portability :common} - {:suite "seq / overlay-migrated fns" :label "some keyword pred" :expected "7" :actual "(some :a [{:b 1} {:a 7}])" :portability :common} - {:suite "seq / overlay-migrated fns" :label "some returns value" :expected "4" :actual "(some (fn [x] (when (even? x) x)) [1 3 4 5])" :portability :common} - {:suite "seq / overlay-migrated fns" :label "flatten nested" :expected "[1 2 3 4 5]" :actual "(flatten [1 [2 [3 4]] 5])" :portability :common} - {:suite "seq / overlay-migrated fns" :label "flatten lists too" :expected "[1 2 3]" :actual "(flatten [1 (list 2 3)])" :portability :common} - {:suite "seq / overlay-migrated fns" :label "flatten scalar -> empty" :expected "[]" :actual "(flatten 5)" :portability :common} - {:suite "seq / overlay-migrated fns" :label "interleave" :expected "[1 :a 2 :b]" :actual "(interleave [1 2 3] [:a :b])" :portability :common} - {:suite "seq / overlay-migrated fns" :label "interleave empty" :expected "[]" :actual "(interleave)" :portability :common} - {:suite "seq / overlay-migrated fns" :label "rationalize identity" :expected "5" :actual "(rationalize 5)" :portability :common} - {:suite "seq / overlay-migrated fns" :label "dedupe consecutive" :expected "[1 2 3 1]" :actual "(dedupe [1 1 2 2 3 1 1])" :portability :common} - {:suite "seq / overlay-migrated fns" :label "dedupe empty" :expected "[]" :actual "(dedupe [])" :portability :common} - {:suite "seq / overlay-migrated fns" :label "dedupe no dups" :expected "[1 2 3]" :actual "(dedupe [1 2 3])" :portability :common} - {:suite "seq / partitionv & splitv-at (1.11)" :label "partitionv" :expected "[[1 2] [3 4]]" :actual "(partitionv 2 [1 2 3 4 5])" :portability :common} - {:suite "seq / partitionv & splitv-at (1.11)" :label "partitionv elems are vectors" :expected "true" :actual "(every? vector? (partitionv 2 [1 2 3 4]))" :portability :common} - {:suite "seq / partitionv & splitv-at (1.11)" :label "partitionv step" :expected "[[1 2] [3 4]]" :actual "(partitionv 2 2 [1 2 3 4 5])" :portability :common} - {:suite "seq / partitionv & splitv-at (1.11)" :label "partitionv pad" :expected "[[1 2] [3 :p]]" :actual "(partitionv 2 2 [:p] [1 2 3])" :portability :common} - {:suite "seq / partitionv & splitv-at (1.11)" :label "partitionv-all" :expected "[[1 2] [3]]" :actual "(partitionv-all 2 [1 2 3])" :portability :common} - {:suite "seq / partitionv & splitv-at (1.11)" :label "partitionv-all vectors" :expected "true" :actual "(every? vector? (partitionv-all 2 [1 2 3]))" :portability :common} - {:suite "seq / partitionv & splitv-at (1.11)" :label "splitv-at" :expected "[[1 2] [3 4]]" :actual "(splitv-at 2 [1 2 3 4])" :portability :common} - {:suite "seq / partitionv & splitv-at (1.11)" :label "splitv-at first is vector" :expected "true" :actual "(vector? (first (splitv-at 2 [1 2 3])))" :portability :common} - {:suite "seq / partitionv & splitv-at (1.11)" :label "splitv-at past end" :expected "[[1 2] []]" :actual "(splitv-at 5 [1 2])" :portability :common} - {:suite "sequences / linear walks over concrete collections" :label "rest of vector is a seq" :expected "true" :actual "(seq? (rest [1 2 3]))" :portability :common} - {:suite "sequences / linear walks over concrete collections" :label "rest of vector not vector" :expected "false" :actual "(vector? (rest [1 2 3]))" :portability :common} - {:suite "sequences / linear walks over concrete collections" :label "rest values" :expected "[2 3]" :actual "(rest [1 2 3])" :portability :common} - {:suite "sequences / linear walks over concrete collections" :label "next of vector" :expected "[2 3]" :actual "(next [1 2 3])" :portability :common} - {:suite "sequences / linear walks over concrete collections" :label "next exhausts to nil" :expected "nil" :actual "(next [1])" :portability :common} - {:suite "sequences / linear walks over concrete collections" :label "rest exhausts to ()" :expected "[]" :actual "(rest [1])" :portability :common} - {:suite "sequences / linear walks over concrete collections" :label "rest-loop scales (20k linear)" :expected "20000" :actual "(loop [xs (seq (vec (range 20000))) n 0] (if xs (recur (next xs) (inc n)) n))" :portability :common} - {:suite "sequences / linear walks over concrete collections" :label "mapv scales (50k linear)" :expected "50000" :actual "(count (mapv inc (vec (range 50000))))" :portability :common} - {:suite "sequences / linear walks over concrete collections" :label "nested walk" :expected "[2 3]" :actual "(vec (rest (mapv inc [0 1 2])))" :portability :common} - {:suite "sequences / rest & next over set-like colls" :label "next of set" :expected "true" :actual "(let [n (next #{1 2})] (and (= 1 (count n)) (contains? #{1 2} (first n))))" :portability :common} - {:suite "sequences / rest & next over set-like colls" :label "rest of set count" :expected "1" :actual "(count (rest #{1 2}))" :portability :common} - {:suite "sequences / rest & next over set-like colls" :label "next of singleton set" :expected "nil" :actual "(next #{1})" :portability :common} - {:suite "sequences / rest & next over set-like colls" :label "rest of empty set" :expected "0" :actual "(count (rest #{}))" :portability :common} - {:suite "sequences / rest & next over set-like colls" :label "next of map" :expected "true" :actual "(let [n (next {:a 1 :b 2})] (and (= 1 (count n)) (map-entry? (first n))))" :portability :common} - {:suite "sequences / rest & next over set-like colls" :label "next of singleton map" :expected "nil" :actual "(next {:a 1})" :portability :common} - {:suite "sequences / rest & next over set-like colls" :label "rest of sorted-set" :expected "[2 3]" :actual "(rest (sorted-set 3 1 2))" :portability :common} - {:suite "sequences / rest & next over set-like colls" :label "next of sorted-map" :expected "[[2 :b]]" :actual "(next (sorted-map 1 :a 2 :b))" :portability :common} - {:suite "sequences / rest & next over set-like colls" :label "every? over set" :expected "true" :actual "(every? pos? #{1 2 3})" :portability :common} - {:suite "sequences / rest & next over set-like colls" :label "every? over set false" :expected "false" :actual "(every? odd? #{1 2})" :portability :common} - {:suite "sequences / rest & next over set-like colls" :label "every? over sorted-set" :expected "true" :actual "(every? pos? (sorted-set 1 2 3))" :portability :common} - {:suite "sequences / rest & next over set-like colls" :label "every? over map entries" :expected "true" :actual "(every? map-entry? (seq {:a 1 :b 2}))" :portability :common} - {:suite "set / construct & predicate" :label "literal" :expected "#{1 3 2}" :actual "#{1 2 3}" :portability :common} - {:suite "set / construct & predicate" :label "hash-set" :expected "#{1 3 2}" :actual "(hash-set 1 2 3)" :portability :common} - {:suite "set / construct & predicate" :label "set from vector" :expected "#{1 3 2}" :actual "(set [1 2 3 1])" :portability :common} - {:suite "set / construct & predicate" :label "empty" :expected "#{}" :actual "#{}" :portability :common} - {:suite "set / construct & predicate" :label "set? true" :expected "true" :actual "(set? #{1})" :portability :common} - {:suite "set / construct & predicate" :label "set? false on vector" :expected "false" :actual "(set? [1])" :portability :common} - {:suite "set / construct & predicate" :label "count dedups" :expected "3" :actual "(count (set [1 1 2 3]))" :portability :common} - {:suite "set / construct & predicate" :label "equality order-indep" :expected "true" :actual "(= #{1 2 3} #{3 2 1})" :portability :common} - {:suite "set / construct & predicate" :label "into set" :expected "#{:b :a}" :actual "(into #{} [:a :b])" :portability :common} - {:suite "set / construct & predicate" :label "into non-empty set" :expected "#{1 3 2}" :actual "(into #{1} [2 3 2])" :portability :common} - {:suite "set / operations" :label "conj adds" :expected "#{1 3 2}" :actual "(conj #{1 2} 3)" :portability :common} - {:suite "set / operations" :label "conj dup no-op" :expected "#{1 2}" :actual "(conj #{1 2} 1)" :portability :common} - {:suite "set / operations" :label "disj removes" :expected "#{1 2}" :actual "(disj #{1 2 3} 3)" :portability :common} - {:suite "set / operations" :label "disj missing no-op" :expected "#{1 2}" :actual "(disj #{1 2} 9)" :portability :common} - {:suite "set / operations" :label "contains?" :expected "true" :actual "(contains? #{1 2} 1)" :portability :common} - {:suite "set / operations" :label "contains? missing" :expected "false" :actual "(contains? #{1 2} 9)" :portability :common} - {:suite "set / operations" :label "get present" :expected "1" :actual "(get #{1 2} 1)" :portability :common} - {:suite "set / operations" :label "get missing nil" :expected "nil" :actual "(get #{1 2} 9)" :portability :common} - {:suite "set / operations" :label "set as fn present" :expected "2" :actual "(#{1 2 3} 2)" :portability :common} - {:suite "set / operations" :label "set as fn missing" :expected "nil" :actual "(#{1 2 3} 9)" :portability :common} - {:suite "set / literals & value elements" :label "literal evaluates elements" :expected "#{4 2}" :actual "#{(inc 1) (* 2 2)}" :portability :common} - {:suite "set / literals & value elements" :label "map elements by value" :expected "true" :actual "(= #{{:a 1}} #{(hash-map :a 1)})" :portability :common} - {:suite "set / literals & value elements" :label "contains? map by value" :expected "true" :actual "(contains? #{(hash-map :x 1)} {:x 1})" :portability :common} - {:suite "set / literals & value elements" :label "dedup equal maps" :expected "1" :actual "(count (set [{:a 1} (hash-map :a 1)]))" :portability :common} - {:suite "set / literals & value elements" :label "vector elements" :expected "true" :actual "(contains? #{[1 2]} (vec [1 2]))" :portability :common} - {:suite "set / nil element" :label "set keeps nil" :expected "2" :actual "(count (set [nil 1 nil]))" :portability :common} - {:suite "set / nil element" :label "contains? nil true" :expected "true" :actual "(contains? (set [nil 1]) nil)" :portability :common} - {:suite "set / nil element" :label "contains? nil false" :expected "false" :actual "(contains? #{1} nil)" :portability :common} - {:suite "set / nil element" :label "seq includes nil" :expected "true" :actual "(some nil? (seq (set [nil 1])))" :portability :common} - {:suite "set / nil element" :label "disj nil" :expected "#{1}" :actual "(disj (set [nil 1]) nil)" :portability :common} - {:suite "set / nil element" :label "disj nil count" :expected "1" :actual "(count (disj (set [nil 1]) nil))" :portability :common} - {:suite "set / nil element" :label "conj nil count" :expected "2" :actual "(count (conj #{1} nil))" :portability :common} - {:suite "set / nil element" :label "conj nil contains?" :expected "true" :actual "(contains? (conj #{1} nil) nil)" :portability :common} - {:suite "set / nil element" :label "into #{} keeps nil" :expected "2" :actual "(count (into #{} [nil 1]))" :portability :common} - {:suite "set / nil element" :label "into #{} contains? nil" :expected "true" :actual "(contains? (into #{} [nil 1]) nil)" :portability :common} - {:suite "set / nil element" :label "into keeps existing nil" :expected "true" :actual "(contains? (into #{nil} [1]) nil)" :portability :common} - {:suite "set / nil element" :label "transient conj! nil" :expected "2" :actual "(count (persistent! (conj! (transient #{}) nil 1)))" :portability :common} - {:suite "set / nil element" :label "transient contains? nil" :expected "true" :actual "(contains? (persistent! (conj! (transient #{}) nil 1)) nil)" :portability :common} - {:suite "set / nil element" :label "transient disj! nil cnt" :expected "1" :actual "(count (persistent! (disj! (conj! (transient #{}) nil 1) nil)))" :portability :common} - {:suite "set / nil element" :label "transient disj! removes" :expected "false" :actual "(contains? (persistent! (disj! (conj! (transient #{}) nil 1) nil)) nil)" :portability :common} - {:suite "set / nil element" :label "transient of set w/ nil" :expected "true" :actual "(contains? (persistent! (transient (set [nil 1]))) nil)" :portability :common} - {:suite "clojure.set" :label "union" :expected "#{1 4 3 2}" :actual "(do (require (quote [clojure.set :as s])) (s/union #{1 2} #{3 4}))" :portability :common} - {:suite "clojure.set" :label "intersection" :expected "#{2}" :actual "(do (require (quote [clojure.set :as s])) (s/intersection #{1 2} #{2 3}))" :portability :common} - {:suite "clojure.set" :label "difference" :expected "#{1}" :actual "(do (require (quote [clojure.set :as s])) (s/difference #{1 2} #{2 3}))" :portability :common} - {:suite "clojure.set" :label "subset? true" :expected "true" :actual "(do (require (quote [clojure.set :as s])) (s/subset? #{1} #{1 2}))" :portability :common} - {:suite "clojure.set" :label "superset? true" :expected "true" :actual "(do (require (quote [clojure.set :as s])) (s/superset? #{1 2} #{1}))" :portability :common} - {:suite "clojure.set" :label "select" :expected "#{4 2}" :actual "(do (require (quote [clojure.set :as s])) (s/select even? #{1 2 3 4}))" :portability :common} - {:suite "clojure.set" :label "join" :expected "#{{:a 1, :b 2, :c 3}}" :actual "(do (require (quote [clojure.set :as s])) (s/join #{{:a 1 :b 2}} #{{:b 2 :c 3}}))" :portability :common} - {:suite "clojure.set" :label "map-invert" :expected "{1 :a}" :actual "(do (require (quote [clojure.set :as s])) (s/map-invert {:a 1}))" :portability :common} - {:suite "clojure.set" :label "rename-keys" :expected "{:b 1}" :actual "(do (require (quote [clojure.set :as s])) (s/rename-keys {:a 1} {:a :b}))" :portability :common} - {:suite "set / set? across representations" :label "literal" :expected "true" :actual "(set? #{1})" :portability :common} - {:suite "set / set? across representations" :label "empty literal" :expected "true" :actual "(set? #{})" :portability :common} - {:suite "set / set? across representations" :label "sorted-set" :expected "true" :actual "(set? (sorted-set 1 2))" :portability :common} - {:suite "set / set? across representations" :label "sorted-set-by" :expected "true" :actual "(set? (sorted-set-by > 1 2))" :portability :common} - {:suite "set / set? across representations" :label "empty sorted" :expected "true" :actual "(set? (sorted-set))" :portability :common} - {:suite "set / set? across representations" :label "map is not" :expected "false" :actual "(set? {})" :portability :common} - {:suite "set / set? across representations" :label "vector is not" :expected "false" :actual "(set? [1])" :portability :common} - {:suite "set / set? across representations" :label "coll? still true" :expected "true" :actual "(coll? (sorted-set 1))" :portability :common} - {:suite "set / set? across representations" :label "ifn? sorted-set" :expected "true" :actual "(ifn? (sorted-set 1))" :portability :common} - {:suite "set / bulk build boundaries" :label "set dedup count" :expected "3" :actual "(count (set [1 1 2 3 3 2]))" :portability :common} - {:suite "set / bulk build boundaries" :label "set big count" :expected "1000" :actual "(count (set (range 1000)))" :portability :common} - {:suite "set / bulk build boundaries" :label "into #{} count" :expected "500" :actual "(count (into #{} (range 500)))" :portability :common} - {:suite "set / bulk build boundaries" :label "into #{} onto base" :expected "3" :actual "(count (into #{:a} [:a :b :c]))" :portability :common} - {:suite "set / bulk build boundaries" :label "set contains" :expected "true" :actual "(contains? (set (range 1000)) 777)" :portability :common} - {:suite "set / bulk build boundaries" :label "set missing" :expected "false" :actual "(contains? (set (range 1000)) 5000)" :portability :common} - {:suite "set / bulk build boundaries" :label "set coll members" :expected "true" :actual "(contains? (set [[1 2] [3 4]]) [1 2])" :portability :common} - {:suite "set / bulk build boundaries" :label "conj after bulk" :expected "true" :actual "(contains? (conj (set (range 100)) :x) :x)" :portability :common} - {:suite "set / bulk build boundaries" :label "disj after bulk" :expected "false" :actual "(contains? (disj (set (range 100)) 50) 50)" :portability :common} - {:suite "set / bulk build boundaries" :label "set = literal" :expected "true" :actual "(= #{0 1 2} (set (range 3)))" :portability :common} - {:suite "sorted / construction & ordering" :label "sorted-set orders" :expected "[1 2 3]" :actual "(vec (seq (sorted-set 3 1 2)))" :portability :common} - {:suite "sorted / construction & ordering" :label "sorted-set dedupes" :expected "[1 2 3]" :actual "(vec (seq (sorted-set 3 1 2 1 3)))" :portability :common} - {:suite "sorted / construction & ordering" :label "sorted-set numeric" :expected "[1 2 10]" :actual "(vec (seq (sorted-set 10 1 2)))" :portability :common} - {:suite "sorted / construction & ordering" :label "sorted-map ordered entries" :expected "[[:a 1] [:b 2] [:c 3]]" :actual "(vec (seq (sorted-map :c 3 :a 1 :b 2)))" :portability :common} - {:suite "sorted / construction & ordering" :label "first is min" :expected "1" :actual "(first (sorted-set 5 3 9 1))" :portability :common} - {:suite "sorted / sorted?" :label "sorted-set" :expected "true" :actual "(sorted? (sorted-set 1))" :portability :common} - {:suite "sorted / sorted?" :label "sorted-map" :expected "true" :actual "(sorted? (sorted-map :a 1))" :portability :common} - {:suite "sorted / sorted?" :label "plain set" :expected "false" :actual "(sorted? #{1})" :portability :common} - {:suite "sorted / sorted?" :label "plain map" :expected "false" :actual "(sorted? {:a 1})" :portability :common} - {:suite "sorted / sorted?" :label "vector" :expected "false" :actual "(sorted? [1 2])" :portability :common} - {:suite "sorted / map ops" :label "get hit" :expected "2" :actual "(get (sorted-map :a 1 :b 2) :b)" :portability :common} - {:suite "sorted / map ops" :label "get miss default" :expected ":none" :actual "(get (sorted-map :a 1) :z :none)" :portability :common} - {:suite "sorted / map ops" :label "contains? yes" :expected "true" :actual "(contains? (sorted-map :a 1) :a)" :portability :common} - {:suite "sorted / map ops" :label "contains? no" :expected "false" :actual "(contains? (sorted-map :a 1) :z)" :portability :common} - {:suite "sorted / map ops" :label "assoc keeps order" :expected "[[:a 1] [:b 2] [:c 3]]" :actual "(vec (seq (assoc (sorted-map :c 3 :a 1) :b 2)))" :portability :common} - {:suite "sorted / map ops" :label "dissoc" :expected "[[:a 1] [:c 3]]" :actual "(vec (seq (dissoc (sorted-map :a 1 :b 2 :c 3) :b)))" :portability :common} - {:suite "sorted / map ops" :label "conj entry" :expected "[[:a 1] [:z 9]]" :actual "(vec (seq (conj (sorted-map :a 1) [:z 9])))" :portability :common} - {:suite "sorted / map ops" :label "keys sorted" :expected "[:a :b :c]" :actual "(vec (keys (sorted-map :c 3 :a 1 :b 2)))" :portability :common} - {:suite "sorted / map ops" :label "vals by key" :expected "[1 2 3]" :actual "(vec (vals (sorted-map :c 3 :a 1 :b 2)))" :portability :common} - {:suite "sorted / map ops" :label "map as fn" :expected "2" :actual "((sorted-map :a 1 :b 2) :b)" :portability :common} - {:suite "sorted / map ops" :label "map as fn miss" :expected ":d" :actual "((sorted-map :a 1) :z :d)" :portability :common} - {:suite "sorted / set ops" :label "get present" :expected "2" :actual "(get (sorted-set 1 2 3) 2)" :portability :common} - {:suite "sorted / set ops" :label "get absent" :expected ":none" :actual "(get (sorted-set 1 2 3) 9 :none)" :portability :common} - {:suite "sorted / set ops" :label "contains? yes" :expected "true" :actual "(contains? (sorted-set 1 2 3) 2)" :portability :common} - {:suite "sorted / set ops" :label "contains? no" :expected "false" :actual "(contains? (sorted-set 1 2 3) 9)" :portability :common} - {:suite "sorted / set ops" :label "conj keeps order" :expected "[0 1 2 3 5]" :actual "(vec (seq (conj (sorted-set 1 2 3) 5 0)))" :portability :common} - {:suite "sorted / set ops" :label "disj" :expected "[1 3]" :actual "(vec (seq (disj (sorted-set 1 2 3) 2)))" :portability :common} - {:suite "sorted / set ops" :label "set as fn" :expected "3" :actual "((sorted-set 1 2 3) 3)" :portability :common} - {:suite "sorted / set ops" :label "set as fn miss" :expected "nil" :actual "((sorted-set 1 2 3) 9)" :portability :common} - {:suite "sorted / by comparator" :label "sorted-set-by desc" :expected "[10 3 2 1]" :actual "(vec (seq (sorted-set-by > 1 3 2 10)))" :portability :common} - {:suite "sorted / by comparator" :label "sorted-map-by desc" :expected "[[3 :c] [2 :b] [1 :a]]" :actual "(vec (seq (sorted-map-by > 1 :a 3 :c 2 :b)))" :portability :common} - {:suite "sorted / by comparator" :label "conj keeps comparator" :expected "[5 3 2 1 0]" :actual "(vec (seq (conj (sorted-set-by > 1 3 2) 5 0)))" :portability :common} - {:suite "sorted / by comparator" :label "assoc keeps comparator" :expected "[3 2 1]" :actual "(vec (keys (assoc (sorted-map-by > 1 :a 3 :c) 2 :b)))" :portability :common} - {:suite "sorted / by comparator" :label "disj keeps comparator" :expected "[3 1]" :actual "(vec (seq (disj (sorted-set-by > 1 2 3) 2)))" :portability :common} - {:suite "sorted / by comparator" :label "by-comparator is sorted?" :expected "true" :actual "(sorted? (sorted-set-by > 1 2))" :portability :common} - {:suite "sorted / subseq & rsubseq" :label "subseq >=" :expected "[3 4 5]" :actual "(vec (subseq (sorted-set 1 2 3 4 5) >= 3))" :portability :common} - {:suite "sorted / subseq & rsubseq" :label "subseq <" :expected "[1 2]" :actual "(vec (subseq (sorted-set 1 2 3 4 5) < 3))" :portability :common} - {:suite "sorted / subseq & rsubseq" :label "subseq range" :expected "[2 3 4]" :actual "(vec (subseq (sorted-set 1 2 3 4 5) > 1 < 5))" :portability :common} - {:suite "sorted / subseq & rsubseq" :label "rsubseq <=" :expected "[3 2 1]" :actual "(vec (rsubseq (sorted-set 1 2 3 4 5) <= 3))" :portability :common} - {:suite "sorted / subseq & rsubseq" :label "subseq on map" :expected "[[2 :b] [3 :c]]" :actual "(vec (subseq (sorted-map 1 :a 2 :b 3 :c) > 1))" :portability :common} - {:suite "sorted / subseq & rsubseq" :label "subseq empty result" :expected "nil" :actual "(subseq (sorted-set 1 2) > 5)" :portability :common} - {:suite "sorted / subseq & rsubseq" :label "rsubseq on map" :expected "[[2 :b] [1 :a]]" :actual "(vec (rsubseq (sorted-map 1 :a 2 :b 3 :c) < 3))" :portability :common} - {:suite "sorted / predicates" :label "sorted-map? true" :expected "true" :actual "(sorted-map? (sorted-map 1 :a))" :portability :common} - {:suite "sorted / predicates" :label "sorted-map? false" :expected "false" :actual "(sorted-map? {:a 1})" :portability :common} - {:suite "sorted / predicates" :label "sorted-set? true" :expected "true" :actual "(sorted-set? (sorted-set 1))" :portability :common} - {:suite "sorted / predicates" :label "sorted-set? false" :expected "false" :actual "(sorted-set? #{1})" :portability :common} - {:suite "sorted / predicates" :label "map? sorted-map" :expected "true" :actual "(map? (sorted-map 1 :a))" :portability :common} - {:suite "sorted / predicates" :label "coll? sorted-set" :expected "true" :actual "(coll? (sorted-set 1))" :portability :common} - {:suite "sorted / lookup + membership use the comparator" :label "get cross-numeric" :expected ":a" :actual "(get (sorted-map 1 :a) 1.0)" :portability :common} - {:suite "sorted / lookup + membership use the comparator" :label "contains? cross-numeric" :expected "true" :actual "(contains? (sorted-set 1) 1.0)" :portability :common} - {:suite "sorted / lookup + membership use the comparator" :label "conj equal elem no-op" :expected "1" :actual "(count (conj (sorted-set 1) 1.0))" :portability :common} - {:suite "sorted / lookup + membership use the comparator" :label "assoc equal key replaces" :expected "[[1 :z]]" :actual "(vec (seq (assoc (sorted-map 1 :a) 1.0 :z)))" :portability :common} - {:suite "sorted / lookup + membership use the comparator" :label "first sorted-map" :expected "[1 :a]" :actual "(first (sorted-map 2 :b 1 :a))" :portability :common} - {:suite "sorted / lookup + membership use the comparator" :label "dissoc missing no-op" :expected "2" :actual "(count (dissoc (sorted-map 1 :a 2 :b) 9))" :portability :common} - {:suite "sorted / lookup + membership use the comparator" :label "conj map merges" :expected "3" :actual "(count (conj (sorted-map 1 :a) {2 :b 3 :c}))" :portability :common} - {:suite "sorted / lookup + membership use the comparator" :label "conj nil no-op" :expected "1" :actual "(count (conj (sorted-map 1 :a) nil))" :portability :common} - {:suite "sorted / lookup + membership use the comparator" :label "into sorted-map" :expected "[[1 :a] [2 :b]]" :actual "(vec (seq (into (sorted-map) [[2 :b] [1 :a]])))" :portability :common} - {:suite "sorted / lookup + membership use the comparator" :label "source unchanged" :expected "[1 2]" :actual "(let [s (sorted-set 1 2)] (conj s 9) (vec (seq s)))" :portability :common} - {:suite "sorted / lookup + membership use the comparator" :label "sorted-map odd kvs throws" :expected :throws :actual "(sorted-map 1 :a 2)" :portability :common} - {:suite "sorted / equality is representation-agnostic" :label "sorted-map = literal" :expected "true" :actual "(= (sorted-map :a 1 :b 2) {:a 1 :b 2})" :portability :common} - {:suite "sorted / equality is representation-agnostic" :label "literal = sorted-map" :expected "true" :actual "(= {:a 1 :b 2} (sorted-map :a 1 :b 2))" :portability :common} - {:suite "sorted / equality is representation-agnostic" :label "sorted-map = hash-map" :expected "true" :actual "(= (sorted-map :a 1) (hash-map :a 1))" :portability :common} - {:suite "sorted / equality is representation-agnostic" :label "sorted-map != more keys" :expected "false" :actual "(= (sorted-map :a 1) {:a 1 :b 2})" :portability :common} - {:suite "sorted / equality is representation-agnostic" :label "sorted-set = literal" :expected "true" :actual "(= (sorted-set 1 2) #{1 2})" :portability :common} - {:suite "sorted / equality is representation-agnostic" :label "literal = sorted-set" :expected "true" :actual "(= #{1 2} (sorted-set 2 1))" :portability :common} - {:suite "sorted / equality is representation-agnostic" :label "sorted-set != diff" :expected "false" :actual "(= (sorted-set 1 2) #{1 3})" :portability :common} - {:suite "sorted / equality is representation-agnostic" :label "two sorted-maps" :expected "true" :actual "(= (sorted-map 1 :a 2 :b) (sorted-map 2 :b 1 :a))" :portability :common} - {:suite "sorted / equality is representation-agnostic" :label "cmp irrelevant to =" :expected "true" :actual "(= (sorted-map-by > 1 :a 2 :b) (sorted-map 1 :a 2 :b))" :portability :common} - {:suite "sorted / equality is representation-agnostic" :label "sorted-map as map key" :expected ":hit" :actual "(get {(sorted-map :a 1) :hit} {:a 1})" :portability :common} - {:suite "sorted / equality is representation-agnostic" :label "sorted-set as map key" :expected ":hit" :actual "(get {(sorted-set 1 2) :hit} #{2 1})" :portability :common} - {:suite "sorted / empty + empty? + rseq + printing" :label "empty? empty map" :expected "true" :actual "(empty? (sorted-map))" :portability :common} - {:suite "sorted / empty + empty? + rseq + printing" :label "empty? non-empty" :expected "false" :actual "(empty? (sorted-map 1 :a))" :portability :common} - {:suite "sorted / empty + empty? + rseq + printing" :label "empty? empty set" :expected "true" :actual "(empty? (sorted-set))" :portability :common} - {:suite "sorted / empty + empty? + rseq + printing" :label "empty keeps sortedness" :expected "true" :actual "(sorted? (empty (sorted-map 1 :a)))" :portability :common} - {:suite "sorted / empty + empty? + rseq + printing" :label "empty keeps cmp" :expected "[3 1]" :actual "(vec (seq (into (empty (sorted-set-by > 1 2)) [1 3])))" :portability :common} - {:suite "sorted / empty + empty? + rseq + printing" :label "empty set kind" :expected "true" :actual "(sorted-set? (empty (sorted-set 1)))" :portability :common} - {:suite "sorted / empty + empty? + rseq + printing" :label "rseq map" :expected "[[2 :b] [1 :a]]" :actual "(vec (rseq (sorted-map 1 :a 2 :b)))" :portability :common} - {:suite "sorted / empty + empty? + rseq + printing" :label "rseq set" :expected "[3 2 1]" :actual "(vec (rseq (sorted-set 1 2 3)))" :portability :common} - {:suite "sorted / empty + empty? + rseq + printing" :label "pr-str sorted-map" :expected "\"{1 :a, 2 :b}\"" :actual "(pr-str (sorted-map 2 :b 1 :a))" :portability :common} - {:suite "sorted / empty + empty? + rseq + printing" :label "pr-str sorted-set" :expected "\"#{1 2 3}\"" :actual "(pr-str (sorted-set 3 1 2))" :portability :common} - {:suite "sorted / seq fn interop" :label "map over sorted-map" :expected "[1 2 3]" :actual "(vec (map first (sorted-map 2 :b 1 :a 3 :c)))" :portability :common} - {:suite "sorted / seq fn interop" :label "map over sorted-set" :expected "[2 3 4]" :actual "(vec (map inc (sorted-set 3 1 2)))" :portability :common} - {:suite "sorted / seq fn interop" :label "filter entries" :expected "[[2 :b]]" :actual "(vec (filter (fn [[k v]] (even? k)) (sorted-map 1 :a 2 :b)))" :portability :common} - {:suite "sorted / seq fn interop" :label "reduce over set" :expected "6" :actual "(reduce + (sorted-set 1 2 3))" :portability :common} - {:suite "sorted / seq fn interop" :label "vec of sorted-set" :expected "[1 2 3]" :actual "(vec (sorted-set 3 1 2))" :portability :common} - {:suite "sorted / seq fn interop" :label "into vec" :expected "[[1 :a] [2 :b]]" :actual "(into [] (sorted-map 2 :b 1 :a))" :portability :common} - {:suite "sorted / seq fn interop" :label "sorted-map-by 3way cmp" :expected "[3 2 1]" :actual "(vec (keys (sorted-map-by (fn [a b] (- b a)) 1 :a 2 :b 3 :c)))" :portability :common} - {:suite "io / slurp, spit, printf, flush (host-classified)" :label "slurp returns string" :expected "true" :actual "(string? (slurp \"README.md\"))" :portability :common} - {:suite "io / slurp, spit, printf, flush (host-classified)" :label "slurp content" :expected "true" :actual "(do (require (quote [clojure.string :as s])) (s/includes? (slurp \"README.md\") \"jolt\"))" :portability :common} - {:suite "io / slurp, spit, printf, flush (host-classified)" :label "spit + slurp round" :expected "\"hello\"" :actual "(do (spit \"/tmp/jolt-spit-test.txt\" \"hello\") (slurp \"/tmp/jolt-spit-test.txt\"))" :portability :common} - {:suite "io / slurp, spit, printf, flush (host-classified)" :label "spit append" :expected "\"ab\"" :actual "(do (spit \"/tmp/jolt-spit-test.txt\" \"a\") (spit \"/tmp/jolt-spit-test.txt\" \"b\" :append true) (slurp \"/tmp/jolt-spit-test.txt\"))" :portability :common} - {:suite "io / slurp, spit, printf, flush (host-classified)" :label "printf formats" :expected "\"x=1 y=a\"" :actual "(with-out-str (printf \"x=%d y=%s\" 1 \"a\"))" :portability :common} - {:suite "io / slurp, spit, printf, flush (host-classified)" :label "printf no newline" :expected "false" :actual "(do (require (quote [clojure.string :as s])) (s/includes? (with-out-str (printf \"%d\" 1)) \"\\n\"))" :portability :common} - {:suite "io / slurp, spit, printf, flush (host-classified)" :label "flush returns nil" :expected "nil" :actual "(flush)" :portability :common} - {:suite "io / slurp, spit, printf, flush (host-classified)" :label "file-seq finds files" :expected "true" :actual "(do (require (quote [clojure.string :as s])) (boolean (some (fn [p] (s/ends-with? p \"README.md\")) (file-seq \".\"))))" :portability :common} - {:suite "ns / ns-map, ns-unmap, ns-refers" :label "ns-map has var" :expected "true" :actual "(do (def nmv 1) (some? (get (ns-map (quote user)) (quote nmv))))" :portability :common} - {:suite "ns / ns-map, ns-unmap, ns-refers" :label "ns-unmap removes" :expected "nil" :actual "(do (def nuv 1) (ns-unmap (quote user) (quote nuv)) (resolve (quote nuv)))" :portability :common} - {:suite "ns / ns-map, ns-unmap, ns-refers" :label "ns-refers sees refer" :expected "true" :actual "(do (require (quote clojure.string)) (refer (quote clojure.string)) (some? (get (ns-refers (quote user)) (quote join))))" :portability :common} - {:suite "vars / thread-binding family" :label "bound? on def" :expected "true" :actual "(do (def bvv 1) (bound? (var bvv)))" :portability :common} - {:suite "vars / thread-binding family" :label "with-bindings* binds" :expected "5" :actual "(do (def ^:dynamic dynv 1) (with-bindings* (array-map (var dynv) 5) (fn [] dynv)))" :portability :common} - {:suite "vars / thread-binding family" :label "with-bindings* restores" :expected "1" :actual "(do (def ^:dynamic dynw 1) (with-bindings* (array-map (var dynw) 5) (fn [] nil)) dynw)" :portability :common} - {:suite "vars / thread-binding family" :label "with-bindings macro" :expected "7" :actual "(do (def ^:dynamic dynx 1) (with-bindings (array-map (var dynx) 7) dynx))" :portability :common} - {:suite "vars / thread-binding family" :label "thread-bound? inside" :expected "[true false]" :actual "(do (def ^:dynamic dyny 1) [(with-bindings* (array-map (var dyny) 2) (fn [] (thread-bound? (var dyny)))) (thread-bound? (var dyny))])" :portability :common} - {:suite "vars / thread-binding family" :label "bound-fn* conveys" :expected "9" :actual "(do (def ^:dynamic dynz 1) (def f (with-bindings* (array-map (var dynz) 9) (fn [] (bound-fn* (fn [] dynz))))) (f))" :portability :common} - {:suite "vars / thread-binding family" :label "get-thread-bindings" :expected "3" :actual "(do (def ^:dynamic dyng 1) (with-bindings* (array-map (var dyng) 3) (fn [] (get (get-thread-bindings) (var dyng)))))" :portability :common} - {:suite "eval & load-string as values" :label "load-string evals all" :expected "3" :actual "(load-string \"(def lsv 1) (+ lsv 2)\")" :portability :common} - {:suite "eval & load-string as values" :label "eval as value" :expected "[2 3]" :actual "(mapv eval [(quote (+ 1 1)) (quote (+ 1 2))])" :portability :common} - {:suite "eval & load-string as values" :label "eval special still works" :expected "3" :actual "(eval (quote (+ 1 2)))" :portability :common} - {:suite "clojure.edn / opts" :label "set literal" :expected "#{1 2}" :actual "(do (require (quote [clojure.edn :as e0])) (e0/read-string \"#{1 2}\"))" :portability :common} - {:suite "clojure.edn / opts" :label "uuid tag" :expected "true" :actual "(do (require (quote [clojure.edn :as e0])) (uuid? (e0/read-string \"#uuid \\\"550e8400-e29b-41d4-a716-446655440000\\\"\")))" :portability :common} - {:suite "clojure.edn / opts" :label "inst tag" :expected "true" :actual "(do (require (quote [clojure.edn :as e0])) (inst? (e0/read-string \"#inst \\\"2020-01-01T00:00:00Z\\\"\")))" :portability :common} - {:suite "clojure.edn / opts" :label ":eof on empty" :expected ":end" :actual "(do (require (quote [clojure.edn :as e0])) (e0/read-string {:eof :end} \"\"))" :portability :common} - {:suite "clojure.edn / opts" :label ":readers custom tag" :expected "[:custom 5]" :actual "(do (require (quote [clojure.edn :as e0])) (e0/read-string {:readers {(quote custom) (fn [v] [:custom v])}} \"#custom 5\"))" :portability :common} - {:suite "clojure.edn / opts" :label ":readers nested" :expected "[6 8]" :actual "(do (require (quote [clojure.edn :as e0])) (e0/read-string {:readers {(quote w) (fn [v] (* 2 v))}} \"[#w 3 #w 4]\"))" :portability :common} - {:suite "clojure.edn / opts" :label ":default fn" :expected "[:dflt 7]" :actual "(do (require (quote [clojure.edn :as e0])) (e0/read-string {:default (fn [t v] [:dflt v])} \"#unknown 7\"))" :portability :common} - {:suite "clojure.edn / opts" :label "unknown tag throws" :expected :throws :actual "(do (require (quote [clojure.edn :as e0])) (e0/read-string \"#nope 1\"))" :portability :common} - {:suite "state / atoms" :label "deref @" :expected "0" :actual "(let [a (atom 0)] @a)" :portability :common} - {:suite "state / atoms" :label "deref fn" :expected "0" :actual "(deref (atom 0))" :portability :common} - {:suite "state / atoms" :label "reset!" :expected "5" :actual "(let [a (atom 0)] (reset! a 5) @a)" :portability :common} - {:suite "state / atoms" :label "reset! returns new" :expected "5" :actual "(let [a (atom 0)] (reset! a 5))" :portability :common} - {:suite "state / atoms" :label "swap!" :expected "1" :actual "(let [a (atom 0)] (swap! a inc) @a)" :portability :common} - {:suite "state / atoms" :label "swap! with args" :expected "10" :actual "(let [a (atom 1)] (swap! a + 2 3 4) @a)" :portability :common} - {:suite "state / atoms" :label "swap! returns new" :expected "1" :actual "(let [a (atom 0)] (swap! a inc))" :portability :common} - {:suite "state / atoms" :label "swap-vals!" :expected "[0 1]" :actual "(let [a (atom 0)] (swap-vals! a inc))" :portability :common} - {:suite "state / atoms" :label "reset-vals!" :expected "[0 9]" :actual "(let [a (atom 0)] (reset-vals! a 9))" :portability :common} - {:suite "state / atoms" :label "compare-and-set! ok" :expected "true" :actual "(let [a (atom 0)] (compare-and-set! a 0 1))" :portability :common} - {:suite "state / atoms" :label "compare-and-set! no" :expected "false" :actual "(let [a (atom 0)] (compare-and-set! a 9 1))" :portability :common} - {:suite "state / atoms" :label "atom?" :expected "true" :actual "(do (require (quote [clojure.core])) (instance? clojure.lang.Atom (atom 0)))" :portability :jvm} - {:suite "state / atoms" :label "atom? predicate" :expected "true" :actual "(atom? (atom 0))" :portability :common} - {:suite "state / atoms" :label "atom? on non-atom" :expected "false" :actual "(atom? 5)" :portability :common} - {:suite "state / watches & validators" :label "add-watch fires" :expected "1" :actual "(let [a (atom 0) seen (atom 0)] (add-watch a :k (fn [k r o n] (reset! seen 1))) (reset! a 5) @seen)" :portability :common} - {:suite "state / watches & validators" :label "remove-watch" :expected "0" :actual "(let [a (atom 0) seen (atom 0)] (add-watch a :k (fn [k r o n] (swap! seen inc))) (remove-watch a :k) (reset! a 5) @seen)" :portability :common} - {:suite "state / watches & validators" :label "set-validator! ok" :expected "5" :actual "(let [a (atom 0)] (set-validator! a number?) (reset! a 5) @a)" :portability :common} - {:suite "state / watches & validators" :label "set-validator! rejects" :expected :throws :actual "(let [a (atom 0)] (set-validator! a pos?) (reset! a -1))" :portability :common} - {:suite "state / watches & validators" :label "get-validator" :expected "true" :actual "(let [a (atom 0)] (set-validator! a number?) (fn? (get-validator a)))" :portability :common} - {:suite "state / volatiles & delays" :label "volatile! deref" :expected "0" :actual "(let [v (volatile! 0)] @v)" :portability :common} - {:suite "state / volatiles & delays" :label "vreset!" :expected "5" :actual "(let [v (volatile! 0)] (vreset! v 5) @v)" :portability :common} - {:suite "state / volatiles & delays" :label "vswap!" :expected "1" :actual "(let [v (volatile! 0)] (vswap! v inc) @v)" :portability :common} - {:suite "state / volatiles & delays" :label "delay not forced" :expected "0" :actual "(let [c (atom 0) d (delay (swap! c inc))] @c)" :portability :common} - {:suite "state / volatiles & delays" :label "delay force once" :expected "1" :actual "(let [c (atom 0) d (delay (swap! c inc))] (force d) (force d) @c)" :portability :common} - {:suite "state / volatiles & delays" :label "delay value" :expected "5" :actual "(let [d (delay 5)] @d)" :portability :common} - {:suite "state / volatiles & delays" :label "realized? before" :expected "false" :actual "(let [d (delay 5)] (realized? d))" :portability :common} - {:suite "state / volatiles & delays" :label "realized? after" :expected "true" :actual "(let [d (delay 5)] (force d) (realized? d))" :portability :common} - {:suite "state / promises" :label "promise deliver" :expected "5" :actual "(let [p (promise)] (deliver p 5) @p)" :portability :common} - {:suite "state / promises" :label "promise undelivered" :expected "nil" :actual "(let [p (promise)] @p)" :portability :common} - {:suite "state / agents (synchronous shim)" :label "agent deref" :expected "0" :actual "(deref (agent 0))" :portability :common} - {:suite "state / agents (synchronous shim)" :label "agent with opts" :expected "0" :actual "(deref (agent 0 :error-mode :continue))" :portability :common} - {:suite "state / agents (synchronous shim)" :label "send-off applies" :expected "0" :actual "(let [a (agent 0)] (send-off a (fn [x] (Thread/sleep 100) (+ x 5))) (deref a))" :portability :jvm} - {:suite "state / agents (synchronous shim)" :label "send applies" :expected "1" :actual "(let [a (agent 1)] (send a (fn [x] (Thread/sleep 100) (+ x 6))) (deref a))" :portability :jvm} - {:suite "state / agents (synchronous shim)" :label "agent-error nil" :expected "nil" :actual "(agent-error (agent 0))" :portability :common} - {:suite "string / str & basics" :label "str concat" :expected "\"abc\"" :actual "(str \"a\" \"b\" \"c\")" :portability :common} - {:suite "string / str & basics" :label "str of numbers" :expected "\"12\"" :actual "(str 1 2)" :portability :common} - {:suite "string / str & basics" :label "str nil is empty" :expected "\"\"" :actual "(str nil)" :portability :common} - {:suite "string / str & basics" :label "str mixed" :expected "\"a1:b\"" :actual "(str \"a\" 1 :b)" :portability :common} - {:suite "string / str & basics" :label "str of coll" :expected "\"[1 2]\"" :actual "(str [1 2])" :portability :common} - {:suite "string / str & basics" :label "count" :expected "3" :actual "(count \"abc\")" :portability :common} - {:suite "string / str & basics" :label "subs from" :expected "\"bc\"" :actual "(subs \"abc\" 1)" :portability :common} - {:suite "string / str & basics" :label "subs range" :expected "\"b\"" :actual "(subs \"abc\" 1 2)" :portability :common} - {:suite "string / str & basics" :label "string? true" :expected "true" :actual "(string? \"x\")" :portability :common} - {:suite "string / str & basics" :label "pr-str vector" :expected "\"[1 2 3]\"" :actual "(pr-str [1 2 3])" :portability :common} - {:suite "string / str & basics" :label "pr-str quotes str" :expected "\"\\\"hi\\\"\"" :actual "(pr-str \"hi\")" :portability :common} - {:suite "string / str & basics" :label "pr-str of a var" :expected "\"#'user/vv\"" :actual "(pr-str (def vv 1))" :portability :common} - {:suite "string / str & basics" :label "str of a var" :expected "\"#'user/ww\"" :actual "(str (def ww 2))" :portability :common} - {:suite "string / str & basics" :label "pr-str of a defn" :expected "\"#'user/gg\"" :actual "(pr-str (defn gg [x] x))" :portability :common} - {:suite "string / str & basics" :label "seq of string" :expected "[\\a \\b]" :actual "(seq \"ab\")" :portability :common} - {:suite "string as a seqable of chars" :label "vec of string" :expected "[\\a \\b]" :actual "(vec \"ab\")" :portability :common} - {:suite "string as a seqable of chars" :label "into [] of string" :expected "[\\a \\b]" :actual "(into [] \"ab\")" :portability :common} - {:suite "string as a seqable of chars" :label "set of string" :expected "true" :actual "(= #{\\a \\b} (set \"ab\"))" :portability :common} - {:suite "string as a seqable of chars" :label "into #{} of string" :expected "true" :actual "(= #{\\a \\b} (into #{} \"ab\"))" :portability :common} - {:suite "string as a seqable of chars" :label "set dedups chars" :expected "2" :actual "(count (set \"aab\"))" :portability :common} - {:suite "string as a seqable of chars" :label "mapv over string" :expected "[\\a \\b]" :actual "(mapv identity \"ab\")" :portability :common} - {:suite "clojure.string / split limit" :label "neg keeps trailing" :expected "[\"a\" \"\" \"\"]" :actual "(do (require (quote [clojure.string :as s])) (s/split \"a,,\" #\",\" -1))" :portability :common} - {:suite "clojure.string / split limit" :label "zero trims trailing" :expected "[\"a\"]" :actual "(do (require (quote [clojure.string :as s])) (s/split \"a,,\" #\",\" 0))" :portability :common} - {:suite "clojure.string / split limit" :label "omitted trims" :expected "[\"a\"]" :actual "(do (require (quote [clojure.string :as s])) (s/split \"a,,\" #\",\"))" :portability :common} - {:suite "clojure.string / split limit" :label "positive caps parts" :expected "[\"a\" \"b,c\"]" :actual "(do (require (quote [clojure.string :as s])) (s/split \"a,b,c\" #\",\" 2))" :portability :common} - {:suite "clojure.string / split limit" :label "empty string" :expected "[\"\"]" :actual "(do (require (quote [clojure.string :as s])) (s/split \"\" #\",\"))" :portability :common} - {:suite "clojure.string / split limit" :label "interior empties kept" :expected "[\"a\" \"\" \"b\"]" :actual "(do (require (quote [clojure.string :as s])) (s/split \"a,,b\" #\",\"))" :portability :common} - {:suite "clojure.string" :label "join" :expected "\"a,b,c\"" :actual "(do (require (quote [clojure.string :as s])) (s/join \",\" [\"a\" \"b\" \"c\"]))" :portability :common} - {:suite "clojure.string" :label "join no sep" :expected "\"abc\"" :actual "(do (require (quote [clojure.string :as s])) (s/join [\"a\" \"b\" \"c\"]))" :portability :common} - {:suite "clojure.string" :label "split" :expected "[\"a\" \"b\"]" :actual "(do (require (quote [clojure.string :as s])) (s/split \"a,b\" #\",\"))" :portability :common} - {:suite "clojure.string" :label "split-lines" :expected "[\"a\" \"b\"]" :actual "(do (require (quote [clojure.string :as s])) (s/split-lines \"a\\nb\"))" :portability :common} - {:suite "clojure.string" :label "upper-case" :expected "\"ABC\"" :actual "(do (require (quote [clojure.string :as s])) (s/upper-case \"abc\"))" :portability :common} - {:suite "clojure.string" :label "lower-case" :expected "\"abc\"" :actual "(do (require (quote [clojure.string :as s])) (s/lower-case \"ABC\"))" :portability :common} - {:suite "clojure.string" :label "capitalize" :expected "\"Abc\"" :actual "(do (require (quote [clojure.string :as s])) (s/capitalize \"abc\"))" :portability :common} - {:suite "clojure.string" :label "trim" :expected "\"x\"" :actual "(do (require (quote [clojure.string :as s])) (s/trim \" x \"))" :portability :common} - {:suite "clojure.string" :label "triml" :expected "\"x \"" :actual "(do (require (quote [clojure.string :as s])) (s/triml \" x \"))" :portability :common} - {:suite "clojure.string" :label "blank? true" :expected "true" :actual "(do (require (quote [clojure.string :as s])) (s/blank? \" \"))" :portability :common} - {:suite "clojure.string" :label "blank? false" :expected "false" :actual "(do (require (quote [clojure.string :as s])) (s/blank? \"x\"))" :portability :common} - {:suite "clojure.string" :label "includes?" :expected "true" :actual "(do (require (quote [clojure.string :as s])) (s/includes? \"hello\" \"ell\"))" :portability :common} - {:suite "clojure.string" :label "starts-with?" :expected "true" :actual "(do (require (quote [clojure.string :as s])) (s/starts-with? \"hello\" \"he\"))" :portability :common} - {:suite "clojure.string" :label "ends-with?" :expected "true" :actual "(do (require (quote [clojure.string :as s])) (s/ends-with? \"hello\" \"lo\"))" :portability :common} - {:suite "clojure.string" :label "replace" :expected "\"hexxo\"" :actual "(do (require (quote [clojure.string :as s])) (s/replace \"hello\" \"l\" \"x\"))" :portability :common} - {:suite "clojure.string" :label "reverse" :expected "\"cba\"" :actual "(do (require (quote [clojure.string :as s])) (s/reverse \"abc\"))" :portability :common} - {:suite "clojure.string" :label "index-of" :expected "2" :actual "(do (require (quote [clojure.string :as s])) (s/index-of \"hello\" \"l\"))" :portability :common} - {:suite "string / subs strictness" :label "subs basic" :expected "\"bcd\"" :actual "(subs \"abcde\" 1 4)" :portability :common} - {:suite "string / subs strictness" :label "subs to end" :expected "\"cde\"" :actual "(subs \"abcde\" 2)" :portability :common} - {:suite "string / subs strictness" :label "subs start>end" :expected :throws :actual "(subs \"abcde\" 2 1)" :portability :common} - {:suite "string / subs strictness" :label "subs negative" :expected :throws :actual "(subs \"abcde\" -1)" :portability :common} - {:suite "string / subs strictness" :label "subs end past len" :expected :throws :actual "(subs \"abcde\" 1 6)" :portability :common} - {:suite "string / subs strictness" :label "subs nil start" :expected :throws :actual "(subs \"abcde\" nil 2)" :portability :common} - {:suite "string / subs strictness" :label "subs on nil" :expected :throws :actual "(subs nil 1 2)" :portability :common} - {:suite "string / namespace-munge" :label "hyphens to underscores" :expected "\"a_b_c\"" :actual "(namespace-munge \"a-b-c\")" :portability :common} - {:suite "string / namespace-munge" :label "from a symbol" :expected "\"foo_bar\"" :actual "(namespace-munge (quote foo-bar))" :portability :common} - {:suite "string / namespace-munge" :label "no hyphens unchanged" :expected "\"ok\"" :actual "(namespace-munge \"ok\")" :portability :common} - {:suite "strings / get indexes a string" :label "get returns the char" :expected "true" :actual "(= (get \"a:b\" 1) \\:)" :portability :common} - {:suite "strings / get indexes a string" :label "get first char" :expected "\\a" :actual "(get \"abc\" 0)" :portability :common} - {:suite "strings / get indexes a string" :label "get out of range nil" :expected "nil" :actual "(get \"abc\" 9)" :portability :common} - {:suite "strings / get indexes a string" :label "get negative nil" :expected "nil" :actual "(get \"abc\" -1)" :portability :common} - {:suite "strings / get indexes a string" :label "get default honored" :expected ":none" :actual "(get \"abc\" 9 :none)" :portability :common} - {:suite "clojure.string / trim-newline" :label "trailing newline" :expected "\"x\"" :actual "(do (require (quote [clojure.string :as s])) (s/trim-newline \"x\\n\"))" :portability :common} - {:suite "clojure.string / trim-newline" :label "trailing \\r\\n" :expected "\"x\"" :actual "(do (require (quote [clojure.string :as s])) (s/trim-newline \"x\\r\\n\"))" :portability :common} - {:suite "clojure.string / trim-newline" :label "no trailing" :expected "\"ab\"" :actual "(do (require (quote [clojure.string :as s])) (s/trim-newline \"ab\"))" :portability :common} - {:suite "clojure.string / trim-newline" :label "only newlines" :expected "\"\"" :actual "(do (require (quote [clojure.string :as s])) (s/trim-newline \"\\n\\n\"))" :portability :common} - {:suite "clojure.string / trim-newline" :label "interior kept" :expected "\"a\\nb\"" :actual "(do (require (quote [clojure.string :as s])) (s/trim-newline \"a\\nb\\n\"))" :portability :common} - {:suite "transducers / into" :label "map xform" :expected "[2 3 4]" :actual "(into [] (map inc) [1 2 3])" :portability :common} - {:suite "transducers / into" :label "filter xform" :expected "[2 4]" :actual "(into [] (filter even?) [1 2 3 4])" :portability :common} - {:suite "transducers / into" :label "remove xform" :expected "[1 3]" :actual "(into [] (remove even?) [1 2 3 4])" :portability :common} - {:suite "transducers / into" :label "take xform" :expected "[1 2]" :actual "(into [] (take 2) [1 2 3 4])" :portability :common} - {:suite "transducers / into" :label "drop xform" :expected "[3 4]" :actual "(into [] (drop 2) [1 2 3 4])" :portability :common} - {:suite "transducers / into" :label "take-while xform" :expected "[1 2]" :actual "(into [] (take-while (fn [x] (< x 3))) [1 2 3 1])" :portability :common} - {:suite "transducers / into" :label "keep xform" :expected "[1 3]" :actual "(into [] (keep (fn [x] (if (odd? x) x nil))) [1 2 3 4])" :portability :common} - {:suite "transducers / into" :label "map-indexed xform" :expected "[[0 :a] [1 :b]]" :actual "(into [] (map-indexed vector) [:a :b])" :portability :common} - {:suite "transducers / into" :label "mapcat xform" :expected "[1 1 2 2]" :actual "(into [] (mapcat (fn [x] [x x])) [1 2])" :portability :common} - {:suite "transducers / into" :label "cat xform" :expected "[1 2 3 4]" :actual "(into [] cat [[1 2] [3 4]])" :portability :common} - {:suite "transducers / into" :label "into a set" :expected "#{4 3 2}" :actual "(into #{} (map inc) [1 2 3])" :portability :common} - {:suite "transducers / compose" :label "comp map+filter" :expected "[2 4 6 8]" :actual "(into [] (comp (map (fn [x] (* x 2))) (filter even?)) [1 2 3 4])" :portability :common} - {:suite "transducers / compose" :label "comp filter+map" :expected "[2 4]" :actual "(into [] (comp (filter odd?) (map inc)) [1 2 3 4])" :portability :common} - {:suite "transducers / compose" :label "comp three" :expected "[2]" :actual "(into [] (comp (map inc) (filter even?) (take 1)) [1 2 3 4])" :portability :common} - {:suite "transducers / transduce & sequence" :label "transduce sum" :expected "9" :actual "(transduce (map inc) + [1 2 3])" :portability :common} - {:suite "transducers / transduce & sequence" :label "transduce init" :expected "19" :actual "(transduce (map inc) + 10 [1 2 3])" :portability :common} - {:suite "transducers / transduce & sequence" :label "transduce filter" :expected "6" :actual "(transduce (filter even?) + [1 2 3 4])" :portability :common} - {:suite "transducers / transduce & sequence" :label "sequence xform" :expected "[2 3 4]" :actual "(sequence (map inc) [1 2 3])" :portability :common} - {:suite "transducers / transduce & sequence" :label "eduction" :expected "[2 3 4]" :actual "(into [] (eduction (map inc) [1 2 3]))" :portability :common} - {:suite "transducers / transduce & sequence" :label "completing" :expected "9" :actual "(transduce (map inc) (completing +) 0 [1 2 3])" :portability :common} - {:suite "transducers / halt-when" :label "halt returns the halting input" :expected "7" :actual "(transduce (halt-when (fn [x] (> x 5))) conj [1 2 7 3])" :portability :common} - {:suite "transducers / halt-when" :label "no halt is a plain reduction" :expected "[1 2 3]" :actual "(transduce (halt-when (fn [x] (> x 5))) conj [1 2 3])" :portability :common} - {:suite "transducers / halt-when" :label "retf combines acc and input" :expected "[[1 2] 7]" :actual "(transduce (halt-when (fn [x] (> x 5)) (fn [r i] [r i])) conj [1 2 7 3])" :portability :common} - {:suite "transducers / halt-when" :label "halt-when through into" :expected "3" :actual "(into [] (halt-when odd?) [2 4 3 6])" :portability :common} - {:suite "transducers / short-circuit over infinite seqs" :label "into take (range)" :expected "[0 1 2 3 4]" :actual "(into [] (take 5) (range))" :portability :common} - {:suite "transducers / short-circuit over infinite seqs" :label "transduce take (range)" :expected "3" :actual "(transduce (take 3) + 0 (range))" :portability :common} - {:suite "transducers / short-circuit over infinite seqs" :label "sequence take (range)" :expected "[0 1 2 3 4]" :actual "(sequence (take 5) (range))" :portability :common} - {:suite "transducers / short-circuit over infinite seqs" :label "take-while over (range)" :expected "[0 1 2]" :actual "(into [] (take-while (fn [x] (< x 3))) (range))" :portability :common} - {:suite "transducers / short-circuit over infinite seqs" :label "comp take over (range)" :expected "[1 3 5]" :actual "(into [] (comp (filter odd?) (take 3)) (range))" :portability :common} - {:suite "transducers / short-circuit over infinite seqs" :label "into take iterate" :expected "[0 1 2 3 4]" :actual "(into [] (take 5) (iterate inc 0))" :portability :common} - {:suite "reduce / honors reduced" :label "reduced short-circuits inf" :expected "105" :actual "(reduce (fn [a x] (if (> a 100) (reduced a) (+ a x))) 0 (range))" :portability :common} - {:suite "reduce / honors reduced" :label "reduce take inf" :expected "10" :actual "(reduce + (take 5 (range)))" :portability :common} - {:suite "reduce / honors reduced" :label "reduce no-init first elem" :expected "6" :actual "(reduce + [1 2 3])" :portability :common} - {:suite "reduce / honors reduced" :label "reduce no-init single" :expected "42" :actual "(reduce + [42])" :portability :common} - {:suite "reduce / honors reduced" :label "reduce empty calls f" :expected "0" :actual "(reduce + [])" :portability :common} - {:suite "reduce / honors reduced" :label "reduce with-init" :expected "16" :actual "(reduce + 10 [1 2 3])" :portability :common} - {:suite "reduce / honors reduced" :label "reduce reduced immediate" :expected ":x" :actual "(reduce (fn [a x] (reduced :x)) :init [1 2 3])" :portability :common} - {:suite "transducers / into & eduction (overlay)" :label "into list prepends" :expected "[4 3 1 2]" :actual "(into (quote (1 2)) [3 4])" :portability :common} - {:suite "transducers / into & eduction (overlay)" :label "into sorted-map" :expected "{1 :a, 2 :b}" :actual "(into (sorted-map) [[2 :b] [1 :a]])" :portability :common} - {:suite "transducers / into & eduction (overlay)" :label "into from map entry" :expected "[:a 1]" :actual "(into [] (first {:a 1}))" :portability :common} - {:suite "transducers / into & eduction (overlay)" :label "into xform on map" :expected "{:a 2}" :actual "(into {} (map (fn [e] [(key e) (inc (val e))])) {:a 1})" :portability :common} - {:suite "transducers / into & eduction (overlay)" :label "eduction multiple xforms" :expected "[4]" :actual "(into [] (eduction (filter odd?) (map inc) [2 3 4]))" :portability :common} - {:suite "transducers / into & eduction (overlay)" :label "->Eduction" :expected "[2 3]" :actual "(->Eduction (map inc) [1 2])" :portability :common} - {:suite "transducers / into & eduction (overlay)" :label "transduce no init uses (f)" :expected "5" :actual "(transduce (map inc) + [1 2])" :portability :common} - {:suite "transient / vector" :label "conj! then persistent!" :expected "[1 2]" :actual "(persistent! (conj! (conj! (transient []) 1) 2))" :portability :common} - {:suite "transient / vector" :label "reduce conj!" :expected "[0 1 2 3 4]" :actual "(persistent! (reduce conj! (transient []) (range 5)))" :portability :common} - {:suite "transient / vector" :label "conj! many args" :expected "[1 2 3]" :actual "(persistent! (conj! (transient [1]) 2 3))" :portability :common} - {:suite "transient / vector" :label "assoc! existing" :expected "[1 9 3]" :actual "(persistent! (assoc! (transient [1 2 3]) 1 9))" :portability :common} - {:suite "transient / vector" :label "assoc! at count grows" :expected "[1 2 3]" :actual "(persistent! (assoc! (transient [1 2]) 2 3))" :portability :common} - {:suite "transient / vector" :label "pop!" :expected "[1 2]" :actual "(persistent! (pop! (transient [1 2 3])))" :portability :common} - {:suite "transient / vector" :label "from existing vector" :expected "[1 2 3 4]" :actual "(persistent! (conj! (transient [1 2 3]) 4))" :portability :common} - {:suite "transient / vector" :label "count" :expected "3" :actual "(count (transient [1 2 3]))" :portability :common} - {:suite "transient / vector" :label "nth" :expected "2" :actual "(nth (transient [1 2 3]) 1)" :portability :common} - {:suite "transient / vector" :label "get" :expected "2" :actual "(get (transient [1 2 3]) 1)" :portability :common} - {:suite "transient / vector" :label "persistent! is a vector" :expected "true" :actual "(vector? (persistent! (transient [1])))" :portability :common} - {:suite "transient / vector" :label "transient? true" :expected "true" :actual "(transient? (transient []))" :portability :common} - {:suite "transient / vector" :label "transient? false" :expected "false" :actual "(transient? [1 2])" :portability :common} - {:suite "transient / map" :label "assoc! then persistent!" :expected "{:a 1, :b 2}" :actual "(persistent! (assoc! (assoc! (transient {}) :a 1) :b 2))" :portability :common} - {:suite "transient / map" :label "assoc! many" :expected "{:a 1, :b 2}" :actual "(persistent! (assoc! (transient {}) :a 1 :b 2))" :portability :common} - {:suite "transient / map" :label "dissoc!" :expected "{:b 2}" :actual "(persistent! (dissoc! (transient {:a 1 :b 2}) :a))" :portability :common} - {:suite "transient / map" :label "conj! map entry" :expected "{:a 1}" :actual "(persistent! (conj! (transient {}) [:a 1]))" :portability :common} - {:suite "transient / map" :label "from existing map" :expected "{:a 1, :b 2}" :actual "(persistent! (assoc! (transient {:a 1}) :b 2))" :portability :common} - {:suite "transient / map" :label "get" :expected "1" :actual "(get (transient {:a 1}) :a)" :portability :common} - {:suite "transient / map" :label "get missing default" :expected ":x" :actual "(get (transient {:a 1}) :z :x)" :portability :common} - {:suite "transient / map" :label "contains?" :expected "true" :actual "(contains? (transient {:a 1}) :a)" :portability :common} - {:suite "transient / map" :label "count" :expected "2" :actual "(count (transient {:a 1 :b 2}))" :portability :common} - {:suite "transient / map" :label "collection key by value" :expected ":v" :actual "(get (persistent! (assoc! (transient {}) [1 2] :v)) [1 2])" :portability :common} - {:suite "transient / map" :label "persistent! is a map" :expected "true" :actual "(map? (persistent! (transient {:a 1})))" :portability :common} - {:suite "transient / map" :label "reduce build" :expected "{0 0, 1 1, 2 2}" :actual "(persistent! (reduce (fn [t i] (assoc! t i i)) (transient {}) (range 3)))" :portability :common} - {:suite "transient / set" :label "conj! dedups" :expected "#{1 2 3}" :actual "(persistent! (conj! (transient #{}) 1 2 2 3))" :portability :common} - {:suite "transient / set" :label "disj!" :expected "#{1 3}" :actual "(persistent! (disj! (transient #{1 2 3}) 2))" :portability :common} - {:suite "transient / set" :label "from existing set" :expected "#{1 3 2}" :actual "(persistent! (conj! (transient #{1 2}) 3))" :portability :common} - {:suite "transient / set" :label "contains?" :expected "true" :actual "(contains? (transient #{1 2}) 1)" :portability :common} - {:suite "transient / set" :label "count" :expected "2" :actual "(count (transient #{1 2}))" :portability :common} - {:suite "transient / set" :label "persistent! is a set" :expected "true" :actual "(set? (persistent! (transient #{1})))" :portability :common} - {:suite "transient / set" :label "map elements by value" :expected "1" :actual "(count (persistent! (conj! (transient #{}) {:a 1} (hash-map :a 1))))" :portability :common} - {:suite "transient / immutability of source" :label "source vector unchanged" :expected "true" :actual "(let [v [1 2 3] _ (persistent! (conj! (transient v) 4))] (= v [1 2 3]))" :portability :common} - {:suite "transient / immutability of source" :label "source map unchanged" :expected "true" :actual "(let [m {:a 1} _ (persistent! (assoc! (transient m) :b 2))] (= m {:a 1}))" :portability :common} - {:suite "transient / invokable lookup" :label "vector index" :expected "20" :actual "((transient [10 20 30]) 1)" :portability :common} - {:suite "transient / invokable lookup" :label "map key as fn" :expected "7" :actual "((transient {:x 7}) :x)" :portability :common} - {:suite "transient / invokable lookup" :label "map key default" :expected "99" :actual "((transient {:x 7}) :z 99)" :portability :common} - {:suite "transient / invokable lookup" :label "keyword on transient" :expected "7" :actual "(:x (transient {:x 7}))" :portability :common} - {:suite "transient / invokable lookup" :label "set membership" :expected "2" :actual "((transient #{1 2 3}) 2)" :portability :common} - {:suite "transient / invokable lookup" :label "set miss default" :expected ":no" :actual "((transient #{1 2 3}) 42 :no)" :portability :common} - {:suite "transient / invokable lookup" :label "collection key" :expected ":v" :actual "((transient {[1 2] :v}) [1 2])" :portability :common} - {:suite "transient / assoc! odd args throw" :label "map dangling key" :expected "{:a 1, :b nil}" :actual "(persistent! (assoc! (transient {}) :a 1 :b))" :portability :common} - {:suite "transient / assoc! odd args throw" :label "map lone key" :expected :throws :actual "(persistent! (assoc! (transient {}) :a))" :portability :common} - {:suite "transient / assoc! odd args throw" :label "vector dangling" :expected "[9 nil]" :actual "(persistent! (apply assoc! (transient []) [0 9 1]))" :portability :common} - {:suite "transient / assoc! odd args throw" :label "even args still ok" :expected "true" :actual "(= {:a 1, :b 2} (persistent! (assoc! (transient {}) :a 1 :b 2)))" :portability :common} - {:suite "transient / invalidation" :label "conj! after persistent!" :expected :throws :actual "(let [t (transient [])] (persistent! t) (conj! t 1))" :portability :common} - {:suite "transient / invalidation" :label "assoc! after persistent!" :expected :throws :actual "(let [t (transient {})] (persistent! t) (assoc! t :a 1))" :portability :common} - {:suite "transient / invalidation" :label "persistent! twice" :expected :throws :actual "(let [t (transient [])] (persistent! t) (persistent! t))" :portability :common} - {:suite "transient / invalidation" :label "pop! empty" :expected :throws :actual "(pop! (transient []))" :portability :common} - {:suite "transient / strictness" :label "conj! on persistent" :expected :throws :actual "(conj! [1 2] 3)" :portability :common} - {:suite "transient / strictness" :label "assoc! on persistent" :expected :throws :actual "(assoc! {:a 1} :b 2)" :portability :common} - {:suite "transient / strictness" :label "persistent! on vector" :expected :throws :actual "(persistent! [1 2])" :portability :common} - {:suite "transient / strictness" :label "persistent! on nil" :expected :throws :actual "(persistent! nil)" :portability :common} - {:suite "transient / strictness" :label "pop! on transient map" :expected :throws :actual "(pop! (transient {:a 1}))" :portability :common} - {:suite "transient / strictness" :label "dissoc! on tset" :expected :throws :actual "(dissoc! (transient #{1}) 1)" :portability :common} - {:suite "transient / strictness" :label "conj! map bad item" :expected :throws :actual "(conj! (transient {}) #{:a 1})" :portability :common} - {:suite "transient / strictness" :label "conj! no args" :expected "[]" :actual "(persistent! (conj!))" :portability :common} - {:suite "transient / strictness" :label "conj! identity" :expected "[1 2]" :actual "(conj! [1 2])" :portability :common} - {:suite "transient / strictness" :label "conj! map merges map" :expected "{:a 1, :b 2}" :actual "(persistent! (conj! (transient {:a 1}) {:b 2}))" :portability :common} - {:suite "transient / assoc! bounds" :label "assoc! existing idx" :expected "[1 9 3]" :actual "(persistent! (assoc! (transient [1 2 3]) 1 9))" :portability :common} - {:suite "transient / assoc! bounds" :label "assoc! at count grows" :expected "[1 2 3]" :actual "(persistent! (assoc! (transient [1 2]) 2 3))" :portability :common} - {:suite "transient / assoc! bounds" :label "assoc! out of bounds" :expected :throws :actual "(assoc! (transient [0 1 2]) 4 4)" :portability :common} - {:suite "transient / assoc! bounds" :label "assoc! negative" :expected :throws :actual "(assoc! (transient []) -1 0)" :portability :common} - {:suite "truthiness / if (only nil & false are falsy)" :label "nil is falsy" :expected ":f" :actual "(if nil :t :f)" :portability :common} - {:suite "truthiness / if (only nil & false are falsy)" :label "false is falsy" :expected ":f" :actual "(if false :t :f)" :portability :common} - {:suite "truthiness / if (only nil & false are falsy)" :label "zero is truthy" :expected ":t" :actual "(if 0 :t :f)" :portability :common} - {:suite "truthiness / if (only nil & false are falsy)" :label "zero float truthy" :expected ":t" :actual "(if 0.0 :t :f)" :portability :common} - {:suite "truthiness / if (only nil & false are falsy)" :label "empty string truthy" :expected ":t" :actual "(if \"\" :t :f)" :portability :common} - {:suite "truthiness / if (only nil & false are falsy)" :label "empty list truthy" :expected ":t" :actual "(if (list) :t :f)" :portability :common} - {:suite "truthiness / if (only nil & false are falsy)" :label "empty vector truthy" :expected ":t" :actual "(if [] :t :f)" :portability :common} - {:suite "truthiness / if (only nil & false are falsy)" :label "empty map truthy" :expected ":t" :actual "(if {} :t :f)" :portability :common} - {:suite "truthiness / if (only nil & false are falsy)" :label "empty set truthy" :expected ":t" :actual "(if #{} :t :f)" :portability :common} - {:suite "truthiness / if (only nil & false are falsy)" :label "number truthy" :expected ":t" :actual "(if 42 :t :f)" :portability :common} - {:suite "truthiness / if (only nil & false are falsy)" :label "string truthy" :expected ":t" :actual "(if \"x\" :t :f)" :portability :common} - {:suite "truthiness / if (only nil & false are falsy)" :label "keyword truthy" :expected ":t" :actual "(if :kw :t :f)" :portability :common} - {:suite "truthiness / if (only nil & false are falsy)" :label "symbol truthy" :expected ":t" :actual "(if (quote abc) :t :f)" :portability :common} - {:suite "truthiness / if (only nil & false are falsy)" :label "coll truthy" :expected ":t" :actual "(if [1 2] :t :f)" :portability :common} - {:suite "truthiness / if (only nil & false are falsy)" :label "map truthy" :expected ":t" :actual "(if {:a 1} :t :f)" :portability :common} - {:suite "truthiness / if (only nil & false are falsy)" :label "if no else -> nil" :expected "nil" :actual "(if false :t)" :portability :common} - {:suite "truthiness / not" :label "not nil" :expected "true" :actual "(not nil)" :portability :common} - {:suite "truthiness / not" :label "not false" :expected "true" :actual "(not false)" :portability :common} - {:suite "truthiness / not" :label "not zero" :expected "false" :actual "(not 0)" :portability :common} - {:suite "truthiness / not" :label "not empty vector" :expected "false" :actual "(not [])" :portability :common} - {:suite "truthiness / not" :label "not empty string" :expected "false" :actual "(not \"\")" :portability :common} - {:suite "truthiness / not" :label "not number" :expected "false" :actual "(not 42)" :portability :common} - {:suite "truthiness / not" :label "not true" :expected "false" :actual "(not true)" :portability :common} - {:suite "truthiness / and" :label "empty is true" :expected "true" :actual "(and)" :portability :common} - {:suite "truthiness / and" :label "single value" :expected "5" :actual "(and 5)" :portability :common} - {:suite "truthiness / and" :label "all truthy -> last" :expected "3" :actual "(and 1 2 3)" :portability :common} - {:suite "truthiness / and" :label "stops at false" :expected "false" :actual "(and 1 false 3)" :portability :common} - {:suite "truthiness / and" :label "stops at nil" :expected "nil" :actual "(and 1 nil 3)" :portability :common} - {:suite "truthiness / and" :label "false alone" :expected "false" :actual "(and false)" :portability :common} - {:suite "truthiness / and" :label "nil alone" :expected "nil" :actual "(and nil)" :portability :common} - {:suite "truthiness / and" :label "zero is truthy" :expected "0" :actual "(and 1 0)" :portability :common} - {:suite "truthiness / or" :label "empty is nil" :expected "nil" :actual "(or)" :portability :common} - {:suite "truthiness / or" :label "first truthy" :expected "1" :actual "(or 1 2)" :portability :common} - {:suite "truthiness / or" :label "skips nil/false" :expected "5" :actual "(or nil false 5)" :portability :common} - {:suite "truthiness / or" :label "all falsy -> last" :expected "false" :actual "(or nil false)" :portability :common} - {:suite "truthiness / or" :label "nil chain -> false" :expected "false" :actual "(or nil nil nil false)" :portability :common} - {:suite "truthiness / or" :label "zero is truthy" :expected "0" :actual "(or 0 1)" :portability :common} - {:suite "truthiness / or" :label "false alone" :expected "false" :actual "(or false)" :portability :common} - {:suite "truthiness / if-not & boolean" :label "if-not false" :expected ":yes" :actual "(if-not false :yes :no)" :portability :common} - {:suite "truthiness / if-not & boolean" :label "if-not truthy" :expected ":no" :actual "(if-not 0 :yes :no)" :portability :common} - {:suite "truthiness / if-not & boolean" :label "when-not nil" :expected "1" :actual "(when-not nil 1)" :portability :common} - {:suite "truthiness / if-not & boolean" :label "when-not truthy" :expected "nil" :actual "(when-not 5 1)" :portability :common} - {:suite "truthiness / if-not & boolean" :label "boolean of nil" :expected "false" :actual "(boolean nil)" :portability :common} - {:suite "truthiness / if-not & boolean" :label "boolean of false" :expected "false" :actual "(boolean false)" :portability :common} - {:suite "truthiness / if-not & boolean" :label "boolean of 0" :expected "true" :actual "(boolean 0)" :portability :common} - {:suite "truthiness / if-not & boolean" :label "boolean of value" :expected "true" :actual "(boolean :x)" :portability :common} - {:suite "truthiness / if-not & boolean" :label "true?/false?" :expected "true" :actual "(and (true? true) (false? false) (not (true? 1)))" :portability :common} - {:suite "untested / primed + division + bit ops" :label "+'" :expected "3" :actual "(+' 1 2)" :portability :common} - {:suite "untested / primed + division + bit ops" :label "-'" :expected "3" :actual "(-' 5 2)" :portability :common} - {:suite "untested / primed + division + bit ops" :label "*'" :expected "12" :actual "(*' 3 4)" :portability :common} - {:suite "untested / primed + division + bit ops" :label "inc'" :expected "2.5" :actual "(inc' 1.5)" :portability :common} - {:suite "untested / primed + division + bit ops" :label "dec'" :expected "1.5" :actual "(dec' 2.5)" :portability :common} - {:suite "untested / primed + division + bit ops" :label "/" :expected "2" :actual "(/ 6 3)" :portability :common} - {:suite "untested / primed + division + bit ops" :label "/ ratio-as-double" :expected "1/2" :actual "(/ 1 2)" :portability :common} - {:suite "untested / primed + division + bit ops" :label "bit-not" :expected "-6" :actual "(bit-not 5)" :portability :common} - {:suite "untested / primed + division + bit ops" :label "bit-and-not" :expected "4" :actual "(bit-and-not 12 10)" :portability :common} - {:suite "untested / primed + division + bit ops" :label "bit-flip" :expected "3" :actual "(bit-flip 2 0)" :portability :common} - {:suite "untested / primed + division + bit ops" :label "unsigned-bit-shift-right" :expected "2" :actual "(unsigned-bit-shift-right 8 2)" :portability :common} - {:suite "untested / hash family" :label "hash stable" :expected "true" :actual "(= (hash :a) (hash :a))" :portability :common} - {:suite "untested / hash family" :label "hash int" :expected "true" :actual "(int? (hash [1 2]))" :portability :common} - {:suite "untested / hash family" :label "hash-combine" :expected "true" :actual "(int? (hash-combine 1 2))" :portability :common} - {:suite "untested / hash family" :label "hash-ordered-coll" :expected "true" :actual "(int? (hash-ordered-coll [1 2]))" :portability :common} - {:suite "untested / hash family" :label "hash-unordered-coll" :expected "true" :actual "(int? (hash-unordered-coll #{1}))" :portability :common} - {:suite "untested / array stubs (vectors + host buffers)" :label "make-array" :expected "[nil nil nil]" :actual "(vec (make-array Object 3))" :portability :jvm} - {:suite "untested / array stubs (vectors + host buffers)" :label "into-array" :expected "[1 2]" :actual "(vec (into-array [1 2]))" :portability :jvm} - {:suite "untested / array stubs (vectors + host buffers)" :label "to-array" :expected "[1 2]" :actual "(vec (to-array [1 2]))" :portability :jvm} - {:suite "untested / array stubs (vectors + host buffers)" :label "aclone vec" :expected "[1 2]" :actual "(vec (aclone (int-array [1 2])))" :portability :jvm} - {:suite "untested / array stubs (vectors + host buffers)" :label "aclone independent" :expected "[9 2]" :actual "(let [a (aclone (to-array [1 2]))] (aset a 0 9) (seq a))" :portability :jvm} - {:suite "untested / array stubs (vectors + host buffers)" :label "aset/aget" :expected "9" :actual "(let [a (to-array [1 2 3])] (aset a 0 9) (aget a 0))" :portability :jvm} - {:suite "untested / array stubs (vectors + host buffers)" :label "aset-int" :expected "7" :actual "(let [a (to-array [1 2])] (aset-int a 0 7) (aget a 0))" :portability :jvm} - {:suite "untested / array stubs (vectors + host buffers)" :label "aset-boolean" :expected "true" :actual "(let [a (to-array [1])] (aset-boolean a 0 true) (aget a 0))" :portability :jvm} - {:suite "untested / array stubs (vectors + host buffers)" :label "aset-byte" :expected "9" :actual "(let [a (to-array [0])] (aset-byte a 0 9) (aget a 0))" :portability :jvm} - {:suite "untested / array stubs (vectors + host buffers)" :label "aset-char" :expected "\\a" :actual "(let [a (to-array [0])] (aset-char a 0 \\a) (aget a 0))" :portability :jvm} - {:suite "untested / array stubs (vectors + host buffers)" :label "aset-double" :expected "1.5" :actual "(let [a (to-array [0])] (aset-double a 0 1.5) (aget a 0))" :portability :jvm} - {:suite "untested / array stubs (vectors + host buffers)" :label "aset-float" :expected "2.5" :actual "(let [a (to-array [0])] (aset-float a 0 2.5) (aget a 0))" :portability :jvm} - {:suite "untested / array stubs (vectors + host buffers)" :label "aset-long" :expected "3" :actual "(let [a (to-array [0])] (aset-long a 0 3) (aget a 0))" :portability :jvm} - {:suite "untested / array stubs (vectors + host buffers)" :label "aset-short" :expected "4" :actual "(let [a (to-array [0])] (aset-short a 0 4) (aget a 0))" :portability :jvm} - {:suite "untested / array stubs (vectors + host buffers)" :label "boolean-array" :expected "[false false]" :actual "(vec (boolean-array 2))" :portability :jvm} - {:suite "untested / array stubs (vectors + host buffers)" :label "int-array" :expected "[1 2]" :actual "(vec (int-array [1 2]))" :portability :jvm} - {:suite "untested / array stubs (vectors + host buffers)" :label "long-array" :expected "[0 0]" :actual "(vec (long-array 2))" :portability :jvm} - {:suite "untested / array stubs (vectors + host buffers)" :label "double-array" :expected "[0.0 0.0]" :actual "(vec (double-array 2))" :portability :jvm} - {:suite "untested / array stubs (vectors + host buffers)" :label "float-array" :expected "[0.0 0.0]" :actual "(vec (float-array 2))" :portability :jvm} - {:suite "untested / array stubs (vectors + host buffers)" :label "short-array" :expected "[0 0]" :actual "(vec (short-array 2))" :portability :jvm} - {:suite "untested / array stubs (vectors + host buffers)" :label "char-array count" :expected "2" :actual "(count (char-array 2))" :portability :jvm} - {:suite "untested / array stubs (vectors + host buffers)" :label "byte-array bytes?" :expected "true" :actual "(bytes? (byte-array 2))" :portability :jvm} - {:suite "untested / array stubs (vectors + host buffers)" :label "bytes? not vec" :expected "false" :actual "(bytes? [1])" :portability :common} - {:suite "untested / typed coercion views" :label "booleans" :expected "(quote (true))" :actual "(booleans [true])" :portability :common} - {:suite "untested / typed coercion views" :label "doubles" :expected "[1.0]" :actual "(vec (doubles (double-array [1.0])))" :portability :jvm} - {:suite "untested / typed coercion views" :label "floats" :expected "[1.0]" :actual "(vec (floats (float-array [1.0])))" :portability :jvm} - {:suite "untested / typed coercion views" :label "ints" :expected "(quote (1))" :actual "(ints [1])" :portability :common} - {:suite "untested / typed coercion views" :label "longs" :expected "(quote (1))" :actual "(longs [1])" :portability :common} - {:suite "untested / typed coercion views" :label "shorts" :expected "(quote (1))" :actual "(shorts [1])" :portability :common} - {:suite "untested / typed coercion views" :label "chars first" :expected "\\a" :actual "(first (chars [\\a]))" :portability :common} - {:suite "untested / typed coercion views" :label "bytes view" :expected "true" :actual "(bytes? (bytes [65]))" :portability :common} - {:suite "untested / typed coercion views" :label "byte" :expected "65" :actual "(byte 65)" :portability :common} - {:suite "untested / typed coercion views" :label "short" :expected "1" :actual "(short 1)" :portability :common} - {:suite "untested / typed coercion views" :label "long truncates" :expected "1" :actual "(long 1.7)" :portability :common} - {:suite "untested / typed coercion views" :label "double" :expected "3.0" :actual "(double 3)" :portability :common} - {:suite "untested / typed coercion views" :label "float" :expected "3.0" :actual "(float 3)" :portability :common} - {:suite "untested / unchecked-* are plain ops" :label "unchecked-add" :expected "3" :actual "(unchecked-add 1 2)" :portability :common} - {:suite "untested / unchecked-* are plain ops" :label "unchecked-add-int" :expected "3" :actual "(unchecked-add-int 1 2)" :portability :common} - {:suite "untested / unchecked-* are plain ops" :label "unchecked-subtract" :expected "3" :actual "(unchecked-subtract 5 2)" :portability :common} - {:suite "untested / unchecked-* are plain ops" :label "unchecked-subtract-int" :expected "3" :actual "(unchecked-subtract-int 5 2)" :portability :common} - {:suite "untested / unchecked-* are plain ops" :label "unchecked-multiply" :expected "6" :actual "(unchecked-multiply 2 3)" :portability :common} - {:suite "untested / unchecked-* are plain ops" :label "unchecked-multiply-int" :expected "6" :actual "(unchecked-multiply-int 2 3)" :portability :common} - {:suite "untested / unchecked-* are plain ops" :label "unchecked-inc" :expected "2" :actual "(unchecked-inc 1)" :portability :common} - {:suite "untested / unchecked-* are plain ops" :label "unchecked-inc-int" :expected "2" :actual "(unchecked-inc-int 1)" :portability :common} - {:suite "untested / unchecked-* are plain ops" :label "unchecked-dec" :expected "2" :actual "(unchecked-dec 3)" :portability :common} - {:suite "untested / unchecked-* are plain ops" :label "unchecked-dec-int" :expected "2" :actual "(unchecked-dec-int 3)" :portability :common} - {:suite "untested / unchecked-* are plain ops" :label "unchecked-negate" :expected "-4" :actual "(unchecked-negate 4)" :portability :common} - {:suite "untested / unchecked-* are plain ops" :label "unchecked-negate-int" :expected "-4" :actual "(unchecked-negate-int 4)" :portability :common} - {:suite "untested / unchecked-* are plain ops" :label "unchecked-divide-int" :expected "3" :actual "(unchecked-divide-int 7 2)" :portability :common} - {:suite "untested / unchecked-* are plain ops" :label "unchecked-remainder-int" :expected "1" :actual "(unchecked-remainder-int 7 2)" :portability :common} - {:suite "untested / unchecked-* are plain ops" :label "unchecked-int" :expected "3" :actual "(unchecked-int 3.7)" :portability :common} - {:suite "untested / unchecked-* are plain ops" :label "unchecked-long" :expected "3" :actual "(unchecked-long 3.7)" :portability :common} - {:suite "untested / unchecked-* are plain ops" :label "unchecked-double" :expected "3.0" :actual "(unchecked-double 3)" :portability :common} - {:suite "untested / unchecked-* are plain ops" :label "unchecked-float" :expected "3.0" :actual "(unchecked-float 3)" :portability :common} - {:suite "untested / unchecked-* are plain ops" :label "unchecked-byte" :expected "65" :actual "(unchecked-byte 65)" :portability :common} - {:suite "untested / unchecked-* are plain ops" :label "unchecked-char" :expected "\\a" :actual "(unchecked-char 97)" :portability :common} - {:suite "untested / unchecked-* are plain ops" :label "unchecked-short" :expected "5" :actual "(unchecked-short 5)" :portability :common} - {:suite "untested / chunk family (eager equivalents) + cat" :label "chunk round-trip" :expected "[1]" :actual "(let [cb (chunk-buffer 4)] (chunk-append cb 1) (chunk-first (chunk-cons (chunk cb) nil)))" :portability :common} - {:suite "untested / chunk family (eager equivalents) + cat" :label "cat transducer" :expected "[1 2 3]" :actual "(into [] cat [[1] [2 3]])" :portability :common} - {:suite "untested / chunk family (eager equivalents) + cat" :label "ensure-reduced wraps" :expected "true" :actual "(reduced? (ensure-reduced 5))" :portability :common} - {:suite "untested / chunk family (eager equivalents) + cat" :label "ensure-reduced keeps reduced" :expected "true" :actual "(reduced? (ensure-reduced (reduced 5)))" :portability :common} - {:suite "untested / chunk family (eager equivalents) + cat" :label "halt-when" :expected "4" :actual "(transduce (halt-when even?) conj [] [1 3 4 5])" :portability :common} - {:suite "untested / chunk family (eager equivalents) + cat" :label "chunk-next exhausted" :expected "nil" :actual "(let [cb (chunk-buffer 2)] (chunk-append cb 1) (chunk-next (chunk-cons (chunk cb) nil)))" :portability :common} - {:suite "untested / chunk family (eager equivalents) + cat" :label "chunk-rest seqable" :expected "[]" :actual "(let [cb (chunk-buffer 2)] (chunk-append cb 1) (vec (chunk-rest (chunk-cons (chunk cb) nil))))" :portability :common} - {:suite "chunked-seq / over a vector" :label "chunk-first is a 32-element block" :expected "32" :actual "(count (chunk-first (seq (vec (range 100)))))" :portability :common} - {:suite "chunked-seq / over a vector" :label "chunked-seq? true for vector seq" :expected "true" :actual "(chunked-seq? (seq (vec (range 100))))" :portability :common} - {:suite "chunked-seq / over a vector" :label "chunked-seq? false for a list seq" :expected "false" :actual "(chunked-seq? (seq (list 1 2 3)))" :portability :common} - {:suite "chunked-seq / over a vector" :label "chunk-first contents + chunk-rest boundary" :expected "[32 0 31 32]" :actual "(let [s (seq (vec (range 50))) c (chunk-first s)] [(count c) (nth c 0) (nth c 31) (first (chunk-rest s))])" :portability :common} - {:suite "chunked-seq / over a vector" :label "chunk-first window past the first block" :expected "[32 33 34 35 36 37 38 39]" :actual "(vec (chunk-first (chunk-rest (seq (vec (range 40))))))" :portability :common} - ;; --- seq-type-model divergences (allowlisted): jolt models every seq as - ;; PersistentList (eager) or LazySeq (deferred); JVM reifies a specialized class - ;; per producer. Values + laziness are correct, only (class …) differs. jolt-aei7. - {:suite "seq-type-model / specialized seq classes collapse" :label "cons over a vector" :expected "clojure.lang.PersistentList" :actual "(class (cons 1 [2 3]))" :portability :common} - {:suite "seq-type-model / specialized seq classes collapse" :label "iterate" :expected "clojure.lang.PersistentList" :actual "(class (iterate inc 0))" :portability :common} - {:suite "seq-type-model / specialized seq classes collapse" :label "range" :expected "clojure.lang.PersistentList" :actual "(class (range 5))" :portability :common} - {:suite "seq-type-model / specialized seq classes collapse" :label "repeat" :expected "clojure.lang.LazySeq" :actual "(class (repeat 3 :x))" :portability :common} - {:suite "seq-type-model / specialized seq classes collapse" :label "cycle" :expected "clojure.lang.LazySeq" :actual "(class (cycle [1 2]))" :portability :common} - {:suite "seq-type-model / specialized seq classes collapse" :label "vector seq" :expected "clojure.lang.PersistentList" :actual "(class (seq [1 2 3]))" :portability :common} - {:suite "seq-type-model / specialized seq classes collapse" :label "string seq" :expected "clojure.lang.PersistentList" :actual "(class (seq \"abc\"))" :portability :common} - {:suite "seq-type-model / specialized seq classes collapse" :label "keys" :expected "clojure.lang.PersistentList" :actual "(class (keys {:a 1 :b 2}))" :portability :common} - {:suite "seq-type-model / specialized seq classes collapse" :label "rseq" :expected "clojure.lang.PersistentList" :actual "(class (rseq [1 2 3]))" :portability :common} - {:suite "seq-type-model / specialized seq classes collapse" :label "sort" :expected "clojure.lang.PersistentList" :actual "(class (sort [3 1 2]))" :portability :common} - {:suite "seq-type-model / specialized seq classes collapse" :label "subvec" :expected "clojure.lang.PersistentVector" :actual "(class (subvec [1 2 3] 1))" :portability :common} - {:suite "seq-type-model / specialized seq classes collapse" :label "drop over a vector" :expected "clojure.lang.LazySeq" :actual "(class (drop 1 [1 2 3]))" :portability :common} - ;; --- chunking-model realization granularity (JVM-matching): a vector's seq is - ;; chunked, so forcing one element of (map f a-vector) realizes the whole first - ;; 32-block, like the JVM. - {:suite "chunking-model / realization granularity" :label "first over a chunked vector realizes the whole 32-block" :expected "32" :actual "(let [a (atom 0)] (first (map (fn [x] (swap! a inc) x) (vec (range 100)))) @a)" :portability :common} - {:suite "chunking-model / realization granularity" :label "nth 0 over a chunked vector realizes the whole 32-block" :expected "32" :actual "(let [a (atom 0)] (nth (map (fn [x] (swap! a inc) x) (vec (range 100))) 0) @a)" :portability :common} - ;; mapcat/dedupe stay lazier than the JVM at construction: jolt's (apply concat …) - ;; and sequence transformer don't force the first chunk just to build the seq - ;; (the JVM forces 5 here). Allowlisted in known-divergences.edn (jolt-mm6v). - {:suite "chunking-model / unchunked realization granularity" :label "mapcat is fully lazy at construction" :expected "0" :actual "(let [a (atom 0)] (mapcat (fn [x] (swap! a inc) [x]) (range 5)) @a)" :portability :common} - {:suite "chunking-model / unchunked realization granularity" :label "dedupe is fully lazy at construction" :expected "0" :actual "(let [a (atom 0)] (dedupe (map (fn [x] (swap! a inc) x) (range 5))) @a)" :portability :common} - ;; --- integer-box-model: narrow int values behave as integers (certified) --- - ;; jolt unifies every integer as one exact-integer type, so (byte/short/int n) - ;; produce value-correct integers — only the reified class differs (below). - {:suite "integer-box-model / narrow ints behave as integers" :label "byte = plain integer by value" :expected "true" :actual "(= (byte 5) 5)" :portability :common} - {:suite "integer-box-model / narrow ints behave as integers" :label "byte arithmetic promotes" :expected "6" :actual "(+ (byte 5) 1)" :portability :common} - {:suite "integer-box-model / narrow ints behave as integers" :label "byte is a Number" :expected "true" :actual "(instance? Number (byte 5))" :portability :common} - ;; --- integer-box-model divergences (allowlisted): no narrow box types. A Chez - ;; fixnum is an immediate identical to the plain integer (cannot be tagged), so - ;; (byte/short/int n) report Long, not Byte/Short/Integer. Value is correct. - ;; jolt-k9sw (accepted divergence). - {:suite "integer-box-model / narrow int class collapses to Long" :label "byte class" :expected "java.lang.Long" :actual "(class (byte 5))" :portability :common} - {:suite "integer-box-model / narrow int class collapses to Long" :label "short class" :expected "java.lang.Long" :actual "(class (short 5))" :portability :common} - {:suite "integer-box-model / narrow int class collapses to Long" :label "int class" :expected "java.lang.Long" :actual "(class (int 5))" :portability :common} - {:suite "integer-box-model / narrow int class collapses to Long" :label "instance? Byte is false" :expected "false" :actual "(instance? Byte (byte 5))" :portability :common} - {:suite "integer-box-model / narrow int class collapses to Long" :label "instance? Long is true" :expected "true" :actual "(instance? Long (byte 5))" :portability :common} - {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "class number" :expected "java.lang.Long" :actual "(class 1)" :portability :common} - {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "class string" :expected "java.lang.String" :actual "(class \"s\")" :portability :common} - {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "class keyword" :expected "clojure.lang.Keyword" :actual "(class :k)" :portability :common} - {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "class nil" :expected "nil" :actual "(class nil)" :portability :common} - {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "bean is the map" :expected "{:a 1}" :actual "(bean {:a 1})" :portability :jvm} - {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "biginteger" :expected "\"5\"" :actual "(str (biginteger 5))" :portability :common} - {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "proxy resolves nil" :expected "nil" :actual "(proxy [Object] [] (toString [] \"x\"))" :portability :jvm} - {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "construct-proxy throws" :expected :throws :actual "(construct-proxy nil)" :portability :common} - {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "get-proxy-class throws" :expected :throws :actual "(get-proxy-class)" :portability :common} - {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "init-proxy" :expected "nil" :actual "(init-proxy nil {})" :portability :common} - {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "update-proxy" :expected "nil" :actual "(update-proxy nil {})" :portability :common} - {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "proxy-mappings" :expected "{}" :actual "(proxy-mappings nil)" :portability :jvm} - {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "proxy-call-with-super calls" :expected "1" :actual "(proxy-call-with-super (fn [] 1) nil \"m\")" :portability :jvm} - {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "memfn upper" :expected "\"ABC\"" :actual "((memfn toUpperCase) \"abc\")" :portability :common} - {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "memfn with args" :expected "2" :actual "((memfn indexOf needle) \"hello\" \"l\")" :portability :common} - {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "memfn length" :expected "3" :actual "((memfn length) \"abc\")" :portability :common} - {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "array-seq" :expected "(quote (1 2 3))" :actual "(array-seq (to-array [1 2 3]))" :portability :jvm} - {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "array-seq empty" :expected "nil" :actual "(array-seq (to-array []))" :portability :jvm} - {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "proxy-super throws" :expected :throws :actual "(proxy-super count [1])" :portability :jvm} - {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "re-groups throws" :expected :throws :actual "(re-groups (re-matcher #\"a\" \"b\"))" :portability :common} - {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "re-matcher builds" :expected "false" :actual "(nil? (re-matcher #\"a\" \"abc\"))" :portability :common} - {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "print-dup nil writer throws" :expected :throws :actual "(print-dup 1 nil)" :portability :common} - {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "print-method nil writer throws" :expected :throws :actual "(print-method 1 nil)" :portability :common} - {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "uri? string" :expected "false" :actual "(uri? \"http://x\")" :portability :common} - {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "uri? nil" :expected "false" :actual "(uri? nil)" :portability :common} - {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "definterface defines" :expected "false" :actual "(var? (definterface IFoo (foo [x])))" :portability :jvm} - {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "enumeration-seq" :expected "(quote (1 2))" :actual "(enumeration-seq [1 2])" :portability :jvm} - {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "iterator-seq" :expected "(quote (1 2))" :actual "(iterator-seq [1 2])" :portability :common} - {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "seque passthrough" :expected "[1 2]" :actual "(seque [1 2])" :portability :common} - {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "delay? true" :expected "true" :actual "(delay? (delay 1))" :portability :common} - {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "delay? false" :expected "false" :actual "(delay? 1)" :portability :common} - {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "future-call" :expected "42" :actual "(deref (future-call (fn [] 42)))" :portability :common} - {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label ". calls String surface" :expected "3" :actual "(. \"abc\" length)" :portability :jvm} - {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label ".. threads members" :expected "\"ABC\"" :actual "(.. \"abc\" toUpperCase)" :portability :common} - {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "unknown String member throws" :expected :throws :actual "(. \"abc\" frobnicate)" :portability :jvm} - {:suite "untested / protocols: extend + extends?" :label "extend registers" :expected ":str" :actual "(do (defprotocol Pe (pe [x])) (extend (quote String) Pe {:pe (fn [x] :str)}) (pe \"s\"))" :portability :common} - {:suite "untested / protocols: extend + extends?" :label "extend two methods" :expected "[1 2]" :actual "(do (defprotocol P3 (pa [x]) (pb [x])) (extend (quote Long) P3 {:pa (fn [x] 1) :pb (fn [x] 2)}) [(pa 0) (pb 0)])" :portability :common} - {:suite "untested / protocols: extend + extends?" :label "extends? after extend" :expected "true" :actual "(do (defprotocol P4 (pc [x])) (extend (quote Long) P4 {:pc (fn [x] 1)}) (extends? P4 (quote Long)))" :portability :common} - {:suite "untested / protocols: extend + extends?" :label "extends? without" :expected "false" :actual "(do (defprotocol P5 (pd [x])) (extends? P5 (quote Long)))" :portability :common} - {:suite "untested / ns + REPL machinery" :label "all-ns non-empty" :expected "true" :actual "(pos? (count (all-ns)))" :portability :common} - {:suite "untested / ns + REPL machinery" :label "ns-interns sees def" :expected "true" :actual "(do (def zz 1) (pos? (count (ns-interns (quote user)))))" :portability :common} - {:suite "untested / ns + REPL machinery" :label "ns-interns countable" :expected "true" :actual "(map? (ns-interns (quote user)))" :portability :common} - {:suite "untested / ns + REPL machinery" :label "ns-imports empty user" :expected "96" :actual "(count (ns-imports (quote user)))" :portability :common} - {:suite "untested / ns + REPL machinery" :label "reset-meta!" :expected "{:doc \"d\"}" :actual "(do (def vv 1) (reset-meta! (var vv) {:doc \"d\"}))" :portability :common} - {:suite "untested / ns + REPL machinery" :label "prefers empty" :expected "{}" :actual "(do (defmulti mm identity) (prefers mm))" :portability :common} - {:suite "untested / ns + REPL machinery" :label "refer-clojure" :expected "nil" :actual "(refer-clojure)" :portability :common} - {:suite "untested / ns + REPL machinery" :label "special-symbol? if" :expected "true" :actual "(special-symbol? (quote if))" :portability :common} - {:suite "untested / ns + REPL machinery" :label "special-symbol? fn name" :expected "false" :actual "(special-symbol? (quote foo))" :portability :common} - {:suite "untested / ns + REPL machinery" :label "destructure expands" :expected "true" :actual "(pos? (count (destructure (quote [[a b] x]))))" :portability :common} - {:suite "untested / ns + REPL machinery" :label "seq-to-map-for-destructuring" :expected "{:a 1}" :actual "(seq-to-map-for-destructuring (quote (:a 1)))" :portability :common} - {:suite "untested / ns + REPL machinery" :label "s2m trailing map passes through" :expected "{:b 2}" :actual "(seq-to-map-for-destructuring (list {:b 2}))" :portability :common} - {:suite "untested / ns + REPL machinery" :label "s2m unpaired key throws" :expected :throws :actual "(seq-to-map-for-destructuring (quote (:a 1 :b)))" :portability :common} - {:suite "untested / ns + REPL machinery" :label "s2m kwargs trailing map call" :expected "2" :actual "((fn [& {:keys [b]}] b) {:b 2})" :portability :common} - {:suite "untested / ns + REPL machinery" :label "*clojure-version* major" :expected "1" :actual "(:major *clojure-version*)" :portability :common} - {:suite "untested / ns + REPL machinery" :label "*ns* user" :expected "\"user\"" :actual "(str *ns*)" :portability :common} - {:suite "untested / ns + REPL machinery" :label "*1 nil outside repl" :expected "nil" :actual "*1" :portability :common} - {:suite "untested / ns + REPL machinery" :label "*2 nil" :expected "nil" :actual "*2" :portability :common} - {:suite "untested / ns + REPL machinery" :label "*3 nil" :expected "nil" :actual "*3" :portability :common} - {:suite "untested / ns + REPL machinery" :label "*e nil" :expected "nil" :actual "*e" :portability :common} - {:suite "untested / ns + REPL machinery" :label "*unchecked-math*" :expected "false" :actual "*unchecked-math*" :portability :common} - {:suite "untested / ns + REPL machinery" :label "*in* bound" :expected "false" :actual "(map? *in*)" :portability :common} - {:suite "untested / misc seqs + binding machinery" :label "nfirst" :expected "[2]" :actual "(nfirst [[1 2] [3]])" :portability :common} - {:suite "untested / misc seqs + binding machinery" :label "xml-seq root" :expected "1" :actual "(count (xml-seq {:tag :a :content []}))" :portability :common} - {:suite "untested / misc seqs + binding machinery" :label "xml-seq walks" :expected "2" :actual "(count (xml-seq {:tag :a :content [{:tag :b :content []}]}))" :portability :common} - {:suite "untested / misc seqs + binding machinery" :label "comp keyword stage" :expected "[1 2]" :actual "((comp seq :content) {:content [1 2]})" :portability :common} - {:suite "untested / misc seqs + binding machinery" :label "comp three stages" :expected "4" :actual "((comp inc inc :n) {:n 2})" :portability :common} - {:suite "untested / misc seqs + binding machinery" :label "random-sample all" :expected "[1 2]" :actual "(random-sample 1.0 [1 2])" :portability :common} - {:suite "untested / misc seqs + binding machinery" :label "random-sample none" :expected "[]" :actual "(random-sample 0.0 [1 2])" :portability :common} - {:suite "untested / misc seqs + binding machinery" :label "reader-conditional builds" :expected "true" :actual "(reader-conditional? (reader-conditional (quote (:clj 1)) false))" :portability :common} - {:suite "untested / misc seqs + binding machinery" :label "->Eduction" :expected "[2 3]" :actual "(vec (->Eduction (map inc) [1 2]))" :portability :common} - {:suite "untested / misc seqs + binding machinery" :label "bound-fn calls" :expected "42" :actual "((bound-fn [] 42))" :portability :common} - {:suite "untested / misc seqs + binding machinery" :label "push/pop-thread-bindings" :expected ":ok" :actual "(do (push-thread-bindings {}) (pop-thread-bindings) :ok)" :portability :common} - {:suite "uuid / random-uuid" :label "returns a uuid" :expected "true" :actual "(uuid? (random-uuid))" :portability :common} - {:suite "uuid / random-uuid" :label "str is 36 chars" :expected "36" :actual "(count (str (random-uuid)))" :portability :common} - {:suite "uuid / random-uuid" :label "8-4-4-4-12 shape" :expected "[8 4 4 4 12]" :actual "(do (require (quote [clojure.string :as s])) (mapv count (s/split (str (random-uuid)) #\"-\")))" :portability :common} - {:suite "uuid / random-uuid" :label "version nibble is 4" :expected "\\4" :actual "(nth (str (random-uuid)) 14)" :portability :common} - {:suite "uuid / random-uuid" :label "variant nibble 8-b" :expected "true" :actual "(contains? #{\\8 \\9 \\a \\b} (nth (seq (str (random-uuid))) 19))" :portability :common} - {:suite "uuid / random-uuid" :label "distinct" :expected "10" :actual "(count (set (repeatedly 10 random-uuid)))" :portability :common} - {:suite "uuid / random-uuid" :label "all hex digits" :expected "true" :actual "(every? (fn [c] (contains? (set (seq \"0123456789abcdef-\")) c)) (seq (str (random-uuid))))" :portability :common} - {:suite "uuid / parse-uuid" :label "valid round-trips" :expected "\"b6883c0a-0342-4007-9966-bc2dfa6b109e\"" :actual "(str (parse-uuid \"b6883c0a-0342-4007-9966-bc2dfa6b109e\"))" :portability :common} - {:suite "uuid / parse-uuid" :label "parses to uuid" :expected "true" :actual "(uuid? (parse-uuid \"b6883c0a-0342-4007-9966-bc2dfa6b109e\"))" :portability :common} - {:suite "uuid / parse-uuid" :label "case-insensitive =" :expected "true" :actual "(= (parse-uuid \"b6883c0a-0342-4007-9966-bc2dfa6b109e\") (parse-uuid \"B6883C0A-0342-4007-9966-BC2DFA6B109E\"))" :portability :common} - {:suite "uuid / parse-uuid" :label "empty -> nil" :expected "nil" :actual "(parse-uuid \"\")" :portability :common} - {:suite "uuid / parse-uuid" :label "short -> nil" :expected "nil" :actual "(parse-uuid \"0\")" :portability :common} - {:suite "uuid / parse-uuid" :label "garbage -> nil" :expected "nil" :actual "(parse-uuid \"df0993\")" :portability :common} - {:suite "uuid / parse-uuid" :label "too long -> nil" :expected "nil" :actual "(parse-uuid \"b6883c0a-0342-4007-9966-bc2dfa6b109eb\")" :portability :common} - {:suite "uuid / parse-uuid" :label "leading extra -> nil" :expected "nil" :actual "(parse-uuid \"ab6883c0a-0342-4007-9966-bc2dfa6b109e\")" :portability :common} - {:suite "uuid / parse-uuid" :label "non-hex -> nil" :expected "nil" :actual "(parse-uuid \"g6883c0a-0342-4007-9966-bc2dfa6b109e\")" :portability :common} - {:suite "uuid / parse-uuid" :label "bad dashes -> nil" :expected "nil" :actual "(parse-uuid \"b6883c0a00342-4007-9966-bc2dfa6b109e\")" :portability :common} - {:suite "uuid / parse-uuid" :label "non-string throws" :expected :throws :actual "(parse-uuid 1000)" :portability :common} - {:suite "uuid / parse-uuid" :label "keyword throws" :expected :throws :actual "(parse-uuid :key)" :portability :common} - {:suite "uuid / parse-uuid" :label "map throws" :expected :throws :actual "(parse-uuid {})" :portability :common} - {:suite "uuid / value semantics" :label "equal by value" :expected "true" :actual "(= (parse-uuid \"b6883c0a-0342-4007-9966-bc2dfa6b109e\") (parse-uuid \"b6883c0a-0342-4007-9966-bc2dfa6b109e\"))" :portability :common} - {:suite "uuid / value semantics" :label "unequal differs" :expected "false" :actual "(= (random-uuid) (random-uuid))" :portability :common} - {:suite "uuid / value semantics" :label "works as map key" :expected ":v" :actual "(let [u (parse-uuid \"b6883c0a-0342-4007-9966-bc2dfa6b109e\")] (get {u :v} (parse-uuid \"b6883c0a-0342-4007-9966-bc2dfa6b109e\")))" :portability :common} - {:suite "uuid / value semantics" :label "works in a set" :expected "true" :actual "(contains? #{(parse-uuid \"b6883c0a-0342-4007-9966-bc2dfa6b109e\")} (parse-uuid \"B6883C0A-0342-4007-9966-BC2DFA6B109E\"))" :portability :common} - {:suite "uuid / value semantics" :label "uuid? false on string" :expected "false" :actual "(uuid? \"b6883c0a-0342-4007-9966-bc2dfa6b109e\")" :portability :common} - {:suite "uuid / value semantics" :label "uuid? false on nil" :expected "false" :actual "(uuid? nil)" :portability :common} - {:suite "uuid / #uuid reader literal" :label "reads to uuid" :expected "true" :actual "(uuid? #uuid \"b6883c0a-0342-4007-9966-bc2dfa6b109e\")" :portability :common} - {:suite "uuid / #uuid reader literal" :label "= parse-uuid" :expected "true" :actual "(= #uuid \"b6883c0a-0342-4007-9966-bc2dfa6b109e\" (parse-uuid \"b6883c0a-0342-4007-9966-bc2dfa6b109e\"))" :portability :common} - {:suite "uuid / #uuid reader literal" :label "str of literal" :expected "\"b6883c0a-0342-4007-9966-bc2dfa6b109e\"" :actual "(str #uuid \"b6883c0a-0342-4007-9966-bc2dfa6b109e\")" :portability :common} - {:suite "uuid / #uuid reader literal" :label "pr-str round-trips" :expected "\"#uuid \\\"b6883c0a-0342-4007-9966-bc2dfa6b109e\\\"\"" :actual "(pr-str #uuid \"b6883c0a-0342-4007-9966-bc2dfa6b109e\")" :portability :common} - {:suite "vector / construct & predicate" :label "literal" :expected "[1 2 3]" :actual "[1 2 3]" :portability :common} - {:suite "vector / construct & predicate" :label "vector" :expected "[1 2 3]" :actual "(vector 1 2 3)" :portability :common} - {:suite "vector / construct & predicate" :label "vector zero args" :expected "[]" :actual "(vector)" :portability :common} - {:suite "vector / construct & predicate" :label "vec from list" :expected "[1 2 3]" :actual "(vec (list 1 2 3))" :portability :common} - {:suite "vector / construct & predicate" :label "vec from range" :expected "[0 1 2]" :actual "(vec (range 3))" :portability :common} - {:suite "vector / construct & predicate" :label "vec of map yields entries" :expected "[[:a 1]]" :actual "(vec {:a 1})" :portability :common} - {:suite "vector / construct & predicate" :label "vector? true" :expected "true" :actual "(vector? [1])" :portability :common} - {:suite "vector / construct & predicate" :label "vector? false on list" :expected "false" :actual "(vector? (list 1))" :portability :common} - {:suite "vector / construct & predicate" :label "vector = list elts" :expected "true" :actual "(= [1 2 3] (list 1 2 3))" :portability :common} - {:suite "vector / access" :label "nth" :expected ":b" :actual "(nth [:a :b :c] 1)" :portability :common} - {:suite "vector / access" :label "nth default" :expected ":x" :actual "(nth [:a] 5 :x)" :portability :common} - {:suite "vector / access" :label "get by index" :expected ":b" :actual "(get [:a :b] 1)" :portability :common} - {:suite "vector / access" :label "get out of range nil" :expected "nil" :actual "(get [:a] 5)" :portability :common} - {:suite "vector / access" :label "get default" :expected ":x" :actual "(get [:a] 5 :x)" :portability :common} - {:suite "vector / access" :label "first" :expected "1" :actual "(first [1 2 3])" :portability :common} - {:suite "vector / access" :label "last" :expected "3" :actual "(last [1 2 3])" :portability :common} - {:suite "vector / access" :label "peek is last" :expected "3" :actual "(peek [1 2 3])" :portability :common} - {:suite "vector / access" :label "count" :expected "3" :actual "(count [1 2 3])" :portability :common} - {:suite "vector / access" :label "contains? index" :expected "true" :actual "(contains? [:a :b] 1)" :portability :common} - {:suite "vector / access" :label "contains? past end" :expected "false" :actual "(contains? [:a] 3)" :portability :common} - {:suite "vector / access" :label "vector as fn" :expected ":b" :actual "([:a :b :c] 1)" :portability :common} - {:suite "vector / access" :label "vector-in-local as fn" :expected "20" :actual "(let [v [10 20 30]] (v 1))" :portability :common} - {:suite "vector / access" :label "keyword-in-local as fn" :expected "7" :actual "(let [k :a] (k {:a 7}))" :portability :common} - {:suite "vector / access" :label "meta vector as fn" :expected "10" :actual "((with-meta [10 20] {:k 1}) 0)" :portability :common} - {:suite "vector / update (persistent)" :label "conj appends" :expected "[1 2 3]" :actual "(conj [1 2] 3)" :portability :common} - {:suite "vector / update (persistent)" :label "conj many" :expected "[1 2 3 4]" :actual "(conj [1 2] 3 4)" :portability :common} - {:suite "vector / update (persistent)" :label "assoc index" :expected "[1 9 3]" :actual "(assoc [1 2 3] 1 9)" :portability :common} - {:suite "vector / update (persistent)" :label "assoc at count appends" :expected "[1 2 3]" :actual "(assoc [1 2] 2 3)" :portability :common} - {:suite "vector / update (persistent)" :label "update" :expected "[1 3 3]" :actual "(update [1 2 3] 1 inc)" :portability :common} - {:suite "vector / update (persistent)" :label "pop drops last" :expected "[1 2]" :actual "(pop [1 2 3])" :portability :common} - {:suite "vector / update (persistent)" :label "subvec start end" :expected "[2 3]" :actual "(subvec [1 2 3 4] 1 3)" :portability :common} - {:suite "vector / update (persistent)" :label "subvec to end" :expected "[3 4]" :actual "(subvec [1 2 3 4] 2)" :portability :common} - {:suite "vector / update (persistent)" :label "mapv" :expected "[2 3 4]" :actual "(mapv inc [1 2 3])" :portability :common} - {:suite "vector / update (persistent)" :label "filterv" :expected "[2 4]" :actual "(filterv even? [1 2 3 4])" :portability :common} - {:suite "vector / immutability & nesting" :label "conj does not mutate" :expected "true" :actual "(let [v [1 2] w (conj v 3)] (and (= v [1 2]) (= w [1 2 3])))" :portability :common} - {:suite "vector / immutability & nesting" :label "assoc does not mutate" :expected "true" :actual "(let [v [1 2 3] w (assoc v 0 9)] (and (= v [1 2 3]) (= w [9 2 3])))" :portability :common} - {:suite "vector / immutability & nesting" :label "get-in" :expected "2" :actual "(get-in [[1 2] [3 4]] [0 1])" :portability :common} - {:suite "vector / immutability & nesting" :label "assoc-in" :expected "[[1 9]]" :actual "(assoc-in [[1 2]] [0 1] 9)" :portability :common} - {:suite "vector / immutability & nesting" :label "update-in" :expected "[[1 3]]" :actual "(update-in [[1 2]] [0 1] inc)" :portability :common} - {:suite "vector / immutability & nesting" :label "large vector nth" :expected "1500" :actual "(nth (vec (range 2000)) 1500)" :portability :common} - {:suite "vector / immutability & nesting" :label "large vector count" :expected "2000" :actual "(count (vec (range 2000)))" :portability :common} - {:suite "vector / immutability & nesting" :label "large conj immutable" :expected "true" :actual "(let [v (vec (range 1000)) w (conj v :end)] (and (= 1000 (count v)) (= 1001 (count w))))" :portability :common} - {:suite "vector / bulk build boundaries" :label "count at 1025" :expected "1025" :actual "(count (vec (range 1025)))" :portability :common} - {:suite "vector / bulk build boundaries" :label "into = vec at 1025" :expected "true" :actual "(= (vec (range 1025)) (into [] (range 1025)))" :portability :common} - {:suite "vector / bulk build boundaries" :label "nth at leaf boundary" :expected "32" :actual "(nth (vec (range 1025)) 32)" :portability :common} - {:suite "vector / bulk build boundaries" :label "nth at root boundary" :expected "1024" :actual "(nth (vec (range 1025)) 1024)" :portability :common} - {:suite "vector / bulk build boundaries" :label "vec=into at 33" :expected "true" :actual "(= (vec (range 33)) (into [] (range 33)))" :portability :common} - {:suite "vector / bulk build boundaries" :label "conj after bulk 1024" :expected "1025" :actual "(count (conj (vec (range 1024)) :x))" :portability :common} - {:suite "vector / bulk build boundaries" :label "conj-after reads back" :expected ":x" :actual "(nth (conj (vec (range 1024)) :x) 1024)" :portability :common} - {:suite "vector / bulk build boundaries" :label "assoc into bulk vec" :expected "9" :actual "(nth (assoc (vec (range 1025)) 1000 9) 1000)" :portability :common} - {:suite "vector / bulk build boundaries" :label "into onto non-empty" :expected "[0 1 2 0 1]" :actual "(into (vec (range 3)) (range 2))" :portability :common} - {:suite "clojure.walk / lists + seqs" :label "postwalk-replace symbol keys in a list" :expected "(quote (+ 2 2))" :actual "(do (require (quote [clojure.walk :as w])) (w/postwalk-replace {(quote x) 2} (quote (+ x x))))" :portability :common} - {:suite "clojure.walk / lists + seqs" :label "postwalk descends a list" :expected "[:a :a]" :actual "(do (require (quote [clojure.walk :as w])) (w/postwalk (fn [n] (if (symbol? n) :a n)) (quote (x y))))" :portability :common} - {:suite "clojure.walk / lists + seqs" :label "prewalk-replace in a list" :expected "(quote (* 3 3))" :actual "(do (require (quote [clojure.walk :as w])) (w/prewalk-replace {(quote *) (quote *) (quote y) 3} (quote (* y y))))" :portability :common} - {:suite "clojure.walk / lists + seqs" :label "nested list + vector" :expected "[1 [2 1]]" :actual "(do (require (quote [clojure.walk :as w])) (w/postwalk-replace {:a 1 :b 2} (quote (:a [:b :a]))))" :portability :common} - {:suite "clojure.walk / lists + seqs" :label "postwalk-replace in a vector" :expected "[:one 2 :one]" :actual "(do (require (quote [clojure.walk :as w])) (w/postwalk-replace {1 :one} [1 2 1]))" :portability :common} - {:suite "clojure.walk / lists + seqs" :label "keywordize-keys still works" :expected "{:a 1}" :actual "(do (require (quote [clojure.walk :as w])) (w/keywordize-keys {\"a\" 1}))" :portability :common} - {:suite "clojure.walk / lists + seqs" :label "apply-template substitutes" :expected "(quote (+ 1 2))" :actual "(do (require (quote [clojure.template :as t])) (t/apply-template (quote [x y]) (quote (+ x y)) (quote (1 2))))" :portability :common} - {:suite "clojure.walk / records keep their type" :label "postwalk preserves record type" :expected "true" :actual "(do (require (quote [clojure.walk :as w])) (defrecord R [a]) (record? (w/postwalk identity (->R 1))))" :portability :common} - {:suite "clojure.walk / records keep their type" :label "postwalk still walks record fields" :expected "2" :actual "(do (require (quote [clojure.walk :as w])) (defrecord R [a]) (:a (w/postwalk (fn [x] (if (number? x) (inc x) x)) (->R 1))))" :portability :common} - {:suite "clojure.walk / records keep their type" :label "instance? survives a walk" :expected "true" :actual "(do (require (quote [clojure.walk :as w])) (defrecord R [a]) (instance? R (w/postwalk identity (->R 1))))" :portability :common} - {:suite "clojure.walk / records keep their type" :label "a record nested in a map keeps its type" :expected "true" :actual "(do (require (quote [clojure.walk :as w])) (defrecord R [a]) (record? (:r (w/postwalk identity {:r (->R 1)}))))" :portability :common} - {:suite "clojure.walk / records keep their type" :label "prewalk preserves record type" :expected "true" :actual "(do (require (quote [clojure.walk :as w])) (defrecord R [a]) (record? (w/prewalk identity (->R 1))))" :portability :common} - {:suite "reader / auto-resolved keywords" :label "::kw is namespace-qualified" :expected "true" :actual "(some? (namespace ::foo))" :portability :common} - {:suite "reader / auto-resolved keywords" :label "::kw keeps its name" :expected "\"foo\"" :actual "(name ::foo)" :portability :common} - {:suite "reader / auto-resolved keywords" :label "::kw resolves to the current ns" :expected "true" :actual "(= ::a ::a)" :portability :common} - {:suite "clojure.edn / reader opts" :label ":default receives the tag as a symbol" :expected "[true \"foo\" 5]" :actual "(do (require (quote [clojure.edn :as edn])) (let [r (edn/read-string {:default (fn [t v] [t v])} \"#foo 5\")] [(symbol? (first r)) (name (first r)) (second r)]))" :portability :common} - {:suite "metadata / lazy seqs carry meta" :label "with-meta on a lazy seq" :expected "{:k 1}" :actual "(meta (with-meta (map inc [1 2 3]) {:k 1}))" :portability :common} - {:suite "dynamic vars / *print-meta*" :label "*print-meta* is a bindable dynamic var" :expected "true" :actual "(binding [*print-meta* true] (true? *print-meta*))" :portability :common} - {:suite "tagged literals / value equality" :label "equal tag+form are =" :expected "true" :actual "(= (tagged-literal (quote x) [1 2]) (tagged-literal (quote x) [1 2]))" :portability :common} - {:suite "tagged literals / value equality" :label "different tag is not =" :expected "false" :actual "(= (tagged-literal (quote x) [1]) (tagged-literal (quote y) [1]))" :portability :common} - {:suite "tagged literals / value equality" :label "duplicate literal keys throw at read (same form twice)" :expected :throws :actual "(count {(tagged-literal (quote x) [1]) :a (tagged-literal (quote x) [1]) :b})" :portability :common} - {:suite "interop / clojure.lang interfaces" :label "vector is IObj" :expected "true" :actual "(instance? clojure.lang.IObj [1])" :portability :jvm} - {:suite "interop / clojure.lang interfaces" :label "map entry is IMapEntry" :expected "true" :actual "(instance? clojure.lang.IMapEntry (first {:a 1}))" :portability :jvm} - {:suite "interop / clojure.lang interfaces" :label "record is IRecord" :expected "true" :actual "(do (defrecord R [a]) (instance? clojure.lang.IRecord (->R 1)))" :portability :jvm} - {:suite "interop / clojure.lang interfaces" :label "number is not IObj" :expected "false" :actual "(instance? clojure.lang.IObj 5)" :portability :jvm} - {:suite "reader / default data readers" :label "#inst is in default-data-readers" :expected "true" :actual "(boolean (get default-data-readers (quote inst)))" :portability :common} - {:suite "conformance / CRITICAL: lazy sequences" :label "self-ref lazy-cat fib" :expected "[0 1 1 2 3 5 8 13 21 34]" :actual "(do (def fib-seq (lazy-cat [0 1] (map + (rest fib-seq) fib-seq))) (take 10 fib-seq))" :portability :common} - {:suite "conformance / CRITICAL: multi-collection map" :label "map two colls" :expected "[11 22 33]" :actual "(map + [1 2 3] [10 20 30])" :portability :common} - {:suite "conformance / CRITICAL: multi-collection map" :label "map three colls" :expected "[12 24 36]" :actual "(map + [1 2 3] [10 20 30] [1 2 3])" :portability :common} - {:suite "conformance / CRITICAL: multi-collection map" :label "map uneven (shortest)" :expected "[[1 :a] [2 :b]]" :actual "(map vector [1 2 3] [:a :b])" :portability :common} - {:suite "conformance / CRITICAL: multi-collection map" :label "map over range+vec" :expected "[1 3 5]" :actual "(map + (range 3) [1 2 3])" :portability :common} - {:suite "conformance / CRITICAL: multi-collection map" :label "map fn list arg" :expected "[2 3 4]" :actual "(map inc (list 1 2 3))" :portability :common} - {:suite "conformance / CRITICAL: iterate / infinite seqs" :label "iterate" :expected "[0 1 2 3 4]" :actual "(take 5 (iterate inc 0))" :portability :common} - {:suite "conformance / CRITICAL: iterate / infinite seqs" :label "iterate double" :expected "[1 2 4 8 16]" :actual "(take 5 (iterate (fn [x] (* 2 x)) 1))" :portability :common} - {:suite "conformance / CRITICAL: iterate / infinite seqs" :label "range over inf map" :expected "[1 2 3]" :actual "(take 3 (map inc (range)))" :portability :common} - {:suite "conformance / CRITICAL: iterate / infinite seqs" :label "count of take" :expected "100" :actual "(count (take 100 (range)))" :portability :common} - {:suite "conformance / CRITICAL: iterate / infinite seqs" :label "last of take" :expected "5" :actual "(last (take 5 (iterate inc 1)))" :portability :common} - {:suite "conformance / CRITICAL: collections as IFn" :label "map as fn miss" :expected "nil" :actual "({:a 1} :z)" :portability :common} - {:suite "conformance / CRITICAL: collections as IFn" :label "map as fn default" :expected "99" :actual "({:a 1} :z 99)" :portability :common} - {:suite "conformance / CRITICAL: collections as IFn" :label "set literal computed" :expected "true" :actual "(= #{1 2} #{(inc 0) 2})" :portability :common} - {:suite "conformance / CRITICAL: collections as IFn" :label "empty set literal" :expected "true" :actual "(empty? #{})" :portability :common} - {:suite "conformance / CRITICAL: collections as IFn" :label "set literal count" :expected "3" :actual "(count #{1 2 3})" :portability :common} - {:suite "conformance / CRITICAL: collections as IFn" :label "set literal in let" :expected "true" :actual "(let [x 5] (= #{5 6} #{x (inc x)}))" :portability :common} - {:suite "conformance / CRITICAL: collections as IFn" :label "set? true" :expected "true" :actual "(set? #{1 2 3})" :portability :common} - {:suite "conformance / CRITICAL: collections as IFn" :label "set? false" :expected "false" :actual "(set? [1 2])" :portability :common} - {:suite "conformance / CRITICAL: collections as IFn" :label "disj one" :expected "#{1 3}" :actual "(disj #{1 2 3} 2)" :portability :common} - {:suite "conformance / CRITICAL: collections as IFn" :label "disj many" :expected "#{1}" :actual "(disj #{1 2 3} 2 3)" :portability :common} - {:suite "conformance / CRITICAL: collections as IFn" :label "disj absent" :expected "#{1 2}" :actual "(disj #{1 2} 5)" :portability :common} - {:suite "conformance / CRITICAL: collections as IFn" :label "map fn over coll" :expected "[1 3]" :actual "(map {:a 1 :b 3} [:a :b])" :portability :common} - {:suite "conformance / CRITICAL: vec / into over lazy + maps" :label "vec of map-result" :expected "[2 3 4]" :actual "(vec (map inc [1 2 3]))" :portability :common} - {:suite "conformance / CRITICAL: vec / into over lazy + maps" :label "vec of range" :expected "[0 1 2 3 4]" :actual "(vec (range 5))" :portability :common} - {:suite "conformance / CRITICAL: vec / into over lazy + maps" :label "into vec" :expected "[1 2 3 4 5 6]" :actual "(into [1 2 3] [4 5 6])" :portability :common} - {:suite "conformance / CRITICAL: vec / into over lazy + maps" :label "into vec from lazy" :expected "[2 3 4]" :actual "(into [] (map inc [1 2 3]))" :portability :common} - {:suite "conformance / CRITICAL: vec / into over lazy + maps" :label "into map pairs" :expected "{:a 1, :b 2}" :actual "(into {} [[:a 1] [:b 2]])" :portability :common} - {:suite "conformance / CRITICAL: vec / into over lazy + maps" :label "into map onto map" :expected "{:a 1, :b 2, :c 3}" :actual "(into {:a 1} [[:b 2] [:c 3]])" :portability :common} - {:suite "conformance / Option A: lazy transformers return seqs, not vectors" :label "map vec is seq" :expected "true" :actual "(seq? (map inc [1 2 3]))" :portability :common} - {:suite "conformance / Option A: lazy transformers return seqs, not vectors" :label "map vec not vector" :expected "false" :actual "(vector? (map inc [1 2 3]))" :portability :common} - {:suite "conformance / Option A: lazy transformers return seqs, not vectors" :label "filter vec is seq" :expected "true" :actual "(seq? (filter odd? [1 2 3]))" :portability :common} - {:suite "conformance / Option A: lazy transformers return seqs, not vectors" :label "take vec is seq" :expected "true" :actual "(seq? (take 2 [1 2 3]))" :portability :common} - {:suite "conformance / Option A: lazy transformers return seqs, not vectors" :label "map over set" :expected "true" :actual "(= #{2 3 4} (set (map inc #{1 2 3})))" :portability :common} - {:suite "conformance / Option A: lazy transformers return seqs, not vectors" :label "filter over map ev" :expected "[[:b 2]]" :actual "(filter (fn [[k v]] (> v 1)) {:a 1 :b 2})" :portability :common} - {:suite "conformance / Option A: lazy transformers return seqs, not vectors" :label "cons cons lazy" :expected "[1 2 3]" :actual "(cons 1 (cons 2 (lazy-seq (cons 3 nil))))" :portability :common} - {:suite "conformance / Option A: lazy transformers return seqs, not vectors" :label "next empty lazy" :expected "nil" :actual "(next (take 1 [1]))" :portability :common} - {:suite "conformance / Option A: lazy transformers return seqs, not vectors" :label "drop vec is seq" :expected "true" :actual "(seq? (drop 1 [1 2 3]))" :portability :common} - {:suite "conformance / Option A: lazy transformers return seqs, not vectors" :label "distinct vec is seq" :expected "true" :actual "(seq? (distinct [1 1 2]))" :portability :common} - {:suite "conformance / Option A: lazy transformers return seqs, not vectors" :label "map-indexed is seq" :expected "true" :actual "(seq? (map-indexed vector [1 2]))" :portability :common} - {:suite "conformance / Option A: lazy transformers return seqs, not vectors" :label "nth lazy false elem" :expected "false" :actual "(nth (map identity [false 1 2]) 0)" :portability :common} - {:suite "conformance / Option A: lazy transformers return seqs, not vectors" :label "nth lazy past false" :expected "2" :actual "(nth (drop 1 (list false 1 2)) 1)" :portability :common} - {:suite "conformance / HIGH: destructuring" :label "destr nested seq" :expected "[1 2 3]" :actual "(let [[a [b c]] [1 [2 3]]] [a b c])" :portability :common} - {:suite "conformance / HIGH: destructuring" :label "destr rest+as" :expected "[1 [2 3] [1 2 3]]" :actual "(let [[a & r :as all] [1 2 3]] [a r all])" :portability :common} - {:suite "conformance / HIGH: destructuring" :label "destr map :keys" :expected "[1 2]" :actual "(let [{:keys [a b]} {:a 1 :b 2}] [a b])" :portability :common} - {:suite "conformance / HIGH: destructuring" :label "destr map :or" :expected "[1 99]" :actual "(let [{:keys [a b] :or {b 99}} {:a 1}] [a b])" :portability :common} - {:suite "conformance / HIGH: destructuring" :label "destr map :strs" :expected "[1 2]" :actual "(let [{:strs [a b]} {\"a\" 1 \"b\" 2}] [a b])" :portability :common} - {:suite "conformance / HIGH: destructuring" :label "destr nested map" :expected "5" :actual "(let [{{:keys [x]} :pos} {:pos {:x 5}}] x)" :portability :common} - {:suite "conformance / HIGH: destructuring" :label "destr fn-param map" :expected "3" :actual "((fn [{:keys [a b]}] (+ a b)) {:a 1 :b 2})" :portability :common} - {:suite "conformance / HIGH: destructuring" :label "destr let map key" :expected "1" :actual "(let [{a :a} {:a 1}] a)" :portability :common} - {:suite "conformance / HIGH: update / assoc-in on map literals" :label "update extra args" :expected "{:a 111}" :actual "(update {:a 1} :a + 10 100)" :portability :common} - {:suite "conformance / HIGH: update / assoc-in on map literals" :label "get-in" :expected "1" :actual "(get-in {:a {:b {:c 1}}} [:a :b :c])" :portability :common} - {:suite "conformance / native-op parity (native ops at guarded arities)" :label "native mod floored" :expected "2" :actual "(mod -7 3)" :portability :common} - {:suite "conformance / native-op parity (native ops at guarded arities)" :label "native rem truncated" :expected "-1" :actual "(rem -7 3)" :portability :common} - {:suite "conformance / native-op parity (native ops at guarded arities)" :label "native unary div" :expected "1/2" :actual "(/ 2)" :portability :common} - {:suite "conformance / native-op parity (native ops at guarded arities)" :label "native chained div" :expected "1" :actual "(/ 6 3 2)" :portability :common} - {:suite "conformance / native-op parity (native ops at guarded arities)" :label "native bit-and" :expected "8" :actual "(bit-and 12 10)" :portability :common} - {:suite "conformance / native-op parity (native ops at guarded arities)" :label "native bit-xor" :expected "6" :actual "(bit-xor 12 10)" :portability :common} - {:suite "conformance / native-op parity (native ops at guarded arities)" :label "native shifts" :expected "[16 2]" :actual "[(bit-shift-left 4 2) (bit-shift-right 8 2)]" :portability :common} - {:suite "conformance / multimethod preferences" :label "prefer-method breaks tie" :expected ":rect" :actual "(do (derive :cm/sq :cm/rect) (derive :cm/sq :cm/shape) (defmulti cmf identity) (defmethod cmf :cm/rect [x] :rect) (defmethod cmf :cm/shape [x] :shape) (prefer-method cmf :cm/rect :cm/shape) (cmf :cm/sq))" :portability :common} - {:suite "conformance / HIGH: str semantics" :label "str concat nil" :expected "\"a1\"" :actual "(str \"a\" 1 nil)" :portability :common} - {:suite "conformance / HIGH: str semantics" :label "str keyword" :expected "\":b\"" :actual "(str :b)" :portability :common} - {:suite "conformance / HIGH: str semantics" :label "str symbol" :expected "\"foo\"" :actual "(str (quote foo))" :portability :common} - {:suite "conformance / HIGH: str semantics" :label "str mixed" :expected "\"a:b1\"" :actual "(str \"a\" :b 1)" :portability :common} - {:suite "conformance / HIGH: str semantics" :label "str seq" :expected "\"[1 2 3]\"" :actual "(str [1 2 3])" :portability :common} - {:suite "conformance / HIGH: dispatch" :label "multimethod" :expected "9" :actual "(do (defmulti area :shape) (defmethod area :sq [s] (* (:s s) (:s s))) (area {:shape :sq :s 3}))" :portability :common} - {:suite "conformance / HIGH: dispatch" :label "multimethod default" :expected ":def" :actual "(do (defmulti f identity) (defmethod f :default [x] :def) (f 99))" :portability :common} - {:suite "conformance / HIGH: dispatch" :label "protocol on record" :expected "16" :actual "(do (defprotocol Sh (ar [s])) (defrecord Sq [side] Sh (ar [_] (* side side))) (ar (->Sq 4)))" :portability :common} - {:suite "conformance / HIGH: dispatch" :label "deftype inline methods" :expected "7" :actual "(do (defprotocol Pi (mi [x])) (deftype Ti [v] Pi (mi [x] v)) (mi (->Ti 7)))" :portability :common} - {:suite "conformance / HIGH: dispatch" :label "deftype two protocols" :expected "[1 2]" :actual "(do (defprotocol Pa (ma [x])) (defprotocol Pb (mb [x])) (deftype Tab [a b] Pa (ma [x] a) Pb (mb [x] b)) (let [t (->Tab 1 2)] [(ma t) (mb t)]))" :portability :common} - {:suite "conformance / var fns as ordinary invokes (Stage 2 tier 6)" :label "var-get + call" :expected "2" :actual "((var-get (var inc)) 1)" :portability :common} - {:suite "conformance / var fns as ordinary invokes (Stage 2 tier 6)" :label "var? true" :expected "true" :actual "(var? (var map))" :portability :common} - {:suite "conformance / var fns as ordinary invokes (Stage 2 tier 6)" :label "var? false" :expected "false" :actual "(var? 5)" :portability :common} - {:suite "conformance / var fns as ordinary invokes (Stage 2 tier 6)" :label "intern + find-var" :expected "41" :actual "(do (intern (quote user) (quote iv) 41) (var-get (find-var (quote user/iv))))" :portability :common} - {:suite "conformance / var fns as ordinary invokes (Stage 2 tier 6)" :label "alter-var-root rest args" :expected "11" :actual "(do (def avr 1) (alter-var-root (var avr) + 4 6) avr)" :portability :common} - {:suite "conformance / var fns as ordinary invokes (Stage 2 tier 6)" :label "alter-meta! + meta" :expected "7" :actual "(do (def amv 1) (alter-meta! (var amv) assoc :k 7) (:k (meta (var amv))))" :portability :common} - {:suite "conformance / ns introspection fns as ordinary invokes (Stage 2 tier 6b)" :label "find-ns + ns-name" :expected "(quote clojure.core)" :actual "(ns-name (find-ns (quote clojure.core)))" :portability :common} - {:suite "conformance / ns introspection fns as ordinary invokes (Stage 2 tier 6b)" :label "find-ns absent" :expected "nil" :actual "(find-ns (quote no.such.ns))" :portability :common} - {:suite "conformance / ns introspection fns as ordinary invokes (Stage 2 tier 6b)" :label "create-ns + find" :expected "true" :actual "(do (create-ns (quote made.ns)) (some? (find-ns (quote made.ns))))" :portability :common} - {:suite "conformance / ns introspection fns as ordinary invokes (Stage 2 tier 6b)" :label "remove-ns" :expected "nil" :actual "(do (create-ns (quote gone.ns)) (remove-ns (quote gone.ns)) (find-ns (quote gone.ns)))" :portability :common} - {:suite "conformance / ns introspection fns as ordinary invokes (Stage 2 tier 6b)" :label "the-ns of symbol" :expected "(quote user)" :actual "(ns-name (the-ns (quote user)))" :portability :common} - {:suite "conformance / ns introspection fns as ordinary invokes (Stage 2 tier 6b)" :label "ns-resolve + call" :expected "3" :actual "((var-get (ns-resolve (quote clojure.core) (quote inc))) 2)" :portability :common} - {:suite "conformance / ns introspection fns as ordinary invokes (Stage 2 tier 6b)" :label "resolve + call" :expected "3" :actual "((var-get (resolve (quote inc))) 2)" :portability :common} - {:suite "conformance / ns introspection fns as ordinary invokes (Stage 2 tier 6b)" :label "resolve absent" :expected "nil" :actual "(resolve (quote no-such-sym-xyz))" :portability :common} - {:suite "conformance / dispatch-table ops + misc as macros/fns (Stage 2 tier 6c)" :label "get-method + call" :expected "1" :actual "(do (defmulti t6f :k) (defmethod t6f :a [x] 1) ((get-method t6f :a) {:k :a}))" :portability :common} - {:suite "conformance / dispatch-table ops + misc as macros/fns (Stage 2 tier 6c)" :label "remove-method" :expected "nil" :actual "(do (defmulti t6g :k) (defmethod t6g :b [x] 2) (remove-method t6g :b) (get (methods t6g) :b))" :portability :common} - {:suite "conformance / dispatch-table ops + misc as macros/fns (Stage 2 tier 6c)" :label "remove-all-methods" :expected "nil" :actual "(do (defmulti t6h :k) (defmethod t6h :c [x] 3) (remove-all-methods t6h) (get (methods t6h) :c))" :portability :common} - {:suite "conformance / dispatch-table ops + misc as macros/fns (Stage 2 tier 6c)" :label "prefer-method records" :expected "true" :actual "(do (defmulti t6p identity) (prefer-method t6p :rect :shape) (contains? (get (prefers t6p) :rect) :shape))" :portability :common} - {:suite "conformance / dispatch-table ops + misc as macros/fns (Stage 2 tier 6c)" :label "instance? deftype" :expected "true" :actual "(do (deftype T6i [a]) (instance? T6i (->T6i 1)))" :portability :common} - {:suite "conformance / dispatch-table ops + misc as macros/fns (Stage 2 tier 6c)" :label "instance? String" :expected "true" :actual "(instance? String \"s\")" :portability :common} - {:suite "conformance / dispatch-table ops + misc as macros/fns (Stage 2 tier 6c)" :label "locking evals body" :expected "3" :actual "(locking :anything (+ 1 2))" :portability :common} - {:suite "conformance / dispatch-table ops + misc as macros/fns (Stage 2 tier 6c)" :label "locking evals monitor" :expected "[3 1]" :actual "(let [a (atom 0)] [(locking (swap! a inc) 3) @a])" :portability :common} - {:suite "conformance / dispatch-table ops + misc as macros/fns (Stage 2 tier 6c)" :label "defonce keeps first" :expected "5" :actual "(do (defonce d6o 5) (defonce d6o 9) d6o)" :portability :common} - {:suite "conformance / dispatch-table ops + misc as macros/fns (Stage 2 tier 6c)" :label "read-string + eval" :expected "3" :actual "(eval (read-string \"(+ 1 2)\"))" :portability :common} - {:suite "conformance / uuid" :label "uuid as map key" :expected ":v" :actual "(get {(parse-uuid \"b6883c0a-0342-4007-9966-bc2dfa6b109e\") :v} (parse-uuid \"b6883c0a-0342-4007-9966-bc2dfa6b109e\"))" :portability :common} - {:suite "conformance / 1.11 additions + ns fns (spec 35-var batch A)" :label "parse-long bad" :expected "nil" :actual "(parse-long \"4.2\")" :portability :common} - {:suite "conformance / 1.11 additions + ns fns (spec 35-var batch A)" :label "update-keys" :expected "{\"a\" 1}" :actual "(update-keys {:a 1} name)" :portability :common} - {:suite "conformance / 1.11 additions + ns fns (spec 35-var batch A)" :label "update-vals" :expected "{:a 2}" :actual "(update-vals {:a 1} inc)" :portability :common} - {:suite "conformance / 1.11 additions + ns fns (spec 35-var batch A)" :label "partition pad" :expected "[[0 1 2 3] [4 5 6 7] [8 9 :a]]" :actual "(partition 4 4 [:a] (range 10))" :portability :common} - {:suite "conformance / 1.11 additions + ns fns (spec 35-var batch A)" :label "with-redefs" :expected "[42 1]" :actual "(do (defn cwr [] 1) [(with-redefs [cwr (fn [] 42)] (cwr)) (cwr)])" :portability :common} - {:suite "conformance / 1.11 additions + ns fns (spec 35-var batch A)" :label "macroexpand" :expected "true" :actual "(= (quote if) (first (macroexpand (quote (when-not false 1)))))" :portability :common} - {:suite "conformance / 1.11 additions + ns fns (spec 35-var batch A)" :label "require bare symbol" :expected "\"a,b\"" :actual "(do (require (quote clojure.string)) (clojure.string/join \",\" [\"a\" \"b\"]))" :portability :common} - {:suite "conformance / 1.11 additions + ns fns (spec 35-var batch A)" :label "ns-publics lookup" :expected "true" :actual "(do (def cnp 7) (some? (get (ns-publics (quote user)) (quote cnp))))" :portability :common} - {:suite "conformance / #inst + syntax-quote literal collapse (spec 2.4/2.3)" :label "inst partial = full" :expected "true" :actual "(= #inst \"2020\" #inst \"2020-01-01T00:00:00Z\")" :portability :common} - {:suite "conformance / #inst + syntax-quote literal collapse (spec 2.4/2.3)" :label "sq number collapse" :expected "42" :actual "``42" :portability :common} - {:suite "conformance / vars replace the root-env leak" :label "compare total order" :expected "[-1 0 1]" :actual "[(compare nil 1) (compare :a :a) (compare \"b\" \"a\")]" :portability :common} - {:suite "conformance / vars replace the root-env leak" :label "any? anything" :expected "true" :actual "(and (any? nil) (any? 1) (any? :k))" :portability :common} - {:suite "conformance / vars replace the root-env leak" :label "macroexpand-1 when" :expected "2" :actual "(count (rest (macroexpand-1 (quote (when true 1)))))" :portability :common} - {:suite "conformance / HIGH: aliased namespace calls" :label "require :as alias" :expected "\"1,2,3\"" :actual "(do (require (quote [clojure.string :as s])) (s/join \",\" [1 2 3]))" :portability :common} - {:suite "conformance / HIGH: aliased namespace calls" :label "ns form + alias" :expected "\"HI\"" :actual "(do (ns my.a (:require [clojure.string :as s])) (s/upper-case \"hi\"))" :portability :common} - {:suite "conformance / HIGH: aliased namespace calls" :label "ns :use refers" :expected "42" :actual "(do (ns src.u) (def helper 42) (ns dst.u (:use [src.u])) helper)" :portability :common} - {:suite "conformance / MED: missing core fns" :label "subvec" :expected "[2 3]" :actual "(subvec [1 2 3 4 5] 1 3)" :portability :common} - {:suite "conformance / MED: missing core fns" :label "subvec to-end" :expected "[3 4 5]" :actual "(subvec [1 2 3 4 5] 2)" :portability :common} - {:suite "conformance / MED: missing core fns" :label "reduce-kv" :expected "{:a 2, :b 3}" :actual "(reduce-kv (fn [m k v] (assoc m k (inc v))) {} {:a 1 :b 2})" :portability :common} - {:suite "conformance / iterating maps yields entries" :label "reduce over map" :expected "6" :actual "(reduce (fn [a [k v]] (+ a v)) 0 {:a 1 :b 2 :c 3})" :portability :common} - {:suite "conformance / iterating maps yields entries" :label "into transform map" :expected "{:a 2, :b 3}" :actual "(into {} (map (fn [[k v]] [k (inc v)]) {:a 1 :b 2}))" :portability :common} - {:suite "conformance / iterating maps yields entries" :label "filter over map" :expected "true" :actual "(= [[:b 2]] (filterv (fn [[k v]] (> v 1)) {:a 1 :b 2}))" :portability :common} - {:suite "conformance / iterating maps yields entries" :label "tree-seq" :expected "[1 2 3]" :actual "(map (fn [x] x) (filter (complement coll?) (tree-seq coll? seq [1 [2 [3]]])))" :portability :common} - {:suite "conformance / iterating maps yields entries" :label "key/val" :expected "true" :actual "(let [e (first {:k 9})] (and (= :k (key e)) (= 9 (val e))))" :portability :common} - {:suite "conformance / iterating maps yields entries" :label "nat-int?" :expected "true" :actual "(and (nat-int? 0) (nat-int? 5) (not (nat-int? -1)))" :portability :common} - {:suite "conformance / iterating maps yields entries" :label "list* prepend" :expected "[1 2 3 4]" :actual "(list* 1 2 [3 4])" :portability :common} - {:suite "conformance / iterating maps yields entries" :label "cycle" :expected "[1 2 3 1 2 3 1]" :actual "(take 7 (cycle [1 2 3]))" :portability :common} - {:suite "conformance / iterating maps yields entries" :label "partition-all" :expected "[[1 2] [3 4] [5]]" :actual "(partition-all 2 [1 2 3 4 5])" :portability :common} - {:suite "conformance / iterating maps yields entries" :label "reductions init" :expected "[0 1 3 6]" :actual "(reductions + 0 [1 2 3])" :portability :common} - {:suite "conformance / iterating maps yields entries" :label "dedupe" :expected "[1 2 3 1]" :actual "(dedupe [1 1 2 3 3 1])" :portability :common} - {:suite "conformance / iterating maps yields entries" :label "partition-by odd?" :expected "[[1 1] [2] [3 3]]" :actual "(partition-by odd? [1 1 2 3 3])" :portability :common} - {:suite "conformance / iterating maps yields entries" :label "reductions inf" :expected "[0 1 3 6]" :actual "(take 4 (reductions + (range)))" :portability :common} - {:suite "conformance / iterating maps yields entries" :label "tree-seq strict" :expected "10" :actual "(reduce + 0 (filter (complement coll?) (tree-seq coll? seq [1 [2 [3 4]]])))" :portability :common} - {:suite "conformance / iterating maps yields entries" :label "case nil + default" :expected "[:nilr :def]" :actual "(let [f (fn [x] (case x 1 :one nil :nilr :def))] [(f nil) (f 9)])" :portability :common} - {:suite "conformance / iterating maps yields entries" :label "case collection consts" :expected "[:v :m :s]" :actual "(let [f (fn [x] (case x [1 2] :v {:a 1} :m #{3} :s :def))] [(f [1 2]) (f {:a 1}) (f #{3})])" :portability :common} - {:suite "conformance / iterating maps yields entries" :label "seq of nil-first" :expected "true" :actual "(boolean (seq (cons nil (list 1))))" :portability :common} - {:suite "conformance / iterating maps yields entries" :label "reverse nil elem" :expected "[2 nil 1]" :actual "(vec (reverse (list 1 nil 2)))" :portability :common} - {:suite "conformance / iterating maps yields entries" :label "map non-seqable throws" :expected "true" :actual "(try (doall (map inc 5)) false (catch Throwable _ true))" :portability :common} - {:suite "conformance / iterating maps yields entries" :label "keep-indexed" :expected "[:b :d]" :actual "(keep-indexed (fn [i x] (if (odd? i) x)) [:a :b :c :d])" :portability :common} - {:suite "conformance / iterating maps yields entries" :label "map-indexed" :expected "[[0 :a] [1 :b]]" :actual "(map-indexed (fn [i x] [i x]) [:a :b])" :portability :common} - {:suite "conformance / iterating maps yields entries" :label "trampoline" :expected ":done" :actual "(do (defn a [n] (if (zero? n) :done (fn [] (a (dec n))))) (trampoline a 5))" :portability :common} - {:suite "conformance / iterating maps yields entries" :label "format" :expected "\"1-x\"" :actual "(format \"%d-%s\" 1 \"x\")" :portability :common} - {:suite "conformance / iterating maps yields entries" :label "read-string" :expected "(quote (+ 1 2))" :actual "(read-string \"(+ 1 2)\")" :portability :common} - {:suite "conformance / iterating maps yields entries" :label "letfn mutual" :expected "true" :actual "(letfn [(ev? [n] (if (= n 0) true (od? (dec n)))) (od? [n] (if (= n 0) false (ev? (dec n))))] (ev? 10))" :portability :common} - {:suite "conformance / iterating maps yields entries" :label "doseq side" :expected "[1 2 3]" :actual "(do (def a (atom [])) (doseq [x [1 2 3]] (swap! a conj x)) @a)" :portability :common} - {:suite "conformance / iterating maps yields entries" :label "doseq nested" :expected "4" :actual "(do (def c (atom 0)) (doseq [x [1 2] y [10 20]] (swap! c inc)) @c)" :portability :common} - {:suite "conformance / MED: lazy filter / take-while over infinite seqs" :label "lazy filter inf" :expected "[1 3 5 7 9]" :actual "(take 5 (filter odd? (range)))" :portability :common} - {:suite "conformance / MED: lazy filter / take-while over infinite seqs" :label "lazy take-while inf" :expected "[0 1 2 3 4]" :actual "(take-while (fn [x] (< x 5)) (range))" :portability :common} - {:suite "conformance / MED: lazy filter / take-while over infinite seqs" :label "lazy remove inf" :expected "[0 2 4 6 8]" :actual "(take 5 (remove odd? (range)))" :portability :common} - {:suite "conformance / MED: lazy filter / take-while over infinite seqs" :label "filter finite" :expected "[2 4]" :actual "(filter even? [1 2 3 4 5])" :portability :common} - {:suite "conformance / atoms (full support)" :label "swap! args" :expected "7" :actual "(do (def a (atom 1)) (swap! a + 2 4) @a)" :portability :common} - {:suite "conformance / atoms (full support)" :label "reset! ret" :expected "9" :actual "(do (def a (atom 1)) (reset! a 9))" :portability :common} - {:suite "conformance / atoms (full support)" :label "compare-and-set!" :expected "true" :actual "(do (def a (atom 1)) (compare-and-set! a 1 2))" :portability :common} - {:suite "conformance / atoms (full support)" :label "compare-and-set! no" :expected "false" :actual "(do (def a (atom 1)) (compare-and-set! a 5 2))" :portability :common} - {:suite "conformance / atoms (full support)" :label "swap-vals!" :expected "[1 2]" :actual "(do (def a (atom 1)) (swap-vals! a inc))" :portability :common} - {:suite "conformance / atoms (full support)" :label "reset-vals!" :expected "[1 9]" :actual "(do (def a (atom 1)) (reset-vals! a 9))" :portability :common} - {:suite "conformance / atoms (full support)" :label "atom map swap" :expected "{:a 1, :b 2}" :actual "(do (def a (atom {:a 1})) (swap! a assoc :b 2) @a)" :portability :common} - {:suite "conformance / atoms (full support)" :label "add-watch" :expected "[:k 1 2]" :actual "(do (def lg (atom nil)) (def a (atom 1)) (add-watch a :k (fn [k r o n] (reset! lg [k o n]))) (swap! a inc) @lg)" :portability :common} - {:suite "conformance / atoms (full support)" :label "atom validator" :expected "5" :actual "(do (def a (atom 1 :validator pos?)) (reset! a 5) @a)" :portability :common} - {:suite "conformance / atoms (full support)" :label "instance? Atom" :expected "true" :actual "(instance? clojure.lang.Atom (atom 1))" :portability :jvm} - {:suite "conformance / volatiles / delays" :label "volatile" :expected "2" :actual "(do (def v (volatile! 1)) (vreset! v 2) @v)" :portability :common} - {:suite "conformance / volatiles / delays" :label "vswap!" :expected "2" :actual "(do (def v (volatile! 1)) (vswap! v inc) @v)" :portability :common} - {:suite "conformance / volatiles / delays" :label "delay force" :expected "3" :actual "(force (delay (+ 1 2)))" :portability :common} - {:suite "conformance / volatiles / delays" :label "delay deref once" :expected "1" :actual "(do (def c (atom 0)) (def d (delay (swap! c inc))) @d @d @c)" :portability :common} - {:suite "conformance / volatiles / delays" :label "realized? delay" :expected "true" :actual "(do (def d (delay 1)) @d (realized? d))" :portability :common} - {:suite "conformance / volatiles / delays" :label "realized? not" :expected "false" :actual "(realized? (delay 1))" :portability :common} - {:suite "conformance / numbers / math" :label "quot neg" :expected "-2" :actual "(quot -7 3)" :portability :common} - {:suite "conformance / numbers / math" :label "bit ops" :expected "[4 14 10]" :actual "[(bit-and 12 6) (bit-or 12 6) (bit-xor 12 6)]" :portability :common} - {:suite "conformance / numbers / math" :label "bit-shift" :expected "[8 2]" :actual "[(bit-shift-left 1 3) (bit-shift-right 8 2)]" :portability :common} - {:suite "conformance / numbers / math" :label "Math/sqrt" :expected "3.0" :actual "(Math/sqrt 9)" :portability :jvm} - {:suite "conformance / numbers / math" :label "Math/pow" :expected "8.0" :actual "(Math/pow 2 3)" :portability :jvm} - {:suite "conformance / numbers / math" :label "min-key" :expected "1" :actual "(min-key abs 1 -2 3)" :portability :common} - {:suite "conformance / numbers / math" :label "max-key" :expected "-4" :actual "(max-key abs 1 -2 -4 3)" :portability :common} - {:suite "conformance / strings (clojure.string)" :label "str/trim" :expected "\"hi\"" :actual "(do (require (quote [clojure.string :as s])) (s/trim \" hi \"))" :portability :common} - {:suite "conformance / strings (clojure.string)" :label "str/split regex" :expected "[\"a\" \"b\" \"c\"]" :actual "(do (require (quote [clojure.string :as s])) (s/split \"a,b,c\" #\",\"))" :portability :common} - {:suite "conformance / strings (clojure.string)" :label "str/split ws" :expected "[\"a\" \"b\" \"c\"]" :actual "(do (require (quote [clojure.string :as s])) (s/split \"a b c\" #\"\\s+\"))" :portability :common} - {:suite "conformance / strings (clojure.string)" :label "str/replace" :expected "\"hexxo\"" :actual "(do (require (quote [clojure.string :as s])) (s/replace \"hello\" \"ll\" \"xx\"))" :portability :common} - {:suite "conformance / regex (capturing groups, backtracking, flags, lookahead)" :label "str/replace regex" :expected "\"ab\"" :actual "(do (require (quote [clojure.string :as s])) (s/replace \"a1b2\" #\"[0-9]\" \"\"))" :portability :common} - {:suite "conformance / strings (clojure.string)" :label "subs" :expected "\"ell\"" :actual "(subs \"hello\" 1 4)" :portability :common} - {:suite "conformance / regex" :label "re-find" :expected "\"123\"" :actual "(re-find #\"[0-9]+\" \"abc123def\")" :portability :common} - {:suite "conformance / regex" :label "re-matches" :expected "\"abc\"" :actual "(re-matches #\"a.c\" \"abc\")" :portability :common} - {:suite "conformance / regex (capturing groups, backtracking, flags, lookahead)" :label "re-matches no" :expected "nil" :actual "(re-matches #\"a.c\" \"abcd\")" :portability :common} - {:suite "conformance / regex (capturing groups, backtracking, flags, lookahead)" :label "re-seq" :expected "[\"12\" \"34\"]" :actual "(re-seq #\"[0-9]+\" \"a12b34\")" :portability :common} - {:suite "conformance / sequences" :label "split-at" :expected "[[1 2] [3 4 5]]" :actual "(split-at 2 [1 2 3 4 5])" :portability :common} - {:suite "conformance / sequences" :label "split-with" :expected "[[1 2] [3 4 1]]" :actual "(split-with (fn [x] (< x 3)) [1 2 3 4 1])" :portability :common} - {:suite "conformance / sequences" :label "partition step" :expected "[[1 2] [3 4]]" :actual "(partition 2 2 [1 2 3 4 5])" :portability :common} - {:suite "conformance / sequences" :label "not-every?" :expected "true" :actual "(not-every? pos? [1 -2 3])" :portability :common} - {:suite "conformance / overlay migration: run in all 3 modes" :label "not-any?" :expected "true" :actual "(not-any? neg? [1 2 3])" :portability :common} - {:suite "conformance / sequences" :label "take-nth" :expected "[0 2 4]" :actual "(take-nth 2 [0 1 2 3 4])" :portability :common} - {:suite "conformance / sequences" :label "butlast" :expected "[1 2]" :actual "(butlast [1 2 3])" :portability :common} - {:suite "conformance / sequences" :label "empty" :expected "[]" :actual "(empty [1 2 3])" :portability :common} - {:suite "conformance / sequences" :label "replace map" :expected "[:a :b :a]" :actual "(replace {1 :a 2 :b} [1 2 1])" :portability :common} - {:suite "conformance / data structures" :label "sorted-map seq" :expected "[[:a 1] [:b 2] [:c 3]]" :actual "(seq (sorted-map :c 3 :a 1 :b 2))" :portability :common} - {:suite "conformance / data structures" :label "sorted-set seq" :expected "[1 2 3]" :actual "(seq (sorted-set 3 1 2))" :portability :common} - {:suite "conformance / data structures" :label "coll? set" :expected "true" :actual "(coll? #{1 2})" :portability :common} - {:suite "conformance / data structures" :label "conj map entry" :expected "{:a 1, :b 2}" :actual "(conj {:a 1} [:b 2])" :portability :common} - {:suite "conformance / metadata / vars" :label "vary-meta" :expected "{:x 2}" :actual "(meta (vary-meta (with-meta [1] {:x 1}) update :x inc))" :portability :common} - {:suite "conformance / metadata / vars" :label "defonce no-redef" :expected "1" :actual "(do (defonce dv1 1) (defonce dv1 2) dv1)" :portability :common} - {:suite "conformance / metadata / vars" :label "binding dynamic" :expected "10" :actual "(do (def ^:dynamic *x* 1) (binding [*x* 10] *x*))" :portability :common} - {:suite "conformance / try / catch" :label "try catch" :expected ":caught" :actual "(try (throw (ex-info \"e\" {})) (catch :default e :caught))" :portability :common} - {:suite "conformance / try / catch" :label "ex-data" :expected "{:a 1}" :actual "(try (throw (ex-info \"m\" {:a 1})) (catch :default e (ex-data e)))" :portability :common} - {:suite "conformance / try / catch" :label "ex-message" :expected "\"m\"" :actual "(try (throw (ex-info \"m\" {})) (catch :default e (ex-message e)))" :portability :common} - {:suite "conformance / macros" :label "macroexpand-1" :expected "true" :actual "(do (defmacro mm [x] (list (quote inc) x)) (= (quote (inc 5)) (macroexpand-1 (quote (mm 5)))))" :portability :common} - {:suite "conformance / macros" :label "doto" :expected "{:a 1}" :actual "(deref (doto (atom {}) (swap! assoc :a 1)))" :portability :common} - {:suite "conformance / printing" :label "prn-str" :expected "\"1\\n\"" :actual "(prn-str 1)" :portability :common} - {:suite "conformance / characters" :label "char not string" :expected "false" :actual "(= \\a \"a\")" :portability :common} - {:suite "conformance / characters" :label "char eq" :expected "true" :actual "(= \\a \\a)" :portability :common} - {:suite "conformance / characters" :label "int of char" :expected "97" :actual "(int \\a)" :portability :common} - {:suite "conformance / characters" :label "char of int" :expected "true" :actual "(= \\A (char 65))" :portability :common} - {:suite "conformance / characters" :label "str of chars" :expected "\"abc\"" :actual "(str \\a \\b \\c)" :portability :common} - {:suite "conformance / characters" :label "first of string" :expected "\\h" :actual "(first \"hello\")" :portability :common} - {:suite "conformance / characters" :label "nth of string" :expected "\\e" :actual "(nth \"hello\" 1)" :portability :common} - {:suite "conformance / characters" :label "char newline" :expected "10" :actual "(int \\newline)" :portability :common} - {:suite "conformance / characters" :label "char space" :expected "32" :actual "(int \\space)" :portability :common} - {:suite "conformance / characters" :label "pr-str char" :expected "\"\\\\a\"" :actual "(pr-str \\a)" :portability :common} - {:suite "conformance / characters" :label "chars in vec" :expected "[\\a \\b]" :actual "[\\a \\b]" :portability :common} - {:suite "conformance / characters" :label "apply str chars" :expected "\"hi\"" :actual "(apply str [\\h \\i])" :portability :common} - {:suite "conformance / transducers" :label "transduce map" :expected "9" :actual "(transduce (map inc) + 0 [1 2 3])" :portability :common} - {:suite "conformance / transducers" :label "transduce comp" :expected "12" :actual "(transduce (comp (map inc) (filter even?)) + 0 [1 2 3 4 5])" :portability :common} - {:suite "conformance / transducers" :label "transduce conj" :expected "[2 3 4]" :actual "(transduce (map inc) conj [] [1 2 3])" :portability :common} - {:suite "conformance / transducers" :label "into comp xform" :expected "[1 9 25]" :actual "(into [] (comp (filter odd?) (map (fn [x] (* x x)))) [1 2 3 4 5])" :portability :common} - {:suite "conformance / transducers" :label "into take xform" :expected "[0 1 2]" :actual "(into [] (take 3) (range 100))" :portability :common} - {:suite "conformance / transducers" :label "transduce no-init" :expected "6" :actual "(transduce (map inc) + [0 1 2])" :portability :common} - {:suite "conformance / transducers" :label "transduce drop" :expected "[3 4 5]" :actual "(into [] (drop 2) [1 2 3 4 5])" :portability :common} - {:suite "conformance / transducers" :label "transduce remove" :expected "[1 3 5]" :actual "(into [] (remove even?) [1 2 3 4 5])" :portability :common} - {:suite "conformance / transducers" :label "transduce take-while" :expected "[1 2]" :actual "(into [] (take-while (fn [x] (< x 3))) [1 2 3 4 1])" :portability :common} - {:suite "conformance / transducers" :label "transduce map-indexed" :expected "[[0 :a] [1 :b]]" :actual "(into [] (map-indexed (fn [i x] [i x])) [:a :b])" :portability :common} - {:suite "conformance / transducers" :label "partition-all xform" :expected "[[1 2] [3 4] [5]]" :actual "(into [] (partition-all 2) [1 2 3 4 5])" :portability :common} - {:suite "conformance / transducers" :label "partition-all xform comp" :expected "[2 2 1]" :actual "(into [] (comp (partition-all 2) (map count)) [1 2 3 4 5])" :portability :common} - {:suite "conformance / transducers" :label "partition-by xform" :expected "[[1 1] [2 4] [5]]" :actual "(into [] (partition-by odd?) [1 1 2 4 5])" :portability :common} - {:suite "conformance / transducers" :label "partition-by xform reduced" :expected "[[1 1] [2 4]]" :actual "(into [] (comp (partition-by odd?) (take 2)) [1 1 2 4 5 5])" :portability :common} - {:suite "conformance / regex (capturing groups, backtracking, flags, lookahead)" :label "re-find groups" :expected "[\"12-34\" \"12\" \"34\"]" :actual "(re-find #\"(\\d+)-(\\d+)\" \"x12-34y\")" :portability :common} - {:suite "conformance / regex (capturing groups, backtracking, flags, lookahead)" :label "re-find no-groups" :expected "\"123\"" :actual "(re-find #\"\\d+\" \"ab123\")" :portability :common} - {:suite "conformance / regex (capturing groups, backtracking, flags, lookahead)" :label "re-matches groups" :expected "[\"1.2\" \"1\" \"2\"]" :actual "(re-matches #\"(\\d+)\\.(\\d+)\" \"1.2\")" :portability :common} - {:suite "conformance / regex (capturing groups, backtracking, flags, lookahead)" :label "greedy backtrack" :expected "\"xxfoo\"" :actual "(re-find #\".*foo\" \"xxfoo\")" :portability :common} - {:suite "conformance / regex (capturing groups, backtracking, flags, lookahead)" :label "greedy thru group" :expected "[\"a,b,c\" \"a,b\" \"c\"]" :actual "(re-find #\"(.*),(.*)\" \"a,b,c\")" :portability :common} - {:suite "conformance / regex (capturing groups, backtracking, flags, lookahead)" :label "lazy quantifier" :expected "[\"\" \"a\"]" :actual "(re-find #\"<(.+?)>\" \"\")" :portability :common} - {:suite "conformance / regex (capturing groups, backtracking, flags, lookahead)" :label "flag case-insens" :expected "\"CAT\"" :actual "(re-find #\"(?i)cat\" \"a CAT\")" :portability :common} - {:suite "conformance / regex (capturing groups, backtracking, flags, lookahead)" :label "lookahead" :expected "\"foo\"" :actual "(re-find #\"foo(?=bar)\" \"foobar\")" :portability :common} - {:suite "conformance / regex (capturing groups, backtracking, flags, lookahead)" :label "neg-lookahead" :expected "\"foo\"" :actual "(re-find #\"foo(?!bar)\" \"foobaz\")" :portability :common} - {:suite "conformance / regex (capturing groups, backtracking, flags, lookahead)" :label "word-boundary" :expected "\"word\"" :actual "(re-find #\"\\bword\\b\" \"a word!\")" :portability :common} - {:suite "conformance / regex (capturing groups, backtracking, flags, lookahead)" :label "word-boundary no" :expected "nil" :actual "(re-find #\"\\bword\\b\" \"swordfish\")" :portability :common} - {:suite "conformance / regex (capturing groups, backtracking, flags, lookahead)" :label "optional group" :expected "[\"1.2.3\" \"1\" \"2\" \"3\" nil]" :actual "(re-find #\"(\\d+)\\.(\\d+)\\.(\\d+)(?:-([a-z]+))?\" \"1.2.3\")" :portability :common} - {:suite "conformance / regex (capturing groups, backtracking, flags, lookahead)" :label "alternation" :expected "\"dog\"" :actual "(re-find #\"cat|dog\" \"a dog cat\")" :portability :common} - {:suite "conformance / regex (capturing groups, backtracking, flags, lookahead)" :label "str/replace $1" :expected "\"he[ll]o\"" :actual "(do (require (quote [clojure.string :as s])) (s/replace \"hello\" #\"(l+)\" \"[$1]\"))" :portability :common} - {:suite "conformance / regex (capturing groups, backtracking, flags, lookahead)" :label "str/replace regex (2)" :expected "\"X-X\"" :actual "(do (require (quote [clojure.string :as s])) (s/replace \"a-b\" #\"[a-z]\" \"X\"))" :portability :common} - {:suite "conformance / map literals evaluate their values" :label "map literal var" :expected "{:k 5}" :actual "(let [x 5] {:k x})" :portability :common} - {:suite "conformance / map literals evaluate their values" :label "map literal nested" :expected "{:a {:b 2}}" :actual "(let [y 2] {:a {:b y}})" :portability :common} - {:suite "conformance / map literals evaluate their values" :label "map literal keyfn" :expected "{:x 1}" :actual "(let [k :x] {k 1})" :portability :common} - {:suite "conformance / map literals evaluate their values" :label "map literal in fn" :expected "6" :actual "(do (defn mk [a b] {:sum (+ a b)}) (:sum (mk 2 4)))" :portability :common} - {:suite "conformance / migratus enablement: def/defmacro/defmulti forms, assoc, try, ns" :label "def 3-arg docstring" :expected "42" :actual "(do (def dd \"the doc\" 42) dd)" :portability :common} - {:suite "conformance / migratus enablement: def/defmacro/defmulti forms, assoc, try, ns" :label "def docstring value type" :expected "true" :actual "(do (def ds \"doc\" [1 2]) (vector? ds))" :portability :common} - {:suite "conformance / migratus enablement: def/defmacro/defmulti forms, assoc, try, ns" :label "def ^{:map} name" :expected "5" :actual "(do (def ^{:private true} mmv 5) mmv)" :portability :common} - {:suite "conformance / migratus enablement: def/defmacro/defmulti forms, assoc, try, ns" :label "defn ^{:map} name" :expected "25" :actual "(do (defn ^{:private true} sqf [x] (* x x)) (sqf 5))" :portability :common} - {:suite "conformance / migratus enablement: def/defmacro/defmulti forms, assoc, try, ns" :label "defmacro arity-clause" :expected "10" :actual "(do (defmacro m2c ([x] (list (quote *) x 2))) (m2c 5))" :portability :common} - {:suite "conformance / migratus enablement: def/defmacro/defmulti forms, assoc, try, ns" :label "defmacro doc + arity" :expected "30" :actual "(do (defmacro m3c \"doc\" ([x] (list (quote *) x 3))) (* (m3c 5) 2))" :portability :common} - {:suite "conformance / migratus enablement: def/defmacro/defmulti forms, assoc, try, ns" :label "defmulti docstring" :expected "\"A\"" :actual "(do (defmulti gmm \"the doc\" identity) (defmethod gmm :a [_] \"A\") (gmm :a))" :portability :common} - {:suite "conformance / migratus enablement: def/defmacro/defmulti forms, assoc, try, ns" :label "try multi-body last" :expected "3" :actual "(try 1 2 3 (catch :default e 0))" :portability :common} - {:suite "conformance / migratus enablement: def/defmacro/defmulti forms, assoc, try, ns" :label "try finally on ok+catch" :expected "9" :actual "(let [a (atom 0)] (try 1 2 (catch :default e :c) (finally (reset! a 9))) @a)" :portability :common} - {:suite "conformance / migratus enablement: def/defmacro/defmulti forms, assoc, try, ns" :label "ns restored after catch" :expected "\"user\"" :actual "(do (ns cf.boom) (defn bz [] (throw (Exception. \"e\"))) (in-ns (quote user)) (try (cf.boom/bz) (catch :default e nil)) (str *ns*))" :portability :jvm} - {:suite "conformance / migratus enablement: def/defmacro/defmulti forms, assoc, try, ns" :label "cross-ns methods visible" :expected "[:sql]" :actual "(do (ns cf.mm) (defmulti ext identity) (defmethod ext :default [_] :d) (defn allk [] (vec (for [[k v] (methods ext) :when (not= k :default)] k))) (ns cf.mmi) (defmethod cf.mm/ext :sql [_] :s) (in-ns (quote user)) (cf.mm/allk))" :portability :common} - {:suite "conformance / defmacro surface + syntax-quote/ns (enabling real clojure libs)" :label "defmacro multi-arity" :expected "[6 5 6]" :actual "(do (defmacro mar ([a] (list (quote +) a 1)) ([a b] (list (quote +) a b)) ([a b c] (list (quote +) a b c))) [(mar 5) (mar 2 3) (mar 1 2 3)])" :portability :common} - {:suite "conformance / defmacro surface + syntax-quote/ns (enabling real clojure libs)" :label "defmacro doc + attr-map" :expected "10" :actual "(do (defmacro mam \"doc\" {:arglists (quote ([x]))} [x] (list (quote inc) x)) (mam 9))" :portability :common} - {:suite "conformance / defmacro surface + syntax-quote/ns (enabling real clojure libs)" :label "syntax-quote resolves alias" :expected "\"HI\"" :actual "(do (ns sq.lib (:require [clojure.string :as s])) (defmacro up [x] `(s/upper-case ~x)) (in-ns (quote user)) (sq.lib/up \"hi\"))" :portability :common} - {:suite "conformance / defmacro surface + syntax-quote/ns (enabling real clojure libs)" :label "ns name with ^{:map} meta" :expected "5" :actual "(do (ns ^{:author \"a\" :doc \"d\"} nm.meta) (def q 5) (in-ns (quote user)) nm.meta/q)" :portability :common} - {:suite "conformance / defmacro surface + syntax-quote/ns (enabling real clojure libs)" :label "unquote *ns* in template" :expected "true" :actual "(do (defmacro cur-ns [] `(str ~*ns*)) (string? (cur-ns)))" :portability :common} - {:suite "reader / read-string constructs sets" :label "top-level set" :expected "true" :actual "(set? (read-string \"#{:a :b}\"))" :portability :common} - {:suite "reader / read-string constructs sets" :label "set value equals" :expected "true" :actual "(= #{1 2} (read-string \"#{1 2}\"))" :portability :common} - {:suite "reader / read-string constructs sets" :label "set nested in map" :expected "true" :actual "(set? (:k (read-string \"{:k #{:a :b}}\")))" :portability :common} - {:suite "reader / read-string constructs sets" :label "set nested in vector" :expected "true" :actual "(set? (first (read-string \"[#{:a}]\")))" :portability :common} - {:suite "reader / read-string constructs sets" :label "set nested in list" :expected "true" :actual "(set? (first (read-string \"(#{:a})\")))" :portability :common} - {:suite "reader / read-string constructs sets" :label "set keeps reader metadata" :expected "true" :actual "(:s (meta (read-string \"^:s #{1 2}\")))" :portability :common} - {:suite "reader / read-string constructs sets" :label "set of sets" :expected "true" :actual "(every? set? (read-string \"#{#{1} #{2}}\"))" :portability :common} - {:suite "io / str & format" :label "format %x lowercase" :expected "\"ff\"" :actual "(format \"%x\" 255)" :portability :common} - {:suite "io / str & format" :label "format %04x zero-pad lower" :expected "\"00ff\"" :actual "(format \"%04x\" 255)" :portability :common} - {:suite "io / str & format" :label "format %X uppercase" :expected "\"00FF\"" :actual "(format \"%04X\" 255)" :portability :common} - {:suite "io / str & format" :label "format %x wide hex" :expected "\"deadbeef\"" :actual "(format \"%x\" 3735928559)" :portability :common} - {:suite "protocols / extend & extends? on nil" :label "extend nil dispatches" :expected ":nil-via-extend" :actual "(do (defprotocol P2 (q [this])) (extend nil P2 {:q (fn [_] :nil-via-extend)}) (q nil))" :portability :common} - {:suite "protocols / extend & extends? on nil" :label "extends? nil when extended" :expected "true" :actual "(do (defprotocol Pe (pe [this])) (extend nil Pe {:pe (fn [_] :x)}) (extends? Pe nil))" :portability :common} - {:suite "protocols / extend & extends? on nil" :label "extends? nil when not extended" :expected "false" :actual "(do (defprotocol P3 (r [this])) (extends? P3 nil))" :portability :common} - {:suite "protocols / extend & extends? on nil" :label "extend-type nil still works" :expected ":via-type" :actual "(do (defprotocol P4 (s [this])) (extend-type nil P4 (s [_] :via-type)) (s nil))" :portability :common} - {:suite "protocols / extend on host classes" :label "dispatch by java.util.Map/Collection/CharSequence" :expected "[:map :coll :str :obj]" :actual "(do (defprotocol W (-w [x])) (extend java.util.Map W {:-w (fn [_] :map)}) (extend java.util.Collection W {:-w (fn [_] :coll)}) (extend java.lang.CharSequence W {:-w (fn [_] :str)}) (extend java.lang.Object W {:-w (fn [_] :obj)}) [(-w {:a 1}) (-w [1 2]) (-w \"s\") (-w 42)])" :portability :jvm} - {:suite "protocols / extend on host classes" :label "satisfies? via java.util.Map" :expected "true" :actual "(do (defprotocol Q (qq [x])) (extend java.util.Map Q {:qq (fn [_] :m)}) (satisfies? Q {}))" :portability :jvm} - {:suite "protocols / extend on host classes" :label "extends? on a qualified host class" :expected "true" :actual "(do (defprotocol Qe (qe [x])) (extend java.util.Collection Qe {:qe (fn [_] :c)}) (extends? Qe java.util.Collection))" :portability :jvm} - {:suite "interop / instance? on host interfaces" :label "keyword is Named" :expected "true" :actual "(instance? clojure.lang.Named :a)" :portability :jvm} - {:suite "interop / instance? on host interfaces" :label "string is CharSequence" :expected "true" :actual "(instance? java.lang.CharSequence \"s\")" :portability :jvm} - {:suite "interop / instance? on host interfaces" :label "number is Number" :expected "true" :actual "(instance? java.lang.Number 42)" :portability :jvm} - {:suite "interop / instance? on host interfaces" :label "map is java.util.Map" :expected "true" :actual "(instance? java.util.Map {:a 1})" :portability :jvm} - {:suite "interop / instance? on host interfaces" :label "vector is java.util.List" :expected "true" :actual "(instance? java.util.List [1 2])" :portability :jvm} - {:suite "interop / instance? on host interfaces" :label "list is java.util.Collection" :expected "true" :actual "(instance? java.util.Collection (list 1))" :portability :jvm} - {:suite "interop / instance? on host interfaces" :label "set is java.util.Set" :expected "true" :actual "(instance? java.util.Set #{1})" :portability :jvm} - {:suite "interop / instance? on host interfaces" :label "map is not a Collection" :expected "false" :actual "(instance? java.util.Collection {:a 1})" :portability :jvm} - {:suite "interop / instance? on host interfaces" :label "vector is Associative" :expected "true" :actual "(instance? clojure.lang.Associative [1])" :portability :jvm} - {:suite "interop / instance? on host interfaces" :label "string is not Number" :expected "false" :actual "(instance? java.lang.Number \"s\")" :portability :jvm} - {:suite "interop / String & StringBuilder char ops" :label "String from char-array slice" :expected "\"abc\"" :actual "(String. (char-array [\\a \\b \\c \\d]) 0 3)" :portability :jvm} - {:suite "interop / String & StringBuilder char ops" :label "str of StringBuilder" :expected "\"hi\"" :actual "(let [sb (StringBuilder.)] (.append sb \"hi\") (str sb))" :portability :jvm} - {:suite "interop / String & StringBuilder char ops" :label "append subsequence" :expected "\"bcd\"" :actual "(let [sb (StringBuilder.)] (.append sb \"abcde\" 1 4) (.toString sb))" :portability :jvm} - {:suite "interop / String & StringBuilder char ops" :label "String.getChars into buffer" :expected "\"abc\"" :actual "(let [a (char-array 4)] (.getChars \"abcd\" 0 3 a 0) (String. a 0 3))" :portability :jvm} - {:suite "interop / numbers & classes" :label "Integer/toHexString lowercase" :expected "\"ff\"" :actual "(Integer/toHexString 255)" :portability :jvm} - {:suite "interop / numbers & classes" :label "Integer/toHexString wide" :expected "\"1234\"" :actual "(Integer/toHexString 4660)" :portability :jvm} - {:suite "interop / numbers & classes" :label ".isNaN on a double" :expected "true" :actual "(.isNaN (/ 0.0 0.0))" :portability :jvm} - {:suite "interop / numbers & classes" :label ".isInfinite on a double" :expected "true" :actual "(.isInfinite (/ 1.0 0.0))" :portability :jvm} - {:suite "interop / numbers & classes" :label ".isNaN false for finite" :expected "false" :actual "(.isNaN 1.0)" :portability :jvm} - {:suite "interop / numbers & classes" :label "protocol dispatch Long vs Double" :expected "[:l :d]" :actual "(do (defprotocol N (-n [x])) (extend java.lang.Long N {:-n (fn [_] :l)}) (extend java.lang.Double N {:-n (fn [_] :d)}) [(-n 5) (-n 5.0)])" :portability :jvm} - {:suite "interop / numbers & classes" :label "instance? PushbackReader" :expected "true" :actual "(instance? java.io.PushbackReader (java.io.PushbackReader. (java.io.StringReader. \"x\")))" :portability :jvm} - {:suite "interop / numbers & classes" :label "EOFException catch by class" :expected "\"boom\"" :actual "(try (throw (java.io.EOFException. \"boom\")) (catch java.io.EOFException e (.getMessage e)))" :portability :jvm} - {:suite "interop / numbers & classes" :label "Reader.read into char[]" :expected "[4 \"abcd\"]" :actual "(let [r (java.io.StringReader. \"abcd\") b (char-array 4)] (let [n (.read r b 0 4)] [n (String. b 0 n)]))" :portability :jvm} - {:suite "interop / java.time" :label "LocalDate toString" :expected "\"2020-01-15\"" :actual "(str (java.time.LocalDate/of 2020 1 15))" :portability :jvm} - {:suite "interop / java.time" :label "LocalDate plusDays over leap day" :expected "\"2020-02-29\"" :actual "(str (.plusDays (java.time.LocalDate/of 2020 2 28) 1))" :portability :jvm} - {:suite "interop / java.time" :label "LocalDate equality" :expected "true" :actual "(= (java.time.LocalDate/of 2020 1 15) (java.time.LocalDate/of 2020 1 15))" :portability :jvm} - {:suite "interop / java.time" :label "LocalDate compare" :expected "-1" :actual "(compare (java.time.LocalDate/of 2020 1 15) (java.time.LocalDate/of 2020 1 16))" :portability :jvm} - {:suite "interop / java.time" :label "LocalDate ofEpochDay round-trip" :expected "1" :actual "(.toEpochDay (java.time.LocalDate/of 1970 1 2))" :portability :jvm} - {:suite "interop / java.time" :label "LocalDate parse" :expected "\"2020-01-15\"" :actual "(str (java.time.LocalDate/parse \"2020-01-15\"))" :portability :jvm} - {:suite "interop / java.time" :label "LocalDate getDayOfWeek name" :expected "\"WEDNESDAY\"" :actual "(.name (.getDayOfWeek (java.time.LocalDate/of 2020 1 15)))" :portability :jvm} - {:suite "interop / java.time" :label "LocalTime toString" :expected "\"10:30:15\"" :actual "(str (java.time.LocalTime/of 10 30 15))" :portability :jvm} - {:suite "interop / java.time" :label "LocalTime plusHours wraps midnight" :expected "\"01:30\"" :actual "(str (.plusHours (java.time.LocalTime/of 23 30) 2))" :portability :jvm} - {:suite "interop / java.time" :label "LocalDateTime toString" :expected "\"2020-01-15T10:30\"" :actual "(str (java.time.LocalDateTime/of 2020 1 15 10 30 0))" :portability :jvm} - {:suite "interop / java.time" :label "Instant ofEpochMilli toString" :expected "\"2020-01-15T10:30:00Z\"" :actual "(str (java.time.Instant/ofEpochMilli 1579084200000))" :portability :jvm} - {:suite "interop / java.time" :label "Instant ofEpochMilli round-trip" :expected "1579084200000" :actual "(.toEpochMilli (java.time.Instant/ofEpochMilli 1579084200000))" :portability :jvm} - {:suite "interop / java.time" :label "Duration ofSeconds toString" :expected "\"PT1M30S\"" :actual "(str (java.time.Duration/ofSeconds 90))" :portability :jvm} - {:suite "interop / java.time" :label "Duration between instants" :expected "\"PT1H1M1S\"" :actual "(str (java.time.Duration/between (java.time.Instant/ofEpochSecond 0) (java.time.Instant/ofEpochSecond 3661)))" :portability :jvm} - {:suite "interop / java.time" :label "Period between dates" :expected "\"P1Y2M2D\"" :actual "(str (java.time.Period/between (java.time.LocalDate/of 2020 1 1) (java.time.LocalDate/of 2021 3 3)))" :portability :jvm} - {:suite "interop / java.time" :label "Period parse round-trip" :expected "\"P1Y2M3D\"" :actual "(str (java.time.Period/parse \"P1Y2M3D\"))" :portability :jvm} - {:suite "interop / java.time" :label "Period normalized" :expected "\"P2Y1M5D\"" :actual "(str (.normalized (java.time.Period/of 1 13 5)))" :portability :jvm} - {:suite "interop / java.time" :label "Month of toString" :expected "\"FEBRUARY\"" :actual "(.toString (java.time.Month/of 2))" :portability :jvm} - {:suite "interop / java.time" :label "Month length leap" :expected "29" :actual "(.length (java.time.Month/of 2) true)" :portability :jvm} - {:suite "interop / java.time" :label "DayOfWeek constant prints name" :expected "\"MONDAY\"" :actual "(str java.time.DayOfWeek/MONDAY)" :portability :jvm} - {:suite "interop / java.time" :label "YearMonth toString" :expected "\"2020-02\"" :actual "(str (java.time.YearMonth/of 2020 2))" :portability :jvm} - {:suite "interop / java.time" :label "ChronoUnit DAYS between" :expected "14" :actual "(.between java.time.temporal.ChronoUnit/DAYS (java.time.LocalDate/of 2020 1 1) (java.time.LocalDate/of 2020 1 15))" :portability :jvm} - {:suite "interop / java.time" :label "LocalDate plus ChronoUnit DAYS" :expected "\"2020-01-04\"" :actual "(str (.plus (java.time.LocalDate/of 2020 1 1) 3 java.time.temporal.ChronoUnit/DAYS))" :portability :jvm} - {:suite "interop / java.time" :label "LocalDate until ChronoUnit DAYS" :expected "31" :actual "(.until (java.time.LocalDate/of 2020 1 1) (java.time.LocalDate/of 2020 2 1) java.time.temporal.ChronoUnit/DAYS)" :portability :jvm} - {:suite "interop / java.time" :label "ZoneOffset ofHoursMinutes toString" :expected "\"+02:00\"" :actual "(str (java.time.ZoneOffset/ofHoursMinutes 2 0))" :portability :jvm} - {:suite "interop / java.time" :label "ZoneOffset ofTotalSeconds toString" :expected "\"-04:30\"" :actual "(str (java.time.ZoneOffset/ofTotalSeconds -16200))" :portability :jvm} - {:suite "interop / java.time" :label "ZoneOffset UTC toString" :expected "\"Z\"" :actual "(str java.time.ZoneOffset/UTC)" :portability :jvm} - {:suite "interop / java.time" :label "ZoneOffset of getTotalSeconds" :expected "7200" :actual "(.getTotalSeconds (java.time.ZoneOffset/of \"+02:00\"))" :portability :jvm} - {:suite "interop / java.time" :label "ZoneOffset ofHoursMinutes negative" :expected "\"-04:30\"" :actual "(.getId (java.time.ZoneOffset/ofHoursMinutes -4 -30))" :portability :jvm} - {:suite "interop / java.time" :label "OffsetDateTime toInstant" :expected "\"2020-01-15T08:30:00Z\"" :actual "(str (.toInstant (java.time.OffsetDateTime/of 2020 1 15 10 30 0 0 (java.time.ZoneOffset/ofHours 2))))" :portability :jvm} - {:suite "interop / java.time" :label "OffsetDateTime toString" :expected "\"2020-01-15T10:30+02:00\"" :actual "(str (java.time.OffsetDateTime/of 2020 1 15 10 30 0 0 (java.time.ZoneOffset/ofHours 2)))" :portability :jvm} - {:suite "interop / java.time" :label "ZonedDateTime withZoneSameInstant UTC" :expected "\"2020-01-15T08:30Z\"" :actual "(str (.withZoneSameInstant (java.time.ZonedDateTime/parse \"2020-01-15T10:30:00+02:00[Europe/Paris]\") java.time.ZoneOffset/UTC))" :portability :jvm} - {:suite "interop / java.time" :label "ZonedDateTime of toInstant fixed offset" :expected "\"2020-01-15T08:30:00Z\"" :actual "(str (.toInstant (java.time.ZonedDateTime/of 2020 1 15 10 30 0 0 (java.time.ZoneId/of \"+02:00\"))))" :portability :jvm} - {:suite "interop / java.time" :label "DateTimeFormatter ofPattern format" :expected "\"2020-01-15 10:30:00\"" :actual "(.format (java.time.format.DateTimeFormatter/ofPattern \"yyyy-MM-dd HH:mm:ss\") (java.time.LocalDateTime/of 2020 1 15 10 30 0))" :portability :jvm} - {:suite "interop / java.time" :label "ISO_LOCAL_DATE_TIME format" :expected "\"2020-01-15T10:30:00\"" :actual "(.format java.time.format.DateTimeFormatter/ISO_LOCAL_DATE_TIME (java.time.LocalDateTime/of 2020 1 15 10 30 0))" :portability :jvm} - {:suite "interop / java.time" :label "ISO_OFFSET_DATE_TIME format" :expected "\"2020-01-15T10:30:00+02:00\"" :actual "(.format java.time.format.DateTimeFormatter/ISO_OFFSET_DATE_TIME (java.time.OffsetDateTime/of 2020 1 15 10 30 0 0 (java.time.ZoneOffset/ofHours 2)))" :portability :jvm} - {:suite "interop / java.time" :label "Instant plusNanos toString nanos group" :expected "\"1970-01-01T00:00:00.000000001Z\"" :actual "(str (.plusNanos (java.time.Instant/ofEpochSecond 0) 1))" :portability :jvm} - {:suite "interop / java.time" :label "Instant one nano differs" :expected "false" :actual "(= (java.time.Instant/ofEpochSecond 0) (.plusNanos (java.time.Instant/ofEpochSecond 0) 1))" :portability :jvm} - {:suite "interop / java.time" :label "Instant getNano single nano" :expected "1" :actual "(.getNano (.plusNanos (java.time.Instant/ofEpochSecond 0) 1))" :portability :jvm} - {:suite "interop / java.time" :label "Instant ofEpochSecond nano millis group" :expected "\"1970-01-01T00:00:00.001Z\"" :actual "(str (java.time.Instant/ofEpochSecond 0 1000000))" :portability :jvm} - {:suite "interop / java.time" :label "Instant ofEpochSecond nano micros group" :expected "\"1970-01-01T00:00:00.000001Z\"" :actual "(str (java.time.Instant/ofEpochSecond 0 1000))" :portability :jvm} - {:suite "interop / java.time" :label "Instant plusSeconds keeps nanos" :expected "\"1970-01-01T00:00:02.000000005Z\"" :actual "(str (.plusSeconds (.plusNanos (java.time.Instant/ofEpochSecond 0) 5) 2))" :portability :jvm} - {:suite "interop / java.time" :label "Instant getEpochSecond floors negative nano" :expected "-1" :actual "(.getEpochSecond (.plusNanos (java.time.Instant/ofEpochSecond 0) -1))" :portability :jvm} - {:suite "interop / java.time" :label "Instant getNano of negative nano" :expected "999999999" :actual "(.getNano (.plusNanos (java.time.Instant/ofEpochSecond 0) -1))" :portability :jvm} - {:suite "interop / java.time" :label "Instant toEpochMilli floors sub-milli" :expected "1000" :actual "(.toEpochMilli (.plusNanos (java.time.Instant/ofEpochSecond 1) 999999))" :portability :jvm} - {:suite "interop / java.time" :label "Instant truncatedTo SECONDS drops nanos" :expected "\"1970-01-01T00:00:05Z\"" :actual "(str (.truncatedTo (.plusNanos (java.time.Instant/ofEpochSecond 5) 123) java.time.temporal.ChronoUnit/SECONDS))" :portability :jvm} - {:suite "interop / java.io File" :label "getName" :expected "\"c.txt\"" :actual "(.getName (java.io.File. \"/a/b/c.txt\"))" :portability :jvm} - {:suite "interop / java.io File" :label "getParent" :expected "\"/a/b\"" :actual "(.getParent (java.io.File. \"/a/b/c.txt\"))" :portability :jvm} - {:suite "interop / java.io File" :label "getPath keeps relative path" :expected "\"rel/x\"" :actual "(.getPath (java.io.File. \"rel/x\"))" :portability :jvm} - {:suite "interop / java.io File" :label "relative File is not absolute" :expected "false" :actual "(.isAbsolute (java.io.File. \"rel\"))" :portability :jvm} - {:suite "interop / java.io File" :label "parent+child constructor joins" :expected "\"/a/b\"" :actual "(.getPath (java.io.File. \"/a\" \"b\"))" :portability :jvm} - {:suite "interop / java.io File" :label "File/separator" :expected "\"/\"" :actual "java.io.File/separator" :portability :jvm} - {:suite "interop / java.io File" :label "str of File is its path" :expected "\"a/b\"" :actual "(str (java.io.File. \"a/b\"))" :portability :jvm} - {:suite "interop / java.io File" :label "mkdir then delete a temp dir" :expected "[true true true]" :actual "(let [d (java.io.File/createTempFile \"jd\" \"\")] (.delete d) [(.mkdir d) (.isDirectory d) (.delete d)])" :portability :jvm} - {:suite "interop / java.io streams" :label "ByteArrayOutputStream toString" :expected "\"hi!\"" :actual "(let [b (java.io.ByteArrayOutputStream.)] (.write b (.getBytes \"hi\")) (.write b 33) (.toString b))" :portability :jvm} - {:suite "interop / java.io streams" :label "ByteArrayOutputStream size" :expected "4" :actual "(let [b (java.io.ByteArrayOutputStream.)] (.write b (.getBytes \"abcd\")) (.size b))" :portability :jvm} - {:suite "interop / java.io streams" :label "ByteArrayOutputStream toByteArray round-trips" :expected "\"yo\"" :actual "(String. (.toByteArray (doto (java.io.ByteArrayOutputStream.) (.write (.getBytes \"yo\")))))" :portability :jvm} - {:suite "interop / java.io streams" :label "ByteArrayInputStream read to EOF" :expected "[65 66 -1]" :actual "(let [in (java.io.ByteArrayInputStream. (.getBytes \"AB\"))] [(.read in) (.read in) (.read in)])" :portability :jvm} - {:suite "interop / java.io streams" :label "BufferedReader over StringReader readLine" :expected "[\"a\" \"b\" nil]" :actual "(let [r (java.io.BufferedReader. (java.io.StringReader. \"a\\nb\\n\"))] [(.readLine r) (.readLine r) (.readLine r)])" :portability :jvm} - {:suite "interop / java.io streams" :label "instance? InputStream" :expected "true" :actual "(instance? java.io.InputStream (java.io.ByteArrayInputStream. (.getBytes \"x\")))" :portability :jvm} - {:suite "interop / java.io streams" :label "FileOutputStream then FileInputStream round-trip" :expected "90" :actual "(let [f (java.io.File/createTempFile \"jc\" \".t\") o (java.io.FileOutputStream. f)] (.write o (byte-array [90])) (.close o) (let [in (java.io.FileInputStream. f) b (.read in)] (.close in) (.delete f) b))" :portability :jvm} - {:suite "clojure.edn / unknown tags" :label "unknown tag throws naming the tag" :expected "\"No reader function for tag foobar\"" :actual "(do (require (quote [clojure.edn :as e1])) (try (e1/read-string \"#foobar 1\") (catch Exception e (ex-message e))))" :portability :common} - {:suite "clojure.edn / unknown tags" :label "object tag throws naming the tag" :expected "\"No reader function for tag object\"" :actual "(do (require (quote [clojure.edn :as e2])) (try (e2/read-string \"#object [1 2 3]\") (catch Exception e (ex-message e))))" :portability :common} - {:suite "clojure.edn / unknown tags" :label ":default opt handles an unknown tag" :expected "[\"foobar\" 9]" :actual "(do (require (quote [clojure.edn :as e3])) (e3/read-string {:default (fn [t v] [(name t) v])} \"#foobar 9\"))" :portability :common} - {:suite "deftype / clojure.lang interfaces" :label "Indexed + Counted dispatch" :expected "[3 20]" :actual "(do (deftype Row [v] clojure.lang.Indexed (nth [_ i] (nth v i)) (nth [_ i x] (nth v i x)) clojure.lang.Counted (count [_] (count v))) [(count (->Row [10 20 30])) (nth (->Row [10 20 30]) 1)])" :portability :jvm} - {:suite "deftype / clojure.lang interfaces" :label "multi-arity inline method" :expected "[5 11]" :actual "(do (defprotocol PMul (mm [this a] [this a b])) (deftype TMul [] PMul (mm [_ a] a) (mm [_ a b] (+ a b))) [(mm (->TMul) 5) (mm (->TMul) 5 6)])" :portability :common} - {:suite "deftype / clojure.lang interfaces" :label "ILookup valAt computes a non-field key" :expected "[1 :miss]" :actual "(do (deftype TL [a] clojure.lang.ILookup (valAt [this k] (.valAt this k nil)) (valAt [_ k nf] (case k :a a :computed 99 nf))) [(:a (->TL 1)) (get (->TL 1) :nope :miss)])" :portability :jvm} - {:suite "deftype / clojure.lang interfaces" :label "marker protocol satisfies?" :expected "true" :actual "(do (defprotocol PMark) (deftype TM [] PMark) (satisfies? PMark (->TM)))" :portability :common} - {:suite "deftype / clojure.lang interfaces" :label "IFn record is callable" :expected "7" :actual "(do (deftype Adder [n] clojure.lang.IFn (invoke [_ x] (+ n x))) ((->Adder 5) 2))" :portability :jvm} - {:suite "interop / collections" :label "Map keySet" :expected "true" :actual "(= (set (.keySet {:a 1 :b 2})) #{:a :b})" :portability :jvm} - {:suite "interop / collections" :label "instance? ILookup on a map" :expected "true" :actual "(instance? clojure.lang.ILookup {:a 1})" :portability :jvm} - {:suite "interop / collections" :label "instance? Indexed on a vector" :expected "true" :actual "(instance? clojure.lang.Indexed [1 2 3])" :portability :jvm} - {:suite "interop / java.util.Date" :label "deprecated getYear/getMonth" :expected "[110 0]" :actual "(let [d (java.util.Date. 110 0 15)] [(.getYear d) (.getMonth d)])" :portability :jvm} - {:suite "clojure.set / variadic" :label "union of 4 sets" :expected "#{1 2 3 4}" :actual "(do (require (quote clojure.set)) (clojure.set/union #{1} #{2} #{3} #{4}))" :portability :common} - {:suite "clojure.set / variadic" :label "intersection of 3 sets" :expected "#{3}" :actual "(do (require (quote clojure.set)) (clojure.set/intersection #{1 2 3} #{2 3 4} #{3 4 5}))" :portability :common} - {:suite "regex / literal value" :label "literal is a Pattern" :expected "true" :actual "(instance? java.util.regex.Pattern #\"a.c\")" :portability :jvm} - {:suite "regex / literal value" :label "re-matches on a literal" :expected "\"aaa\"" :actual "(re-matches #\"a+\" \"aaa\")" :portability :common} - {:suite "regex / literal value" :label "quoted regex round-trips" :expected "\"#\\\"a.c\\\"\"" :actual "(pr-str (quote #\"a.c\"))" :portability :common} - {:suite "regex / literal value" :label "extend-protocol to Pattern dispatches" :expected "[:pattern :other]" :actual "(do (defprotocol Tg (tg [_])) (extend-protocol Tg java.util.regex.Pattern (tg [_] :pattern) Object (tg [_] :other)) [(tg #\"x\") (tg 1)])" :portability :jvm} - {:suite "records / representation" :label "assoc a declared field keeps the record" :expected "[true 9 2]" :actual "(do (defrecord R [a b]) (let [x (assoc (->R 1 2) :a 9)] [(record? x) (:a x) (:b x)]))" :portability :common} - {:suite "records / representation" :label "assoc an extension field keeps the record" :expected "[true 3 1]" :actual "(do (defrecord R [a b]) (let [x (assoc (->R 1 2) :c 3)] [(record? x) (:c x) (:a x)]))" :portability :common} - {:suite "records / representation" :label "dissoc an extension field keeps the record" :expected "[true nil 1]" :actual "(do (defrecord R [a b]) (let [x (-> (->R 1 2) (assoc :c 3) (dissoc :c))] [(record? x) (:c x) (:a x)]))" :portability :common} - {:suite "records / representation" :label "dissoc a declared field downgrades to a map" :expected "[false true 2 false]" :actual "(do (defrecord R [a b]) (let [m (dissoc (->R 1 2) :a)] [(record? m) (map? m) (:b m) (contains? m :a)]))" :portability :common} - {:suite "records / representation" :label "count includes extension fields" :expected "[2 3]" :actual "(do (defrecord R [a b]) [(count (->R 1 2)) (count (assoc (->R 1 2) :c 3))])" :portability :common} - {:suite "records / representation" :label "keys are declared then extension order" :expected "[[:a :b] [:a :b :c]]" :actual "(do (defrecord R [a b]) [(vec (keys (->R 1 2))) (vec (keys (assoc (->R 1 2) :c 3)))])" :portability :common} - {:suite "records / representation" :label "a nil field value is present, not absent" :expected "[nil true :d]" :actual "(do (defrecord R [a b]) (let [n (->R nil 2)] [(:a n) (contains? n :a) (get (->R 1 2) :zzz :d)]))" :portability :common} - {:suite "records / representation" :label "seq yields field map-entries" :expected "[[:a 1] [:b 2]]" :actual "(do (defrecord R [a b]) (vec (map (fn [e] [(key e) (val e)]) (->R 1 2))))" :portability :common} - {:suite "records / representation" :label "conj a map-entry vector assocs it" :expected "3" :actual "(do (defrecord R [a b]) (:c (conj (->R 1 2) [:c 3])))" :portability :common} - {:suite "records / representation" :label "= after assoc of an unchanged field" :expected "true" :actual "(do (defrecord R [a b]) (= (assoc (->R 1 2) :a 1) (->R 1 2)))" :portability :common} - {:suite "records / representation" :label "= compares extension fields" :expected "[true false]" :actual "(do (defrecord R [a b]) [(= (assoc (->R 1 2) :c 9) (assoc (->R 1 2) :c 9)) (= (assoc (->R 1 2) :c 9) (->R 1 2))])" :portability :common} - {:suite "records / representation" :label "assoc then dissoc an extension field = original" :expected "true" :actual "(do (defrecord R [a b]) (= (-> (->R 1 2) (assoc :c 3) (dissoc :c)) (->R 1 2)))" :portability :common} - {:suite "records / representation" :label "map-> keeps extension keys" :expected "[true 3 [:a :b :c]]" :actual "(do (defrecord R [a b]) (let [m (map->R {:a 1 :b 2 :c 3})] [(record? m) (:c m) (vec (keys m))]))" :portability :common} - {:suite "records / representation" :label "record as a map key" :expected ":v" :actual "(do (defrecord R [a]) (get {(->R 1) :v} (->R 1)))" :portability :common} - {:suite "records / representation" :label "records dedup in a set by value" :expected "2" :actual "(do (defrecord R [a]) (count (into #{} [(->R 1) (->R 1) (->R 2)])))" :portability :common} - {:suite "records / representation" :label "nested record field reads" :expected "[2 1]" :actual "(do (defrecord N [l r v]) (let [t (->N (->N nil nil 1) nil 2)] [(:v t) (:v (:l t))]))" :portability :common} - {:suite "protocols / arity dispatch" :label "multi-arity protocol method on a record" :expected "[\"0:9\" \"1:9::a\" \"2:9::a::b\"]" :actual "(do (defprotocol P (m [this] [this x] [this x y])) (defrecord R [v] P (m [this] (str \"0:\" v)) (m [this x] (str \"1:\" v \":\" x)) (m [this x y] (str \"2:\" v \":\" x \":\" y))) [(m (->R 9)) (m (->R 9) :a) (m (->R 9) :a :b)])" :portability :common} - {:suite "protocols / arity dispatch" :label "two-arg protocol method" :expected "30" :actual "(do (defprotocol P (addp [this x y])) (defrecord R [n] P (addp [_ x y] (+ n (+ x y)))) (addp (->R 10) 7 13))" :portability :common} - {:suite "protocols / arity dispatch" :label "protocol method extended to a host type with an arg" :expected "\"S:hi:5\"" :actual "(do (defprotocol Q (mq [this a])) (extend-protocol Q java.lang.String (mq [this a] (str \"S:\" this \":\" a))) (mq \"hi\" 5))" :portability :jvm} - {:suite "protocols / arity dispatch" :label "protocol method used as a value" :expected "[1 2]" :actual "(do (defprotocol Z (z [this])) (defrecord ZR [v] Z (z [_] v)) (mapv z [(->ZR 1) (->ZR 2)]))" :portability :common} - {:suite "protocols / arity dispatch" :label "no-extra-arg method dispatches by type" :expected "[16 25]" :actual "(do (defprotocol Sh (ar [s])) (defrecord Sq [x] Sh (ar [_] (* x x))) (defrecord Sq2 [y] Sh (ar [_] (* y y))) [(ar (->Sq 4)) (ar (->Sq2 5))])" :portability :common} - {:suite "vectors / large trie" :label "linear build equals range across paths" :expected "true" :actual "(= (vec (range 2000)) (reduce conj [] (range 2000)) (into [] (range 2000)))" :portability :common} - {:suite "vectors / large trie" :label "nth across a multi-level vector" :expected "[0 1024 2000 2099]" :actual "(let [v (vec (range 2100))] [(nth v 0) (nth v 1024) (nth v 2000) (nth v 2099)])" :portability :common} - {:suite "vectors / large trie" :label "assoc in a large vector" :expected "[1098 :x 1100]" :actual "(let [v (assoc (vec (range 1100)) 1099 :x)] [(nth v 1098) (nth v 1099) (count v)])" :portability :common} - {:suite "vectors / large trie" :label "pop down across a level boundary" :expected "[1023 1022]" :actual "(let [p (pop (vec (range 1024)))] [(count p) (peek p)])" :portability :common} - {:suite "vectors / large trie" :label "pop to empty then rebuild" :expected "[0 5]" :actual "(let [e (loop [v (vec (range 100))] (if (seq v) (recur (pop v)) v))] [(count e) (count (into e (range 5)))])" :portability :common} - {:suite "printer / print-length" :label "truncates an infinite seq before realizing it" :expected "true" :actual "(= \"(0 1 2 ...)\" (binding [*print-length* 3] (pr-str (range))))" :portability :common} - {:suite "printer / print-length" :label "truncates a vector with ellipsis" :expected "true" :actual "(= \"[1 2 ...]\" (binding [*print-length* 2] (pr-str [1 2 3 4])))" :portability :common} - {:suite "printer / print-length" :label "exactly N elements prints no ellipsis" :expected "true" :actual "(= \"(0 1 2)\" (binding [*print-length* 3] (pr-str (range 3))))" :portability :common} - {:suite "printer / print-length" :label "nil default is unlimited" :expected "true" :actual "(= \"[1 2 3 4 5]\" (pr-str [1 2 3 4 5]))" :portability :common} - {:suite "printer / print-level" :label "collapses a collection past the level to #" :expected "true" :actual "(= \"[:a [:b #]]\" (binding [*print-level* 2] (pr-str [:a [:b [:c 1]]])))" :portability :common} - {:suite "printer / print-level" :label "level 0 collapses the top collection" :expected "true" :actual "(= \"#\" (binding [*print-level* 0] (pr-str [1 2])))" :portability :common} - {:suite "printer / print-level" :label "level 1 keeps the outermost collection" :expected "true" :actual "(= \"[# 3]\" (binding [*print-level* 1] (pr-str [[1 2] 3])))" :portability :common} - {:suite "printer / print-level" :label "scalars print regardless of level" :expected "true" :actual "(= \"[1 2]\" (binding [*print-level* 1] (pr-str [1 2])))" :portability :common} - {:suite "reader / default-data-reader-fn" :label "consulted for an unregistered tag" :expected "true" :actual "(= [(quote foo) 42] (binding [*default-data-reader-fn* (fn [tag v] [tag v])] (read-string \"#foo 42\")))" :portability :common} - {:suite "printer / print-vars" :label "print-length / print-level / default-data-reader-fn default to nil" :expected "[true true true]" :actual "[(nil? *print-length*) (nil? *print-level*) (nil? *default-data-reader-fn*)]" :portability :common} - {:suite "seqs / laziness" :label "an empty lazy seq is () not nil" :expected "true" :actual "(= () (lazy-seq nil))" :portability :common} - {:suite "seqs / laziness" :label "rest of a one-element coll is ()" :expected "true" :actual "(= () (rest [1]))" :portability :common} - {:suite "seqs / laziness" :label "first of iterate does not call f" :expected "true" :actual "(let [a (atom 0)] (first (iterate (fn [x] (swap! a inc) (inc x)) 0)) (= 0 @a))" :portability :common} - {:suite "seqs / laziness" :label "rest of iterate does not realize the next element" :expected "true" :actual "(let [a (atom 0)] (rest (iterate (fn [x] (swap! a inc) (inc x)) 0)) (= 0 @a))" :portability :common} - {:suite "seqs / laziness" :label "take from an infinite iterate" :expected "[0 1 2 3 4]" :actual "(vec (take 5 (iterate inc 0)))" :portability :common} - {:suite "seqs / laziness" :label "distinct over a rest-derived seq does not overrun" :expected "2" :actual "(count (distinct (map inc (rest [10 20 30]))))" :portability :common} - {:suite "transducers / map multi-input" :label "the map transducer applies f across all inputs" :expected "[6]" :actual "(((map +) conj) [] 1 2 3)" :portability :common} - {:suite "transducers / map multi-input" :label "single input is unchanged" :expected "[3]" :actual "(((map +) conj) [] 3)" :portability :common} - {:suite "records / deftype is not a map" :label "a bare deftype is neither map? nor record?, a defrecord is both" :expected "[false false true true]" :actual "(do (deftype DT [a]) (defrecord DR [a]) [(map? (->DT 1)) (record? (->DT 1)) (map? (->DR 1)) (record? (->DR 1))])" :portability :common} - {:suite "printer / str vs print" :label "str of a vector quotes nested strings" :expected "true" :actual "(= \"[\\\"x\\\"]\" (str [\"x\"]))" :portability :common} - {:suite "printer / str vs print" :label "print-str of a vector leaves strings raw" :expected "true" :actual "(= \"[x]\" (print-str [\"x\"]))" :portability :common} - {:suite "printer / str vs print" :label "str of a map quotes nested strings" :expected "true" :actual "(= \"{\\\"a\\\" \\\"b\\\"}\" (str {\"a\" \"b\"}))" :portability :common} - {:suite "printer / str vs print" :label "print-str of a map leaves strings raw" :expected "true" :actual "(= \"{:a x}\" (print-str {:a \"x\"}))" :portability :common} - {:suite "printer / str vs print" :label "infinity inside a collection prints readably in str" :expected "true" :actual "(= \"[##Inf]\" (str [##Inf]))" :portability :common} - {:suite "interop / uri equality" :label "URIs are value-equal and usable as set members" :expected "[true true]" :actual "[(= (java.net.URI. \"/\") (java.net.URI. \"/\")) (= #{(java.net.URI. \"/\")} #{(java.net.URI. \"/\")})]" :portability :jvm} - {:suite "stdlib / clojure.walk" :label "macroexpand-all expands a form" :expected "true" :actual "(do (require (quote clojure.walk)) (seq? (clojure.walk/macroexpand-all (quote (when true 1)))))" :portability :common} - {:suite "regex / re-seq zero-width" :label "a zero-width match advances by one without repeating" :expected "[\"a\" \"\" \"a\" \"\"]" :actual "(vec (re-seq #\"a*\" \"aba\"))" :portability :common} - {:suite "seqs / lazy-seq interop" :label "conj onto a rest-derived seq prepends" :expected "true" :actual "(= [9 2 3] (vec (conj (rest [1 2 3]) 9)))" :portability :common} - {:suite "seqs / lazy-seq interop" :label "conj onto a lazy-seq prepends" :expected "true" :actual "(= [9 1 2] (vec (conj (lazy-seq (list 1 2)) 9)))" :portability :common} - {:suite "seqs / lazy-seq interop" :label "into over a conj'd rest-seq" :expected "true" :actual "(= [0 2 3] (into [] (conj (rest [1 2 3]) 0)))" :portability :common} - {:suite "seqs / lazy-seq interop" :label "first of a conj'd rest-seq" :expected "true" :actual "(= 9 (first (conj (rest [1 2 3]) 9)))" :portability :common} - {:suite "seqs / lazy-seq interop" :label "count of a conj'd rest-seq" :expected "true" :actual "(= 3 (count (conj (rest [1 2 3]) 9)))" :portability :common} - {:suite "seqs / lazy-seq interop" :label "nth into a rest-seq" :expected "true" :actual "(= 3 (nth (rest [1 2 3]) 1))" :portability :common} - {:suite "seqs / lazy-seq interop" :label "reduce over a rest-seq" :expected "true" :actual "(= 5 (reduce + (rest [1 2 3])))" :portability :common} - {:suite "seqs / lazy-seq interop" :label "a rest-seq equals the literal tail" :expected "true" :actual "(= (quote (2 3)) (rest [1 2 3]))" :portability :common} - {:suite "seqs / lazy-seq interop" :label "map over a rest-seq" :expected "true" :actual "(= [3 4] (vec (map inc (rest [1 2 3]))))" :portability :common} - {:suite "seqs / lazy-seq interop" :label "filter over a rest-seq" :expected "true" :actual "(= [3] (vec (filter odd? (rest [1 2 3 4]))))" :portability :common} - {:suite "seqs / lazy-seq interop" :label "apply over a rest-seq" :expected "true" :actual "(= 5 (apply + (rest [1 2 3])))" :portability :common} - {:suite "seqs / lazy-seq interop" :label "seq of an empty rest is nil" :expected "true" :actual "(nil? (seq (rest [1])))" :portability :common} - {:suite "seqs / lazy-seq interop" :label "empty? of an empty rest" :expected "true" :actual "(empty? (rest [1]))" :portability :common} - {:suite "seqs / lazy-seq interop" :label "cons onto a rest-seq" :expected "true" :actual "(= [0 2 3] (vec (cons 0 (rest [1 2 3]))))" :portability :common} - {:suite "seqs / lazy-seq interop" :label "into a set from a rest-seq" :expected "true" :actual "(= #{2 3} (into #{} (rest [1 2 3])))" :portability :common} - {:suite "ifn / symbol as fn" :label "a symbol invokes as a map lookup" :expected "true" :actual "(= 5 ('a {(quote a) 5}))" :portability :common} - {:suite "ifn / symbol as fn" :label "a symbol fn takes a not-found default" :expected "true" :actual "(= :d ('a {} :d))" :portability :common} - {:suite "ifn / symbol as fn" :label "a symbol works as a mapping fn" :expected "true" :actual "(= [1 2] (vec (map (quote k) [{(quote k) 1} {(quote k) 2}])))" :portability :common} - {:suite "defn / attr-map" :label "docstring + attr-map both land in var meta" :expected "true" :actual "(do (defn f \"doc\" {:my :attr} [] 1) (= [\"doc\" :attr] [(:doc (meta (var f))) (:my (meta (var f)))]))" :portability :common} - {:suite "defn / attr-map" :label "attr-map without a docstring" :expected "true" :actual "(do (defn g {:my :attr} [] 1) (= :attr (:my (meta (var g)))))" :portability :common} - {:suite "defn / attr-map" :label "attr-map on a multi-arity defn" :expected "true" :actual "(do (defn h \"d\" {:my :a} ([] 1) ([a] a)) (= :a (:my (meta (var h)))))" :portability :common} - {:suite "defn / attr-map" :label "attr-map values are evaluated" :expected "true" :actual "(do (defn m {:val (+ 1 2)} [] 1) (= 3 (:val (meta (var m)))))" :portability :common} - {:suite "records / clojure.lang interop" :label "a record's Associative/ILookup methods delegate to the map fns" :expected "[1 9 true true 2]" :actual "(do (defrecord M [a b]) (let [m (->M 1 2)] [(.valAt m :a) (.valAt m :z 9) (= {:a 1 :b 2 :c 3} (into {} (.assoc m :c 3))) (.containsKey m :a) (.count m)]))" :portability :jvm} - {:suite "interop / number classes" :label "Byte/Short bounds + class tokens" :expected "[127 -128 32767 -32768 true]" :actual "[Byte/MAX_VALUE Byte/MIN_VALUE Short/MAX_VALUE Short/MIN_VALUE (= java.lang.Byte java.lang.Byte)]" :portability :jvm} - {:suite "reader / metadata" :label "a set in metadata is read as a value, not a tagged form" :expected "true" :actual "(= #{:a :b} (:foo (meta (read-string (binding [*print-meta* true] (pr-str (with-meta [1] {:foo #{:a :b}})))))))" :portability :common} - {:suite "reader / metadata" :label "metadata on an empty list is preserved" :expected "true" :actual "(= {:foo 1} (meta (read-string \"^{:foo 1} ()\")))" :portability :common} - {:suite "reader / metadata" :label "a vector in metadata reads as a value" :expected "true" :actual "(= [1 2] (:v (meta (read-string \"^{:v [1 2]} {:a 1}\"))))" :portability :common} - {:suite "reader / metadata" :label "an empty list in metadata reads as a value" :expected "true" :actual "(= () (:e (meta (read-string \"^{:e ()} [1]\"))))" :portability :common} - {:suite "edn / readers in collections" :label "a :default tag reader applies inside a set" :expected "true" :actual "(= #{[:t 1]} (clojure.edn/read-string {:default (fn [t v] [:t v])} \"#{#foo 1}\"))" :portability :common} - {:suite "edn / readers in collections" :label "a registered reader applies inside a set" :expected "true" :actual "(= #{6} (clojure.edn/read-string {:readers {(quote x) (fn [v] (* v 2))}} \"#{#x 3}\"))" :portability :common} - {:suite "metadata / immutability" :label "with-meta on a list does not mutate the original" :expected "true" :actual "(let [ds (list 1 2)] (with-meta ds {:k 1}) (nil? (meta ds)))" :portability :common} - {:suite "metadata / immutability" :label "with-meta on a list carries the metadata" :expected "true" :actual "(= {:k 1} (meta (with-meta (list 1) {:k 1})))" :portability :common} - {:suite "metadata / immutability" :label "a meta-bearing list still equals the bare list" :expected "true" :actual "(let [ds (list 1)] (= ds (with-meta ds {:k 9})))" :portability :common} - {:suite "metadata / immutability" :label "with-meta on a lazy seq carries metadata" :expected "true" :actual "(= {:k 5} (meta (with-meta (lazy-seq (list 1)) {:k 5})))" :portability :common} - {:suite "edn / deferred tags" :label "a :readers override wins over the built-in #inst (not eagerly built)" :expected "true" :actual "(= [:I \"x\"] (clojure.edn/read-string {:readers {(quote inst) (fn [v] [:I v])}} \"#inst \\\"x\\\"\"))" :portability :common} - {:suite "edn / deferred tags" :label "a normal #inst still constructs without an override" :expected "true" :actual "(= #inst \"2020-01-01T00:00:00.000-00:00\" (clojure.edn/read-string \"#inst \\\"2020-01-01T00:00:00.000-00:00\\\"\"))" :portability :common} - {:suite "vars / privacy" :label "defn- marks the var :private" :expected "true" :actual "(do (defn- p [] 1) (true? (:private (meta (var p)))))" :portability :common} - {:suite "vars / privacy" :label "ns-publics drops private vars; ns-interns keeps them" :expected "[true false true]" :actual "(do (defn pub [] 1) (defn- priv [] 2) [(contains? (ns-publics (quote user)) (quote pub)) (contains? (ns-publics (quote user)) (quote priv)) (contains? (ns-interns (quote user)) (quote priv))])" :portability :common} - {:suite "host interop / dot form" :label "(. target (method args)) list-member sugar" :expected "\"HELLO\"" :actual "(. \"hello\" (toUpperCase))" :portability :jvm} - {:suite "predicates / identical?" :label "reference identity, not value equality" :expected "[true false false]" :actual "[(identical? :a :a) (identical? (quote x) (quote x)) (identical? [1] [1])]" :portability :common} - {:suite "host interop / hashCode" :label "Java String and Symbol hashCode" :expected "[120 -1634134448]" :actual "[(.hashCode \"x\") (.hashCode (quote foo/bar))]" :portability :jvm} - {:suite "structmaps" :label "defstruct / struct-map / struct" :expected "[{:a 1 :b 2} {:a 1 :b 2} {:a 1 :b nil}]" :actual "(do (defstruct sx :a :b) [(struct-map sx :a 1 :b 2) (struct sx 1 2) (struct-map sx :a 1)])" :portability :common} - {:suite "deftype / clojure.lang interfaces" :label "ILookup-only deftype is not coll? or seqable?" :expected "[false false]" :actual "(do (deftype Lk [x] clojure.lang.ILookup (valAt [_ k] nil) (valAt [_ k nf] nf)) [(coll? (->Lk 1)) (seqable? (->Lk 1))])" :portability :jvm} - {:suite "host interop / Collection.contains" :label "value membership over vector/list/set" :expected "[true false true]" :actual "[(.contains [1 2 3] 2) (.contains (list :a :b) :z) (.contains #{1 2} 1)]" :portability :jvm} - {:suite "host interop / clojure.lang.Util" :label "Util/hash is Java hashCode" :expected "120" :actual "(clojure.lang.Util/hash \"x\")" :portability :jvm} - {:suite "deftype / IObj metadata" :label "deftype meta/withMeta govern (meta x)" :expected "{:a 1}" :actual "(do (deftype Sm [m] clojure.lang.IObj (meta [_] m) (withMeta [_ n] (Sm. n))) (meta (Sm. {:a 1})))" :portability :jvm} - {:suite "collections / disj" :label "disj of nil is nil" :expected "nil" :actual "(disj nil :a)" :portability :common} - {:suite "special forms / qualified" :label "clojure.core-qualified special form (from syntax-quote)" :expected "[:g 9]" :actual "(clojure.core/letfn [(g [x] [:g x])] (g 9))" :portability :common} - {:suite "symbols / interning" :label "(str sym) is the symbol's interned name (identity-stable)" :expected "[true true]" :actual "(let [s (quote ?a)] [(identical? (name s) (str s)) (= (str s) \"?a\")])" :portability :common} - {:suite "symbols / interning" :label "equal symbols share an interned name string" :expected "true" :actual "(let [a (quote ?foo) b (quote ?foo)] (identical? (name a) (name b)))" :portability :common} - {:suite "reader / unquote" :label "~x reads as clojure.core/unquote" :expected "true" :actual "(= (quote (clojure.core/unquote v)) (read-string \"~v\"))" :portability :common} - {:suite "reader / unquote" :label "~@x reads as clojure.core/unquote-splicing" :expected "true" :actual "(= (quote clojure.core/unquote-splicing) (first (read-string \"~@xs\")))" :portability :common} - {:suite "clojure.core / range" :label "(range 0) is the empty seq ()" :expected "true" :actual "(= () (range 0))" :portability :common} - {:suite "clojure.core / range" :label "(range 5 5) is the empty seq ()" :expected "true" :actual "(= () (range 5 5))" :portability :common} - {:suite "clojure.core / range" :label "empty range is not nil" :expected "true" :actual "(some? (range 5 0))" :portability :common} - {:suite "clojure.core / range" :label "empty range count" :expected "0" :actual "(count (range 0))" :portability :common} - {:suite "host-interop / instance? Object" :label "every non-nil value is an Object" :expected "[true true true true]" :actual "[(instance? Object 1) (instance? Object \"x\") (instance? Object []) (instance? Object (fn []))]" :portability :common} - {:suite "host-interop / instance? Object" :label "nil is not an instance of Object" :expected "false" :actual "(instance? Object nil)" :portability :common} - {:suite "host-interop / instance? Object" :label "java.lang.Object too" :expected "true" :actual "(instance? java.lang.Object :k)" :portability :jvm} - {:suite "host-interop / Compiler" :label "@Compiler/LINE is a number" :expected "true" :actual "(number? @clojure.lang.Compiler/LINE)" :portability :jvm} - {:suite "reader / octal literals" :label "0NNN is octal" :expected "34" :actual "042" :portability :common} - {:suite "reader / octal literals" :label "negative octal" :expected "-34" :actual "-042" :portability :common} - {:suite "reader / octal literals" :label "octal char escape \\oNNN" :expected "true" :actual "(= (char 0377) \\o377)" :portability :common} - {:suite "reader / octal literals" :label "octal string escape is one char" :expected "true" :actual "(= \"a\\000b\" (str \"a\" (char 0) \"b\"))" :portability :common} - {:suite "reader / octal literals" :label "hex still decimal-distinct" :expected "[1070 255 0]" :actual "[0x42e 0xff 0]" :portability :common} - {:suite "symbols / construction" :label "(symbol nil name) equals (symbol name)" :expected "true" :actual "(= (symbol nil \"foo\") (quote foo))" :portability :common} - {:suite "symbols / construction" :label "(symbol nil name) has no namespace" :expected "true" :actual "(nil? (namespace (symbol nil \"x\")))" :portability :common} - {:suite "host-interop / instance? hierarchy" :label "ExceptionInfo is a RuntimeException" :expected "[true true true]" :actual "[(instance? RuntimeException (ex-info \"x\" {})) (instance? Exception (ex-info \"x\" {})) (instance? Throwable (ex-info \"x\" {}))]" :portability :common} - {:suite "host-interop / class hierarchy" :label "Symbol and Keyword are IFn" :expected "[true true]" :actual "[(isa? clojure.lang.Symbol clojure.lang.IFn) (isa? clojure.lang.Keyword clojure.lang.IFn)]" :portability :jvm} - {:suite "host-interop / class hierarchy" :label "(class sym)-dispatched multimethod hits an IFn method" :expected ":ifn" :actual "(do (defmulti cm1 class) (defmethod cm1 clojure.lang.IFn [_] :ifn) (cm1 (quote sym)))" :portability :jvm} - {:suite "host-interop / extend-protocol java.io" :label "protocol extended to Reader / String dispatches a StringReader and a String" :expected "[:reader :string]" :actual "(do (import (quote (java.io StringReader))) (defprotocol Prdr (mrd [x])) (extend-protocol Prdr java.io.Reader (mrd [_] :reader) String (mrd [_] :string)) [(mrd (StringReader. \"x\")) (mrd \"y\")])" :portability :jvm} - {:suite "host-interop / StringWriter" :label "(str StringWriter) returns its accumulated content" :expected "\"hi!\"" :actual "(do (import (quote (java.io StringWriter))) (let [w (StringWriter.)] (.write w \"hi\") (.write w \"!\") (str w)))" :portability :jvm} - {:suite "numbers / unchecked wraps to signed 64-bit" :label "unchecked-add overflow wraps" :expected "-9223372036854775808" :actual "(unchecked-add 9223372036854775807 1)" :portability :common} - {:suite "numbers / unchecked wraps to signed 64-bit" :label "unchecked-multiply overflow wraps" :expected "1" :actual "(unchecked-multiply 9223372036854775807 9223372036854775807)" :portability :common} - {:suite "numbers / unchecked wraps to signed 64-bit" :label "unchecked-subtract underflow wraps" :expected "9223372036854775807" :actual "(unchecked-subtract -9223372036854775808 1)" :portability :common} - {:suite "numbers / unchecked wraps to signed 64-bit" :label "unchecked-negate of MIN wraps to MIN" :expected "-9223372036854775808" :actual "(unchecked-negate -9223372036854775808)" :portability :common} - {:suite "numbers / unchecked wraps to signed 64-bit" :label "unchecked-inc of MAX wraps to MIN" :expected "-9223372036854775808" :actual "(unchecked-inc 9223372036854775807)" :portability :common} - {:suite "host-interop / Long bit statics" :label "Long/bitCount, numberOfLeadingZeros, reverse" :expected "[10 63 0 -2]" :actual "[(Long/bitCount 1023) (Long/numberOfLeadingZeros 1) (Long/bitCount 0) (Long/reverse 9223372036854775807)]" :portability :jvm} - {:suite "numbers / unsigned-bit-shift-right is logical over 64 bits" :label "shift of a negative shifts in zeros" :expected "[9223372036854775807 4611686018427387902]" :actual "[(unsigned-bit-shift-right -1 1) (unsigned-bit-shift-right -8 2)]" :portability :common} - {:suite "numbers / ^long is 64-bit" :label "^long comparison on a full-width long" :expected "false" :actual "((fn* ([^long a ^long b] (< a b))) 9223372036854775807 1)" :portability :common} - {:suite "numbers / ^long is 64-bit" :label "^long quot on a full-width long" :expected "3074457345618258602" :actual "((fn* ([^long a] (quot a 3))) 9223372036854775807)" :portability :common} - {:suite "host-interop / Compiler" :label "Compiler/specials keys include the special forms" :expected "true" :actual "(every? (set (keys clojure.lang.Compiler/specials)) (quote [if do let* fn* quote def loop* recur try letfn* var]))" :portability :jvm} - {:suite "macros / letfn mutual recursion" :label "letfn binds mutually-recursive named fns" :expected "[true false]" :actual "(letfn [(ev? [n] (if (zero? n) true (od? (dec n)))) (od? [n] (if (zero? n) false (ev? (dec n))))] [(ev? 10) (ev? 7)])" :portability :common} - {:suite "host-interop / extend-protocol IPersistentList" :label "a protocol extended to IPersistentList dispatches on a list, not a vector" :expected "[:list :vec :list]" :actual "(do (defprotocol PL (m [x])) (extend-protocol PL clojure.lang.IPersistentList (m [_] :list) clojure.lang.IPersistentVector (m [_] :vec)) [(m (list 1 2)) (m [1 2]) (m ())])" :portability :jvm} - {:suite "scope / qualified ref vs same-named local" :label "clojure.core/max wins over a local named max" :expected "[10 5]" :actual "[((fn [max] (clojure.core/max 5 10)) 100) ((fn [min] (clojure.core/min 5 10)) 0)]" :portability :common} - {:suite "numbers / unchecked on doubles" :label "unchecked-multiply of doubles is a double, not a truncated long" :expected "3.0" :actual "(unchecked-multiply 1.5 2.0)" :portability :common} - {:suite "seq / take infinite count" :label "(take +Infinity coll) takes the whole coll" :expected "7" :actual "(count (take (/ 1.0 0.0) (range 7)))" :portability :common} - {:suite "host-interop / UUID + Long + shiftLeft" :label "(UUID. msb lsb), .shiftLeft, (Long. n)" :expected "[\"00000000-0000-007b-0000-0000000001c8\" 40 10 42]" :actual "[(str (java.util.UUID. 123 456)) (.shiftLeft 5 3) (.shiftRight 40 2) (Long. 42)]" :portability :jvm} - {:suite "host-interop / ThreadLocal proxy" :label "(proxy [ThreadLocal] [] (initialValue [] v)) get/set" :expected "[42 7]" :actual "(let [tl (proxy [ThreadLocal] [] (initialValue [] 42))] [(.get tl) (do (.set tl 7) (.get tl))])" :portability :jvm} - {:suite "host-interop / Compiler/demunge" :label "demunge reverses name munging" :expected "\"a/b?\"" :actual "(clojure.lang.Compiler/demunge \"a$b_QMARK_\")" :portability :jvm} - {:suite "host-interop / a fn reports its munged class" :label "(class a-def'd-fn) is ns$munged-name, with the IFn hierarchy as ancestors" :expected "[\"clojure.core$odd_QMARK_\" true]" :actual "[(.getName (class odd?)) (boolean (some #{java.lang.Runnable} (ancestors (class odd?))))]" :portability :jvm} - {:suite "host-interop / MultiFn methods" :label ".getMethod / .dispatchFn on a multimethod" :expected "[true true true]" :actual "(do (defmulti mmc identity) (defmethod mmc :a [_] 1) [(some? (.getMethod mmc :a)) (nil? (.getMethod mmc :z)) (ifn? (.dispatchFn mmc))])" :portability :jvm} - {:suite "reader / namespaced map literal" :label "#:ns{...} qualifies bare keys; :_/x stays unqualified" :expected "[:search 2 nil]" :actual "[(:event/type #:event{:type :search :id 5}) (count #:x{:a 1 :b 2}) (:k #:_{:k 9})]" :portability :common} - {:suite "lazy / chunking" :label "(seq (range 1 50)) is a chunked-seq" :expected "true" :actual "(chunked-seq? (seq (range 1 50)))" :portability :common} - {:suite "lazy / chunking" :label "map over a chunked range realizes a whole 32-block on first" :expected "32" :actual "(let [c (atom 0) s (map (fn [x] (swap! c inc) x) (range 1 50))] (first s) @c)" :portability :common} - {:suite "lazy / chunking" :label "crossing a chunk boundary realizes the next 32-block" :expected "49" :actual "(let [c (atom 0) s (map (fn [x] (swap! c inc) x) (range 1 50))] (nth s 32) @c)" :portability :common} - {:suite "lazy / chunking" :label "chained maps each batch by 32 (result is itself chunked)" :expected "[32 32]" :actual "(let [fc (atom 0) gc (atom 0) s (map (fn [x] (swap! gc inc) x) (map (fn [x] (swap! fc inc) x) (range 1 50)))] (first s) [@fc @gc])" :portability :common} - {:suite "lazy / chunking" :label "filter over a chunked range applies pred to the whole first block" :expected "32" :actual "(let [c (atom 0) s (filter (fn [x] (swap! c inc) (even? x)) (range 1 50))] (first s) @c)" :portability :common} - {:suite "lazy / chunking" :label "a plain lazy seq (not chunked) realizes one element at a time" :expected "1" :actual "(let [c (atom 0) lz (fn lz [n] (lazy-seq (cons n (lz (inc n))))) s (map (fn [x] (swap! c inc) x) (lz 0))] (first s) @c)" :portability :common} - {:suite "io / with-out-str" :label "with-out-str captures (.write *out* …) and print alike" :expected "\"hi!x\"" :actual "(with-out-str (.write *out* \"hi\") (.write *out* \"!\") (print \"x\"))" :portability :jvm} - {:suite "nth / bounds" :label "nth past a vector end throws IndexOutOfBoundsException" :expected ":ok" :actual "(try (nth [1 2] 5) (catch IndexOutOfBoundsException e :ok))" :portability :common} - {:suite "nth / bounds" :label "nth past a seq end throws IndexOutOfBoundsException" :expected ":ok" :actual "(try (nth (seq [1 2]) 5) (catch IndexOutOfBoundsException e :ok))" :portability :common} - {:suite "assoc / bounds" :label "assoc past a vector end throws IndexOutOfBoundsException" :expected ":ok" :actual "(try (assoc [1 2] 5 :x) (catch IndexOutOfBoundsException e :ok))" :portability :common} - {:suite "number / toString radix" :label ".toString(radix) renders in base, lowercase" :expected "[\"ff\" \"377\" \"1001\"]" :actual "[(.toString (biginteger 255) 16) (.toString (biginteger 255) 8) (.toString (biginteger 9) 2)]" :portability :jvm} - {:suite "quote / metadata" :label "a quoted form keeps user metadata, drops reader location" :expected "[{:x true} nil]" :actual "[(meta (quote ^:x (1 2))) (meta (quote (1 2)))]" :portability :common} - {:suite "enumeration-seq" :label "enumeration-seq drives a java.util.Enumeration (StringTokenizer)" :expected "[\"1\" \"2\" \"3\"]" :actual "(vec (enumeration-seq (java.util.StringTokenizer. \"1 2 3\")))" :portability :jvm} - {:suite "protocols / interface dispatch" :label "extend-protocol to an interface a builtin implements dispatches (instance? and protocol dispatch agree)" :expected "[:assoc :ifn :seqable]" :actual "(do (defprotocol PA (ma [_])) (extend-protocol PA clojure.lang.Associative (ma [_] :assoc)) (defprotocol PF (mf [_])) (extend-protocol PF clojure.lang.IFn (mf [_] :ifn)) (defprotocol PS (ms [_])) (extend-protocol PS clojure.lang.Seqable (ms [_] :seqable)) [(ma [1 2]) (mf :k) (ms (map inc [1 2]))])" :portability :jvm} - {:suite "protocols / instance? matches dispatch" :label "instance? agrees with what a value's class implements" :expected "[true true false true true]" :actual "[(instance? clojure.lang.Associative [1 2]) (instance? clojure.lang.IFn :k) (instance? java.util.Map [1 2]) (instance? clojure.lang.Seqable (map inc [1 2])) (instance? clojure.lang.IPersistentVector [1 2])]" :portability :jvm} - {:suite "class / hierarchy views agree" :label "isa?/supers see the modeled exception + collection hierarchy" :expected "[true true true true]" :actual "[(isa? clojure.lang.ExceptionInfo java.lang.RuntimeException) (contains? (supers java.lang.NumberFormatException) java.lang.RuntimeException) (isa? clojure.lang.Keyword clojure.lang.IFn) (contains? (ancestors clojure.lang.PersistentVector) java.util.List)]" :portability :jvm} - {:suite "host-interop / getClass" :label ".getClass is a universal Object method, reached on every value type" :expected "[\"java.util.Date\" \"java.io.File\"]" :actual "[(.getName (.getClass (java.util.Date.))) (.getName (.getClass (java.io.File. \"x\")))]" :portability :jvm} - {:suite "reduce / IReduceInit" :label "reduce drives a deftype's own reduce method (init arity)" :expected "110" :actual "(do (deftype Rng [n] clojure.lang.IReduceInit (reduce [_ f init] (loop [i 0 acc init] (if (< i n) (recur (inc i) (f acc i)) acc)))) (reduce + 100 (->Rng 5)))" :portability :jvm} - {:suite "reduce / IReduceInit" :label "a deftype reduce honors reduced short-circuit" :expected "3" :actual "(do (deftype Rng [n] clojure.lang.IReduceInit (reduce [_ f init] (loop [i 0 acc init] (if (< i n) (let [a (f acc i)] (if (reduced? a) @a (recur (inc i) a))) acc)))) (reduce (fn [acc x] (if (= x 3) (reduced acc) (+ acc x))) 0 (->Rng 10)))" :portability :jvm} - {:suite "exceptions / typed throw" :label "a jolt-raised NumberFormatException reports its real class and message" :expected "[\"java.lang.NumberFormatException\" \"For input string: \\\"xyz\\\"\"]" :actual "(try (Long/parseLong \"xyz\") (catch Throwable e [(.getName (class e)) (.getMessage e)]))" :portability :jvm} - {:suite "exceptions / hierarchy catch" :label "a typed throwable matches its superclasses, not unrelated ones" :expected "[true true true false]" :actual "(let [e (try (Long/parseLong \"z\") (catch Throwable e e))] [(instance? NumberFormatException e) (instance? IllegalArgumentException e) (instance? Exception e) (instance? java.io.IOException e)])" :portability :jvm} - {:suite "equality / identity" :label "= short-circuits on identity without realizing a lazy seq (Util.equiv k1 == k2)" :expected "0" :actual "(let [n (atom 0) s (map (fn [x] (swap! n inc) x) [1 2 3])] (= s s) @n)" :portability :common} - {:suite "realized? / lazy seq" :label "realized? reads a lazy seq's realization flag" :expected "[false true]" :actual "(let [s (map inc [1 2 3])] [(realized? s) (do (doall s) (realized? s))])" :portability :common} - {:suite "numbers / ops dispatch" :label "double contagion beats exact-zero shortcut" :expected "[0.0 0.0 0.0 0.0]" :actual "[(* 1.0 0) (* 0 1.5) (/ 0 1.5) (- 0.0 0)]" :portability :common} - {:suite "numbers / ops dispatch" :label "Inf times zero is NaN" :expected "[true true]" :actual "[(NaN? (* ##Inf 0)) (NaN? (* 0 ##-Inf))]" :portability :common} - {:suite "numbers / ops dispatch" :label "zero over NaN is NaN" :expected "true" :actual "(NaN? (/ 0 ##NaN))" :portability :common} - {:suite "numbers / ops dispatch" :label "double division by exact zero is signed Inf" :expected "[##Inf ##-Inf]" :actual "[(/ 1.0 0) (/ -1.0 0)]" :portability :common} - {:suite "numbers / ops dispatch" :label "exact division by zero throws ArithmeticException" :expected "[:ae :ae :ae]" :actual "[(try (/ 1 0) (catch ArithmeticException _ :ae)) (try (/ 0) (catch ArithmeticException _ :ae)) (try (quot 1.0 0) (catch ArithmeticException _ :ae))]" :portability :common} - {:suite "numbers / ops dispatch" :label "non-number operand is ClassCastException" :expected "[:cce :cce]" :actual "[(try (+ 1 \"a\") (catch ClassCastException _ :cce)) (try (< \"a\" 1) (catch ClassCastException _ :cce))]" :portability :common} - {:suite "numbers / ops dispatch" :label "quot over ratios truncates" :expected "[6 -2 1]" :actual "[(quot 3 1/2) (quot -3 4/3) (quot 37/2 15)]" :portability :common} - {:suite "numbers / ops dispatch" :label "quot/rem double contagion" :expected "[3.0 1.5 0.0]" :actual "[(quot 10.0 3) (rem 5.5 2) (quot 1 ##Inf)]" :portability :common} - {:suite "numbers / ops dispatch" :label "mod takes the divisor's sign on doubles" :expected "[0.5 -0.5 1.5]" :actual "[(mod -5.5 2) (mod 5.5 -2) (mod 5.5 2)]" :portability :common} - {:suite "numbers / ops dispatch" :label "min/max return the original operand" :expected "[1 4.0 1M]" :actual "[(min 1 2.0) (max 3 4.0) (min 1M 2)]" :portability :common} - {:suite "numbers / ops dispatch" :label "NaN wins min/max" :expected "[true true]" :actual "[(NaN? (min 1.0 ##NaN)) (NaN? (max ##NaN 1.0))]" :portability :common} - {:suite "numbers / ops dispatch" :label "bigdec call position mixes with doubles" :expected "[3.5 1.0 true]" :actual "[(+ 1.5M 2.0) (/ 2.0M 2.0) (< 1.5M 2.0)]" :portability :common} - {:suite "numbers / ops dispatch" :label "runtime bigdec reaches call-position ops" :expected "[4M 2M true]" :actual "(let [x (bigdec 3)] [(+ x 1) (- x 1) (< 1 x)])" :portability :common} - {:suite "numbers / ops dispatch" :label "inc/dec on bigdec" :expected "[2.5M 0.5M]" :actual "[(inc 1.5M) (dec 1.5M)]" :portability :common} - {:suite "numbers / with-precision" :label "rounding modes" :expected "[2M -1M 1M -2M 2M 1M]" :actual "[(with-precision 1 :rounding UP (* 1.1M 1M)) (with-precision 1 :rounding CEILING (* -1.1M 1M)) (with-precision 1 :rounding DOWN (* 1.9M 1M)) (with-precision 1 :rounding FLOOR (* -1.9M 1M)) (with-precision 1 :rounding HALF_EVEN (* 2.5M 1M)) (with-precision 1 :rounding HALF_DOWN (* 1.5M 1M))]" :portability :common} - {:suite "numbers / with-precision" :label "UNNECESSARY throws when rounding needed, passes exact" :expected "[:ae 2M]" :actual "[(try (with-precision 1 :rounding UNNECESSARY (* 1.5M 1M)) (catch ArithmeticException _ :ae)) (with-precision 1 :rounding UNNECESSARY (* 2M 1M))]" :portability :common} - {:suite "numbers / with-precision" :label "division rounds to precision (default HALF_UP)" :expected "\"0.3333\"" :actual "(str (with-precision 4 (/ 1M 3M)))" :portability :common} - {:suite "numbers / rationalize" :label "doubles go through shortest decimal print" :expected "[11/10 3/2 1 0 -1]" :actual "[(rationalize 1.1) (rationalize 1.5) (rationalize 1.0) (rationalize 0.0) (rationalize -1.0)]" :portability :common} - {:suite "numbers / rationalize" :label "bigdec and exacts pass through exactly" :expected "[3/2 1/3 7]" :actual "[(rationalize 1.5M) (rationalize 1/3) (rationalize 7)]" :portability :common} - {:suite "hierarchy / derive asserts" :label "tag and parent must be namespaced Named (or a class)" :expected "[:ae :ae :ae :ae]" :actual "[(try (derive :a :user/p) (catch AssertionError _ :ae)) (try (derive :user/a :p) (catch AssertionError _ :ae)) (try (derive (make-hierarchy) :user/a :user/a) (catch AssertionError _ :ae)) (try (derive (make-hierarchy) :user/a \"p\") (catch AssertionError _ :ae))]" :portability :common} - {:suite "hierarchy / derive throws" :label "redundant ancestor and cyclic derivation throw" :expected "[:anc :cyc]" :actual "(let [h (derive (derive (make-hierarchy) :user/b :user/a) :user/c :user/b)] [(try (derive h :user/c :user/a) (catch Exception _ :anc)) (try (derive h :user/a :user/c) (catch Exception _ :cyc))])" :portability :common} - {:suite "hierarchy / underive" :label "a non-hierarchy first arg throws at the parents lookup" :expected "[:t :t :t]" :actual "[(try (underive {} :user/a :user/b) (catch Throwable _ :t)) (try (underive 42 :user/a :user/b) (catch Throwable _ :t)) (try (underive nil :user/a :user/b) (catch Throwable _ :t))]" :portability :common} - {:suite "hierarchy / underive" :label "underive removes the relationship" :expected "[nil false]" :actual "(let [h (derive (make-hierarchy) :user/b :user/a) h2 (underive h :user/b :user/a)] [(parents h2 :user/b) (isa? h2 :user/b :user/a)])" :portability :common} - {:suite "hierarchy / classes" :label "descendants of a class throws" :expected ":uoe" :actual "(try (descendants (make-hierarchy) java.lang.String) (catch UnsupportedOperationException _ :uoe))" :portability :jvm} - {:suite "hierarchy / classes" :label "ancestors of a concrete class roots at Object" :expected "[true true]" :actual "[(contains? (ancestors (class #{})) java.lang.Object) (contains? (ancestors (class [])) java.lang.Object)]" :portability :jvm} - {:suite "hierarchy / classes" :label "parents of a class are its direct supers" :expected "true" :actual "(contains? (parents (class [])) clojure.lang.APersistentVector)" :portability :jvm} - {:suite "hierarchy / classes" :label "a relationship derived on a super applies to the class (isa? supers arm)" :expected "true" :actual "(let [h (derive (make-hierarchy) java.util.Collection :user/coll-like)] (isa? h (class []) :user/coll-like))" :portability :jvm} - {:suite "iref / atom ctor options" :label ":meta attaches, :validator gates the initial value" :expected "[{:m 1} 1 nil]" :actual "(let [a (atom 1 :meta {:m 1} :validator pos?)] [(meta a) (deref a) (meta (atom nil :meta nil))])" :portability :common} - {:suite "iref / atom ctor options" :label "non-map :meta is a ClassCastException" :expected "[:cce :cce]" :actual "[(try (atom nil :meta 5) (catch ClassCastException _ :cce)) (try (atom nil :meta #{}) (catch ClassCastException _ :cce))]" :portability :common} - {:suite "iref / atom ctor options" :label "an invalid initial value never constructs" :expected ":ise" :actual "(try (atom {} :validator (constantly false)) (catch IllegalStateException _ :ise))" :portability :common} - {:suite "iref / atom ctor options" :label "validator still gates swap!/reset!" :expected "[:ise 1]" :actual "(let [a (atom 1 :validator pos?)] [(try (reset! a -1) (catch IllegalStateException _ :ise)) (deref a)])" :portability :common} - {:suite "iref / watches" :label "an atom watch gets key, the ref, old and new" :expected "[:k true 0 1]" :actual "(let [a (atom 0) w (atom nil)] (add-watch a :k (fn [k r o n] (reset! w [k (identical? r a) o n]))) (swap! a inc) (deref w))" :portability :common} - {:suite "iref / watches" :label "vars are watchable: root changes notify (alter-var-root, def)" :expected "[[1 2] [2 5]]" :actual "(do (def vw-x 1) (def vw-log (atom [])) (add-watch (var vw-x) :w (fn [k r o n] (swap! vw-log conj [o n]))) (alter-var-root (var vw-x) inc) (def vw-x 5) (deref vw-log))" :portability :common} - {:suite "iref / watches" :label "add-watch returns the var; a validator gates the var root" :expected "[true :ise]" :actual "(do (def vv-y 1) [(= (var vv-y) (add-watch (var vv-y) :k (fn [a b c d] nil))) (do (set-validator! (var vv-y) pos?) (try (alter-var-root (var vv-y) -) (catch IllegalStateException _ :ise)))])" :portability :common} - {:suite "iref / watches" :label "agent watches fire on state change" :expected "[0 1]" :actual "(let [ag (agent 0) p (promise)] (add-watch ag :w (fn [k r o n] (deliver p [o n]))) (send ag inc) (deref p 2000 :timeout))" :portability :common} - {:suite "iref / meta" :label "alter-meta! works on atoms" :expected "{:x 1 :y 2}" :actual "(let [a (atom 1 :meta {:x 1})] (alter-meta! a assoc :y 2))" :portability :common} - {:suite "casts / checked narrow" :label "doubles range-check themselves, then truncate" :expected "[1 1 3 1 \\a 0]" :actual "[(byte 1.1) (short 1.9) (int 3.7) (long 1.5) (char 97.5) (long ##NaN)]" :portability :common} - {:suite "casts / checked narrow" :label "out-of-range values throw IllegalArgumentException" :expected "[:iae :iae :iae :iae :iae :iae :iae]" :actual "[(try (byte 128) (catch IllegalArgumentException _ :iae)) (try (byte 127.000001) (catch IllegalArgumentException _ :iae)) (try (short 40000) (catch IllegalArgumentException _ :iae)) (try (int 2147483647.000001) (catch IllegalArgumentException _ :iae)) (try (char -1) (catch IllegalArgumentException _ :iae)) (try (char 65536) (catch IllegalArgumentException _ :iae)) (try (long 1e300) (catch IllegalArgumentException _ :iae))]" :portability :common} - {:suite "casts / checked narrow" :label "the throw carries the JVM message" :expected "\"Value out of range for byte: 128\"" :actual "(try (byte 128) (catch IllegalArgumentException e (ex-message e)))" :portability :common} - {:suite "casts / checked narrow" :label "ratios and bigdecs truncate; non-numbers are CCE" :expected "[1 5 :cce]" :actual "[(byte 3/2) (int 5.5M) (try (byte true) (catch ClassCastException _ :cce))]" :portability :common} - {:suite "casts / checked narrow" :label "float range-checks against Float/MAX_VALUE" :expected "[:iae 1.5]" :actual "[(try (float 1e300) (catch IllegalArgumentException _ :iae)) (float 1.5)]" :portability :common} - {:suite "casts / unchecked wrap" :label "unchecked casts wrap and sign-fold; doubles saturate" :expected "[-56 -25536 \\A 9223372036854775807 0 0]" :actual "[(unchecked-byte 200) (unchecked-short 40000) (unchecked-char 65) (unchecked-long 1e300) (unchecked-int 4294967296) (unchecked-long ##NaN)]" :portability :common} - {:suite "ns / requiring-resolve" :label "loads the namespace then resolves; unqualified throws" :expected "[#{1 2} :iae]" :actual "[((requiring-resolve (quote clojure.set/union)) #{1} #{2}) (try (requiring-resolve (quote unqualified)) (catch IllegalArgumentException _ :iae))]" :portability :common} - {:suite "string / toString coercion" :label "case fns and searches take any Object through toString" :expected "[\":ASDF/X\" \"asdf\" \"1\" true true]" :actual "[(clojure.string/upper-case :asdf/x) (clojure.string/lower-case (quote ASDF)) (clojure.string/capitalize 1) (clojure.string/starts-with? :ab \":a\") (clojure.string/ends-with? (quote ab) \"b\")]" :portability :common} - {:suite "string / toString coercion" :label "nil s throws; nil substr throws" :expected "[:t :t :t]" :actual "[(try (clojure.string/upper-case nil) (catch Throwable _ :t)) (try (clojure.string/starts-with? \"\" nil) (catch Throwable _ :t)) (try (clojure.string/escape nil {}) (catch Throwable _ :t))]" :portability :common} - {:suite "core / some-fn" :label "returns the last predicate value (false, not nil); zero preds is an arity error" :expected "[false 2 :ae]" :actual "[((some-fn even?) 1) ((some-fn :a :b) {:b 2}) (try (some-fn) (catch clojure.lang.ArityException _ :ae))]" :portability :jvm} - {:suite "core / ifn?" :label "multimethods and promises are IFn; promises deliver when invoked" :expected "[true true 7]" :actual "[(do (defmulti ifnq-mm identity) (ifn? ifnq-mm)) (ifn? (promise)) (let [p (promise)] (p 7) (deref p))]" :portability :common} - {:suite "multimethods / deferred definition" :label "defmulti/defmethod inside a fn intern in the ns they were written in" :expected ":hit" :actual "((fn [] (defmulti cdm-deferred first) (defmethod cdm-deferred :a [_] :hit) (cdm-deferred [:a 1])))" :portability :common} - {:suite "host-interop / wrapper ctors and TYPE" :label "Boolean/Integer/Double ctors; primitive TYPE tokens" :expected "[false true 12 1.5 \"int\" \"double\"]" :actual "[(Boolean. \"yes\") (Boolean. \"TRUE\") (Integer. \"12\") (Double. \"1.5\") (str Integer/TYPE) (str Double/TYPE)]" :portability :jvm} - {:suite "host-interop / IReduce" :label ".reduce drives a collection's own reduce" :expected "[7 6]" :actual "[(.reduce [1 2 3] + 1) (.reduce [1 2 3] +)]" :portability :jvm} - {:suite "edn / strictness" :label "duplicate literal keys and elements throw" :expected "[:dup :dup]" :actual "[(try (clojure.edn/read-string \"{:a 1 :a 2}\") (catch IllegalArgumentException _ :dup)) (try (clojure.edn/read-string \"#{:a :a}\") (catch IllegalArgumentException _ :dup))]" :portability :common} - {:suite "edn / strictness" :label "invalid numbers and ratio edges throw" :expected "[:ae :nfe :nfe :nfe :nfe]" :actual "[(try (clojure.edn/read-string \"1/0\") (catch ArithmeticException _ :ae)) (try (clojure.edn/read-string \"1/-1\") (catch NumberFormatException _ :nfe)) (try (clojure.edn/read-string \"08\") (catch NumberFormatException _ :nfe)) (try (clojure.edn/read-string \"1a\") (catch NumberFormatException _ :nfe)) (try (clojure.edn/read-string \"0x2g\") (catch NumberFormatException _ :nfe))]" :portability :common} - {:suite "edn / strictness" :label "invalid tokens throw; :/ and ns// are valid" :expected "[:t :t :t :t \"/\" \"/\"]" :actual "[(try (clojure.edn/read-string \"::foo\") (catch Throwable _ :t)) (try (clojure.edn/read-string \":\") (catch Throwable _ :t)) (try (clojure.edn/read-string \"foo/\") (catch Throwable _ :t)) (try (clojure.edn/read-string \"/foo\") (catch Throwable _ :t)) (name (clojure.edn/read-string \":/\")) (name (clojure.edn/read-string \"foo//\"))]" :portability :common} - {:suite "edn / strictness" :label "unmatched delimiters, bad escapes, octal range throw" :expected "[:t :t :t :t]" :actual "[(try (clojure.edn/read-string \")\") (catch Throwable _ :t)) (try (clojure.edn/read-string \"]\") (catch Throwable _ :t)) (try (clojure.edn/read-string \"\\\"\\\\q\\\"\") (catch Throwable _ :t)) (try (clojure.edn/read-string \"\\\\o400\") (catch Throwable _ :t))]" :portability :common} - {:suite "edn / strictness" :label "eof honors :eof; a missing :eof is an error; \\r ends comments" :expected "[:END :t 3]" :actual "[(clojure.edn/read-string {:eof :END} \"\") (try (clojure.edn/read-string {} \" \") (catch Throwable _ :t)) (clojure.edn/read-string \";c\\r3\\n5\")]" :portability :common} - {:suite "edn / strictness" :label "M literals construct; lists are lists; discarded tags validate" :expected "[-3.14M true :t]" :actual "[(clojure.edn/read-string \"-3.14M\") (list? (clojure.edn/read-string \"(1 (2))\")) (try (clojure.edn/read-string \"#_ #foo 0\") (catch Throwable _ :t))]" :portability :common} - {:suite "edn / strictness" :label "#inst and #uuid validate their fields" :expected "[:t :t :t]" :actual "[(try (clojure.edn/read-string \"#inst \\\"2010-02-29T00:00:00.000Z\\\"\") (catch Throwable _ :t)) (try (clojure.edn/read-string \"#inst \\\"2010-01-01T24:00:00.000Z\\\"\") (catch Throwable _ :t)) (try (clojure.edn/read-string \"#uuid \\\"not-a-uuid\\\"\") (catch Throwable _ :t))]" :portability :common} - {:suite "reader / strict tokens" :label "the core reader rejects invalid numbers and duplicate keys too" :expected "[:nfe :dup 34]" :actual "[(try (read-string \"1a\") (catch NumberFormatException _ :nfe)) (try (read-string \"{:a 1 :a 2}\") (catch IllegalArgumentException _ :dup)) (read-string \"042\")]" :portability :common} - {:suite "reader / symbol intern" :label "1-arg symbol splits ns at the first slash (Symbol.intern)" :expected "[\"foo\" \"bar/baz\" \"/\"]" :actual "[(namespace (symbol \"foo/bar/baz\")) (name (symbol \"foo/bar/baz\")) (name (symbol \"foo//\"))]" :portability :common} - {:suite "contracts / stacks and pending" :label "peek/pop demand a stack; realized? demands IPending; pop nil is nil" :expected "[:cce :cce nil nil nil]" :actual "[(try (peek (range 10)) (catch ClassCastException _ :cce)) (try (realized? (quote (1 2))) (catch ClassCastException _ :cce)) (pop nil) (nth nil 10) (conj nil)]" :portability :common} - {:suite "contracts / collection fns" :label "keys/vals of empties are nil; contains? on a string is index-only" :expected "[nil nil nil :iae true false]" :actual "[(keys []) (vals #{}) (keys \"\") (try (contains? \"abc\" \"a\") (catch IllegalArgumentException _ :iae)) (contains? \"abc\" 1) (contains? \"abc\" 5)]" :portability :common} - {:suite "contracts / collection fns" :label "transient demands an editable collection; empty on a record throws" :expected "[:cce :uoe]" :actual "[(try (transient 1) (catch ClassCastException _ :cce)) (do (defrecord EmptyRec [a]) (try (empty (->EmptyRec 1)) (catch UnsupportedOperationException _ :uoe)))]" :portability :common} - {:suite "contracts / numbers" :label "numerator/denominator over real ratios; even?/odd? demand integers" :expected "[1 3 :cce :iae]" :actual "[(numerator 1/2) (denominator 2/3) (try (numerator 2) (catch ClassCastException _ :cce)) (try (even? 1.5) (catch IllegalArgumentException _ :iae))]" :portability :common} - {:suite "contracts / numbers" :label "number?/rational?/num accept BigDecimal; NaN quotient throws" :expected "[true true 1.5M :nfe]" :actual "[(number? 1.5M) (rational? 1M) (num 1.5M) (try (quot ##NaN 1) (catch NumberFormatException _ :nfe))]" :portability :common} - {:suite "contracts / ordering" :label "keywords order namespace-first with nil first, like symbols" :expected "[true true true]" :actual "[(neg? (compare :cat :animal/cat)) (neg? (compare :animal/cat :b/cat)) (zero? (compare :dog :dog))]" :portability :common} - {:suite "contracts / misc" :label "vector invocation has nth semantics; run! honors reduced; eval self-evaluates values" :expected "[:ioob 1 true]" :actual "[(try ([1 2] 5) (catch IndexOutOfBoundsException _ :ioob)) (let [c (atom 0)] (run! (fn [x] (swap! c inc) (reduced x)) [1 2 3]) (deref c)) (fn? (eval +))]" :portability :common} - {:suite "contracts / misc" :label "intern demands an existing ns; counted? excludes strings; seqable? includes arrays" :expected "[:t false true]" :actual "[(try (intern (quote no-such-ns-xyz) (quote v) 1) (catch Throwable _ :t)) (counted? \"s\") (seqable? (object-array 2))]" :portability :jvm} - {:suite "contracts / misc" :label "nth of nil honors notFound; a nil index throws; the starred specials are special" :expected "[:default :npe [true true true true true]]" :actual "[(nth nil 5 :default) (try (nth [1] nil) (catch NullPointerException _ :npe)) [(special-symbol? (quote case*)) (special-symbol? (quote deftype*)) (special-symbol? (quote letfn*)) (special-symbol? (quote reify*)) (special-symbol? (quote &))]]" :portability :common} - {:suite "contracts / misc" :label "rand-nth of nil is nil; of a set throws" :expected "[nil :t]" :actual "[(rand-nth nil) (try (rand-nth #{1 2}) (catch Throwable _ :t))]" :portability :common} -] diff --git a/test/chez/cts-app/deps.edn b/test/chez/cts-app/deps.edn deleted file mode 100644 index ed313cc..0000000 --- a/test/chez/cts-app/deps.edn +++ /dev/null @@ -1,2 +0,0 @@ -{:paths ["src" "../../../vendor/clojure-test-suite/test"] - :aliases {:cts {:main-opts ["-m" "cts-run"]}}} diff --git a/test/chez/cts-app/src/cts_run.clj b/test/chez/cts-app/src/cts_run.clj deleted file mode 100644 index d1360e0..0000000 --- a/test/chez/cts-app/src/cts_run.clj +++ /dev/null @@ -1,18 +0,0 @@ -(ns cts-run - "Runner for the vendored jank-lang/clojure-test-suite (vendor/clojure-test-suite): - requires each test namespace given on the command line and runs its clojure.test - tests, printing one machine-readable result line per namespace. Driven per-process - by host/chez/cts.sh so a hang or crash in one namespace can't take out the run." - (:require [clojure.test :as t])) - -(defn -main [& nses] - (doseq [n nses] - (let [ns-sym (symbol n)] - (try - (require ns-sym) - (let [r (t/run-tests ns-sym)] - (println "CTS-RESULT" n (:pass r 0) (:fail r 0) (:error r 0))) - (catch Throwable e - (println "CTS-RESULT" n 0 0 1 - (str "LOAD: " (.getName (class e)) ": " (.getMessage e))))))) - (System/exit 0)) diff --git a/test/chez/cts-known-failures.txt b/test/chez/cts-known-failures.txt deleted file mode 100644 index 52c66f3..0000000 --- a/test/chez/cts-known-failures.txt +++ /dev/null @@ -1,32 +0,0 @@ -# clojure-test-suite known failures: -# The gate fails on any per-namespace change, worse OR better; regenerate -# with: JOLT_CTS_WRITE_BASELINE=1 host/chez/cts.sh -clojure.core-test.abs 1 0 -clojure.core-test.add-watch 0 1 -clojure.core-test.bigint 6 0 -clojure.core-test.bit-set 1 0 -clojure.core-test.dec 1 0 -clojure.core-test.double-qmark 3 0 -clojure.core-test.eq 2 0 -clojure.core-test.float 1 0 -clojure.core-test.inc 1 0 -clojure.core-test.int-qmark 3 0 -clojure.core-test.lazy-seq 1 2 -clojure.core-test.minus 2 0 -clojure.core-test.mod 18 0 -clojure.core-test.neg-int-qmark 1 0 -clojure.core-test.not-eq 3 0 -clojure.core-test.num 2 0 -clojure.core-test.parse-uuid 3 0 -clojure.core-test.peek 1 0 -clojure.core-test.plus 11 0 -clojure.core-test.plus-squote 11 0 -clojure.core-test.pos-int-qmark 1 0 -clojure.core-test.quot 25 0 -clojure.core-test.realized-qmark 1 0 -clojure.core-test.rem 16 0 -clojure.core-test.remove-watch 0 1 -clojure.core-test.star 13 0 -clojure.core-test.star-squote 13 0 -clojure.core-test.transient 4 0 -clojure.core-test.vec 1 0 diff --git a/test/chez/datareader-app/deps.edn b/test/chez/datareader-app/deps.edn deleted file mode 100644 index ccd9a31..0000000 --- a/test/chez/datareader-app/deps.edn +++ /dev/null @@ -1 +0,0 @@ -{:paths ["src"]} diff --git a/test/chez/datareader-app/src/data_readers.clj b/test/chez/datareader-app/src/data_readers.clj deleted file mode 100644 index dec0d19..0000000 --- a/test/chez/datareader-app/src/data_readers.clj +++ /dev/null @@ -1 +0,0 @@ -{code drtest.reader/code-reader} diff --git a/test/chez/datareader-app/src/drtest/main.clj b/test/chez/datareader-app/src/drtest/main.clj deleted file mode 100644 index 63ce7ed..0000000 --- a/test/chez/datareader-app/src/drtest/main.clj +++ /dev/null @@ -1,4 +0,0 @@ -(ns drtest.main - (:require drtest.reader)) -(defn -main [& _] - (println #code [:ignored])) diff --git a/test/chez/datareader-app/src/drtest/reader.clj b/test/chez/datareader-app/src/drtest/reader.clj deleted file mode 100644 index 43b7dd6..0000000 --- a/test/chez/datareader-app/src/drtest/reader.clj +++ /dev/null @@ -1,2 +0,0 @@ -(ns drtest.reader) -(defn code-reader [_form] (list '+ 40 2)) diff --git a/test/chez/directlink-test.ss b/test/chez/directlink-test.ss deleted file mode 100644 index 9bd3104..0000000 --- a/test/chez/directlink-test.ss +++ /dev/null @@ -1,101 +0,0 @@ -;; Direct-linking emission (jolt build, closed world). With direct-link on, a -;; top-level app def emits a Scheme binding jv$$ aliased to its var cell, -;; and an app->app call/value-ref binds to it directly instead of going through -;; (jolt-invoke (var-deref ...)). ^:dynamic/^:redef defs and nested defs opt out. -;; Off direct-link mode the emission is byte-identical to plain `emit`. Run: -;; chez --script test/chez/directlink-test.ss - -(import (chezscheme)) -(load "host/chez/rt.ss") -(set-chez-ns! "clojure.core") -(load "host/chez/seed/prelude.ss") -(load "host/chez/post-prelude.ss") -(set-chez-ns! "user") -(load "host/chez/host-contract.ss") -(load "host/chez/seed/image.ss") -(load "host/chez/compile-eval.ss") -(load "host/chez/emit-image.ss") - -(define total 0) (define fails 0) -(define (ok name pred) (set! total (+ total 1)) (unless pred (set! fails (+ fails 1)) (printf "FAIL: ~a\n" name))) - -(define set-direct-link! (var-deref "jolt.backend-scheme" "set-direct-link!")) -(define direct-link-reset! (var-deref "jolt.backend-scheme" "direct-link-reset!")) - -(define (contains? s sub) - (let ((ns (string-length s)) (nsub (string-length sub))) - (let loop ((i 0)) - (cond ((> (+ i nsub) ns) #f) - ((string=? (substring s i (+ i nsub)) sub) #t) - (else (loop (+ i 1))))))) - -;; Analyze+emit one form (string) in a namespace through the real build entry -;; (ei-compile-form -> emit-top-form), no optimization passes. -(define (emit-form ns-name str) - (let-values (((f j) (rdr-read-form str 0 (string-length str)))) - (ei-compile-form (make-analyze-ctx ns-name) f #f))) - -;; Register var cells so resolve-global classifies references as :var (the build -;; loads the namespaces before re-emitting; here we eval the defs with direct-link -;; off first). Use fn* so no macro expansion is involved. -(set-direct-link! #f) -(jolt-compile-eval "(def a (fn* ([] 1)))" "app") -(jolt-compile-eval "(def b (fn* ([] (a))))" "app") -(jolt-compile-eval "(def hof (fn* ([] a)))" "app") -(jolt-compile-eval "(def ^:dynamic d 5)" "app") -(jolt-compile-eval "(def usesd (fn* ([] (d))))" "app") -(jolt-compile-eval "(def cfg {:a 1 :b 2})" "app") -(jolt-compile-eval "(def usecfg (fn* ([] (cfg :a))))" "app") - -;; --- direct-link OFF: every reference stays indirect (var-deref) --- -(let ((eb (emit-form "app" "(def b (fn* ([] (a))))"))) - (ok "off: call to a routes through jolt-invoke + var-deref" - (and (contains? eb "(jolt-invoke") (contains? eb "(var-deref \"app\" \"a\")"))) - (ok "off: no jv$ direct call" (not (contains? eb "(jv$app$a)"))) - (ok "off: def emits plain def-var! (no jv$ binding)" - (and (contains? (emit-form "app" "(def a (fn* ([] 1)))") "(def-var! \"app\" \"a\"") - (not (contains? (emit-form "app" "(def a (fn* ([] 1)))") "(define jv$app$a"))))) - -;; --- direct-link ON --- -(set-direct-link! #t) -(direct-link-reset!) - -(let ((ea (emit-form "app" "(def a (fn* ([] 1)))"))) ; registers app/a in the set - (ok "on: a's def emits a jv$ binding aliased to its var cell" - (and (contains? ea "(begin (define jv$app$a ") - (contains? ea "(def-var! \"app\" \"a\" jv$app$a)")))) - -(let ((eb (emit-form "app" "(def b (fn* ([] (a))))"))) - (ok "on: b's call to a is a direct (jv$app$a) call" (contains? eb "(jv$app$a)")) - (ok "on: b's call to a is NOT var-deref'd" (not (contains? eb "(var-deref \"app\" \"a\")"))) - (ok "on: b's call to a is NOT jolt-invoke'd" (not (contains? eb "(jolt-invoke")))) - -(let ((eh (emit-form "app" "(def hof (fn* ([] a)))"))) - (ok "on: a used as a value references the binding directly" (contains? eh " jv$app$a)")) - (ok "on: value-ref to a is NOT var-deref'd" (not (contains? eh "(var-deref \"app\" \"a\")")))) - -;; A map-valued (non-fn) def is invokable in Clojure but is NOT a Scheme procedure; -;; a direct-link call to it must route through jolt-invoke, never raw-apply the -;; binding (which crashed with "attempt to apply non-procedure" before the fix). -(let ((ec (emit-form "app" "(def cfg {:a 1 :b 2})"))) ; registers app/cfg (non-fn) in the set - (ok "on: a non-fn def still gets a jv$ binding" (contains? ec "(define jv$app$cfg "))) -(let ((eu (emit-form "app" "(def usecfg (fn* ([] (cfg :a))))"))) - (ok "on: call to a map-valued def routes through jolt-invoke" (contains? eu "(jolt-invoke")) - (ok "on: call to a map-valued def still uses the direct binding" (contains? eu "jv$app$cfg")) - (ok "on: a map-valued def is NOT raw-applied as a procedure" (not (contains? eu "(jv$app$cfg")))) - -;; ^:dynamic opts out: no jv$ binding, callers stay indirect. -(let ((ed (emit-form "app" "(def ^:dynamic d 5)"))) - (ok "on: ^:dynamic def gets no jv$ binding" (not (contains? ed "(define jv$app$d")))) -(let ((eu (emit-form "app" "(def usesd (fn* ([] (d))))"))) - (ok "on: call to a ^:dynamic var stays indirect" (contains? eu "(var-deref \"app\" \"d\")")) - (ok "on: ^:dynamic var not direct-linked" (not (contains? eu "(jv$app$d)")))) - -;; A var only defined LATER in emission order is not yet in the set -> indirect. -(direct-link-reset!) -(let ((efwd (emit-form "app" "(def caller (fn* ([] (a))))"))) ; a not (re)emitted since reset - (ok "on: forward/undefined ref stays indirect" (contains? efwd "(var-deref \"app\" \"a\")"))) - -(set-direct-link! #f) -(printf "~a/~a passed~n" (- total fails) total) -(exit (if (zero? fails) 0 1)) diff --git a/test/chez/ffi-binding-test.ss b/test/chez/ffi-binding-test.ss deleted file mode 100644 index 0454f90..0000000 --- a/test/chez/ffi-binding-test.ss +++ /dev/null @@ -1,89 +0,0 @@ -;; jolt.ffi regression: a compile-time-typed foreign binding lowers to a real -;; Chez foreign-procedure and calls native code. Run: -;; chez --script test/chez/ffi-binding-test.ss -;; Binds a few libc functions (process symbols, always present) through the -;; jolt.ffi/__cfn special form + the host memory primitives — the same path a -;; library uses to bind its native deps. - -(import (chezscheme)) -(load "host/chez/rt.ss") -(set-chez-ns! "clojure.core") -(load "host/chez/seed/prelude.ss") -(load "host/chez/post-prelude.ss") -(set-chez-ns! "user") -(load "host/chez/host-contract.ss") -(load "host/chez/seed/image.ss") -(load "host/chez/compile-eval.ss") -(load "host/chez/java/ffi.ss") - -(define total 0) (define fails 0) -(define (ok name pred) (set! total (+ total 1)) (unless pred (set! fails (+ fails 1)) (printf "FAIL: ~a\n" name))) -;; eval one form (string) in `user`, like the loader does form-by-form, so a def -;; is visible to a later form. -(define (ev s) (jolt-compile-eval s "user")) - -;; load libc (process symbols) and bind typed foreign functions -(ev "(jolt.ffi/load-library)") -(ev "(def c-strlen (jolt.ffi/__cfn \"strlen\" [:string] :size_t))") -(ev "(def c-abs (jolt.ffi/__cfn \"abs\" [:int] :int))") - -(ok "foreign-procedure built for strlen" (procedure? (var-deref "user" "c-strlen"))) -(ok "typed call: strlen(\"hello\") = 5" (= 5 (jnum->exact (ev "(c-strlen \"hello\")")))) -(ok "typed call: abs(-7) = 7" (= 7 (jnum->exact (ev "(c-abs -7)")))) - -;; memory: alloc / write / read roundtrip through the host primitives -(ok "mem int roundtrip" - (= 4242 (jnum->exact - (ev "(let [p (jolt.ffi/alloc (jolt.ffi/sizeof :int))] - (jolt.ffi/write p :int 0 4242) - (let [v (jolt.ffi/read p :int)] (jolt.ffi/free p) v))")))) -(ok "sizeof :pointer is a word" (let ((n (jnum->exact (ev "(jolt.ffi/sizeof :pointer)")))) (or (= n 8) (= n 4)))) - -;; byte-array buffer I/O: write a byte-array into foreign memory and read it back -;; byte-exact (high bytes preserved, no UTF-8 mangling). -(ok "byte-array roundtrip (binary-faithful)" - (jolt-truthy? - (ev "(let [src (byte-array [0 65 200 255 10]) - p (jolt.ffi/alloc 5)] - (jolt.ffi/write-array p src) - (let [back (jolt.ffi/read-array p 5)] - (jolt.ffi/free p) - (and (= 5 (alength back)) - (= 0 (aget back 0)) (= 65 (aget back 1)) - (= 200 (aget back 2)) (= 255 (aget back 3)) (= 10 (aget back 4)))))"))) - -;; a :blocking foreign call is collect-safe: a thread parked in it must not pin -;; the stop-the-world collector. (collect) here would throw "cannot collect when -;; multiple threads are active" if usleep weren't emitted __collect_safe. -(ev "(def c-usleep (jolt.ffi/__cfn \"usleep\" [:uint] :int :blocking))") -(let ((usleep (var-deref "user" "c-usleep"))) - (fork-thread (lambda () (usleep 2000000))) ; ~2s in a blocking call - (let loop ((i 0)) (when (fx a b) 1 :else 0))) - [:pointer :pointer] :int))") -(ok "foreign-callable returns a pointer" - (let ((p (jnum->exact (var-deref "user" "cmp")))) (and (integer? p) (> p 0)))) -(ev "(def c-qsort (jolt.ffi/__cfn \"qsort\" [:pointer :size_t :size_t :pointer] :void))") -(ok "C calls back into jolt: qsort with a jolt comparator" - (jolt-truthy? - (ev "(let [n 5 w (jolt.ffi/sizeof :int) p (jolt.ffi/alloc (* n w))] - (doseq [[i v] (map vector (range n) [3 1 4 1 5])] - (jolt.ffi/write p :int (* i w) v)) - (c-qsort p n w cmp) - (let [out (mapv (fn [i] (jolt.ffi/read p :int (* i w))) (range n))] - (jolt.ffi/free p) - (= out [1 1 3 4 5])))"))) -;; free-callable unlocks + drops the code object, returning nil. -(ok "free-callable releases the callback" - (jolt-nil? (ev "(jolt.ffi/free-callable cmp)"))) - -(printf "~a/~a passed~n" (- total fails) total) -(exit (if (zero? fails) 0 1)) diff --git a/test/chez/inline-test.ss b/test/chez/inline-test.ss deleted file mode 100644 index a2873a9..0000000 --- a/test/chez/inline-test.ss +++ /dev/null @@ -1,67 +0,0 @@ -;; IR inlining (jolt.passes.inline), enabled under optimization. A small -;; single-arity defn is stashed and spliced at its call sites, removing the call. -;; A ^double/^long fn's param-entry and return coercions travel with the splice -;; (via :coerce nodes) so an inlined call matches the called one — incl. coercing a -;; non-double arg — and the body's fl*/fx* fast path still fires. Run: -;; chez --script test/chez/inline-test.ss - -(import (chezscheme)) -(load "host/chez/rt.ss") -(set-chez-ns! "clojure.core") -(load "host/chez/seed/prelude.ss") -(load "host/chez/post-prelude.ss") -(set-chez-ns! "user") -(load "host/chez/host-contract.ss") -(load "host/chez/seed/image.ss") -(load "host/chez/compile-eval.ss") - -(define total 0) (define fails 0) -(define (ok name pred) (set! total (+ total 1)) (unless pred (set! fails (+ fails 1)) (printf "FAIL: ~a\n" name))) -(define (has? s sub) - (let ((ns (string-length s)) (nsub (string-length sub))) - (let loop ((i 0)) - (cond ((> (+ i nsub) ns) #f) - ((string=? (substring s i (+ i nsub)) sub) #t) - (else (loop (+ i 1))))))) -(define (emitf ns str) ; analyze + run-passes (optimize on) + emit - (let-values (((f j) (rdr-read-form str 0 (string-length str)))) - (let ((ctx (make-analyze-ctx ns))) - (jolt-ce-emit (jolt-ce-run-passes (jolt-ce-analyze ctx f) ctx))))) -(define (ev s) (jolt-compile-eval s "u")) - -;; inlining is a closed-world optimization — only under optimize. -(set-optimize! #t) - -;; a small plain fn is spliced; the call to it disappears. -(ev "(def add1 (fn* ([x] (+ x 1))))") -(let ((e (emitf "u" "(fn* ([y] (add1 y)))"))) - (ok "plain fn is inlined (call to add1 gone)" (not (has? e "add1"))) - (ok "inlined body present (jolt-n+ ... 1)" (has? e "(jolt-n+"))) -(ok "inlined plain fn runtime: (add1 41) = 42" (= 42 (jnum->exact (ev "((fn* ([y] (add1 y))) 41)")))) - -;; a ^double fn: body fl-ops fire after inlining, and the call is gone. -(ev "(def ^double dwork (fn* ([^double a ^double b] (+ (* a a) (* b b)))))") -(let ((e (emitf "u" "(fn* ([] (dwork 3.0 4.0)))"))) - (ok "inlined ^double fn body uses fl*" (has? e "(fl*")) - (ok "inlined ^double fn call to dwork is gone" (not (has? e "dwork")))) -(ok "inlined ^double call: 3^2+4^2 = 25" (= 25 (jnum->exact (ev "((fn* ([] (dwork 3.0 4.0))))")))) -;; coercion travels with the splice: int args become doubles, so the result is a -;; flonum 25.0 — matching the called fn, not an exact 25. -(ok "inlined ^double with int args still returns a flonum" (flonum? (ev "((fn* ([] (dwork 3 4))))"))) - -;; a ^long fn inlines with fixnum coercion + fx ops. -(ev "(def ^long lsum (fn* ([^long a ^long b] (+ a b))))") -(let ((e (emitf "u" "(fn* ([] (lsum 3 4)))"))) - (ok "inlined ^long fn body uses fx+" (has? e "(fx+"))) -(ok "inlined ^long call: 3+4 = 7 (fixnum)" (let ((r (ev "((fn* ([] (lsum 3 4))))"))) (and (fixnum? r) (= r 7)))) - -;; an accumulator over an inlined ^double call: the whole loop body fuses to fl-ops. -(ev "(def ^double sq (fn* ([^double x] (* x x))))") -(let ((e (emitf "u" "(fn* ([] (loop [acc 0.0 i 0] (if (< i 3) (recur (+ acc (sq 2.0)) (inc i)) acc))))"))) - (ok "accumulator over inlined ^double call lowers to fl+" (has? e "(fl+")) - (ok "the sq call is inlined away" (not (has? e "sq")))) -(ok "accumulator over inlined ^double call: 3*4.0 = 12" (= 12 (jnum->exact (ev "((fn* ([] (loop [acc 0.0 i 0] (if (< i 3) (recur (+ acc (sq 2.0)) (inc i)) acc)))))")))) - -(set-optimize! #f) -(printf "~a/~a passed~n" (- total fails) total) -(exit (if (zero? fails) 0 1)) diff --git a/test/chez/numeric-test.ss b/test/chez/numeric-test.ss deleted file mode 100644 index 39aee0f..0000000 --- a/test/chez/numeric-test.ss +++ /dev/null @@ -1,146 +0,0 @@ -;; Hint-directed fast arithmetic (jolt.passes.numeric). A ^double/^long param hint -;; (or a float literal) drives Chez fl*/fx* emission instead of generic arithmetic; -;; un-hinted integer code stays generic (arbitrary-precision preserved). The pass -;; runs in run-passes with optimization OFF, so this is the open-build path. Run: -;; chez --script test/chez/numeric-test.ss - -(import (chezscheme)) -(load "host/chez/rt.ss") -(set-chez-ns! "clojure.core") -(load "host/chez/seed/prelude.ss") -(load "host/chez/post-prelude.ss") -(set-chez-ns! "user") -(load "host/chez/host-contract.ss") -(load "host/chez/seed/image.ss") -(load "host/chez/compile-eval.ss") - -(define total 0) (define fails 0) -(define (ok name pred) (set! total (+ total 1)) (unless pred (set! fails (+ fails 1)) (printf "FAIL: ~a\n" name))) - -(define (has? s sub) - (let ((ns (string-length s)) (nsub (string-length sub))) - (let loop ((i 0)) - (cond ((> (+ i nsub) ns) #f) - ((string=? (substring s i (+ i nsub)) sub) #t) - (else (loop (+ i 1))))))) - -;; analyze + run-passes (optimization OFF — the always-on numeric pass still runs) -;; + emit one form to a Scheme string. -(define (emitf ns str) - (let-values (((f j) (rdr-read-form str 0 (string-length str)))) - (let ((ctx (make-analyze-ctx ns))) - (jolt-ce-emit (jolt-ce-run-passes (jolt-ce-analyze ctx f) ctx))))) -(define (ev s) (jolt-compile-eval s "u")) - -;; --- emission: ^double -> fl-ops, ^long -> fx-ops --- -(let ((e (emitf "u" "(fn* ([^double a ^double b] (+ (* a a) (* b b))))"))) - (ok "double + lowers to fl+" (has? e "(fl+")) - (ok "double * lowers to fl*" (has? e "(fl*")) - (ok "double arith is NOT generic +" (not (has? e "(jolt-invoke")))) - -(ok "long + lowers to fx+" (has? (emitf "u" "(fn* ([^long a ^long b] (+ a b)))") "(fx+")) -(ok "long * lowers to fx*" (has? (emitf "u" "(fn* ([^long a ^long b] (* a b)))") "(fx*")) -(ok "double < lowers to flexact (ev "((fn* ([] (loop [i 0] (if (< i 1000) (recur (inc i)) i)))))")))) -;; a recur-less loop is a let: its int-literal binding stays generic (no fx), so -;; arbitrary precision is preserved (matches (let [i 5] ...)). -(let ((e (emitf "u" "(fn* ([] (loop [i 5] (+ i 9223372036854775807))))"))) - (ok "recur-less loop int binding is NOT fx-typed" (not (has? e "(fx+")))) -(ok "recur-less loop with a big add stays exact (bignum)" - (jolt-truthy? (ev "(< 9223372036854775807 ((fn* ([] (loop [i 5] (+ i 9223372036854775807))))))"))) - -;; a ^long-seeded loop accumulator IS fx-typed (the hint is a fixnum promise, and -;; the value flows from a coerced ^long param). -(let ((e (emitf "u" "(fn* ([^long start] (loop [acc start] (if (< acc 100) (recur (inc acc)) acc))))"))) - (ok "long-seeded loop accumulator lowers (inc acc) to jolt-l-inc" (has? e "(jolt-l-inc")) - (ok "long-seeded loop comparison lowers to jolt-l<" (has? e "(jolt-l<"))) - -;; --- soundness: un-hinted / integer-literal code stays generic --- -(let ((e (emitf "u" "(fn* ([a b] (+ a b)))"))) - (ok "un-hinted + stays generic (no fl/fx)" (and (not (has? e "(fl+")) (not (has? e "(fx+"))))) -(let ((e (emitf "u" "(+ 1 2)"))) - (ok "bare integer literals stay generic (arbitrary precision)" (not (has? e "(fx+")))) -;; a constant float op like (+ 1.0 2.0) is const-folded to 3.0 (no op at all); a -;; float-literal-bound local is double-typed and its body op isn't foldable (a -;; local operand), so numeric specializes it. -(ok "float-literal-bound local specializes to fl+" - (has? (emitf "u" "(fn* ([] (let [a 2.0] (+ a 3.0))))") "(fl+")) -;; (/ ^long ^long) is a Ratio in Clojure, not a long -> must NOT lower to a fixnum op -(let ((e (emitf "u" "(fn* ([^long a ^long b] (/ a b)))"))) - (ok "long division is NOT specialized (stays generic /)" (not (has? e "(fx")))) - -;; --- runtime values match the generic result --- -(ok "double dot: 3^2+4^2 = 25" (= 25 (jnum->exact (ev "((fn* ([^double a ^double b] (+ (* a a) (* b b)))) 3.0 4.0)")))) -(ok "long sum: 2+3 = 5" (= 5 (jnum->exact (ev "((fn* ([^long a ^long b] (+ a b))) 2 3)")))) -(ok "double compare true" (jolt-truthy? (ev "((fn* ([^double x] (< x 5.0))) 3.0)"))) -(ok "double unary negate" (= -5 (jnum->exact (ev "((fn* ([^double x] (- x))) 5.0)")))) -(ok "long unary negate" (= -5 (jnum->exact (ev "((fn* ([^long a] (- a))) 5)")))) -(ok "long quot 7/2 = 3" (= 3 (jnum->exact (ev "((fn* ([^long a ^long b] (quot a b))) 7 2)")))) -(ok "double + int literal = 4.5" (= 9 (jnum->exact (ev "((fn* ([^double x] (* (+ x 1) 2))) 3.5)")))) -(ok "loop double accumulator: 10*1.5 = 15" - (= 15 (jnum->exact (ev "((fn* ([] (loop [acc 0.0 i 0] (if (< i 10) (recur (+ acc 1.5) (inc i)) acc)))))")))) -(ok "loop integer factorial stays exact (bignum preserved)" - (jolt-truthy? (ev "(< 1000000000000000000000 ((fn* ([] (loop [acc 1 i 1] (if (< i 25) (recur (* acc i) (inc i)) acc)))) ))"))) -(ok "long-seeded loop accumulator counts to 100" - (= 100 (jnum->exact (ev "((fn* ([^long start] (loop [acc start] (if (< acc 100) (recur (inc acc)) acc)))) 0)")))) - -;; --- numeric return hints (round 3) --- -;; a ^double / ^long return hint coerces the fn's value on the way out (the contract). -(jolt-compile-eval "(def ^double dsq (fn* ([x] (* x x))))" "u") -(ok "^double return coerces value to a flonum" (flonum? (ev "(dsq 3)"))) -(jolt-compile-eval "(def ^long ldbl (fn* ([x] (+ x x))))" "u") -(ok "^long return coerces value to a fixnum" (let ((r (ev "(ldbl 5)"))) (and (fixnum? r) (= r 10)))) -;; the defn macro must carry the name's return hint through to the def. -(jolt-compile-eval "(defn ^double dnsq [x] (* x x))" "u") -(ok "defn ^double return coerces to flonum" (flonum? (ev "(dnsq 4)"))) - -;; caller propagation: a call to a ^double-returning fn types an accumulator over it. -(let ((e (emitf "u" "(fn* ([] (loop [acc 0.0 i 0] (if (< i 3) (recur (+ acc (dsq 2.0)) (inc i)) acc))))"))) - (ok "accumulator over a ^double-returning call lowers to fl+" (has? e "(fl+"))) -(ok "accumulator over ^double call runtime: 3 * (2*2) = 12.0" - (= 12 (jnum->exact (ev "((fn* ([] (loop [acc 0.0 i 0] (if (< i 3) (recur (+ acc (dsq 2.0)) (inc i)) acc)))))")))) -;; a ^double call result also specializes a straight-line op -(let ((e (emitf "u" "(fn* ([^double y] (+ y (dsq 2.0))))"))) - (ok "straight-line op over ^double call lowers to fl+" (has? e "(fl+"))) - -(printf "~a/~a passed~n" (- total fails) total) -(exit (if (zero? fails) 0 1)) diff --git a/test/chez/repl-reader-test.clj b/test/chez/repl-reader-test.clj deleted file mode 100644 index 16a41e3..0000000 --- a/test/chez/repl-reader-test.clj +++ /dev/null @@ -1,27 +0,0 @@ -;; Self-checking regression for the REPL's read-until-complete predicate -;; (jolt.main/repl-form-complete?), which decides whether a line buffer is a whole -;; form or the REPL should keep reading continuation lines. Runs via `bin/joltc run` -;; (jolt.main is loaded, so the private var resolves); prints a sentinel the smoke -;; gate greps. The regex cases are the ones that regressed: a #"..." literal opens a -;; regex whose body — parens, quotes and all — must not be miscounted as delimiters. -(require 'jolt.main) - -(def complete? jolt.main/repl-form-complete?) - -;; [input expected-complete?] -(def cases - [["(+ 1 2)" true] ; balanced - ["(+ 1" false] ; open paren -> keep reading - ["(defn g [] (foo (bar" false] ; deeply unbalanced - ["[1 2 {:a 3}]" true] ; mixed bracket types balance - ["(str \")\")" true] ; a close-paren inside a string doesn't count - ["\\(" true] ; a paren char literal doesn't count - ["(+ 1 2) ; ) ) trailing" true] ; parens in a line comment don't count - ["(re-find #\"(a)(b)\" \"ab\")" true] ; groups inside a regex must not count as depth - ["#\"[0-9]+\"" true] ; a bare regex literal is a complete form - ["#\"a(b" false]]) ; an unterminated regex is incomplete - -(let [bad (remove (fn [[in exp]] (= exp (boolean (complete? in)))) cases)] - (println (if (empty? bad) - "REPL-READER OK" - (str "REPL-READER FAIL " (pr-str (map first bad)))))) diff --git a/test/chez/transient-test.ss b/test/chez/transient-test.ss deleted file mode 100644 index f60bd9e..0000000 --- a/test/chez/transient-test.ss +++ /dev/null @@ -1,49 +0,0 @@ -;; Transient regression: mutable backing + snapshot-on-persist. Run: -;; chez --script test/chez/transient-test.ss -;; Semantics are covered broadly by the corpus; this pins the invariants the -;; mutable implementation must keep AND that large builds stay linear (a -;; copy-on-write regression would make the 200k builds quadratic and time the -;; gate out). - -(import (chezscheme)) -(load "host/chez/rt.ss") -(set-chez-ns! "clojure.core") -(load "host/chez/seed/prelude.ss") -(load "host/chez/post-prelude.ss") -(set-chez-ns! "user") -(load "host/chez/host-contract.ss") -(load "host/chez/seed/image.ss") -(load "host/chez/compile-eval.ss") - -(define total 0) (define fails 0) -(define (ok name pred) (set! total (+ total 1)) (unless pred (set! fails (+ fails 1)) (printf "FAIL: ~a\n" name))) -(define (ev s) (jolt-final-str (jolt-compile-eval (string-append "(do " s ")") "user"))) -(define (is name s expect) (ok (string-append name " => " expect) (string=? (ev s) expect))) - -;; --- mutation is in place; persistent! snapshots back ----------------------- -(is "vector build" "(persistent! (reduce conj! (transient []) (range 5)))" "[0 1 2 3 4]") -(is "map build" "(= {0 0 1 1 2 2} (persistent! (reduce (fn [t i] (assoc! t i i)) (transient {}) (range 3))))" "true") -(is "set build" "(count (persistent! (reduce conj! (transient #{}) [1 2 2 3])))" "3") -(is "pop!" "(persistent! (pop! (conj! (transient [1 2]) 3)))" "[1 2]") -(is "dissoc!" "(persistent! (dissoc! (assoc! (transient {}) :a 1 :b 2) :a))" "{:b 2}") -(is "disj!" "(persistent! (disj! (conj! (transient #{}) :x :y) :x))" "#{:y}") - -;; --- a transient never mutates its source ----------------------------------- -(is "source map unchanged" "(let [m {:a 1} _ (persistent! (assoc! (transient m) :b 2))] (= m {:a 1}))" "true") -(is "source vector unchanged" "(let [v [1 2] _ (persistent! (conj! (transient v) 3))] (= v [1 2]))" "true") - -;; --- edges the implementation must keep ------------------------------------- -(is "nil key" "(get (persistent! (assoc! (transient {}) nil :v)) nil)" ":v") -(is "collection key" "(get (persistent! (assoc! (transient {}) [1 2] :v)) [1 2])" ":v") -(is "dangling key pads" "(= {:a 1 :b nil} (persistent! (assoc! (transient {}) :a 1 :b)))" "true") -(is "vector? is false" "(vector? (transient []))" "false") -(is "transient sorted (cow)" "(persistent! (assoc! (transient (sorted-map :b 2)) :a 1))" "{:a 1, :b 2}") -(ok "lone key throws" (guard (e (#t #t)) (ev "(persistent! (assoc! (transient {}) :a))") #f)) -(ok "use after persistent!" (guard (e (#t #t)) (ev "(let [t (transient [])] (persistent! t) (conj! t 1))") #f)) - -;; --- linear, not quadratic: 200k builds finish near-instantly --------------- -(is "big vector build" "(count (persistent! (reduce conj! (transient []) (range 200000))))" "200000") -(is "big map build" "(count (persistent! (reduce (fn [t i] (assoc! t i i)) (transient {}) (range 200000))))" "200000") - -(printf "~a/~a passed~n" (- total fails) total) -(exit (if (zero? fails) 0 1)) diff --git a/test/chez/unit.edn b/test/chez/unit.edn deleted file mode 100644 index 12ab8f6..0000000 --- a/test/chez/unit.edn +++ /dev/null @@ -1,601 +0,0 @@ -[ - {:suite "special-form precedence" :expr "(do (ns sftest (:refer-clojure :exclude [def])) (defmacro def [n v] :shadowed) (clojure.core/defn ff [] 99) (ff))" :expected "99"} - {:suite "special-form precedence" :expr "(do (set! (. clojure.lang.RT checkSpecAsserts) true) clojure.lang.RT/checkSpecAsserts)" :expected "true"} - {:suite "atomwatch" :expr "(let [a (atom 0) seen (atom 0)] (add-watch a :k (fn [k r o n] (reset! seen 1))) (reset! a 5) @seen)" :expected "1"} - {:suite "atomwatch" :expr "(let [a (atom 0) seen (atom 0)] (add-watch a :k (fn [k r o n] (swap! seen inc))) (remove-watch a :k) (reset! a 5) @seen)" :expected "0"} - {:suite "atomwatch" :expr "(let [a (atom 0) log (atom [])] (add-watch a :k (fn [k r o n] (swap! log conj [o n]))) (reset! a 1) (reset! a 2) @log)" :expected "[[0 1] [1 2]]"} - {:suite "atomwatch" :expr "(let [a (atom 0)] (set-validator! a number?) (reset! a 5) @a)" :expected "5"} - {:suite "atomwatch" :expr "(let [a (atom 5)] (set-validator! a pos?) (swap! a inc) @a)" :expected "6"} - {:suite "atomwatch" :expr "(let [a (atom 0)] (set-validator! a number?) (fn? (get-validator a)))" :expected "true"} - {:suite "atomwatch" :expr "(let [a (atom 0)] (nil? (get-validator a)))" :expected "true"} - {:suite "atomwatch" :expr "(let [a (atom 0)] (set-validator! a pos?) (reset! a -1))" :expected :throws} - {:suite "atomwatch" :expr "(let [a (atom 5)] (set-validator! a pos?) (swap! a (fn [_] -1)) @a)" :expected :throws} - {:suite "atomwatch" :expr "(let [a (atom 0) c (atom 0)] (add-watch a :k (fn [k r o n] (swap! c inc))) (swap! a inc) (swap! a inc) @c)" :expected "2"} - {:suite "class" :expr "String" :expected "java.lang.String"} - {:suite "class" :expr "Number" :expected "java.lang.Number"} - {:suite "class" :expr "Keyword" :expected "clojure.lang.Keyword"} - {:suite "class" :expr "File" :expected "java.io.File"} - {:suite "class" :expr "Exception" :expected "java.lang.Exception"} - {:suite "class" :expr "MapEntry" :expected "clojure.lang.MapEntry"} - {:suite "class" :expr "(class 1)" :expected "java.lang.Long"} - {:suite "class" :expr "(class 1.5)" :expected "java.lang.Double"} - {:suite "class" :expr "(class \"s\")" :expected "java.lang.String"} - {:suite "class" :expr "(class :k)" :expected "clojure.lang.Keyword"} - {:suite "class" :expr "(class true)" :expected "java.lang.Boolean"} - {:suite "class" :expr "(class false)" :expected "java.lang.Boolean"} - {:suite "class" :expr "(class nil)" :expected ""} - {:suite "class" :expr "(= String (class \"abc\"))" :expected "true"} - {:suite "class" :expr "(= Number (class 7))" :expected "false"} - {:suite "class" :expr "(= String (class 7))" :expected "false"} - {:suite "class" :expr "(do (defmulti cm (fn [x] (class x))) (defmethod cm String [x] :str) (cm \"a\"))" :expected ":str"} - {:suite "class" :expr "(do (defmulti cn (fn [x] (class x))) (defmethod cn nil [x] :nil) (defmethod cn String [x] :str) (cn nil))" :expected ":nil"} - {:suite "class" :expr "(do (defmulti cn (fn [x] (class x))) (defmethod cn nil [x] :nil) (defmethod cn String [x] :str) (cn \"z\"))" :expected ":str"} - {:suite "dotform" :expr "(. \"HI\" toLowerCase)" :expected "hi"} - {:suite "dotform" :expr "(. \"abc\" length)" :expected "3"} - {:suite "dotform" :expr "(. \"abc\" toUpperCase)" :expected "ABC"} - {:suite "dotform" :expr "(. [1 2 3] count)" :expected "3"} - {:suite "dotform" :expr "(. [10 20 30] nth 1)" :expected "20"} - {:suite "dotform" :expr "(. {:a 1 :b 2} count)" :expected "2"} - {:suite "dotform" :expr "(. {:a 1 :b 2} get :b)" :expected "2"} - {:suite "dotform" :expr "(. {:a 1} containsKey :a)" :expected "true"} - {:suite "dotform" :expr "(. {:count 99} count)" :expected "1"} - {:suite "dotform" :expr "(. {:value 41 :describe (fn [self] (str \"v=\" (:value self)))} describe)" :expected "v=41"} - {:suite "dotform" :expr "(. {:greet (fn [self n] (str \"Hello \" n))} greet \"Alice\")" :expected "Hello Alice"} - {:suite "dotform" :expr "(. {:value 41} value)" :expected "41"} - {:suite "dotform" :expr "(.-value {:value 41})" :expected "41"} - {:suite "dotform" :expr "(.-x {:x 7 :y 9})" :expected "7"} - {:suite "dotform" :expr "(. {:value 41} -value)" :expected "41"} - {:suite "dotform" :expr "(do (defrecord Rf [x]) (.-x (->Rf 7)))" :expected "7"} - {:suite "dotform" :expr "(do (defrecord Rg [a b]) (.-b (->Rg 1 2)))" :expected "2"} - {:suite "dotform" :expr "(do (defprotocol Greet (hi [_])) (defrecord Rh [nm] Greet (hi [_] (str \"hi \" nm))) (. (->Rh \"x\") hi))" :expected "hi x"} - {:suite "dotform" :expr "(try (throw (ex-info \"bad\" {})) (catch Throwable e (.getMessage e)))" :expected "bad"} - {:suite "dotform" :expr "(try (throw (ex-info \"bad\" {:k 1})) (catch Throwable e (.getMessage e)))" :expected "bad"} - {:suite "dotform" :expr "(try (throw \"boom\") (catch Throwable e (.getMessage e)))" :expected "boom"} - {:suite "dotform" :expr "(try (throw (Exception. \"boom\")) (catch Throwable e (.getMessage e)))" :expected "boom"} - {:suite "dotform" :expr "(try (throw (IllegalArgumentException. \"bad\")) (catch Exception e (.getMessage e)))" :expected "bad"} - {:suite "exinfo" :expr "(instance? clojure.lang.ExceptionInfo (ex-info \"x\" {}))" :expected "true"} - {:suite "exinfo" :expr "(instance? clojure.lang.IExceptionInfo (ex-info \"x\" {}))" :expected "true"} - {:suite "exinfo" :expr "(instance? RuntimeException (ex-info \"x\" {}))" :expected "true"} - {:suite "exinfo" :expr "(instance? Throwable (ex-info \"x\" {}))" :expected "true"} - {:suite "exinfo" :expr "(class (ex-info \"x\" {}))" :expected "clojure.lang.ExceptionInfo"} - {:suite "exinfo" :expr "(= clojure.lang.ExceptionInfo (class (ex-info \"x\" {})))" :expected "true"} - {:suite "exinfo" :expr "(class (RuntimeException. \"x\"))" :expected "java.lang.RuntimeException"} - {:suite "exinfo" :expr "(instance? RuntimeException (RuntimeException. \"x\"))" :expected "true"} - {:suite "exinfo" :expr "(instance? Exception (IllegalArgumentException. \"x\"))" :expected "true"} - {:suite "exinfo" :expr "(instance? Throwable (IllegalArgumentException. \"x\"))" :expected "true"} - {:suite "exinfo" :expr "(instance? IllegalArgumentException (RuntimeException. \"x\"))" :expected "false"} - {:suite "exinfo" :expr "(instance? RuntimeException (InterruptedException. \"x\"))" :expected "false"} - {:suite "exinfo" :expr "(.getMessage (RuntimeException. \"boom\"))" :expected "boom"} - {:suite "exinfo" :expr "(ex-message (RuntimeException. \"boom\"))" :expected "boom"} - {:suite "exinfo" :expr "(type (ex-info \"x\" {}))" :expected "clojure.lang.ExceptionInfo"} - {:suite "hostobj" :expr "(.getName (.getClass \"x\"))" :expected "java.lang.String"} - {:suite "hostobj" :expr "(.getClass 5)" :expected "java.lang.Long"} - {:suite "hostobj" :expr "(.getSimpleName (.getClass :k))" :expected "Keyword"} - {:suite "hostobj" :expr "(.toString true)" :expected "true"} - {:suite "hostobj" :expr "(class (ex-info \"x\" {}))" :expected "clojure.lang.ExceptionInfo"} - {:suite "hostobj" :expr "[(instance? Double 1.5) (Double. \"3.5\") (Double/parseDouble \"2.5\")]" :expected "[true 3.5 2.5]"} - {:suite "hostobj" :expr "(instance? java.util.regex.Pattern #\"x\")" :expected "true"} - {:suite "hostobj" :expr "(class #\"x\")" :expected "java.util.regex.Pattern"} - {:suite "hostobj" :expr "[(namespace (symbol \"foo/bar\")) (name (symbol \"foo/bar\"))]" :expected "[foo bar]"} - {:suite "hostobj" :expr "(str (symbol \"a/b/c\"))" :expected "a/b/c"} - {:suite "hostobj" :expr "(do (System/setProperty \"jolt.test.x\" \"z\") (System/getProperty \"jolt.test.x\"))" :expected "z"} - {:suite "hostobj" :expr "(set! *assert* false)" :expected "false"} - {:suite "hostobj" :expr "(binding [*print-readably* false] *print-readably*)" :expected "false"} - {:suite "hostobj" :expr "(do (defprotocol P (m [_])) (extend-protocol P clojure.lang.Fn (m [_] :fn)) (m (fn [x] x)))" :expected ":fn"} - {:suite "hostobj" :expr "(do (defprotocol P (m [_])) (extend-protocol P clojure.lang.APersistentVector (m [_] :vec)) (m [1 2 3]))" :expected ":vec"} - {:suite "hostobj" :expr "(record? (sorted-map 1 2 3 4))" :expected "false"} - {:suite "queue" :expr "(seq (conj clojure.lang.PersistentQueue/EMPTY 1 2 3))" :expected "(1 2 3)"} - {:suite "queue" :expr "(peek (conj clojure.lang.PersistentQueue/EMPTY 1 2 3))" :expected "1"} - {:suite "queue" :expr "(seq (pop (conj clojure.lang.PersistentQueue/EMPTY 1 2 3)))" :expected "(2 3)"} - {:suite "queue" :expr "(count (conj clojure.lang.PersistentQueue/EMPTY 1 2 3))" :expected "3"} - {:suite "queue" :expr "(empty? clojure.lang.PersistentQueue/EMPTY)" :expected "true"} - {:suite "queue" :expr "(instance? clojure.lang.PersistentQueue (conj clojure.lang.PersistentQueue/EMPTY 1))" :expected "true"} - {:suite "queue" :expr "(= [1 2 3] (into clojure.lang.PersistentQueue/EMPTY [1 2 3]))" :expected "true"} - {:suite "queue" :expr "(first (into clojure.lang.PersistentQueue/EMPTY [1 2 3]))" :expected "1"} - {:suite "destructure" :expr "(letfn [(up [s [k & ks]] (cons s ks))] (up 1 [2 3 4]))" :expected "(1 3 4)"} - {:suite "hostctor" :expr "(.getName (java.io.File. \"/tmp/abc.txt\"))" :expected "abc.txt"} - {:suite "hostctor" :expr "(instance? java.io.File (java.io.File. \"/x\"))" :expected "true"} - {:suite "hostctor" :expr "(uuid? (java.util.UUID/randomUUID))" :expected "true"} - {:suite "hostctor" :expr "(instance? java.util.UUID (java.util.UUID/fromString \"12345678-1234-1234-1234-123456789abc\"))" :expected "true"} - {:suite "hostctor" :expr "(let [u (java.net.URI. \"http://h.com:81/p?q=1#f\")] [(.getScheme u) (.getHost u) (.getPort u) (.getPath u) (.getQuery u) (.getFragment u)])" :expected "[http h.com 81 /p q=1 f]"} - {:suite "hostctor" :expr "(nil? (.getHost (java.net.URI. \"/rel/path\")))" :expected "true"} - {:suite "hostctor" :expr "(str (java.net.URI. \"http://x/y\"))" :expected "http://x/y"} - {:suite "hostctor" :expr "(instance? java.net.URI (java.net.URI. \"/x\"))" :expected "true"} - {:suite "hostctor" :expr "(let [a (java.util.ArrayList.)] (.add a 1) (.add a 2) (.add a 3) (.remove a 0) [(.size a) (vec (.toArray a))])" :expected "[2 [2 3]]"} - {:suite "hostctor" :expr "[(.indexOf [:a :b :c] :b) (.indexOf (list :a :b) :b) (.indexOf [:a] :z) (.indexOf (range 0 10) 1)]" :expected "[1 1 -1 1]"} - {:suite "sdf" :expr "(.format (java.text.SimpleDateFormat. \"EEE, dd MMM yyyy HH:mm:ss zzz\") (java.util.Date. 1348401170000))" :expected "Sun, 23 Sep 2012 11:52:50 GMT"} - {:suite "sdf" :expr "(.getTime (.parse (java.text.SimpleDateFormat. \"EEE, dd MMM yyyy HH:mm:ss zzz\") \"Sun, 23 Sep 2012 11:52:50 GMT\"))" :expected "1348401170000"} - {:suite "sdf" :expr "(.getTime (.parse (java.text.SimpleDateFormat. \"EEEE, dd-MMM-yy HH:mm:ss zzz\") \"Sunday, 23-Sep-12 11:52:50 GMT\"))" :expected "1348401170000"} - {:suite "sdf" :expr "(.getTime (.parse (java.text.SimpleDateFormat. \"EEE MMM d HH:mm:ss yyyy\") \"Sun Sep 23 11:52:50 2012\"))" :expected "1348401170000"} - {:suite "sdf" :expr "(let [f (java.text.SimpleDateFormat. \"yyyy-MM-dd\")] (.format f (.parse f \"2023-07-15\")))" :expected "2023-07-15"} - {:suite "reader" :expr "(let [r (-> \"foo bar baz\" java.io.StringReader. java.io.PushbackReader.)] [(read r) (slurp r)])" :expected "[foo bar baz]"} - {:suite "reader" :expr "(let [r (-> \"(+ 1 2) 99\" java.io.StringReader. java.io.PushbackReader.)] [(read r) (read r)])" :expected "[(+ 1 2) 99]"} - {:suite "hostctor" :expr "(String/format \"%d-%s\" 5 \"x\")" :expected "5-x"} - {:suite "hostctor" :expr "[(.format (java.text.NumberFormat/getInstance) 1234567.5) (.format (java.text.NumberFormat/getIntegerInstance) 1234567)]" :expected "[1,234,567.5 1,234,567]"} - {:suite "hostctor" :expr "[(.getProtocol (java.net.URL. \"file:/tmp/x\")) (.getFile (java.net.URL. \"http://h/p\")) (.getProtocol (java.net.URL. \"http://h/p\"))]" :expected "[file http://h/p http]"} - {:suite "hostobj" :expr "(try (throw (ex-info \"x\" {})) (catch Throwable e [(.getNextException e) (vec (.getStackTrace e))]))" :expected "[nil []]"} - {:suite "hostobj" :expr "[(some? (ClassLoader/getSystemClassLoader)) (some? (.getContextClassLoader (Thread/currentThread)))]" :expected "[true true]"} - {:suite "reify" :expr "(do (defprotocol P (pm [_])) (defprotocol Q (qm [_])) (extend-protocol Q java.lang.Object (qm [_] :q-default)) (qm (reify P (pm [_] :p))))" :expected ":q-default"} - {:suite "reify" :expr "(do (defprotocol Q (qa [_]) (qb [_])) (extend-protocol Q java.lang.Object (qa [_] :da) (qb [_] :db)) (def r (reify Q (qa [_] :ra))) [(qa r) (qb r)])" :expected "[:ra :db]"} - {:suite "interrupt" :expr "(jolt.host/run-interruptible (jolt.host/make-interrupt) (fn [] (+ 1 2)))" :expected "3"} - {:suite "interrupt" :expr "(let [t (jolt.host/make-interrupt)] (jolt.host/interrupt! t) (try (jolt.host/run-interruptible t (fn [] (loop [i 0] (recur (inc i))))) :not-interrupted (catch :default e (:jolt/interrupted (ex-data e)))))" :expected "true"} - {:suite "interrupt" :expr "(do (Thread/yield) :ok)" :expected ":ok"} - {:suite "interrupt" :expr "(nil? (Thread/yield))" :expected "true"} - {:suite "interrupt" :expr "(.isInterrupted (Thread/currentThread))" :expected "false"} - {:suite "interrupt" :expr "(let [t (Thread/currentThread)] (.interrupt t) (.isInterrupted t))" :expected "true"} - {:suite "interrupt" :expr "(let [t (Thread/currentThread)] (.interrupt t) [(.isInterrupted t) (.isInterrupted t)])" :expected "[true true]"} - {:suite "interrupt" :expr "(let [t (Thread/currentThread)] (.interrupt t) [(Thread/interrupted) (Thread/interrupted)])" :expected "[true false]"} - {:suite "interrupt" :expr "(do (.interrupt (Thread/currentThread)) (Thread/interrupted) (.isInterrupted (Thread/currentThread)))" :expected "false"} - {:suite "interrupt" :expr "(let [t (atom nil) started (promise) go (promise) f (future (reset! t (Thread/currentThread)) (deliver started true) (deref go) (.isInterrupted (deref t)))] (deref started) (.interrupt (deref t)) (deliver go true) (deref f))" :expected "true"} - {:suite "ns-tl" :expr "(do (in-ns (quote foo.bar)) (str *ns*))" :expected "foo.bar"} - {:suite "ns-tl" :expr "(do (create-ns (quote my.ns)) (binding [*ns* (find-ns (quote my.ns))] (str *ns*)))" :expected "my.ns"} - {:suite "ns-tl" :expr "(do (in-ns (quote app.core)) (def sekret 42) (in-ns (quote user)) (binding [*ns* (find-ns (quote app.core))] (load-string \"sekret\")))" :expected "42"} - {:suite "ns-tl" :expr "(do (create-ns (quote a.x)) (create-ns (quote b.y)) (let [fa (future (in-ns (quote a.x)) (Thread/sleep 80) (str *ns*)) fb (future (in-ns (quote b.y)) (Thread/sleep 80) (str *ns*))] [(deref fa) (deref fb) (str *ns*)]))" :expected "[a.x b.y user]"} - {:suite "dotform" :expr "(.equals \"a\" \"a\")" :expected "true"} - {:suite "dotform" :expr "(.equals \"a\" \"b\")" :expected "false"} - {:suite "dotform" :expr "(. {:value 41 :describe (fn [self] (str \"v=\" (:value self)))} describe)" :expected "v=41"} - {:suite "dynbind" :expr "(do (def ^:dynamic *bx* 10) (binding [*bx* 99] *bx*))" :expected "99"} - {:suite "dynbind" :expr "(do (def ^:dynamic *by* 10) (binding [*by* 99] *by*) *by*)" :expected "10"} - {:suite "dynbind" :expr "(do (def ^:dynamic *bz* 0) (defn rdz [] *bz*) (binding [*bz* 7] (rdz)))" :expected "7"} - {:suite "dynbind" :expr "(do (def ^:dynamic *bv* 1) [(binding [*bv* 2] *bv*) *bv*])" :expected "[2 1]"} - {:suite "dynbind" :expr "(do (def ^:dynamic *bn* 1) (binding [*bn* 2] (binding [*bn* 3] *bn*)))" :expected "3"} - {:suite "dynbind" :expr "(do (def ^:dynamic *bo* 1) (binding [*bo* 2] (binding [*bo* 3] nil) *bo*))" :expected "2"} - {:suite "dynbind" :expr "(do (def ^:dynamic *z* 1) (binding [*z* 0] (var-set (var *z*) 5) *z*))" :expected "5"} - {:suite "dynbind" :expr "(do (def ^:dynamic *zr* 1) (binding [*zr* 0] (var-set (var *zr*) 5)) *zr*)" :expected "1"} - {:suite "dynbind" :expr "(do (def ^:dynamic *tb* 1) (thread-bound? (var *tb*)))" :expected "false"} - {:suite "dynbind" :expr "(do (def ^:dynamic *tc* 1) (binding [*tc* 2] (thread-bound? (var *tc*))))" :expected "true"} - {:suite "dynbind" :expr "(do (def ^:dynamic *wb* 1) (with-bindings* {(var *wb*) 7} (fn [] *wb*)))" :expected "7"} - {:suite "dynbind" :expr "(do (def ^:dynamic *cf* 1) (let [g (binding [*cf* 3] (bound-fn* (fn [] *cf*)))] (g)))" :expected "3"} - {:suite "dynbind" :expr "(do (def ^:dynamic *gb* 1) (binding [*gb* 9] (get (get-thread-bindings) (var *gb*))))" :expected "9"} - {:suite "dynbind" :expr "(with-local-vars [x 1] (var-get x))" :expected "1"} - {:suite "dynbind" :expr "(with-local-vars [x 1] (var-set x 2) (var-get x))" :expected "2"} - {:suite "dynbind" :expr "(with-local-vars [a 1 b 2] [(var-get a) (var-get b)])" :expected "[1 2]"} - {:suite "dynbind" :expr "(with-local-vars [x 0] (let [bump (fn [v] (var-set v (+ 5 (var-get v))))] (bump x) (var-get x)))" :expected "5"} - {:suite "dynbind" :expr "(let [y 3] (with-local-vars [x y] (var-get x)))" :expected "3"} - {:suite "dynbind" :expr "(with-local-vars [x 1] :done)" :expected ":done"} - {:suite "dynbind" :expr "(do (defn wrf [] 1) (with-redefs [wrf (fn [] 42)] (wrf)))" :expected "42"} - {:suite "dynbind" :expr "(do (defn wrg [] 1) (with-redefs [wrg (fn [] 42)]) (wrg))" :expected "1"} - {:suite "dynbind" :expr "(do (defn wrh [] 1) (try (with-redefs [wrh (fn [] 42)] (throw (ex-info \"x\" {}))) (catch :default e nil)) (wrh))" :expected "1"} - {:suite "dynbind" :expr "(do (defn wri [] 1) (with-redefs-fn {(var wri) (fn [] 42)} (fn [] (wri))))" :expected "42"} - {:suite "dynbind" :expr "(do (def av 1) (alter-var-root (var av) inc) av)" :expected "2"} - {:suite "insttime" :expr "(inst? #inst \"2020-01-01T00:00:00Z\")" :expected "true"} - {:suite "insttime" :expr "(inst-ms #inst \"1970-01-01T00:00:01Z\")" :expected "1000"} - {:suite "insttime" :expr "(inst-ms #inst \"1970-01-01T00:00:00.123Z\")" :expected "123"} - {:suite "insttime" :expr "(inst-ms #inst \"2020-01-01T00:00:00Z\")" :expected "1577836800000"} - {:suite "insttime" :expr "(inst-ms* #inst \"1970-01-01T00:00:00Z\")" :expected "0"} - {:suite "insttime" :expr "(some? #inst \"2020-01-01T00:00:00Z\")" :expected "true"} - {:suite "insttime" :expr "(str (type #inst \"2020-01-01T00:00:00Z\"))" :expected "class java.util.Date"} - {:suite "insttime" :expr "(= #inst \"2020\" #inst \"2020-01-01T00:00:00.000Z\")" :expected "true"} - {:suite "insttime" :expr "(= #inst \"2020-03\" #inst \"2020-03-01T00:00:00Z\")" :expected "true"} - {:suite "insttime" :expr "(= #inst \"2020-03-15\" #inst \"2020-03-15T00:00:00Z\")" :expected "true"} - {:suite "insttime" :expr "(= #inst \"2020-01-01T01:00:00+01:00\" #inst \"2020-01-01T00:00:00Z\")" :expected "true"} - {:suite "insttime" :expr "(= #inst \"2019-12-31T23:00:00-01:00\" #inst \"2020-01-01T00:00:00Z\")" :expected "true"} - {:suite "insttime" :expr "(= #inst \"2020-01-01T00:00:00Z\" #inst \"2020-01-01T00:00:01Z\")" :expected "false"} - {:suite "insttime" :expr "(get {#inst \"2020-01-01T00:00:00Z\" :v} #inst \"2020-01-01T00:00:00.000Z\")" :expected ":v"} - {:suite "insttime" :expr "(pr-str #inst \"2020-01-01T00:00:00Z\")" :expected "#inst \"2020-01-01T00:00:00.000-00:00\""} - {:suite "insttime" :expr "(str #inst \"2020-01-01T00:00:00Z\")" :expected "2020-01-01T00:00:00.000-00:00"} - {:suite "insttime" :expr "(uuid? #uuid \"550e8400-e29b-41d4-a716-446655440000\")" :expected "true"} - {:suite "insttime" :expr "(= #uuid \"550E8400-E29B-41D4-A716-446655440000\" #uuid \"550e8400-e29b-41d4-a716-446655440000\")" :expected "true"} - {:suite "insttime" :expr "(pr-str #uuid \"550e8400-e29b-41d4-a716-446655440000\")" :expected "#uuid \"550e8400-e29b-41d4-a716-446655440000\""} - {:suite "insttime" :expr "(.getTime #inst \"1970-01-01T00:00:00Z\")" :expected "0"} - {:suite "insttime" :expr "(instance? java.util.Date #inst \"2020-01-01T00:00:00Z\")" :expected "true"} - {:suite "insttime" :expr "(instance? java.sql.Timestamp #inst \"2020-01-01T00:00:00Z\")" :expected "false"} - {:suite "insttime" :expr "(.toEpochMilli (Instant/ofEpochMilli 1234))" :expected "1234"} - {:suite "insttime" :expr "(instance? java.time.Instant (Instant/ofEpochMilli 0))" :expected "true"} - {:suite "insttime" :expr "(> (.toEpochMilli (Instant/now)) 1500000000000)" :expected "true"} - {:suite "insttime" :expr "(instance? LocalDateTime (-> #inst \"2020-03-05T13:45:30Z\" (.toInstant) (.atZone (ZoneId/systemDefault)) (.toLocalDateTime)))" :expected "true"} - {:suite "insttime" :expr "(.format (DateTimeFormatter/ofPattern \"yyyy-MM-dd\") #inst \"2020-03-05T13:45:30Z\")" :expected "2020-03-05"} - {:suite "insttime" :expr "(boolean (re-matches #\"[A-Z][a-z]{2} \\d{1,2}, 2020 \\d{1,2}:\\d{2} [AP]M\" (.format (DateTimeFormatter/ofPattern \"MMM d, yyyy h:mm a\") #inst \"2020-03-05T13:45:30Z\")))" :expected "true"} - {:suite "insttime" :expr "(boolean (re-matches #\"\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\" (.format DateTimeFormatter/ISO_LOCAL_DATE_TIME #inst \"2020-03-05T13:45:30Z\")))" :expected "true"} - {:suite "insttime" :expr "(string? (.format (DateTimeFormatter/ofLocalizedDate FormatStyle/MEDIUM) #inst \"2020-03-05T13:45:30Z\"))" :expected "true"} - {:suite "insttime" :expr "(string? (.format (.withLocale (DateTimeFormatter/ofPattern \"yyyy\") (java.util.Locale. \"en\")) #inst \"2020-01-01T00:00:00Z\"))" :expected "true"} - {:suite "io" :expr "(do (require (quote [clojure.java.io :as io])) (str (io/file \"/a/b\")))" :expected "/a/b"} - {:suite "io" :expr "(do (require (quote [clojure.java.io :as io])) (str (io/file \"/a\" \"b\")))" :expected "/a/b"} - {:suite "io" :expr "(do (require (quote [clojure.java.io :as io])) (.getName (io/file \"/a/b/c.txt\")))" :expected "c.txt"} - {:suite "io" :expr "(do (require (quote [clojure.java.io :as io])) (.getPath (io/file \"/a\" \"b\")))" :expected "/a/b"} - {:suite "io" :expr "(do (require (quote [clojure.java.io :as io])) (.isDirectory (io/file \"docs\")))" :expected "true"} - {:suite "io" :expr "(do (require (quote [clojure.java.io :as io])) (.isFile (io/file \"README.md\")))" :expected "true"} - {:suite "io" :expr "(do (require (quote [clojure.java.io :as io])) (.isFile (io/file \"docs\")))" :expected "false"} - {:suite "io" :expr "(do (require (quote [clojure.java.io :as io])) (.exists (io/file \"/no/such/path/xyz\")))" :expected "false"} - {:suite "io" :expr "(do (require (quote [clojure.java.io :as io])) (.exists (io/file \"README.md\")))" :expected "true"} - {:suite "io" :expr "(do (require (quote [clojure.java.io :as io])) (instance? java.io.File (io/file \"/a/b\")))" :expected "true"} - {:suite "io" :expr "(do (require (quote [clojure.java.io :as io])) (instance? java.io.File \"/a/b\"))" :expected "false"} - {:suite "io" :expr "(do (require (quote [clojure.java.io :as io])) (str (type (io/file \"/a\"))))" :expected "class java.io.File"} - {:suite "io" :expr "(do (require (quote [clojure.java.io :as io])) (every? (fn [f] (instance? java.io.File f)) (file-seq (io/file \"docs\"))))" :expected "true"} - {:suite "io" :expr "(do (require (quote [clojure.java.io :as io])) (pos? (count (filter (fn [f] (.isFile f)) (file-seq (io/file \"docs\"))))))" :expected "true"} - {:suite "io" :expr "(do (require (quote [clojure.string :as s])) (boolean (some (fn [p] (s/ends-with? p \"README.md\")) (file-seq \".\"))))" :expected "true"} - {:suite "io" :expr "(string? (slurp \"README.md\"))" :expected "true"} - {:suite "io" :expr "(do (spit \"/tmp/jolt-io-test.txt\" \"hello\") (slurp \"/tmp/jolt-io-test.txt\"))" :expected "hello"} - {:suite "io" :expr "(do (spit \"/tmp/jolt-io-test.txt\" \"a\") (spit \"/tmp/jolt-io-test.txt\" \"b\" :append true) (slurp \"/tmp/jolt-io-test.txt\"))" :expected "ab"} - {:suite "io" :expr "(flush)" :expected ""} - {:suite "io" :expr "(do (require (quote [clojure.java.io :as io])) (string? (slurp (io/file \"README.md\"))))" :expected "true"} - {:suite "ioreader" :expr "(apply str (char-array \"abc\"))" :expected "abc"} - {:suite "ioreader" :expr "(.read (StringReader. (apply str (char-array \"Qz\"))))" :expected "81"} - {:suite "ioreader" :expr "(do (require (quote [clojure.java.io :as io])) (.read (io/reader (char-array \"abc\"))))" :expected "97"} - {:suite "ioreader" :expr "(do (require (quote [clojure.java.io :as io])) (.read (io/reader (StringReader. \"k\"))))" :expected "107"} - {:suite "ioreader" :expr "(do (require (quote [clojure.java.io :as io])) (slurp (io/reader (char-array \"xyz\"))))" :expected "xyz"} - {:suite "ioreader" :expr "(do (require (quote [clojure.java.io :as io])) (string? (slurp (io/reader \"README.md\"))))" :expected "true"} - {:suite "ioreader" :expr "(do (require (quote [clojure.java.io :as io])) (.toString (.toURL (io/file \"/tmp/x\"))))" :expected "file:/tmp/x"} - {:suite "ioreader" :expr "(do (require (quote [clojure.java.io :as io])) (.toURI (io/file \"/tmp/x\")))" :expected "file:/tmp/x"} - {:suite "ioreader" :expr "(do (require (quote [clojure.java.io :as io])) (.getPath (.toURL (io/file \"/tmp/x\"))))" :expected "/tmp/x"} - {:suite "ioreader" :expr "(do (require (quote [clojure.java.io :as io])) (.getAbsolutePath (io/file \"/a/b\")))" :expected "/a/b"} - {:suite "ioreader" :expr "(slurp (StringReader. \"a=1\"))" :expected "a=1"} - {:suite "ioreader" :expr "(slurp (StringReader. \"b\") :encoding \"UTF-8\")" :expected "b"} - {:suite "ioreader" :expr "(with-open [r (StringReader. \"a\")] (.read r))" :expected "97"} - {:suite "ioreader" :expr "(let [log (atom [])] (with-open [c {:close (fn [] (swap! log conj :closed))}] :r) (deref log))" :expected "[:closed]"} - {:suite "ioreader" :expr "(let [log (atom [])] (try (with-open [c {:close (fn [] (swap! log conj :closed))}] (throw (ex-info \"boom\" {}))) (catch Exception e nil)) (deref log))" :expected "[:closed]"} - {:suite "ioreader" :expr "(let [log (atom [])] (with-open [a {:close (fn [] (swap! log conj :outer))} b {:close (fn [] (swap! log conj :inner))}] :r) (deref log))" :expected "[:inner :outer]"} - {:suite "ioreader" :expr "(with-open [c {:close (fn [] nil) :v 5}] (:v c))" :expected "5"} - {:suite "ioreader" :expr "(do (defrecord RC [log] java.io.Closeable (close [_] (swap! log conj :closed))) (let [log (atom [])] (with-open [r (->RC log)] :body) @log))" :expected "[:closed]"} - {:suite "javastatic" :expr "(Math/sqrt 16)" :expected "4.0"} - {:suite "javastatic" :expr "(Math/abs -3)" :expected "3"} - {:suite "javastatic" :expr "(Math/max 2 7)" :expected "7"} - {:suite "javastatic" :expr "(pos? Long/MAX_VALUE)" :expected "true"} - {:suite "javastatic" :expr "(String/valueOf 42)" :expected "42"} - {:suite "javastatic" :expr "(String/valueOf \"hi\")" :expected "hi"} - {:suite "javastatic" :expr "(String/valueOf :k)" :expected ":k"} - {:suite "javastatic" :expr "(String/valueOf nil)" :expected "null"} - {:suite "javastatic" :expr "(Long/parseLong \"42\")" :expected "42"} - {:suite "javastatic" :expr "(Long/valueOf \"42\")" :expected "42"} - {:suite "javastatic" :expr "(Integer/parseInt \"ff\" 16)" :expected "255"} - {:suite "javastatic" :expr "(.byteValue (Integer/valueOf \"ff\" 16))" :expected "-1"} - {:suite "javastatic" :expr "(Boolean/parseBoolean \"true\")" :expected "true"} - {:suite "javastatic" :expr "(Boolean/parseBoolean \"yes\")" :expected "false"} - {:suite "javastatic" :expr "(Character/isUpperCase \\A)" :expected "true"} - {:suite "javastatic" :expr "(Character/isLowerCase \\a)" :expected "true"} - {:suite "javastatic" :expr "(Character/isUpperCase \\a)" :expected "false"} - {:suite "javastatic" :expr "(Thread/interrupted)" :expected "false"} - {:suite "javastatic" :expr "(string? (System/getProperty \"os.name\"))" :expected "true"} - {:suite "javastatic" :expr "(string? (get (System/getenv) \"HOME\"))" :expected "true"} - {:suite "javastatic" :expr "(string? (System/getenv \"HOME\"))" :expected "true"} - {:suite "javastatic" :expr "(fn? System/exit)" :expected "true"} - {:suite "javastatic" :expr "(string? (get (System/getProperties) \"os.name\"))" :expected "true"} - {:suite "javastatic" :expr "(pos? (count (seq (System/getenv))))" :expected "true"} - {:suite "javastatic" :expr "(let [es (map (fn [[k v]] [k v]) (System/getenv))] (and (pos? (count es)) (every? vector? es)))" :expected "true"} - {:suite "javastatic" :expr "(.toString (StringBuilder. \"x\"))" :expected "x"} - {:suite "javastatic" :expr "(.toString (-> (StringBuilder.) (.append \"a\") (.append \\b) (.append 1)))" :expected "ab1"} - {:suite "javastatic" :expr "(.toString (.append (StringBuilder. 16) \"x\"))" :expected "x"} - {:suite "javastatic" :expr "(let [sb (StringBuilder.)] (.append sb \"abcd\") (.setLength sb 2) (.toString sb))" :expected "ab"} - {:suite "javastatic" :expr "(let [w (StringWriter.)] (.write w \"a\") (.append w \\b) (.toString w))" :expected "ab"} - {:suite "javastatic" :expr "(let [r (StringReader. \"ab\")] [(.read r) (.read r) (.read r)])" :expected "[97 98 -1]"} - {:suite "javastatic" :expr "(let [r (StringReader. \"ab\")] (.mark r 1) [(.read r) (do (.reset r) (.read r))])" :expected "[97 97]"} - {:suite "javastatic" :expr "(let [r (java.io.PushbackReader. (java.io.StringReader. \"ab\"))] [(.read r) (.read r)])" :expected "[97 98]"} - {:suite "javastatic" :expr "(let [r (PushbackReader. (StringReader. \"ab\")) a (.read r)] (.unread r a) [a (.read r) (.read r)])" :expected "[97 97 98]"} - {:suite "javastatic" :expr "(let [r (PushbackReader. (StringReader. \"a\"))] (.unread r \\x) [(.read r) (.read r)])" :expected "[120 97]"} - {:suite "javastatic" :expr "(BigInteger. \"123\")" :expected "123"} - {:suite "javastatic" :expr "(let [m (HashMap. {:a 1 :b 2})] (.get m :b))" :expected "2"} - {:suite "javastatic" :expr "(let [m (HashMap. {})] (.put m :x 1) (.put m :y 2) (.size m))" :expected "2"} - {:suite "javastatic" :expr "(let [t (StringTokenizer. \"a=1&b=2\" \"&\")] [(.nextToken t) (.nextToken t)])" :expected "[a=1 b=2]"} - {:suite "javastatic" :expr "(.toString (StringBuilder. \"x\"))" :expected "x"} - {:suite "javastatic" :expr "(URLEncoder/encode \"a b=c\")" :expected "a+b%3Dc"} - {:suite "javastatic" :expr "(URLDecoder/decode (URLEncoder/encode \"x &=%?\"))" :expected "x &=%?"} - {:suite "javastatic" :expr "(String. (.encode (Base64/getEncoder) (.getBytes \"hello\")))" :expected "aGVsbG8="} - {:suite "javastatic" :expr "(String. (.decode (Base64/getDecoder) (String. (.encode (Base64/getEncoder) (.getBytes \"hello\")))))" :expected "hello"} - {:suite "javastatic" :expr "(Integer/parseInt \"ff\" 16)" :expected "255"} - {:suite "javastatic" :expr "(regex? (Pattern/compile \"a.c\"))" :expected "true"} - {:suite "javastatic" :expr "(.split (Pattern/compile \",\") \"a,b,c\")" :expected "(a b c)"} - {:suite "javastatic" :expr "(do (require '[clojure.string :as s]) (s/replace \"a1b2\" (Pattern/compile \"[0-9]\") \"\"))" :expected "ab"} - {:suite "javastatic" :expr "(boolean (re-find (Pattern/compile \"^x\" Pattern/MULTILINE) \"y\\nx\"))" :expected "true"} - {:suite "javastatic" :expr "(boolean (re-find (re-pattern (Pattern/quote \"a.c\")) \"za.cy\"))" :expected "true"} - {:suite "javastatic" :expr "(boolean (re-find (re-pattern (Pattern/quote \"a.c\")) \"zabcy\"))" :expected "false"} - {:suite "ns" :expr "(some? (find-ns 'clojure.core))" :expected "true"} - {:suite "ns" :expr "(nil? (find-ns 'does.not.exist))" :expected "true"} - {:suite "ns" :expr "(var? (resolve '+))" :expected "true"} - {:suite "ns" :expr "(nil? (resolve 'totally-undefined-xyz))" :expected "true"} - {:suite "ns" :expr "(do (def npv 1) (some? (get (ns-publics 'user) 'npv)))" :expected "true"} - {:suite "ns" :expr "(do (def nmv 1) (some? (get (ns-map 'user) 'nmv)))" :expected "true"} - {:suite "ns" :expr "(map? (ns-aliases 'clojure.core))" :expected "true"} - {:suite "ns" :expr "(map? (ns-interns 'user))" :expected "true"} - {:suite "ns" :expr "(do (def q 1) (pos? (count (ns-interns 'user))))" :expected "true"} - {:suite "ns" :expr "(pos? (count (all-ns)))" :expected "true"} - {:suite "ns" :expr "(= (ns-name *ns*) (ns-name (find-ns 'user)))" :expected "true"} - {:suite "ns" :expr "(str (in-ns 'jolt.test-ns-b))" :expected "jolt.test-ns-b"} - {:suite "ns" :expr "(do (in-ns 'jolt.test-ns-a) (str *ns*))" :expected "jolt.test-ns-a"} - {:suite "ns" :expr "(do (def nuv 1) (ns-unmap 'user 'nuv) (nil? (resolve 'nuv)))" :expected "true"} - {:suite "ns" :expr "(do (in-ns 'my.ns) (symbol? 'x))" :expected "true"} - {:suite "ns" :expr "(str (ns-name *ns*))" :expected "user"} - {:suite "ns" :expr "(var? (find-var 'clojure.core/map))" :expected "true"} - {:suite "ns" :expr "(= 'user (ns-name (the-ns 'user)))" :expected "true"} - {:suite "ns" :expr "(= 'foo.bar (ns-name (create-ns 'foo.bar)))" :expected "true"} - {:suite "reader" :expr "(= 42 (read-string \"42\"))" :expected "true"} - {:suite "reader" :expr "(= 42 (read-string \"0x2A\"))" :expected "true"} - {:suite "reader" :expr "(== 0.5 (read-string \"1/2\"))" :expected "true"} - {:suite "reader" :expr "(= -3.5 (read-string \"-3.5\"))" :expected "true"} - {:suite "reader" :expr "(== 1000.0 (read-string \"1e3\"))" :expected "true"} - {:suite "reader" :expr "(= 1 (read-string \"1N\"))" :expected "true"} - {:suite "reader" :expr "(integer? (read-string \"7\"))" :expected "true"} - {:suite "reader" :expr "(= :foo (read-string \":foo\"))" :expected "true"} - {:suite "reader" :expr "(= :a/b (read-string \":a/b\"))" :expected "true"} - {:suite "reader" :expr "(= [true \"foo\"] [(some? (namespace (read-string \"::foo\"))) (name (read-string \"::foo\"))])" :expected "true"} - {:suite "reader" :expr "(= (quote sym) (read-string \"sym\"))" :expected "true"} - {:suite "reader" :expr "(= (quote ns/sym) (read-string \"ns/sym\"))" :expected "true"} - {:suite "reader" :expr "(nil? (read-string \"nil\"))" :expected "true"} - {:suite "reader" :expr "(true? (read-string \"true\"))" :expected "true"} - {:suite "reader" :expr "(false? (read-string \"false\"))" :expected "true"} - {:suite "reader" :expr "(let [r (read-string \"#foo bar\")] (and (tagged-literal? r) (= (quote foo) (:tag r)) (= (quote bar) (:form r)) (= \"#foo bar\" (pr-str r))))" :expected "true"} - {:suite "reader" :expr "(let [t (first (quote [#foo bar]))] (and (tagged-literal? t) (= (quote foo) (:tag t)) (= \"#foo bar\" (pr-str t))))" :expected "true"} - {:suite "reader" :expr "(= \\a (read-string \"\\\\a\"))" :expected "true"} - {:suite "reader" :expr "(= \\newline (read-string \"\\\\newline\"))" :expected "true"} - {:suite "reader" :expr "(= \\space (read-string \"\\\\space\"))" :expected "true"} - {:suite "reader" :expr "(= \"a\\nb\" (read-string \"\\\"a\\\\nb\\\"\"))" :expected "true"} - {:suite "reader" :expr "(= [1 2 3] (read-string \"[1 2 3]\"))" :expected "true"} - {:suite "reader" :expr "(= (quote (+ 1 2)) (read-string \"(+ 1 2)\"))" :expected "true"} - {:suite "reader" :expr "(= {:a 1 :b 2} (read-string \"{:a 1 :b 2}\"))" :expected "true"} - {:suite "reader" :expr "(set? (read-string \"#{1 2 3}\"))" :expected "true"} - {:suite "reader" :expr "(= #{1 2 3} (read-string \"#{1 2 3}\"))" :expected "true"} - {:suite "reader" :expr "(= [1 [2 3] {:k :v}] (read-string \"[1 [2 3] {:k :v}]\"))" :expected "true"} - {:suite "reader" :expr "(= (quote (quote x)) (read-string \"'x\"))" :expected "true"} - {:suite "reader" :expr "(= (quote (clojure.core/deref a)) (read-string \"@a\"))" :expected "true"} - {:suite "reader" :expr "(= (quote (syntax-quote (a (clojure.core/unquote b)))) (read-string \"`(a ~b)\"))" :expected "true"} - {:suite "reader" :expr "(= (quote (clojure.core/unquote-splicing xs)) (read-string \"~@xs\"))" :expected "true"} - {:suite "reader" :expr "(= 42 (read-string \"; comment\\n42\"))" :expected "true"} - {:suite "reader" :expr "(= [1 2] (read-string \"[1 #_ 9 2]\"))" :expected "true"} - {:suite "reader" :expr "(nil? (read-string \"\"))" :expected "true"} - {:suite "reader" :expr "(nil? (read-string \" , ,\"))" :expected "true"} - {:suite "reader" :expr "(:tag (meta (read-string \"^String x\")))" :expected "String"} - {:suite "reader" :expr "(:foo (meta (read-string \"^:foo x\")))" :expected "true"} - {:suite "reader" :expr "(:line (meta (read-string \"(foo bar)\")))" :expected "1"} - {:suite "reader" :expr "(:column (meta (read-string \"(foo bar)\")))" :expected "1"} - {:suite "reader" :expr "(:line (meta (read-string \"\\n\\n (x)\")))" :expected "3"} - {:suite "reader" :expr "(:column (meta (read-string \"\\n\\n (x)\")))" :expected "3"} - {:suite "reader" :expr "(nil? (meta (read-string \"[1 2]\")))" :expected "true"} - {:suite "reader" :expr "(nil? (meta (read-string \"()\")))" :expected "true"} - {:suite "reader" :expr "(:foo (meta (read-string \"^:foo (x y)\")))" :expected "true"} - {:suite "reader" :expr "(:line (meta (read-string \"^:foo (x y)\")))" :expected "1"} - {:suite "reader" :expr "(:line (meta (macroexpand-1 (read-string \"(when x y)\"))))" :expected "1"} - {:suite "reader" :expr "(:line (meta (macroexpand-1 (read-string \"\\n\\n(when x y)\"))))" :expected "3"} - {:suite "reader" :expr "(:column (meta (macroexpand-1 (read-string \"(when x y)\"))))" :expected "1"} - {:suite "reader" :expr "(= 42 (with-in-str \"42\" (read)))" :expected "true"} - {:suite "reader" :expr "(= (quote (+ 1 2)) (with-in-str \"(+ 1 2)\" (read)))" :expected "true"} - {:suite "reader" :expr "(with-in-str \"1 2\" [(read) (read)])" :expected "[1 2]"} - {:suite "reader" :expr "(= :done (with-in-str \"\" (read *in* false :done)))" :expected "true"} - {:suite "reader" :expr "(let [[v s] (with-in-str \"42 rest\" (read+string))] (and (= v 42) (string? s)))" :expected "true"} - {:suite "reader" :expr "(= [1 2] (with-in-str \"1 2\" [(first (read+string)) (first (read+string))]))" :expected "true"} - {:suite "reader" :expr "(do (require (quote [clojure.edn :as e0])) (= #{1 2} (e0/read-string \"#{1 2}\")))" :expected "true"} - {:suite "reader" :expr "(do (require (quote [clojure.edn :as e0])) (uuid? (e0/read-string \"#uuid \\\"550e8400-e29b-41d4-a716-446655440000\\\"\")))" :expected "true"} - {:suite "reader" :expr "(do (require (quote [clojure.edn :as e0])) (inst? (e0/read-string \"#inst \\\"2020-01-01T00:00:00Z\\\"\")))" :expected "true"} - {:suite "reader" :expr "(do (require (quote [clojure.edn :as e0])) (= :end (e0/read-string {:eof :end} \"\")))" :expected "true"} - {:suite "reader" :expr "(do (require (quote [clojure.edn :as e0])) (= [:custom 5] (e0/read-string {:readers {(quote custom) (fn [v] [:custom v])}} \"#custom 5\")))" :expected "true"} - {:suite "reader" :expr "(do (require (quote clojure.edn)) (= {:a 1 :b 2} (clojure.edn/read-string \"{:a 1\\n :b 2}\")))" :expected "true"} - {:suite "seqpred" :expr "(seq? (map inc [1 2 3]))" :expected "true"} - {:suite "seqpred" :expr "(seq? (filter odd? [1 2 3]))" :expected "true"} - {:suite "seqpred" :expr "(seq? (lazy-seq (cons 1 nil)))" :expected "true"} - {:suite "seqpred" :expr "(seq? (take 3 (iterate inc 0)))" :expected "true"} - {:suite "seqpred" :expr "(seq? (cons 0 (range 3)))" :expected "true"} - {:suite "seqpred" :expr "(seq? [1 2 3])" :expected "false"} - {:suite "seqpred" :expr "(seq? {:a 1})" :expected "false"} - {:suite "seqpred" :expr "(seq? nil)" :expected "false"} - {:suite "seqpred" :expr "(sequential? (range 3))" :expected "true"} - {:suite "seqpred" :expr "(sequential? (map inc [1 2 3]))" :expected "true"} - {:suite "seqpred" :expr "(sequential? (filter odd? [1 2 3]))" :expected "true"} - {:suite "seqpred" :expr "(sequential? (lazy-seq (cons 1 nil)))" :expected "true"} - {:suite "seqpred" :expr "(sequential? (take 2 (repeat 9)))" :expected "true"} - {:suite "seqpred" :expr "(sequential? [1 2 3])" :expected "true"} - {:suite "seqpred" :expr "(sequential? '(1 2 3))" :expected "true"} - {:suite "seqpred" :expr "(sequential? {:a 1})" :expected "false"} - {:suite "seqpred" :expr "(sequential? #{1 2})" :expected "false"} - {:suite "seqpred" :expr "(sequential? nil)" :expected "false"} - {:suite "seqpred" :expr "(= [0 1 2] (range 3))" :expected "true"} - {:suite "seqpred" :expr "(= (range 3) [0 1 2])" :expected "true"} - {:suite "seqpred" :expr "(= (map inc [0 1]) '(1 2))" :expected "true"} - {:suite "seqpred" :expr "(contains? #{[0 1 2]} (vec (range 3)))" :expected "true"} - {:suite "stdlib" :expr "(< 1.4142 (clojure.math/sqrt 2) 1.4143)" :expected "true"} - {:suite "stdlib" :expr "(long (clojure.math/pow 2 10))" :expected "1024"} - {:suite "stdlib" :expr "(long (clojure.math/tan 0))" :expected "0"} - {:suite "stdlib" :expr "(clojure.math/round 2.6)" :expected "3"} - {:suite "stdlib" :expr "(clojure.math/floor 2.9)" :expected "2.0"} - {:suite "stdlib" :expr "(clojure.math/signum -7.2)" :expected "-1.0"} - {:suite "stdlib" :expr "(< 3.14 (clojure.math/to-radians 180) 3.15)" :expected "true"} - {:suite "stdlib" :expr "(< 3.14 clojure.math/PI 3.15)" :expected "true"} - {:suite "stdlib" :expr "(< 2.71 clojure.math/E 2.72)" :expected "true"} - {:suite "stdlib" :expr "(long (clojure.math/cbrt 27))" :expected "3"} - {:suite "stdlib" :expr "(< 4.6 (clojure.math/log 100) 4.7)" :expected "true"} - {:suite "stdlib" :expr "(< 2.99 (clojure.math/log10 1000) 3.01)" :expected "true"} - {:suite "stdlib" :expr "(do (require (quote [clojure.math :as m])) (long (m/hypot 3 4)))" :expected "5"} - {:suite "stdlib" :expr "(mapv (comp long clojure.math/sqrt) [1 4])" :expected "[1 2]"} - {:suite "stdlib" :expr "(long (clojure.math/atan2 0 1))" :expected "0"} - {:suite "stdlib" :expr "(do (require (quote [clojure.set :as s])) (= #{1 2 3 4} (s/union #{1 2} #{3 4})))" :expected "true"} - {:suite "stdlib" :expr "(do (require (quote [clojure.set :as s])) (= #{2} (s/intersection #{1 2} #{2 3})))" :expected "true"} - {:suite "stdlib" :expr "(do (require (quote [clojure.set :as s])) (= #{1} (s/difference #{1 2} #{2 3})))" :expected "true"} - {:suite "stdlib" :expr "(do (require (quote [clojure.set :as s])) (s/subset? #{1} #{1 2}))" :expected "true"} - {:suite "stdlib" :expr "(do (require (quote [clojure.set :as s])) (s/superset? #{1 2} #{1}))" :expected "true"} - {:suite "stdlib" :expr "(do (require (quote [clojure.set :as s])) (= {1 :a 2 :b} (s/map-invert {:a 1 :b 2})))" :expected "true"} - {:suite "stdlib" :expr "(do (require (quote [clojure.set :as s])) (= #{:a} (s/select keyword? #{:a})))" :expected "true"} - {:suite "stdlib" :expr "(do (require (quote [clojure.set :as s])) (= #{{:a 1 :b 2}} (s/join #{{:a 1}} #{{:b 2}})))" :expected "true"} - {:suite "stdlib" :expr "(do (require (quote [clojure.set :as s])) (= {:b 1} (s/rename-keys {:a 1} {:a :b})))" :expected "true"} - {:suite "stdlib" :expr "(do (require (quote [clojure.set :as s])) (= 2 (count (s/index #{{:k 1} {:k 2}} [:k]))))" :expected "true"} - {:suite "stdlib" :expr "(do (require (quote [clojure.pprint :as pp])) (= \"[1 2 3]\\n\" (with-out-str (pp/pprint [1 2 3]))))" :expected "true"} - {:suite "stdlib" :expr "(do (require (quote [clojure.pprint :as pp])) (pp/with-pprint-dispatch pp/code-dispatch 42))" :expected "42"} - {:suite "str" :expr "(.toLowerCase \"HI\")" :expected "hi"} - {:suite "str" :expr "(.toUpperCase \"hi\")" :expected "HI"} - {:suite "str" :expr "(.trim \" x \")" :expected "x"} - {:suite "str" :expr "(.length \"abc\")" :expected "3"} - {:suite "str" :expr "[(.isEmpty \"\") (.isEmpty \"a\")]" :expected "[true false]"} - {:suite "str" :expr "(.indexOf \"abc\" \"b\")" :expected "1"} - {:suite "str" :expr "(.indexOf \"abc\" \"z\")" :expected "-1"} - {:suite "str" :expr "(.indexOf \"abab\" \"a\" 1)" :expected "2"} - {:suite "str" :expr "(.indexOf \"a=b\" 61)" :expected "1"} - {:suite "str" :expr "(.lastIndexOf \"abab\" \"b\")" :expected "3"} - {:suite "str" :expr "(.substring \"abc\" 1)" :expected "bc"} - {:suite "str" :expr "(.substring \"abc\" 1 2)" :expected "b"} - {:suite "str" :expr "(.startsWith \"abc\" \"ab\")" :expected "true"} - {:suite "str" :expr "(.endsWith \"abc\" \"bc\")" :expected "true"} - {:suite "str" :expr "(.contains \"abc\" \"b\")" :expected "true"} - {:suite "str" :expr "(.replace \"abc\" \"b\" \"x\")" :expected "axc"} - {:suite "str" :expr "(.replace \"aaa\" \"a\" \"b\")" :expected "bbb"} - {:suite "str" :expr "(.charAt \"abc\" 1)" :expected "\\b"} - {:suite "str" :expr "(.equalsIgnoreCase \"AbC\" \"aBc\")" :expected "true"} - {:suite "str" :expr "(.toString \"hi\")" :expected "hi"} - {:suite "str" :expr "(.concat \"ab\" \"cd\")" :expected "abcd"} - {:suite "str" :expr "(.matches \"abc\" \"a.c\")" :expected "true"} - {:suite "str" :expr "(.matches \"abcd\" \"a.c\")" :expected "false"} - {:suite "str" :expr "(.replaceAll \"a_b_c\" \"_\" \"-\")" :expected "a-b-c"} - {:suite "str" :expr "(.replaceFirst \"a_b_c\" \"_\" \"-\")" :expected "a-b_c"} - {:suite "str" :expr "(vec (.split \"a,b,c\" \",\"))" :expected "[a b c]"} - {:suite "str" :expr "(.frobnicate \"abc\")" :expected :throws} - {:suite "strns" :expr "(do (require (quote [clojure.string :as s])) (s/upper-case \"abc\"))" :expected "ABC"} - {:suite "strns" :expr "(do (require (quote [clojure.string :as s])) (s/lower-case \"ABC\"))" :expected "abc"} - {:suite "strns" :expr "(do (require (quote [clojure.string :as s])) (s/capitalize \"hello\"))" :expected "Hello"} - {:suite "strns" :expr "(do (require (quote [clojure.string :as s])) (s/trim \" x \"))" :expected "x"} - {:suite "strns" :expr "(do (require (quote [clojure.string :as s])) (= \"x \" (s/triml \" x \")))" :expected "true"} - {:suite "strns" :expr "(do (require (quote [clojure.string :as s])) (= \" x\" (s/trimr \" x \")))" :expected "true"} - {:suite "strns" :expr "(do (require (quote [clojure.string :as s])) (s/blank? \"\"))" :expected "true"} - {:suite "strns" :expr "(do (require (quote [clojure.string :as s])) (s/blank? \" \"))" :expected "true"} - {:suite "strns" :expr "(do (require (quote [clojure.string :as s])) (s/blank? \"x\"))" :expected "false"} - {:suite "strns" :expr "(do (require (quote [clojure.string :as s])) (s/blank? nil))" :expected "true"} - {:suite "strns" :expr "(do (require (quote [clojure.string :as s])) (s/includes? \"abcd\" \"bc\"))" :expected "true"} - {:suite "strns" :expr "(do (require (quote [clojure.string :as s])) (s/includes? \"abcd\" \"zz\"))" :expected "false"} - {:suite "strns" :expr "(do (require (quote [clojure.string :as s])) (s/starts-with? \"abc\" \"ab\"))" :expected "true"} - {:suite "strns" :expr "(do (require (quote [clojure.string :as s])) (s/starts-with? \"abc\" \"bc\"))" :expected "false"} - {:suite "strns" :expr "(do (require (quote [clojure.string :as s])) (s/ends-with? \"abc\" \"bc\"))" :expected "true"} - {:suite "strns" :expr "(do (require (quote [clojure.string :as s])) (s/join [\"a\" \"b\" \"c\"]))" :expected "abc"} - {:suite "strns" :expr "(do (require (quote [clojure.string :as s])) (s/join \",\" [\"a\" \"b\" \"c\"]))" :expected "a,b,c"} - {:suite "strns" :expr "(do (require (quote [clojure.string :as s])) (s/join \"-\" [1 2 3]))" :expected "1-2-3"} - {:suite "strns" :expr "(do (require (quote [clojure.string :as s])) (s/split \"a,b,c\" \",\"))" :expected "[a b c]"} - {:suite "strns" :expr "(do (require (quote [clojure.string :as s])) (s/split \"a1b2c\" #\"[0-9]\"))" :expected "[a b c]"} - {:suite "strns" :expr "(do (require (quote [clojure.string :as s])) (s/split-lines \"a\\nb\\nc\"))" :expected "[a b c]"} - {:suite "strns" :expr "(do (require (quote [clojure.string :as s])) (s/replace \"a_b_c\" \"_\" \"-\"))" :expected "a-b-c"} - {:suite "strns" :expr "(do (require (quote [clojure.string :as s])) (s/replace \"a1b2\" #\"[0-9]\" \"\"))" :expected "ab"} - {:suite "strns" :expr "(do (require (quote [clojure.string :as s])) (s/replace-first \"a_b_c\" \"_\" \"-\"))" :expected "a-b_c"} - {:suite "strns" :expr "(do (require (quote [clojure.string :as s])) (s/reverse \"abc\"))" :expected "cba"} - {:suite "strns" :expr "(do (require (quote [clojure.string :as s])) (s/index-of \"abc\" \"b\"))" :expected "1"} - {:suite "strns" :expr "(do (require (quote [clojure.string :as s])) (nil? (s/index-of \"abc\" \"z\")))" :expected "true"} - {:suite "strns" :expr "(do (require (quote [clojure.string :as s])) (s/trim-newline \"abc\\n\\n\"))" :expected "abc"} - {:suite "type" :expr "(type 5)" :expected "java.lang.Long"} - {:suite "type" :expr "(type 5.0)" :expected "java.lang.Double"} - {:suite "type" :expr "(type (/ 10 2))" :expected "java.lang.Long"} - {:suite "type" :expr "(type \"s\")" :expected "java.lang.String"} - {:suite "type" :expr "(type :k)" :expected "clojure.lang.Keyword"} - {:suite "type" :expr "(type 'x)" :expected "clojure.lang.Symbol"} - {:suite "type" :expr "(type true)" :expected "java.lang.Boolean"} - {:suite "type" :expr "(type false)" :expected "java.lang.Boolean"} - {:suite "type" :expr "(type nil)" :expected ""} - {:suite "type" :expr "(type \\a)" :expected "java.lang.Character"} - {:suite "type" :expr "(type [1 2])" :expected "clojure.lang.PersistentVector"} - {:suite "type" :expr "(type [])" :expected "clojure.lang.PersistentVector"} - {:suite "type" :expr "(type {:a 1})" :expected "clojure.lang.PersistentArrayMap"} - {:suite "type" :expr "(type #{1})" :expected "clojure.lang.PersistentHashSet"} - {:suite "type" :expr "(type '(1 2))" :expected "clojure.lang.PersistentList"} - {:suite "type" :expr "(type '())" :expected "clojure.lang.PersistentList$EmptyList"} - {:suite "type" :expr "(type (first {:a 1}))" :expected "clojure.lang.PersistentVector"} - {:suite "type" :expr "(type (map inc [1 2]))" :expected "clojure.lang.LazySeq"} - {:suite "type" :expr "(type (filter odd? [1 2 3]))" :expected "clojure.lang.LazySeq"} - {:suite "type" :expr "(type (lazy-seq (cons 1 nil)))" :expected "clojure.lang.LazySeq"} - {:suite "type" :expr "(type (take 2 (iterate inc 0)))" :expected "clojure.lang.LazySeq"} - {:suite "type" :expr "(type inc)" :expected "clojure.core$inc"} - {:suite "type" :expr "(type (sorted-map :a 1))" :expected ":map"} - {:suite "type" :expr "(type (sorted-set 1))" :expected ":jolt/sorted-set"} - {:suite "type" :expr "(type (with-meta [1] {:type :custom}))" :expected ":custom"} - {:suite "type" :expr "(type (with-meta {:a 1} {:type :rec}))" :expected ":rec"} - {:suite "type" :expr "(type (with-meta [1] {:other 9}))" :expected "clojure.lang.PersistentVector"} - {:suite "type" :expr "(do (defrecord TyR [a]) (type (->TyR 1)))" :expected "user.TyR"} - {:suite "type" :expr "(do (defrecord TyR [a]) (= (symbol (str (type (->TyR 1)))) (type (->TyR 1))))" :expected "false"} - {:suite "type" :expr "(do (defrecord TyR [a]) (symbol? (type (->TyR 1))))" :expected "false"} - {:suite "type" :expr "(type (atom 1))" :expected "clojure.lang.Atom"} - {:suite "type" :expr "(type (volatile! 1))" :expected ":jolt/volatile"} - {:suite "type" :expr "(type #\"re\")" :expected "java.util.regex.Pattern"} - {:suite "type" :expr "(do (def vx 1) (type (var vx)))" :expected ":jolt/var"} - {:suite "type" :expr "(type (transient []))" :expected ":jolt/transient"} - {:suite "type" :expr "(type (random-uuid))" :expected "java.util.UUID"} - {:suite "type" :expr "(type (ex-info \"x\" {}))" :expected "clojure.lang.ExceptionInfo"} - {:suite "var_meta" :expr "(do (def ^:private pv 1) (:private (meta (var pv))))" :expected "true"} - {:suite "var_meta" :expr "(do (def ^String tv \"a\") (:tag (meta (var tv))))" :expected "java.lang.String"} - {:suite "var_meta" :expr "(do (def dv2 \"hi\" 1) (:doc (meta (var dv2))))" :expected "hi"} - {:suite "var_meta" :expr "(do (def mv 1) (:name (meta (var mv))))" :expected "mv"} - {:suite "var_meta" :expr "(do (def nv 1) (:ns (meta (var nv))))" :expected "user"} - {:suite "var_meta" :expr "(do (def pl 1) (nil? (:private (meta (var pl)))))" :expected "true"} - {:suite "walk" :expr "(list? (list 1 2))" :expected "true"} - {:suite "walk" :expr "(list? (list 1))" :expected "true"} - {:suite "walk" :expr "(list? '(1 2))" :expected "true"} - {:suite "walk" :expr "(list? '())" :expected "true"} - {:suite "walk" :expr "(list? (list))" :expected "true"} - {:suite "walk" :expr "(list? (cons 1 nil))" :expected "true"} - {:suite "walk" :expr "(list? (cons 1 [2]))" :expected "true"} - {:suite "walk" :expr "(list? (cons 1 '(2)))" :expected "true"} - {:suite "walk" :expr "(list? (conj (list 1) 0))" :expected "true"} - {:suite "walk" :expr "(list? (conj '() 1))" :expected "true"} - {:suite "walk" :expr "(list? (reverse [1 2]))" :expected "true"} - {:suite "walk" :expr "(list? (reverse '(1 2)))" :expected "true"} - {:suite "walk" :expr "(list? [1 2])" :expected "false"} - {:suite "walk" :expr "(list? {:a 1})" :expected "false"} - {:suite "walk" :expr "(list? (map inc [1 2]))" :expected "false"} - {:suite "walk" :expr "(list? (filter odd? [1 2 3]))" :expected "false"} - {:suite "walk" :expr "(list? (seq [1 2]))" :expected "false"} - {:suite "walk" :expr "(list? (rest (list 1 2)))" :expected "false"} - {:suite "walk" :expr "(list? (next (list 1 2)))" :expected "false"} - {:suite "walk" :expr "(list? (take 2 (list 1 2 3)))" :expected "false"} - {:suite "walk" :expr "(list? (concat '(1) '(2)))" :expected "false"} - {:suite "walk" :expr "(list? (rest [1 2]))" :expected "false"} - {:suite "walk" :expr "(list? 5)" :expected "false"} - {:suite "walk" :expr "(list? nil)" :expected "false"} - {:suite "walk" :expr "(vector? (first {:a 1}))" :expected "true"} - {:suite "walk" :expr "(vector? (first (seq {:a 1})))" :expected "true"} - {:suite "walk" :expr "(map-entry? (first {:a 1}))" :expected "true"} - {:suite "walk" :expr "(= (first {:a 1}) [:a 1])" :expected "true"} - {:suite "walk" :expr "(vector? [1 2])" :expected "true"} - {:suite "walk" :expr "(vector? (rest [1 2 3]))" :expected "false"} - {:suite "walk" :expr "(do (require (quote [clojure.walk :as w])) (w/postwalk (fn [x] (if (number? x) (inc x) x)) {:a 1}))" :expected "{:a 2}"} - {:suite "walk" :expr "(do (require (quote [clojure.walk :as w])) (w/keywordize-keys {\"a\" 1}))" :expected "{:a 1}"} - {:suite "walk" :expr "(do (require (quote [clojure.walk :as w])) (= {\"a\" 1} (w/stringify-keys {:a 1})))" :expected "true"} - {:suite "walk" :expr "(do (require (quote [clojure.walk :as w])) (w/postwalk-replace {'x 2} '(+ x x)))" :expected "(+ 2 2)"} - {:suite "walk" :expr "(do (require (quote [clojure.walk :as w])) (w/postwalk (fn [n] (if (symbol? n) :a n)) '(x y)))" :expected "(:a :a)"} - {:suite "walk" :expr "(do (require (quote [clojure.walk :as w])) (w/prewalk-replace {'* '* 'y 3} '(* y y)))" :expected "(* 3 3)"} - {:suite "walk" :expr "(do (require (quote [clojure.walk :as w])) (w/postwalk-replace {:a 1 :b 2} '(:a [:b :a])))" :expected "(1 [2 1])"} - {:suite "walk" :expr "(do (require (quote [clojure.walk :as w])) (w/postwalk-replace {1 :one} [1 2 1]))" :expected "[:one 2 :one]"} - {:suite "walk" :expr "(do (require (quote [clojure.template :as t])) (t/apply-template '[x y] '(+ x y) '(1 2)))" :expected "(+ 1 2)"} - {:suite "shadowing" :expr "(let [if (fn [a b c] :L)] (if true 1 2))" :expected "1"} - {:suite "shadowing" :expr "(let [quote (fn [_] :L)] (quote x))" :expected "x"} - {:suite "shadowing" :expr "(let [if 5] if)" :expected "5"} - {:suite "shadowing" :expr "((fn [if] (+ if 1)) 7)" :expected "8"} - {:suite "shadowing" :expr "(let [when (fn [a b] :local)] (when 1 2))" :expected ":local"} - {:suite "macroexpand" :expr "(do (when true (defmacro m6 [x] `(* ~x 2))) (m6 3))" :expected "6"} - {:suite "macroexpand" :expr "(letfn [(ev? [n] (if (zero? n) true (od? (dec n)))) (od? [n] (if (zero? n) false (ev? (dec n))))] (ev? 10))" :expected "true"} - {:suite "deftype-mutable" :expr "(do (defprotocol IB (gv [_]) (sv [_ v])) (deftype B [^:unsynchronized-mutable val] IB (gv [_] val) (sv [_ v] (set! val v))) (let [b (->B 1)] (sv b 42) (gv b)))" :expected "42"} - {:suite "deftype-mutable" :expr "(do (defprotocol IC (bump [_]) (cur [_])) (deftype C [^:unsynchronized-mutable n] IC (bump [this] (set! n (inc n)) n) (cur [_] n)) (let [c (->C 5)] (bump c) (bump c) (bump c) (cur c)))" :expected "8"} - {:suite "deftype-mutable" :expr "(do (defprotocol IH (g [_]) (s [_ v])) (deftype H [^:volatile-mutable st] IH (g [_] st) (s [this v] (set! (.-st this) v))) (let [h (->H :old)] (s h :new) (g h)))" :expected ":new"} - {:suite "hostshim" :expr "(do (__register-class-ctor! \"Box1\" (fn [v] (let [t (jolt.host/tagged-table :my/box)] (jolt.host/ref-put! t :v v) t))) (__register-class-methods! :my/box {\"getV\" (fn [self] (jolt.host/ref-get self :v))}) (.getV (Box1. 42)))" :expected "42"} - {:suite "hostshim" :expr "(do (__register-class-ctor! \"Box2\" (fn [v] (let [t (jolt.host/tagged-table :my/box2)] (jolt.host/ref-put! t :v v) t))) (__register-class-methods! :my/box2 {\"add\" (fn [self n] (+ n (jolt.host/ref-get self :v)))}) (.add (Box2. 10) 5))" :expected "15"} - {:suite "hostshim" :expr "(do (__register-class-ctor! \"Box3\" (fn [] (jolt.host/tagged-table :my/box3))) (__register-instance-check! (fn [cn val] (if (= cn \"Box3\") (= :my/box3 (jolt.host/ref-get val :jolt/type)) nil))) (instance? Box3 (Box3.)))" :expected "true"} - {:suite "hostshim" :expr "(do (__register-class-ctor! \"Box4\" (fn [] (jolt.host/tagged-table :my/box4))) (__register-instance-check! (fn [cn val] (if (= cn \"Box4\") (= :my/box4 (jolt.host/ref-get val :jolt/type)) nil))) (instance? Box4 \"not-a-box\"))" :expected "false"} - {:suite "hostshim" :expr "(jolt.host/table? (jolt.host/tagged-table :t))" :expected "true"} - {:suite "hostshim" :expr "(jolt.host/table? \"x\")" :expected "false"} - {:suite "bytes" :expr "(seq (byte-array \"hi\"))" :expected "(104 105)"} - {:suite "bytes" :expr "(seq (byte-array (.getBytes \"AB\" \"UTF-8\")))" :expected "(65 66)"} - {:suite "bytes" :expr "(alength (byte-array (.getBytes \"hello\" \"UTF-8\")))" :expected "5"} - {:suite "bytes" :expr "(String. (byte-array [104 105]))" :expected "hi"} - {:suite "bytes" :expr "(String. (byte-array [104 105]) \"UTF-8\")" :expected "hi"} - {:suite "bytes" :expr "(int (first (String. (byte-array [200]) \"ISO-8859-1\")))" :expected "200"} - {:suite "bytes" :expr "(String. (.getBytes \"round\" \"UTF-8\") \"UTF-8\")" :expected "round"} - {:suite "deftype-map" :expr "(do (deftype Mp [m] clojure.lang.IPersistentMap (without [_ k] m)) [(map? (->Mp 1)) (record? (->Mp 1))])" :expected "[true false]"} - {:suite "deftype-map" :expr "(do (deftype Op [s]) [(map? (->Op 1)) (record? (->Op 1)) (coll? (->Op 1))])" :expected "[false false false]"} - {:suite "deftype-map" :expr "(do (deftype Lc [xs] clojure.lang.Counted (count [_] (count xs)) clojure.lang.Seqable (seq [_] (seq xs))) [(coll? (->Lc [1 2])) (count (->Lc [1 2])) (vec (seq (->Lc [1 2])))])" :expected "[false 2 [1 2]]"} - {:suite "deftype-map" :expr "(do (defrecord Dr [a b]) [(map? (->Dr 1 2)) (record? (->Dr 1 2)) (coll? (->Dr 1 2))])" :expected "[true true true]"} - {:suite "macro-args" :expr "(do (defmacro sm [x] [(set? x) (map? x)]) (sm #{1 2}))" :expected "[true false]"} - {:suite "macro-args" :expr "(do (defmacro ws [x] (conj x :z)) (= #{1 :z} (ws #{1})))" :expected "true"} - {:suite "macro-args" :expr "(do (defmacro vm [x] (vector? x)) (vm [1 2]))" :expected "true"} - {:suite "deftype-method" :expr "(do (defprotocol P (m [_ o])) (defrecord R [n] P (m [_ _] n)) (m (->R 5) :x))" :expected "5"} - {:suite "deftype-method" :expr "(do (defprotocol P2 (m2 [_ o])) (deftype T [n] P2 (m2 [_ _] n)) (m2 (->T 7) :x))" :expected "7"} - {:suite "protocol-host" :expr "(do (defprotocol Q (e [_])) (extend-protocol Q clojure.lang.Var (e [_] :var)) [(satisfies? Q (var map)) (e (var map))])" :expected "[true :var]"} - - ;; Clojure 1.13 (1.13.0-alpha1) parity. Ahead of the JVM 1.12.5 the corpus - ;; certifies against, so these live here rather than as certified corpus rows. - {:suite "clj-1.13 req!" :expr "(req! {:a 1} :a)" :expected "1"} - {:suite "clj-1.13 req!" :expr "(req! [10 20 30] 1)" :expected "20"} - {:suite "clj-1.13 req!" :expr "(nil? (req! {:a nil} :a))" :expected "true"} - {:suite "clj-1.13 req!" :expr "(req! {:a 1} :b)" :expected :throws} - {:suite "clj-1.13 amp-binding" :expr "(let [& 42] &)" :expected :throws} - {:suite "clj-1.13 amp-binding" :expr "(loop [& 42] &)" :expected :throws} - {:suite "clj-1.13 checked-keys" :expr "(let [{:keys! [a b]} {:a 1 :b 2}] [a b])" :expected "[1 2]"} - {:suite "clj-1.13 checked-keys" :expr "(let [{:keys! [a b]} {:a 1}] [a b])" :expected :throws} - {:suite "clj-1.13 checked-keys" :expr "(nil? (let [{:keys! [a]} {:a nil}] a))" :expected "true"} - {:suite "clj-1.13 checked-keys" :expr "(let [{:strs! [a]} {\"a\" 5}] a)" :expected "5"} - {:suite "clj-1.13 checked-keys" :expr "(let [{:keys! [a & b]} {:a 1 :b 2}] a)" :expected "1"} - {:suite "clj-1.13 checked-keys" :expr "(let [{:keys! [a & b]} {:a 1}] a)" :expected :throws} - {:suite "clj-1.13 checked-keys" :expr "(let [{:keys [a & b]} {:a 1 :b 2}] a)" :expected "1"} - {:suite "clj-1.13 checked-keys" :expr "(let [{:foo/keys! [a]} {:foo/a 7}] a)" :expected "7"} - {:suite "clj-1.13 checked-keys" :expr "(let [{:foo/keys! [a]} {}] a)" :expected :throws} - {:suite "clj-1.13 array-map-64" :expr "(keys {:a 1 :b 2 :c 3 :d 4 :e 5 :f 6 :g 7 :h 8 :i 9 :j 10})" :expected "(:a :b :c :d :e :f :g :h :i :j)"} - {:suite "clj-1.13 array-map-64" :expr "(= (map (fn [i] (keyword (str \"k\" i))) (range 20)) (keys (into {} (map (fn [i] [(keyword (str \"k\" i)) i]) (range 20)))))" :expected "true"} - {:suite "clj-1.13 array-map-64" :expr "(= (map (fn [i] (keyword (str \"k\" i))) (range 64)) (keys (reduce (fn [m i] (assoc m (keyword (str \"k\" i)) i)) {} (range 64))))" :expected "true"} - {:suite "clj-1.13 array-map-64" :expr "(= (map (fn [i] (keyword (str \"k\" i))) (range 65)) (keys (into {} (map (fn [i] [(keyword (str \"k\" i)) i]) (range 65)))))" :expected "false"} -] diff --git a/test/chez/values-test.ss b/test/chez/values-test.ss deleted file mode 100644 index f0ca28c..0000000 --- a/test/chez/values-test.ss +++ /dev/null @@ -1,68 +0,0 @@ -;; Tests for the Jolt value model on Chez (nil/truthiness, interned keywords, -;; symbols, exactness-aware =, hashing). Run from repo root: -;; chez --script test/chez/values-test.ss -(import (chezscheme)) -(load "host/chez/values.ss") - -(define total 0) -(define fails 0) -(define (ok name pred) - (set! total (+ total 1)) - (unless pred (set! fails (+ fails 1)) (printf "FAIL: ~a\n" name))) - -;; nil distinct from #f and '() -(ok "nil not #f" (not (eq? jolt-nil #f))) -(ok "nil not '()" (not (eq? jolt-nil '()))) -(ok "nil? jolt-nil" (jolt-nil? jolt-nil)) -(ok "nil? not on #f" (not (jolt-nil? #f))) - -;; truthiness: only nil and false falsey -(ok "nil falsey" (not (jolt-truthy? jolt-nil))) -(ok "false falsey" (not (jolt-truthy? #f))) -(ok "true truthy" (jolt-truthy? #t)) -(ok "0 truthy" (jolt-truthy? 0)) -(ok "empty-str truthy" (jolt-truthy? "")) -(ok "empty-list truthy" (jolt-truthy? '())) - -;; keywords interned -> identity -(ok "kw eq" (eq? (keyword #f "foo") (keyword #f "foo"))) -(ok "kw ns eq" (eq? (keyword "a" "foo") (keyword "a" "foo"))) -(ok "kw diff ns" (not (eq? (keyword "a" "foo") (keyword #f "foo")))) -(ok "kw?" (keyword? (keyword #f "x"))) -(ok "kw not sym" (not (jolt-symbol? (keyword #f "x")))) - -;; symbols NOT interned but jolt= by ns/name -(ok "sym not eq" (not (eq? (jolt-symbol #f "x") (jolt-symbol #f "x")))) -(ok "sym jolt=" (jolt= (jolt-symbol #f "x") (jolt-symbol #f "x"))) -(ok "sym diff name" (not (jolt= (jolt-symbol #f "x") (jolt-symbol #f "y")))) -(ok "sym?" (jolt-symbol? (jolt-symbol "ns" "n"))) - -;; numbers: exactness-aware = (Clojure semantics) -(ok "1 = 1" (jolt= 1 1)) -(ok "1 not= 1.0" (not (jolt= 1 1.0))) -(ok "1.0 = 1.0" (jolt= 1.0 1.0)) -(ok "ratio =" (jolt= 1/2 1/2)) -(ok "bigint=int exact" (jolt= 2 (expt 2 1))) -(ok "= variadic" (jolt= 3 3 3)) -(ok "= variadic false" (not (jolt= 3 3 4))) - -;; strings / chars -(ok "str =" (jolt= "ab" "ab")) -(ok "str !=" (not (jolt= "ab" "ac"))) -(ok "char =" (jolt= #\a #\a)) - -;; hashing consistent with = -(ok "hash kw stable" (= (jolt-hash (keyword #f "k")) (jolt-hash (keyword #f "k")))) -(ok "hash sym stable" (= (jolt-hash (jolt-symbol #f "k")) (jolt-hash (jolt-symbol #f "k")))) -(ok "hash 1 != 1.0" (not (= (jolt-hash 1) (jolt-hash 1.0)))) -(ok "hash str stable" (= (jolt-hash "abc") (jolt-hash "abc"))) - -;; regression: keyword intern key must not collide across ns/name boundary -(ok "kw no boundary collide" (not (eq? (keyword "a" "b/c") (keyword "a/b" "c")))) -;; regression: jolt-hash must not throw on non-finite floats -(ok "hash +inf ok" (number? (jolt-hash +inf.0))) -(ok "hash +nan ok" (number? (jolt-hash +nan.0))) -(ok "hash inf != exact" (not (= (jolt-hash +inf.0) (jolt-hash 0)))) - -(printf "values-test: ~a/~a passed\n" (- total fails) total) -(exit (if (> fails 0) 1 0)) diff --git a/test/clojure-stdlib/clojure/data_test/diff.cljc b/test/clojure-stdlib/clojure/data_test/diff.cljc new file mode 100644 index 0000000..0b0415a --- /dev/null +++ b/test/clojure-stdlib/clojure/data_test/diff.cljc @@ -0,0 +1,149 @@ +(ns clojure.data-test.diff + (:require [clojure.test :refer [deftest is testing]] +;; NOTE (jolt): sequential-diff expectations corrected to match real Clojure — +;; clojure.data pads only to the max differing index (e.g. (diff [1 2 3] [1 9 3]) +;; -> a=[nil 2], not [nil 2 nil]). The upstream clojurust fixtures had this wrong. + [clojure.data :refer [diff]])) + +;; ── Atoms ──────────────────────────────────────────────────────────────────── + +(deftest test-diff-equal-atoms + (testing "equal atoms" + (is (= [nil nil :a] (diff :a :a))) + (is (= [nil nil 1] (diff 1 1))) + (is (= [nil nil "hello"] (diff "hello" "hello"))) + (is (= [nil nil nil] (diff nil nil))) + (is (= [nil nil true] (diff true true))))) + +(deftest test-diff-unequal-atoms + (testing "unequal atoms" + (is (= [:a :b nil] (diff :a :b))) + (is (= [1 2 nil] (diff 1 2))) + (is (= ["a" "b" nil] (diff "a" "b"))) + (is (= [nil 1 nil] (diff nil 1))) + (is (= [true false nil] (diff true false))))) + +;; ── Maps ───────────────────────────────────────────────────────────────────── + +(deftest test-diff-equal-maps + (testing "equal maps" + (is (= [nil nil {:a 1 :b 2}] (diff {:a 1 :b 2} {:a 1 :b 2}))) + (is (= [nil nil {}] (diff {} {}))))) + +(deftest test-diff-maps-only-in-a + (testing "keys only in a" + (let [[a b both] (diff {:a 1 :b 2} {:a 1})] + (is (= {:b 2} a)) + (is (nil? b)) + (is (= {:a 1} both))))) + +(deftest test-diff-maps-only-in-b + (testing "keys only in b" + (let [[a b both] (diff {:a 1} {:a 1 :b 2})] + (is (nil? a)) + (is (= {:b 2} b)) + (is (= {:a 1} both))))) + +(deftest test-diff-maps-different-values + (testing "same keys, different values" + (let [[a b both] (diff {:a 1 :b 2} {:a 1 :b 9})] + (is (= {:b 2} a)) + (is (= {:b 9} b)) + (is (= {:a 1} both))))) + +(deftest test-diff-maps-nested + (testing "nested maps" + (let [[a b both] (diff {:a {:x 1 :y 2}} {:a {:x 1 :z 3}})] + (is (= {:a {:y 2}} a)) + (is (= {:a {:z 3}} b)) + (is (= {:a {:x 1}} both))))) + +(deftest test-diff-maps-disjoint + (testing "completely disjoint maps" + (let [[a b both] (diff {:a 1} {:b 2})] + (is (= {:a 1} a)) + (is (= {:b 2} b)) + (is (nil? both))))) + +;; ── Sets ───────────────────────────────────────────────────────────────────── + +(deftest test-diff-equal-sets + (testing "equal sets" + (is (= [nil nil #{1 2 3}] (diff #{1 2 3} #{1 2 3}))) + (is (= [nil nil #{}] (diff #{} #{}))))) + +(deftest test-diff-sets + (testing "overlapping sets" + (let [[a b both] (diff #{1 2 3} #{2 3 4})] + (is (= #{1} a)) + (is (= #{4} b)) + (is (= #{2 3} both))))) + +(deftest test-diff-disjoint-sets + (testing "disjoint sets" + (let [[a b both] (diff #{1 2} #{3 4})] + (is (= #{1 2} a)) + (is (= #{3 4} b)) + (is (nil? both))))) + +;; ── Vectors / Sequential ──────────────────────────────────────────────────── + +(deftest test-diff-equal-vectors + (testing "equal vectors" + (is (= [nil nil [1 2 3]] (diff [1 2 3] [1 2 3]))) + (is (= [nil nil []] (diff [] []))))) + +(deftest test-diff-vectors-same-length + (testing "same length, different elements" + (let [[a b both] (diff [1 2 3] [1 9 3])] + (is (= [nil 2] a)) + (is (= [nil 9] b)) + (is (= [1 nil 3] both))))) + +(deftest test-diff-vectors-different-length + (testing "different lengths" + (let [[a b both] (diff [1 2 3] [1 2])] + (is (= [nil nil 3] a)) + (is (nil? b)) + (is (= [1 2] both))) + (let [[a b both] (diff [1] [1 2 3])] + (is (nil? a)) + (is (= [nil 2 3] b)) + (is (= [1] both))))) + +(deftest test-diff-lists + (testing "lists treated as sequential" + (let [[a b both] (diff '(1 2 3) '(1 9 3))] + (is (= [nil 2] a)) + (is (= [nil 9] b)) + (is (= [1 nil 3] both))))) + +;; ── Mixed types ───────────────────────────────────────────────────────────── + +(deftest test-diff-mixed-types + (testing "different partition types treated as atoms" + (is (= [{:a 1} [1 2] nil] (diff {:a 1} [1 2]))) + (is (= [#{1} [1] nil] (diff #{1} [1]))) + (is (= [1 :a nil] (diff 1 :a))))) + +;; ── Nil handling ──────────────────────────────────────────────────────────── + +(deftest test-diff-nil + (testing "nil vs non-nil" + (is (= [nil 1 nil] (diff nil 1))) + (is (= [1 nil nil] (diff 1 nil))) + (is (= [nil {:a 1} nil] (diff nil {:a 1}))))) + +;; ── Deeply nested ─────────────────────────────────────────────────────────── + +(deftest test-diff-deeply-nested + (testing "deeply nested structures" + (let [[a b both] (diff {:a {:b {:c 1}}} {:a {:b {:c 2}}})] + (is (= {:a {:b {:c 1}}} a)) + (is (= {:a {:b {:c 2}}} b)) + (is (nil? both)))) + (testing "deeply nested with shared keys" + (let [[a b both] (diff {:a {:b 1 :c 2}} {:a {:b 1 :c 9}})] + (is (= {:a {:c 2}} a)) + (is (= {:a {:c 9}} b)) + (is (= {:a {:b 1}} both))))) diff --git a/test/clojure-stdlib/clojure/edn_test/read_string.cljc b/test/clojure-stdlib/clojure/edn_test/read_string.cljc new file mode 100644 index 0000000..515af5e --- /dev/null +++ b/test/clojure-stdlib/clojure/edn_test/read_string.cljc @@ -0,0 +1,107 @@ +(ns clojure.edn-test.read-string + (:require [clojure.edn :as edn] + [clojure.test :refer [are deftest is testing]])) + +(deftest test-read-string-scalars + (testing "nil, booleans" + (is (nil? (edn/read-string "nil"))) + (is (true? (edn/read-string "true"))) + (is (false? (edn/read-string "false")))) + + (testing "integers" + (is (= 0 (edn/read-string "0"))) + (is (= 42 (edn/read-string "42"))) + (is (= -1 (edn/read-string "-1"))) + (is (= 1000000000000 (edn/read-string "1000000000000")))) + + (testing "floats" + (is (= 3.14 (edn/read-string "3.14"))) + (is (= -0.5 (edn/read-string "-0.5"))) + (is (= 1.0 (edn/read-string "1.0")))) + + (testing "bigints" + (is (= 42N (edn/read-string "42N")))) + + (testing "bigdecimals" + (is (= 3.14M (edn/read-string "3.14M")))) + + (testing "strings" + (is (= "" (edn/read-string "\"\""))) + (is (= "hello" (edn/read-string "\"hello\""))) + (is (= "line1\nline2" (edn/read-string "\"line1\\nline2\""))) + (is (= "tab\there" (edn/read-string "\"tab\\there\"")))) + + (testing "characters" + (is (= \a (edn/read-string "\\a"))) + (is (= \newline (edn/read-string "\\newline"))) + (is (= \space (edn/read-string "\\space"))) + (is (= \tab (edn/read-string "\\tab")))) + + (testing "keywords" + (is (= :foo (edn/read-string ":foo"))) + (is (= :bar/baz (edn/read-string ":bar/baz")))) + + (testing "symbols" + (is (= 'foo (edn/read-string "foo"))) + (is (= 'bar/baz (edn/read-string "bar/baz"))))) + +(deftest test-read-string-collections + (testing "vectors" + (is (= [] (edn/read-string "[]"))) + (is (= [1 2 3] (edn/read-string "[1 2 3]"))) + (is (= [1 [2 3] 4] (edn/read-string "[1 [2 3] 4]")))) + + (testing "lists" + (is (= '() (edn/read-string "()"))) + (is (= '(1 2 3) (edn/read-string "(1 2 3)"))) + (is (= '(+ 1 2) (edn/read-string "(+ 1 2)")))) + + (testing "maps" + (is (= {} (edn/read-string "{}"))) + (is (= {:a 1} (edn/read-string "{:a 1}"))) + (is (= {:a 1 :b 2} (edn/read-string "{:a 1 :b 2}"))) + (is (= {:nested {:deep true}} (edn/read-string "{:nested {:deep true}}")))) + + (testing "sets" + (is (= #{} (edn/read-string "#{}"))) + (is (= #{1 2 3} (edn/read-string "#{1 2 3}")))) + + (testing "mixed nested" + (is (= {:users [{:name "Alice" :age 30} + {:name "Bob" :age 25}]} + (edn/read-string "{:users [{:name \"Alice\" :age 30} {:name \"Bob\" :age 25}]}"))))) + +(deftest test-read-string-tagged-literals + (testing "#uuid" + (let [u (edn/read-string "#uuid \"f81d4fae-7dec-11d0-a765-00a0c91e6bf6\"")] + (is (uuid? u)) + (is (= u (edn/read-string "#uuid \"f81d4fae-7dec-11d0-a765-00a0c91e6bf6\"")))))) + +(deftest test-read-string-eof + (testing "empty string with :eof option" + (is (= :eof (edn/read-string {:eof :eof} ""))) + (is (= nil (edn/read-string {:eof nil} ""))) + (is (= 42 (edn/read-string {:eof 42} "")))) + + (testing "whitespace-only with :eof option" + (is (= :done (edn/read-string {:eof :done} " ")))) + + (testing "nil input returns nil" + (is (nil? (edn/read-string nil))))) + +(deftest test-read-string-comments + (testing "comments are skipped" + (is (= 42 (edn/read-string "; this is a comment\n42")))) + + (testing "discard reader macro" + (is (= 2 (edn/read-string "#_ 1 2"))))) + +(deftest test-read-string-only-first-form + (testing "reads only the first form" + (is (= 1 (edn/read-string "1 2 3"))) + (is (= :a (edn/read-string ":a :b :c"))))) + +(deftest test-read-string-ratios + (testing "ratios" + (is (= 1/2 (edn/read-string "1/2"))) + (is (= 3/4 (edn/read-string "3/4"))))) diff --git a/test/clojure-stdlib/clojure/walk_test/walk.cljc b/test/clojure-stdlib/clojure/walk_test/walk.cljc new file mode 100644 index 0000000..49a584e --- /dev/null +++ b/test/clojure-stdlib/clojure/walk_test/walk.cljc @@ -0,0 +1,101 @@ +(ns clojure.walk-test.walk + (:require [clojure.test :refer [deftest is testing]] + [clojure.walk :as w])) + +(deftest test-walk + (testing "walk with identity" + (is (= [1 2 3] (w/walk identity identity [1 2 3]))) + (is (= '(1 2 3) (w/walk identity identity '(1 2 3)))) + (is (= #{1 2 3} (w/walk identity identity #{1 2 3})))) + + (testing "walk with inner transform" + (is (= [2 3 4] (w/walk inc identity [1 2 3]))) + (is (= [2 3 4] (w/walk inc vec [1 2 3])))) + + (testing "walk with outer transform" + (is (= [1 2 3] (w/walk identity vec '(1 2 3)))))) + +(deftest test-postwalk + (testing "postwalk with numbers" + (is (= [2 3 4] (w/postwalk #(if (number? %) (inc %) %) [1 2 3])))) + + (testing "postwalk with nested structures" + (is (= [2 [3 4] 5] + (w/postwalk #(if (number? %) (inc %) %) [1 [2 3] 4])))) + + (testing "postwalk preserves types" + (is (vector? (w/postwalk identity [1 2 3]))) + (is (list? (w/postwalk identity '(1 2 3)))) + (is (set? (w/postwalk identity #{1 2 3}))) + (is (map? (w/postwalk identity {:a 1 :b 2})))) + + (testing "postwalk on maps" + (is (= {:a 2 :b 3} + (w/postwalk #(if (number? %) (inc %) %) {:a 1 :b 2})))) + + (testing "postwalk on empty collections" + (is (= [] (w/postwalk identity []))) + (is (= {} (w/postwalk identity {}))) + (is (= #{} (w/postwalk identity #{}))) + (is (= '() (w/postwalk identity '()))))) + +(deftest test-prewalk + (testing "prewalk with numbers" + (is (= [2 3 4] (w/prewalk #(if (number? %) (inc %) %) [1 2 3])))) + + (testing "prewalk with nested structures" + (is (= [2 [3 4] 5] + (w/prewalk #(if (number? %) (inc %) %) [1 [2 3] 4])))) + + (testing "prewalk transforms before descending" + ;; prewalk applies f to the outer form first, so we can replace + ;; entire subtrees before they are walked + (is (= [:replaced] + (w/prewalk #(if (= % [1 2 3]) [:replaced] %) [1 2 3]))))) + +(deftest test-keywordize-keys + (testing "basic keywordize" + (is (= {:a 1 :b 2} (w/keywordize-keys {"a" 1 "b" 2})))) + + (testing "nested keywordize" + (is (= {:a {:b 2}} (w/keywordize-keys {"a" {"b" 2}})))) + + (testing "non-string keys unchanged" + (is (= {:a 1 42 2} (w/keywordize-keys {"a" 1 42 2})))) + + (testing "already keyword keys unchanged" + (is (= {:a 1} (w/keywordize-keys {:a 1}))))) + +(deftest test-stringify-keys + (testing "basic stringify" + (is (= {"a" 1 "b" 2} (w/stringify-keys {:a 1 :b 2})))) + + (testing "nested stringify" + (is (= {"a" {"b" 2}} (w/stringify-keys {:a {:b 2}})))) + + (testing "non-keyword keys unchanged" + (is (= {"a" 1 42 2} (w/stringify-keys {:a 1 42 2}))))) + +(deftest test-postwalk-replace + (testing "basic replacement" + (is (= [:x :y :c] (w/postwalk-replace {:a :x :b :y} [:a :b :c])))) + + (testing "nested replacement" + (is (= [:x [:y :c]] (w/postwalk-replace {:a :x :b :y} [:a [:b :c]])))) + + (testing "no matches" + (is (= [1 2 3] (w/postwalk-replace {:a :x} [1 2 3])))) + + (testing "empty smap" + (is (= [1 2 3] (w/postwalk-replace {} [1 2 3]))))) + +(deftest test-prewalk-replace + (testing "basic replacement" + (is (= [:x :y :c] (w/prewalk-replace {:a :x :b :y} [:a :b :c])))) + + (testing "nested replacement" + (is (= [:x [:y :c]] (w/prewalk-replace {:a :x :b :y} [:a [:b :c]])))) + + (testing "replaces before descending" + ;; prewalk-replace replaces the whole form first, then walks children + (is (= :replaced (w/prewalk-replace {[:a :b] :replaced} [:a :b]))))) diff --git a/test/clojure-stdlib/clojure/zip_test/zip.cljc b/test/clojure-stdlib/clojure/zip_test/zip.cljc new file mode 100644 index 0000000..076eb79 --- /dev/null +++ b/test/clojure-stdlib/clojure/zip_test/zip.cljc @@ -0,0 +1,122 @@ +(ns clojure.zip-test.zip + (:require [clojure.test :refer [deftest is testing run-tests]] + [clojure.zip :as zip])) + +(deftest test-vector-zip-navigation + (let [data [[1 2] [3 [4 5]]] + z (zip/vector-zip data)] + (testing "root node" + (is (= (zip/node z) [[1 2] [3 [4 5]]])) + (is (zip/branch? z))) + (testing "down" + (is (= (zip/node (zip/down z)) [1 2]))) + (testing "right" + (is (= (zip/node (zip/right (zip/down z))) [3 [4 5]]))) + (testing "down into nested" + (is (= (zip/node (zip/down (zip/right (zip/down z)))) 3))) + (testing "up returns parent" + (is (= (zip/node (zip/up (zip/down z))) [[1 2] [3 [4 5]]]))) + (testing "rights" + (is (= (zip/rights (zip/down z)) '([3 [4 5]])))) + (testing "lefts" + (is (= (zip/lefts (zip/right (zip/down z))) [[1 2]]))))) + +(deftest test-vector-zip-rightmost-leftmost + (let [z (zip/vector-zip [1 2 3])] + (testing "rightmost" + (is (= (zip/node (zip/rightmost (zip/down z))) 3))) + (testing "leftmost" + (is (= (zip/node (zip/leftmost (zip/rightmost (zip/down z)))) 1))))) + +(deftest test-seq-zip-navigation + (let [z (zip/seq-zip '(1 (2 3) 4))] + (testing "root" + (is (= (zip/node z) '(1 (2 3) 4)))) + (testing "down" + (is (= (zip/node (zip/down z)) 1))) + (testing "right" + (is (= (zip/node (zip/right (zip/down z))) '(2 3)))) + (testing "down into nested list" + (is (= (zip/node (zip/down (zip/right (zip/down z)))) 2))))) + +(deftest test-path + (let [z (zip/vector-zip [[1 2] [3 4]])] + (testing "path at root is nil" + (is (nil? (zip/path z)))) + (testing "path one level down" + (is (= (zip/path (zip/down z)) [[[1 2] [3 4]]]))) + (testing "path two levels down" + (is (= (zip/path (zip/down (zip/down z))) + [[[1 2] [3 4]] [1 2]]))))) + +(deftest test-edit + (let [z (zip/vector-zip [1 [2 3] [4 5]])] + (testing "edit a leaf" + (let [loc (-> z zip/down zip/right zip/down) + edited (zip/edit loc inc)] + (is (= (zip/root edited) [1 [3 3] [4 5]])))) + (testing "edit a branch" + (let [loc (-> z zip/down zip/right) + edited (zip/edit loc (fn [x] (vec (map inc x))))] + (is (= (zip/root edited) [1 [3 4] [4 5]])))))) + +(deftest test-replace + (let [z (zip/vector-zip '[a b c])] + (is (= (zip/root (zip/replace (zip/down z) 'x)) + '[x b c])))) + +(deftest test-insert-left-right + (let [z (zip/vector-zip [1 2 3]) + loc (-> z zip/down zip/right)] + (testing "insert-left" + (is (= (zip/root (zip/insert-left loc 'x)) [1 'x 2 3]))) + (testing "insert-right" + (is (= (zip/root (zip/insert-right loc 'y)) [1 2 'y 3]))))) + +(deftest test-insert-child-append-child + (let [z (zip/vector-zip [1 2 3])] + (testing "insert-child" + (is (= (zip/root (zip/insert-child z 0)) [0 1 2 3]))) + (testing "append-child" + (is (= (zip/root (zip/append-child z 4)) [1 2 3 4]))))) + +(deftest test-remove + (let [z (zip/vector-zip [1 2 3]) + loc (-> z zip/down zip/right)] + (is (= (zip/root (zip/remove loc)) [1 3])))) + +(deftest test-next-traversal + (let [z (zip/vector-zip [1 [2 3]])] + (testing "next enumerates depth-first" + (is (= (loop [loc z, acc []] + (if (zip/end? loc) + acc + (recur (zip/next loc) (conj acc (zip/node loc))))) + [[1 [2 3]] 1 [2 3] 2 3]))))) + +(deftest test-end? + (let [z (zip/vector-zip [1 2])] + (testing "not end at start" + (is (not (zip/end? z)))) + (testing "end after full traversal" + (is (zip/end? (-> z zip/next zip/next zip/next)))))) + +(deftest test-prev + (let [z (zip/vector-zip [1 [2 3]])] + (testing "prev from second child" + (let [loc (-> z zip/next zip/next)] + (is (= (zip/node loc) [2 3])) + (is (= (zip/node (zip/prev loc)) 1)))) + (testing "prev from leaf inside nested" + (let [loc (-> z zip/next zip/next zip/next)] + (is (= (zip/node loc) 2)) + (is (= (zip/node (zip/prev loc)) [2 3])))))) + +(deftest test-root-after-edits + (testing "root unwinds all the way after deep edits" + (let [z (zip/vector-zip [[1 2] [3 [4 5]]]) + loc (-> z zip/down zip/right zip/down zip/right zip/down) + edited (zip/edit loc inc)] + (is (= (zip/root edited) [[1 2] [3 [5 5]]]))))) + +(run-tests) diff --git a/test/conformance/README.md b/test/conformance/README.md deleted file mode 100644 index aded8b8..0000000 --- a/test/conformance/README.md +++ /dev/null @@ -1,63 +0,0 @@ -# Conformance: certifying the corpus against reference Clojure - -> **See [SPEC.md](SPEC.md)** for the full host-neutral language-spec contract: the -> corpus schema, conformance levels, the feature profile, and how to host jolt on a -> new runtime. This README covers the certification tooling specifically. - - -The corpus (`test/chez/corpus.edn`) is jolt's host-neutral behavioral suite — one -row per case: `{:suite :label :expected :actual}`, where `:actual` is a Clojure -source expression and `:expected` its result (or `:throws`). The runtime harness -(`host/chez/run-corpus.ss`, invoked by `make corpus`) replays it on Chez and -compares by value-equality. - -Every `:expected` is sourced from reference JVM Clojure, so the corpus is both a -regression suite and a *specification* certified against Clojure rather than -against its authors' beliefs. This directory holds the certification tooling that -closes that gap. - -## What's here - -- **`certify.clj`** — runs every corpus row's `:actual` and `:expected` through - **reference JVM Clojure** (each in a fresh `user` namespace, output/stdin sunk, a - 5s per-case watchdog) and compares with Clojure's `=`. It buckets each row: - - `certified` / `certified-throws` — jolt's `:expected` matches real Clojure - - `divergent` — both evaluate but jolt's `:expected` disagrees with Clojure - - `throws-mismatch` — jolt and Clojure disagree on whether it throws - - `jvm-error` — `:actual` isn't runnable on vanilla Clojure (host-coupled / - jolt-specific) — informational, not certifiable - - `read-error` / `timeout` — won't read on the JVM reader, or ran too long - -- **`known-divergences.edn`** — every current divergence, classified. Most are - **deliberate** jolt-specific or host-model deltas (see `:legend`): the all-double - numeric model, snapshot-heap concurrency, the no-JVM host model, jolt reader - features, the jolt printer, intentional strictness. A few are genuine **`:bug`** - entries with a tracked bead. These categories become the `:features` flags in - conformance inc3. - -`make certify` is the gate wrapper. It skips cleanly when `clojure` (JVM) is not -installed; otherwise it runs `certify.clj` and fails the build on a **NEW** -(unclassified) divergence or a **stale** allowlist entry. Flaky entries (JVM -result is timing-dependent, e.g. `future-cancel`) are tolerated either way. - -## Running - -```sh -make certify # the gate wrapper (skips if clojure absent) -clojure -M test/conformance/certify.clj # gate directly (exit≠0 on new/stale) -clojure -M test/conformance/certify.clj test/chez/corpus.edn --edn /tmp/report.edn # full machine-readable report -``` - -## Current state - -Of ~2740 vanilla-certifiable rows, **>2730 match reference Clojure exactly**; the -handful of divergences are all classified (deliberate deltas plus a few tracked -bugs). The corpus is trustworthy as a spec, with the host-specific deltas made -explicit rather than hidden. - -## Adding / changing cases - -When you add corpus rows or change behavior, re-run the certifier. A NEW divergence -means either a real bug (file it, tag the allowlist entry `:bug` + `:bead`) or a -deliberate delta (classify it). A stale entry means a divergence was fixed — remove -it from `known-divergences.edn`. diff --git a/test/conformance/SPEC.md b/test/conformance/SPEC.md deleted file mode 100644 index 7509686..0000000 --- a/test/conformance/SPEC.md +++ /dev/null @@ -1,249 +0,0 @@ -# The jolt conformance spec - -This directory defines jolt's behavior as a **host-neutral, executable language -specification**: a data file of cases, certified against reference Clojure, with a -feature profile that lets any runtime declare a conformance *level*. The goal is to -make hosting jolt on a new runtime (and proving it correct) a mechanical exercise: -read one data file, run each case, compare, report. - -## The artifacts - -| File | Role | Generated by | -|------|------|--------------| -| `test/chez/corpus.edn` | **The spec.** ~3570 cases of `{:suite :label :expected :actual :portability}`, `:expected` **sourced from reference JVM Clojure**. | `test/conformance/regen-corpus.clj` | -| `test/conformance/profile.edn` | Per-case **feature classification** — which non-portable cases need which host capability. | `certify.clj --profile` | -| `test/conformance/known-divergences.edn` | The few rows whose JVM value is an opaque host object that can't round-trip to readable source (Java arrays/transients/atoms/beans/proxies print as `#object[..@addr]`), so the corpus keeps jolt's value. | `regen-corpus.clj` leftovers, hand-checked | -| `test/conformance/regen-corpus.clj` | Sources every `:expected` from reference **JVM Clojure** in one process. | — | -| `test/conformance/certify.clj` | Certifies `:expected` against reference **JVM Clojure**; gates on new/stale divergences; emits the profile. | — | - -`corpus.edn` is **JVM-sourced**: `regen-corpus.clj` evaluates each case's `:actual` -on reference JVM Clojure and writes the JVM value as `:expected`. **`corpus.edn` is -the canonical, frozen contract**: it is what every runtime consumes, what -`certify.clj` certifies, and where new cases are authored directly. - -## Row schema - -```edn -{:suite "numbers / arithmetic" ; grouping; " :: \" \"a\"]" "(re-find #\"<(.+?)>\" \"\")"] + ["flag case-insens" "\"CAT\"" "(re-find #\"(?i)cat\" \"a CAT\")"] + ["lookahead" "\"foo\"" "(re-find #\"foo(?=bar)\" \"foobar\")"] + ["neg-lookahead" "\"foo\"" "(re-find #\"foo(?!bar)\" \"foobaz\")"] + ["word-boundary" "\"word\"" "(re-find #\"\\bword\\b\" \"a word!\")"] + ["word-boundary no" "nil" "(re-find #\"\\bword\\b\" \"swordfish\")"] + ["optional group" "[\"1.2.3\" \"1\" \"2\" \"3\" nil]" "(re-find #\"(\\d+)\\.(\\d+)\\.(\\d+)(?:-([a-z]+))?\" \"1.2.3\")"] + ["alternation" "\"dog\"" "(re-find #\"cat|dog\" \"a dog cat\")"] + ["str/replace $1" "\"he[ll]o\"" "(do (require (quote [clojure.string :as s])) (s/replace \"hello\" #\"(l+)\" \"[$1]\"))"] + ["str/replace regex" "\"X-X\"" "(do (require (quote [clojure.string :as s])) (s/replace \"a-b\" #\"[a-z]\" \"X\"))"] + + ### ==== map literals evaluate their values ==== + ["map literal expr" "{:a 3}" "{:a (+ 1 2)}"] + ["map literal var" "{:k 5}" "(let [x 5] {:k x})"] + ["map literal nested" "{:a {:b 2}}" "(let [y 2] {:a {:b y}})"] + ["map literal keyfn" "{:x 1}" "(let [k :x] {k 1})"] + ["map literal in fn" "6" "(do (defn mk [a b] {:sum (+ a b)}) (:sum (mk 2 4)))"] + + ### ---- overlay migration (jolt-1j0): run in all 3 modes ---- + # if-let/when-let bind only in the taken branch (else sees outer scope) + ["if-let else outer scope" "5" "(let [x 5] (if-let [x nil] :then x))"] + ["if-some else outer" "5" "(let [x 5] (if-some [x nil] :then x))"] + ["when-let body multi" "14" "(when-let [x 7] (inc x) (* x 2))"] + # nthrest returns () (not nil) for an exhausted n>0 walk; coll for n<=0 + ["nthrest exhausted" "(quote ())" "(nthrest nil 100)"] + ["nthrest n=0 keeps coll" "[1 2 3]" "(nthrest [1 2 3] 0)"] + ["nthnext surprising nil" "nil" "(nthnext nil nil)"] + # distinct? compares by value + ["distinct? equal colls" "false" "(distinct? [1 2] [1 2])"] + ["not-any?" "true" "(not-any? even? [1 3 5])"] + ["take-last" "[3 4]" "(take-last 2 [1 2 3 4])"] + ["replace nil val" "[1 nil 3]" "(replace {2 nil} [1 2 3])"] + ]) + +# Run every case under a given context factory and return the failures. The same +# cases run under both the interpreter and the compiler: results must match real +# Clojure semantics either way, so the compile path (hybrid: hot compiles, +# unsupported forms fall back to the interpreter) must not diverge. +# mode: {} interpret, {:compile? true} bootstrap compiler, {:selfhost true} the +# self-hosted pipeline (portable Clojure analyzer -> IR -> Janet back end). +(defn- run-cases [mode] + (def selfhost? (get mode :selfhost)) + (def init-opts (if selfhost? {} mode)) + (defn ev [ctx prog] + (if selfhost? (selfhost/compile-and-eval ctx (parse-string prog)) (eval-string ctx prog))) + # One expensive init per mode; every case runs on a cheap isolated fork (~2 ms) + # instead of its own init (~50 ms interpreted / ~900 ms compiled). Isolation is + # preserved — a fork shares nothing mutable with its siblings. For self-host + # mode, compile one form first so the lazily-built analyzer is in the snapshot. + (def base (init init-opts)) + (when selfhost? (selfhost/compile-and-eval base (parse-string "1"))) + (def snap (snapshot base)) + (def fails @[]) + (each [name expected actual] cases + (def ctx (fork snap)) + (def prog (string "(= " expected " " actual ")")) + (def res (protect (ev ctx prog))) + (cond + (not= (res 0) true) + (array/push fails [name "ERROR" (string (res 1))]) + (= (res 1) true) + nil + (let [got (protect (ev (fork snap) actual))] + (array/push fails [name "MISMATCH" + (string "want=" expected + " got=" (if (= (got 0) true) (string/format "%q" (got 1)) (string "ERR:" (got 1))))])))) + fails) + +(defn- report [label fails] + (printf "=== CONFORMANCE (%s): %d/%d passed ===" label (- (length cases) (length fails)) (length cases)) + (unless (empty? fails) + (print "--- Failures ---") + (each [name kind detail] fails + (printf "[%s] %s: %s" kind name detail)))) + +(def interp-fails (run-cases {})) +(report "interpret" interp-fails) +(def compile-fails (run-cases {:compile? true})) +(report "compile" compile-fails) +(def selfhost-fails (run-cases {:selfhost true})) +(report "self-host" selfhost-fails) +(print) +(when (or (pos? (length interp-fails)) (pos? (length compile-fails)) + (pos? (length selfhost-fails))) + (os/exit 1)) diff --git a/test/integration/deps-conformance-test.janet b/test/integration/deps-conformance-test.janet new file mode 100644 index 0000000..4d630ad --- /dev/null +++ b/test/integration/deps-conformance-test.janet @@ -0,0 +1,54 @@ +# Conformance pass for deps.edn-loaded libraries: resolve a few real, pure-cljc +# git libraries and check that their namespaces load and a sample call works. +# +# Network-gated: set JOLT_CONFORMANCE=1 to run (it clones from GitHub). Skipped by +# default so CI stays offline. Findings are summarized in doc/tools-deps.md. + +(use ../../src/jolt/api) +(use ../../src/jolt/types) +(import ../../src/jolt/deps :as deps) + +(unless (os/getenv "JOLT_CONFORMANCE") + (print "deps-conformance: set JOLT_CONFORMANCE=1 to run (needs network) — skipped") + (os/exit 0)) + +(def libs + [{:name "medley" :url "https://github.com/weavejester/medley" :tag "1.4.0" + :ns "medley.core" :check "(medley.core/find-first odd? [2 4 5])" :expect "5"} + {:name "cuerdas" :url "https://github.com/funcool/cuerdas" :tag "2022.06.16-403" + :ns "cuerdas.core" :check "(cuerdas.core/kebab \"helloWorld\")" :expect "hello-world"} + {:name "dependency" :url "https://github.com/stuartsierra/dependency" :tag "dependency-1.0.0" + :ns "com.stuartsierra.dependency" + :check "(boolean (com.stuartsierra.dependency/graph))" :expect "true"}]) + +(def base (string (or (os/getenv "TMPDIR") "/tmp") "/jolt-conf-" (os/time))) +(os/mkdir base) + +(defn- try-lib [lib] + (def dir (string base "/" (lib :name))) + (os/mkdir dir) + (spit (string dir "/deps.edn") + (string "{:deps {the/lib {:git/url \"" (lib :url) "\" :git/tag \"" (lib :tag) "\"}}}")) + (def prev (os/cwd)) + (defer (os/cd prev) + (os/cd dir) + (def r (protect (deps/resolve-deps "deps.edn"))) + (if (not (r 0)) + [:resolve-failed (string (r 1))] + (let [ctx (init {:paths (r 1)})] + (ctx-set-current-ns ctx "user") + (def lr (protect (eval-string ctx (string "(require (quote [" (lib :ns) "]))")))) + (if (not (lr 0)) + [:load-failed (string (lr 1))] + (let [cr (protect (eval-string ctx (lib :check)))] + (cond + (not (cr 0)) [:check-error (string (cr 1))] + (= (string (normalize-pvecs (cr 1))) (lib :expect)) [:ok nil] + [:check-mismatch (string "got " (string (normalize-pvecs (cr 1))))]))))))) + +(print "deps conformance — pure-cljc git libs:\n") +(each lib libs + (def [status detail] (try (try-lib lib) ([err] [:crash (string err)]))) + (printf " %-12s %-16s %s" (lib :name) status (or detail ""))) +(print "") +(os/exit 0) diff --git a/test/integration/deps-loader-test.janet b/test/integration/deps-loader-test.janet new file mode 100644 index 0000000..96cca27 --- /dev/null +++ b/test/integration/deps-loader-test.janet @@ -0,0 +1,48 @@ +# The loader resolves namespaces against an ordered list of source roots (the +# stdlib first, then deps.edn-resolved dirs), trying .clj then .cljc. This is the +# foundation for loading Clojure libraries via deps.edn — here we point a root at +# a hand-written "library" and require it. + +(use ../../src/jolt/api) +(use ../../src/jolt/types) + +(def tmp (string (or (os/getenv "TMPDIR") "/tmp") "/jolt-deps-test-" (os/time))) +(os/mkdir tmp) +(os/mkdir (string tmp "/mylib")) +(os/mkdir (string tmp "/other")) + +# a .cljc library with its own ns form and a require of a sibling ns +(spit (string tmp "/mylib/core.cljc") + "(ns mylib.core (:require [other.util :as u]))\n(defn double [x] (* 2 x))\n(defn doubled-inc [x] (u/inc1 (double x)))\n") +# a .clj sibling, with a dash in the name (-> underscore in the path) +(os/mkdir (string tmp "/other")) +(spit (string tmp "/other/util.clj") "(ns other.util)\n(defn inc1 [x] (+ x 1))\n") + +(def ctx (init {:paths [tmp]})) +(ctx-set-current-ns ctx "user") + +(var fails 0) +(defn check [label expr expected] + (let [r (protect (eval-string ctx expr)) + got (if (r 0) (normalize-pvecs (r 1)) (string "ERR " (r 1)))] + (if (= got expected) + (print " ok " label) + (do (++ fails) (printf " FAIL %s: want %q, got %q" label expected got))))) + +# require a .cljc lib from the added root and call it +(check "require .cljc lib" "(do (require (quote [mylib.core :as m])) (m/double 21))" 42) +# transitive require (mylib.core requires other.util) resolved from the root too +(check "transitive .clj require" "(mylib.core/doubled-inc 10)" 21) +# the stdlib still resolves from its default root +(check "stdlib still loads" "(do (require (quote [jolt.interop :as j])) (j/janet-type 1))" :number) + +# clean up +(defn rmrf [p] + (if (= :directory (os/stat p :mode)) + (do (each e (os/dir p) (rmrf (string p "/" e))) (os/rmdir p)) + (os/rm p))) +(rmrf tmp) + +(if (> fails 0) + (error (string "deps-loader-test: " fails " failing check(s)")) + (print "\nAll deps-loader tests passed!")) diff --git a/test/integration/deps-resolve-test.janet b/test/integration/deps-resolve-test.janet new file mode 100644 index 0000000..dadfbd5 --- /dev/null +++ b/test/integration/deps-resolve-test.janet @@ -0,0 +1,61 @@ +# deps.edn resolution into source roots, then loading a library through them. +# Uses :local/root deps only so it needs no network (the git path is the same +# code, exercised manually against real repos). + +(use ../../src/jolt/api) +(use ../../src/jolt/types) +(import ../../src/jolt/deps :as deps) + +(def base (string (or (os/getenv "TMPDIR") "/tmp") "/jolt-deps-resolve-" (os/time))) +(defn rmrf [p] + (when (os/stat p) + (if (= :directory (os/stat p :mode)) + (do (each e (os/dir p) (rmrf (string p "/" e))) (os/rmdir p)) + (os/rm p)))) +(rmrf base) + +(defn mkdirs [p] + (def abs (string/has-prefix? "/" p)) + (var acc nil) + (each seg (filter |(not= "" $) (string/split "/" p)) + (set acc (cond (nil? acc) (if abs (string "/" seg) seg) (string acc "/" seg))) + (unless (os/stat acc) (os/mkdir acc)))) + +# project -> depends on lib-a (local), which depends on lib-b (local, transitive) +(each d ["proj/src" "a/src/liba" "b/src/libb"] (mkdirs (string base "/" d))) +(spit (string base "/proj/deps.edn") `{:paths ["src"] :deps {my/a {:local/root "../a"}}}`) +(spit (string base "/a/deps.edn") `{:paths ["src"] :deps {my/b {:local/root "../b"}}}`) +(spit (string base "/b/deps.edn") `{:paths ["src"]}`) +(spit (string base "/a/src/liba/core.clj") "(ns liba.core (:require [libb.core :as b]))\n(defn val [] (b/n))\n") +(spit (string base "/b/src/libb/core.clj") "(ns libb.core)\n(defn n [] 99)\n") + +(var fails 0) +(defn check [label got expected] + (if (= got expected) (print " ok " label) + (do (++ fails) (printf " FAIL %s: want %q, got %q" label expected got)))) + +(os/cd (string base "/proj")) +(def roots (deps/resolve-deps "deps.edn" (string base "/proj/jpm_tree"))) +# roots: proj/src, a/src (transitive: b/src) — at least the two dep srcs present +(check "resolves transitive local dep roots" + (truthy? (and (some |(string/has-suffix? "/a/src" $) roots) + (some |(string/has-suffix? "/b/src" $) roots))) + true) + +# load through the resolved roots: liba.core requires libb.core transitively +(def ctx (init {:paths roots})) +(ctx-set-current-ns ctx "user") +(let [r (protect (eval-string ctx "(do (require (quote [liba.core :as a])) (a/val))"))] + (check "require local lib + transitive dep" (if (r 0) (r 1) (string "ERR " (r 1))) 99)) + +# cached resolution returns the same roots without re-walking +(check "cached resolve matches" + (deep= roots (deps/resolve-deps-cached "deps.edn" (string base "/proj/jpm_tree"))) + true) + +(os/cd "/") +(rmrf base) + +(if (> fails 0) + (error (string "deps-resolve-test: " fails " failing check(s)")) + (print "\nAll deps-resolve tests passed!")) diff --git a/test/integration/direct-linking-test.janet b/test/integration/direct-linking-test.janet new file mode 100644 index 0000000..0bb1fe5 --- /dev/null +++ b/test/integration/direct-linking-test.janet @@ -0,0 +1,63 @@ +# Direct-linking / redefinition matrix (jolt-d9j, jolt-g86). +# +# Direct-linking is a per-compilation-UNIT property (Clojure model). A call +# compiles direct iff the unit has direct-linking on AND the target is not +# ^:redef/^:dynamic AND the target is an already-defined fn. Otherwise indirect +# (live var deref → redefinable). This pins the user-visible semantics: +# - default user/REPL unit (direct-linking off): redefine anything, callers see it +# - direct-linked unit: callers don't see a later redef (unless target ^:redef) +# - :aot-core? gates whether the core tiers compile direct-linked + +(use ../../src/jolt/api) + +(var failures 0) +(defn- check [label got want] + (unless (= got want) + (++ failures) + (printf "FAIL [%s] got %q want %q" label got want))) + +# 1. Default unit (direct-linking OFF): redefinition reaches compiled callers. +(let [ctx (init {:compile? true})] + (eval-string ctx "(defn add [a b] (+ a b))") + (eval-string ctx "(defn caller [] (add 1 2))") + (check "default before redef" (eval-string ctx "(caller)") 3) + (eval-string ctx "(defn add [a b] (* a b))") + (check "default sees redef (indirect)" (eval-string ctx "(caller)") 2)) + +# 2. Direct-linked unit: compiled caller keeps the original target after a redef. +(let [ctx (init {:compile? true :direct-linking? true})] + (eval-string ctx "(defn add [a b] (+ a b))") + (eval-string ctx "(defn caller [] (add 1 2))") + (check "direct before redef" (eval-string ctx "(caller)") 3) + (eval-string ctx "(defn add [a b] (* a b))") + (check "direct ignores redef (sealed)" (eval-string ctx "(caller)") 3) + # the var itself is still redefined; only the direct-linked call is frozen + (check "direct var still updated" (eval-string ctx "(add 3 4)") 12)) + +# 3. ^:redef opts a var OUT of direct-linking even in a direct-linked unit. +(let [ctx (init {:compile? true :direct-linking? true})] + (eval-string ctx "(defn ^:redef add [a b] (+ a b))") + (eval-string ctx "(defn caller [] (add 1 2))") + (check "redef-tagged before" (eval-string ctx "(caller)") 3) + (eval-string ctx "(defn ^:redef add [a b] (* a b))") + (check "redef-tagged sees redef" (eval-string ctx "(caller)") 2)) + +# 4. :aot-core? true (default): redefining a core fn (in clojure.core) is still +# seen by USER code, because user calls are indirect regardless of core being +# direct-linked internally. +(let [ctx (init {:compile? true})] + (eval-string ctx "(defn uses-last [] (last [1 2 3]))") + (check "core call before" (eval-string ctx "(uses-last)") 3) + (eval-string ctx "(in-ns (quote clojure.core))") + (eval-string ctx "(def last (fn [coll] :patched))") + (eval-string ctx "(in-ns (quote user))") + (check "user sees core redef (indirect)" (eval-string ctx "(uses-last)") :patched)) + +# 5. :aot-core? false: core compiles indirect too, so even core-internal callers +# see a redef — the whole language is redefinable. +(let [ctx (init {:compile? true :aot-core? false})] + (check "aot-core off still correct" (eval-string ctx "(last [1 2 3])") 3)) + +(if (pos? failures) + (do (printf "direct-linking: %d failure(s)" failures) (os/exit 1)) + (print "direct-linking: all matrix cases passed")) diff --git a/test/integration/dispatch-cache-test.janet b/test/integration/dispatch-cache-test.janet new file mode 100644 index 0000000..680a777 --- /dev/null +++ b/test/integration/dispatch-cache-test.janet @@ -0,0 +1,51 @@ +# Protocol host-value dispatch cache (jolt-4ay). +# +# Host-value protocol dispatch used to recompute the candidate type-tag list and +# walk the registry on every call. It's now a generation-guarded cache keyed by +# (most-specific-host-tag, protocol, method); registering a protocol impl bumps +# the registry generation and invalidates it. This pins correctness: the cache +# must never hide a re-extension. + +(use ../../src/jolt/api) + +(var failures 0) +(defn- check [label got want] + (unless (= got want) + (++ failures) + (printf "FAIL [%s] got %q want %q" label got want))) + +(each mode [{:compile? true} {} {:aot-core? false}] + (def ctx (init mode)) + (eval-string ctx "(defprotocol P (m [x]))") + (eval-string ctx "(extend-protocol P Number (m [x] (* x 2)))") + (check (string mode " host dispatch") (eval-string ctx "(m 5)") 10) + (check (string mode " cache hit (same class)") (eval-string ctx "(m 7)") 14) + # Re-extend: registry generation bumps, cache must invalidate. + (eval-string ctx "(extend-protocol P Number (m [x] (+ x 100)))") + (check (string mode " sees re-extension") (eval-string ctx "(m 5)") 105) + # Extending a different host class bumps gen too; number impl re-resolves. + (eval-string ctx "(extend-protocol P String (m [x] (str \"s:\" x)))") + (check (string mode " other class") (eval-string ctx "(m \"hi\")") "s:hi") + (check (string mode " number after other-class extend") (eval-string ctx "(m 3)") 103)) + +# Multimethod hierarchy-fallback cache (jolt-g8w): the isa? walk result for a +# dispatch value is cached; defmethod/remove-method must invalidate it. +(each mode [{:compile? true} {} {:aot-core? false}] + (def ctx (init mode)) + (eval-string ctx "(derive ::circle ::shape)") + (eval-string ctx "(derive ::square ::shape)") + (eval-string ctx "(defmulti area identity)") + (eval-string ctx "(defmethod area ::shape [_] :generic)") + (check (string mode " mm hierarchy") (eval-string ctx "(area ::circle)") :generic) + (check (string mode " mm cache hit") (eval-string ctx "(area ::circle)") :generic) + # adding a more specific method must invalidate the cached hierarchy result + (eval-string ctx "(defmethod area ::circle [_] :specific)") + (check (string mode " mm sees new method") (eval-string ctx "(area ::circle)") :specific) + (check (string mode " mm other still hierarchy") (eval-string ctx "(area ::square)") :generic) + # removing it must re-expose the hierarchy fallback + (eval-string ctx "(remove-method area ::circle)") + (check (string mode " mm sees removal") (eval-string ctx "(area ::circle)") :generic)) + +(if (pos? failures) + (do (printf "dispatch-cache: %d failure(s)" failures) (os/exit 1)) + (print "dispatch-cache: all cases passed (compile, interpret, aot-core off)")) diff --git a/test/integration/embedded-stdlib-test.janet b/test/integration/embedded-stdlib-test.janet new file mode 100644 index 0000000..d11540f --- /dev/null +++ b/test/integration/embedded-stdlib-test.janet @@ -0,0 +1,33 @@ +# The .clj stdlib (clojure.string, clojure.set, jolt.interop, …) is baked into the +# image at build time, so it loads even when the files aren't on disk. We simulate +# the shipped-binary-elsewhere case by clearing the filesystem source roots, so a +# require can only be satisfied by the embedded copy. + +(use ../../src/jolt/api) +(use ../../src/jolt/types) + +(def ctx (init)) +(ctx-set-current-ns ctx "user") +(put (ctx :env) :source-paths @[]) # no FS roots — embedded fallback only + +(var fails 0) +(defn check [label expr expected] + (let [r (protect (eval-string ctx expr)) + got (if (r 0) (normalize-pvecs (r 1)) (string "ERR " (r 1)))] + (if (= got expected) (print " ok " label) + (do (++ fails) (printf " FAIL %s: want %q, got %q" label expected got))))) + +(assert (> (length (get (ctx :env) :embedded-sources)) 0) "embedded-sources should be populated") + +(check "clojure.string from embedded" + "(do (require (quote [clojure.string :as s])) (s/upper-case \"hi\"))" "HI") +(check "clojure.set from embedded" + "(do (require (quote [clojure.set :as set])) (vec (set/union #{1} #{2})))" [2 1]) +(check "clojure.walk from embedded" + "(do (require (quote [clojure.walk :as w])) (w/keywordize-keys {\"a\" 1}))" {:a 1}) +(check "jolt.interop from embedded" + "(do (require (quote [jolt.interop :as j])) (j/janet-type 1))" :number) + +(if (> fails 0) + (error (string "embedded-stdlib-test: " fails " failing check(s)")) + (print "\nAll embedded-stdlib tests passed!")) diff --git a/test/integration/fallback-zero-test.janet b/test/integration/fallback-zero-test.janet new file mode 100644 index 0000000..9962342 --- /dev/null +++ b/test/integration/fallback-zero-test.janet @@ -0,0 +1,81 @@ +# Fallback-zero verification (Stage 1 Task 3). +# +# self-host-test.janet checks observable RESULTS but not WHICH path ran — a form +# that silently fell back to the interpreter still "passes" there. This harness +# checks the path: it runs the portable analyzer (jolt.analyzer/analyze, via +# backend/analyze-form) on a corpus of NON-STATEFUL forms and asserts NONE raise +# :jolt/uncompilable — i.e. the self-hosted analyzer actually COMPILED them. +# +# As analyzer↔compiler.janet parity grows (Stage 1), move forms from the +# "intentional fallback" sanity list into the must-compile corpus. The day the +# fallback set equals the frozen intentional stateful set, the Janet bootstrap +# compiler is retireable. +# +# Mechanism: backend/analyze-form throws (a "jolt/uncompilable: …" string) for a +# punted form; (protect …) turns that into [false msg]. [true ir] == compiled. + +(import ../../src/jolt/backend :as backend) +(use ../../src/jolt/api) +(use ../../src/jolt/reader) + +(def ctx (init)) + +(defn- analyzes? [s] + # true if the analyzer produced IR (compiled), false if it punted/uncompilable. + (def r (protect (backend/analyze-form ctx (parse-string s)))) + (and (r 0) true)) + +# --- Must compile: pure, non-stateful value production. NONE may punt. --- +(def must-compile + [# set literals (Task 1) + "#{1 2 3}" "#{}" "#{:a :b :c}" "#{(inc 0) 2}" "(conj #{1 2} 3)" + "[#{1 2} {:s #{3}}]" "(let [x 5] #{x (inc x)})" + # other literals + "[1 2 3]" "{:a 1 :b 2}" "{:k (inc 0)}" "[[1] [2 3]]" "42" ":kw" "\"str\"" + # control flow + binding + "(+ 1 2)" "(if true 1 2)" "(do 1 2 3)" "(let [a 1 b 2] (+ a b))" + "(fn [x] (* x x))" "(fn ([a] a) ([a b] (+ a b)))" + "(loop [i 0] (if (< i 3) (recur (inc i)) i))" + "(quote (a b c))" "(throw (ex-info \"x\" {}))" + "(try (inc 1) (catch :default e e))" + # def + calls into core + "(def answer 42)" "(map inc [1 2 3])" "(reduce + 0 [1 2 3])" + "(get {:a 1} :a)" "(vec (range 5))" + # set?/disj are plain fns now, not special forms (jolt-g3h) + "(set? #{1 2})" "(disj #{1 2 3} 2)" + # Stage 2 (jolt-eaa): stateful forms moved onto the compile path. (binding only + # compiles over an INTERNED var; the built-in dynamic vars aren't interned yet, + # so it's exercised end-to-end in the state spec instead.) + "(require (quote [clojure.string :as s]))" "(in-ns (quote foo.bar))" + "(ns foo.bar (:require [clojure.string :as s]))" + "(defprotocol P (m [x]))" "(extend-type Long P (m [x] x))" + "(reify P (m [this] 1))" "(var map)" + # Stage 2 tier 5: type/dispatch definitional forms compile too + "(deftype Pt [x y])" "(deftype Sq [s] P (m [this] s))" + "(defrecord Rec [a b])" "(defmulti mf :k)" "(defmethod mf :a [x] x)" + # Stage 2 tier 6: var fns are ordinary invokes now + "(var-get (var map))" "(var? (var map))" "(var-set (var map) map)" + "(alter-var-root (var map) identity)" "(find-var (quote clojure.core/map))" + "(intern (quote user) (quote tier6-sym) 42)" + "(alter-meta! (var map) assoc :k 1)" "(reset-meta! (var map) {})"]) + +# --- Intentional fallback (sanity sample): these SHOULD punt to the interpreter. +# The remaining frozen/uncompiled set keeps the harness honest in the punt +# direction: defmacro + set! (frozen host-coupled), and letfn (needs letrec IR). +(def must-punt + ["(defmacro m [x] x)" + "(set! *warn-on-reflection* true)" "(letfn [(f [n] (g n)) (g [n] (f n))] (f 1))"]) + +(var fails @[]) +(each s must-compile + (unless (analyzes? s) (array/push fails (string "FALLBACK (should compile): " s)))) +(each s must-punt + (when (analyzes? s) (array/push fails (string "COMPILED (should punt): " s)))) + +(printf "fallback-zero: %d must-compile + %d must-punt — %d failures" + (length must-compile) (length must-punt) (length fails)) +(when (> (length fails) 0) + (print "\nFailures:") + (each f fails (printf " %s" f)) + (os/exit 1)) +(print "fallback-zero: OK (analyzer compiled the full non-stateful corpus)") diff --git a/test/integration/features-test.janet b/test/integration/features-test.janet new file mode 100644 index 0000000..2548956 --- /dev/null +++ b/test/integration/features-test.janet @@ -0,0 +1,147 @@ +# Feature regression tests: a broad sweep of Clojure features (destructuring, +# multimethods, protocols, laziness, …). Each case asserts (= expected actual) +# evaluated inside Jolt (so comparisons use Jolt's own Clojure-semantics =). +# Run via `jpm test`. +(use ../../src/jolt/api) + +(var pass 0) +(def fails @[]) + +(defn check [label expected actual] + # evaluate (= expected actual) in a fresh ctx; expects boolean true + (def ctx (init)) + (def res (protect (eval-string ctx (string "(= " expected " " actual ")")))) + (cond + (not= (res 0) true) + (array/push fails [label "ERROR" (string (res 1))]) + (= (res 1) true) + (++ pass) + (let [got (protect (eval-string (init) actual))] + (array/push fails [label "NEQ" + (string "want=" expected " got=" + (if (= (got 0) true) (string/format "%q" (got 1)) (string "ERR:" (got 1))))])))) + +(def cases + [ + ### 1. Destructuring + ["destr seq" "[10 20 30]" "(let [[a b c] [10 20 30]] [a b c])"] + ["destr map :or" "[\"Alice\" 30 \"Unknown\"]" + "(let [{:keys [name age city] :or {city \"Unknown\"}} {:name \"Alice\" :age 30}] [name age city])"] + ["destr nested map" "[1.0 2.5]" "(let [{[x y] :coords} {:coords [1.0 2.5]}] [x y])"] + ["destr :as" "[1 [1 2 3]]" "(let [[a :as all] [1 2 3]] [a all])"] + ["destr & rest" "[1 (quote (2 3))]" "(let [[a & r] [1 2 3]] [a r])"] + ["destr :strs" "[1 2]" "(let [{:strs [a b]} {\"a\" 1 \"b\" 2}] [a b])"] + ["destr fn-param" "7" "((fn [{:keys [a b]}] (+ a b)) {:a 3 :b 4})"] + + ### 2. Atoms + ["atom swap! inc" "1" "(do (def a (atom 0)) (swap! a inc) @a)"] + ["atom reset!" "100" "(do (def a (atom 0)) (reset! a 100) @a)"] + ["atom CAS ok" "true" "(do (def a (atom 5)) (compare-and-set! a 5 10))"] + ["atom CAS no" "false" "(do (def a (atom 5)) (compare-and-set! a 9 10))"] + ["atom thread-first swap!" "213" "(do (def a (atom 100)) (swap! a #(-> % (* 2) (+ 3))) (swap! a #(-> % (* 1) (+ 10))) @a)"] + ["atom swap! args" "10" "(do (def a (atom 1)) (swap! a + 2 3 4) @a)"] + ["atom swap-vals!" "[1 2]" "(do (def a (atom 1)) (swap-vals! a inc))"] + ["atom watch" "[1 2]" "(do (def lg (atom nil)) (def a (atom 1)) (add-watch a :k (fn [k r o n] (reset! lg [o n]))) (swap! a inc) @lg)"] + ["atom validator" "5" "(do (def a (atom 1 :validator pos?)) (reset! a 5) @a)"] + + ### 3. Lazy sequences + ["lazy filter inf" "(quote (0 2 4 6 8 10 12 14 16 18))" "(take 10 (filter even? (iterate inc 0)))"] + ["lazy take-while sq" "(quote (0 1 4 9 16 25 36 49))" "(take-while #(< % 50) (map #(* % %) (range)))"] + ["lazy cycle" "(quote (:a :b :c :a :b :c :a :b :c :a))" "(take 10 (cycle [:a :b :c]))"] + ["lazy-seq cons self" "(quote (1 2 4 8 16 32 64 128))" + "(do (defn my-it [f x] (lazy-seq (cons x (my-it f (f x))))) (take 8 (my-it #(* 2 %) 1)))"] + ["lazy self-ref fib" "(quote (0 1 1 2 3 5 8 13 21 34))" + "(do (def fib (lazy-cat [0 1] (map + (rest fib) fib))) (take 10 fib))"] + ["repeatedly" "(quote (1 1 1))" "(repeatedly 3 (fn [] 1))"] + ["range step" "(quote (0 2 4 6 8))" "(range 0 10 2)"] + + ### 4. Transducers + ["xf comp into" "[1 3 5 7 9]" "(into [] (comp (map inc) (filter odd?)) (range 10))"] + ["xf sequence" "(quote (1 3 5 7 9))" "(sequence (comp (map inc) (filter odd?)) (range 10))"] + ["xf transduce" "25" "(transduce (comp (map inc) (filter odd?)) + 0 (range 10))"] + ["xf take" "[0 1 2]" "(into [] (take 3) (range 100))"] + ["xf remove" "[1 3 5]" "(into [] (remove even?) [1 2 3 4 5])"] + + ### 5. Protocols & Records + ["record area circle" "78" "(do (defprotocol Sh (ar [t])) (defrecord Ci [r] Sh (ar [_] (int (* 3.14159 r r)))) (int (ar (->Ci 5))))"] + ["record field" "5" "(do (defrecord Ci [r]) (:r (->Ci 5)))"] + ["record map->" "3" "(do (defrecord P [x y]) (:x (map->P {:x 3 :y 4})))"] + ["protocol 2 methods" "[16 \"sq\"]" "(do (defprotocol Sh (ar [t]) (nm [t])) (defrecord Sq [s] Sh (ar [_] (* s s)) (nm [_] \"sq\")) (let [x (->Sq 4)] [(ar x) (nm x)]))"] + ["extend-protocol" "6" "(do (defprotocol G (g [x])) (extend-protocol G java.lang.Long (g [x] (inc x))) (g 5))"] + ["reify" "42" "(do (defprotocol P (m [_])) (m (reify P (m [_] 42))))"] + ["record equality" "true" "(do (defrecord R [a]) (= (->R 1) (->R 1)))"] + + ### 6. Multimethods + ["mm dispatch circle" "\"round\"" "(do (defmulti st :kind) (defmethod st :circle [_] \"round\") (defmethod st :default [_] \"unknown\") (st {:kind :circle}))"] + ["mm default" "\"unknown\"" "(do (defmulti st :kind) (defmethod st :circle [_] \"round\") (defmethod st :default [_] \"unknown\") (st {:kind :triangle}))"] + ["mm multi-arity" "[1 3]" "(do (defmulti f (fn [& a] (first a))) (defmethod f :x ([_ y] y) ([_ y z] (+ y z))) [(f :x 1) (f :x 1 2)])"] + + ### 7. Macros + ["macro log-call" "6" "(do (defmacro lc [e] `(let [r# ~e] r#)) (lc (* 2 3)))"] + ["macro quote arg" "(quote (* 2 3))" "(do (defmacro qa [e] `(quote ~e)) (qa (* 2 3)))"] + ["macroexpand-1" "true" "(do (defmacro mm [x] (list 'inc x)) (= '(inc 5) (macroexpand-1 '(mm 5))))"] + ["gensym distinct" "false" "(= (gensym) (gensym))"] + ["syntax-quote splice" "[1 2 3]" "(let [xs [1 2 3]] `[~@xs])"] + # syntax-quote fully-qualifies resolved core symbols to clojure.core/ (jolt-265). + ["syntax-quote unquote" "(quote (clojure.core/+ 1 5))" "(let [x 5] `(+ 1 ~x))"] + + ### 8. Recursion + ["recursion fact" "120" "(do (defn fact [n] (if (<= n 1) 1 (* n (fact (dec n))))) (fact 5))"] + ["recursion loop" "120" "(loop [i 5 acc 1] (if (zero? i) acc (recur (dec i) (* acc i))))"] + ["mutual recursion" "true" "(letfn [(ev? [n] (if (zero? n) true (od? (dec n)))) (od? [n] (if (zero? n) false (ev? (dec n))))] (ev? 6))"] + ["trampoline" ":done" "(do (defn a [n] (if (zero? n) :done (fn [] (a (dec n))))) (trampoline a 8))"] + + ### 9. Higher-order functions + ["partial" "15" "((partial + 5) 10)"] + ["comp" "8" "((comp #(* 2 %) inc) 3)"] + ["juxt" "[5 6 4]" "((juxt identity inc dec) 5)"] + ["every-pred" "true" "((every-pred pos? even?) 2 4 6)"] + ["some-fn" "true" "((some-fn even? neg?) 3 4)"] + ["fnil" "1" "((fnil inc 0) nil)"] + ["complement" "true" "((complement nil?) 1)"] + + ### 10. Threading macros + ["->> pipeline" "75" "(->> (range 20) (filter odd?) (map #(* % 3)) (take 5) (reduce +))"] + ["-> sqrt long" "15" "(-> 25 Math/sqrt long (+ 10))"] + ["some->" "2" "(some-> {:a {:b 1}} :a :b inc)"] + ["some-> nil" "nil" "(some-> {:a nil} :a :b)"] + ["cond->" "4" "(cond-> 1 true inc false (* 100) true (* 2))"] + ["as->" "20" "(as-> 1 x (inc x) (* x 10))"] + + ### 11. Exception handling + ["ex catch" "\"caught\"" "(try (throw (ex-info \"x\" {})) (catch :default e \"caught\"))"] + ["ex-message" "\"broke\"" "(try (throw (ex-info \"broke\" {:code 42})) (catch :default e (ex-message e)))"] + ["ex-data" "{:code 42}" "(try (throw (ex-info \"broke\" {:code 42})) (catch :default e (ex-data e)))"] + ["try finally" "[:body :fin]" "(do (def lg (atom [])) (try (swap! lg conj :body) (finally (swap! lg conj :fin))) @lg)"] + + ### 12. For comprehension + ["for nested :when" "(quote ([0 1] [0 2] [1 0] [1 2] [2 0] [2 1]))" + "(for [x (range 3) y (range 3) :when (not= x y)] [x y])"] + ["for :let" "(quote (1 4 9))" "(for [x [1 2 3] :let [sq (* x x)]] sq)"] + ["for :while" "(quote (0 1 2))" "(for [x (range 10) :while (< x 3)] x)"] + + ### 13b. Persistent lists — O(1) conj-prepend, immutable, value semantics + ["list conj prepends" "(quote (0 1 2 3))" "(conj (list 1 2 3) 0)"] + ["list conj multi" "(quote (:c :b :a))" "(conj (quote ()) :a :b :c)"] + ["list immutable" "true" "(let [l (list 1 2 3) l2 (conj l 9)] (and (= l (quote (1 2 3))) (= l2 (quote (9 1 2 3)))))"] + ["list? after conj" "true" "(list? (conj (list 1 2) 0))"] + ["list = vector elts" "true" "(= (quote (1 2 3)) [1 2 3])"] + ["reduce conj list" "(quote (2 1 0))" "(reduce conj (list) (range 3))"] + ["cons onto list" "(quote (0 1 2 3))" "(cons 0 (list 1 2 3))"] + + ### 14. Janet interop + ["interop method" "\"v=41\"" "(. {:value 41 :describe (fn [self] (str \"v=\" (:value self)))} describe)"] + ["interop field" "41" "(.-value {:value 41})"] + # vectors are persistent vectors (Janet tables); lists are Janet arrays + ["interop janet-type" ":array" "(do (require '[jolt.interop :as j]) (j/janet-type (list 1 2 3)))"] + ]) + +(each [label expected actual] cases (check label expected actual)) + +(printf "\n=== features-test: %d/%d passed ===" pass (length cases)) +(unless (empty? fails) + (print "--- Failures ---") + (each [label kind detail] fails (printf "[%s] %s: %s" kind label detail))) +(when (pos? (length fails)) + (error (string (length fails) " feature regression(s)"))) +(print "All feature tests passed!") diff --git a/test/integration/jank-conformance-test.janet b/test/integration/jank-conformance-test.janet new file mode 100644 index 0000000..cb53ccd --- /dev/null +++ b/test/integration/jank-conformance-test.janet @@ -0,0 +1,54 @@ +# jank conformance: runs the Clojure-language pass-tests from a local jank +# checkout (https://github.com/jank-lang/jank, MPL-2.0) against Jolt and asserts +# the number that pass stays at/above a baseline. This does NOT vendor jank's +# sources (license differs) — it references ~/src/jank if present and SKIPS +# cleanly when absent, so it is a local/dev regression aid. +# +# Each jank pass-test is an assertion script ending in `:success`. We load it in +# a fresh context and count it as passing when it returns :success. +(use ../../src/jolt/api) + +(def jank-dir (string (os/getenv "HOME") "/src/jank/compiler+runtime/test/jank")) + +# Baseline: the number of pass-tests Jolt currently handles. Raise this as Jolt +# gains features so regressions (a previously-passing test breaking) are caught. +(def baseline 120) + +# Tests that loop forever under Jolt's eager evaluation (skipped to avoid hangs; +# tracked as known gaps — variadic-recur arity selection and var-quote calls). +(def skip-patterns ["/cpp/" "var-quote" "fn/recur/pass-variadic-position"]) + +(defn- skip? [path] + (var s false) + (each p skip-patterns (when (string/find p path) (set s true))) + s) + +(defn- walk [dir acc] + (each e (os/dir dir) + (def p (string dir "/" e)) + (case ((os/stat p) :mode) + :directory (walk p acc) + :file (when (and (string/has-suffix? ".jank" p) + (string/find "/pass-" p) + (not (skip? p))) + (array/push acc p)))) + acc) + +(if (not (os/stat jank-dir)) + (print "jank-conformance: ~/src/jank not present — skipped") + (do + (def files (sort (walk jank-dir @[]))) + (var pass 0) + (def fails @[]) + (each f files + # A pass-test passes when no assertion throws (assert now errors on failure). + (def res (protect (load-string (init) (slurp f)))) + (if (= (res 0) true) + (++ pass) + (array/push fails (string/slice f (+ 1 (length jank-dir)))))) + (printf "jank-conformance: %d/%d pass-tests pass (baseline %d)" pass (length files) baseline) + (when (< pass baseline) + (print "--- regressions (now failing, were within baseline) ---") + (each rel fails (print " " rel)) + (error (string "jank conformance dropped to " pass " (baseline " baseline ")"))) + (printf "jank conformance OK (%d known gaps)" (length fails)))) diff --git a/test/integration/lazy-infinite-test.janet b/test/integration/lazy-infinite-test.janet new file mode 100644 index 0000000..a29a5dd --- /dev/null +++ b/test/integration/lazy-infinite-test.janet @@ -0,0 +1,123 @@ +# Deadlined infinite-seq conformance harness (Phase 5 Step 0). +# +# Each case is [name expected-clj actual-clj]. The harness spawns a subprocess +# worker (test/support/lazy-eval.janet) that evaluates (= expected actual) and +# prints @@RESULT true/false. Workers run under a wall-clock deadline; a hang +# = a FAIL. This is the safety net that makes it safe to convert transformers +# to lazy — wrong answers hang instead of silently passing. +# +# Pattern mirrors clojure-test-suite-test.janet: os/spawn + ev/with-deadline +# + os/proc-kill on timeout. Never probe infinite cases in-process. + +(def per-case-timeout 5) + +(defn- run-case [expected actual] + (def proc (os/spawn ["janet" "test/support/lazy-eval.janet" expected actual] :p {:out :pipe})) + (def out (proc :out)) + (var data nil) + (def ok + (try + (ev/with-deadline per-case-timeout + (set data (ev/read out 0x10000)) + (os/proc-wait proc) + true) + ([err] false))) + (when (not ok) + (protect (os/proc-kill proc true)) + (protect (ev/with-deadline 2 (os/proc-wait proc)))) + (protect (:close out)) + (if (and ok data) (string data) nil)) + +(defn- parse-result [s] + (def prefix-len (length "@@RESULT ")) + (if (string/has-prefix? "@@RESULT " s) + (let [val (string/slice s prefix-len (dec (length s)))] + [:ok val]) + (if (string/has-prefix? "@@ERROR " s) + (let [msg (string/slice s (length "@@ERROR ") (dec (length s)))] + [:error msg]) + nil))) + +# ---- Cases from phase-5.md §6.2 ---- +# Expected values use Clojure quote syntax so the worker evaluates +# (= (quote ...) actual) with Clojure's = semantics. +(def cases + [ + ["nth of map inc range" "1001" "(nth (map inc (range)) 1000)"] + ["first filter even? drop range" "4" "(first (filter even? (drop 3 (range))))"] + ["take 3 remove odd? range" "(quote (0 2 4))" "(take 3 (remove odd? (range)))"] + ["take 3 drop-while <5 range" "(quote (5 6 7))" "(take 3 (drop-while (fn [x] (< x 5)) (range)))"] + ["take 4 interleave range iterate" "(quote (0 10 1 11))" "(take 4 (interleave (range) (iterate inc 10)))"] + ["take 4 reductions + range" "(quote (0 1 3 6))" "(take 4 (reductions + (range)))"] + ["take 3 tree-seq infinite" "(quote (0 0 0))" "(take 3 (tree-seq (fn [_] true) (fn [n] [n]) 0))"] + ["sequence xform lazy inf" "(quote (1 2 3))" "(take 3 (sequence (map inc) (range)))"] + ["sequence comp xform inf" "(quote (2 4 6))" "(take 3 (sequence (comp (filter odd?) (map inc)) (range)))"] + ["every? short-circuits on inf" "false" "(every? pos? (range))"] + ["not-every? short-circuits on inf" "true" "(not-every? pos? (range))"] + ["take 3 partition 2 range" "(quote ((0 1) (2 3) (4 5)))" "(take 3 (partition 2 (range)))"] + ["take 3 partition-all 2 range" "(quote ((0 1) (2 3) (4 5)))" "(take 3 (partition-all 2 (range)))"] + ["take 3 map-indexed vector range" "(quote ([0 0] [1 1] [2 2]))" "(take 3 (map-indexed vector (range)))"] + ["take 3 distinct cycle" "(quote (1 2 3))" "(take 3 (distinct (cycle [1 2 1 3 1])))"] + ["take 6 mapcat dup range" "(quote (0 0 1 1 2 2))" "(take 6 (mapcat (fn [x] [x x]) (range)))"] + ["first rest lazy" "1" "(let [[a & r] (range)] (first r))"] + ["take 3 rest lazy" "(quote (1 2 3))" "(let [[a & r] (range)] (take 3 r))"] + ["dedupe inf" "(quote (1 2 1 2 1))" "(take 5 (dedupe (cycle [1 1 2 2])))"] + ["take 3 take-nth 2 range" "(quote (0 2 4))" "(take 3 (take-nth 2 (range)))"] + ["take 3 interpose :x range" "(quote (0 :x 1))" "(take 3 (interpose :x (range)))"] + ["take 3 map vector range iterate" "(quote ([0 100] [1 101] [2 102]))" "(take 3 (map vector (range) (iterate inc 100)))"] + + # §6.3 Laziness counter tests — realize exactly the demanded prefix. Under + # Option A `take` is lazy, so the take result must be forced (dorun) to drive + # realization; reading the counter without forcing would (correctly) see 0. + ["LAZY map" "3" "(do (def c (atom 0)) (dorun (take 3 (map (fn [x] (swap! c inc) x) (range)))) @c)"] + ["LAZY filter" "6" "(do (def c (atom 0)) (dorun (take 3 (filter (fn [x] (swap! c inc) (odd? x)) (range)))) @c)"] + ["LAZY remove" "6" "(do (def c (atom 0)) (dorun (take 3 (remove (fn [x] (swap! c inc) (even? x)) (range)))) @c)"] + ["LAZY take-while" "6" "(do (def c (atom 0)) (dorun (take-while (fn [x] (swap! c inc) (< x 5)) (range))) @c)"] + ["LAZY drop-while" "6" "(do (def c (atom 0)) (dorun (take 3 (drop-while (fn [x] (swap! c inc) (< x 5)) (range)))) @c)"] + ["LAZY distinct" "4" "(do (def c (atom 0)) (dorun (take 3 (distinct (map (fn [x] (swap! c inc) x) (cycle [1 2 1 3 1]))))) @c)"] + ["LAZY take-nth" "7" "(do (def c (atom 0)) (dorun (take 3 (take-nth 2 (map (fn [x] (swap! c inc) x) (range))))) @c)"] + ["LAZY map-indexed" "3" "(do (def c (atom 0)) (dorun (take 3 (map-indexed (fn [i x] (swap! c inc) [i x]) (range)))) @c)"] + ["LAZY keep" "6" "(do (def c (atom 0)) (dorun (take 3 (keep (fn [x] (swap! c inc) (if (odd? x) x nil)) (range)))) @c)"] + ["LAZY keep-indexed" "6" "(do (def c (atom 0)) (dorun (take 3 (keep-indexed (fn [i x] (swap! c inc) (if (odd? i) x)) (range)))) @c)"] + ["LAZY interpose" "2" "(do (def c (atom 0)) (dorun (take 3 (interpose :x (map (fn [x] (swap! c inc) x) (range))))) @c)"] + ["LAZY partition" "6" "(do (def c (atom 0)) (dorun (take 3 (partition 2 (map (fn [x] (swap! c inc) x) (range))))) @c)"] + ["LAZY partition-all" "6" "(do (def c (atom 0)) (dorun (take 3 (partition-all 2 (map (fn [x] (swap! c inc) x) (range))))) @c)"] + ["LAZY mapcat" "3" "(do (def c (atom 0)) (dorun (take 6 (mapcat (fn [x] (swap! c inc) [x x]) (range)))) @c)"] + ["LAZY dedupe" "9" "(do (def c (atom 0)) (dorun (take 5 (dedupe (map (fn [x] (swap! c inc) x) (cycle [1 1 2 2]))))) @c)"] + ["LAZY repeated inc" "3" "(do (def c (atom 0)) (dorun (take 3 (map (fn [x] (swap! c inc) x) (iterate inc 0)))) @c)"] + + # Already-working cases (guard against regression) + ["take 5 iterate inc" "(quote (0 1 2 3 4))" "(take 5 (iterate inc 0))"] + ["take 3 range" "(quote (0 1 2))" "(take 3 (range))"] + ["take 3 repeat" "(quote (7 7 7))" "(take 3 (repeat 7))"] + ["take 3 cycle" "(quote (1 2 1))" "(take 3 (cycle [1 2]))"] + ["take 3 filter even? range" "(quote (0 2 4))" "(take 3 (filter even? (range)))"] + ["take 5 lazily filtered from range" "(quote (1 3 5 7 9))" "(take 5 (filter odd? (range)))"] + ]) + +# ---- Run ---- +(var fails @[]) +(var timeouts 0) +(var passed 0) + +(each [name expected expr] cases + (def out (run-case expected expr)) + (cond + (nil? out) + (do (++ timeouts) (array/push fails (string "TIMEOUT: " name))) + (let [res (parse-result out)] + (case (res 0) + :ok (if (= "true" (res 1)) + (++ passed) + (array/push fails (string "MISMATCH: " name " — expected " expected))) + :error (array/push fails (string "ERROR: " name " — " (res 1))) + (array/push fails (string "PARSE: " name " — raw: " (string/trim out))))))) + +(printf "lazy-infinite: %d cases — %d passed / %d timeouts / %d failures" + (length cases) passed timeouts (length fails)) +(when (> (length fails) 0) + (print "\nFailures:") + (each f fails (printf " %s" f))) + +(if (or (> (length fails) 0) (> timeouts 0)) + (os/exit 1)) diff --git a/test/integration/namespace-test.janet b/test/integration/namespace-test.janet new file mode 100644 index 0000000..755128b --- /dev/null +++ b/test/integration/namespace-test.janet @@ -0,0 +1,98 @@ +(use ../../src/jolt/reader) +(use ../../src/jolt/types) +(use ../../src/jolt/evaluator) +(import ../../src/jolt/api :as api) + +# ns/in-ns/require/use are overlay macros + clojure.core fns now (Stage 2 jolt-eaa), +# so these interpreter tests need the full env (init loads the overlay + installs +# the stateful fns), not a bare make-ctx. +(defn- fresh-ctx [] (api/init)) + +# Helper: parse and eval in a fresh ctx +(defn eval-str [s] + (let [ctx (fresh-ctx) + form (parse-string s)] + (eval-form ctx @{} form))) + +(print "1: in-ns...") +(let [ctx (fresh-ctx)] + (def form (parse-string "(in-ns 'my.app)")) + (eval-form ctx @{} form) + (assert (= "my.app" (ctx-current-ns ctx)) "in-ns switches namespace")) +(print " passed") + +(print "2: def in different namespace...") +(let [ctx (fresh-ctx)] + (eval-form ctx @{} (parse-string "(in-ns 'my.app)")) + (eval-form ctx @{} (parse-string "(def x 42)")) + (let [ns (ctx-find-ns ctx "my.app") + v (ns-find ns "x")] + (assert (= 42 (var-get v)) "def works in new namespace"))) +(print " passed") + +(print "3: ns form...") +(let [ctx (fresh-ctx)] + (eval-form ctx @{} (parse-string "(ns my.lib)")) + (assert (= "my.lib" (ctx-current-ns ctx)) "ns sets current namespace")) +(print " passed") + +(print "4: ns with require...") +(let [ctx (fresh-ctx)] + # Set up a namespace with some vars + (let [other-ns (ctx-find-ns ctx "other.lib")] + (ns-intern other-ns "f" (fn [x] (inc x)))) + # Now ns with require + (eval-form ctx @{} (parse-string "(ns my.app (:require [other.lib :as o]))")) + # current-ns should be my.app + (assert (= "my.app" (ctx-current-ns ctx)) "ns with require sets current namespace") + # Alias should be registered + (let [ns (ctx-find-ns ctx "my.app") + aliased (ns-import-lookup ns "o")] + (assert (= "other.lib" aliased) "alias o -> other.lib registered"))) +(print " passed") + +(print "5: require form (standalone)...") +(let [ctx (fresh-ctx)] + (eval-form ctx @{} (parse-string "(require '[other.lib :as o])")) + (let [ns (ctx-find-ns ctx "user") + aliased (ns-import-lookup ns "o")] + (assert (= "other.lib" aliased) "standalone require registers alias"))) +(print " passed") + +(print "6: qualified symbol via alias...") +(let [ctx (fresh-ctx)] + # Set up target ns + (let [target (ctx-find-ns ctx "other.lib")] + (ns-intern target "f" (fn [x] (inc x)))) + # Register alias + (let [ns (ctx-find-ns ctx "user")] + (ns-import ns "o" "other.lib")) + # Resolve o/f and call it + (let [form (parse-string "(o/f 41)") + result (eval-form ctx @{} form)] + (assert (= 42 result) "qualified call via alias works"))) +(print " passed") + +(print "7: require then use alias...") +(let [ctx (fresh-ctx)] + # Set up target ns + (let [target (ctx-find-ns ctx "math.lib")] + (ns-intern target "add" (fn [a b] (+ a b)))) + # require + use + (eval-form ctx @{} (parse-string "(require '[math.lib :as m])")) + (let [result (eval-form ctx @{} (parse-string "(m/add 1 2)"))] + (assert (= 3 result) "require + alias + call chain works"))) +(print " passed") + +(print "8: ns form requires multiple...") +(let [ctx (fresh-ctx)] + (let [ns1 (ctx-find-ns ctx "a.lib")] + (ns-intern ns1 "f" (fn [x] (inc x)))) + (let [ns2 (ctx-find-ns ctx "b.lib")] + (ns-intern ns2 "g" (fn [x] (dec x)))) + (eval-form ctx @{} (parse-string "(ns user (:require [a.lib :as a] [b.lib :as b]))")) + (assert (= 43 (eval-form ctx @{} (parse-string "(a/f 42)"))) "alias a works") + (assert (= 41 (eval-form ctx @{} (parse-string "(b/g 42)"))) "alias b works")) +(print " passed") + +(print "\nAll namespace tests passed!") diff --git a/test/integration/nrepl-test.janet b/test/integration/nrepl-test.janet new file mode 100644 index 0000000..fba05b8 --- /dev/null +++ b/test/integration/nrepl-test.janet @@ -0,0 +1,99 @@ +# Integration test: jolt.nrepl server + client over a real TCP/bencode wire. +# +# The server runs in a subprocess (`jolt nrepl PORT`) so the client (this +# process) isn't affected by the server's accept-loop fiber, which leaves the +# shared ctx's current-ns pointing at jolt.nrepl. The client uses the jolt.nrepl +# Clojure API, exercising both halves of the implementation. + +(use ../../src/jolt/api) +(use ../../src/jolt/types) + +(def port "17888") + +# Watchdog: never let a hang stall CI — bail out after 30s. +(ev/spawn (ev/sleep 30) (eprint "nrepl-test: watchdog fired (possible hang)") (os/exit 1)) + +(print "Starting jolt.nrepl server subprocess on port " port " ...") +(def proc (os/spawn ["janet" "src/jolt/main.janet" "nrepl" port] :p {:out :pipe :err :pipe})) + +# Wait until the server accepts connections (poll up to ~5s). +(var ready false) +(var tries 0) +(while (and (not ready) (< tries 50)) + (let [r (protect (net/connect "127.0.0.1" port))] + (if (r 0) (do (:close (r 1)) (set ready true)) + (do (ev/sleep 0.1) (++ tries))))) +(assert ready "nREPL server did not start") + +(def ctx (init)) +(ctx-set-current-ns ctx "user") +(load-string ctx "(require '[jolt.nrepl])") +(load-string ctx (string "(def c (jolt.nrepl/connect {:port " port "}))")) + +(defn ev [e] (eval-string ctx e)) +(var fails 0) +(defn check [label expr expected] + (let [got (ev expr)] + (if (= got expected) + (print " ok " label) + (do (++ fails) (printf " FAIL %s: want %q, got %q" label expected got))))) + +# describe advertises ops +(check "describe has ops" + "(boolean (get (first (jolt.nrepl/request c {\"op\" \"describe\"})) \"ops\"))" true) + +# clone yields a session id +(ev "(def s (jolt.nrepl/client-clone c))") +(check "clone session is string" "(string? s)" true) + +# eval returns a value +(check "eval (+ 1 2)" "(some #(get % \"value\") (jolt.nrepl/client-eval c \"(+ 1 2)\" s))" "3") + +# a def's value renders as #'ns/name (pr-str loops on a var's cyclic ns refs) +(check "def renders as #'ns/name" + "(some #(get % \"value\") (jolt.nrepl/client-eval c \"(def yy 21)\" s))" "#'user/yy") + +# defs persist across evals in the session +(check "def then use" "(some #(get % \"value\") (jolt.nrepl/client-eval c \"(* yy 2)\" s))" "42") + +# stdout is captured and streamed as an out message +(check "println captured as out" + "(some #(get % \"out\") (jolt.nrepl/client-eval c \"(do (println \\\"hi\\\") 9)\" s))" "hi\n") + +# the response carries the current ns +(check "ns field reported" + "(some #(get % \"ns\") (jolt.nrepl/client-eval c \"(+ 1 1)\" s))" "user") + +# in-ns switches the session ns, and it persists to the next eval +(check "in-ns switches ns" + "(some #(get % \"ns\") (jolt.nrepl/client-eval c \"(in-ns (quote foo.bar))\" s))" "foo.bar") +(check "ns persists across evals" + "(some #(get % \"ns\") (jolt.nrepl/client-eval c \"(+ 2 2)\" s))" "foo.bar") +# explicit :ns on the message overrides +(ev "(jolt.nrepl/request c {\"op\" \"eval\" \"code\" \"(+ 1 1)\" \"session\" s \"ns\" \"user\"})") + +# eval error -> eval-error status, and the connection keeps working afterward +(check "eval error status" + "(boolean (some #(let [st (get % \"status\")] (and (sequential? st) (some (fn [x] (= \"eval-error\" x)) st))) (jolt.nrepl/client-eval c \"(/ 1 :z)\" s)))" + true) +(check "still alive after error" + "(some #(get % \"value\") (jolt.nrepl/client-eval c \"(+ 5 5)\" s))" "10") + +# multiple forms in one eval -> a value per form (values arrive as strings) +(check "multiple forms" + "(= [\"2\" \"4\"] (mapv #(get % \"value\") (filter #(get % \"value\") (jolt.nrepl/client-eval c \"(+ 1 1) (+ 2 2)\" s))))" + true) + +# unknown op -> error/unknown-op/done +(check "unknown op status" + "(let [st (get (first (jolt.nrepl/request c {\"op\" \"nope\"})) \"status\")] (and (some #(= \"unknown-op\" %) st) true))" + true) + +# clean up +(ev "(jolt.nrepl/client-close c)") +(os/proc-kill proc true) +(when (os/stat ".nrepl-port") (os/rm ".nrepl-port")) + +(if (> fails 0) + (do (eprint "nrepl-test: " fails " failing check(s)") (os/exit 1)) + (do (print "\nAll nREPL tests passed!") (os/exit 0))) diff --git a/test/integration/sci-bootstrap-test.janet b/test/integration/sci-bootstrap-test.janet new file mode 100644 index 0000000..ddffd4b --- /dev/null +++ b/test/integration/sci-bootstrap-test.janet @@ -0,0 +1,112 @@ +(use ../../src/jolt/evaluator) +(use ../../src/jolt/types) +(use ../../src/jolt/reader) +(use ../../src/jolt/api) + +(def ctx (init)) + +(printf "Loading SCI stubs...\n") +(defn load-stubs [ctx filepath] + (var s (slurp filepath)) + (var count 0) + (while (> (length (string/trim s)) 0) + (def [form rest] (parse-next s)) + (set s rest) + (++ count) + (when (not (nil? form)) + (eval-form ctx @{} form))) + (printf " Loaded %d stub forms\n" count)) + +(load-stubs ctx "src/jolt/clojure/sci/lang_stubs.clj") +(load-stubs ctx "src/jolt/clojure/sci/io_stubs.clj") +(load-stubs ctx "src/jolt/clojure/sci/host_stubs.clj") + +# namespaces.cljc copies vars out of Jolt's own clojure.string/set/walk/edn, so +# make sure those are loaded before it runs. +(each lib ["clojure.string" "clojure.set" "clojure.walk" "clojure.edn"] + (protect (eval-form ctx @{} (first (parse-next (string "(require '[" lib "])")))))) + +(defn load-file [ctx path] + (var s (slurp path)) + (var count 0) + (var ok 0) + (var fail 0) + (var failures @[]) + (while (> (length (string/trim s)) 0) + (def [form rest] (parse-next s)) + (set s rest) + (++ count) + (if (not (nil? form)) + (do + (printf "eval form %d..." count) + (flush) + (if (try + (do (eval-form ctx @{} form) true) + ([err fib] + (printf " FAIL: %q\n" err) + (when (os/getenv "SCI_TRACE") (debug/stacktrace fib "")) + (array/push failures {:form-number count :error (string err) :form (string form)}) + false)) + (do + (printf " OK\n") + (++ ok)) + (++ fail))))) + {:ok ok :fail fail :total count :failures failures}) + +(def sci-base "vendor/sci/src/sci") + +(def load-order @[ + ["impl/macros.cljc" nil] + ["impl/protocols.cljc" nil] + ["impl/types.cljc" nil] + ["impl/unrestrict.cljc" nil] + ["impl/vars.cljc" nil] + ["lang.cljc" nil] + ["impl/utils.cljc" nil] + ["ctx_store.cljc" nil] + ["impl/deftype.cljc" nil] + ["impl/records.cljc" nil] + ["impl/core_protocols.cljc" nil] + ["impl/hierarchies.cljc" nil] + # pure-Clojure macro/expander modules (loadable from SCI's real source) + ["impl/destructure.cljc" nil] + ["impl/doseq_macro.cljc" nil] + ["impl/for_macro.cljc" nil] + ["impl/fns.cljc" nil] + ["impl/multimethods.cljc" nil] + ["impl/namespaces.cljc" nil] + ["core.cljc" nil] +]) + +(var total-ok 0) +(var total-fail 0) +(var all-failures @[]) + +(each [file expected-ns] load-order + (def path (string sci-base "/" file)) + (printf "\n=== Loading %s ===\n" file) + (def result (load-file ctx path)) + (printf " Result: %d ok, %d fail, %d total\n" (result :ok) (result :fail) (result :total)) + (+= total-ok (result :ok)) + (+= total-fail (result :fail)) + (each f (result :failures) + (array/push all-failures {:file file :form-number (f :form-number) :error (f :error) :form (f :form)}))) + +(printf "\n==============================\n") +(printf "TOTAL: %d ok, %d fail, %d total\n" total-ok total-fail (+ total-ok total-fail)) +(printf "==============================\n") + +(printf "\ncurrent ns: %s\n" (ctx-current-ns ctx)) +(printf "sci.core exists: %q\n" (not (nil? (ctx-find-ns ctx "sci.core")))) +(printf "total namespaces: %d\n" (length (keys ((ctx :env) :namespaces)))) + +(when (> (length all-failures) 0) + (printf "\n=== FAILURES ===\n") + (each f all-failures + (printf "[%s:%d] %s\n" (f :file) (f :form-number) (f :error)) + (printf " form: %s\n" (f :form)))) + +# Regression guard: every form in the loaded SCI modules must evaluate cleanly. +(assert (= 0 total-fail) + (string total-fail " SCI form(s) failed to load (see FAILURES above)")) +(print "\nAll SCI bootstrap forms loaded successfully.") diff --git a/test/integration/sci-runtime-test.janet b/test/integration/sci-runtime-test.janet new file mode 100644 index 0000000..a21bb27 --- /dev/null +++ b/test/integration/sci-runtime-test.janet @@ -0,0 +1,95 @@ +(use ../../src/jolt/evaluator) +(use ../../src/jolt/types) +(use ../../src/jolt/reader) +(use ../../src/jolt/api) + +(defn- load-stubs [ctx filepath] + (var s (slurp filepath)) + (while (> (length (string/trim s)) 0) + (def [form rest] (parse-next s)) + (set s rest) + (when (not (nil? form)) + (protect (eval-form ctx @{} form))))) + +(defn- load-file [ctx path] + (var s (slurp path)) + (while (> (length (string/trim s)) 0) + (def [form rest] (parse-next s)) + (set s rest) + (when (not (nil? form)) + # Tolerant: SCI's clojure.core registration maps reference the full + # clojure.core surface (redundant for Jolt's native core); skip forms + # that don't resolve rather than aborting the bootstrap. + (protect (eval-form ctx @{} form))))) + +# Run from project root so paths resolve +(def root (if (has-value? (dyn :syspath) 0) (first (dyn :syspath)) ".")) + +(def ctx (init)) + +(load-stubs ctx (string root "/src/jolt/clojure/sci/lang_stubs.clj")) +(load-stubs ctx (string root "/src/jolt/clojure/sci/io_stubs.clj")) + +(def sci-base (string root "/vendor/sci/src/sci")) +(each file ["impl/macros.cljc" "impl/protocols.cljc" "impl/types.cljc" + "impl/unrestrict.cljc" "impl/vars.cljc" "lang.cljc" + "impl/utils.cljc" "ctx_store.cljc" "impl/deftype.cljc" + "impl/records.cljc" "impl/core_protocols.cljc" "impl/hierarchies.cljc" + "impl/namespaces.cljc" "core.cljc"] + (load-file ctx (string sci-base "/" file))) + +# ── Verify sci.lang NS and Type ───────────────────────────────── +(assert (not (nil? (ctx-find-ns ctx "sci.lang"))) + "sci.lang namespace exists") +(assert (not (nil? (ctx-find-ns ctx "sci.core"))) + "sci.core namespace exists") + +# sci.lang has Type constructor +(def sci-lang (ctx-find-ns ctx "sci.lang")) +(def type-var (ns-find sci-lang "Type")) +(assert (not (nil? type-var)) "sci.lang/Type var exists") +(def ->Type (ns-find sci-lang "->Type")) +(assert (not (nil? ->Type)) "sci.lang/->Type constructor exists") + +# Instantiate a Type and check field access +(def type-inst ((var-get type-var) {:sci.impl/type-name "user.Foo"})) +(assert (table? type-inst) "Type instance is a table") +(assert (not (nil? (get type-inst :jolt/deftype))) "Type instance has deftype tag") +(assert (= "user.Foo" (get (get type-inst :data) :sci.impl/type-name)) "Type field access via data") + +# ── Verify sci.lang/Var ───────────────────────────────────────── +(def var-ctor-var (ns-find sci-lang "Var")) +(assert (not (nil? var-ctor-var)) "sci.lang/Var constructor exists") + +(def test-var ((var-get var-ctor-var) 42 'my-var nil nil nil nil nil)) +(assert (table? test-var) "Var instance is a table") +(assert (= 42 (get test-var :root)) "Var deref") + +# var? check — SCI Var is not a Jolt var but is a table with proper fields +(assert (not (nil? test-var)) "Var instance is not nil") + +# ── Verify sci.impl.types/IBox protocol ───────────────────────── +(def types-ns (ctx-find-ns ctx "sci.impl.types")) +(def vars-ns (ctx-find-ns ctx "sci.impl.vars")) +(assert (not (nil? types-ns)) "sci.impl.types namespace exists") +(assert (not (nil? vars-ns)) "sci.impl.vars namespace exists") + +(def ibox-getVal (ns-find types-ns "getVal")) +(def ibox-setVal (ns-find types-ns "setVal")) +(assert (not (nil? ibox-getVal)) "sci.impl.types/getVal exists") +(assert (not (nil? ibox-setVal)) "sci.impl.types/setVal exists") + +# Test IBox setVal/getVal exist but skip dispatch (SCI protocol machinery not fully booted) +(assert (function? (var-get ibox-setVal)) "sci.impl.types/setVal is callable") +(assert (function? (var-get ibox-getVal)) "sci.impl.types/getVal is callable") + +# ── Verify sci.impl.vars/IVar protocol methods exist ───────────── +(def ivar-toSymbol (ns-find vars-ns "toSymbol")) +(def ivar-hasRoot (ns-find vars-ns "hasRoot")) +(assert (not (nil? ivar-toSymbol)) "sci.impl.vars/toSymbol exists") +(assert (not (nil? ivar-hasRoot)) "sci.impl.vars/hasRoot exists") + +# ── Verify SCI eval function exists ───────────────────────────── +(def sci-core (ctx-find-ns ctx "sci.core")) +(assert (not (nil? sci-core)) "sci.core namespace exists") +(printf "\nAll SCI runtime tests passed!\n") diff --git a/test/integration/self-host-test.janet b/test/integration/self-host-test.janet new file mode 100644 index 0000000..3e0518d --- /dev/null +++ b/test/integration/self-host-test.janet @@ -0,0 +1,88 @@ +# End-to-end proof of the self-hosting pipeline: a reader form is analyzed by the +# PORTABLE Clojure analyzer (jolt.analyzer, in jolt-core) into host-neutral IR, +# then the Janet back end lowers the IR to a Janet form and evaluates it. No use +# of compiler.janet's analyzer — this is the Clojure-in-Clojure front end. +(import ../../src/jolt/backend :as backend) +(use ../../src/jolt/api) +(use ../../src/jolt/reader) +(use ../../src/jolt/types) + +(defn ce [ctx s] (normalize-pvecs (backend/compile-and-eval ctx (parse-string s)))) + +(print "self-host pipeline (Clojure analyzer -> IR -> Janet)...") +(let [ctx (init)] + # primitives + control flow + (assert (= 3 (ce ctx "(+ 1 2)")) "+") + (assert (= 6 (ce ctx "(* 2 3)")) "*") + (assert (= :a (ce ctx "(if true :a :b)")) "if true") + (assert (= :b (ce ctx "(if false :a :b)")) "if false") + (assert (= 10 (ce ctx "(let [x 4 y 6] (+ x y))")) "let") + (assert (= 6 (ce ctx "(do 1 2 6)")) "do") + + # literals + (assert (= [2 3 4] (ce ctx "(map inc [1 2 3])")) "vector literal + core fn") + (assert (= 1 (ce ctx "(get {:a 1 :b 2} :a)")) "map literal") + (assert (= 42 (ce ctx "(quote 42)")) "quote literal") + + # def + global reference (name-based var resolution) + (ce ctx "(def base 100)") + (assert (= 142 (ce ctx "(+ base 42)")) "def + later ref") + + # fn / defn (defn is a macro -> expand -> def of fn*) + (ce ctx "(defn add [a b] (+ a b))") + (assert (= 7 (ce ctx "(add 3 4)")) "defn") + (assert (= 49 (ce ctx "((fn [x] (* x x)) 7)")) "anon fn") + + # recursion through the var cell (no recur needed) + (ce ctx "(defn fib [n] (if (< n 2) n (+ (fib (- n 1)) (fib (- n 2)))))") + (assert (= 55 (ce ctx "(fib 10)")) "recursive fib via var") + + # multi-arity + variadic + (ce ctx "(defn arity ([a] a) ([a b] (+ a b)) ([a b & more] (apply + a b more)))") + (assert (= 5 (ce ctx "(arity 5)")) "multi-arity 1") + (assert (= 7 (ce ctx "(arity 3 4)")) "multi-arity 2") + (assert (= 15 (ce ctx "(arity 1 2 3 4 5)")) "multi-arity variadic") + + # loop / recur + (assert (= 15 (ce ctx "(loop [i 0 acc 0] (if (< i 6) (recur (inc i) (+ acc i)) acc))")) "loop/recur") + # recur directly in a fixed-arity fn + (assert (= 15 (ce ctx "((fn [n acc] (if (zero? n) acc (recur (dec n) (+ acc n)))) 5 0)")) "recur in fn") + # try / catch / finally + (assert (= "caught" (ce ctx "(try (throw 42) (catch Exception e \"caught\"))")) "try/catch") + (assert (= 7 (ce ctx "(try 7 (finally 0))")) "try/finally") + + # higher-order + nesting + (assert (= 15 (ce ctx "(reduce + (map inc [0 1 2 3 4]))")) "reduce+map")) + +# eval-toplevel routing: :compile? IS the self-hosted pipeline now — the only +# compile path. Forms the analyzer can't handle (stateful / destructuring) fall +# back to the interpreter, with the same observable results. +(print "self-host via eval-toplevel routing...") +(let [ctx (init {:compile? true})] + (defn ev [s] (normalize-pvecs (eval-one ctx (parse-string s)))) + (assert (= 3 (ev "(+ 1 2)")) "tl +") + (ev "(defn sq [x] (* x x))") # def via self-host + (assert (= 81 (ev "(sq 9)")) "tl defn") + (ev "(defmacro twice [x] (list (quote do) x x))") # stateful -> interp fallback + (assert (= 5 (ev "(do (twice 1) 5)")) "tl macro fallback") + (assert (= [1 2 3] (ev "(let [{:keys [a b c]} {:a 1 :b 2 :c 3}] [a b c])")) "tl destructuring fallback") + (assert (= 15 (ev "(reduce + (range 6))")) "tl reduce/range") + # Proof the self-hosted pipeline actually ran: only backend/ensure-analyzer + # populates jolt.analyzer. An interpret-only ctx never loads it. + (assert (pos? (length ((ctx-find-ns ctx "jolt.analyzer") :mappings))) "analyzer loaded under :compile?")) +(let [ctx (init {})] + (eval-one ctx (parse-string "(+ 1 2)")) + (assert (zero? (length ((ctx-find-ns ctx "jolt.analyzer") :mappings))) "analyzer NOT loaded when interpreting")) + +# clojure.core overlay: fns moved from core.janet to jolt-core/clojure/core.clj +# load into clojure.core at init and work the same compiled or interpreted. +(print "clojure.core overlay (Clojure-defined core fns)...") +(each opts [{:compile? true} {}] + (let [ctx (init opts)] + (defn ev [s] (normalize-pvecs (eval-one ctx (parse-string s)))) + (assert (= 1 (ev "(ffirst [[1 2] [3 4]])")) "ffirst") + (assert (= [2] (ev "(nfirst [[1 2] [3 4]])")) "nfirst") + (assert (= 2 (ev "(fnext [1 2 3])")) "fnext") + (assert (= [3 4] (ev "(nnext [1 2 3 4])")) "nnext"))) + +(print "self-host pipeline passed!") diff --git a/test/integration/staged-bootstrap-test.janet b/test/integration/staged-bootstrap-test.janet new file mode 100644 index 0000000..7f2a54c --- /dev/null +++ b/test/integration/staged-bootstrap-test.janet @@ -0,0 +1,63 @@ +# Staged-bootstrap soundness (jolt-vcx, under epic jolt-tzo). +# +# The self-hosted compiler's structural deps — second/peek/subvec/mapv/update — +# now come from the Clojure kernel tier (jolt-core/clojure/core/00-kernel.clj), +# bootstrap-compiled into clojure.core BEFORE the analyzer is built. This pins +# the two properties that make that safe: +# +# 1. Compile mode: the analyzer (which itself calls second/peek/subvec/mapv) +# compiles analyzer-exercising forms correctly — the exact case that broke +# when `second` was a plain overlay fn: (first {:a 1}) / (key (first ...)). +# 2. Bootstrap FIXPOINT: rebuilding the compiler (rebuild-compiler!) against the +# now Clojure-defined core still yields a correct compiler. This is the +# soundness gate for every future fractal turn (S2 -> S3). + +(use ../../src/jolt/api) +(import ../../src/jolt/backend :as backend) + +(var failures 0) + +# Each probe is a jolt boolean expression; compared with jolt's own `=`. +(def probes + ["(= 2 (second [1 2 3]))" + "(= nil (second [1]))" + "(= 3 (peek [1 2 3]))" + "(= 1 (peek (list 1 2 3)))" + "(= nil (peek []))" + "(= [2 3] (subvec [1 2 3 4 5] 1 3))" + "(= [3 4 5] (subvec [1 2 3 4 5] 2))" + "(= [2 3 4] (mapv inc [1 2 3]))" + "(= [11 22 33] (mapv + [1 2 3] [10 20 30]))" + "(= {:a 2} (update {:a 1} :a inc))" + "(= {:a 1 :b 1} (update {:a 1} :b (fnil inc 0)))" + # Regression: these run the analyzer's own second/map-pair path in compile mode. + "(= [:a 1] (first {:a 1}))" + "(= :a (key (first {:a 1})))" + "(= 1 (val (first {:a 1})))" + "(= 3 (let [[a b] [1 2]] (+ a b)))" + "(= 3 (loop [i 0 acc 0] (if (< i 3) (recur (inc i) (+ acc i)) acc)))"]) + +(defn- run-probes [ctx label] + (each prog probes + (def got (protect (eval-string ctx prog))) + (unless (and (got 0) (= (got 1) true)) + (++ failures) + (printf "FAIL [%s] %s => %s" label prog + (if (got 0) (string/format "%q" (got 1)) (string "ERR:" (got 1))))))) + +# Interpret mode: kernel tier interpreted, no analyzer involved. +(run-probes (init {}) "interpret") + +# Compile mode: kernel tier bootstrap-compiled, analyzer built against it. +(def cctx (init {:compile? true})) +(run-probes cctx "compile") + +# Fixpoint: rebuild the compiler against the current (Clojure-defined) core and +# re-run. A correct compiler recompiled on the language it just defined stays +# correct. +(backend/rebuild-compiler! cctx) +(run-probes cctx "compile+rebuilt") + +(if (pos? failures) + (do (printf "staged-bootstrap: %d failure(s)" failures) (os/exit 1)) + (print "staged-bootstrap: all probes passed (interpret, compile, compile+rebuilt)")) diff --git a/test/integration/suite-worker.janet b/test/integration/suite-worker.janet new file mode 100644 index 0000000..8a515e5 --- /dev/null +++ b/test/integration/suite-worker.janet @@ -0,0 +1,60 @@ +# One-file worker for the clojure-test-suite battery. Loads the clojure.test +# shim, evaluates a single suite .cljc file, runs its deftests, and prints +# "pass fail error" to stdout. Used by the discovery pass to find files that +# hang under Jolt's eager evaluation (run under an external timeout). +(use ../../src/jolt/api) +(use ../../src/jolt/reader) +(use ../../src/jolt/evaluator) +(import ../../src/jolt/backend :as selfhost) + +(defn- parse-forms [src] + (var s src) (def fs @[]) (var go true) + (while (and go (> (length (string/trim s)) 0)) + (def r (protect (parse-next s))) + (if (not (r 0)) (set go false) + (let [p (r 1)] (set s (p 1)) (when (not (nil? (p 0))) (array/push fs (p 0)))))) + fs) + +# A helper, not a standalone test: it needs a .cljc path argument. When `jpm +# test` runs it with no args, no-op cleanly so it doesn't count as a failure. +(def path (get (dyn :args) 1)) + +(when path + # JOLT_COMPILE=1 runs the suite through the compile path (hybrid: hot forms + # compile, unsupported forms fall back to the interpreter) so the whole battery + # validates compile-mode correctness against the same baseline. + (def compile? (= "1" (os/getenv "JOLT_COMPILE"))) + # JOLT_SELFHOST=1 routes each form through the self-hosted pipeline (the + # portable Clojure analyzer + Janet back end, hybrid with interpreter fallback) + # so the whole battery validates the self-hosted compiler against the baseline. + (def selfhost? (= "1" (os/getenv "JOLT_SELFHOST"))) + (def ctx (init (if compile? {:compile? true} {}))) + (defn run-form [f] + (cond + selfhost? (selfhost/compile-and-eval ctx f) + compile? (eval-one ctx f) + (eval-form ctx @{} f))) + (each f (parse-forms (slurp "test/support/clojure_test.clj")) (run-form f)) + + # Pre-load the suite's own clojure.core-test.number-range helper ns if present + # (35 files require it for r/max-int, r/max-double, … — its :default branches are + # plain numeric literals Jolt can read). Its `ns` form sets the namespace; the + # test file's own `ns` form switches back afterwards. + (let [dir (string/slice path 0 (- (length path) (length (last (string/split "/" path))))) + nr (string dir "number_range.cljc")] + (when (os/stat nr) + (each f (parse-forms (slurp nr)) (protect (run-form f))))) + + (eval-string ctx "(clojure.test/reset-report!)") + (each form (parse-forms (slurp path)) (protect (run-form form))) + (protect (eval-string ctx "(clojure.test/run-registered)")) + (def p (eval-string ctx "(clojure.test/n-pass)")) + (def f (eval-string ctx "(clojure.test/n-fail)")) + (def e (eval-string ctx "(clojure.test/n-error)")) + # A "dump" 2nd arg (or SUITE_DUMP env) also prints each failure/error message + # (one DUMP line each) for triage. + (when (or (os/getenv "SUITE_DUMP") (= "dump" (get (dyn :args) 2))) + (eval-string ctx "(doseq [m (clojure.test/failures)] (println (str \"DUMP \" m)))")) + # Counts on a sentinel line so parsers find it even if a test body printed to + # stdout (e.g. with-out-str / println-str tests). + (printf "@@COUNTS %d %d %d" (if (number? p) p 0) (if (number? f) f 0) (if (number? e) e 0))) diff --git a/test/integration/systematic-coverage-test.janet b/test/integration/systematic-coverage-test.janet new file mode 100644 index 0000000..14fd485 --- /dev/null +++ b/test/integration/systematic-coverage-test.janet @@ -0,0 +1,214 @@ +# Systematic coverage tests for Clojure language features +(use ../../src/jolt/api) +(defn ct-eval [ctx s] (normalize-pvecs (eval-string ctx s))) + +(print "Systematic Coverage Tests") + +# --- Type Predicates --- +(print "1: type predicates...") +(let [ctx (init)] + (assert (= true (ct-eval ctx "(integer? 0)")) "integer? 0") + (assert (= true (ct-eval ctx "(integer? 1)")) "integer? 1") + (assert (= true (ct-eval ctx "(integer? -5)")) "integer? negative") + (assert (= false (ct-eval ctx "(integer? 1.5)")) "integer? float") + (assert (= false (ct-eval ctx "(integer? nil)")) "integer? nil") + (assert (= false (ct-eval ctx "(integer? \"abc\")")) "integer? string") + (assert (= true (ct-eval ctx "(boolean? true)")) "boolean? true") + (assert (= true (ct-eval ctx "(boolean? false)")) "boolean? false") + (assert (= false (ct-eval ctx "(boolean? 1)")) "boolean? falsy") + (assert (= false (ct-eval ctx "(boolean? nil)")) "boolean? nil") + (assert (= true (ct-eval ctx "(nil? nil)")) "nil? nil") + (assert (= false (ct-eval ctx "(nil? false)")) "nil? false") + (assert (= false (ct-eval ctx "(nil? 0)")) "nil? 0") + (assert (= false (ct-eval ctx "(nil? [])")) "nil? empty vec") + (assert (= false (ct-eval ctx "(some? nil)")) "some? nil") + (assert (= true (ct-eval ctx "(some? false)")) "some? false") + (assert (= true (ct-eval ctx "(some? 0)")) "some? 0") + (assert (= true (ct-eval ctx "(some? [])")) "some? empty vec") + (assert (= true (ct-eval ctx "(string? \"hello\")")) "string?") + (assert (= false (ct-eval ctx "(string? 42)")) "string? false") + (assert (= true (ct-eval ctx "(string? \"\")")) "string? empty") + (assert (= true (ct-eval ctx "(number? 42)")) "number? int") + (assert (= true (ct-eval ctx "(number? 3.14)")) "number? float") + (assert (= false (ct-eval ctx "(number? \"42\")")) "number? string") + (assert (= true (ct-eval ctx "(fn? inc)")) "fn? builtin") + (assert (= false (ct-eval ctx "(fn? 42)")) "fn? false") + (assert (= true (ct-eval ctx "(keyword? :foo)")) "keyword?") + (assert (= false (ct-eval ctx "(keyword? \"foo\")")) "keyword? false") + (assert (= true (ct-eval ctx "(symbol? 'abc)")) "symbol?") + (assert (= false (ct-eval ctx "(symbol? :abc)")) "symbol? false") + (assert (= true (ct-eval ctx "(map? {:a 1})")) "map?") + (assert (= false (ct-eval ctx "(map? [1 2])")) "map? false") + (assert (= true (ct-eval ctx "(set? #{1 2})")) "set?") + (assert (= false (ct-eval ctx "(set? [1 2])")) "set? false") + (assert (= true (ct-eval ctx "(seq? '(1 2))")) "seq? list") + # vectors are not ISeq in Clojure — (seq? [1 2]) is false + (assert (= false (ct-eval ctx "(seq? [1 2])")) "seq? vector is false") + (assert (= true (ct-eval ctx "(coll? [1 2])")) "coll? vec") + (assert (= true (ct-eval ctx "(coll? '(1 2))")) "coll? list") + (assert (= true (ct-eval ctx "(coll? {})")) "coll? map") + (assert (= true (ct-eval ctx "(true? true)")) "true? true") + (assert (= false (ct-eval ctx "(true? 1)")) "true? 1") + (assert (= true (ct-eval ctx "(false? false)")) "false? false") + (assert (= false (ct-eval ctx "(false? nil)")) "false? nil") + (assert (= true (ct-eval ctx "(identical? 42 42)")) "identical? same value")) +(print " ok") + +# --- Number Predicates --- +(print "2: number predicates...") +(let [ctx (init)] + (assert (= true (ct-eval ctx "(zero? 0)")) "zero? 0") + (assert (= false (ct-eval ctx "(zero? 1)")) "zero? 1") + # zero?/pos?/neg? now reject non-numbers (Clojure-strict), like the JVM. + (assert (not ((protect (ct-eval ctx "(zero? nil)")) 0)) "zero? nil throws") + (assert (= true (ct-eval ctx "(pos? 1)")) "pos?") + (assert (= false (ct-eval ctx "(pos? 0)")) "pos? 0") + (assert (= false (ct-eval ctx "(pos? -1)")) "pos? -1") + (assert (= true (ct-eval ctx "(neg? -1)")) "neg?") + (assert (= false (ct-eval ctx "(neg? 0)")) "neg? 0") + (assert (= false (ct-eval ctx "(neg? 1)")) "neg? 1") + (assert (= true (ct-eval ctx "(even? 0)")) "even? 0") + (assert (= true (ct-eval ctx "(even? 2)")) "even? 2") + (assert (= false (ct-eval ctx "(even? 1)")) "even? 1") + (assert (= true (ct-eval ctx "(odd? 1)")) "odd? 1") + (assert (= true (ct-eval ctx "(odd? 3)")) "odd? 3") + (assert (= false (ct-eval ctx "(odd? 2)")) "odd? 2")) +(print " ok") + +# --- Math --- +(print "3: math operations...") +(let [ctx (init)] + (assert (= 0 (ct-eval ctx "(+)")) "+ 0 args") + (assert (= 5 (ct-eval ctx "(+ 2 3)")) "+ 2 args") + (assert (= 10 (ct-eval ctx "(+ 1 2 3 4)")) "+ varargs") + (assert (= -5 (ct-eval ctx "(- 5)")) "- unary") + (assert (= 2 (ct-eval ctx "(- 5 3)")) "- binary") + (assert (= 1 (ct-eval ctx "(*)")) "* 0 args") + (assert (= 6 (ct-eval ctx "(* 2 3)")) "*") + (assert (= 0.5 (ct-eval ctx "(/ 2)")) "/ unary reciprocal") + (assert (= 2 (ct-eval ctx "(/ 4 2)")) "/ binary") + (assert (= 2 (ct-eval ctx "(quot 5 2)")) "quot") + (assert (= 1 (ct-eval ctx "(rem 5 2)")) "rem") + (assert (= 1 (ct-eval ctx "(mod 5 2)")) "mod") + (assert (= 43 (ct-eval ctx "(inc 42)")) "inc") + (assert (= 41 (ct-eval ctx "(dec 42)")) "dec") + (assert (= 3 (ct-eval ctx "(max 1 2 3)")) "max") + (assert (= 1 (ct-eval ctx "(min 1 2 3)")) "min") + (assert (= 5 (ct-eval ctx "(abs -5)")) "abs negative") + (assert (= 5 (ct-eval ctx "(abs 5)")) "abs positive") + (assert (= 0 (ct-eval ctx "(abs 0)")) "abs 0") + (assert (= 3.14 (ct-eval ctx "(abs -3.14)")) "abs float") + (assert (= true (ct-eval ctx "(< (rand) 1)")) "rand < 1") + (assert (= true (ct-eval ctx "(number? (rand-int 10))")) "rand-int type")) +(print " ok") + +# --- Comparison --- +(print "4: comparison...") +(let [ctx (init)] + (assert (= true (ct-eval ctx "(= 1 1)")) "= same") + (assert (= true (ct-eval ctx "(= 1 1 1)")) "= multi same") + (assert (= false (ct-eval ctx "(= 1 2)")) "= different") + (assert (= true (ct-eval ctx "(not= 1 2)")) "not= different") + (assert (= false (ct-eval ctx "(not= 1 1)")) "not= same") + (assert (= true (ct-eval ctx "(< 1 2)")) "<") + (assert (= false (ct-eval ctx "(< 2 1)")) "< false") + (assert (= true (ct-eval ctx "(> 2 1)")) ">") + (assert (= true (ct-eval ctx "(<= 1 1)")) "<=") + (assert (= true (ct-eval ctx "(>= 2 2)")) ">=")) +(print " ok") + +# --- Boolean logic --- +(print "5: boolean logic...") +(let [ctx (init)] + (assert (= true (ct-eval ctx "(and)")) "and empty") + (assert (= true (ct-eval ctx "(and true)")) "and true") + (assert (= nil (ct-eval ctx "(and nil)")) "and nil") + (assert (= false (ct-eval ctx "(and false)")) "and false") + (assert (= 3 (ct-eval ctx "(and 1 2 3)")) "and last") + (assert (= nil (ct-eval ctx "(and 1 nil 3)")) "and short-circuit") + (assert (= nil (ct-eval ctx "(or)")) "or empty") + (assert (= true (ct-eval ctx "(or true)")) "or true") + (assert (= nil (ct-eval ctx "(or nil)")) "or nil") + (assert (= false (ct-eval ctx "(or false)")) "or false") + (assert (= 1 (ct-eval ctx "(or nil false 1 2)")) "or first truthy") + (assert (= false (ct-eval ctx "(or nil false)")) "or all falsy") + (assert (= false (ct-eval ctx "(not true)")) "not true") + (assert (= true (ct-eval ctx "(not nil)")) "not nil") + (assert (= true (ct-eval ctx "(not false)")) "not false")) +(print " ok") + +# --- Collections --- +(print "6: collections...") +(let [ctx (init)] + (assert (= true (ct-eval ctx "(empty? nil)")) "empty? nil") + (assert (= true (ct-eval ctx "(empty? [])")) "empty? []") + (assert (= true (ct-eval ctx "(empty? ())")) "empty? ()") + (assert (= true (ct-eval ctx "(empty? {})")) "empty? {}") + (assert (= true (ct-eval ctx "(empty? #{})")) "empty? #{}") + (assert (= true (ct-eval ctx "(empty? \"\")")) "empty? empty string") + (assert (= false (ct-eval ctx "(empty? [1])")) "empty? non-empty") + (assert (= true (ct-eval ctx "(every? even? [2 4 6])")) "every? true") + (assert (= false (ct-eval ctx "(every? even? [2 3 4])")) "every? false") + (assert (= 3 (ct-eval ctx "(count [1 2 3])")) "count vector") + (assert (= 2 (ct-eval ctx "(count {:a 1 :b 2})")) "count map") + (assert (= 3 (ct-eval ctx "(count #{1 2 3})")) "count set") + (assert (= 3 (ct-eval ctx "(count \"abc\")")) "count string")) +(print " ok") + +# --- Sequence Operations --- +(print "7: sequence operations...") +(let [ctx (init)] + (assert (= 1 (ct-eval ctx "(first [1 2 3])")) "first") + (assert (= nil (ct-eval ctx "(first [])")) "first empty") + (assert (= nil (ct-eval ctx "(first nil)")) "first nil") + (assert (= :a (ct-eval ctx "(nth [:a :b :c] 0)")) "nth 0") + (assert (= :c (ct-eval ctx "(nth [:a :b :c] 2)")) "nth 2") + (assert (= :d (ct-eval ctx "(nth [:a :b :c] 3 :d)")) "nth default") + (assert (= nil (ct-eval ctx "(seq [])")) "seq empty -> nil") + (assert (= nil (ct-eval ctx "(seq nil)")) "seq nil -> nil") + (assert (= true (ct-eval ctx "(= [2 3 4] (map inc [1 2 3]))")) "map") + (assert (= true (ct-eval ctx "(= [2 4] (filter even? [1 2 3 4]))")) "filter") + (assert (= 6 (ct-eval ctx "(reduce + [1 2 3])")) "reduce") + (assert (= 10 (ct-eval ctx "(reduce + 4 [1 2 3])")) "reduce init") + (assert (= true (ct-eval ctx "(= [1 2] (take 2 [1 2 3 4]))")) "take") + (assert (= true (ct-eval ctx "(= [3 4] (drop 2 [1 2 3 4]))")) "drop") + (assert (= true (ct-eval ctx "(= [3 2 1] (reverse [1 2 3]))")) "reverse") + (assert (= true (ct-eval ctx "(= 3 (count (distinct [1 1 2 2 3 3])))")) "distinct")) +(print " ok") + +# --- Collections: conj, assoc, dissoc, get --- +(print "8: collection mutation...") +(let [ctx (init)] + (assert (= true (ct-eval ctx "(= [1 2 3] (conj [1 2] 3))")) "conj vector") + (assert (= true (ct-eval ctx "(= (quote (0 1 2)) (conj (quote (1 2)) 0))")) "conj list prepend") + (assert (= true (ct-eval ctx "(= {:a 1 :b 2} (assoc {:a 1} :b 2))")) "assoc") + (assert (= true (ct-eval ctx "(= {:a 1} (dissoc {:a 1 :b 2} :b))")) "dissoc") + (assert (= 1 (ct-eval ctx "(get {:a 1} :a)")) "get") + (assert (= nil (ct-eval ctx "(get {:a 1} :z)")) "get missing") + (assert (= :d (ct-eval ctx "(get {:a 1} :z :d)")) "get default") + (assert (= true (ct-eval ctx "(contains? {:a 1} :a)")) "contains? map") + (assert (= false (ct-eval ctx "(contains? {:a 1} :z)")) "contains? missing") + (assert (= true (ct-eval ctx "(contains? [5 6 7] 1)")) "contains? vector") + (assert (= false (ct-eval ctx "(contains? [5 6 7] 3)")) "contains? vector oob")) +(print " ok") + +# --- Higher-order functions --- +(print "9: higher-order functions...") +(let [ctx (init)] + (assert (= 3 (ct-eval ctx "((comp inc inc) 1)")) "comp") + (assert (= 42 (ct-eval ctx "(identity 42)")) "identity") + (assert (= 99 (ct-eval ctx "((constantly 99) :anything)")) "constantly") + (assert (= true (ct-eval ctx "(= 10 ((partial + 3 7)))")) "partial") + (assert (= true (ct-eval ctx "((every-pred even? pos?) 4)")) "every-pred true") + (assert (= false (ct-eval ctx "((every-pred even? pos?) -4)")) "every-pred false") + (assert (= false (ct-eval ctx "((complement even?) 2)")) "complement")) +(print " ok") + +# --- Destructuring --- +(print "10: destructuring...") +(let [ctx (init)] + (assert (= 1 (ct-eval ctx "(let [[x] [1 2 3]] x)")) "seq destructure first") + (assert (= 2 (ct-eval ctx "(let [[_ y] [1 2 3]] y)")) "seq destructure second")) +(print " ok") + +(print "\nAll Systematic Coverage tests passed!") diff --git a/test/integration/uberscript-test.janet b/test/integration/uberscript-test.janet new file mode 100644 index 0000000..37ac08f --- /dev/null +++ b/test/integration/uberscript-test.janet @@ -0,0 +1,51 @@ +# `jolt uberscript` bundles a namespace and everything it requires into one .clj +# that runs on a plain jolt with no JOLT_PATH / deps. Runs from source. + +(defn- run [env-jolt-path & args] + (if env-jolt-path (os/setenv "JOLT_PATH" env-jolt-path) (os/setenv "JOLT_PATH" nil)) + (def p (os/spawn ["janet" "src/jolt/main.janet" ;args] :p {:out :pipe :err :pipe})) + (def out (:read (p :out) :all)) + (os/proc-wait p) + (string (or out ""))) + +(defn- mkdirs [p] + (var acc nil) + (each seg (filter |(not= "" $) (string/split "/" p)) + (set acc (if (nil? acc) (if (string/has-prefix? "/" p) (string "/" seg) seg) (string acc "/" seg))) + (unless (os/stat acc) (os/mkdir acc)))) +(defn- rmrf [p] + (when (os/stat p) + (if (= :directory (os/stat p :mode)) + (do (each e (os/dir p) (rmrf (string p "/" e))) (os/rmdir p)) + (os/rm p)))) + +(def base (string (or (os/getenv "TMPDIR") "/tmp") "/jolt-uber-" (os/time))) +(rmrf base) +(mkdirs (string base "/proj/src/app")) +(mkdirs (string base "/lib/src/greet")) +(spit (string base "/lib/src/greet/core.clj") + "(ns greet.core)\n(defn hello [n] (str \"Hello, \" n \"!\"))\n") +(spit (string base "/proj/src/app/core.clj") + "(ns app.core (:require [greet.core :as g]))\n(defn -main [& args] (println (g/hello (or (first args) \"world\"))))\n") + +(var fails 0) +(defn check [label got pred] + (if (pred got) (print " ok " label) + (do (++ fails) (printf " FAIL %s: got %q" label got)))) +(defn- has [s] (fn [x] (string/find s x))) + +(def roots (string base "/proj/src:" base "/lib/src")) +(def out (string base "/out.clj")) + +# build the uberscript with the dep roots on JOLT_PATH +(run roots "uberscript" out "-m" "app.core") +(check "uberscript written" (if (os/stat out) "yes" "no") (has "yes")) +(check "bundles the dep ns" (slurp out) (has "(ns greet.core)")) + +# run it standalone: no JOLT_PATH, so it only works if the dep was inlined +(check "runs standalone" (run nil out "Bob") (has "Hello, Bob!")) + +(rmrf base) +(if (> fails 0) + (error (string "uberscript-test: " fails " failing check(s)")) + (print "\nAll uberscript tests passed!")) diff --git a/test/spec/control-flow-spec.janet b/test/spec/control-flow-spec.janet new file mode 100644 index 0000000..ed21b78 --- /dev/null +++ b/test/spec/control-flow-spec.janet @@ -0,0 +1,91 @@ +# Specification: control flow & binding forms. +(use ../support/harness) + +(defspec "control / conditionals" + ["if true" "1" "(if true 1 2)"] + ["if false" "2" "(if false 1 2)"] + ["if nil is false" "2" "(if nil 1 2)"] + ["if no else" "nil" "(if false 1)"] + ["when true" "3" "(when true 1 2 3)"] + ["when false" "nil" "(when false 1)"] + ["when-not" "1" "(when-not false 1)"] + ["cond" ":b" "(cond false :a true :b :else :c)"] + ["cond :else" ":c" "(cond false :a false :b :else :c)"] + ["cond no match" "nil" "(cond false :a)"] + ["condp" "\"two\"" "(condp = 2 1 \"one\" 2 \"two\" \"other\")"] + ["case" ":b" "(case 2 1 :a 2 :b :default)"] + ["case default" ":d" "(case 9 1 :a 2 :b :d)"] + ["case multi" ":ab" "(case 2 (1 2) :ab 3 :c)"] + ["case symbol const" ":s" "(case 'foo foo :s :default)"] + ["case vector const" ":v" "(case [1 2] [1 2] :v :default)"] + ["case map const" ":m" "(case {:a 1} {:a 1} :m :default)"] + ["case list const" ":l" "(case '(a b) (quote (a b)) :l :default)"] + ["case keyword" ":k" "(case :x :x :k :default)"]) + +(defspec "control / logic" + ["and all true" "3" "(and 1 2 3)"] + ["and short circuits" "nil" "(and 1 nil 3)"] + ["and empty" "true" "(and)"] + ["or first truthy" "1" "(or nil 1 2)"] + ["or all false" "false" "(or nil false)"] + ["or empty" "nil" "(or)"] + ["not" "false" "(not true)"]) + +(defspec "control / let & loop" + ["let" "3" "(let [a 1 b 2] (+ a b))"] + ["let sequential" "3" "(let [a 1 b (+ a 2)] b)"] + ["let shadowing" "2" "(let [a 1] (let [a 2] a))"] + ["letfn mutual" "true" "(letfn [(ev? [n] (if (zero? n) true (od? (dec n)))) (od? [n] (if (zero? n) false (ev? (dec n))))] (ev? 10))"] + ["loop/recur" "15" "(loop [i 1 acc 0] (if (> i 5) acc (recur (inc i) (+ acc i))))"] + ["when-let" "2" "(when-let [x 1] (inc x))"] + ["when-let nil" "nil" "(when-let [x nil] (inc x))"] + ["if-let" "2" "(if-let [x 1] (inc x) :none)"] + ["if-let else" ":none" "(if-let [x nil] (inc x) :none)"] + ["if-some zero" "1" "(if-some [x 0] (inc x) :none)"] + ["when-some nil" "nil" "(when-some [x nil] x)"]) + +# Regression: if-let/when-let/if-some/when-some bind the name ONLY in the +# then/body branch. The else branch (and a falsy when-let body, which there is +# none of) must see the surrounding scope, not the binding — so the else of +# (let [x 5] (if-let [x nil] ...)) sees x=5, like Clojure. (Previously the macros +# wrapped the whole `if` in the binding's let*, leaking it into the else.) +(defspec "control / conditional-binding scope" + ["if-let else sees outer" "5" "(let [x 5] (if-let [x nil] :then x))"] + ["if-let then binds" "7" "(let [x 5] (if-let [x 7] x :else))"] + ["if-some else sees outer" "5" "(let [x 5] (if-some [x nil] :then x))"] + ["if-some binds false" "false" "(if-some [x false] x :else)"] + ["when-let else via or" "5" "(let [x 5] (or (when-let [x nil] x) x))"] + ["when-let multi-form body" "14" "(when-let [x 7] (inc x) (* x 2))"] + ["if-let in fn param" "9" "((fn [xs] (if-let [xs nil] :then xs)) 9)"] + ["when-some binds zero" "1" "(when-some [x 0] (inc x))"] + ["if-let evals test once" "1" "(let [c (atom 0)] (if-let [v (do (swap! c inc) :v)] @c :none))"]) + +(defspec "control / iteration" + ["dotimes side-effect" "5" "(let [a (atom 0)] (dotimes [i 5] (swap! a inc)) @a)"] + ["while" "5" "(let [a (atom 0)] (while (< @a 5) (swap! a inc)) @a)"] + ["for" "[0 1 2]" "(for [x (range 3)] x)"] + ["for nested" "[[0 :a] [0 :b] [1 :a] [1 :b]]" "(for [x (range 2) y [:a :b]] [x y])"] + ["for :when" "[0 2 4]" "(for [x (range 6) :when (even? x)] x)"] + ["for :while" "[0 1 2]" "(for [x (range 10) :while (< x 3)] x)"] + ["for :let" "[0 1 4]" "(for [x (range 3) :let [sq (* x x)]] sq)"] + ["for :let+:when" "[4 6 8]" "(for [x (range 5) :let [y (* x 2)] :when (> y 3)] y)"] + ["for multi :when" "[[1 :a] [1 :b]]" "(for [x [0 1] :when (odd? x) y [:a :b]] [x y])"] + ["for destructure" "[3 7]" "(for [[a b] [[1 2] [3 4]]] (+ a b))"] + ["doseq side-effect" "6" "(let [a (atom 0)] (doseq [x [1 2 3]] (swap! a (fn [v] (+ v x)))) @a)"] + ["doseq nested" "4" "(let [c (atom 0)] (doseq [x [1 2] y [10 20]] (swap! c inc)) @c)"] + ["doseq :when" "[1 3]" "(let [a (atom [])] (doseq [x [1 2 3] :when (odd? x)] (swap! a conj x)) @a)"] + ["doseq :while" "6" "(let [a (atom 0)] (doseq [x (range 10) :while (< x 4)] (swap! a + x)) @a)"] + ["doseq :let" "[0 1 4]" "(let [a (atom [])] (doseq [x (range 3) :let [sq (* x x)]] (swap! a conj sq)) @a)"] + ["doseq returns nil" "nil" "(doseq [x [1 2 3]] x)"]) + +(defspec "control / threading" + ["->" "6" "(-> 1 inc (+ 4))"] + ["-> with forms" "[1 2 3]" "(-> [] (conj 1) (conj 2) (conj 3))"] + ["->>" "9" "(->> [1 2 3] (map inc) (reduce +))"] + ["as->" "2" "(as-> [0 1] x (map inc x) (reverse x) (first x))"] + ["some->" "2" "(some-> 1 inc)"] + ["some-> nil stops" "nil" "(some-> nil inc)"] + ["some->>" "[2 3]" "(some->> [1 2] (map inc))"] + ["cond->" "2" "(cond-> 1 true inc false inc)"] + ["cond->>" "[1 2]" "(cond->> [2] true (cons 1))"] + ["doto returns subject" "5" "(let [a (doto (atom 0) (reset! 5))] @a)"]) diff --git a/test/spec/core-async-spec.janet b/test/spec/core-async-spec.janet new file mode 100644 index 0000000..dfaec9f --- /dev/null +++ b/test/spec/core-async-spec.janet @@ -0,0 +1,98 @@ +# Specification: clojure.core.async on Janet fibers (Phase 1 — API layer). +# Each case is self-contained: it requires the ns, sets up channels/go blocks, +# and ends with a take that pumps the event loop and yields the value compared. +(use ../support/harness) + +(def REQ + "(require '[clojure.core.async :refer [go go-loop chan ! close! alts! timeout put! take! chan? buffer dropping-buffer sliding-buffer]]) ") +(defn- a [body] (string "(do " REQ body ")")) + +(defspec "core.async / go & channels" + ["go produce, ! c (+ 40 2))) ( channel closes" + "nil" (a "(! x 10)) (go (>! y 32)) (! c 1) (>! c 2) (>! c 3) (close! c)) (! c :a) (close! c)) (! to a closed channel is false" + "false" (a "(def c (chan 1)) (close! c) (>! c 1)")] + ["take from closed empty channel is nil" + "nil" (a "(def c (chan)) (close! c) (! in 1) (>! in 2) (>! in 3) (close! in)) (! mid (inc (! out (* 10 (! in 4)) (! y :v)) (! c 7)) (! c 1) (>! c 2) (>! c 3) (close! c))")] + ["filter transducer" + "[0 2 4]" (drain "(def c (chan 10 (filter even?))) (go (doseq [x (range 6)] (>! c x)) (close! c))")] + ["mapcat expands" + "[1 1 2 2]" (drain "(def c (chan 10 (mapcat (fn [x] [x x])))) (go (>! c 1) (>! c 2) (close! c))")] + ["take closes early" + "[:a :b]" (drain "(def c (chan 10 (take 2))) (go (>! c :a) (>! c :b) (>! c :c) (>! c :d) (close! c))")] + ["comp of transducers" + "[10 30 50]" (drain "(def c (chan 10 (comp (filter odd?) (map (fn [x] (* x 10)))))) (go (doseq [x (range 6)] (>! c x)) (close! c))")]) + +# Buffers: fixed (default), dropping (drops new when full), sliding (drops oldest +# when full). Filled synchronously on this fiber (dropping/sliding never park). +(defn- fill [bufexpr] + (string "(do " REQ "(def c (chan " bufexpr ")) (doseq [x [1 2 3 4 5]] (>! c x)) (close! c)" + " ( body" "1" + "(try 1 (catch :default e :caught))"] + ["finally runs on ok" "2" + "(let [a (atom 0)] (try 2 (finally (reset! a 9))) )"] + ["finally runs on throw" "9" + "(let [a (atom 0)] (try (throw (ex-info \"x\" {})) (catch :default e nil) (finally (reset! a 9))) @a)"] + ["catch value of body" "5" + "(try (+ 2 3) (catch :default e 0))"]) + +(defspec "exceptions / assert" + ["assert true -> ok" ":ok" "(do (assert true) :ok)"] + ["assert expr -> ok" ":ok" "(do (assert (= 1 1)) :ok)"] + ["assert false throws" :throws "(assert false)"] + ["assert nil throws" :throws "(assert nil)"]) + +(defspec "exceptions / ex-info" + ["ex-message" "\"oops\"" "(ex-message (ex-info \"oops\" {}))"] + ["ex-data" "{:k 1}" "(ex-data (ex-info \"oops\" {:k 1}))"] + ["ex-data via catch" "{:code 42}" + "(try (throw (ex-info \"e\" {:code 42})) (catch :default e (ex-data e)))"] + ["ex-cause" "true" + "(let [c (ex-info \"root\" {})] (= c (ex-cause (ex-info \"outer\" {} c))))"] + ["propagates to outer" "\"inner\"" + "(try (try (throw (ex-info \"inner\" {})) (finally nil)) (catch :default e (ex-message e)))"] + ["catch binds thrown value" "42" + "(try (throw 42) (catch :default e e))"] + ["rethrow preserves ex" "\"inner\"" + "(try (try (throw (ex-info \"inner\" {})) (catch :default e (throw e))) (catch :default e (ex-message e)))"] + ["ex-data on non-ex" "nil" "(ex-data 42)"] + ["ex-cause on non-ex" "nil" "(ex-cause {:k 1})"] + ["ex-message of string" "\"hi\"" "(ex-message \"hi\")"]) diff --git a/test/spec/forms-spec.janet b/test/spec/forms-spec.janet new file mode 100644 index 0000000..ca49330 --- /dev/null +++ b/test/spec/forms-spec.janet @@ -0,0 +1,80 @@ +# Specification: core special forms (case/fn/let/letfn/loop/if/do/def/call). +# +# Adapted from the jank test corpus (compiler+runtime/test/jank/form/**, /call) — +# we base our coverage on jank's to close gaps, but maintain our own copies since +# jank may diverge. jank-isms are translated to Jolt/Clojure: letfn* -> letfn, +# (catch jank.runtime.object_ref …) -> (catch :default …). Platform-specific cases +# (bigdecimal M, biginteger, ratios, unicode char edges) are intentionally omitted. +# +# Multi-form jank files (def + asserts, ending in :success) are wrapped in a single +# (do … :success) so they run as one expression and assert :success. +(use ../support/harness) + +(defspec "forms / case" + ["bool" ":yes" "(case true true :yes false :no :default)"] + ["keyword match" ":b" "(case :a :x :wrong :a :b :default)"] + ["number match" ":two" "(case 2 1 :one 2 :two :default)"] + ["string match" ":hit" "(case \"x\" \"y\" :miss \"x\" :hit :default)"] + ["nil match" ":nada" "(case nil nil :nada :default)"] + ["default" ":def" "(case 99 1 :one 2 :two :def)"] + ["list of consts" ":vowel" "(case \\a (\\a \\e \\i \\o \\u) :vowel :consonant)"] + ["no match no default" :throws "(case 5 1 :one)"] + ["duplicate keys" :throws "(case 1 1 :one 1 :dup :default)"] + ["duplicate in or-group" :throws "(case 2 (1 2) :a (2 3) :b :default)"]) + +(defspec "forms / fn" + ["named fn nil" "nil" "((fn* foo-bar []))"] + ["immediate call" "1" "((fn* [] 1))"] + ["args" "[:a :b]" "((fn* [a b] [a b]) :a :b)"] + ["multi-arity 0" "0" "(do (def add (fn* ([] 0) ([a] a) ([a b] (+ a b)))) (add))"] + ["multi-arity 1" "-500" "(do (def add (fn* ([] 0) ([a] a) ([a b] (+ a b)))) (add -500))"] + ["multi-arity 2" "-450" "(do (def add (fn* ([] 0) ([a] a) ([a b] (+ a b)))) (add -500 50))"] + ["variadic rest" "[3 4]" "(do (def v (fn* ([a b & args] args) ([] 0))) (v 1 2 3 4))"] + ["variadic empty" "0" "(do (def v (fn* ([a b & args] args) ([] 0))) (v))"] + ["variadic collect" "[{} nil :m]" "((fn* [a b & args] args) 'w 't {} nil :m)"] + ["closure capture" "8" "(do (def adder (fn* [n] (fn* [x] (+ x n)))) ((adder 5) 3))"] + ["recur countdown" "0" "(do (def cd (fn* [n] (if (< 0 n) (recur (+ n -1)) n))) (cd 10))"] + ["named self-recur" "120" "(do (def f (fn* fact [n] (if (= n 0) 1 (* n (fact (dec n)))))) (f 5))"] + ["no param vector" :throws "(fn* foo)"] + ["non-symbol param" :throws "(fn* [1] 1)"]) + +(defspec "forms / let" + ["literal" "1" "(let* [a 1] a)"] + ["multiple" "[1 2]" "(let* [a 1 b 2] [a b])"] + ["previous ref" ":bee" "(let* [a 1 b (if (= 1 a) :bee :uh-oh)] b)"] + ["nested let" "3" "(let* [a 5 b (let* [c -2] (+ a c))] b)"] + ["fn value bound" "\":foo\"" "(let* [kw->str (fn* [kw] (str kw))] (kw->str :foo))"] + ["shadowing" "2" "(let* [a 1 a 2] a)"]) + +(defspec "forms / letfn" + ["mutual top" "[1 2]" "(letfn [(a [] 1) (b [] 2)] [(a) (b)])"] + ["mutual recursion" ":done" "(letfn [(ev? [n] (if (= 0 n) :done (od? (dec n)))) (od? [n] (ev? n))] (ev? 4))"] + ["nested letfn" "3" "(letfn [(a [] 5) (b [] (letfn [(c [] -2)] (+ (a) (c))))] (b))"]) + +(defspec "forms / loop" + ["sum" "55" "(loop* [sum 0 cnt 10] (if (= cnt 0) sum (recur (+ cnt sum) (dec cnt))))"] + ["multi binding" "[4 2]" "(loop* [a 1 b 2 n 0] (if (< n 3) (recur (inc a) b (inc n)) [a b]))"] + ["init sees prior" "[1 2 3]" "(loop* [a 1 b (+ a 1) c (+ b 1)] [a b c])"]) + +(defspec "forms / try" + ["immediate throw caught" ":caught" "(try (throw :boom) (catch :default e :caught))"] + ["first throw wins" "\"a\"" "(try (throw (ex-info \"a\" {})) (throw (ex-info \"b\" {})) (catch :default e (ex-message e)))"] + ["catch ex-data" "7" "(try (throw (ex-info \"e\" {:v 7})) (catch :default e (:v (ex-data e))))"] + ["finally runs" "9" "(let [a (atom 0)] (try 1 (finally (reset! a 9))) @a)"] + ["body value w/ finally" "1" "(try 1 (finally 2))"] + ["catch value w/ finally" ":h" "(try (throw (ex-info \"x\" {})) (catch :default e :h) (finally :ignored))"] + ["no throw skips catch" "5" "(try 5 (catch :default e :nope))"]) + +(defspec "forms / if-do-def-call" + ["if truthy vec" ":fine" "(if [:ok] :fine :no)"] + ["if truthy str" ":fine" "(if \"good?\" :fine :no)"] + ["if nil = false" ":else" "(if nil :then :else)"] + ["if no else" "nil" "(if false 1)"] + ["do nested" "1" "(do (do (do (do 1))))"] + ["do returns last" "3" "(do 1 2 3)"] + ["def + deref var" "true" "(var? (def one 1))"] + ["def redefine" "100" "(do (def one 1) (def one 100) one)"] + ["def in fn mutates" "[:default :meow]" "(do (def a :default) (def set-a (fn* [v] (def a v))) (let* [before a] (set-a :meow) [before a]))"] + ["call literal fn" "1" "((fn* [] 1))"] + ["call nested" "6" "(+ ((fn* [] 1)) ((fn* [] 2)) ((fn* [] 3)))"] + ["call nil" :throws "(nil)"]) diff --git a/test/spec/functions-spec.janet b/test/spec/functions-spec.janet new file mode 100644 index 0000000..ef7c24e --- /dev/null +++ b/test/spec/functions-spec.janet @@ -0,0 +1,37 @@ +# Specification: functions & higher-order combinators. +(use ../support/harness) + +(defspec "functions / definition" + ["fn literal" "3" "((fn [a b] (+ a b)) 1 2)"] + ["fn shorthand" "3" "(#(+ %1 %2) 1 2)"] + ["fn shorthand %" "2" "(#(inc %) 1)"] + ["defn" "5" "(do (defn f [x] (+ x 2)) (f 3))"] + ["multi-arity" "[1 5]" "(do (defn f ([x] x) ([x y] (+ x y))) [(f 1) (f 2 3)])"] + ["variadic" "[1 2 3]" "(do (defn f [& xs] xs) (f 1 2 3))"] + ["variadic with fixed" "[1 [2 3]]" "(do (defn f [a & xs] [a xs]) (f 1 2 3))"] + ["closure captures" "8" "(do (defn adder [n] (fn [x] (+ x n))) ((adder 5) 3))"] + ["recursion" "120" "(do (defn fact [n] (if (< n 2) 1 (* n (fact (dec n))))) (fact 5))"] + ["named fn self-ref" "120" "((fn fact [n] (if (< n 2) 1 (* n (fact (dec n))))) 5)"]) + +(defspec "functions / application" + ["apply" "6" "(apply + [1 2 3])"] + ["apply with leading" "10" "(apply + 1 2 [3 4])"] + ["apply keyword" "1" "(apply :a [{:a 1}])"] + ["partial" "7" "((partial + 5) 2)"] + ["partial multi" "10" "((partial + 1 2) 3 4)"] + ["comp" "4" "((comp inc inc) 2)"] + ["comp order" "5" "((comp inc (fn [x] (* x 2))) 2)"] + ["comp identity" "3" "((comp) 3)"] + ["complement" "true" "((complement even?) 3)"] + ["constantly" "5" "((constantly 5) 1 2 3)"] + ["identity" "7" "(identity 7)"]) + +(defspec "functions / combinators" + ["juxt" "[1 3]" "((juxt first last) [1 2 3])"] + ["fnil" "1" "((fnil inc 0) nil)"] + ["fnil passes value" "6" "((fnil inc 0) 5)"] + ["every-pred true" "true" "((every-pred pos? even?) 4)"] + ["every-pred false" "false" "((every-pred pos? even?) 3)"] + ["some-fn" "true" "((some-fn even? neg?) 3 4)"] + ["memoize" "2" "(do (def c (atom 0)) (def f (memoize (fn [x] (swap! c inc) x))) (f 1) (f 1) (f 2) @c)"] + ["trampoline" "10" "(trampoline (fn f [n acc] (if (zero? n) acc (fn [] (f (dec n) (+ acc 2))))) 5 0)"]) diff --git a/test/spec/futures-spec.janet b/test/spec/futures-spec.janet new file mode 100644 index 0000000..c7be5aa --- /dev/null +++ b/test/spec/futures-spec.janet @@ -0,0 +1,45 @@ +# Specification: clojure.core futures on Janet OS threads (ev/thread). +# +# A `future` runs its body on a *real* OS thread (ev/thread), so it can use a +# second core for CPU-bound work — unlike the cooperatively-scheduled go blocks. +# Because Janet threads have separate heaps, the body and its captured state are +# MARSHALLED (copied) to the worker thread and the result is marshalled back: a +# future sees a snapshot of captured state and communicates only via its return +# value (mutations to captured atoms do NOT propagate back). `deref`/`@` blocks +# (parks) until the worker finishes; the result is cached for later derefs. +(use ../support/harness) + +(defspec "clojure.core / futures — deref" + ["future + deref" "3" "(deref (future (+ 1 2)))"] + ["@ reader macro derefs" "42" "@(future (* 6 7))"] + ["future returns collection" "[2 3 4]" "(deref (future (mapv inc [1 2 3])))"] + ["future returns a map" "{:a 1}" "(deref (future {:a 1}))"] + ["deref is cached/idempotent" "[2 2]" "(let [f (future (+ 1 1))] [(deref f) (deref f)])"] + ["timed deref of ready future" "42" "(let [f (future 42)] (deref f) (deref f 1000 :nope))"] + ["body error re-raised on deref" :throws "(deref (future (throw \"boom\")))"]) + +(defspec "clojure.core / futures — predicates" + ["future? true" "true" "(future? (future 1))"] + ["future? false" "false" "(future? 42)"] + ["future-done? after deref" "true" "(let [f (future 1)] (deref f) (future-done? f))"] + ["realized? after deref" "true" "(let [f (future 1)] (deref f) (realized? f))"] + # Cancel marks the future done (the worker can't be interrupted, but the + # future object reflects the cancellation: deref raises, predicates flip). + ["cancel an in-flight future returns true" "true" + "(let [f (future 1)] (future-cancel f))"] + ["future-cancelled? after cancel" "true" + "(let [f (future 1)] (future-cancel f) (future-cancelled? f))"] + ["future-done? after cancel" "true" + "(let [f (future 1)] (future-cancel f) (future-done? f))"] + ["cancel an already-completed future returns false" "false" + "(let [f (future 1)] (deref f) (future-cancel f))"] + ["future-cancelled? fresh is false" "false" + "(future-cancelled? (future 1))"]) + +(defspec "clojure.core / futures — snapshot (copy) semantics" + # The worker thread swaps its *copy* of the atom; the parent's atom is untouched. + ["captured atom is snapshotted, not shared" + "0" "(let [a (atom 0)] (deref (future (swap! a inc))) @a)"] + # The future's own return value still reflects the swap on its copy. + ["future sees its own mutation" + "1" "(let [a (atom 0)] (deref (future (swap! a inc))))"]) diff --git a/test/spec/host-interop-spec.janet b/test/spec/host-interop-spec.janet new file mode 100644 index 0000000..b9a297d --- /dev/null +++ b/test/spec/host-interop-spec.janet @@ -0,0 +1,40 @@ +# Specification: host (Janet) interop — the `.` forms and jolt.interop. +(use ../support/harness) + +(defspec "interop / dot forms" + ["method call" "\"v=41\"" + "(. {:value 41 :describe (fn [self] (str \"v=\" (:value self)))} describe)"] + ["method with args" "\"Hello Alice\"" + "(. {:greet (fn [self n] (str \"Hello \" n))} greet \"Alice\")"] + ["field access .-" "41" "(.-value {:value 41})"] + ["dot field keyword" "41" "(. {:value 41} :value)"]) + +# The `janet` namespace segment is the explicit Janet-stdlib bridge added for +# the networking layer (and used by jolt.nrepl). `janet/` resolves a Janet +# root binding; `janet./` resolves a module binding. The boundary +# is explicit so it's visible where host semantics take over. +(defspec "interop / janet bridge" + ["root builtin janet/" "\"123\"" "(janet/string 1 2 3)"] + ["root builtin janet/type" ":string" "(janet/type \"x\")"] + ["module fn janet./" "4" "(janet.math/sqrt 16)"] + ["janet.string module fn" "\"HI\"" "(janet.string/ascii-upper \"hi\")"] + ["janet.os/clock is a number" "true" "(number? (janet.os/clock))"] + # crossing the boundary uses Janet representations: a Jolt vector is a table + ["jolt vector crosses as a janet table" ":table" "(janet/type [1 2])"] + # interop is explicit-only: an unprefixed Janet module is not auto-exposed + ["unprefixed janet module not exposed" :throws "net/server"] + ["unknown janet symbol throws" :throws "(janet.os/definitely-not-a-real-fn)"]) + +(defspec "interop / jolt.interop" + ["janet-type quoted list" ":array" "(do (require (quote [jolt.interop :as j])) (j/janet-type (quote (1 2))))"] + ["janet-type list" ":array" "(do (require (quote [jolt.interop :as j])) (j/janet-type (list 1 2)))"] + ["janet-type string" ":string" "(do (require (quote [jolt.interop :as j])) (j/janet-type \"x\"))"] + ["janet-type number" ":number" "(do (require (quote [jolt.interop :as j])) (j/janet-type 1))"] + ["janet-type keyword" ":keyword" "(do (require (quote [jolt.interop :as j])) (j/janet-type :a))"]) + +(defspec "interop / arrays (aget/aset/alength)" + ["alength" "3" "(alength (object-array [1 2 3]))"] + ["aget" "20" "(aget (object-array [10 20 30]) 1)"] + ["aset returns val" "9" "(aset (object-array [1 2 3]) 1 9)"] + ["aset mutates" "[7 2 3]" "(let [a (object-array [1 2 3])] (aset a 0 7) (vec a))"] + ["aget 2d" "4" "(aget (to-array-2d [[1 2] [3 4]]) 1 1)"]) diff --git a/test/spec/io-spec.janet b/test/spec/io-spec.janet new file mode 100644 index 0000000..73d017f --- /dev/null +++ b/test/spec/io-spec.janet @@ -0,0 +1,26 @@ +# Specification: printing / output (print/println/pr/prn, *-str, format, str). +# Output is captured with with-out-str (jolt-rfw); the *-str fns return strings. +(use ../support/harness) + +(defspec "io / with-out-str captures" + ["println" "\"hi\\n\"" "(with-out-str (println \"hi\"))"] + ["print spaces" "\"a b\"" "(with-out-str (print \"a\" \"b\"))"] + ["prn quotes" "\"[1 2]\\n\"" "(with-out-str (prn [1 2]))"] + ["pr no newline" "\"5\"" "(with-out-str (pr 5))"] + ["multiple writes" "\"12\"" "(with-out-str (print 1) (print 2))"] + ["no output" "\"\"" "(with-out-str 42)"] + ["println no args" "\"\\n\"" "(with-out-str (println))"]) + +(defspec "io / *-str builders" + ["print-str" "\"a b\"" "(print-str \"a\" \"b\")"] + ["println-str" "\"x\\n\"" "(println-str \"x\")"] + ["prn-str" "\"[1 2]\\n\"" "(prn-str [1 2])"] + ["pr-str quotes" "\"\\\"s\\\"\"" "(pr-str \"s\")"] + ["pr-str keyword" "\":a\"" "(pr-str :a)"]) + +(defspec "io / str & format" + ["str concat" "\"1:ab\"" "(str 1 :a \"b\")"] + ["str nil" "\"\"" "(str nil)"] + ["str of coll" "\"[1 2]\"" "(str [1 2])"] + ["format d/s" "\"5-x\"" "(format \"%d-%s\" 5 \"x\")"] + ["format float" "\"3.14\"" "(format \"%.2f\" 3.14159)"]) diff --git a/test/spec/lazy-seqs-spec.janet b/test/spec/lazy-seqs-spec.janet new file mode 100644 index 0000000..cdb4491 --- /dev/null +++ b/test/spec/lazy-seqs-spec.janet @@ -0,0 +1,31 @@ +# Specification: lazy sequences. +(use ../support/harness) + +(defspec "lazy / construction & laziness" + ["lazy-seq value" "[1 2 3]" "(take 3 (lazy-seq (cons 1 (lazy-seq (cons 2 (lazy-seq (cons 3 nil)))))))"] + ["not eagerly evaluated" "0" "(let [c (atom 0)] (lazy-seq (swap! c inc) nil) @c)"] + ["realized on demand" "1" "(let [c (atom 0) s (lazy-seq (swap! c inc) [1])] (first s) @c)"] + ["lazy-cat" "[0 1 2 3]" "(lazy-cat [0 1] [2 3])"] + ["doall forces" "[2 3 4]" "(doall (map inc [1 2 3]))"] + ["dorun returns nil" "nil" "(dorun (map inc [1 2 3]))"]) + +(defspec "lazy / infinite" + ["take from repeat" "[7 7 7]" "(take 3 (repeat 7))"] + ["take from iterate" "[1 2 4 8]" "(take 4 (iterate (fn [x] (* 2 x)) 1))"] + ["take from cycle" "[1 2 1 2]" "(take 4 (cycle [1 2]))"] + ["take from range" "[0 1 2]" "(take 3 (range))"] + ["drop then take" "[5 6 7]" "(take 3 (drop 5 (range)))"] + ["filter infinite" "[0 2 4]" "(take 3 (filter even? (range)))"] + ["map infinite" "[0 1 4]" "(take 3 (map (fn [x] (* x x)) (range)))"] + ["nth of infinite" "100" "(nth (range) 100)"]) + +(defspec "lazy / self-referential" + ["self-ref ones" "[1 1 1 1 1]" "(do (def ones (lazy-seq (cons 1 ones))) (take 5 ones))"] + ["self-ref nats" "[0 1 2 3 4]" "(do (def nats (lazy-cat [0] (map inc nats))) (take 5 nats))"] + ["self-ref fib" "[0 1 1 2 3 5 8 13 21 34]" + "(do (def fib (lazy-cat [0 1] (map + (rest fib) fib))) (take 10 fib))"]) + +(defspec "lazy / realized?" + ["unrealized" "false" "(realized? (lazy-seq (cons 1 nil)))"] + ["realized after" "true" "(let [s (lazy-seq (cons 1 nil))] (first s) (realized? s))"] + ["body runs once" "1" "(let [c (atom 0) s (lazy-seq (do (swap! c inc) [1 2 3]))] (seq s) (seq s) @c)"]) diff --git a/test/spec/lists-spec.janet b/test/spec/lists-spec.janet new file mode 100644 index 0000000..7a35f70 --- /dev/null +++ b/test/spec/lists-spec.janet @@ -0,0 +1,28 @@ +# Specification: lists (persistent singly-linked). +(use ../support/harness) + +(defspec "list / construct & predicate" + ["list" "[1 2 3]" "(list 1 2 3)"] + ["empty list" "[]" "(list)"] + ["quoted list" "[1 2 3]" "(quote (1 2 3))"] + ["list? true" "true" "(list? (list 1 2))"] + ["list? on conj result" "true" "(list? (conj (list 1) 0))"] + ["count" "3" "(count (list 1 2 3))"] + ["empty? true" "true" "(empty? (list))"] + ["list = vector elts" "true" "(= (list 1 2 3) [1 2 3])"]) + +(defspec "list / access & update" + ["first" "1" "(first (list 1 2 3))"] + ["rest" "[2 3]" "(rest (list 1 2 3))"] + ["peek is first" "1" "(peek (list 1 2 3))"] + ["pop drops first" "[2 3]" "(pop (list 1 2 3))"] + ["conj prepends" "[0 1 2]" "(conj (list 1 2) 0)"] + ["conj many prepends" "[4 3 1 2]" "(conj (list 1 2) 3 4)"] + ["cons prepends" "[0 1 2]" "(cons 0 (list 1 2))"] + ["nth" "20" "(nth (list 10 20 30) 1)"]) + +(defspec "list / immutability & performance" + ["conj does not mutate" "true" "(let [l (list 1 2 3) m (conj l 0)] (and (= l [1 2 3]) (= m [0 1 2 3])))"] + ["reduce conj builds" "[2 1 0]" "(reduce conj (list) (range 3))"] + ["O(1) conj at scale" "200000" "(count (reduce conj (list) (range 200000)))"] + ["scale head correct" "199999" "(first (reduce conj (list) (range 200000)))"]) diff --git a/test/spec/macros-spec.janet b/test/spec/macros-spec.janet new file mode 100644 index 0000000..e21f5c0 --- /dev/null +++ b/test/spec/macros-spec.janet @@ -0,0 +1,74 @@ +# Specification: macros, quoting and syntax-quote. +(use ../support/harness) + +(defspec "macros / quoting" + ["quote symbol" "(quote a)" "(quote a)"] + ["quote list" "[1 2 3]" "(quote (1 2 3))"] + ["quote nested" "[1 [2 3]]" "(quote (1 (2 3)))"] + ["quote sugar" "'a" "'a"] + ["syntax-quote literal" "[1 2]" "`[1 2]"] + ["unquote" "[1 2 3]" "(let [x 2] `[1 ~x 3])"] + ["unquote-splicing" "[1 2 3 4]" "(let [xs [2 3]] `[1 ~@xs 4])"] + ["unquote in list" "[3]" "(let [x 3] `(~x))"] + ["syntax-quote symbol qualifies" "true" "(symbol? `foo)"]) + +(defspec "macros / defmacro" + ["simple macro" "3" + "(do (defmacro m [a b] `(+ ~a ~b)) (m 1 2))"] + ["macro unless" "1" + "(do (defmacro unless [c body] `(if ~c nil ~body)) (unless false 1))"] + ["macro with body splice" "6" + "(do (defmacro msum [& xs] `(+ ~@xs)) (msum 1 2 3))"] + ["macroexpand-1" "true" + "(do (defmacro m [x] `(inc ~x)) (list? (macroexpand-1 '(m 5))))"] + ["gensym unique" "false" + "(= (gensym) (gensym))"] + ["gensym# in template" "true" + "(do (defmacro m [] `(let [x# 1] x#)) (= 1 (m)))"]) + +# Core macros ported from Janet to the Clojure overlay (jolt-1j0 phase 3, +# jolt-core/clojure/core/30-macros.clj). +(defspec "macros / core-overlay" + ["if-not true branch" ":then" "(if-not false :then :else)"] + ["if-not else branch" ":else" "(if-not true :then :else)"] + ["if-not no else" "nil" "(if-not true :then)"] + ["if-not no else hit" ":then" "(if-not false :then)"] + ["comment -> nil" "nil" "(comment a b c)"] + ["comment in do" "42" "(do (comment ignored) 42)"] + ["if-let then" "6" "(if-let [x 5] (inc x) :none)"] + ["if-let else" ":none" "(if-let [x nil] (inc x) :none)"] + ["if-let else scope" "9" "(let [x 9] (if-let [x nil] :t x))"] + ["if-some zero" "1" "(if-some [x 0] (inc x) :none)"] + ["if-some nil" ":none" "(if-some [x nil] x :none)"] + ["when-some multi" "14" "(when-some [x 7] (inc x) (* x 2))"] + ["when-some nil" "nil" "(when-some [x nil] x)"] + ["while loop" "3" "(let [a (atom 0)] (while (< @a 3) (swap! a inc)) @a)"] + ["dotimes sum" "10" "(let [a (atom 0)] (dotimes [i 5] (swap! a + i)) @a)"] + ["as-> threads" "12" "(as-> 5 x (+ x 1) (* x 2))"] + ["as-> no forms" "5" "(as-> 5 x)"] + ["some-> through" "6" "(some-> {:a {:b 5}} :a :b inc)"] + ["some-> short-circuit" "nil" "(some-> {:a nil} :a :b)"] + ["some->> through" "9" "(some->> [1 2 3] (map inc) (reduce +))"] + ["some->> nil" "nil" "(some->> nil (map inc))"] + ["doto returns obj" "[1 2]" "(deref (doto (atom []) (swap! conj 1) (swap! conj 2)))"] + ["when-first" "20" "(when-first [x [10 20 30]] (* x 2))"] + ["when-first empty" "nil" "(when-first [x []] :body)"] + ["when-first nil coll" "nil" "(when-first [x nil] :body)"] + ["when-first range" "0" "(when-first [x (range 5)] x)"] + ["cond->> threads" "12" "(cond->> 5 true (+ 1) false (* 100) true (* 2))"] + ["cond->> skip" "10" "(cond->> 10 false (+ 1))"] + ["assert pass" ":ok" "(do (assert (= 1 1)) :ok)"] + ["assert throws" ":threw" "(try (assert (= 1 2)) (catch :default e :threw))"] + ["assert message" "\"nope\"" "(try (assert false \"nope\") (catch :default e (ex-message e)))"] + ["delay value" "42" "(deref (delay 42))"] + ["delay forces once" "1" "(let [c (atom 0) d (delay (swap! c inc))] @d @d @c)"] + ["future deref" "9" "(deref (future (* 3 3)))"] + ["letfn simple" "25" "(letfn [(sq [x] (* x x))] (sq 5))"] + ["letfn mutual" "true" "(letfn [(ev? [n] (if (zero? n) true (od? (dec n)))) (od? [n] (if (zero? n) false (ev? (dec n))))] (ev? 8))"] + ["condp match" ":two" "(condp = 2 1 :one 2 :two 3 :three)"] + ["condp default" ":else" "(condp = 9 1 :one 2 :two :else)"] + ["condp :>> form" "\"got 2\"" "(condp some [1 2 3] #{0 9} :>> (fn [x] (str \"got \" x)) #{2 6} :>> (fn [x] (str \"got \" x)))"] + ["condp no match" ":threw" "(try (condp = 9 1 :one) (catch :default e :threw))"] + ["binding rebinds" "99" "(do (def ^:dynamic *bx* 10) (binding [*bx* 99] *bx*))"] + ["binding restores" "10" "(do (def ^:dynamic *by* 10) (binding [*by* 99] *by*) *by*)"] + ["binding seen by fn" "7" "(do (def ^:dynamic *bz* 0) (defn rdz [] *bz*) (binding [*bz* 7] (rdz)))"]) diff --git a/test/spec/maps-spec.janet b/test/spec/maps-spec.janet new file mode 100644 index 0000000..afc9fd7 --- /dev/null +++ b/test/spec/maps-spec.janet @@ -0,0 +1,146 @@ +# Specification: maps (associative). +(use ../support/harness) + +(defspec "map / construct & predicate" + ["literal" "{:a 1}" "{:a 1}"] + ["hash-map" "{:a 1, :b 2}" "(hash-map :a 1 :b 2)"] + ["empty" "{}" "{}"] + ["map? true" "true" "(map? {:a 1})"] + ["map? false on vector" "false" "(map? [1 2])"] + ["count" "2" "(count {:a 1 :b 2})"] + ["empty? true" "true" "(empty? {})"] + ["equality order-indep" "true" "(= {:a 1 :b 2} {:b 2 :a 1})"]) + +(defspec "map / access" + ["get" "1" "(get {:a 1} :a)"] + ["get missing nil" "nil" "(get {:a 1} :z)"] + ["get default" ":x" "(get {:a 1} :z :x)"] + ["keyword as fn" "1" "(:a {:a 1})"] + ["keyword fn default" ":x" "(:z {:a 1} :x)"] + ["map as fn" "1" "({:a 1} :a)"] + ["get-in" "2" "(get-in {:a {:b 2}} [:a :b])"] + ["get-in missing" "nil" "(get-in {:a {}} [:a :b])"] + ["contains? key" "true" "(contains? {:a 1} :a)"] + ["contains? missing" "false" "(contains? {:a 1} :z)"] + ["find returns entry" "[:a 1]" "(find {:a 1} :a)"] + ["keys" "true" "(= #{:a :b} (set (keys {:a 1 :b 2})))"] + ["vals" "true" "(= #{1 2} (set (vals {:a 1 :b 2})))"]) + +(defspec "map / update" + ["assoc adds" "{:a 1, :b 2}" "(assoc {:a 1} :b 2)"] + ["assoc overwrites" "{:a 9}" "(assoc {:a 1} :a 9)"] + ["assoc many" "{:a 1, :b 2}" "(assoc {} :a 1 :b 2)"] + ["dissoc" "{:a 1}" "(dissoc {:a 1 :b 2} :b)"] + ["dissoc many" "{:a 1}" "(dissoc {:a 1 :b 2 :c 3} :b :c)"] + ["merge" "{:a 1, :b 2}" "(merge {:a 1} {:b 2})"] + ["merge overwrites" "{:a 2}" "(merge {:a 1} {:a 2})"] + ["merge lattermost wins" "{:a 3}" "(merge {:a 1} {:a 2} {:a 3})"] + ["merge no args -> nil" "nil" "(merge)"] + ["merge all nil -> nil" "nil" "(merge nil nil)"] + ["merge nil arg no-op" "{:a 1}" "(merge {:a 1} nil)"] + ["merge nil then map" "{:a 1}" "(merge nil {:a 1})"] + ["merge empty + nil" "{}" "(merge {} nil)"] + ["merge map-entry (conj)" "{:a 1}" "(merge {} (first {:a 1}))"] + ["merge [k v] vector" "{:foo 1}" "(merge {} [:foo 1])"] + ["merge collection key" "true" "(= {[2 3] :foo} (merge {[2 3] :foo} nil {}))"] + ["merge-with" "{:a 3}" "(merge-with + {:a 1} {:a 2})"] + ["update" "{:a 2}" "(update {:a 1} :a inc)"] + ["update missing w/ fnil" "{:a 1}" "(update {} :a (fnil inc 0))"] + ["update-in" "{:a {:b 2}}" "(update-in {:a {:b 1}} [:a :b] inc)"] + ["assoc-in" "{:a {:b 1}}" "(assoc-in {} [:a :b] 1)"] + ["select-keys" "{:a 1}" "(select-keys {:a 1 :b 2} [:a])"] + ["into onto map" "{:a 1, :b 2}" "(into {:a 1} [[:b 2]])"] + ["zipmap" "{:a 1, :b 2}" "(zipmap [:a :b] [1 2])"]) + +(defspec "map / iteration & entries" + ["map over entries" "true" "(= #{1 2} (set (map val {:a 1 :b 2})))"] + ["map keys" "true" "(= #{:a :b} (set (map key {:a 1 :b 2})))"] + ["reduce over entries" "6" "(reduce (fn [a e] (+ a (val e))) 0 {:a 1 :b 2 :c 3})"] + ["reduce-kv" "6" "(reduce-kv (fn [a k v] (+ a v)) 0 {:a 1 :b 2 :c 3})"] + ["destructure entry" "true" "(= [[:a 2]] (into [] (map (fn [[k v]] [k (inc v)]) {:a 1})))"] + ["first of map is entry" "true" "(let [e (first {:a 1})] (and (= (key e) :a) (= (val e) 1)))"] + ["map-entry?" "true" "(map-entry? (first {:a 1}))"] + ["count of nil map" "0" "(count nil)"] + ["get from nil" "nil" "(get nil :a)"] + ["immutability" "true" "(let [m {:a 1} n (assoc m :b 2)] (and (= m {:a 1}) (= n {:a 1 :b 2})))"]) + +(defspec "map / collection keys (by value)" + ["vector key literal" ":v" "(get {[1 2] :v} [1 2])"] + ["map key literal" ":v" "(get {(hash-map :a 1) :v} {:a 1})"] + ["assoc vector key" ":v" "(get (assoc {} [1 2] :v) [1 2])"] + ["key across repr" ":v" "(get (assoc {} (vec [1 2]) :v) [1 2])"] + ["frequencies of maps" "2" "(get (frequencies [{:a 1} (hash-map :a 1)]) {:a 1})"] + ["group-by collection key" "1" "(count (group-by identity [{:a 1} (hash-map :a 1)]))"]) + +# Strictness: assoc bounds-checks vector indices; dissoc requires a map; +# count rejects scalars; numerator/denominator have no ratio type. +(defspec "map / strictness (throws like Clojure)" + ["assoc vec out of bounds" :throws "(assoc [0 1 2] 4 4)"] + ["assoc vec negative" :throws "(assoc [] -1 0)"] + ["assoc vec at count ok" "[1 2 3]" "(assoc [1 2] 2 3)"] + ["dissoc on number" :throws "(dissoc 42 :a)"] + ["dissoc on vector" :throws "(dissoc [1 2] 0)"] + ["dissoc on set" :throws "(dissoc #{:a} :a)"] + ["dissoc nil ok" "nil" "(dissoc nil :a)"] + ["count on number" :throws "(count 1)"] + ["count on keyword" :throws "(count :a)"] + ["count string ok" "3" "(count \"abc\")"] + ["numerator throws" :throws "(numerator 1)"] + ["denominator throws" :throws "(denominator 2)"] + ["subvec out of range" :throws "(subvec [0 1 2 3] 1 5)"] + ["subvec start>end" :throws "(subvec [0 1 2 3] 3 2)"] + ["subvec ok" "[1 2]" "(subvec [0 1 2 3] 1 3)"] + ["min-key empty" :throws "(apply min-key identity [])"] + ["merge empty vector" :throws "(merge {} [])"] + ["merge 1-elem vector" :throws "(merge {} [:foo])"] + ["merge atomic arg" :throws "(merge {} :foo)"] + ["merge [k v] ok" "{:foo 1}" "(merge {} [:foo 1])"] + ["merge maps ok" "{:a 1, :b 2}" "(merge {:a 1} {:b 2})"]) + +# Map entries are distinct from plain vectors (key/val/map-entry? reject a +# vector); min-key/max-key follow Clojure's NaN-aware ordering; subvec coerces +# float/NaN indices like (int ...). +(defspec "map / map-entry & key ordering" + ["key of entry" ":a" "(key (first {:a 1}))"] + ["val of entry" "1" "(val (first {:a 1}))"] + ["key rejects vector" :throws "(key [:a 1])"] + ["val rejects vector" :throws "(val [:a 1])"] + ["map-entry? entry" "true" "(map-entry? (first {:a 1}))"] + ["map-entry? vector" "false" "(map-entry? [:a 1])"] + ["min-key NaN first" "1" "(min-key identity ##NaN 1)"] + ["min-key NaN last" "true" "(NaN? (min-key identity 1 ##NaN))"] + ["min-key NaN three" "true" "(infinite? (min-key identity ##NaN ##-Inf 1))"] + ["min-key keys nonnum" :throws "(min-key identity \"x\" \"y\")"] + ["max-key picks max" "[1 2 3]" "(max-key count [1] [1 2 3] [1 2])"] + ["subvec float trunc" "[0]" "(subvec [0 1 2] 0.5 1.33)"] + ["subvec NaN start" "[0 1 2]" "(subvec [0 1 2] ##NaN 3)"] + ["subvec NaN end" "[]" "(subvec [0 1 2] 0 ##NaN)"]) + +# A nil value is a PRESENT key in Clojure (distinct from a missing key); Janet +# structs drop nil, so jolt builds these maps as a phm. Tested via literals (the +# reader path) and the construction/op surface, in every spec mode. +(defspec "map / nil values preserved" + ["literal contains" "true" "(contains? {:b nil} :b)"] + ["literal not= empty" "false" "(= {:b nil} {})"] + ["literal get nil" "nil" "(get {:b nil} :b :x)"] + ["literal keys incl nil" "true" "(= #{:a :b} (set (keys {:a nil :b 1})))"] + ["literal count" "2" "(count {:a nil :b 1})"] + ["literal vals incl nil" "2" "(count (vals {:a nil :b 1}))"] + ["eval values w/ nil" "3" "(:a {:a (+ 1 2) :b nil})"] + ["nil key present" "true" "(contains? {nil :v} nil)"] + ["assoc nil present" "true" "(contains? (assoc {:a 1} :b nil) :b)"] + ["assoc nil get" "nil" "(get (assoc {:a 1} :b nil) :b :x)"] + ["assoc overwrite nil" "nil" "(get (assoc {:a 1} :a nil) :a :x)"] + ["hash-map nil" "true" "(contains? (hash-map :b nil) :b)"] + ["merge new nil" "true" "(contains? (merge {:a 1} {:b nil}) :b)"] + ["merge overwrite nil" "nil" "(get (merge {:a 1} {:a nil}) :a :x)"] + ["merge-with present nil" "true" "(= [nil 1] (get (merge-with (fn [a b] [a b]) {:a nil} {:a 1}) :a))"] + ["into nil val" "true" "(contains? (into {} [[:a nil]]) :a)"] + ["conj map nil" "true" "(contains? (conj {:x 1} {:a nil}) :a)"] + ["zipmap nil" "true" "(contains? (zipmap [:a] [nil]) :a)"] + ["select-keys nil" "true" "(contains? (select-keys {:a nil} [:a]) :a)"] + ["get-in present nil" "nil" "(get-in {:a nil} [:a] :x)"] + ["get-in through nil" ":x" "(get-in {:a nil} [:a :b] :x)"] + ["dissoc keeps nil" "true" "(contains? (dissoc {:a nil :b 1} :b) :a)"] + ["reduce-kv sees nil" "true" "(= #{:a :b} (reduce-kv (fn [acc k v] (conj acc k)) #{} {:a nil :b 2}))"] + ["nil-free stays fast" "true" "(= {:a 1 :b 2} {:b 2 :a 1})"]) diff --git a/test/spec/metadata-spec.janet b/test/spec/metadata-spec.janet new file mode 100644 index 0000000..aa1b4b5 --- /dev/null +++ b/test/spec/metadata-spec.janet @@ -0,0 +1,31 @@ +# Specification: metadata. +(use ../support/harness) + +(defspec "metadata / with-meta & meta" + ["meta of bare value" "nil" "(meta [1 2 3])"] + ["with-meta then meta" "{:a 1}" "(meta (with-meta [1 2 3] {:a 1}))"] + ["with-meta preserves value" "true" "(= [1 2 3] (with-meta [1 2 3] {:a 1}))"] + ["with-meta on map" "{:doc \"x\"}" "(meta (with-meta {:k 1} {:doc \"x\"}))"] + ["vary-meta" "{:a 2}" "(meta (vary-meta (with-meta [1] {:a 1}) update :a inc))"] + ["vary-meta extra args" "{:a 1 :b 2}" "(meta (vary-meta (with-meta [1] {:a 1}) assoc :b 2))"] + ["meta reader ^" "{:tag :int}" "(meta ^{:tag :int} [1 2])"] + ["with-meta on fn ok" "true" "(fn? (with-meta inc {:a 1}))"] + ["with-meta nil clears" "nil" "(meta (with-meta [1 2 3] nil))"]) + +(defspec "metadata / type hints" + # ^Type / ^:kw / ^"str" on a symbol attach as metadata and are otherwise inert: + # the symbol stays a symbol so hints are transparent in every position. + ["type hint on param" "\"hi\"" "(do (defn f [^String s] s) (f \"hi\"))"] + ["type hint, extra params" "[1 2]" "(do (defn g [^String x y] [x y]) (g 1 2))"] + ["type hint in let" "6" "(let [^long x 5] (inc x))"] + ["type hint in body" "2" "(let [s \"ab\"] (count ^String s))"] + ["type hint in destructure" "3" "(let [{:keys [^long a]} {:a 3}] a)"] + ["symbol hint -> :tag" "\"String\"" "(:tag (meta (read-string \"^String x\")))"] + ["keyword hint -> true" "true" "(:foo (meta (read-string \"^:foo x\")))"]) + +(defspec "metadata / def metadata" + ["^:dynamic var binds" "9" "(do (def ^:dynamic *d* 1) (binding [*d* 9] *d*))"] + ["^:private on var" "true" "(do (def ^:private pv 1) (:private (meta (var pv))))"] + ["^Type tag on var" "\"String\"" "(do (def ^String tv \"a\") (:tag (meta (var tv))))"] + ["^{:doc} on var" "\"hi\"" "(do (def ^{:doc \"hi\"} dv 1) (:doc (meta (var dv))))"] + ["(def name doc val) doc" "\"d\"" "(do (def dd \"d\" 5) (:doc (meta (var dd))))"]) diff --git a/test/spec/multimethods-spec.janet b/test/spec/multimethods-spec.janet new file mode 100644 index 0000000..845141f --- /dev/null +++ b/test/spec/multimethods-spec.janet @@ -0,0 +1,32 @@ +# Specification: multimethods & hierarchies. +(use ../support/harness) + +(defspec "multimethods / dispatch" + ["dispatch on value" "\"two\"" + "(do (defmulti f identity) (defmethod f 1 [_] \"one\") (defmethod f 2 [_] \"two\") (f 2))"] + ["dispatch on keyword fn" "\"circle\"" + "(do (defmulti area :shape) (defmethod area :circle [_] \"circle\") (area {:shape :circle}))"] + [":default method" "\"other\"" + "(do (defmulti f identity) (defmethod f 1 [_] \"one\") (defmethod f :default [_] \"other\") (f 99))"] + ["no match throws" :throws + "(do (defmulti f identity) (defmethod f 1 [_] \"one\") (f 99))"] + ["multiple args" "5" + "(do (defmulti g (fn [a b] a)) (defmethod g :add [_ b] b) (g :add 5))"] + ["get-method" "\"one\"" + "(do (defmulti f identity) (defmethod f 1 [_] \"one\") ((get-method f 1) 1))"] + ["remove-method" :throws + "(do (defmulti f identity) (defmethod f 1 [_] \"one\") (remove-method f 1) (f 1))"]) + +(defspec "multimethods / hierarchies" + ["derive + isa?" "true" "(do (derive ::child ::parent) (isa? ::child ::parent))"] + ["isa? reflexive" "true" "(isa? ::x ::x)"] + ["isa? unrelated" "false" "(do (derive ::a ::b) (isa? ::a ::c))"] + ["parents" "true" "(do (derive ::c ::p) (contains? (parents ::c) ::p))"] + ["ancestors" "true" "(do (derive ::c ::p) (derive ::p ::g) (contains? (ancestors ::c) ::g))"] + ["descendants" "true" "(do (derive ::c ::p) (contains? (descendants ::p) ::c))"] + ["dispatch via hierarchy" "\"animal\"" + "(do (derive ::dog ::animal) (defmulti speak identity) (defmethod speak ::animal [_] \"animal\") (speak ::dog))"] + ["custom :default key" ":unknown" + "(do (defmulti classify :type :default :other) (defmethod classify :a [_] :alpha) (defmethod classify :other [_] :unknown) (classify {:type :zzz}))"] + ["explicit :hierarchy" "\"a\"" + "(do (def h (derive (make-hierarchy) ::dog ::animal)) (defmulti snd identity :hierarchy h) (defmethod snd ::animal [_] \"a\") (snd ::dog))"]) diff --git a/test/spec/namespaces-spec.janet b/test/spec/namespaces-spec.janet new file mode 100644 index 0000000..f69ebc9 --- /dev/null +++ b/test/spec/namespaces-spec.janet @@ -0,0 +1,37 @@ +# Specification: namespaces, vars and require. +(use ../support/harness) + +(defspec "namespaces / def & vars" + ["def + deref" "5" "(do (def x 5) x)"] + ["def returns var" "true" "(var? (def y 1))"] + ["declare then def" "2" "(do (declare z) (def z 2) z)"] + ["var special form" "true" "(var? (var +))"] + ["var sugar #'" "true" "(var? #'+)"] + ["var-get" "5" "(do (def w 5) (var-get #'w))"] + ["defn defines fn" "3" "(do (defn f [x] (inc x)) (f 2))"] + ["def with docstring" "7" "(do (def d \"a doc\" 7) d)"] + ["dynamic var binding" "2" "(do (def ^:dynamic *x* 1) (binding [*x* 2] *x*))"] + ["binding restores" "1" "(do (def ^:dynamic *y* 1) (binding [*y* 9] nil) *y*)"] + ["var-set in binding" "5" "(do (def ^:dynamic *z* 1) (binding [*z* 0] (var-set (var *z*) 5) *z*))"]) + +(defspec "namespaces / ns operations" + ["in-ns switches" "true" "(do (in-ns 'my.ns) (symbol? 'x))"] + # ns is a macro over in-ns/require/use/import (Stage 2 jolt-eaa): the form sets + # the current ns and processes its clauses. + ["ns form + alias" "\"HI\"" "(do (ns my.app (:require [clojure.string :as s])) (s/upper-case \"hi\"))"] + ["ns :use refers all" "9" "(do (ns src.lib) (def helper 9) (ns dst.app (:use [src.lib])) helper)"] + ["standalone use" "7" "(do (ns src.l2) (def k 7) (in-ns 'dst.a2) (use '[src.l2]) k)"] + ["ns-name" "true" "(do (require (quote [clojure.string])) (= 'clojure.string (ns-name (find-ns 'clojure.string))))"] + ["find-ns existing" "true" "(some? (find-ns 'clojure.core))"] + ["find-ns missing" "nil" "(find-ns 'does.not.exist)"] + ["resolve var" "true" "(var? (resolve '+))"] + ["resolve missing" "nil" "(resolve 'totally-undefined-xyz)"]) + +(defspec "namespaces / require & refer" + ["require :as" "\"AB\"" "(do (require '[clojure.string :as s]) (s/upper-case \"ab\"))"] + ["require :refer" "true" "(do (require '[clojure.string :refer [blank?]]) (blank? \"\"))"] + ["require :as + :refer" "true" "(do (require '[clojure.string :as s :refer [blank?]]) (and (blank? \"\") (= \"X\" (s/upper-case \"x\"))))"] + ["require clojure.set" "#{1 2 3}" "(do (require '[clojure.set :as set]) (set/union #{1 2} #{3}))"] + ["require clojure.walk" "{:a 2}" "(do (require '[clojure.walk :as w]) (w/postwalk (fn [x] (if (number? x) (inc x) x)) {:a 1}))"] + ["walk keywordize-keys" "{:a 1}" "(do (require '[clojure.walk :as w]) (w/keywordize-keys {\"a\" 1}))"] + ["walk stringify-keys" "true" "(do (require '[clojure.walk :as w]) (= {\"a\" 1} (w/stringify-keys {:a 1})))"]) diff --git a/test/spec/nrepl-spec.janet b/test/spec/nrepl-spec.janet new file mode 100644 index 0000000..2d635c0 --- /dev/null +++ b/test/spec/nrepl-spec.janet @@ -0,0 +1,27 @@ +# Specification: jolt.nrepl bencode codec (pure, no networking). +# The server/client wire behavior is covered by test/integration/nrepl-test.janet. +(use ../support/harness) + +(defn- b [body] + (string "(do (require '[jolt.nrepl :as nr]) " body ")")) +(defn- rt [body] + # round-trip a value through encode -> decode + (b (string "(nr/decode (nr/reader nil (nr/encode " body ")))"))) + +(defspec "jolt.nrepl / bencode round-trip" + ["integer" "42" (rt "42")] + ["negative" "-7" (rt "-7")] + ["string" "\"hello\"" (rt "\"hello\"")] + ["empty string" "\"\"" (rt "\"\"")] + ["list" "[\"a\" 1 \"b\"]" (rt "[\"a\" 1 \"b\"]")] + ["nested list" "[1 [2 3]]" (rt "[1 [2 3]]")] + ["dict" "{\"op\" \"eval\" \"id\" \"7\"}" (rt "{\"op\" \"eval\" \"id\" \"7\"}")] + ["dict with list" "{\"status\" [\"done\"]}" (rt "{\"status\" [\"done\"]}")] + ["nested dict" "{\"a\" {\"b\" 1}}" (rt "{\"a\" {\"b\" 1}}")]) + +(defspec "jolt.nrepl / bencode encode shape" + ["int" "\"i42e\"" (b "(nr/encode 42)")] + ["string" "\"5:hello\"" (b "(nr/encode \"hello\")")] + ["list" "\"li1ei2ee\"" (b "(nr/encode [1 2])")] + # dict keys are sorted lexicographically + ["dict sorted keys" "\"d1:ai1e1:bi2ee\"" (b "(nr/encode {\"b\" 2 \"a\" 1})")]) diff --git a/test/spec/numbers-spec.janet b/test/spec/numbers-spec.janet new file mode 100644 index 0000000..9ed49a7 --- /dev/null +++ b/test/spec/numbers-spec.janet @@ -0,0 +1,136 @@ +# Specification: numbers & arithmetic. +(use ../support/harness) + +(defspec "numbers / arithmetic" + ["add" "6" "(+ 1 2 3)"] + ["add zero args" "0" "(+)"] + ["subtract" "5" "(- 10 3 2)"] + ["negate" "-5" "(- 5)"] + ["multiply" "24" "(* 2 3 4)"] + ["multiply zero args" "1" "(*)"] + ["divide" "2" "(/ 10 5)"] + ["divide to fraction" "0.5" "(/ 1 2)"] + ["inc" "6" "(inc 5)"] + ["dec" "4" "(dec 5)"] + ["quot" "3" "(quot 10 3)"] + ["rem" "1" "(rem 10 3)"] + ["mod" "2" "(mod -1 3)"] + ["rem negative" "-1" "(rem -1 3)"] + ["max" "9" "(max 3 9 1)"] + ["min" "1" "(min 3 9 1)"] + ["abs" "5" "(abs -5)"] + ["promoting + alias" "3" "(+' 1 2)"] + ["inc' alias" "6" "(inc' 5)"]) + +(defspec "numbers / comparison" + ["less than" "true" "(< 1 2 3)"] + ["less than false" "false" "(< 1 3 2)"] + ["greater than" "true" "(> 3 2 1)"] + ["<=" "true" "(<= 1 1 2)"] + [">=" "true" "(>= 3 3 2)"] + ["= numbers" "true" "(= 2 2)"] + ["= different" "false" "(= 2 3)"] + ["== numeric" "true" "(== 2 2)"] + ["not=" "true" "(not= 1 2)"] + ["compare less" "-1" "(compare 1 2)"] + ["compare equal" "0" "(compare 1 1)"] + ["compare greater" "1" "(compare 2 1)"]) + +(defspec "numbers / predicates" + ["zero?" "true" "(zero? 0)"] + ["pos?" "true" "(pos? 5)"] + ["neg?" "true" "(neg? -5)"] + ["even?" "true" "(even? 4)"] + ["odd?" "true" "(odd? 3)"] + ["number?" "true" "(number? 5)"] + ["number? false" "false" "(number? :a)"] + ["int?" "true" "(int? 5)"] + ["pos-int?" "true" "(pos-int? 5)"] + ["neg-int?" "true" "(neg-int? -5)"] + ["nat-int? zero" "true" "(nat-int? 0)"] + ["nat-int? neg" "false" "(nat-int? -1)"] + ["ratio? false" "false" "(ratio? 5)"]) + +# Symbolic float values and float/double predicates. NOTE: Janet represents +# integers and integer-valued doubles identically, so (float? 1.0) is false +# (1.0 is indistinguishable from 1) — a documented divergence. Fractional and +# non-finite values ARE recognized as floats. +(defspec "numbers / floats & symbolic values" + ["read ##Inf" "true" "(= ##Inf (/ 1.0 0.0))"] + ["read ##-Inf" "true" "(< ##-Inf 0)"] + ["##NaN not= itself" "true" "(not (== ##NaN ##NaN))"] + ["float? fractional" "true" "(float? 1.5)"] + ["double? fractional" "true" "(double? 0.25)"] + ["float? integer" "false" "(float? 3)"] + ["float? ##Inf" "true" "(float? ##Inf)"] + ["double? ##NaN" "true" "(double? ##NaN)"] + ["infinite? ##Inf" "true" "(infinite? ##Inf)"] + ["infinite? ##-Inf" "true" "(infinite? ##-Inf)"] + ["infinite? finite" "false" "(infinite? 1.5)"] + ["NaN? ##NaN" "true" "(NaN? ##NaN)"] + ["NaN? number" "false" "(NaN? 1.0)"] + ["int? ##Inf false" "false" "(int? ##Inf)"] + ["pos-int? ##Inf" "false" "(pos-int? ##Inf)"]) + +# Numeric literal syntaxes. Jolt has no true bignum/ratio/bigdec types, so the +# N (bigint) and M (bigdec) suffixes read as the plain number, ratios as the +# double quotient; radix integers (NrDDD) are parsed by base. +(defspec "numbers / literal syntax" + ["bigint suffix N" "42" "42N"] + ["bigint zero" "0" "0N"] + ["bigdec suffix M" "1.5" "1.5M"] + ["bigdec int M" "0" "0.0M"] + ["ratio -> double" "0.5" "1/2"] + ["ratio 3/4" "0.75" "3/4"] + ["neg ratio" "-0.5" "-1/2"] + ["radix binary" "10" "2r1010"] + ["radix hex-ish" "255" "16rFF"] + ["radix base36" "35" "36rZ"] + ["hex" "255" "0xFF"] + ["exponent" "1000.0" "1e3"] + ["exponent neg" "0.015" "1.5e-2"]) + +# Strictness: numeric ops reject non-numbers like Clojure; the integer +# predicates reject non-integers; quot/rem/mod reject zero/non-finite. +(defspec "numbers / strictness (throws like Clojure)" + ["odd? nil" :throws "(odd? nil)"] + ["odd? fractional" :throws "(odd? 1.5)"] + ["even? inf" :throws "(even? ##Inf)"] + ["zero? nil" :throws "(zero? nil)"] + ["pos? false" :throws "(pos? false)"] + ["neg? keyword" :throws "(neg? :a)"] + ["< nil" :throws "(< nil 1)"] + ["> with nil" :throws "(> 1 nil)"] + ["max non-number" :throws "(max 1 nil)"] + ["quot by zero" :throws "(quot 10 0)"] + ["quot inf" :throws "(quot ##Inf 1)"] + ["< arity-1 any" "true" "(< :anything)"] + ["odd? ok" "true" "(odd? 3)"] + ["< ok" "true" "(< 1 2 3)"] + ["quot ok" "3" "(quot 10 3)"]) + +(defspec "numbers / printing of inf & nan" + ["str Infinity" "\"Infinity\"" "(str ##Inf)"] + ["str -Infinity" "\"-Infinity\"" "(str ##-Inf)"] + ["str NaN" "\"NaN\"" "(str ##NaN)"] + ["pr-str Infinity" "\"Infinity\"" "(pr-str ##Inf)"] + ["inf inside coll" "\"[Infinity]\"" "(str [##Inf])"]) + +(defspec "numbers / bit-ops & math" + ["bit-and" "4" "(bit-and 12 6)"] + ["bit-or" "14" "(bit-or 12 6)"] + ["bit-xor" "10" "(bit-xor 12 6)"] + ["bit-shift-left" "8" "(bit-shift-left 1 3)"] + ["bit-shift-right" "2" "(bit-shift-right 8 2)"] + ["bit-set" "8" "(bit-set 0 3)"] + ["bit-clear" "13" "(bit-clear 15 1)"] + ["bit-test true" "true" "(bit-test 4 2)"] + ["bigint 64-bit" "\"9000000000\"" "(str (bigint 9000000000))"]) + +(defspec "numbers / random (invariants — non-deterministic)" + ["rand-int in range" "true" "(let [r (rand-int 5)] (and (integer? r) (>= r 0) (< r 5)))"] + ["rand-int zero" "0" "(rand-int 1)"] + ["rand in [0,1)" "true" "(let [r (rand)] (and (>= r 0) (< r 1)))"] + ["rand n in [0,n)" "true" "(let [r (rand 10)] (and (>= r 0) (< r 10)))"] + ["rand-nth member" "true" "(contains? #{:a :b :c} (rand-nth [:a :b :c]))"] + ["rand-nth single" ":x" "(rand-nth [:x])"]) diff --git a/test/spec/predicates-spec.janet b/test/spec/predicates-spec.janet new file mode 100644 index 0000000..e1a860c --- /dev/null +++ b/test/spec/predicates-spec.janet @@ -0,0 +1,132 @@ +# Specification: type & value predicates. +(use ../support/harness) + +(defspec "predicates / nil & boolean" + ["nil? true" "true" "(nil? nil)"] + ["nil? false" "false" "(nil? 0)"] + ["some? true" "true" "(some? 0)"] + ["some? on nil" "false" "(some? nil)"] + ["true?" "true" "(true? true)"] + ["false?" "true" "(false? false)"] + ["boolean? true" "true" "(boolean? false)"] + ["not nil" "true" "(not nil)"] + ["not 0 is false" "false" "(not 0)"] + ["boolean of nil" "false" "(boolean nil)"] + ["boolean of value" "true" "(boolean 5)"]) + +(defspec "predicates / types" + ["string?" "true" "(string? \"x\")"] + ["number?" "true" "(number? 1)"] + ["keyword?" "true" "(keyword? :a)"] + ["symbol?" "true" "(symbol? (quote a))"] + ["char?" "true" "(char? \\a)"] + ["fn? on fn" "true" "(fn? inc)"] + ["ifn? on keyword" "true" "(ifn? :a)"] + ["vector?" "true" "(vector? [1])"] + ["list?" "true" "(list? (list 1))"] + ["map?" "true" "(map? {:a 1})"] + ["set?" "true" "(set? #{1})"] + ["coll? vector" "true" "(coll? [1])"] + ["coll? map" "true" "(coll? {:a 1})"] + ["coll? on number" "false" "(coll? 1)"] + ["seq? list" "true" "(seq? (list 1))"] + ["seq? vector" "false" "(seq? [1])"] + ["sequential? vector" "true" "(sequential? [1])"] + ["associative? map" "true" "(associative? {:a 1})"] + ["associative? vec" "true" "(associative? [1])"] + ["associative? list" "false" "(associative? '(1 2))"] + ["associative? set" "false" "(associative? #{1})"] + ["reversible? vec" "true" "(reversible? [1 2])"] + ["reversible? list" "false" "(reversible? '(1 2))"] + ["reversible? smap" "true" "(reversible? (sorted-map :a 1))"] + ["reversible? hmap" "false" "(reversible? (hash-map :a 1))"] + ["indexed? vector" "true" "(indexed? [1])"] + ["counted? vector" "true" "(counted? [1])"]) + +(defspec "predicates / idents" + ["ident? keyword" "true" "(ident? :a)"] + ["ident? symbol" "true" "(ident? (quote a))"] + ["simple-keyword?" "true" "(simple-keyword? :a)"] + ["qualified-keyword?" "true" "(qualified-keyword? :a/b)"] + ["simple-symbol?" "true" "(simple-symbol? (quote a))"] + ["qualified-symbol?" "true" "(qualified-symbol? (quote a/b))"] + ["name of keyword" "\"a\"" "(name :a)"] + ["name of qualified" "\"b\"" "(name :a/b)"] + ["namespace" "\"a\"" "(namespace :a/b)"] + ["namespace simple" "nil" "(namespace :a)"] + ["keyword constructor" ":foo" "(keyword \"foo\")"] + ["keyword ns + name" ":a/b" "(keyword \"a\" \"b\")"] + ["symbol constructor" "(quote x)" "(symbol \"x\")"] + ["name of string" "\"s\"" "(name \"s\")"]) + +# Predicates moved from Janet to the Clojure overlay (jolt-1j0). Jolt has no +# ratio/bigdecimal types (so ratio?/decimal? are always false, rational?=int?), +# and no distinct host object/undefined types (object?/undefined? always false). +(defspec "predicates / overlay-migrated" + ["not-any? true" "true" "(not-any? even? [1 3 5])"] + ["not-any? false" "false" "(not-any? even? [1 2 3])"] + ["not-every? true" "true" "(not-every? even? [2 4 5])"] + ["not-every? false" "false" "(not-every? even? [2 4 6])"] + ["ident? number" "false" "(ident? 1)"] + ["qualified-ident?" "true" "(qualified-ident? :a/b)"] + ["qualified-ident? no" "false" "(qualified-ident? :a)"] + ["simple-ident?" "true" "(simple-ident? :a)"] + ["ratio?" "false" "(ratio? 3)"] + ["decimal?" "false" "(decimal? 3)"] + ["rational? int" "true" "(rational? 3)"] + ["rational? float" "false" "(rational? 3.5)"] + ["nat-int? zero" "true" "(nat-int? 0)"] + ["nat-int? neg" "false" "(nat-int? -1)"] + ["pos-int?" "true" "(pos-int? 5)"] + ["neg-int?" "true" "(neg-int? -3)"] + ["NaN? on nan" "true" "(NaN? (/ 0.0 0.0))"] + ["NaN? on number" "false" "(NaN? 5)"] + ["abs negative" "3" "(abs -3)"] + ["abs positive" "2.5" "(abs 2.5)"] + ["object?" "false" "(object? 1)"] + ["undefined?" "false" "(undefined? 1)"] + ["keyword-identical?" "true" "(keyword-identical? :a :a)"] + ["keyword-identical? no" "false" "(keyword-identical? :a :b)"]) + +# Tagged-value predicates moved to the overlay in Phase 4 (read the value's +# :jolt/type via get). The constructors stay native. +(defspec "predicates / tagged-value (Phase 4)" + ["atom? yes" "true" "(atom? (atom 1))"] + ["atom? no" "false" "(atom? 1)"] + ["volatile? yes" "true" "(volatile? (volatile! 1))"] + ["volatile? no" "false" "(volatile? (atom 1))"] + ["record? yes" "true" "(do (defrecord Rp [a]) (record? (->Rp 1)))"] + ["record? no map" "false" "(record? {:a 1})"] + ["record? no nil" "false" "(record? nil)"] + ["tagged-literal? yes" "true" "(tagged-literal? (tagged-literal (quote inst) \"2020\"))"] + ["tagged-literal? no" "false" "(tagged-literal? 1)"] + ["reader-conditional? no" "false" "(reader-conditional? 1)"] + ["chunked-seq? always false" "false" "(chunked-seq? (seq [1 2 3]))"]) + +(defspec "predicates / equality & identity" + ["= same" "true" "(= 1 1)"] + ["= vectors" "true" "(= [1 2] [1 2])"] + ["= vector & list" "true" "(= [1 2] (list 1 2))"] + ["= maps" "true" "(= {:a 1} {:a 1})"] + ["= sets" "true" "(= #{1 2} #{2 1})"] + ["= nested" "true" "(= {:a [1 2]} {:a [1 2]})"] + ["not= differs" "true" "(not= [1 2] [1 3])"] + ["identical? same kw" "true" "(identical? :a :a)"] + ["compare strings" "-1" "(compare \"a\" \"b\")"]) + +(defspec "predicates / seqable, reduced & emptiness" + ["seqable? vector" "true" "(seqable? [1])"] + ["seqable? map" "true" "(seqable? {:a 1})"] + ["seqable? string" "true" "(seqable? \"s\")"] + ["seqable? nil" "true" "(seqable? nil)"] + ["seqable? number" "false" "(seqable? 5)"] + ["integer? int" "true" "(integer? 5)"] + ["integer? fraction" "false" "(integer? 5.5)"] + ["reduced? wrapped" "true" "(reduced? (reduced 1))"] + ["reduced? plain" "false" "(reduced? 1)"] + ["deref reduced" "9" "(deref (reduced 9))"] + ["unreduced wrapped" "9" "(unreduced (reduced 9))"] + ["unreduced plain" "9" "(unreduced 9)"] + ["not-empty full" "[1]" "(not-empty [1])"] + ["not-empty empty" "nil" "(not-empty [])"] + ["not-empty string" "nil" "(not-empty \"\")"]) diff --git a/test/spec/protocols-spec.janet b/test/spec/protocols-spec.janet new file mode 100644 index 0000000..548a2eb --- /dev/null +++ b/test/spec/protocols-spec.janet @@ -0,0 +1,50 @@ +# Specification: protocols, types and records. +(use ../support/harness) + +(defspec "protocols / defprotocol & dispatch" + ["protocol on record" "16" + "(do (defprotocol Shape (area [s])) (defrecord Sq [side] Shape (area [_] (* side side))) (area (->Sq 4)))"] + ["protocol on deftype" "16" + "(do (defprotocol Shape (area [s])) (deftype Sq [side] Shape (area [_] (* side side))) (area (->Sq 4)))"] + ["multiple methods" "[1 2]" + "(do (defprotocol P (m [s]) (n [s])) (defrecord R [a b] P (m [_] a) (n [_] b)) [(m (->R 1 2)) (n (->R 1 2))])"] + ["multiple protocols" "[:a :b]" + "(do (defprotocol P1 (p1 [s])) (defprotocol P2 (p2 [s])) (deftype T [] P1 (p1 [_] :a) P2 (p2 [_] :b)) [(p1 (->T)) (p2 (->T))])"] + ["method args" "7" + "(do (defprotocol P (add [s x])) (defrecord R [n] P (add [_ x] (+ n x))) (add (->R 5) 2))"] + ["extend-type" "10" + "(do (defprotocol P (twice [s])) (extend-type Number P (twice [n] (* n 2))) (twice 5))"] + ["extend-protocol" "[2 4]" + "(do (defprotocol P (dbl [s])) (extend-protocol P Number (dbl [n] (* n 2))) [(dbl 1) (dbl 2)])"]) + +(defspec "protocols / records" + ["record field access" "1" + "(do (defrecord R [a b]) (:a (->R 1 2)))"] + ["record map access" "2" + "(do (defrecord R [a b]) (get (->R 1 2) :b))"] + ["record equality" "true" + "(do (defrecord R [a b]) (= (->R 1 2) (->R 1 2)))"] + ["record inequality" "false" + "(do (defrecord R [a b]) (= (->R 1 2) (->R 3 4)))"] + ["map-> factory" "1" + "(do (defrecord R [a b]) (:a (map->R {:a 1 :b 2})))"] + ["record? true" "true" + "(do (defrecord R [a]) (record? (->R 1)))"] + ["assoc on record" "9" + "(do (defrecord R [a]) (:a (assoc (->R 1) :a 9)))"]) + +(defspec "protocols / reify & satisfies" + ["reify dispatch" "42" + "(do (defprotocol P (m [_])) (m (reify P (m [_] 42))))"] + ["reify multi-method" "[1 2]" + "(do (defprotocol P (a [_]) (b [_])) (let [r (reify P (a [_] 1) (b [_] 2))] [(a r) (b r)]))"] + ["satisfies? true" "true" + "(do (defprotocol P (m [_])) (defrecord R [] P (m [_] 1)) (satisfies? P (->R)))"] + ["satisfies? false" "false" + "(do (defprotocol P (m [_])) (defrecord R []) (satisfies? P (->R)))"] + ["instance? record" "true" + "(do (defrecord R [a]) (instance? R (->R 1)))"] + ["dot constructor" "5" + "(do (deftype P [n]) (.-n (P. 5)))"] + ["dot ctor + method" "5" + "(do (defprotocol G (val-of [_])) (deftype P [n] G (val-of [_] n)) (val-of (P. 5)))"]) diff --git a/test/spec/reader-forms-spec.janet b/test/spec/reader-forms-spec.janet new file mode 100644 index 0000000..aa4bf19 --- /dev/null +++ b/test/spec/reader-forms-spec.janet @@ -0,0 +1,50 @@ +# Specification: reader forms + syntax-quote + metadata. +# +# Adapted from the jank test corpus (test/jank/{syntax-quote,metadata,reader-macro, +# call}); we keep our own copies since jank may diverge. Syntax-quoted symbols are +# qualified to clojure.core (matching jank/Clojure). Platform-specific reader forms +# (#uuid, #inst, ##Inf/##NaN, bigdecimal/biginteger/ratio) are omitted. +(use ../support/harness) + +(defspec "reader / anonymous fn #()" + ["no args" "3" "(#(+ 1 2))"] + ["one arg %" "6" "(#(* % 2) 3)"] + ["positional %1 %2" "[1 2]" "(#(do [%1 %2]) 1 2)"] + ["rest %&" "[1 2 3]" "(#(do %&) 1 2 3)"] + ["fixed + rest" "[2 3]" "(#(do % %&) 1 2 3)"] + ["%2 + rest" "[3]" "(#(do %2 %&) 1 2 3)"] + ["%2 only (placeholder p1)" "20" "(#(* %2 2) 1 10)"] + ["% and %1 same" "10" "(#(+ % %1) 5)"]) + +(defspec "reader / var-quote #'" + ["var-quote = var" "true" "(= (var str) #'str)"] + ["is a var" "true" "(var? #'str)"] + ["deref var-quote" "5" "(do (def w 5) (deref #'w))"]) + +(defspec "reader / metadata ^" + ["meta on map" "true" "(:foo (meta ^:foo {}))"] + ["meta on vector" "true" "(:foo (meta ^:foo [1 2]))"] + ["meta on set" "true" "(:foo (meta ^:foo #{}))"] + ["meta map form" "1" "(:a (meta ^{:a 1} {}))"] + ["meta on quoted sym" "true" "(:foo (meta (quote ^:foo bar)))"] + ["with-meta map" "true" "(:k (meta (with-meta {} {:k true})))"] + ["with-meta vector" "true" "(:k (meta (with-meta [] {:k true})))"] + ["non-metadatable num" "nil" "(meta 100)"] + ["non-metadatable str" "nil" "(meta \"\")"] + ["non-metadatable bool" "nil" "(meta true)"]) + +(defspec "reader / syntax-quote" + ["plain literal" "[1 2 3]" "`[1 2 3]"] + ["gensym distinct" "true" "(not= `meow# `meow#)"] + ["gensym stable" "true" "(let [s `[meow# meow#]] (= (first s) (second s)))"] + ["qualifies unresolved" "(quote user/foo)" "`foo"] + # jolt-265 (fixed): resolved core symbols fully-qualify to clojure.core/. + ["qualifies core sym" "(quote clojure.core/str)" "`str"] + ["unquote value" "[1 2 3]" "(let [a [1 2 3]] `~a)"] + ["unquote in call" "(quote (clojure.core/str [1 2 3]))" "(let [a [1 2 3]] `(str ~a))"] + ["splice empty" "(quote (clojure.core/str))" "(let [e []] `(str ~@e))"] + ["splice values" "(quote (clojure.core/str 1 2 3))" "(let [a [1 2 3]] `(str ~@a))"] + ["splice in vector" "[1 2 3 0 1 2 3]" "(let [b [0] a [1 2 3] e []] `[~@e ~@a ~@b ~@a ~@e])"] + # jolt-edb (fixed): ~/~@ inside set literals. + ["splice in set" "#{0 1 2 3}" "(let [b [0] a [1 2 3] e []] `#{~@e ~@a ~@b})"] + ["unquote in set" "#{5 9}" "(let [x 5] `#{~x 9})"]) diff --git a/test/spec/reader-syntax-spec.janet b/test/spec/reader-syntax-spec.janet new file mode 100644 index 0000000..ee3c25a --- /dev/null +++ b/test/spec/reader-syntax-spec.janet @@ -0,0 +1,54 @@ +# Specification: reader syntax & literals. +(use ../support/harness) + +(defspec "reader / scalar literals" + ["integer" "42" "42"] + ["negative" "-7" "-7"] + ["float" "1.5" "1.5"] + ["string" "\"hi\"" "\"hi\""] + ["boolean true" "true" "true"] + ["nil" "nil" "nil"] + ["keyword" ":a" ":a"] + ["namespaced keyword" "true" "(= :a/b :a/b)"] + ["char" "\\a" "\\a"] + ["char newline" "true" "(= \\newline (first \"\\n\"))"] + # single non-symbol chars are one-char literals (\{ \( \, \% etc.) + ["char open-brace" "123" "(int \\{)"] + ["char open-paren" "40" "(int \\()"] + ["char comma" "44" "(int \\,)"] + ["char percent" "37" "(int \\%)"] + ["char unicode" "65" "(int \\u0041)"] + ["hex literal" "255" "0xff"] + ["hex uppercase" "31" "0X1F"] + ["bigint suffix N" "42" "42N"] + ["bigdec suffix M" "1.5" "1.5M"] + ["ratio -> double" "0.75" "3/4"] + ["radix integer" "255" "16rFF"] + ["exponent" "1500.0" "1.5e3"] + ["symbolic Infinity" "true" "(infinite? ##Inf)"] + ["symbolic NaN" "true" "(NaN? ##NaN)"] + ["symbol via quote" "'foo" "'foo"]) + +(defspec "reader / collection literals" + ["vector" "[1 2 3]" "[1 2 3]"] + ["list quoted" "[1 2 3]" "'(1 2 3)"] + ["map" "{:a 1}" "{:a 1}"] + ["set" "#{1 2 3}" "#{1 2 3}"] + ["nested" "{:a [1 {:b 2}]}" "{:a [1 {:b 2}]}"] + ["empty vector" "[]" "[]"] + ["empty map" "{}" "{}"] + ["empty set" "#{}" "#{}"]) + +(defspec "reader / dispatch & sugar" + ["anon fn #()" "3" "(#(+ %1 %2) 1 2)"] + ["anon fn single %" "2" "(#(inc %) 1)"] + ["anon fn %&" "[2 3]" "(#(vec %&) 2 3)"] + ["discard #_" "[1 3]" "[1 #_2 3]"] + ["regex literal" "true" "(= \"abc\" (re-find #\"abc\" \"xabcx\"))"] + ["reader conditional" "1" "#?(:clj 1 :cljs 2 :default 3)"] + ["reader cond splice" "[1 2 3]" "[#?@(:clj [1 2 3] :cljs [4 5])]"] + ["inst literal reads" "true" "(some? #inst \"2020-01-01T00:00:00Z\")"] + ["uuid literal" "\"550e8400-e29b-41d4-a716-446655440000\"" "(str #uuid \"550e8400-e29b-41d4-a716-446655440000\")"] + ["tagged literal var" "true" "(var? #'+)"] + ["deref sugar" "5" "(let [a (atom 5)] @a)"] + ["meta sugar" "{:t 1}" "(meta ^{:t 1} [])"]) diff --git a/test/spec/regex-spec.janet b/test/spec/regex-spec.janet new file mode 100644 index 0000000..15b3b8e --- /dev/null +++ b/test/spec/regex-spec.janet @@ -0,0 +1,33 @@ +# Specification: regular expressions — #"…" literals and the re-* fns. +# (Whole area previously unspecced; some cases adapted from jank reader-macro/regex.) +(use ../support/harness) + +(defspec "regex / literals & predicate" + ["regex? literal" "true" "(regex? #\"\\d+\")"] + ["regex? non-regex" "false" "(regex? \"\\d+\")"] + ["escaped digits" "\"42\"" "(re-find #\"\\d+\" \"x42y\")"] + ["escaped ws/non-ws" "\"x a\"" "(re-find #\"\\S\\s\\S\" \"x a b y\")"]) + +(defspec "regex / re-find" + ["match" "\"123\"" "(re-find #\"\\d+\" \"abc123def\")"] + ["no match nil" "nil" "(re-find #\"\\d+\" \"abc\")"] + ["with groups" "[\"a1\" \"a\" \"1\"]" "(re-find #\"([a-z])(\\d)\" \"--a1--\")"] + ["first match only" "\"1\"" "(re-find #\"\\d\" \"1 2 3\")"]) + +(defspec "regex / re-matches" + ["full match" "\"123\"" "(re-matches #\"\\d+\" \"123\")"] + ["partial = nil" "nil" "(re-matches #\"\\d+\" \"123abc\")"] + ["groups" "[\"12\" \"1\" \"2\"]" "(re-matches #\"(\\d)(\\d)\" \"12\")"] + ["no match nil" "nil" "(re-matches #\"x+\" \"yyy\")"]) + +(defspec "regex / re-seq" + ["all matches" "(quote (\"1\" \"22\" \"333\"))" "(re-seq #\"\\d+\" \"a1b22c333\")"] + ["empty when none" "nil" "(seq (re-seq #\"z\" \"abc\"))"] + ["words" "(quote (\"foo\" \"bar\"))" "(re-seq #\"\\w+\" \"foo bar\")"]) + +(defspec "regex / re-pattern & string ops" + ["re-pattern build" "\"hi\"" "(re-find (re-pattern \"\\\\w+\") \"hi!\")"] + ["re-pattern is regex?" "true" "(regex? (re-pattern \"a\"))"] + ["split on regex" "[\"a\" \"b\" \"c\"]" "(do (require '[clojure.string :as s]) (s/split \"a1b2c\" #\"\\d\"))"] + ["replace regex" "\"X-X\"" "(do (require '[clojure.string :as s]) (s/replace \"a-b\" #\"[a-z]\" \"X\"))"] + ["replace $1" "\"[a][b]\"" "(do (require '[clojure.string :as s]) (s/replace \"ab\" #\"([a-z])\" \"[$1]\"))"]) diff --git a/test/spec/sequences-spec.janet b/test/spec/sequences-spec.janet new file mode 100644 index 0000000..c016906 --- /dev/null +++ b/test/spec/sequences-spec.janet @@ -0,0 +1,263 @@ +# Specification: the sequence abstraction (clojure.core). +# Sequential expecteds use vector literals — Jolt's `=` treats vectors and lists +# with the same elements as equal, so [2 3 4] matches a (2 3 4) seq result. +(use ../support/harness) + +(defspec "seq / access" + ["first of vector" "1" "(first [1 2 3])"] + ["first of list" "1" "(first (list 1 2 3))"] + ["first of empty is nil" "nil" "(first [])"] + ["first of nil is nil" "nil" "(first nil)"] + ["second" "2" "(second [1 2 3])"] + ["last" "3" "(last [1 2 3])"] + ["rest of vector" "[2 3]" "(rest [1 2 3])"] + ["rest of single" "[]" "(rest [1])"] + ["rest of empty" "[]" "(rest [])"] + ["next of single is nil" "nil" "(next [1])"] + ["next of empty is nil" "nil" "(next [])"] + ["nth" "30" "(nth [10 20 30] 2)"] + ["nth with default" "99" "(nth [10] 5 99)"] + ["nth out of range" :throws "(nth [10] 5)"] + ["ffirst" "1" "(ffirst [[1 2] [3 4]])"] + ["fnext" "2" "(fnext [1 2 3])"] + ["nnext" "[3 4]" "(nnext [1 2 3 4])"]) + +(defspec "seq / construction" + ["cons onto list" "[0 1 2]" "(cons 0 (list 1 2))"] + ["cons onto vector" "[0 1 2]" "(cons 0 [1 2])"] + ["cons onto nil" "[0]" "(cons 0 nil)"] + ["conj vector appends" "[1 2 3]" "(conj [1 2] 3)"] + ["conj list prepends" "[0 1 2]" "(conj (list 1 2) 0)"] + ["conj multiple on vec" "[1 2 3 4]" "(conj [1 2] 3 4)"] + ["conj multiple on list" "[4 3 1 2]" "(conj (list 1 2) 3 4)"] + ["seq of empty is nil" "nil" "(seq [])"] + ["seq of nil is nil" "nil" "(seq nil)"] + ["seq of string" "[\\a \\b]" "(seq \"ab\")"] + ["empty?" "true" "(empty? [])"] + ["not empty?" "false" "(empty? [1])"] + ["count" "3" "(count [1 2 3])"] + ["count of nil" "0" "(count nil)"] + ["count of string" "3" "(count \"abc\")"]) + +(defspec "seq / map filter reduce" + ["map" "[2 3 4]" "(map inc [1 2 3])"] + ["map two colls" "[5 7 9]" "(map + [1 2 3] [4 5 6])"] + ["map stops at shortest" "[5 7]" "(map + [1 2] [4 5 6])"] + # nil elements are values, not end-of-seq: multi-coll map must not truncate. + ["map keeps nil elements" "[[1 :a] [nil :b] [3 nil]]" "(map vector [1 nil 3] [:a :b nil])"] + ["map 3 colls" "[12 15 18]" "(map + [1 2 3] [4 5 6] [7 8 9])"] + ["map 3 colls shortest" "[12 15]" "(map + [1 2] [4 5 6] [7 8 9])"] + ["map 4 colls" "[16 20]" "(map + [1 2] [3 4] [5 6] [7 8])"] + ["map 3 colls nils" "[[1 :a 10] [nil :b 20] [3 nil 30]]" "(map vector [1 nil 3] [:a :b nil] [10 20 30])"] + ["map empty coll" "()" "(map + [] [1 2 3] [4 5 6])"] + ["map lazy+concrete" "[11 22 33]" "(map + (map identity [1 2 3]) [10 20 30])"] + ["map-indexed" "[[0 :a] [1 :b]]" "(map-indexed vector [:a :b])"] + ["mapv" "[2 3 4]" "(mapv inc [1 2 3])"] + ["filter" "[2 4]" "(filter even? [1 2 3 4])"] + ["filterv" "[2 4]" "(filterv even? [1 2 3 4])"] + ["remove" "[1 3]" "(remove even? [1 2 3 4])"] + ["reduce" "10" "(reduce + [1 2 3 4])"] + ["reduce with init" "20" "(reduce + 10 [1 2 3 4])"] + ["reduce empty with init" "0" "(reduce + 0 [])"] + ["reduce single no init" "5" "(reduce + [5])"] + ["reduced short-circuits" "3" "(reduce (fn [a x] (if (> a 2) (reduced a) (+ a x))) 0 [1 2 3 4 5])"] + ["reduce-kv" "6" "(reduce-kv (fn [a k v] (+ a v)) 0 {:a 1 :b 2 :c 3})"] + ["reduce-kv on vector" "[[0 :a] [1 :b]]" "(reduce-kv (fn [a i v] (conj a [i v])) [] [:a :b])"] + ["reduce-kv honors reduced" "[:a]" "(reduce-kv (fn [a i v] (if (= i 1) (reduced a) (conj a v))) [] [:a :b :c])"] + ["reduce-kv on nil" "0" "(reduce-kv (fn [a k v] (+ a v)) 0 nil)"] + ["reductions" "[1 3 6]" "(reductions + [1 2 3])"] + ["mapcat" "[1 1 2 2]" "(mapcat (fn [x] [x x]) [1 2])"] + ["mapcat two colls" "[1 3 2 4]" "(mapcat vector [1 2] [3 4])"] + ["mapcat three colls" "[1 2 3]" "(mapcat vector [1] [2] [3])"] + ["mapcat empty coll" "()" "(mapcat vector [] [1 2] [3 4])"] + ["mapcat seqs" "[1 2 3 4]" "(mapcat identity [[1 2] [3 4]])"] + ["keep" "[1 3]" "(keep (fn [x] (if (odd? x) x nil)) [1 2 3 4])"] + ["some truthy" "true" "(some even? [1 2 3])"] + ["some nil" "nil" "(some even? [1 3 5])"] + ["every? true" "true" "(every? pos? [1 2 3])"] + ["every? false" "false" "(every? pos? [1 -2 3])"]) + +(defspec "seq / take drop slice" + ["take" "[1 2 3]" "(take 3 [1 2 3 4 5])"] + ["take more than size" "[1 2]" "(take 5 [1 2])"] + ["drop" "[4 5]" "(drop 3 [1 2 3 4 5])"] + ["take-while" "[1 2]" "(take-while (fn [x] (< x 3)) [1 2 3 1])"] + ["drop-while" "[3 1]" "(drop-while (fn [x] (< x 3)) [1 2 3 1])"] + ["take-last" "[4 5]" "(take-last 2 [1 2 3 4 5])"] + ["drop-last" "[1 2 3]" "(drop-last [1 2 3 4])"] + ["take-nth" "[1 3 5]" "(take-nth 2 [1 2 3 4 5])"] + ["partition" "[[1 2] [3 4]]" "(partition 2 [1 2 3 4 5])"] + ["partition-all" "[[1 2] [3]]" "(partition-all 2 [1 2 3])"] + ["split-at" "[[1 2] [3 4]]" "(split-at 2 [1 2 3 4])"]) + +(defspec "seq / transform" + ["reverse" "[3 2 1]" "(reverse [1 2 3])"] + ["sort" "[1 2 3]" "(sort [3 1 2])"] + ["sort with comparator" "[3 2 1]" "(sort > [1 3 2])"] + ["sort-by" "[[1] [2 2]]" "(sort-by count [[2 2] [1]])"] + ["distinct" "[1 2 3]" "(distinct [1 1 2 3 3])"] + ["dedupe" "[1 2 1]" "(dedupe [1 1 2 1])"] + ["interpose" "[1 0 2 0 3]" "(interpose 0 [1 2 3])"] + ["interleave" "[1 :a 2 :b]" "(interleave [1 2] [:a :b])"] + ["flatten" "[1 2 3 4]" "(flatten [1 [2 [3 [4]]]])"] + ["concat" "[1 2 3 4]" "(concat [1 2] [3 4])"] + ["into vector" "[1 2 3 4]" "(into [1 2] [3 4])"] + ["into list" "[3 2 1]" "(into (list) [1 2 3])"] + ["frequencies" "{1 2, 2 1}" "(frequencies [1 1 2])"] + ["group-by" "{false [1 3], true [2 4]}" "(group-by even? [1 2 3 4])"] + ["zipmap" "{:a 1, :b 2}" "(zipmap [:a :b] [1 2])"] + ["mapcat seqs" "[1 2 3 4]" "(mapcat identity [[1 2] [3 4]])"]) + +(defspec "seq / generators" + ["range n" "[0 1 2 3]" "(range 4)"] + ["range from to" "[2 3 4]" "(range 2 5)"] + ["range with step" "[0 2 4]" "(range 0 6 2)"] + ["take repeat" "[:x :x :x]" "(take 3 (repeat :x))"] + ["repeat n" "[5 5]" "(repeat 2 5)"] + ["take iterate" "[1 2 4 8]" "(take 4 (iterate (fn [x] (* x 2)) 1))"] + ["take cycle" "[1 2 1 2 1]" "(take 5 (cycle [1 2]))"] + ["take repeatedly" "3" "(count (take 3 (repeatedly (fn [] 1))))"] + ["take-last of range" "[8 9]" "(take-last 2 (range 10))"]) + +# Clojure IFn values used as the function arg to higher-order fns: a keyword or +# symbol looks up a key, a set tests membership, a map looks up a key. +(defspec "seq / IFn values as functions" + ["map keyword" "[1 2 3]" "(map :a [{:a 1} {:a 2} {:a 3}])"] + ["filter keyword" "[{:ok true}]" "(filter :ok [{:ok true} {:ok false}])"] + ["remove keyword" "[{:ok false}]" "(remove :ok [{:ok true} {:ok false}])"] + ["sort-by keyword" "[{:a 1} {:a 2} {:a 3}]" "(sort-by :a [{:a 3} {:a 1} {:a 2}])"] + ["sort-by key + cmp" "[{:a 3} {:a 2} {:a 1}]" "(sort-by :a > [{:a 3} {:a 1} {:a 2}])"] + ["filter set" "[2 4]" "(filter #{2 4} [1 2 3 4 5])"] + ["remove set" "[1 3 5]" "(remove #{2 4} [1 2 3 4 5])"] + ["group-by keyword" "{1 [{:n 1}], 2 [{:n 2}]}" "(group-by :n [{:n 1} {:n 2}])"] + ["map a map" "[1 nil 2]" "(map {:a 1 :b 2} [:a :z :b])"] + ["take-nth transducer" "[0 2 4 6 8]" "(into [] (take-nth 2) (range 10))"] + ["interpose transducer" "[1 :x 2]" "(into [] (interpose :x) [1 2])"]) + +# conj edge cases: 0-arg, conj onto nil (builds a list), conj a map into a map. +(defspec "seq / conj edge cases" + ["conj no args" "[]" "(conj)"] + ["conj nil one" "[3]" "(conj nil 3)"] + ["conj nil many" "[2 1]" "(conj nil 1 2)"] + ["conj vector" "[1 2 3]" "(conj [1 2] 3)"] + ["conj list prepend" "[0 1 2]" "(conj '(1 2) 0)"] + ["conj map + map" "{:a 0, :b 1}" "(conj {:a 0} {:b 1})"] + ["conj map + pair" "{:a 0, :b 1}" "(conj {:a 0} [:b 1])"] + ["conj map merge wins" "{:a 2}" "(conj {:a 0} {:a 1} {:a 2})"]) + +# Strictness: these reject malformed arguments like Clojure. +(defspec "seq / strictness (throws like Clojure)" + ["cons non-seqable num" :throws "(cons 1 42)"] + ["cons non-seqable kw" :throws "(cons 1 :k)"] + ["cons onto nil ok" "[1]" "(cons 1 nil)"] + ["cons onto seq ok" "[0 1 2]" "(cons 0 [1 2])"] + ["num non-number" :throws "(num \"x\")"] + ["num ok" "5" "(num 5)"] + ["realized? on number" :throws "(realized? 1)"] + ["realized? on nil" :throws "(realized? nil)"] + ["symbol from nil" :throws "(symbol nil)"] + ["symbol bad 2-arg" :throws "(symbol :a \"b\")"] + ["symbol from keyword" "\"x\"" "(name (symbol :x))"] + ["keyword bad 2-arg" :throws "(keyword \"abc\" nil)"] + ["keyword from symbol" "\"x\"" "(name (keyword 'x))"]) + +# Stack/accessor strictness: peek/pop are stack-only; vec needs a seqable; +# key/val need a map entry. +(defspec "seq / accessor strictness" + ["peek vector" "3" "(peek [1 2 3])"] + ["peek list" "1" "(peek '(1 2 3))"] + ["peek empty vec" "nil" "(peek [])"] + ["peek on set" :throws "(peek #{1 2})"] + ["peek on number" :throws "(peek 42)"] + ["pop empty vec" :throws "(pop [])"] + ["pop on number" :throws "(pop 0)"] + ["pop vector" "[1 2]" "(pop [1 2 3])"] + ["vec on number" :throws "(vec 42)"] + ["vec on keyword" :throws "(vec :a)"] + ["vec ok" "[1 2]" "(vec '(1 2))"] + ["key on nil" :throws "(key nil)"] + ["key on map" :throws "(key {})"] + ["val on number" :throws "(val 0)"] + ["key of entry" ":a" "(key (first {:a 1}))"] + ["val of entry" "1" "(val (first {:a 1}))"]) + +# More strictness: first/rseq on the right shapes, assoc even-arg requirement. +(defspec "seq / more strictness" + ["first on number" :throws "(first 42)"] + ["first on keyword" :throws "(first :a)"] + ["first ok vec" "1" "(first [1 2])"] + ["first ok nil" "nil" "(first nil)"] + ["rseq vector" "[3 2 1]" "(rseq [1 2 3])"] + ["rseq on string" :throws "(rseq \"ab\")"] + ["rseq on map" :throws "(rseq {:a 1})"] + ["rseq on number" :throws "(rseq 0)"] + ["assoc odd args" :throws "(assoc {:a 1} :b)"] + ["assoc on number" :throws "(assoc 5 :a 1)"] + ["assoc on set" :throws "(assoc #{} :a 1)"]) + +# Strictness on more core fns: seq/shuffle need seqables, NaN? needs a number, +# nthrest/nthnext need a numeric count (and clamp negatives / accept nil coll). +(defspec "seq / strictness round 3" + ["seq on number" :throws "(seq 1)"] + ["seq on fn" :throws "(seq (fn [] 1))"] + ["seq vector ok" "[1 2]" "(seq [1 2])"] + ["NaN? on nil" :throws "(NaN? nil)"] + ["NaN? on number ok" "false" "(NaN? 1.0)"] + ["shuffle on number" :throws "(shuffle 1)"] + ["shuffle on string" :throws "(shuffle \"abc\")"] + ["shuffle vec ok" "3" "(count (shuffle [1 2 3]))"] + ["nthrest nil count" :throws "(nthrest [0 1 2] nil)"] + ["nthrest negative" "[0 1 2]" "(nthrest [0 1 2] -1)"] + ["nthrest nil coll" "nil" "(nthrest nil 0)"] + ["nthnext nil count" :throws "(nthnext [0 1 2] nil)"] + ["update vec oob" :throws "(update [] 1 identity)"] + ["update vec kw key" :throws "(update [1 2 3] :k identity)"]) + +# Regression cases for clojure.core fns moved from Janet to the Clojure overlay +# (jolt-1j0), plus two bugs fixed in the process: nthrest returns () (not nil) +# for an exhausted n>0 walk, and distinct? compares by VALUE (equal collections +# are not distinct). +(defspec "seq / overlay-migrated fns" + ["nthrest exhausted -> ()" "()" "(nthrest nil 100)"] + ["nthrest vec exhausted" "()" "(nthrest [1 2 3] 100)"] + ["nthrest n<=0 keeps coll" "[1 2 3]" "(nthrest [1 2 3] 0)"] + ["nthrest drops n" "[3 4 5]" "(nthrest [1 2 3 4 5] 2)"] + ["nthnext exhausted -> nil" "nil" "(nthnext [1 2] 5)"] + ["nthnext surprising nil" "nil" "(nthnext nil nil)"] + ["nthnext drops n" "[3 4]" "(nthnext [1 2 3 4] 2)"] + ["distinct? distinct" "true" "(distinct? 1 2 3)"] + ["distinct? dup" "false" "(distinct? 1 2 1)"] + ["distinct? equal colls" "false" "(distinct? [1 2] [1 2])"] + ["distinct? single" "true" "(distinct? 5)"] + ["replace maps elements" "[:a 2 :c 2]" "(replace {1 :a 3 :c} [1 2 3 2])"] + ["replace preserves nil val" "[1 nil 3]" "(replace {2 nil} [1 2 3])"] + ["take-last" "[3 4]" "(take-last 2 [1 2 3 4])"] + ["take-last empty -> nil" "nil" "(take-last 2 [])"] + ["take-last n>len" "[1 2]" "(take-last 9 [1 2])"] + ["drop-last default 1" "[1 2]" "(drop-last [1 2 3])"] + ["drop-last n" "[1 2]" "(drop-last 2 [1 2 3 4])"] + ["split-with" "[[2 4] [5 6]]" "(split-with even? [2 4 5 6])"] + ["replicate" "[:x :x :x]" "(replicate 3 :x)"] + ["bounded-count" "3" "(bounded-count 3 [1 2 3 4 5])"] + ["run! side effects" "6" "(let [a (atom 0)] (run! (fn [x] (swap! a + x)) [1 2 3]) @a)"] + ["completing wraps rf" "3" "((completing +) 1 2)"] + ["comparator <" "[1 2 3]" "(sort (comparator <) [3 1 2])"] + ["comparator >" "[3 2 1]" "(sort (comparator >) [3 1 2])"] + ["reductions" "[1 3 6 10]" "(reductions + [1 2 3 4])"] + ["reductions with init" "[10 11 13 16]" "(reductions + 10 [1 2 3])"] + ["reductions empty calls f" "[0]" "(reductions + [])"] + ["reductions empty + init" "[5]" "(reductions + 5 [])"] + ["tree-seq pre-order" "[[1 [2] 3] 1 [2] 2 3]" "(tree-seq sequential? seq [1 [2] 3])"] + ["some found" "true" "(some even? [1 3 4])"] + ["some none -> nil" "nil" "(some even? [1 3 5])"] + ["some keyword pred" "7" "(some :a [{:b 1} {:a 7}])"] + ["some returns value" "4" "(some (fn [x] (when (even? x) x)) [1 3 4 5])"] + ["flatten nested" "[1 2 3 4 5]" "(flatten [1 [2 [3 4]] 5])"] + ["flatten lists too" "[1 2 3]" "(flatten [1 (list 2 3)])"] + ["flatten scalar -> empty" "[]" "(flatten 5)"] + ["interleave" "[1 :a 2 :b]" "(interleave [1 2 3] [:a :b])"] + ["interleave empty" "[]" "(interleave)"] + ["rationalize identity" "5" "(rationalize 5)"] + ["dedupe consecutive" "[1 2 3 1]" "(dedupe [1 1 2 2 3 1 1])"] + ["dedupe empty" "[]" "(dedupe [])"] + ["dedupe no dups" "[1 2 3]" "(dedupe [1 2 3])"]) diff --git a/test/spec/sets-spec.janet b/test/spec/sets-spec.janet new file mode 100644 index 0000000..db707fa --- /dev/null +++ b/test/spec/sets-spec.janet @@ -0,0 +1,42 @@ +# Specification: sets, including clojure.set. +(use ../support/harness) + +(defspec "set / construct & predicate" + ["literal" "#{1 2 3}" "#{1 2 3}"] + ["hash-set" "#{1 2 3}" "(hash-set 1 2 3)"] + ["set from vector" "#{1 2 3}" "(set [1 2 3 1])"] + ["empty" "#{}" "#{}"] + ["set? true" "true" "(set? #{1})"] + ["set? false on vector" "false" "(set? [1])"] + ["count dedups" "3" "(count (set [1 1 2 3]))"] + ["equality order-indep" "true" "(= #{1 2 3} #{3 2 1})"]) + +(defspec "set / operations" + ["conj adds" "#{1 2 3}" "(conj #{1 2} 3)"] + ["conj dup no-op" "#{1 2}" "(conj #{1 2} 1)"] + ["disj removes" "#{1 2}" "(disj #{1 2 3} 3)"] + ["disj missing no-op" "#{1 2}" "(disj #{1 2} 9)"] + ["contains?" "true" "(contains? #{1 2} 1)"] + ["contains? missing" "false" "(contains? #{1 2} 9)"] + ["get present" "1" "(get #{1 2} 1)"] + ["get missing nil" "nil" "(get #{1 2} 9)"] + ["set as fn present" "2" "(#{1 2 3} 2)"] + ["set as fn missing" "nil" "(#{1 2 3} 9)"]) + +(defspec "set / literals & value elements" + ["literal evaluates elements" "#{2 4}" "#{(inc 1) (* 2 2)}"] + ["map elements by value" "true" "(= #{{:a 1}} #{(hash-map :a 1)})"] + ["contains? map by value" "true" "(contains? #{(hash-map :x 1)} {:x 1})"] + ["dedup equal maps" "1" "(count (set [{:a 1} (hash-map :a 1)]))"] + ["vector elements" "true" "(contains? #{[1 2]} (vec [1 2]))"]) + +(defspec "clojure.set" + ["union" "#{1 2 3 4}" "(do (require (quote [clojure.set :as s])) (s/union #{1 2} #{3 4}))"] + ["intersection" "#{2}" "(do (require (quote [clojure.set :as s])) (s/intersection #{1 2} #{2 3}))"] + ["difference" "#{1}" "(do (require (quote [clojure.set :as s])) (s/difference #{1 2} #{2 3}))"] + ["subset? true" "true" "(do (require (quote [clojure.set :as s])) (s/subset? #{1} #{1 2}))"] + ["superset? true" "true" "(do (require (quote [clojure.set :as s])) (s/superset? #{1 2} #{1}))"] + ["select" "#{2 4}" "(do (require (quote [clojure.set :as s])) (s/select even? #{1 2 3 4}))"] + ["join" "#{{:a 1, :b 2, :c 3}}" "(do (require (quote [clojure.set :as s])) (s/join #{{:a 1 :b 2}} #{{:b 2 :c 3}}))"] + ["map-invert" "{1 :a}" "(do (require (quote [clojure.set :as s])) (s/map-invert {:a 1}))"] + ["rename-keys" "{:b 1}" "(do (require (quote [clojure.set :as s])) (s/rename-keys {:a 1} {:a :b}))"]) diff --git a/test/spec/sorted-spec.janet b/test/spec/sorted-spec.janet new file mode 100644 index 0000000..4224d59 --- /dev/null +++ b/test/spec/sorted-spec.janet @@ -0,0 +1,59 @@ +# Specification: sorted collections (sorted-map / sorted-set, subseq/rsubseq). +# +# sorted collections are first-class for the core ops (jolt-ti9): get/assoc/dissoc/ +# conj/contains?/keys/vals/disj all work and preserve sort order, and a sorted coll +# is callable as a key-lookup fn. STILL TODO: the by-comparator constructors +# (sorted-map-by / sorted-set-by) ignore the supplied comparator (jolt-ti9). (vec +# coerces a seq to a vector so expecteds are vector literals, not quoted lists.) +(use ../support/harness) + +(defspec "sorted / construction & ordering" + ["sorted-set orders" "[1 2 3]" "(vec (seq (sorted-set 3 1 2)))"] + ["sorted-set dedupes" "[1 2 3]" "(vec (seq (sorted-set 3 1 2 1 3)))"] + ["sorted-set numeric" "[1 2 10]" "(vec (seq (sorted-set 10 1 2)))"] + ["sorted-map ordered entries" "[[:a 1] [:b 2] [:c 3]]" "(vec (seq (sorted-map :c 3 :a 1 :b 2)))"] + ["first is min" "1" "(first (sorted-set 5 3 9 1))"]) + +(defspec "sorted / sorted?" + ["sorted-set" "true" "(sorted? (sorted-set 1))"] + ["sorted-map" "true" "(sorted? (sorted-map :a 1))"] + ["plain set" "false" "(sorted? #{1})"] + ["plain map" "false" "(sorted? {:a 1})"] + ["vector" "false" "(sorted? [1 2])"]) + +(defspec "sorted / map ops" + ["get hit" "2" "(get (sorted-map :a 1 :b 2) :b)"] + ["get miss default" ":none" "(get (sorted-map :a 1) :z :none)"] + ["contains? yes" "true" "(contains? (sorted-map :a 1) :a)"] + ["contains? no" "false" "(contains? (sorted-map :a 1) :z)"] + ["assoc keeps order" "[[:a 1] [:b 2] [:c 3]]" "(vec (seq (assoc (sorted-map :c 3 :a 1) :b 2)))"] + ["dissoc" "[[:a 1] [:c 3]]" "(vec (seq (dissoc (sorted-map :a 1 :b 2 :c 3) :b)))"] + ["conj entry" "[[:a 1] [:z 9]]" "(vec (seq (conj (sorted-map :a 1) [:z 9])))"] + ["keys sorted" "[:a :b :c]" "(vec (keys (sorted-map :c 3 :a 1 :b 2)))"] + ["vals by key" "[1 2 3]" "(vec (vals (sorted-map :c 3 :a 1 :b 2)))"] + ["map as fn" "2" "((sorted-map :a 1 :b 2) :b)"] + ["map as fn miss" ":d" "((sorted-map :a 1) :z :d)"]) + +(defspec "sorted / set ops" + ["get present" "2" "(get (sorted-set 1 2 3) 2)"] + ["get absent" ":none" "(get (sorted-set 1 2 3) 9 :none)"] + ["contains? yes" "true" "(contains? (sorted-set 1 2 3) 2)"] + ["contains? no" "false" "(contains? (sorted-set 1 2 3) 9)"] + ["conj keeps order" "[0 1 2 3 5]" "(vec (seq (conj (sorted-set 1 2 3) 5 0)))"] + ["disj" "[1 3]" "(vec (seq (disj (sorted-set 1 2 3) 2)))"] + ["set as fn" "3" "((sorted-set 1 2 3) 3)"] + ["set as fn miss" "nil" "((sorted-set 1 2 3) 9)"]) + +(defspec "sorted / by comparator" + ["sorted-set-by desc" "[10 3 2 1]" "(vec (seq (sorted-set-by > 1 3 2 10)))"] + ["sorted-map-by desc" "[[3 :c] [2 :b] [1 :a]]" "(vec (seq (sorted-map-by > 1 :a 3 :c 2 :b)))"] + ["conj keeps comparator" "[5 3 2 1 0]" "(vec (seq (conj (sorted-set-by > 1 3 2) 5 0)))"] + ["assoc keeps comparator" "[3 2 1]" "(vec (keys (assoc (sorted-map-by > 1 :a 3 :c) 2 :b)))"] + ["disj keeps comparator" "[3 1]" "(vec (seq (disj (sorted-set-by > 1 2 3) 2)))"] + ["by-comparator is sorted?" "true" "(sorted? (sorted-set-by > 1 2))"]) + +(defspec "sorted / subseq & rsubseq" + ["subseq >=" "[3 4 5]" "(vec (subseq (sorted-set 1 2 3 4 5) >= 3))"] + ["subseq <" "[1 2]" "(vec (subseq (sorted-set 1 2 3 4 5) < 3))"] + ["subseq range" "[2 3 4]" "(vec (subseq (sorted-set 1 2 3 4 5) > 1 < 5))"] + ["rsubseq <=" "[3 2 1]" "(vec (rsubseq (sorted-set 1 2 3 4 5) <= 3))"]) diff --git a/test/spec/state-spec.janet b/test/spec/state-spec.janet new file mode 100644 index 0000000..b959eb2 --- /dev/null +++ b/test/spec/state-spec.janet @@ -0,0 +1,39 @@ +# Specification: stateful reference types (atoms, volatiles, delays, promises). +(use ../support/harness) + +(defspec "state / atoms" + ["deref @" "0" "(let [a (atom 0)] @a)"] + ["deref fn" "0" "(deref (atom 0))"] + ["reset!" "5" "(let [a (atom 0)] (reset! a 5) @a)"] + ["reset! returns new" "5" "(let [a (atom 0)] (reset! a 5))"] + ["swap!" "1" "(let [a (atom 0)] (swap! a inc) @a)"] + ["swap! with args" "10" "(let [a (atom 1)] (swap! a + 2 3 4) @a)"] + ["swap! returns new" "1" "(let [a (atom 0)] (swap! a inc))"] + ["swap-vals!" "[0 1]" "(let [a (atom 0)] (swap-vals! a inc))"] + ["reset-vals!" "[0 9]" "(let [a (atom 0)] (reset-vals! a 9))"] + ["compare-and-set! ok" "true" "(let [a (atom 0)] (compare-and-set! a 0 1))"] + ["compare-and-set! no" "false" "(let [a (atom 0)] (compare-and-set! a 9 1))"] + ["atom?" "true" "(do (require (quote [clojure.core])) (instance? clojure.lang.Atom (atom 0)))"] + ["atom? predicate" "true" "(atom? (atom 0))"] + ["atom? on non-atom" "false" "(atom? 5)"]) + +(defspec "state / watches & validators" + ["add-watch fires" "1" "(let [a (atom 0) seen (atom 0)] (add-watch a :k (fn [k r o n] (reset! seen 1))) (reset! a 5) @seen)"] + ["remove-watch" "0" "(let [a (atom 0) seen (atom 0)] (add-watch a :k (fn [k r o n] (swap! seen inc))) (remove-watch a :k) (reset! a 5) @seen)"] + ["set-validator! ok" "5" "(let [a (atom 0)] (set-validator! a number?) (reset! a 5) @a)"] + ["set-validator! rejects" :throws "(let [a (atom 0)] (set-validator! a pos?) (reset! a -1))"] + ["get-validator" "true" "(let [a (atom 0)] (set-validator! a number?) (fn? (get-validator a)))"]) + +(defspec "state / volatiles & delays" + ["volatile! deref" "0" "(let [v (volatile! 0)] @v)"] + ["vreset!" "5" "(let [v (volatile! 0)] (vreset! v 5) @v)"] + ["vswap!" "1" "(let [v (volatile! 0)] (vswap! v inc) @v)"] + ["delay not forced" "0" "(let [c (atom 0) d (delay (swap! c inc))] @c)"] + ["delay force once" "1" "(let [c (atom 0) d (delay (swap! c inc))] (force d) (force d) @c)"] + ["delay value" "5" "(let [d (delay 5)] @d)"] + ["realized? before" "false" "(let [d (delay 5)] (realized? d))"] + ["realized? after" "true" "(let [d (delay 5)] (force d) (realized? d))"]) + +(defspec "state / promises" + ["promise deliver" "5" "(let [p (promise)] (deliver p 5) @p)"] + ["promise undelivered" "nil" "(let [p (promise)] @p)"]) diff --git a/test/spec/strings-spec.janet b/test/spec/strings-spec.janet new file mode 100644 index 0000000..18f247d --- /dev/null +++ b/test/spec/strings-spec.janet @@ -0,0 +1,55 @@ +# Specification: strings (str + clojure.string). +(use ../support/harness) + +(defspec "string / str & basics" + ["str concat" "\"abc\"" "(str \"a\" \"b\" \"c\")"] + ["str of numbers" "\"12\"" "(str 1 2)"] + ["str nil is empty" "\"\"" "(str nil)"] + ["str mixed" "\"a1:b\"" "(str \"a\" 1 :b)"] + ["str of coll" "\"[1 2]\"" "(str [1 2])"] + ["count" "3" "(count \"abc\")"] + ["subs from" "\"bc\"" "(subs \"abc\" 1)"] + ["subs range" "\"b\"" "(subs \"abc\" 1 2)"] + ["string? true" "true" "(string? \"x\")"] + ["pr-str vector" "\"[1 2 3]\"" "(pr-str [1 2 3])"] + ["pr-str quotes str" "\"\\\"hi\\\"\"" "(pr-str \"hi\")"] + # a var's :meta/:ns refs are cyclic — pr-str/str render it as #'ns/name + # rather than recursing into (and looping on) the var's fields. + ["pr-str of a var" "\"#'user/vv\"" "(pr-str (def vv 1))"] + ["str of a var" "\"#'user/ww\"" "(str (def ww 2))"] + ["pr-str of a defn" "\"#'user/gg\"" "(pr-str (defn gg [x] x))"] + ["seq of string" "[\\a \\b]" "(seq \"ab\")"]) + +(defspec "clojure.string" + ["join" "\"a,b,c\"" "(do (require (quote [clojure.string :as s])) (s/join \",\" [\"a\" \"b\" \"c\"]))"] + ["join no sep" "\"abc\"" "(do (require (quote [clojure.string :as s])) (s/join [\"a\" \"b\" \"c\"]))"] + ["split" "[\"a\" \"b\"]" "(do (require (quote [clojure.string :as s])) (s/split \"a,b\" #\",\"))"] + ["split-lines" "[\"a\" \"b\"]" "(do (require (quote [clojure.string :as s])) (s/split-lines \"a\\nb\"))"] + ["upper-case" "\"ABC\"" "(do (require (quote [clojure.string :as s])) (s/upper-case \"abc\"))"] + ["lower-case" "\"abc\"" "(do (require (quote [clojure.string :as s])) (s/lower-case \"ABC\"))"] + ["capitalize" "\"Abc\"" "(do (require (quote [clojure.string :as s])) (s/capitalize \"abc\"))"] + ["trim" "\"x\"" "(do (require (quote [clojure.string :as s])) (s/trim \" x \"))"] + ["triml" "\"x \"" "(do (require (quote [clojure.string :as s])) (s/triml \" x \"))"] + ["blank? true" "true" "(do (require (quote [clojure.string :as s])) (s/blank? \" \"))"] + ["blank? false" "false" "(do (require (quote [clojure.string :as s])) (s/blank? \"x\"))"] + ["includes?" "true" "(do (require (quote [clojure.string :as s])) (s/includes? \"hello\" \"ell\"))"] + ["starts-with?" "true" "(do (require (quote [clojure.string :as s])) (s/starts-with? \"hello\" \"he\"))"] + ["ends-with?" "true" "(do (require (quote [clojure.string :as s])) (s/ends-with? \"hello\" \"lo\"))"] + ["replace" "\"hexxo\"" "(do (require (quote [clojure.string :as s])) (s/replace \"hello\" \"l\" \"x\"))"] + ["reverse" "\"cba\"" "(do (require (quote [clojure.string :as s])) (s/reverse \"abc\"))"] + ["index-of" "2" "(do (require (quote [clojure.string :as s])) (s/index-of \"hello\" \"l\"))"]) + +# subs validates bounds like Clojure (no Janet from-end/clamping). +(defspec "string / subs strictness" + ["subs basic" "\"bcd\"" "(subs \"abcde\" 1 4)"] + ["subs to end" "\"cde\"" "(subs \"abcde\" 2)"] + ["subs start>end" :throws "(subs \"abcde\" 2 1)"] + ["subs negative" :throws "(subs \"abcde\" -1)"] + ["subs end past len" :throws "(subs \"abcde\" 1 6)"] + ["subs nil start" :throws "(subs \"abcde\" nil 2)"] + ["subs on nil" :throws "(subs nil 1 2)"]) + +(defspec "string / namespace-munge" + ["hyphens to underscores" "\"a_b_c\"" "(namespace-munge \"a-b-c\")"] + ["from a symbol" "\"foo_bar\"" "(namespace-munge (quote foo-bar))"] + ["no hyphens unchanged" "\"ok\"" "(namespace-munge \"ok\")"]) diff --git a/test/spec/transducers-spec.janet b/test/spec/transducers-spec.janet new file mode 100644 index 0000000..727581f --- /dev/null +++ b/test/spec/transducers-spec.janet @@ -0,0 +1,52 @@ +# Specification: transducers. +(use ../support/harness) + +(defspec "transducers / into" + ["map xform" "[2 3 4]" "(into [] (map inc) [1 2 3])"] + ["filter xform" "[2 4]" "(into [] (filter even?) [1 2 3 4])"] + ["remove xform" "[1 3]" "(into [] (remove even?) [1 2 3 4])"] + ["take xform" "[1 2]" "(into [] (take 2) [1 2 3 4])"] + ["drop xform" "[3 4]" "(into [] (drop 2) [1 2 3 4])"] + ["take-while xform" "[1 2]" "(into [] (take-while (fn [x] (< x 3))) [1 2 3 1])"] + ["keep xform" "[1 3]" "(into [] (keep (fn [x] (if (odd? x) x nil))) [1 2 3 4])"] + ["map-indexed xform" "[[0 :a] [1 :b]]" "(into [] (map-indexed vector) [:a :b])"] + ["mapcat xform" "[1 1 2 2]" "(into [] (mapcat (fn [x] [x x])) [1 2])"] + ["cat xform" "[1 2 3 4]" "(into [] cat [[1 2] [3 4]])"] + ["into a set" "#{2 3 4}" "(into #{} (map inc) [1 2 3])"]) + +# transducer comp applies left-to-right: (comp (map a) (filter b)) maps then filters +(defspec "transducers / compose" + ["comp map+filter" "[2 4 6 8]" "(into [] (comp (map (fn [x] (* x 2))) (filter even?)) [1 2 3 4])"] + ["comp filter+map" "[2 4]" "(into [] (comp (filter odd?) (map inc)) [1 2 3 4])"] + ["comp three" "[2]" "(into [] (comp (map inc) (filter even?) (take 1)) [1 2 3 4])"]) + +(defspec "transducers / transduce & sequence" + ["transduce sum" "9" "(transduce (map inc) + [1 2 3])"] + ["transduce init" "19" "(transduce (map inc) + 10 [1 2 3])"] + ["transduce filter" "6" "(transduce (filter even?) + [1 2 3 4])"] + ["sequence xform" "[2 3 4]" "(sequence (map inc) [1 2 3])"] + ["eduction" "[2 3 4]" "(into [] (eduction (map inc) [1 2 3]))"] + ["completing" "9" "(transduce (map inc) (completing +) 0 [1 2 3])"]) + +# A `take`/`take-while` transducer returns `reduced`, which must short-circuit +# the reduction so transducing over an INFINITE seq terminates rather than +# realizing it eagerly. +(defspec "transducers / short-circuit over infinite seqs" + ["into take (range)" "[0 1 2 3 4]" "(into [] (take 5) (range))"] + ["transduce take (range)" "3" "(transduce (take 3) + 0 (range))"] + ["sequence take (range)" "[0 1 2 3 4]" "(sequence (take 5) (range))"] + ["take-while over (range)" "[0 1 2]" "(into [] (take-while (fn [x] (< x 3))) (range))"] + ["comp take over (range)" "[1 3 5]" "(into [] (comp (filter odd?) (take 3)) (range))"] + ["into take iterate" "[0 1 2 3 4]" "(into [] (take 5) (iterate inc 0))"]) + +# `reduce` itself honors `reduced`, so a reducing fn that returns `reduced` +# terminates even over an infinite seq. +(defspec "reduce / honors reduced" + ["reduced short-circuits inf" "105" + "(reduce (fn [a x] (if (> a 100) (reduced a) (+ a x))) 0 (range))"] + ["reduce take inf" "10" "(reduce + (take 5 (range)))"] + ["reduce no-init first elem" "6" "(reduce + [1 2 3])"] + ["reduce no-init single" "42" "(reduce + [42])"] + ["reduce empty calls f" "0" "(reduce + [])"] + ["reduce with-init" "16" "(reduce + 10 [1 2 3])"] + ["reduce reduced immediate" ":x" "(reduce (fn [a x] (reduced :x)) :init [1 2 3])"]) diff --git a/test/spec/transients-spec.janet b/test/spec/transients-spec.janet new file mode 100644 index 0000000..be67284 --- /dev/null +++ b/test/spec/transients-spec.janet @@ -0,0 +1,98 @@ +# Specification: transients (mutable scratch collections frozen by persistent!). +(use ../support/harness) + +(defspec "transient / vector" + ["conj! then persistent!" "[1 2]" "(persistent! (conj! (conj! (transient []) 1) 2))"] + ["reduce conj!" "[0 1 2 3 4]" "(persistent! (reduce conj! (transient []) (range 5)))"] + ["conj! many args" "[1 2 3]" "(persistent! (conj! (transient [1]) 2 3))"] + ["assoc! existing" "[1 9 3]" "(persistent! (assoc! (transient [1 2 3]) 1 9))"] + ["assoc! at count grows" "[1 2 3]" "(persistent! (assoc! (transient [1 2]) 2 3))"] + ["pop!" "[1 2]" "(persistent! (pop! (transient [1 2 3])))"] + ["from existing vector" "[1 2 3 4]" "(persistent! (conj! (transient [1 2 3]) 4))"] + ["count" "3" "(count (transient [1 2 3]))"] + ["nth" "2" "(nth (transient [1 2 3]) 1)"] + ["get" "2" "(get (transient [1 2 3]) 1)"] + ["persistent! is a vector" "true" "(vector? (persistent! (transient [1])))"] + ["transient? true" "true" "(transient? (transient []))"] + ["transient? false" "false" "(transient? [1 2])"]) + +(defspec "transient / map" + ["assoc! then persistent!" "{:a 1, :b 2}" "(persistent! (assoc! (assoc! (transient {}) :a 1) :b 2))"] + ["assoc! many" "{:a 1, :b 2}" "(persistent! (assoc! (transient {}) :a 1 :b 2))"] + ["dissoc!" "{:b 2}" "(persistent! (dissoc! (transient {:a 1 :b 2}) :a))"] + ["conj! map entry" "{:a 1}" "(persistent! (conj! (transient {}) [:a 1]))"] + ["from existing map" "{:a 1, :b 2}" "(persistent! (assoc! (transient {:a 1}) :b 2))"] + ["get" "1" "(get (transient {:a 1}) :a)"] + ["get missing default" ":x" "(get (transient {:a 1}) :z :x)"] + ["contains?" "true" "(contains? (transient {:a 1}) :a)"] + ["count" "2" "(count (transient {:a 1 :b 2}))"] + ["collection key by value" ":v" "(get (persistent! (assoc! (transient {}) [1 2] :v)) [1 2])"] + ["persistent! is a map" "true" "(map? (persistent! (transient {:a 1})))"] + ["reduce build" "{0 0, 1 1, 2 2}" "(persistent! (reduce (fn [t i] (assoc! t i i)) (transient {}) (range 3)))"]) + +(defspec "transient / set" + ["conj! dedups" "#{1 2 3}" "(persistent! (conj! (transient #{}) 1 2 2 3))"] + ["disj!" "#{1 3}" "(persistent! (disj! (transient #{1 2 3}) 2))"] + ["from existing set" "#{1 2 3}" "(persistent! (conj! (transient #{1 2}) 3))"] + ["contains?" "true" "(contains? (transient #{1 2}) 1)"] + ["count" "2" "(count (transient #{1 2}))"] + ["persistent! is a set" "true" "(set? (persistent! (transient #{1})))"] + ["map elements by value" "1" "(count (persistent! (conj! (transient #{}) {:a 1} (hash-map :a 1))))"]) + +(defspec "transient / immutability of source" + ["source vector unchanged" "true" + "(let [v [1 2 3] _ (persistent! (conj! (transient v) 4))] (= v [1 2 3]))"] + ["source map unchanged" "true" + "(let [m {:a 1} _ (persistent! (assoc! (transient m) :b 2))] (= m {:a 1}))"]) + +# Transients are invokable for read-only lookup, like their persistent forms. +(defspec "transient / invokable lookup" + ["vector index" "20" "((transient [10 20 30]) 1)"] + ["map key as fn" "7" "((transient {:x 7}) :x)"] + ["map key default" "99" "((transient {:x 7}) :z 99)"] + ["keyword on transient" "7" "(:x (transient {:x 7}))"] + ["set membership" "2" "((transient #{1 2 3}) 2)"] + ["set miss default" ":no" "((transient #{1 2 3}) 42 :no)"] + ["collection key" ":v" "((transient {[1 2] :v}) [1 2])"]) + +# assoc! (unlike assoc) accepts an odd arg count — a missing final value is nil. +# (A struct literal can't express an explicit nil value, so assert via contains?.) +(defspec "transient / assoc! odd args" + ["odd arg key present" "true" + "(contains? (persistent! (assoc! (transient {}) :a 1 :b)) :b)"] + ["odd arg value is nil" "true" + "(nil? (get (persistent! (assoc! (transient {}) :a 1 :b)) :b))"] + ["odd arg keeps prior" "1" + "(get (persistent! (assoc! (transient {}) :a 1 :b)) :a)"] + ["vector odd arg" "[9 nil]" + "(persistent! (apply assoc! (transient []) [0 9 1]))"]) + +# Using a transient after persistent! (or popping an empty one) throws. +(defspec "transient / invalidation" + ["conj! after persistent!" :throws + "(let [t (transient [])] (persistent! t) (conj! t 1))"] + ["assoc! after persistent!" :throws + "(let [t (transient {})] (persistent! t) (assoc! t :a 1))"] + ["persistent! twice" :throws + "(let [t (transient [])] (persistent! t) (persistent! t))"] + ["pop! empty" :throws "(pop! (transient []))"]) + +# The bang ops require an appropriate transient (Clojure throws otherwise); +# conj! has the special 0-/1-arg identity arities. +(defspec "transient / strictness" + ["conj! on persistent" :throws "(conj! [1 2] 3)"] + ["assoc! on persistent" :throws "(assoc! {:a 1} :b 2)"] + ["persistent! on vector" :throws "(persistent! [1 2])"] + ["persistent! on nil" :throws "(persistent! nil)"] + ["pop! on transient map" :throws "(pop! (transient {:a 1}))"] + ["dissoc! on tset" :throws "(dissoc! (transient #{1}) 1)"] + ["conj! map bad item" :throws "(conj! (transient {}) #{:a 1})"] + ["conj! no args" "[]" "(persistent! (conj!))"] + ["conj! identity" "[1 2]" "(conj! [1 2])"] + ["conj! map merges map" "{:a 1, :b 2}" "(persistent! (conj! (transient {:a 1}) {:b 2}))"]) + +(defspec "transient / assoc! bounds" + ["assoc! existing idx" "[1 9 3]" "(persistent! (assoc! (transient [1 2 3]) 1 9))"] + ["assoc! at count grows" "[1 2 3]" "(persistent! (assoc! (transient [1 2]) 2 3))"] + ["assoc! out of bounds" :throws "(assoc! (transient [0 1 2]) 4 4)"] + ["assoc! negative" :throws "(assoc! (transient []) -1 0)"]) diff --git a/test/spec/truthiness-spec.janet b/test/spec/truthiness-spec.janet new file mode 100644 index 0000000..a119e7a --- /dev/null +++ b/test/spec/truthiness-spec.janet @@ -0,0 +1,61 @@ +# Specification: truthiness & boolean logic. +# The core Clojure rule: ONLY nil and false are logically false; every other +# value — including 0, 0.0, "", and empty collections — is logically true. +(use ../support/harness) + +(defspec "truthiness / if (only nil & false are falsy)" + ["nil is falsy" ":f" "(if nil :t :f)"] + ["false is falsy" ":f" "(if false :t :f)"] + ["zero is truthy" ":t" "(if 0 :t :f)"] + ["zero float truthy" ":t" "(if 0.0 :t :f)"] + ["empty string truthy" ":t" "(if \"\" :t :f)"] + ["empty list truthy" ":t" "(if (list) :t :f)"] + ["empty vector truthy" ":t" "(if [] :t :f)"] + ["empty map truthy" ":t" "(if {} :t :f)"] + ["empty set truthy" ":t" "(if #{} :t :f)"] + ["number truthy" ":t" "(if 42 :t :f)"] + ["string truthy" ":t" "(if \"x\" :t :f)"] + ["keyword truthy" ":t" "(if :kw :t :f)"] + ["symbol truthy" ":t" "(if (quote abc) :t :f)"] + ["coll truthy" ":t" "(if [1 2] :t :f)"] + ["map truthy" ":t" "(if {:a 1} :t :f)"] + ["if no else -> nil" "nil" "(if false :t)"]) + +(defspec "truthiness / not" + ["not nil" "true" "(not nil)"] + ["not false" "true" "(not false)"] + ["not zero" "false" "(not 0)"] + ["not empty vector" "false" "(not [])"] + ["not empty string" "false" "(not \"\")"] + ["not number" "false" "(not 42)"] + ["not true" "false" "(not true)"]) + +(defspec "truthiness / and" + ["empty is true" "true" "(and)"] + ["single value" "5" "(and 5)"] + ["all truthy -> last" "3" "(and 1 2 3)"] + ["stops at false" "false" "(and 1 false 3)"] + ["stops at nil" "nil" "(and 1 nil 3)"] + ["false alone" "false" "(and false)"] + ["nil alone" "nil" "(and nil)"] + ["zero is truthy" "0" "(and 1 0)"]) + +(defspec "truthiness / or" + ["empty is nil" "nil" "(or)"] + ["first truthy" "1" "(or 1 2)"] + ["skips nil/false" "5" "(or nil false 5)"] + ["all falsy -> last" "false" "(or nil false)"] + ["nil chain -> false" "false" "(or nil nil nil false)"] + ["zero is truthy" "0" "(or 0 1)"] + ["false alone" "false" "(or false)"]) + +(defspec "truthiness / if-not & boolean" + ["if-not false" ":yes" "(if-not false :yes :no)"] + ["if-not truthy" ":no" "(if-not 0 :yes :no)"] + ["when-not nil" "1" "(when-not nil 1)"] + ["when-not truthy" "nil" "(when-not 5 1)"] + ["boolean of nil" "false" "(boolean nil)"] + ["boolean of false" "false" "(boolean false)"] + ["boolean of 0" "true" "(boolean 0)"] + ["boolean of value" "true" "(boolean :x)"] + ["true?/false?" "true" "(and (true? true) (false? false) (not (true? 1)))"]) diff --git a/test/spec/vectors-spec.janet b/test/spec/vectors-spec.janet new file mode 100644 index 0000000..90572d8 --- /dev/null +++ b/test/spec/vectors-spec.janet @@ -0,0 +1,54 @@ +# Specification: vectors (persistent, indexed). +(use ../support/harness) + +(defspec "vector / construct & predicate" + ["literal" "[1 2 3]" "[1 2 3]"] + ["vector" "[1 2 3]" "(vector 1 2 3)"] + ["vector zero args" "[]" "(vector)"] + ["vec from list" "[1 2 3]" "(vec (list 1 2 3))"] + ["vec from range" "[0 1 2]" "(vec (range 3))"] + ["vec of map yields entries" "[[:a 1]]" "(vec {:a 1})"] + ["vector? true" "true" "(vector? [1])"] + ["vector? false on list" "false" "(vector? (list 1))"] + ["vector = list elts" "true" "(= [1 2 3] (list 1 2 3))"]) + +(defspec "vector / access" + ["nth" ":b" "(nth [:a :b :c] 1)"] + ["nth default" ":x" "(nth [:a] 5 :x)"] + ["get by index" ":b" "(get [:a :b] 1)"] + ["get out of range nil" "nil" "(get [:a] 5)"] + ["get default" ":x" "(get [:a] 5 :x)"] + ["first" "1" "(first [1 2 3])"] + ["last" "3" "(last [1 2 3])"] + ["peek is last" "3" "(peek [1 2 3])"] + ["count" "3" "(count [1 2 3])"] + ["contains? index" "true" "(contains? [:a :b] 1)"] + ["contains? past end" "false" "(contains? [:a] 3)"] + ["vector as fn" ":b" "([:a :b :c] 1)"] + # An IFn collection held in a binding (not just a literal) must dispatch as IFn, + # not as a host call: applies to vectors, keywords, and meta-bearing vectors. + ["vector-in-local as fn" "20" "(let [v [10 20 30]] (v 1))"] + ["keyword-in-local as fn" "7" "(let [k :a] (k {:a 7}))"] + ["meta vector as fn" "10" "((with-meta [10 20] {:k 1}) 0)"]) + +(defspec "vector / update (persistent)" + ["conj appends" "[1 2 3]" "(conj [1 2] 3)"] + ["conj many" "[1 2 3 4]" "(conj [1 2] 3 4)"] + ["assoc index" "[1 9 3]" "(assoc [1 2 3] 1 9)"] + ["assoc at count appends" "[1 2 3]" "(assoc [1 2] 2 3)"] + ["update" "[1 3 3]" "(update [1 2 3] 1 inc)"] + ["pop drops last" "[1 2]" "(pop [1 2 3])"] + ["subvec start end" "[2 3]" "(subvec [1 2 3 4] 1 3)"] + ["subvec to end" "[3 4]" "(subvec [1 2 3 4] 2)"] + ["mapv" "[2 3 4]" "(mapv inc [1 2 3])"] + ["filterv" "[2 4]" "(filterv even? [1 2 3 4])"]) + +(defspec "vector / immutability & nesting" + ["conj does not mutate" "true" "(let [v [1 2] w (conj v 3)] (and (= v [1 2]) (= w [1 2 3])))"] + ["assoc does not mutate" "true" "(let [v [1 2 3] w (assoc v 0 9)] (and (= v [1 2 3]) (= w [9 2 3])))"] + ["get-in" "2" "(get-in [[1 2] [3 4]] [0 1])"] + ["assoc-in" "[[1 9]]" "(assoc-in [[1 2]] [0 1] 9)"] + ["update-in" "[[1 3]]" "(update-in [[1 2]] [0 1] inc)"] + ["large vector nth" "1500" "(nth (vec (range 2000)) 1500)"] + ["large vector count" "2000" "(count (vec (range 2000)))"] + ["large conj immutable" "true" "(let [v (vec (range 1000)) w (conj v :end)] (and (= 1000 (count v)) (= 1001 (count w))))"]) diff --git a/test/support/clojure_test.clj b/test/support/clojure_test.clj new file mode 100644 index 0000000..dfab28d --- /dev/null +++ b/test/support/clojure_test.clj @@ -0,0 +1,118 @@ +;; Minimal `clojure.test` + `clojure.core-test.portability` shims. +;; +;; These exist solely so Jolt can load the external clojure-test-suite +;; (https://github.com/lread/clojure-test-suite, EPL) — 240 per-function +;; `.cljc` files written against `clojure.test`. They are NOT a full +;; clojure.test: just enough surface (deftest/is/testing/are + the suite's +;; portability helpers) to run the suite and tally pass/fail/error. +;; +;; Loaded by test/integration/clojure-test-suite-test.janet, which pre-loads +;; this file so the suite's `(require [clojure.test ...])` finds it already +;; populated (Jolt's require is a no-op for already-loaded namespaces). + +(ns clojure.test) + +;; --- result accumulator (plain atoms; no dynamic vars needed) ------------- + +(def jolt-report (atom {:pass 0 :fail 0 :error 0 :fails []})) +(def jolt-ctx (atom [])) ;; stack of `testing` context strings +(def registry (atom [])) ;; deftest fns defined since last reset + +(defn reset-report! [] + (reset! jolt-report {:pass 0 :fail 0 :error 0 :fails []}) + (reset! jolt-ctx []) + (reset! registry [])) + +(defn- ctx-str [] (apply str (interpose " " @jolt-ctx))) + +(defn inc-pass! [] (swap! jolt-report update :pass inc)) + +(defn fail! [form] + (swap! jolt-report + (fn [r] (-> r (update :fail inc) + (update :fails conj (str (ctx-str) " FAIL: " form)))))) + +(defn err! [form] + (swap! jolt-report + (fn [r] (-> r (update :error inc) + (update :fails conj (str (ctx-str) " ERROR: " form)))))) + +(defn n-pass [] (:pass @jolt-report)) +(defn n-fail [] (:fail @jolt-report)) +(defn n-error [] (:error @jolt-report)) +(defn failures [] (:fails @jolt-report)) + +;; --- assertion macros ------------------------------------------------------ + +;; `(is form)` / `(is form msg)` — the optional msg is absorbed and ignored. +(defmacro is [form & _] + `(try + (if ~form + (clojure.test/inc-pass!) + (clojure.test/fail! (pr-str '~form))) + (catch :default e# + (clojure.test/err! (str (pr-str '~form) " threw"))))) + +(defmacro testing [s & body] + `(do + (swap! clojure.test/jolt-ctx conj ~s) + (try + (do ~@body) + (finally (swap! clojure.test/jolt-ctx pop))))) + +(defmacro deftest [name & body] + `(do + (def ~name (fn [] ~@body)) + (swap! clojure.test/registry conj ~name) + ~name)) + +;; `(are [bindings] expr & data)` — substitute each row of `data` into the +;; template and assert via `is`. Expands to a `do` of let+is forms. +(defmacro are [argv expr & data] + (let [n (count argv) + rows (partition n data)] + `(do ~@(map (fn [row] + `(let [~@(interleave argv row)] + (clojure.test/is ~expr))) + rows)))) + +;; Run every deftest registered since the last reset, isolating crashes. +(defn run-registered [] + (doseq [t @registry] + (try (t) (catch :default e (clojure.test/err! (str "deftest crashed: " (clojure.core/ex-message e)))))) + nil) + +;; clojure.test entry points the suite may call — no-ops; the Janet runner +;; drives execution via run-registered instead. +(defn run-tests [& _] nil) +(defn run-test [& _] nil) +(defn test-var [& _] nil) + + +;; --- clojure.core-test.portability ---------------------------------------- + +(ns clojure.core-test.portability) + +;; Gate a test on whether its target var exists in this dialect. Jolt only +;; implements a subset of clojure.core, so unimplemented fns get skipped +;; cleanly rather than erroring. +;; Skips silently (no stdout) so the worker's stdout stays just the count line; +;; an unimplemented var simply contributes no assertions. +(defmacro when-var-exists [var-sym & body] + (if (resolve var-sym) + `(do ~@body) + nil)) + +;; `(thrown? body)` — true iff evaluating body throws. The suite always uses +;; the single-arg (no exception-class) form via this portability helper. +(defmacro thrown? [& body] + `(try (do ~@body false) (catch :default e# true))) + +(defn big-int? [n] + (and (integer? n) (not (int? n)))) + +(defn lazy-seq? [x] + ;; Jolt has no public LazySeq type test; approximate with seq?-of-non-vector. + (and (seq? x) (not (vector? x)))) + +(defn sleep [ms] nil) diff --git a/test/support/harness.janet b/test/support/harness.janet new file mode 100644 index 0000000..483e79d --- /dev/null +++ b/test/support/harness.janet @@ -0,0 +1,94 @@ +# Shared test harness for Jolt. +# +# Two complementary styles: +# +# defspec — data-driven behavioral tables, for spec/ and integration batteries. +# Each case is ["label" expected actual] where `expected` and `actual` are +# Clojure source strings. Equality is checked with Jolt's own `=`, so it is +# representation-agnostic (a vector result compares equal to a vector +# literal regardless of the underlying Janet type). Use the :throws sentinel +# in the `expected` position to assert that `actual` raises an error. +# +# (defspec "clojure.core / seq" +# ["first of vector" "1" "(first [1 2 3])"] +# ["rest is a seq" "(2 3)" "(rest [1 2 3])"] +# ["nth out of range" :throws "(nth [1] 5)"]) +# +# jeval / expect= / expect-throws — assertion helpers for white-box unit/ tests +# that probe a single component and want Janet-level assertions. +# +# A failing suite prints every failing behavior, then raises — so `jpm test` +# reports a non-zero exit and the offending behaviors are visible. + +(use ../../src/jolt/api) + +# Every case still gets a fully-isolated context, but via api/fork (~2 ms deep +# copy of a snapshotted ctx) instead of a fresh init (~50 ms) — the same +# behavior, ~25x faster across the ~1500 spec cases. Built lazily so harness +# importers that never eval (or that only use run-spec) pay it once at most. +(var- base-snap nil) +(defn fresh-ctx + "A fresh, fully-isolated interpret-mode context (cheap fork of one shared init)." + [] + (when (nil? base-snap) (set base-snap (snapshot (init)))) + (fork base-snap)) + +(defn jeval + "Evaluate a Clojure source string in a fresh context, normalizing persistent + vectors/lists to Janet tuples so results compare with `deep=`/tuple literals." + [s] + (normalize-pvecs (eval-string (fresh-ctx) s))) + +(defn- show [s] + (let [r (protect (eval-string (fresh-ctx) s))] + (if (= (r 0) true) + (string/format "%q" (normalize-pvecs (r 1))) + (string "")))) + +(defn run-spec + "Run a data-driven behavioral suite. See `defspec`." + [suite cases] + (var pass 0) + (def fails @[]) + (each case cases + (def label (in case 0)) + (def expected (in case 1)) + (def actual (in case 2)) + (if (= expected :throws) + (let [r (protect (eval-string (fresh-ctx) actual))] + (if (= (r 0) false) + (++ pass) + (array/push fails [label "expected an error, got a value"]))) + (let [r (protect (eval-string (fresh-ctx) (string "(= " expected " " actual ")")))] + (cond + (not= (r 0) true) (array/push fails [label (string "errored: " (r 1))]) + (= (r 1) true) (++ pass) + (array/push fails [label (string "want " expected ", got " (show actual))]))))) + (printf " %s: %d/%d" suite pass (length cases)) + (flush) + (each [l m] fails (printf " FAIL [%s] %s" l m)) + (when (> (length fails) 0) + (error (string suite ": " (length fails) " failing behavior(s)"))) + pass) + +(defmacro defspec + "Define and immediately run a behavioral suite of [label expected actual] cases." + [suite & cases] + ~(,run-spec ,suite [,;cases])) + +# --- white-box assertion helpers (unit tests) --- + +(defn expect= + "Assert that evaluating Clojure `s` yields `expected` (a Janet value, compared + with deep= after normalizing persistent collections to tuples)." + [expected s] + (let [got (jeval s)] + (assert (deep= expected got) + (string "expected " (string/format "%q" expected) + ", got " (string/format "%q" got) " for: " s)))) + +(defn expect-throws + "Assert that evaluating Clojure `s` raises an error." + [s] + (let [r (protect (eval-string (fresh-ctx) s))] + (assert (= (r 0) false) (string "expected an error for: " s)))) diff --git a/test/support/lazy-eval.janet b/test/support/lazy-eval.janet new file mode 100644 index 0000000..f656ce6 --- /dev/null +++ b/test/support/lazy-eval.janet @@ -0,0 +1,16 @@ +# Worker: evaluate a Clojure equality check in a fresh Jolt ctx and print +# @@RESULT true or @@RESULT false. Used by lazy-infinite-test under a wall-clock +# deadline so infinite-seq hangs are caught as test failures. +(use ../../src/jolt/api) +(use ../../src/jolt/reader) + +(def expected (get (dyn :args) 1)) +(def actual (get (dyn :args) 2)) + +(when (and expected actual) + (def ctx (init {})) + (def prog (string "(= " expected " " actual ")")) + (def [ok val] (protect (eval-string ctx prog))) + (if ok + (printf "@@RESULT %q" val) + (printf "@@ERROR %q" val))) diff --git a/test/unit/compile-fallback-test.janet b/test/unit/compile-fallback-test.janet new file mode 100644 index 0000000..1248128 --- /dev/null +++ b/test/unit/compile-fallback-test.janet @@ -0,0 +1,41 @@ +# Stage 2 Task 3: the compile path's interpreter fallback is DELIBERATE-ONLY. +# +# compile-and-eval used to wrap the compile step in a blanket protect — ANY +# failure (including a genuine compiler bug) silently fell back to the +# interpreter, hiding the bug behind a correct-looking result. Now only the +# analyzer's deliberate punt signal ("jolt/uncompilable: …", raised for the +# curated stateful/letrec set) may fall back; any other compile-step error +# propagates. Verified here by stubbing jolt.analyzer/analyze. + +(use ../../src/jolt/types) +(use ../../src/jolt/api) +(use ../../src/jolt/reader) +(import ../../src/jolt/backend :as backend) + +(def ctx (init)) + +# 1. A deliberate punt (letfn needs letrec IR) falls back and evaluates correctly. +(assert (= 3 (backend/compile-and-eval ctx (parse-string "(letfn [(f [n] (+ n 1))] (f 2))"))) + "deliberate uncompilable punt falls back to the interpreter") + +(assert (backend/analyzer-built? ctx) "analyzer built") +(def analyze-var (ns-find (ctx-find-ns ctx "jolt.analyzer") "analyze")) +(def real-analyze (var-get analyze-var)) + +# 2. A NON-punt compile error must propagate — even though the interpreter could +# evaluate the form fine, it must NOT be silently used (that hides compiler bugs). +(var-set analyze-var (fn [ctx form] (error "boom: simulated compiler bug"))) +(def r (protect (backend/compile-and-eval ctx (parse-string "(+ 1 2)")))) +(assert (not (r 0)) "non-uncompilable compile error must propagate, not silently interpret") +(assert (string/find "boom" (string (r 1))) "the original error is surfaced") + +# 3. The punt marker is the one sanctioned fallback channel. +(var-set analyze-var (fn [ctx form] (error "jolt/uncompilable: stubbed"))) +(assert (= 3 (backend/compile-and-eval ctx (parse-string "(+ 1 2)"))) + "uncompilable punt falls back to the interpreter") + +# Restore the real analyzer and confirm the pipeline still works. +(var-set analyze-var real-analyze) +(assert (= 7 (backend/compile-and-eval ctx (parse-string "(+ 3 4)"))) "restored analyzer compiles") + +(print "All compile-fallback tests passed!") diff --git a/test/unit/compiler-test.janet b/test/unit/compiler-test.janet new file mode 100644 index 0000000..788e3ba --- /dev/null +++ b/test/unit/compiler-test.janet @@ -0,0 +1,335 @@ +# Jolt Compiler Tests — Phase 2 +# Tests for source-to-source Clojure→Janet compilation. +# Core ops: const, do, if, def, fn, let, invoke +# Phase 2 adds: symbol classification with binding awareness + +(use ../../src/jolt/compiler) +(use ../../src/jolt/reader) + +(defn compile-str [s] + (let [form (parse-string s)] + (compile-form form))) + +# ============================================================ +# 1. Literals (const) +# ============================================================ +(print "1: literal constants...") +(assert (= "42" (compile-str "42")) "integer") +(assert (= "nil" (compile-str "nil")) "nil") +(assert (= "true" (compile-str "true")) "true") +(assert (= "false" (compile-str "false")) "false") +(assert (= "\"hello\"" (compile-str "\"hello\"")) "string") +(assert (= ":foo" (compile-str ":foo")) "keyword") +(print " passed") + +# ============================================================ +# 2. do +# ============================================================ +(print "2: do...") +(assert (= "(do 1 2)" (compile-str "(do 1 2)")) "do two exprs") +(assert (= "(do 42)" (compile-str "(do 42)")) "do single expr") +(assert (= "(do (core-inc 1) (core-inc 2))" (compile-str "(do (inc 1) (inc 2))")) "do with fn calls") +(print " passed") + +# ============================================================ +# 3. if +# ============================================================ +(print "3: if...") +(assert (= "(if true 1 2)" (compile-str "(if true 1 2)")) "if three-arg") +(assert (= "(if false 1 nil)" (compile-str "(if false 1)")) "if two-arg") +(print " passed") + +# ============================================================ +# 4. def +# ============================================================ +(print "4: def...") +(assert (= "(def x 42)" (compile-str "(def x 42)")) "def constant") +(assert (= "(def f (fn [x] (core-inc x)))" (compile-str "(def f (fn* [x] (inc x)))")) "def with fn") +(print " passed") + +# ============================================================ +# 5. fn +# ============================================================ +(print "5: fn...") +(assert (= "(fn [x] (core-inc x))" (compile-str "(fn* [x] (inc x))")) "fn single arity") +(assert (= "(fn [] 42)" (compile-str "(fn* [] 42)")) "fn no args") +(assert (= "(fn [x] (do (core-print x) (core-inc x)))" + (compile-str "(fn* [x] (print x) (inc x))")) "fn multi-expr body") +(print " passed") + +# ============================================================ +# 6. let +# ============================================================ +(print "6: let...") +(assert (= "(let [x 1] (core-inc x))" (compile-str "(let* [x 1] (inc x))")) "let single binding") +(assert (= "(let [x 1 y 2] (+ x y))" (compile-str "(let* [x 1 y 2] (+ x y))")) "let two bindings") +(assert (= "(let [x (core-inc 1)] (core-inc x))" (compile-str "(let* [x (inc 1)] (inc x))")) "let with fn in binding") +(print " passed") + +# ============================================================ +# 7. invoke (function calls) +# ============================================================ +(print "7: invoke...") +(assert (= "(core-inc 1)" (compile-str "(inc 1)")) "inc call") +(assert (= "(+ 1 2)" (compile-str "(+ 1 2)")) "+ call") +(assert (= "(+ (core-inc 1) 2)" (compile-str "(+ (inc 1) 2)")) "nested calls") +(assert (= "(core-map core-inc (core-vec 1 2 3))" + (compile-str "(map inc (vec 1 2 3))")) "multi-arg call") +(print " passed") + +# ============================================================ +# 8. Local symbol classification (Phase 2) +# ============================================================ +(print "8: local classification...") +# Shadowing: local inc should NOT be rewritten to core-inc +(assert (= "(let [inc 5] (inc inc))" + (compile-str "(let* [inc 5] (inc inc))")) "local shadows core fn") +# fn params are locals, not core symbols +(assert (= "(fn [map] (core-vec map))" + (compile-str "(fn* [map] (vec map))")) "fn param shadows core map") +# nested let with shadowing +(assert (= "(let [x 1] (let [inc x] (inc x)))" + (compile-str "(let* [x 1] (let* [inc x] (inc x)))")) "nested let local") +(print " passed") + +(print "\nAll compiler Phase 2 tests passed!") + +# ============================================================ +# 9. Compile-and-eval round-trip (Phase 3) +# ============================================================ +(print "9: compile-and-eval...") +(use ../../src/jolt/core) # need core fns in scope for eval + +(defn compile-eval-str [s] + (let [form (parse-string s)] + (compile-and-eval form nil))) + +(assert (= 42 (compile-eval-str "42")) "eval literal") +(assert (= 2 (compile-eval-str "(inc 1)")) "eval inc") +(assert (= 3 (compile-eval-str "(+ 1 2)")) "eval +") +(assert (= 6 (compile-eval-str "(+ (inc 1) (inc 3))")) "eval nested") +(assert (= 2 (compile-eval-str "(do 1 2)")) "eval do") +(assert (= 1 (compile-eval-str "(if true 1 2)")) "eval if true") +(assert (= 2 (compile-eval-str "(if false 1 2)")) "eval if false") +(assert (= 2 (compile-eval-str "(let* [x 1] (inc x))")) "eval let") +(let [f (compile-eval-str "(fn* [x] (inc x))")] + (assert (function? f) "eval fn returns fn") + (assert (= 6 (f 5)) "eval fn works")) +(print " passed") + +# ============================================================ +# 10. Compile flag in context (Phase 3) +# ============================================================ +(print "10: compile flag...") +(use ../../src/jolt/api) + +# Without compile flag +(let [ctx (init)] + (assert (= 2 (eval-string ctx "(inc 1)")) "no-compile flag: inc works")) + +# With compile flag: pure expressions use compile-and-eval +(let [ctx (init {:compile? true})] + (assert (= 2 (eval-string ctx "(inc 1)")) "compile flag: inc works") + (assert (= 3 (eval-string ctx "(+ 1 2)")) "compile flag: + works") + (assert (= 6 (eval-string ctx "(+ (inc 1) (inc 3))")) "compile flag: nested works")) + +# With compile flag: stateful forms fall back to interpreter +(let [ctx (init {:compile? true})] + (eval-string ctx "(def foo 99)") + (assert (= 99 (eval-string ctx "foo")) "compile flag: def works")) + +(print " passed") + +(print "\nAll compiler Phase 3 tests passed!") + +# ============================================================ +# 11. Macro expansion (Phase 4) +# ============================================================ +(print "11: macro expansion...") +(use ../../src/jolt/api) + +(let [ctx (init {:compile? true})] + # defn expands via compiler, produces Janet def + (eval-string ctx "(defn square [n] (* n n))") + (assert (= 25 (eval-string ctx "(square 5)")) "defn via compiler") + + # when macro + (assert (= 42 (eval-string ctx "(when true 42)")) "when true") + (assert (= nil (eval-string ctx "(when false 42)")) "when false") + + # let macro + (assert (= 30 (eval-string ctx "(let [x 10 y 20] (+ x y))")) "let macro") + + # fn macro + (assert (= 49 (eval-string ctx "((fn [x] (* x x)) 7)")) "fn macro") + + # and/or + (assert (= 3 (eval-string ctx "(and 1 2 3)")) "and") + (assert (= 99 (eval-string ctx "(or nil false 99)")) "or")) + +(print " passed") + +(print "\nAll compiler Phase 4 tests passed!") + +# ============================================================ +# 12. throw, try, loop*/recur (Phase 5) +# ============================================================ +(print "12: throw/try/loop...") +(use ../../src/jolt/api) + +(let [ctx (init {:compile? true})] + # throw/catch via compiler + (assert (= "caught" + (eval-string ctx "(try (throw 42) (catch Exception e \"caught\"))")) + "try/catch") + + # try without catch returns body + (assert (= 1 (eval-string ctx "(try 1 (catch Exception e 2))")) "try no throw") + + # throw in nested context + (assert (= "ok" + (eval-string ctx "(try (do (throw 99) 1) (catch Exception e \"ok\"))")) + "throw in do") + + # loop*/recur + (assert (= 3 (eval-string ctx "(loop* [x 0] (if (< x 3) (recur (inc x)) x))")) + "loop count up") + (assert (= 3 + (eval-string ctx "(loop* [i 0 acc 0] (if (< i 3) (recur (inc i) (+ acc i)) acc))")) + "loop with acc")) + +(print " passed") + +(print "\nAll compiler Phase 5 tests passed!") + +# ============================================================ +# 13. defn/def integration (Phase 0 fix) +# ============================================================ +(print "13: defn/def integration...") +(use ../../src/jolt/api) + +(let [ctx (init {:compile? true})] + # defn produces a resolvable var + (eval-string ctx "(defn identity-fn [x] x)") + (assert (= 1 (eval-string ctx "(identity-fn 1)")) "defn works") + (let [f (eval-string ctx "identity-fn")] + (assert (function? f) "bare defn symbol returns fn")) + + # def produces a resolvable var + (eval-string ctx "(def answer 42)") + (assert (= 42 (eval-string ctx "answer")) "def bare symbol") + (assert (= 43 (eval-string ctx "(inc answer)")) "def in call")) + +(print " passed") + +(print "\nAll compiler tests passed!") + +# ============================================================ +# 14. Phase 1: ns accessors + ns form extensions +# ============================================================ +(print "14: ns accessors...") +(use ../../src/jolt/api) + +(let [ctx (init)] + (eval-string ctx "(ns mytest.core)") + (def ns-list (eval-string ctx "(all-ns)")) + (assert (> (length ns-list) 0) "all-ns returns namespaces") + # create-ns + (eval-string ctx "(create-ns mytest.extra)") + (def all (eval-string ctx "(all-ns)")) + (assert (> (length all) 1) "create-ns adds namespace")) + +(print " passed") + +(print "15: ns form extensions...") +(let [ctx (init)] + # ns with :require + :refer + (eval-string ctx "(ns test.ns-ext (:require [clojure.core :refer [inc +]]))") + (assert (= 2 (eval-string ctx "(inc 1)")) "refer inc works")) + +(print " passed") + +(print "\nAll Phase 1 tests passed!") + +# ============================================================ +# 17. Phase 3: Var system completion +# ============================================================ +(print "17: var system...") +(use ../../src/jolt/api) + +(let [ctx (init)] + (eval-string ctx "(def x-var-test 42)") + (assert (= true (eval-string ctx "(var? (var x-var-test))")) "var?") + (eval-string ctx "(def y-var-test 99)") + (assert (= 99 (eval-string ctx "(var-get (var y-var-test))")) "var-get") + (eval-string ctx "(def z-var-test 10)") + (assert (= 20 (eval-string ctx "(do (var-set (var z-var-test) 20) (var-get (var z-var-test)))")) "var-set") + (eval-string ctx "(def a-var-test 1)") + (assert (= 2 (eval-string ctx "(do (alter-var-root (var a-var-test) inc) (var-get (var a-var-test)))")) "alter-var-root") + (eval-string ctx "(def fv-var-test :found)") + (assert (= :found (eval-string ctx "(var-get (find-var 'fv-var-test))")) "find-var") + (eval-string ctx "(intern (the-ns) 'iv-var-test 77)") + (assert (= 77 (eval-string ctx "iv-var-test")) "intern") + (eval-string ctx "(def ^:dynamic *dv* 1)") + (assert (= 99 (eval-string ctx "(binding [*dv* 99] *dv*)")) "dynamic binding")) +(print " passed") + +# ============================================================ +# 18. Phase 3: Var metadata +# ============================================================ +(print "18: var metadata...") +(let [ctx (init)] + (eval-string ctx "(def mvar 42)") + (eval-string ctx "(alter-meta! (var mvar) assoc :doc \"the answer\")") + (assert (= "the answer" (eval-string ctx "(:doc (meta (var mvar)))")) "alter-meta!") + (eval-string ctx "(reset-meta! (var mvar) {:a 1})") + (assert (= 1 (eval-string ctx "(:a (meta (var mvar)))")) "reset-meta!")) +(print " passed") + +(print "\nAll Phase 3 tests passed!") + +# ============================================================ +# 19. Phase 4: deftype +# ============================================================ +(print "19: deftype...") +(use ../../src/jolt/api) + +(let [ctx (init)] + (eval-string ctx "(deftype Point [x y])") + (assert (not (nil? (eval-string ctx "(Point. 3 4)"))) "deftype constructs") + (assert (= 3 (eval-string ctx "(. (Point. 3 4) x)")) ".x access") + (assert (= 4 (eval-string ctx "(. (Point. 3 4) y)")) ".y access") + (assert (= 10 (eval-string ctx "(let [p (Point. 3 4)] (set! (.-x p) 10) (. p x))")) "set! field") + (assert (= true (eval-string ctx "(instance? Point (Point. 1 2))")) "instance?") + (assert (= false (eval-string ctx "(instance? Point {:x 1})")) "instance? false") + (assert (= 5 (eval-string ctx "(. (->Point 5 6) x)")) "arrow factory")) +(print " passed") + +# ============================================================ +# 20. Phase 4: defrecord +# ============================================================ +(print "20: defrecord...") +(let [ctx (init)] + (eval-string ctx "(defrecord Person [name age])") + (assert (not (nil? (eval-string ctx "(Person. \"Alice\" 30)"))) "record constructs") + (assert (= true (eval-string ctx "(map? (Person. \"Alice\" 30))")) "record is map?") + (assert (= "Alice" (eval-string ctx "(:name (Person. \"Alice\" 30))")) "keyword access") + (assert (= 30 (eval-string ctx "(get (Person. \"Alice\" 30) :age)")) "get access") + (assert (= "Alice" (eval-string ctx "(. (Person. \"Alice\" 30) name)")) ".name access") + (assert (= 30 (eval-string ctx "(. (Person. \"Alice\" 30) age)")) ".age access") + (assert (= 2 (eval-string ctx "(count (Person. \"Alice\" 30))")) "count") + (assert (= "Bob" (eval-string ctx "(:name (->Person \"Bob\" 25))")) "arrow factory")) + +(print " passed") + +# ============================================================ +# 21. Phase 4: record equality +# ============================================================ +(print "21: record equality...") +(let [ctx (init)] + (eval-string ctx "(defrecord Point3D [x y z])") + (assert (= true (eval-string ctx "(= (Point3D. 1 2 3) (Point3D. 1 2 3))")) "same values") + (assert (= false (eval-string ctx "(= (Point3D. 1 2 3) (Point3D. 4 5 6))")) "different values")) +(print " passed") + +(print "\nAll Phase 4 tests passed!") diff --git a/test/unit/eval-test.janet b/test/unit/eval-test.janet new file mode 100644 index 0000000..2e566ce --- /dev/null +++ b/test/unit/eval-test.janet @@ -0,0 +1,14 @@ +(use ../../src/jolt/api) +(defn ct-eval [ctx s] (normalize-pvecs (eval-string ctx s))) +(print "Eval Tests") + +(print "1: eval literal...") +(let [ctx (init)] + (assert (= 42 (ct-eval ctx "(eval 42)")) "eval literal") + (assert (= 3 (ct-eval ctx "(eval '(+ 1 2))")) "eval quoted form") + (assert (= 3 (ct-eval ctx "(eval (eval '(+ 1 2)))")) "eval nested") + (ct-eval ctx "(eval '(def ex 99))") + (assert (= 99 (ct-eval ctx "ex")) "eval defines var")) +(print " ok") + +(print "\nAll Eval tests passed!") diff --git a/test/unit/evaluator-test.janet b/test/unit/evaluator-test.janet new file mode 100644 index 0000000..a93aa1b --- /dev/null +++ b/test/unit/evaluator-test.janet @@ -0,0 +1,154 @@ +(use ../../src/jolt/evaluator) +(use ../../src/jolt/types) +(use ../../src/jolt/reader) +(use ../../src/jolt/api) + +# Helper: create a Jolt symbol +(defn sym [name] + (let [slash (string/find "/" name)] + (if slash + {:jolt/type :symbol :ns (string/slice name 0 slash) + :name (string/slice name (+ slash 1))} + {:jolt/type :symbol :ns nil :name name}))) + +# Helper: parse and eval +(defn eval-str [s] + (let [ctx (make-ctx) + form (parse-string s)] + (eval-form ctx @{} form))) + +(print "1: literals...") +(assert (= 42 (eval-str "42")) "integer") +(assert (= "hello" (eval-str "\"hello\"")) "string") +(assert (= true (eval-str "true")) "true") +(assert (= false (eval-str "false")) "false") +(assert (= nil (eval-str "nil")) "nil") +(print " passed") + +(print "2: quote...") +(assert (deep= (sym "x") (eval-str "'x")) "quote returns symbol") +(assert (deep= @[1 2 3] (eval-str "'(1 2 3)")) "quote list") +(print " passed") + +(print "3: do...") +(assert (= 2 (eval-str "(do 1 2)")) "do returns last") +(print " passed") + +(print "4: if...") +(assert (= 1 (eval-str "(if true 1 2)")) "if true") +(assert (= 2 (eval-str "(if false 1 2)")) "if false") +(assert (= :b (eval-str "(if nil :a :b)")) "if nil = false") +(assert (= nil (eval-str "(if false 1)")) "if with no else") +(print " passed") + +(print "5: def...") +(assert (= 42 (eval-str "(do (def x 42) x)")) "def in do") +(print " passed") + +(print "6: fn*...") +(let [f (eval-str "(fn* [x] (inc x))")] + (assert (function? f) "fn* returns function") + (assert (= 42 (f 41)) "fn* fn works")) +# nested function +(let [f (eval-str "(fn* [x] (inc (inc x)))")] + (assert (= 43 (f 41)) "nested inc")) +(print " passed") + +(print "7: let*...") +(assert (= 2 (eval-str "(let* [x 1 y 2] y)")) "let* binds") +(assert (= 3 (eval-str "(let* [x 1] (inc (inc x)))")) "let* with expr") +(print " passed") + +(print "8: loop*/recur...") +(assert (= 5 (eval-str "(loop* [x 0] (if (< x 5) (recur (inc x)) x))")) + "loop counts up") +(assert (= 10 (eval-str "(loop* [i 0 acc 0] (if (< i 5) (recur (inc i) (+ acc i)) acc))")) + "loop with multiple bindings") +(print " passed") + +(print "9: recur in fn*...") +(let [countdown (eval-str "(fn* [n] (if (< n 1) 0 (recur (dec n))))")] + (assert (= 0 (countdown 5)) "recur in fn")) +(print " passed") + +(print "10: throw/try/catch/finally...") +# throw + catch +(let [result (eval-str "(try (throw \"boom\") (catch Exception e \"caught\"))")] + (assert (= "caught" result) "catch catches throw")) + +# try with finally — body returns, finally runs +(let [result (eval-str "(try 1 (finally 2))")] + (assert (= 1 result) "try returns body even with finally")) + +# try/catch/finally — catch returns, finally runs +(let [result (eval-str "(try (throw \"err\") (catch Exception e \"handled\") (finally :cleanup))")] + (assert (= "handled" result) "catch + finally returns catch value")) +(print " passed") + +(print "11: set!...") +# set! on a var +(assert (= 99 (eval-str "(do (def x 1) (set! x 99) x)")) "set! on var") +# set! re-evaluates +(assert (= 3 (eval-str "(do (def a 1) (def b 2) (set! a (+ a b)) a)")) "set! with expression") +(print " passed") + +(print "12: var...") +# (var x) returns the var itself, not its value +(let [v (eval-str "(do (def x 42) (var x))")] + (assert (var? v) "(var x) returns a var") + (assert (= 42 (var-get v)) "var holds value")) +(print " passed") + +(print "13: locking...") +# locking is a no-op in single-threaded Janet — just executes body +(assert (= 42 (eval-str "(locking :lock 42)")) "locking returns body result") +(print " passed") + +(print "14: instance?...") +# instance? checks type +(assert (= true (eval-str "(instance? Number 42)")) "instance? Number matches number") +(assert (= false (eval-str "(instance? Number \"hello\")")) "instance? Number doesn't match string") +(print " passed") + +(print "15: defmulti/defmethod...") +# defmulti/defmethod are overlay macros now (Stage 2 jolt-eaa), so this needs the +# full env (init loads the overlay + installs the *-setup fns), not a bare make-ctx. +(let [ctx (init)] + (eval-form ctx @{} (parse-string "(defmulti my-dispatch (fn* [x] (x :type)))")) + (eval-form ctx @{} (parse-string "(defmethod my-dispatch :foo [_] :got-foo)")) + (eval-form ctx @{} (parse-string "(defmethod my-dispatch :bar [_] :got-bar)")) + (assert (= :got-foo (eval-form ctx @{} (parse-string "(my-dispatch {:type :foo})"))) "defmethod :foo dispatches") + (assert (= :got-bar (eval-form ctx @{} (parse-string "(my-dispatch {:type :bar})"))) "defmethod :bar dispatches")) +(print " passed") + +(print "16: deftype...") +# deftype is an overlay macro now (Stage 2 jolt-eaa) — needs the full env (init). +(let [ctx (init) + _ (eval-form ctx @{} (parse-string "(deftype Point [x y])")) + _ (eval-form ctx @{} (parse-string "(def p (Point. 10 20))")) + p-val (eval-form ctx @{} (parse-string "p")) + x-val (eval-form ctx @{} (parse-string "(p :x)")) + y-val (eval-form ctx @{} (parse-string "(p :y)")) + result [x-val y-val]] + (printf " p-val: %q" p-val) + (printf " x-val: %q, y-val: %q" x-val y-val) + (printf " result: %q" result) + (assert (deep= [10 20] result) "deftype creates tagged instances with fields")) +(print " passed") + +(print "17: defmacro...") +# define a macro using defmacro special form +# init loads clojure.core so `list` is available +(let [ctx (init) + _ (eval-form ctx @{} (parse-string "(defmacro my-when [test body] (list 'if test body nil))")) + result (eval-form ctx @{} (parse-string "(my-when true 2)"))] + (assert (= 2 result) "defmacro defines callable macro")) +# verify the var is marked :macro +(let [ctx (make-ctx) + _ (eval-form ctx @{} (parse-string "(defmacro m [x] (list 'quote x))")) + v (resolve-var ctx @{} (parse-string "m"))] + (assert v "macro var exists") + (assert (v :macro) "macro var has :macro true")) +(print " passed") + +(print "\nAll evaluator tests passed!") diff --git a/test/unit/interop-test.janet b/test/unit/interop-test.janet new file mode 100644 index 0000000..a06d8f3 --- /dev/null +++ b/test/unit/interop-test.janet @@ -0,0 +1,46 @@ +(use ../../src/jolt/api) +(defn ct-eval [ctx s] (normalize-pvecs (eval-string ctx s))) +(print "Janet Interop Tests") + +(print "1: field access on tables...") +(let [ctx (init)] + (ct-eval ctx "(def t {:a 1 :b 2})") + (assert (= 1 (ct-eval ctx "(. t :a)")) ". field access table") + (assert (= 2 (ct-eval ctx "(. t :b)")) ". field access table 2") + (assert (= nil (ct-eval ctx "(. t :z)")) ". field access missing key")) +(print " ok") + +(print "2: field access on structs...") +(let [ctx (init)] + (ct-eval ctx "(def s {:x 10 :y 20})") + (assert (= 10 (ct-eval ctx "(. s :x)")) ". field access struct") + (assert (= 20 (ct-eval ctx "(. s :y)")) ". field access struct 2")) +(print " ok") + +(print "3: method calls on tables...") +(let [ctx (init)] + (ct-eval ctx "(def obj {:greet (fn [self name] (str \"Hello \" name))})") + (assert (= "Hello Alice" (ct-eval ctx "(. obj greet \"Alice\")")) ". method call on table")) +(print " ok") + +(print "4: field access via .- reader sugar...") +(let [ctx (init)] + (ct-eval ctx "(def t {:x 42 :len 5})") + (assert (= 42 (ct-eval ctx "(.-x t)")) ".-x reader sugar") + (assert (= 5 (ct-eval ctx "(.-len t)")) ".-len reader sugar")) +(print " ok") + +(print "5: . field access still works on deftypes...") +(let [ctx (init)] + (ct-eval ctx "(deftype Point [x y])") + (assert (= 3 (ct-eval ctx "(. (Point. 3 4) x)")) ". field access deftype")) +(print " ok") + +(print "6: method call with multiple args...") +(let [ctx (init)] + (ct-eval ctx "(def calc {:add (fn [_ a b] (+ a b)) :mul (fn [_ a b] (* a b))})") + (assert (= 7 (ct-eval ctx "(. calc add 3 4)")) ". method add") + (assert (= 12 (ct-eval ctx "(. calc mul 3 4)")) ". method mul")) +(print " ok") + +(print "\nAll Janet Interop tests passed!") diff --git a/test/unit/lazy-seq-test.janet b/test/unit/lazy-seq-test.janet new file mode 100644 index 0000000..4911642 --- /dev/null +++ b/test/unit/lazy-seq-test.janet @@ -0,0 +1,56 @@ +(use ../../src/jolt/api) +(defn ct-eval [ctx s] (normalize-pvecs (eval-string ctx s))) +(print "LazySeq Tests") + +(print "1: lazy-seq from list...") +(let [ctx (init)] + (assert (= true (ct-eval ctx "(= [1 2 3] (take 10 (lazy-seq [1 2 3])))")) "lazy-seq list") + (assert (= true (ct-eval ctx "(= 3 (count (lazy-seq [1 2 3])))")) "count lazy-seq")) +(print " ok") + +(print "2: lazy-cat concatenation...") +(let [ctx (init)] + (assert (= true (ct-eval ctx "(= [1 2 3 4] (take 10 (lazy-cat [1 2] [3 4])))")) "lazy-cat concat") + (assert (= true (ct-eval ctx "(= 4 (count (lazy-cat [1 2] [3 4])))")) "lazy-cat count")) +(print " ok") + +(print "3: first/rest on lazy-seqs...") +(let [ctx (init)] + (assert (= true (ct-eval ctx "(= 1 (first (lazy-seq [1 2 3])))")) "first lazy") + (assert (= true (ct-eval ctx "(= 2 (first (rest (lazy-seq [1 2 3]))))")) "first rest lazy")) +(print " ok") + +(print "4: drop/nth on lazy-seqs...") +(let [ctx (init)] + (assert (= true (ct-eval ctx "(= [3 4 5] (take 10 (drop 2 (lazy-seq [1 2 3 4 5]))))")) "drop 2 take 10") + (assert (= true (ct-eval ctx "(= 3 (nth (lazy-seq [1 2 3 4 5]) 2))")) "nth lazy")) +(print " ok") + +(print "5: concat on lazy-seqs...") +(let [ctx (init)] + (assert (= true (ct-eval ctx "(= 5 (count (concat (lazy-seq [1 2]) (lazy-seq [3 4 5]))))")) "concat lazy")) +(print " ok") + +(print "6: reverse/sort on lazy-seqs...") +(let [ctx (init)] + (assert (= true (ct-eval ctx "(= [3 2 1] (reverse (lazy-seq [1 2 3])))")) "reverse lazy") + (assert (= true (ct-eval ctx "(= [1 2 3] (sort (lazy-seq [3 1 2])))")) "sort lazy")) +(print " ok") + +(print "7: distinct on lazy-seqs...") +(let [ctx (init)] + (assert (= true (ct-eval ctx "(= [1 2 3] (distinct (lazy-seq [1 2 1 3 2])))")) "distinct lazy")) +(print " ok") + +(print "8: fib-seq (deferred — eager core-map needs lazy upgrade)...") +(let [ctx (init)] + (print " The cell-by-cell lazy-seq architecture is correct. concat, take,") + (print " drop, nth, first, rest all work with self-referencing patterns.") + (print " core-map still eagerly realizes all lazy-seq arguments, which") + (print " loops on infinite sequences. Making core-map return a lazy") + (print " result would complete the self-referencing lazy-seq story.") + (print " When fixed: (def fib-seq (lazy-cat [0 1] (map + (rest fib-seq) fib-seq)))") + (print " → (take 10 fib-seq) = [0 1 1 2 3 5 8 13 21 34]")) +(print " ok (deferred — core-map needs lazy upgrade)") + +(print "\nAll LazySeq tests passed!") diff --git a/test/unit/macro-test.janet b/test/unit/macro-test.janet new file mode 100644 index 0000000..7444a06 --- /dev/null +++ b/test/unit/macro-test.janet @@ -0,0 +1,129 @@ +(use ../../src/jolt/reader) +(use ../../src/jolt/types) +(use ../../src/jolt/evaluator) + +# Helper: create a Jolt symbol +(defn sym [name] + (let [slash (string/find "/" name)] + (if slash + {:jolt/type :symbol :ns (string/slice name 0 slash) + :name (string/slice name (+ slash 1))} + {:jolt/type :symbol :ns nil :name name}))) + +# Helper: parse and eval +(defn eval-str [s] + (let [ctx (make-ctx) + form (parse-string s)] + (eval-form ctx @{} form))) + +# ============================================================ +# 1. syntax-quote — literals pass through +# ============================================================ +(print "1: syntax-quote literals...") +(assert (= 42 (eval-str "`42")) "syntax-quote number") +(assert (= "hello" (eval-str "`\"hello\"")) "syntax-quote string") +(assert (= :foo (eval-str "`:foo")) "syntax-quote keyword") +(assert (= nil (eval-str "`nil")) "syntax-quote nil") +(assert (= true (eval-str "`true")) "syntax-quote true") +(assert (= false (eval-str "`false")) "syntax-quote false") +(print " passed") + +# ============================================================ +# 2. syntax-quote — qualify symbols +# ============================================================ +(print "2: syntax-quote qualifies symbols...") +# In the 'user namespace, `x → user/x +(let [form (eval-str "`x")] + (assert (deep= {:jolt/type :symbol :ns "user" :name "x"} form) + "qualifies bare symbol to current ns")) + +# Already qualified symbols stay as-is +(let [form (eval-str "`foo/bar")] + (assert (deep= {:jolt/type :symbol :ns "foo" :name "bar"} form) + "qualified symbol unchanged")) +(print " passed") + +# ============================================================ +# 3. syntax-quote — lists: qualify symbols, literal items as-is +# ============================================================ +(print "3: syntax-quote lists...") +# `(+ 1 2) → (user/+ 1 2) — but 1 and 2 are numbers, stay as-is +(let [form (eval-str "`(+ 1 2)")] + (assert (array? form) "syntax-quote list is array") + (assert (= 3 (length form)) "has 3 elements") + (assert (deep= {:jolt/type :symbol :ns "user" :name "+"} (in form 0)) + "operator qualified") + (assert (= 1 (in form 1)) "number stays") + (assert (= 2 (in form 2)) "number stays")) +(print " passed") + +# ============================================================ +# 4. unquote inside syntax-quote +# ============================================================ +(print "4: unquote...") +# `~x inside (let* [x 10] ...) → 10 +(let [form (eval-str "(let* [x 10] `~x)")] + (assert (= 10 form) "unquote evaluates")) +# `(~x) produces a list containing x +(let [form2 (eval-str "(let* [x 10] `(~x))")] + (assert (deep= @[10] form2) "unquote in list")) + +# `(+ ~x ~y) with x=1 y=2 → (+ 1 2) +(let [form (eval-str "(let* [x 1 y 2] `(+ ~x ~y))")] + (assert (array? form) "result is list") + (assert (= 1 (in form 1)) "first unquoted value") + (assert (= 2 (in form 2)) "second unquoted value")) +(print " passed") + +# ============================================================ +# 5. unquote-splicing inside syntax-quote +# ============================================================ +(print "5: unquote-splicing...") +# `[1 2 ~@xs] with xs = (3 4) → [1 2 3 4] +(let [form (eval-str "(let* [xs '(3 4)] `[1 2 ~@xs])")] + (assert (tuple? form) "result is vector") + (assert (= 4 (length form)) "spliced items merged") + (assert (deep= [1 2 3 4] form) "correct items")) + +# `(1 ~@xs) with xs = (2 3) → (1 2 3) +(let [form (eval-str "(let* [xs '(2 3)] `(1 ~@xs))")] + (assert (array? form) "result is list") + (assert (= 3 (length form)) "spliced into list") + (assert (deep= @[1 2 3] form) "correct items")) +(print " passed") + +# ============================================================ +# 6. Macro function application +# ============================================================ +(print "6: macro application...") + +# Define a simple macro: (my-when test body) → (if test body nil) +(def ctx (make-ctx)) +(def macro-fn-form (parse-string "(fn* [test body] (if test body nil))")) +(def macro-fn (eval-form ctx @{} macro-fn-form)) +# intern it in user namespace with string key +(let [ns (ctx-find-ns ctx "user")] + (ns-intern ns "my-when" macro-fn) + (put (ns-find ns "my-when") :macro true)) + +# (my-when true 42) should expand to (if true 42 nil), evaluating to 42 +(let [form (parse-string "(my-when true 42)")] + (assert (= 42 (eval-form ctx @{} form)) "macro application returns correct value")) + +# (my-when false 99) should expand to (if false 99 nil), evaluating to nil +(let [form (parse-string "(my-when false 99)")] + (assert (= nil (eval-form ctx @{} form)) "macro returns nil when false")) +(print " passed") + +# ============================================================ +# 7. Nested syntax-quote +# ============================================================ +(print "7: nested syntax-quote...") +# ``x → (syntax-quote user/x) +(let [form (eval-str "``x")] + (assert (array? form) "nested syntax-quote produces list") + (assert (deep= {:jolt/type :symbol :ns nil :name "syntax-quote"} (in form 0)) + "outer is syntax-quote")) +(print " passed") + +(print "\nAll macro tests passed!") diff --git a/test/unit/persistent-map-test.janet b/test/unit/persistent-map-test.janet new file mode 100644 index 0000000..9ccba03 --- /dev/null +++ b/test/unit/persistent-map-test.janet @@ -0,0 +1,75 @@ +# Phase 2: PersistentHashMap Tests +# Uses Clojure = (core-=) for PHM-aware comparison + +(use ../../src/jolt/api) + +(defn ct-eval [ctx s] (normalize-pvecs (eval-string ctx s))) + +# Helper: compare via Clojure = which handles PHM +(defn clj= [ctx a b] + (eval-string ctx (string "(= " a " " b ")"))) + +# ============================================================ +# 1. Basic hash-map construction and access +# ============================================================ +(print "1: hash-map construction...") +(let [ctx (init)] + (def m1 (ct-eval ctx "(hash-map :a 1)")) + (assert (not (nil? m1)) "hash-map returns non-nil") + (assert (= true (ct-eval ctx "(map? (hash-map :a 1))")) "map? returns true for PHM") + (assert (= true (ct-eval ctx "(= (hash-map :a 1) {:a 1})")) "PHM = struct via Clojure =") + + (assert (= 0 (ct-eval ctx "(count (hash-map))")) "count empty") + (assert (= 2 (ct-eval ctx "(count (hash-map :a 1 :b 2))")) "count two") + (assert (= 1 (ct-eval ctx "(get (hash-map :a 1 :b 2) :a)")) "get present") + (assert (= nil (ct-eval ctx "(get (hash-map :a 1) :z)")) "get missing")) +(print " passed") + +# ============================================================ +# 2. assoc and dissoc +# ============================================================ +(print "2: assoc/dissoc...") +(let [ctx (init)] + (assert (= true (ct-eval ctx "(= (assoc (hash-map :a 1) :b 2) (hash-map :a 1 :b 2))")) "assoc add") + (assert (= true (ct-eval ctx "(= (assoc (hash-map :a 1) :a 99) (hash-map :a 99))")) "assoc replace") + (assert (= true (ct-eval ctx "(= (dissoc (hash-map :a 1 :b 2) :a) (hash-map :b 2))")) "dissoc") + (assert (= true (ct-eval ctx "(contains? (hash-map :a 1) :a)")) "contains? true") + (assert (= false (ct-eval ctx "(contains? (hash-map :a 1) :z)")) "contains? false")) +(print " passed") + +# ============================================================ +# 3. keys, vals, merge +# ============================================================ +(print "3: keys/vals/merge...") +(let [ctx (init)] + (assert (= 2 (ct-eval ctx "(count (keys (hash-map :a 1 :b 2)))")) "keys count") + (assert (= 2 (ct-eval ctx "(count (vals (hash-map :a 1 :b 2)))")) "vals count") + (assert (= true (ct-eval ctx "(= (merge (hash-map :a 1) (hash-map :b 2)) (hash-map :a 1 :b 2))")) "merge")) + +(print " passed") + +# ============================================================ +# 4. Empty and seq +# ============================================================ +(print "4: empty? and seq...") +(let [ctx (init)] + (assert (= true (ct-eval ctx "(empty? (hash-map))")) "empty? true") + (assert (= false (ct-eval ctx "(empty? (hash-map :a 1))")) "empty? false") + (assert (= 1 (ct-eval ctx "(count (seq (hash-map :a 1)))")) "seq count")) +(print " passed") + +# ============================================================ +# 5. Larger maps +# ============================================================ +(print "5: larger maps...") +(let [ctx (init)] + (eval-string ctx " + (def big-map + (reduce (fn [m i] (assoc m (keyword (str \"k\" i)) i)) + (hash-map) + (range 100)))") + (assert (= 100 (ct-eval ctx "(count big-map)")) "count 100") + (assert (= 42 (ct-eval ctx "(get big-map :k42)")) "get k42")) +(print " passed") + +(print "\nAll PersistentHashMap tests passed!") diff --git a/test/unit/reader-test.janet b/test/unit/reader-test.janet new file mode 100644 index 0000000..87a1565 --- /dev/null +++ b/test/unit/reader-test.janet @@ -0,0 +1,148 @@ +(use ../../src/jolt/reader) + +# Helper: create a symbol +(defn sym [name] + (let [slash (string/find "/" name)] + (if slash + {:jolt/type :symbol + :ns (string/slice name 0 slash) + :name (string/slice name (+ slash 1))} + {:jolt/type :symbol + :ns nil + :name name}))) + +# Symbols +(assert (deep= (sym "foo") (parse-string "foo")) + "bare symbol") +(assert (deep= (sym "foo/bar") (parse-string "foo/bar")) + "namespaced symbol") +(assert (deep= (sym "+") (parse-string "+")) + "operator symbol") +(assert (deep= (sym "->foo") (parse-string "->foo")) + "arrow symbol") + +# Keywords +(assert (= :foo (parse-string ":foo")) + "bare keyword") +(assert (= :foo/bar (parse-string "::foo/bar")) + "auto-resolved keyword") +(assert (= :foo/bar (parse-string ":foo/bar")) + "namespaced keyword") + +# Numbers +(assert (= 1 (parse-string "1")) + "integer") +(assert (= -42 (parse-string "-42")) + "negative integer") +(assert (= 3.14 (parse-string "3.14")) + "float") + +# Strings +(assert (= "hello" (parse-string "\"hello\"")) + "simple string") + +# Nil, booleans +(assert (= nil (parse-string "nil")) + "nil") +(assert (= true (parse-string "true")) + "true") +(assert (= false (parse-string "false")) + "false") + +# Lists → Janet arrays (to distinguish from vectors) +(assert (array? (parse-string "(1 2 3)")) + "list produces array") +(assert (deep= @[1 2 3] (parse-string "(1 2 3)")) + "simple list") + +# Vectors → Janet tuples +(assert (tuple? (parse-string "[1 2 3]")) + "vector produces tuple") +(assert (deep= [1 2 3] (parse-string "[1 2 3]")) + "simple vector") + +# Maps → Janet structs +(let [m (parse-string "{:a 1 :b 2}")] + (assert (struct? m) "map is struct") + (assert (= 1 (m :a)) "map key lookup")) + +# Sets → tagged with :jolt/set +(let [form (parse-string "#{1 2 3}")] + (assert (struct? form) "set is struct") + (assert (= :jolt/set (form :jolt/type)) "set type tag")) + +# Quote and shorthand +(assert (deep= @[(sym "quote") (sym "x")] (parse-string "'x")) + "quote shorthand") +(assert (deep= @[(sym "syntax-quote") (sym "x")] (parse-string "`x")) + "syntax-quote") +(assert (deep= @[(sym "unquote") (sym "x")] (parse-string "~x")) + "unquote") +(assert (deep= @[(sym "unquote-splicing") (sym "x")] (parse-string "~@x")) + "unquote-splicing") +(assert (deep= @[(sym "deref") (sym "x")] (parse-string "@x")) + "deref shorthand") + +# Metadata: a keyword/symbol/string hint on a symbol attaches to the symbol's +# :meta and keeps it a bare symbol (so type hints are transparent everywhere). +(let [form (parse-string "^:meta x")] + (assert (and (struct? form) (= :symbol (form :jolt/type))) "meta-hinted symbol stays a symbol") + (assert (= "x" (form :name)) "symbol name preserved") + (assert (= true (get (form :meta) :meta)) "keyword hint -> {kw true}")) +(let [form (parse-string "^String s")] + (assert (= "s" (form :name)) "type-hinted symbol name preserved") + (assert (= "String" (get (form :meta) :tag)) "symbol hint -> {:tag name}")) +# Map metadata on a symbol still uses a runtime with-meta form. +(let [form (parse-string "^{:doc \"d\"} y")] + (assert (and (array? form) (struct? (first form)) (= "with-meta" ((first form) :name))) + "map metadata -> with-meta form")) + +# Comments (skip to end of line) +(assert (= 42 (parse-string "; comment\n42")) + "comment then form") + +# Discard #_ +(assert (= 42 (parse-string "#_ (ignored 1 2) 42")) + "discard skips next form") + +# Anonymous function #() +(let [form (parse-string "#(+ %1 %2)")] + (assert (array? form) "fn form is array") + (assert (deep= (sym "fn*") (in form 0)) "first element is fn*")) + +# Nested forms +(let [form (parse-string "(+ 1 (* 2 3))")] + (assert (array? form) "outer list is array") + (assert (deep= (sym "+") (in form 0)) "+ is first") + (assert (= 1 (in form 1)) "1 is second") + (assert (array? (in form 2)) "nested list is array")) + +# Multiple forms: parse-next +(let [[form1 rest-str] (parse-next "(1 2) [3 4]")] + (assert (deep= @[1 2] form1) "first form is list") + (let [[form2 _] (parse-next rest-str)] + (assert (deep= [3 4] form2) "second form is vector"))) + +# Reader conditional — resolves :clj branch at read time +(assert (= 1 (parse-string "#?(:clj 1 :cljs 2)")) + "#?(:clj) picks :clj branch") +(assert (= nil (parse-string "#?(:cljs 999)")) + "#?(:cljs) returns nil on CLJ") +(assert (= 42 (parse-string "#?(:clj 42)")) + "#?(:clj) with single branch") +(assert (deep= (sym "clj-only") (parse-string "#?(:clj clj-only :cljs cljs-only)")) + "#?(:clj) picks :clj symbol") +# Nested inside a list — :clj branch is evaluated at read time +(assert (deep= @[(sym "+") 1 3] (parse-string "(+ 1 #?(:clj 3 :cljs 4))")) + "#? inside list picks :clj") + +# Characters — the reader now produces char values {:jolt/type :jolt/char :ch N} +(let [form (parse-string "\\newline")] + (assert (struct? form) "char is struct") + (assert (= :jolt/char (form :jolt/type)) "char type") + (assert (= 10 (form :ch)) "newline codepoint")) + +(let [form (parse-string "\\a")] + (assert (= 97 (form :ch)) "simple char codepoint")) + +(print "All reader tests passed!") diff --git a/test/unit/types-test.janet b/test/unit/types-test.janet new file mode 100644 index 0000000..4acd864 --- /dev/null +++ b/test/unit/types-test.janet @@ -0,0 +1,133 @@ +(use ../../src/jolt/types) + +# ============================================================ +# Var tests +# ============================================================ + +# make-var +(let [v (make-var 'x 42)] + (assert (var? v) "var? returns true") + (assert (= 42 (var-get v)) "var-get returns root binding") + (assert (deep= {:name 'x} (var-meta v)) "var-meta returns metadata") + (assert (deep= 'x (var-name v)) "var-name returns name symbol")) + +# var without init value +(let [v (make-var 'y)] + (assert (var? v) "unbound var is still a var")) + +# dynamic var +(let [v (make-var '*dyn* 1 {:dynamic true})] + (assert (var-dynamic? v) "var-dynamic? true") + (assert (not (var-macro? v)) "var-macro? false for dynamic var")) + +# macro var +(let [v (make-var 'when nil {:macro true})] + (assert (var-macro? v) "var-macro? true")) + +# var-set — set root binding +(let [v (make-var 'x 1)] + (var-set v 99) + (assert (= 99 (var-get v)) "var-set changes root binding")) + +# alter-var-root +(let [v (make-var 'c 0)] + (alter-var-root v inc) + (assert (= 1 (var-get v)) "alter-var-root applies fn")) + +# with-meta — returns new var with updated meta +(let [v (make-var 'x 42) + v2 (with-meta v {:private true})] + (assert (deep= {:name 'x :private true} (var-meta v2)) "with-meta merges meta") + (assert (= 42 (var-get v2)) "with-meta preserves root binding")) + +# generation counter — bumps on every root change (substrate for direct-link +# staleness detection and redefinition-aware dispatch caches) +(let [v (make-var 'g 1)] + (assert (= 0 (v :gen)) "fresh var starts at generation 0") + (bind-root v 2) + (assert (= 1 (v :gen)) "bind-root bumps generation") + (var-set v 3) + (assert (= 2 (v :gen)) "var-set (root) bumps generation") + (alter-var-root v inc) + (assert (= 3 (v :gen)) "alter-var-root bumps generation") + (assert (= 4 (var-get v)) "value still tracks through gen bumps")) +(let [v (make-var 'g 1) + v2 (with-meta v {:doc "x"})] + (assert (= (v :gen) (v2 :gen)) "with-meta carries generation")) + +# var with namespace +(let [ns (make-ns 'my.ns) + v (make-var 'my.ns/x 1 {:ns ns})] + (assert (= ns (var-ns v)) "var-ns returns namespace")) + +# ============================================================ +# Namespace tests +# ============================================================ + +(let [ns (make-ns 'foo.bar)] + (assert (ns? ns) "ns? returns true") + (assert (deep= 'foo.bar (ns-name ns)) "ns-name returns name symbol") + (assert (table? (ns-map ns)) "ns-map returns table") + (assert (= 0 (length (ns-map ns))) "empty namespace has no mappings")) + +# ns-intern +(let [ns (make-ns 'test.ns) + v (ns-intern ns 'x 42)] + (assert (var? v) "ns-intern returns a var") + (assert (= 42 (var-get v)) "ns-intern sets root binding") + # check ns-find returns the same var (by reference, not deep=) + (assert (= v (ns-find ns 'x)) "ns-find returns interned var")) + +# ns-intern without value +(let [ns (make-ns 'test.ns) + v (ns-intern ns 'y)] + (assert (var? v) "ns-intern without value creates unbound var")) + +# ns-unmap +(let [ns (make-ns 'test.ns) + _ (ns-intern ns 'x 1) + _ (ns-unmap ns 'x)] + (assert (nil? (ns-find ns 'x)) "ns-unmap removes mapping")) + +# ns-resolve — own ns +(let [ns (make-ns 'test.ns) + v (ns-intern ns 'x 10)] + (assert (= v (ns-resolve ns 'x)) "ns-resolve finds var in own ns")) + +# ns-import +(let [ns (make-ns 'test.ns)] + (ns-import ns 'Date 'java.util.Date) + (assert (= 'java.util.Date (ns-import-lookup ns 'Date)) "ns-import-lookup returns import")) + +# ============================================================ +# Context tests +# ============================================================ + +(let [ctx (make-ctx)] + (assert (ctx? ctx) "ctx? returns true")) + +# ctx with initial namespaces +(let [ctx (make-ctx {:namespaces {"user" {"x" 1 "y" 2}}})] + (let [ns (ctx-find-ns ctx "user")] + (assert (ns? ns) "ctx-find-ns returns namespace for user") + (let [v (ns-find ns "x")] + (assert (var? v) "user/x is a var") + (assert (= 1 (var-get v)) "user/x has correct value")))) + +# ctx-find-ns creates ns if not present +(let [ctx (make-ctx) + ns (ctx-find-ns ctx "foo")] + (assert (ns? ns) "ctx-find-ns creates namespace on demand")) + +# ============================================================ +# Dynamic binding support (thread-local bindings table) +# ============================================================ + +# push-thread-bindings / pop-thread-bindings +(let [v (make-var '*dyn* 0 {:dynamic true})] + (push-thread-bindings @{v 100}) + (assert (= 100 (var-get v)) "push-thread-bindings sets binding") + (pop-thread-bindings) + (assert (= 0 (var-get v)) "pop-thread-bindings restores root")) + +(print "All types tests passed!") diff --git a/tools/clojuredocs-export.json b/tools/clojuredocs-export.json deleted file mode 100644 index 22b2e80..0000000 --- a/tools/clojuredocs-export.json +++ /dev/null @@ -1 +0,0 @@ -{"created-at":1781050155961,"description":"ClojureDocs Data Export","vars":[{"ns":"clojure.core","name":"def","type":"var","see-alsos":[{"created-at":1289040035000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"defn","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b15"},{"created-at":1289040039000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"fn","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b16"},{"created-at":1289040051000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"defmacro","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b17"},{"created-at":1289040055000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"defmulti","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b18"},{"created-at":1421928720188,"author":{"login":"Gitward","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8510849?v=3"},"to-var":{"ns":"clojure.core","name":"defonce","library-url":"https://github.com/clojure/clojure"},"_id":"54c0e910e4b0e2ac61831cce"},{"created-at":1426949770053,"author":{"login":"ryoakg","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/23413?v=3"},"to-var":{"ns":"clojure.core","name":"ns-unmap","library-url":"https://github.com/clojure/clojure"},"_id":"550d868ae4b056ca16cfecf8"}],"examples":[{"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":"user=> (def my-val 5)\n#'user/my-val\n\nuser=> my-val\n5","created-at":1289040027000,"updated-at":1411962925119,"_id":"542692cfc026201cdc326e95"},{"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"editors":[],"body":"user=> (def my-function (fn [x] (* x x x)))\n#'user/my-function\nuser=> (my-function 4)\n64","created-at":1289040110000,"updated-at":1289040110000,"_id":"542692cfc026201cdc326e96"},{"author":{"login":"puredanger","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/89c8afd032c7b3473f67c9b00d3acd5a?r=PG&default=identicon"},"editors":[{"login":"puredanger","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/89c8afd032c7b3473f67c9b00d3acd5a?r=PG&default=identicon"},{"login":"pjlegato","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/4ce55cfd8b3ae2f63f5ecbc8fc1c05d4?r=PG&default=identicon"},{"login":"pjlegato","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/4ce55cfd8b3ae2f63f5ecbc8fc1c05d4?r=PG&default=identicon"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":";; This is an example of setting a docstring during a def.\n;; (Note that the clojure.repl namespace which contains the\n;; doc function is not loaded by default in Emacs' SLIME mode.)\n\nuser> (def ted-nugent \"The nuge rocks\" 123)\n#'user/ted-nugent\nuser> (doc ted-nugent)\n-------------------------\nuser/ted-nugent\n The nuge rocks\nuser> ted-nugent\n123\n","created-at":1300830366000,"updated-at":1411962895678,"_id":"542692cfc026201cdc326e97"},{"author":{"login":"jamesqiu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bc1268deaa7f2e78fe2b5ea76e6481d8?r=PG&default=identicon"},"editors":[{"login":"jamesqiu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bc1268deaa7f2e78fe2b5ea76e6481d8?r=PG&default=identicon"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":";; give function another name\nuser=> (def sys-map map)\n\n;; give macro another name\nuser=> (def #^{:macro true} sys-loop #'loop)","created-at":1313515810000,"updated-at":1411962917894,"_id":"542692cfc026201cdc326e9b"},{"updated-at":1518778836326,"created-at":1518778836326,"author":{"login":"ibercode","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/31028993?v=4"},"body":";;Assign a Function to a Variable\n\n(def say-hello\n (fn [name]\n (str \"Hello \" name)))\n\n(say-hello \"World\")\n;;\"Hello World\"\n\n\n;;the same but using an anonymous function\n(def say-hello\n #(str \"Hello \" %))\n\n(say-hello \"World\")\n;;\"Hello World\"\n\n\n;;anonymous function using two arguments\n(def hello-doc #(str \"Hello \" %1 %2))\n\n(hello-doc \"Dr.\" \"House\")\n;;\"Hello Dr.House\"\n\n","_id":"5a86b9d4e4b0316c0f44f8c6"},{"updated-at":1640101185494,"created-at":1640101185494,"author":{"login":"deadghost","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1156996?v=4"},"body":";; Private var\n(def ^:private foobar\n \"I am the docstring.\"\n \"I am the value.\")\n","_id":"61c1f541e4b0b1e3652d758c"},{"updated-at":1654772119878,"created-at":1654772119878,"author":{"login":"clojer","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/107184681?v=4"},"body":"\n;; function checks: variable = 9 or not\nuser=> (def ?9 #(= % 9))\n#'user/?9\nuser=> (?9 9)\ntrue\nuser=> (?9 5)\nfalse","_id":"62a1d197e4b0b1e3652d75fa"},{"updated-at":1712575657726,"created-at":1712575657726,"author":{"login":"siddharthjain-in","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/6537820?v=4"},"body":"; add a doc-string to your def variable\n(def my-var \"this is doc string for my var\" \"hello\")\n\n; add a doc-string using meta key `:doc` \n(def ^{:doc \"this is doc string for my var\"} my-var \"hello\") ","_id":"6613d4a969fbcc0c226174b9"}],"notes":null,"arglists":[],"doc":"Creates and interns or locates a global var with the name of symbol and a\nnamespace of the value of the current namespace (*ns*). See\nhttp://clojure.org/special_forms for more information.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/def"},{"ns":"clojure.core","name":"if","type":"var","see-alsos":[{"created-at":1302510837000,"author":{"login":"Havvy","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e799a79441c7543be48562403411cd13?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"cond","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e12"},{"created-at":1311797747000,"author":{"login":"OnesimusUnbound","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2fa4c391db0d2d1744cc2cd0d787dd3d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"when","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e13"},{"created-at":1334293230000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.core","name":"if-let","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e14"},{"created-at":1340541172000,"author":{"login":"jhulten","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/b15299ac3f0bf5347d14a1232338b1cd?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"if-not","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e15"},{"created-at":1545243343724,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/109629?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"when-let","ns":"clojure.core"},"_id":"5c1a8acfe4b0ca44402ef5ed"}],"examples":[{"author":{"login":"Victor","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bc41ebab54cc0e0fbe99d753876d45ce?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":"(defn is-small? [number]\n (if (< number 100) \"yes\" \"no\"))\n\nuser=> (is-small? 50)\n\"yes\"\n\nuser=> (is-small? 500)\n\"no\"","created-at":1288222254000,"updated-at":1288871229000,"_id":"542692cfc026201cdc326e9d"},{"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":";; Be aware that the only two values considered \"logical false\" in Clojure\n;; are nil and false, where Clojure's \"false\" is the Java value Boolean/FALSE\n;; under the hood. Everything else is \"logical true\". Particularly surprising\n;; may be that the Java Object with class Boolean and value (Boolean. false) is\n;; considered logical true.\n\n;; This notion of logical true and logical false holds for at least the following\n;; conditional statements in Clojure: if, cond, when, if-let, when-let.\n;; It also applies to functions like filter, remove, and others that use\n;; these conditional statements in their implementation.\n\n;; nil and false are logical false\nuser=> (if nil \"logical true\" \"logical false\")\n\"logical false\"\nuser=> (if false \"logical true\" \"logical false\")\n\"logical false\"\n;; Boolean/FALSE is how Clojure's \"false\" is represented internally.\nuser=> (if Boolean/FALSE \"logical true\" \"logical false\")\n\"logical false\"\n\n;; Everything else that is the value of the condition, including numbers (even 0),\n;; characters, strings (even the empty string), vectors, maps, _and_ a freshly\n;; constructed Boolean class object (Boolean. false), is logical true.\n\nuser=> (if 0 \"logical true\" \"logical false\")\n\"logical true\"\n;; A vector containing nil is not the same as nil.\nuser=> (if [nil] \"logical true\" \"logical false\")\n\"logical true\"\nuser=> (if (first [nil]) \"logical true\" \"logical false\")\n\"logical false\"\n\n;; Bad idea even in Java. See below for more details.\nuser=> (if (Boolean. false) \"logical true\" \"logical false\")\n\"logical true\"\n\n;; Java documentation itself warns:\n;; Note: It is rarely appropriate to use this constructor. Unless a new instance\n;; is required, the static factory valueOf(boolean) is generally a better choice.\n;; It is likely to yield significantly better space and time performance.\n\n;; (boolean x) converts a value to a primitive boolean. It converts nil, false,\n;; and (Boolean. false) to primitive false.\nuser=> (if (boolean (Boolean. false)) \"logical true\" \"logical false\")\n\"logical false\"\n\n;; (Boolean/valueOf ) is similar:\nuser=> (if (Boolean/valueOf (Boolean. false)) \"logical true\" \"logical false\")\n\"logical false\"\n","created-at":1334293223000,"updated-at":1422027142917,"_id":"542692d6c026201cdc3270cc"},{"updated-at":1603184553184,"created-at":1603184553184,"author":{"login":"agodde","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/18694682?v=4"},"body":";; if vs. when\n\n;; An if without an else branch...\nuser=> (if true \"then branch\")\n\"then branch\"\nuser=> (if false \"then branch\")\nnil\n\n;; ...is the same as when.\nuser=> (when true \"then branch\")\n\"then branch\"\nuser=> (when false \"then branch\")\nnil\n\n;; Use of when instead of if is recommended in cases where you do not need the else branch.","_id":"5f8ea7a9e4b0b1e3652d73e6"}],"notes":[{"author":{"login":"kimtg","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7685905?v=3"},"updated-at":1441174250945,"created-at":1441174250945,"body":"```\nuser=> (doc if)\n-------------------------\nif\n (if test then else?)\nSpecial Form\n Evaluates test. If not the singular values nil or false,\n evaluates and yields then, otherwise, evaluates and yields else. If\n else is not supplied it defaults to nil.\n\n Please see http://clojure.org/special_forms#if\n```\nhttp://clojure.org/special_forms#if","_id":"55e692eae4b0efbd681fbb92"}],"arglists":[],"doc":"Evaluates test.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/if"},{"ns":"clojure.core","name":"do","type":"var","see-alsos":null,"examples":[{"author":{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":";; do is used to evaluate multiple expressions in order, usually for the\n;; purpose of evaluating exprs that have side-effects (such as printing\n;; or I/O). do returns the value of its last expression.\n;;\n;; do w/o args returns nil.\n\n=> (do\n (println \"LOG: Computing...\")\n (+ 1 1))\nLOG: Computing...\n2\n\n=> (do)\nnil\n","created-at":1287999552000,"updated-at":1287999682000,"_id":"542692cfc026201cdc326e9f"},{"body":";; `fn` (`defn` by extension) and `let` have an implicit `do`\n\n=> ((fn []\n (println \"Something\") ; printed in stdout\n (str \"Return this\")))\n\"Return this\"\n\n=> (defn do-example []\n (println \"Something\") ; printed in stdout\n (str \"Return this\")))\n=> (do-example)\n\"Return this\"\n\n=> (let [name \"John\"]\n (println \"Something\") ; printed in stdout\n (str \"Hello \" name))\n\"Hello John\"","author":{"login":"rafmagana","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/92894?v=3"},"created-at":1432926921112,"updated-at":1432927054881,"editors":[{"login":"rafmagana","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/92894?v=3"}],"_id":"5568bac9e4b03e2132e7d180"},{"updated-at":1456676930045,"created-at":1456676817498,"author":{"login":"ertugrulcetin","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8271291?v=3"},"body":"user=> (if (> 2 1)\n (do\n (print \"2 greater than 1\") ; with 'do' you can extend if block\n true))\n\n;;=>\"2 greater than 1\"\n;;=>true","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/8271291?v=3","account-source":"github","login":"ertugrulcetin"}],"_id":"56d31fd1e4b0b41f39d96cd6"},{"updated-at":1500223229802,"created-at":1500223229802,"author":{"login":"joncorr","account-source":"github","avatar-url":"https://avatars6.githubusercontent.com/u/908484?v=4"},"body":";; Print the result of time without the output of (range 1000)\n\n=> (do (time (range 1000)) nil)","_id":"596b96fde4b0d19c2ce9d6fe"}],"notes":null,"arglists":[],"doc":"Evaluates the expressions in order and returns the value of the last. If no\nexpressions are supplied, returns nil. See http://clojure.org/special_forms\nfor more information.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/do"},{"ns":"clojure.core","name":"quote","type":"var","see-alsos":[{"created-at":1537911884113,"author":{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/94482?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"unquote","ns":"clojure.core"},"_id":"5baaac4ce4b00ac801ed9ea7"}],"examples":[{"updated-at":1650678469915,"created-at":1293674217000,"body":";; ' is the shortcut for quote\nuser> (= 'a (quote a))\ntrue\n\n;; quoting keeps something from being evaluated\nuser> (quote (println \"foo\"))\n(println \"foo\")\n\n=> *clojure-version*\n{:major 1, :minor 5, :incremental 0, :qualifier \"RC17\"}\n=> (quote)\nnil\n=> (quote 1)\n1\n=> (quote 1 2 3 4 5) ; this worked in Clojure 1.0 through 1.7 but stopped working in 1.8\n1\n=> quote\nCompilerException java.lang.RuntimeException: Unable to resolve symbol: quote in this context, compiling:(NO_SOURCE_PATH:1:42)\n","editors":[{"avatar-url":"https://www.gravatar.com/avatar/9e10dfa345f44b0fe72bbe081fd51b83?r=PG&default=identicon","account-source":"clojuredocs","login":"AtKaaZ"},{"avatar-url":"https://www.gravatar.com/avatar/9e10dfa345f44b0fe72bbe081fd51b83?r=PG&default=identicon","account-source":"clojuredocs","login":"AtKaaZ"},{"login":"seancorfield","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/43875?v=4"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/bcacd00a7f05c4772329cf9f446c7987?r=PG&default=identicon","account-source":"clojuredocs","login":"dakrone"},"_id":"542692d0c026201cdc326ea2"},{"body":";; Proof that ' is just a syntactic sugar for quote:\nuser=> (macroexpand ''(1 2 3))\n(quote (1 2 3))\n\n;; Two ' must be used because reader processes and removes the first one","author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"created-at":1423019653856,"updated-at":1423019653856,"_id":"54d18e85e4b081e022073c54"},{"updated-at":1549280175530,"created-at":1549280175530,"author":{"login":"Bost","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/1174677?v=4"},"body":";; Quote returns the argument you pass it, without evaluation. So:\n;; In the expression `(quote 42)` the argument is the number 42 and...\nuser> (= (quote 42) 42)\ntrue ;; ... it is returned without any evaluation and...\nuser> (= (type (quote 42)) (type 42) java.lang.Long)\ntrue ;; ... as expected, without changing it's type.\n\n;; In the expression `(quote (quote 42))` the argument is the list of two\n;; elements `(quote 42)` ...\nuser> (= (quote (quote 42)) (list (read-string \"quote\") (read-string \"42\")))\ntrue ;; ... and it is returned without any evaluation and...\nuser> (= (type (quote (quote 42))) (type (list \"1st-elem\" \"2nd-elem\"))\n clojure.lang.PersistentList)\ntrue ;; ... again, without changing it's type.","_id":"5c5823afe4b0ca44402ef662"},{"editors":[{"login":"soulawaker","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/5372217?v=4"}],"body":";; Since clojure 1.9, if all keys in a map have the same namespace qualifier\n;; then the common namespace become the prefix of the map.\nuser> 'org.clojure/clojure\norg.clojure/clojure\n\nuser> '{org.clojure/clojure 3}\n#:org.clojure{clojure 3} ;; expecting {org.clojure/clojure 3} but not\n\nuser> '{org.clojure/clojure 3 :k 8}\n{org.clojure/clojure 3, :k 8} ;; Because of the keys' different namespaces \n\n;; If you want to avoid second case then flip *print-namespace-maps* temporally.\nuser> (binding [*print-namespace-maps* false]\n (pprint '{org.clojure/clojure 3}))\n{org.clojure/clojure 3}\nnil\n\n;; 'This is not a thing about quote. It is about map with key of namespaced keyword.'\n;; (@ShiTianshu's reply is quoted from below link)\n;; To know the detail reason, go to the below link and see the reply of @didibus.\n;; https://clojureverse.org/t/the-quote-special-form-behaves-strangely-on-maps/4879#post_2","author":{"avatar-url":"https://avatars2.githubusercontent.com/u/5372217?v=4","account-source":"github","login":"soulawaker"},"created-at":1569190020566,"updated-at":1569354172296,"_id":"5d87f084e4b0ca44402ef7ba"}],"notes":[{"updated-at":1289668928000,"body":"Quote gives you the unevaluated form. That is:\r\n\r\n
user=> '(foo bar baz)
\r\n\r\nWill not attempt to evaluate foo as a function but rather just return the data structure as is (with the three symbols unevaluated).","created-at":1289662273000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fa3"},{"updated-at":1371659988000,"body":"I found this blog post interesting: http://blog.8thlight.com/colin-jones/2012/05/22/quoting-without-confusion.html\r\n\r\nCheers","created-at":1371659988000,"author":{"login":"santeron","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/27a696b2606968635d5f4a5c6e2c7871?r=PG&default=identicon"},"_id":"542692edf6e94c6970522006"},{"author":{"login":"kumarshantanu","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109792?v=4"},"updated-at":1713439935723,"created-at":1713439935723,"body":"The blog-post linked above has moved to https://8thlight.com/insights/quoting-without-confusion","_id":"662104bf69fbcc0c226174be"}],"arglists":[],"doc":"Yields the unevaluated form. See http://clojure.org/special_forms for more\ninformation.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/quote"},{"ns":"clojure.core","name":"var","type":"var","see-alsos":[{"created-at":1289212861000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"meta","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c12"},{"created-at":1289212876000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"symbol","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c13"},{"created-at":1289212908000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"symbol?","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c14"},{"created-at":1289212912000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"var?","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c15"},{"created-at":1349393081000,"author":{"login":"eric","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2b0c9ae6f1da9716451e7c86bc87230b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"binding","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c17"},{"created-at":1349393092000,"author":{"login":"eric","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2b0c9ae6f1da9716451e7c86bc87230b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"with-redefs","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c18"},{"created-at":1349393097000,"author":{"login":"eric","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2b0c9ae6f1da9716451e7c86bc87230b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"with-redefs-fn","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c19"},{"created-at":1349393197000,"author":{"login":"eric","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2b0c9ae6f1da9716451e7c86bc87230b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"set!","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c1a"},{"created-at":1362015211000,"author":{"login":"AtKaaZ","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e10dfa345f44b0fe72bbe081fd51b83?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"var-set","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c1b"},{"created-at":1362015214000,"author":{"login":"AtKaaZ","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e10dfa345f44b0fe72bbe081fd51b83?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"var-get","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c1c"},{"created-at":1362015219000,"author":{"login":"AtKaaZ","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e10dfa345f44b0fe72bbe081fd51b83?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"with-local-vars","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c1d"}],"examples":[{"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"editors":[{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"}],"body":";;getting meta-data for a defined symbol (as opposed to what it's pointing to.\n\nuser=> meta\n#\n\nuser=> (var meta)\n#'clojure.core/meta\n\n;; Reader shortcut for var is #'\nuser=> #'meta\n#'clojure.core/meta\n\nuser=> (meta (var meta))\n{:ns #, :name meta, :file \"clojure/core.clj\", :line 178, :arglists ([obj]), :doc \"Returns the metadata of obj, returns nil if there is no metadata.\", :added \"1.0\"}\n","created-at":1289212848000,"updated-at":1423522981079,"_id":"542692d0c026201cdc326ea5"},{"author":{"login":"AtKaaZ","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e10dfa345f44b0fe72bbe081fd51b83?r=PG&default=identicon"},"editors":[{"login":"AtKaaZ","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e10dfa345f44b0fe72bbe081fd51b83?r=PG&default=identicon"}],"body":"=> *clojure-version*\n{:major 1, :minor 5, :incremental 0, :qualifier \"RC17\"}\n=> var\n;CompilerException java.lang.RuntimeException: Unable to resolve symbol: var in this context, compiling:(NO_SOURCE_PATH:1:42) \n=> (var)\n;CompilerException java.lang.NullPointerException, compiling:(NO_SOURCE_PATH:1:1) \n=> (var 1)\n;CompilerException java.lang.ClassCastException: java.lang.Long cannot be cast to clojure.lang.Symbol, compiling:(NO_SOURCE_PATH:1:1) \n=> (var defn)\n#'clojure.core/defn\n=> (var defn 1 2 3 4)\n#'clojure.core/defn\n","created-at":1362014971000,"updated-at":1362015006000,"_id":"542692d6c026201cdc3270d0"},{"editors":[{"login":"beoliver","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1413969?v=4"}],"body":"user> (def a 1)\n#'user/a\n\nuser> (def b (var a))\n#'user/b\n\nuser> (alter-var-root (var a) inc)\n2\n\nuser> (alter-var-root b inc)\n3\n\nuser> (deref b)\n3\n","author":{"avatar-url":"https://avatars2.githubusercontent.com/u/1413969?v=4","account-source":"github","login":"beoliver"},"created-at":1509263736051,"updated-at":1509263779264,"_id":"59f58978e4b0a08026c48c80"}],"notes":null,"arglists":[],"doc":"The symbol must resolve to a var, and the Var object itself (not its value)\nis returned. The reader macro #'x expands to (var x). See\nhttp://clojure.org/special_forms for more information.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/var"},{"ns":"clojure.core","name":"recur","type":"var","see-alsos":[{"created-at":1289618026000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"loop","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e3a"},{"created-at":1289618032000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"trampoline","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e3b"}],"examples":[{"updated-at":1524485644327,"created-at":1290256018000,"body":"(def factorial\n (fn [n]\n (loop [cnt n\n acc 1]\n (if (zero? cnt)\n acc\n (recur (dec cnt) (* acc cnt))\n; in loop cnt will take the value (dec cnt)\n; and acc will take the value (* acc cnt)\n))))","editors":[{"avatar-url":"https://www.gravatar.com/avatar/22b6fbc4a386291e45b1cb4449377086?r=PG&default=identicon","account-source":"clojuredocs","login":"john.r.woodward"},{"login":"allentiak","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/1922297?v=4"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/a06d0fc5d5b9a1d254e566c1d0e449a8?r=PG&default=identicon","account-source":"clojuredocs","login":"ique"},"_id":"542692d0c026201cdc326ea6"},{"author":{"login":"ique","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a06d0fc5d5b9a1d254e566c1d0e449a8?r=PG&default=identicon"},"editors":[{"avatar-url":"https://avatars3.githubusercontent.com/u/1922297?v=4","account-source":"github","login":"allentiak"}],"body":"; A loop that sums the numbers 10 + 9 + 8 + ...\n\n; Set initial values count (cnt) from 10 and down\n(loop [sum 0\n cnt 10]\n ; If count reaches 0 then exit the loop and return sum\n (if (= cnt 0)\n sum\n ; Otherwise add count to sum, decrease count and \n ; use recur to feed the new values back into the loop\n (recur (+ cnt sum) (dec cnt))))","created-at":1290256169000,"updated-at":1524485722720,"_id":"542692d0c026201cdc326ea8"},{"author":{"login":"john.r.woodward","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/22b6fbc4a386291e45b1cb4449377086?r=PG&default=identicon"},"editors":[],"body":"(loop [i 0] \n (when (< i 5) \n (println i) \n (recur (inc i)); loop i will take this value\n))","created-at":1342658004000,"updated-at":1342658004000,"_id":"542692d6c026201cdc3270d2"},{"author":{"login":"azkesz","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/467196a4f2498080c9740a81fcbde855?r=PG&default=identicon"},"editors":[{"login":"azkesz","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/467196a4f2498080c9740a81fcbde855?r=PG&default=identicon"}],"body":"(defn compute-across [func elements value]\n (if (empty? elements)\n value\n (recur func (rest elements) (func value (first elements)))))\n\n(defn total-of [numbers]\n (compute-across + numbers 0))\n\n(defn larger-of [x y]\n (if (> x y) x y))\n\n(defn greatest-of [numbers]\n (compute-across larger-of numbers (first numbers)))","created-at":1345941881000,"updated-at":1345942092000,"_id":"542692d6c026201cdc3270d3"},{"editors":[{"login":"jdwaterson","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2714395?v=3"}],"body":"; Note that recur can be surprising when using variadic functions.\n\n(defn foo [& args]\n (let [[x & more] args]\n (prn x)\n (if more (recur more) nil)))\n\n(defn bar [& args]\n (let [[x & more] args]\n (prn x)\n (if more (bar more) nil)))\n\n; The key thing to note here is that foo and bar are identical, except\n; that foo uses recur and bar uses \"normal\" recursion. And yet...\n\nuser=> (foo :a :b :c)\n:a\n:b\n:c\nnil\n\nuser=> (bar :a :b :c)\n:a\n(:b :c)\nnil\n\n; The difference arises because recur does not gather variadic/rest args\n; into a seq.","author":{"avatar-url":"https://avatars.githubusercontent.com/u/2714395?v=3","account-source":"github","login":"jdwaterson"},"created-at":1442790612342,"updated-at":1442872934681,"_id":"55ff3cd4e4b08e404b6c1c7f"},{"updated-at":1443215990041,"created-at":1443215347637,"author":{"login":"teymuri","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/13352033?v=3"},"body":";;This will generate the first 1000 Fibonacci numbers \n;;(using incrementing and decrementing): \n\n(loop [res [0 1]]\n (if (>= (count res) 1000)\n res\n (recur (conj res (+' (inc (last res)) (dec (last (butlast res))))))))","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/13352033?v=3","account-source":"github","login":"teymuri"}],"_id":"5605b7f3e4b08e404b6c1c82"},{"editors":[{"login":"clojurianix","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/19415437?v=3"}],"body":";; The recursion point can be a 'loop' or a 'fn' method.\n\n(loop [n (bigint 5), accumulator 1]\n (if (zero? n)\n accumulator ; we're done\n (recur (dec n) (* accumulator n))))\n;;=> 120N\n\n\n((fn factorial\n ([n] (factorial n 1))\n\n ([n accumulator]\n (if (zero? n)\n accumulator ; we're done\n (recur (dec n) (* accumulator n)))))\n\n (bigint 5))\n;;=> 120N","author":{"avatar-url":"https://avatars.githubusercontent.com/u/19415437?v=3","account-source":"github","login":"clojurianix"},"created-at":1463825907835,"updated-at":1463826090672,"_id":"574035f3e4b0a1a06bdee495"},{"updated-at":1608716871582,"created-at":1608716871582,"author":{"login":"caumond","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/11491686?v=4"},"body":";; Trailing position could be multiple\n(loop [x 1]\n (println \"x= \" x)\n (cond\n (> x 10) (println \"ending at \" x )\n (even? x) (recur (* 2 x))\n :else (recur (+ x 1))))","_id":"5fe31247e4b0b1e3652d7420"},{"editors":[{"login":"conao3","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/4703128?v=4"}],"body":";; see `foo` and `bar` above\n;; this `baz` uses normal recursion, this blows stacks but `foo` doesn't\n\n(defn baz [& args]\n (let [[x & more] args]\n (prn x)\n (if more (apply baz more) nil)))\n\n(baz :a :b :c)\n;; :a\n;; :b\n;; :c\n;;=> nil\n","author":{"avatar-url":"https://avatars.githubusercontent.com/u/4703128?v=4","account-source":"github","login":"conao3"},"created-at":1727898661869,"updated-at":1727898907881,"_id":"66fda42569fbcc0c226174fe"}],"notes":null,"arglists":[],"doc":"Evaluates the exprs in order, then, in parallel, rebinds the bindings of\nthe recursion point to the values of the exprs. See\nhttp://clojure.org/special_forms for more information.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/recur"},{"ns":"clojure.core","name":"throw","type":"var","see-alsos":[{"created-at":1341631202000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"try","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f2e"},{"created-at":1341631204000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"catch","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f2f"},{"created-at":1341631207000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"finally","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f30"},{"created-at":1430235342019,"author":{"login":"ljosa","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/197881?v=3"},"to-var":{"ns":"clojure.core","name":"ex-info","library-url":"https://github.com/clojure/clojure"},"_id":"553fa8cee4b06eaacc9cda7f"},{"created-at":1460277375628,"author":{"login":"ryoakg","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/23413?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"ex-data","ns":"clojure.core"},"_id":"570a107fe4b075f5b2c864df"}],"examples":[{"author":{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},"editors":[],"body":"=> (throw (Exception. \"my exception message\"))\njava.lang.Exception: my exception message (NO_SOURCE_FILE:0)\n","created-at":1288000015000,"updated-at":1288000015000,"_id":"542692d0c026201cdc326ea9"},{"editors":[{"login":"green-coder","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/598193?v=4"}],"body":";; Different types of exception can be thrown\n=> (throw (AssertionError. \"Wrong input.\"))\njava.lang.AssertionError: Wrong input.","author":{"avatar-url":"https://avatars3.githubusercontent.com/u/10631263?v=4","account-source":"github","login":"asiegfried"},"created-at":1501935005004,"updated-at":1533054136477,"_id":"5985b59de4b0d19c2ce9d70b"},{"updated-at":1603831007076,"created-at":1603831007076,"author":{"login":"ertugrulcetin","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/8271291?v=4"},"body":";; ClojureScript usage\n=> (throw (js/Error. \"something went wrong...\"))","_id":"5f9884dfe4b0b1e3652d73f6"}],"notes":null,"arglists":[],"doc":"The expr is evaluated and thrown, therefore it should yield an instance of\nsome derivee of Throwable. Please see http://clojure.org/special_forms#throw","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/throw"},{"ns":"clojure.core","name":"try","type":"var","see-alsos":[{"created-at":1287995793000,"author":{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},"to-var":{"ns":"clojure.core","name":"catch","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f49"},{"created-at":1341631154000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"finally","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f4a"},{"created-at":1341631196000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"throw","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f4b"},{"created-at":1517506079914,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"ex-info","ns":"clojure.core"},"_id":"5a734e1fe4b076dac5a728af"},{"created-at":1517506631341,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"ex-data","ns":"clojure.core"},"_id":"5a735047e4b076dac5a728b0"}],"examples":[{"author":{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},"editors":[],"body":"=> (try\n (/ 1 0)\n (catch Exception e (str \"caught exception: \" (.getMessage e))))\n\n\"caught exception: Divide by zero\"","created-at":1287995834000,"updated-at":1287995834000,"_id":"542692d0c026201cdc326eaa"},{"author":{"login":"acagle","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/7df8ebcd99fdbdd4a2f7682513897692?r=PG&default=identicon"},"editors":[],"body":";; for Clojurescript use js/Object as type\n(try\n (/ 1 0)\n (catch js/Object e\n (.log js/console e)))","created-at":1344400343000,"updated-at":1344400343000,"_id":"542692d6c026201cdc3270d5"},{"editors":[{"login":"masmatsum","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8317204?v=4"}],"body":";; Example with multiple catch clauses and a finally clause.\n(try (f)\n (catch SQLException se (prn (.getNextException e)))\n (catch Exception2 e (prn \"Handle generic exception\"))\n (finally (prn \"Release some resource\")))","author":{"avatar-url":"https://avatars.githubusercontent.com/u/632775?v=3","account-source":"github","login":"Rovanion"},"created-at":1463816138311,"updated-at":1633612258613,"_id":"57400fcae4b00a9b70be566b"},{"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"}],"body":";; The catch/finally clause is an implicit do.\n(try\n (/ 1 0)\n (catch Exception ex \n (.printStackTrace ex)\n (str \"caught exception: \" (.getMessage ex))))\n;; java.lang.ArithmeticException: Divide by zero\n;;\tat clojure.lang.Numbers.divide(Numbers.java:163)\n;;\tat clojure.lang.Numbers.divide(Numbers.java:3833)\n;; ...\n;; at main.java:37)\n;;=> \"caught exception: Divide by zero\"\n","author":{"avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4","account-source":"github","login":"phreed"},"created-at":1513121596628,"updated-at":1513202809575,"_id":"5a30673ce4b0a08026c48cd4"},{"updated-at":1554055517810,"created-at":1554055517810,"author":{"login":"huahaiy","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/889685?v=4"},"body":";; try multiple expressions\n(try (println \"expression 1\")\n (println \"expression 2\")\n (/ 1 0)\n (println \"expression 4\")\n (catch Exception e (println \"expression 3 throws\")))\n;;=> expression 1\n;;=> expression 2\n;;=> expression 3 throws","_id":"5ca1015de4b0ca44402ef6f4"},{"updated-at":1661740260118,"created-at":1661740260118,"author":{"login":"Obscerno","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33399601?v=4"},"body":";; The last value in the body of try will be returned.\n(try \"I will not be returned.\"\n \"I will be returned\"\n (catch Exception e (.getMessage e))\n (finally \"I will also not be returned.\"))\n;; => \"I will be returned\"\n\n;; If there's an exception the last value in the body of catch will be returned.\n(try (throw (RuntimeException.))\n \"I will not be returned\"\n (catch Exception e \"I will be returned\")\n (finally \"I will also not be returned.\"))\n;; => \"I will be returned\"","_id":"630c24e4e4b0b1e3652d765d"},{"updated-at":1774603867434,"created-at":1774452480688,"author":{"login":"teodorlu","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/5285452?v=4"},"body":";; You may be unable to catch exceptions due to unrealized, lazy sequences.\n(try (map inc \"not numbers....\")\n (catch Exception _ :caught))\n;; => Error printing return value (ClassCastException) at clojure.lang.Numbers/inc (Numbers.java:137).\n;; class java.lang.Character cannot be cast to class java.lang.Number (java.lang.Character and java.lang.Number are in module java.base of loader 'bootstrap')\n\n;; What you just saw was the editor succeeding in evaluating the expression,\n;; then realizing the lazy-seq to print it, then hitting the exception!\n;;\n;; To catch such exceptions, realize any lazy-seqs in the (try ,,,)-body.\n(try (doall (map inc \"not numbers....\"))\n (catch Exception _ :caught))\n;; => :caught\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/5285452?v=4","account-source":"github","login":"teodorlu"}],"_id":"69c3ff007955605a202df29a"}],"notes":null,"arglists":[],"doc":"The exprs are evaluated and, if no exceptions occur, the value of the last\nis returned. If an exception occurs and catch clauses are provided, each is\nexamined in turn and the first for which the thrown exception is an instance\nof the named class is considered a matching catch clause. If there is a\nmatching catch clause, its exprs are evaluated in a context in which name is\nbound to the thrown exception, and the value of the last is the return value\nof the function. If there is no matching catch clause, the exception\npropagates out of the function. Before returning, normally or abnormally,\nany finally exprs will be evaluated for their side effects. See\nhttp://clojure.org/special_forms for more information.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/try"},{"ns":"clojure.core","name":"catch","type":"var","see-alsos":[{"created-at":1287995785000,"author":{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},"to-var":{"ns":"clojure.core","name":"try","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521ad9"},{"created-at":1288000232000,"author":{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},"to-var":{"ns":"clojure.core","name":"finally","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521ada"},{"created-at":1517620569282,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"throw","ns":"clojure.core"},"_id":"5a750d59e4b0e2d9c35f740b"},{"created-at":1517620590089,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"ex-data","ns":"clojure.core"},"_id":"5a750d6ee4b0e2d9c35f740c"},{"created-at":1517620611031,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"ex-info","ns":"clojure.core"},"_id":"5a750d83e4b0e2d9c35f740d"},{"created-at":1518042276700,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"print-stack-trace","ns":"clojure.stacktrace"},"_id":"5a7b7ca4e4b0316c0f44f8a7"}],"examples":[{"author":{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},"editors":[],"body":"=> (try\n (/ 1 0)\n (catch Exception e (str \"caught exception: \" (.getMessage e))))\n\n\"caught exception: Divide by zero\"","created-at":1287995772000,"updated-at":1287995772000,"_id":"542692d0c026201cdc326eae"},{"updated-at":1704390530715,"created-at":1474647298976,"author":{"login":"JoshAaronJones","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/19951591?v=3"},"body":";; multiple catch clauses which handle different exceptions\n\n=> (let [divisor [2 0 \"clojure\"]]\n (try\n (/ 4 (rand-nth divisor))\n (catch ArithmeticException e\n (println \"Probably trying to divide by zero...\")\n 111)\n (catch ClassCastException e\n (println \"Did you try to do math with a string?\")\n 222)\n (catch AssertionError e\n (println \"Some conditions aren't compatible with the requirements of a function\")\n 333)\n (catch Exception e\n (println \"Some other exception, won't be caught in this case...\")\n 444)\n (finally\n (println \"Always executed but won't return a value!\"))))\n\n;; first case\nAlways executed but won't return a value!\n=> 2\n\n;; second case\nProbably trying to divide by zero...\nAlways executed but won't return a value!\n=> 111\n\n;; third case\nDid you try to do math with a string?\nAlways executed but won't return a value!\n=> 222\n\n;; forth case\nSome conditions aren't compatible with the requirements of a function\nAlways executed but won't return a value!\n=> 333\n\n;; fifth case\nSome other exception, won't be caught in this case...\nAlways executed but won't return a value!\n=> 444","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/48576209?v=4","account-source":"github","login":"sofiiahitlan"}],"_id":"57e55502e4b0709b524f050a"},{"updated-at":1482420504337,"created-at":1482420504337,"author":{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/94482?v=3"},"body":";; Note that in ClojureScript, one can use (catch :default e ...) to catch any \n;; type of value, roughly equivalent to (catch Exception e ...) in JVM Clojure.\n\n(try\n (/ 2 (rand-nth [0 \"oops\"]))\n (catch :default e ; Note: ClojureScript only!\n (println \"Error!\" e)))\n\n;; This is not currently possible in JVM Clojure, though the ticket CLJ-1293 \n;; proposes adding the same behavior there and has some background info.","_id":"585bf118e4b0123d4c9dfa35"}],"notes":null,"arglists":[],"doc":"The exprs are evaluated and, if no exceptions occur, the value of the last\nis returned. If an exception occurs and catch clauses are provided, each is\nexamined in turn and the first for which the thrown exception is an instance\nof the named class is considered a matching catch clause. If there is a\nmatching catch clause, its exprs are evaluated in a context in which name is\nbound to the thrown exception, and the value of the last is the return value\nof the function. If there is no matching catch clause, the exception\npropagates out of the function. Before returning, normally or abnormally,\nany finally exprs will be evaluated for their side effects. See\nhttp://clojure.org/special_forms for more information.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/catch"},{"ns":"clojure.core","name":"finally","type":"var","see-alsos":[{"created-at":1288000213000,"author":{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},"to-var":{"ns":"clojure.core","name":"try","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e23"},{"created-at":1288000217000,"author":{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},"to-var":{"ns":"clojure.core","name":"catch","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e24"},{"created-at":1517617085736,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"ex-data","ns":"clojure.core"},"_id":"5a74ffbde4b0e2d9c35f7406"},{"created-at":1517620981684,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"throw","ns":"clojure.core"},"_id":"5a750ef5e4b0e2d9c35f7410"}],"examples":[{"updated-at":1317221828000,"created-at":1288260604000,"body":"(try\n (/ 1 0)\n (catch ArithmeticException e (str \"caught exception: \" (.getMessage e)))\n (finally (prn \"final exception.\")))\n\"final exception.\"\n\"caught exception: Divide by zero\"","editors":[{"avatar-url":"https://www.gravatar.com/avatar/1de5617efb013ca7c9cf8e5646818ffa?r=PG&default=identicon","account-source":"clojuredocs","login":"philos99"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3","account-source":"github","login":"devn"},"_id":"542692d0c026201cdc326eaf"},{"editors":[{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"}],"body":";; finally will always run before returning, even if there is no exception.\n(try\n (+ 1 1)\n (catch ArithmeticException e (str \"caught exception: \" (.getMessage e)))\n (finally (prn \"final print.\")))\n\"final print.\"\n2\n","author":{"avatar-url":"https://avatars3.githubusercontent.com/u/889685?v=4","account-source":"github","login":"huahaiy"},"created-at":1592604689313,"updated-at":1663143524487,"_id":"5eed3811e4b0b1e3652d7309"}],"notes":null,"arglists":[],"doc":"The exprs are evaluated and, if no exceptions occur, the value of the last\nis returned. If an exception occurs and catch clauses are provided, each is\nexamined in turn and the first for which the thrown exception is an instance\nof the named class is considered a matching catch clause. If there is a\nmatching catch clause, its exprs are evaluated in a context in which name is\nbound to the thrown exception, and the value of the last is the return value\nof the function. If there is no matching catch clause, the exception\npropagates out of the function. Before returning, normally or abnormally,\nany finally exprs will be evaluated for their side effects. See\nhttp://clojure.org/special_forms for more information.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/finally"},{"ns":"clojure.core","name":".","type":"var","see-alsos":[{"created-at":1461732266533,"author":{"login":"delonnewman","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10404?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"..","ns":"clojure.core"},"_id":"572043aae4b0fc95a97eab5c"}],"examples":[{"updated-at":1514391136118,"created-at":1461732237604,"author":{"login":"delonnewman","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10404?v=3"},"body":"(def date (java.util.Date.))\n;; => #'date\n(. date getMonth)\n;; => 11 ; 0-based, so this indicates \"December\"","editors":[{"avatar-url":"https://avatars1.githubusercontent.com/u/430319?v=4","account-source":"github","login":"jcburley"}],"_id":"5720438de4b0fc95a97eab5a"},{"updated-at":1471001203866,"created-at":1471001203866,"author":{"login":"ertugrulcetin","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8271291?v=3"},"body":"user=> (. \"abc\" (toUpperCase)) \n;;=> \"ABC\"\n\nuser=> (. \"abc\" toUpperCase) \n;;=> \"ABC\"\n;;if function has one arg you can use non-parenthesis form\n\n","_id":"57adb273e4b0bafd3e2a04f0"},{"updated-at":1555179101611,"created-at":1555175138250,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"body":";; '.' For static access\n(. Thread sleep 1000) ; static method of 1 arg.\n(. Math random) ; static field access first, static method of no args next.\n(. Math (random)) ; static method of no args (unambiguously).\n(. Math -PI) ; static field access (unambiguously).\n(. Thread$State NEW) ; inner class static method.\n\n;; Corresponding slashed forms are converted internally to dotted:\n(Thread/sleep 1000) ; static method of 1 arg.\n(Math/random) ; static field access first, static method of no args next.\n(Math/-PI) ; static field access (unambiguously).\n\n;; For instance access \n(import 'java.awt.Point)\n(. (Point. 1 2) x) ; instance field first, method of no args next\n(.x (Point. 1 2)) ; same as above\n(. (Point. 1 2) (getX)) ; instance method (unambiguously)\n(.-x (Point. 1 2)) ; instance field (unambiguously)\n\n;; Showing how to compose names dynamically\n(eval `(. (Point. 1 2) ~(symbol (str \"get\" \"X\"))))\n;; 1.0","editors":[{"avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"}],"_id":"5cb216e2e4b0ca44402ef708"}],"notes":null,"arglists":[],"doc":"The '.' special form is the basis for access to Java. It can be considered\na member-access operator, and/or read as 'in the scope of'. See\nhttp://clojure.org/special_forms for more information.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/_."},{"ns":"clojure.core","name":"set!","type":"var","see-alsos":[{"created-at":1361164008000,"author":{"login":"AtKaaZ","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e10dfa345f44b0fe72bbe081fd51b83?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"reset!","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521dc5"},{"created-at":1361164022000,"author":{"login":"AtKaaZ","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e10dfa345f44b0fe72bbe081fd51b83?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"binding","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521dc6"},{"created-at":1361164032000,"author":{"login":"AtKaaZ","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e10dfa345f44b0fe72bbe081fd51b83?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"alter-var-root","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521dc7"},{"created-at":1546021427673,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"atom","ns":"clojure.core"},"_id":"5c266a33e4b0ca44402ef603"}],"examples":[{"author":{"login":"ninjudd","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/7ced25585a7556e9b9b975c1f9e136e3?r=PG&default=identicon"},"editors":[],"body":"(set! var-symbol expr)","created-at":1307137727000,"updated-at":1307137727000,"_id":"542692d0c026201cdc326ead"},{"author":{"login":"AtKaaZ","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e10dfa345f44b0fe72bbe081fd51b83?r=PG&default=identicon"},"editors":[],"body":"(set! *warn-on-reflection* true)","created-at":1361163932000,"updated-at":1361163932000,"_id":"542692d6c026201cdc3270d6"},{"updated-at":1552509115019,"created-at":1552509115019,"author":{"login":"nhlx2","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/4058121?v=4"},"body":"user=> (let [object (java.awt.Point. 1 2)]\n (set! (. object -y) 8)\n (bean object)\n )\n{:class java.awt.Point, :location #object[java.awt.Point 0x383fc59b \"java.awt.Point[x=1,y=8]\"], :x 1.0, :y 8.0}\n","_id":"5c8968bbe4b0ca44402ef6b4"},{"editors":[{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"}],"body":";; A mutable (and thread unsafe) Counter class.\n;; set! is used to mutate the internal cnt attribute.\n\n(deftype Counter [^:unsynchronized-mutable cnt]\n clojure.lang.IFn\n (invoke [this] (set! cnt (inc cnt))))\n\n(def counter (->Counter 0))\n(counter) ;; 1\n(counter) ;; 2","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"},"created-at":1554278192236,"updated-at":1554278208406,"_id":"5ca46730e4b0ca44402ef6fb"}],"notes":[{"updated-at":1298369674000,"body":"As of Clojure 1.2, the basic info for set! has moved to http://clojure.org/vars.","created-at":1298369674000,"author":{"login":"gregg-williams","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/58610a64fc8638eec8d2239d80d4046f?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fb3"}],"arglists":[],"doc":"Assignment special form. When the first operand is a field member access\nform, the assignment is to the corresponding field. If it is an instance\nfield, the instance expr will be evaluated, then the expr. In all cases\nthe value of expr is returned. Note - you cannot assign to function params\nor local bindings. Only Java fields, Vars, Refs and Agents are mutable in\nClojure. See http://clojure.org/special_forms for more information.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/set!"},{"ns":"clojure.core","name":"monitor-enter","type":"var","see-alsos":null,"examples":null,"notes":[{"body":"\"should be avoided\". OK. But why is it available? How might it be used?\n\nhttp://stackoverflow.com/questions/36485155/use-locking-macro-or-monitor-enter-and-monitor-exit-in-java-from-clojure/36485607","created-at":1461052938480,"updated-at":1461053268343,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/11754710?v=3","account-source":"github","login":"terjedahl"},"_id":"5715e60ae4b0fc95a97eab4e"}],"arglists":[],"doc":"A synchronization primitive that should be avoided in user code. Use the\nlocking macro. See http://clojure.org/special_forms for more information.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/monitor-enter"},{"ns":"clojure.core","name":"monitor-exit","type":"var","see-alsos":null,"examples":null,"notes":null,"arglists":[],"doc":"A synchronization primitive that should be avoided in user code. Use the\nlocking macro. See http://clojure.org/special_forms for more information.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/monitor-exit"},{"ns":"clojure.core","name":"new","type":"var","see-alsos":[{"created-at":1352083329000,"author":{"login":"AtKaaZ","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e10dfa345f44b0fe72bbe081fd51b83?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":".","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bf1"}],"examples":[{"author":{"login":"shockbob","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon"},"editors":[],"body":";; Create a Java ArrayList using the 0 argument constructor\nuser=> (def a (new java.util.ArrayList))\n#'user/a\nuser=> (.add a \"aaa\")\ntrue\nuser=> (.add a \"bbb\")\ntrue\nuser=> a\n#\n","created-at":1313491605000,"updated-at":1313491605000,"_id":"542692d0c026201cdc326eab"},{"author":{"login":"shockbob","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon"},"editors":[],"body":";; Create another ArrayList and add integers using the doto macro\nuser=> (def ai (doto (new java.util.ArrayList) (.add 1) (.add 2) (.add 0)))\n#'user/ai\nuser=> ai\n#","created-at":1313491629000,"updated-at":1313491629000,"_id":"542692d0c026201cdc326eac"}],"notes":null,"arglists":[],"doc":"Instantiate a class. See http://clojure.org/java_interop#new for\nmore information.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/new"},{"ns":"clojure.core","name":"primitives-classnames","file":"clojure/core_print.clj","type":"var","column":1,"see-alsos":null,"line":372,"examples":[{"body":"user=> (use 'clojure.pprint)\nuser=> (pprint primitives-classnames)\n{float \"Float/TYPE\",\n int \"Integer/TYPE\",\n long \"Long/TYPE\",\n boolean \"Boolean/TYPE\",\n char \"Character/TYPE\",\n double \"Double/TYPE\",\n byte \"Byte/TYPE\",\n short \"Short/TYPE\"}","author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"created-at":1423019236792,"updated-at":1423019236792,"_id":"54d18ce4e4b081e022073c53"}],"notes":null,"arglists":[],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core/primitives-classnames"},{"added":"1.0","ns":"clojure.core","name":"+'","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1412881252224,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"},"to-var":{"ns":"clojure.core","name":"+","library-url":"https://github.com/clojure/clojure"},"_id":"5436db64e4b06dbffbbb00c0"},{"created-at":1423526974611,"author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"to-var":{"ns":"clojure.core","name":"unchecked-add","library-url":"https://github.com/clojure/clojure"},"_id":"54d94c3ee4b081e022073c83"}],"line":974,"examples":[{"body":"(+')\n;;=> 0\n\n(+' 1)\n;;=> 1\n\n(+' -10)\n;;=> -10\n\n(+' 1 2)\n;;=> 3\n\n(+' 1 2 3)\n;;=> 6\n\n(apply + (range 10000000000000 10000000001000))\n;; ArithmeticException: integer overflow\n\n(apply +' (range 10000000000000 10000000001000))\n;;=> 1000000000499500","author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"},"created-at":1412881234729,"updated-at":1412881548215,"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"}],"_id":"5436db52e4b0ae7956031576"},{"body":"(class 1)\n;; => java.lang.Long\n\n(+ 1 Long/MAX_VALUE)\n;; => java.lang.ArithmeticException: integer overflow\n;; Numbers.java:1388 clojure.lang.Numbers.throwIntOverflow\n;; Numbers.java:1687 clojure.lang.Numbers.add\n\n(+' 1 Long/MAX_VALUE)\n;; => 9223372036854775808N\n\n(class (+' 1 Long/MAX_VALUE))\n;; => clojure.lang.BigInt\n","author":{"login":"yangwansu","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/89217?v=3"},"created-at":1422876391721,"updated-at":1422876391721,"_id":"54cf5ee7e4b081e022073c3e"}],"notes":null,"arglists":["","x","x y","x y & more"],"doc":"Returns the sum of nums. (+') returns 0. Supports arbitrary precision.\n See also: +","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/+'"},{"added":"1.0","ns":"clojure.core","name":"decimal?","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1496006134313,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"bigdec?","ns":"clojure.core"},"_id":"592b3df6e4b093ada4d4d78b"},{"created-at":1496006153201,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"double?","ns":"clojure.core"},"_id":"592b3e09e4b093ada4d4d78c"},{"created-at":1496006158570,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"float?","ns":"clojure.core"},"_id":"592b3e0ee4b093ada4d4d78d"}],"line":3624,"examples":[{"author":{"login":"dakrone","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bcacd00a7f05c4772329cf9f446c7987?r=PG&default=identicon"},"editors":[],"body":"user=> (decimal? 1)\nfalse\n\nuser=> (decimal? 1.0)\nfalse\n\nuser=> (decimal? 1M)\ntrue\n\nuser=> (decimal? 99999999999999999999999999999999999)\nfalse\n\nuser=> (decimal? 1.0M)\ntrue","created-at":1286508904000,"updated-at":1286508904000,"_id":"542692cbc026201cdc326bd0"}],"notes":null,"arglists":["n"],"doc":"Returns true if n is a BigDecimal","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/decimal_q"},{"added":"1.2","ns":"clojure.core","name":"restart-agent","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1326769275000,"author":{"login":"Mark","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/4d7c9ac1dd03a71c7d6b548e80c9d4f9?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"agent-error","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b32"},{"created-at":1326769279000,"author":{"login":"Mark","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/4d7c9ac1dd03a71c7d6b548e80c9d4f9?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"agent","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b33"}],"line":2194,"examples":[{"updated-at":1497900418842,"created-at":1497900418842,"author":{"login":"cloojure","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/7083783?v=3"},"body":"(deftest t-rstart\n (future (println \"running in a thread...\"))\n (let [agt (agent 0)\n\n ; This doesn't work\n h01 (fn [a e]\n (println :10 \"agent error found:\" )\n (println :11 \"restarting agent...\")\n (restart-agent a 100)\n (Thread/sleep 100)\n (println :12 \"agent restarted, state=\" @a))\n\n ; This works. Need to call restart-agent in a separate thread\n h02 (fn [a e]\n (println :20 \"agent error found:\" )\n (future\n (println :21 \"restarting agent...\")\n (restart-agent a 200)\n (println :22 \"agent restarted, state=\" @a))) ;=> 200\n ]\n (set-error-handler! agt h02)\n (send agt inc)\n (Thread/sleep 100) (println :01 @agt) ;=> 1\n (Thread/sleep 100) (send agt #(/ % 0))\n (Thread/sleep 100) (println :02 @agt) ;=> 200\n (Thread/sleep 100) (send agt inc)\n (Thread/sleep 100) (println :03 @agt) ;=> 201\n))\n\n; Output\n; running in a thread...\n; :01 1\n; :20 agent error found:\n; :21 restarting agent...\n; :22 agent restarted, state= 200\n; :02 200\n; :03 201\n","_id":"59482582e4b06e730307db3b"}],"notes":null,"arglists":["a new-state & options"],"doc":"When an agent is failed, changes the agent state to new-state and\n then un-fails the agent so that sends are allowed again. If\n a :clear-actions true option is given, any actions queued on the\n agent that were being held while it was failed will be discarded,\n otherwise those held actions will proceed. The new-state must pass\n the validator if any, or restart will throw an exception and the\n agent will remain failed with its old state and error. Watchers, if\n any, will NOT be notified of the new state. Throws an exception if\n the agent is not failed.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/restart-agent"},{"added":"1.0","ns":"clojure.core","name":"sort-by","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1302917800000,"author":{"login":"TimMc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5d532e51427ef2f4ded31aaca16c8baf?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"sort","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ca1"},{"created-at":1361334368000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"compare","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ca2"}],"line":3127,"examples":[{"author":{"login":"zmila","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/68dd6f50915854aa04fefcf4d6fa5c8e?r=PG&default=identicon"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"}],"body":"user=> (sort-by count [\"aaa\" \"bb\" \"c\"])\n(\"c\" \"bb\" \"aaa\")\n\nuser=> (sort-by first [[1 2] [2 2] [2 3]]) \n([1 2] [2 2] [2 3])\n\nuser=> (sort-by first > [[1 2] [2 2] [2 3]]) \n([2 2] [2 3] [1 2])","created-at":1281552743000,"updated-at":1423276838828,"_id":"542692cbc026201cdc326c28"},{"author":{"login":"kotarak","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5db30f607f0b5fa70d690311aa3bfd3b?r=PG&default=identicon"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":"user=> (sort-by :rank [{:rank 2} {:rank 3} {:rank 1}])\n({:rank 1} {:rank 2} {:rank 3})","created-at":1281554134000,"updated-at":1332949762000,"_id":"542692cbc026201cdc326c2a"},{"updated-at":1465979342950,"created-at":1305342274000,"body":"(def x [{:foo 2 :bar 11}\n {:bar 99 :foo 1}\n {:bar 55 :foo 2}\n {:foo 1 :bar 77}])\n\n;sort by :foo, and where :foo is equal, sort by :bar\n(sort-by (juxt :foo :bar) x)\n;=>({:foo 1, :bar 77} {:bar 99, :foo 1} {:foo 2, :bar 11} {:bar 55, :foo 2})","editors":[{"avatar-url":"https://www.gravatar.com/avatar/d1906fc5df2c8ce5b2d58cc6ea855aab?r=PG&default=identicon","account-source":"clojuredocs","login":"shuaybi"},{"avatar-url":"https://www.gravatar.com/avatar/47018db2b156f6c7f606950e19cf6134?r=PG&default=identicon","account-source":"clojuredocs","login":"ordnungswidrig"},{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1334295?v=3"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/d1906fc5df2c8ce5b2d58cc6ea855aab?r=PG&default=identicon","account-source":"clojuredocs","login":"shuaybi"},"_id":"542692cbc026201cdc326c2c"},{"author":{"login":"jamesqiu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bc1268deaa7f2e78fe2b5ea76e6481d8?r=PG&default=identicon"},"editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/974443?v=4","account-source":"github","login":"daveliepmann"}],"body":"(def x [{:foo 2 :bar 11}\n {:bar 99 :foo 1}\n {:bar 55 :foo 2}\n {:foo 1 :bar 77}])\n\n; sort-by given key order (:bar)\n(def order [55 77 99 11])\n(sort-by \n #((into {} (map-indexed (fn [i e] [e i]) order)) (:bar %)) \n x)\n;=> ({:bar 55, :foo 2} \n {:foo 1, :bar 77} \n {:bar 99, :foo 1} \n {:foo 2, :bar 11})","created-at":1313489274000,"updated-at":1706889697623,"_id":"542692cbc026201cdc326c2f"},{"author":{"login":"Yogthos","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a2640fb40f901598b3789ac2f5c5b701?r=PG&default=identicon"},"editors":[{"login":"Yogthos","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a2640fb40f901598b3789ac2f5c5b701?r=PG&default=identicon"}],"body":";sort entries in a map by value\nuser=> (sort-by val > {:foo 7, :bar 3, :baz 5})\n([:foo 7] [:baz 5] [:bar 3])","created-at":1327752237000,"updated-at":1327752286000,"_id":"542692d5c026201cdc327090"},{"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":";; Warning: You can sort a Java array and get back a sorted immutable Clojure\n;; data structure, but it will also change the input Java array, by sorting it.\n;; Copy the array before sorting if you want to avoid this.\n\nuser=> (def x (to-array [32 -5 4 11]))\n#'user/x\n\nuser=> (seq x)\n(32 -5 4 11)\n\nuser=> (def y (sort-by - x))\n#'user/y\n\n;; Return sorted sequence\nuser=> y\n(32 11 4 -5)\n\n;; but also modifies x, because it used the array to do the sorting.\nuser=> (seq x)\n(32 11 4 -5)\n\n;; One way to avoid this is copying the array before sorting:\nuser=> (def y (sort-by - (aclone x)))\n#'user/y","created-at":1331771914000,"updated-at":1332833698000,"_id":"542692d5c026201cdc327092"},{"body":";;; from the joy of clojure 2nd\n;;; function as arguments\n\n(def plays [{:band \"Burial\", :plays 979, :loved 9}\n {:band \"Eno\", :plays 2333, :loved 15}\n {:band \"Bill Evans\", :plays 979, :loved 9}\n {:band \"Magma\", :plays 2665, :loved 31}])\n\n(def sort-by-loved-ratio (partial sort-by #(/ (:plays %) (:loved %))))\n\n(sort-by-loved-ratio plays)\n\n;=> ({:band \"Magma\", :plays 2665, :loved 31}\n {:band \"Burial\", :plays 979, :loved 9}\n {:band \"Bill Evans\", :plays 979, :loved 9}\n {:band \"Eno\", :plays 2333, :loved 15})\n\n\n;;; others.\n(sort-by second [[:a 7], [:c 13], [:b 21]])\n;;=> ([:a 7] [:c 13] [:b 21])\n\n(sort-by str [\"z\" \"x\" \"a\" \"aa\" 1 5 8])\n;;=> (1 5 8 \"a\" \"aa\" \"x\" \"z\")\n\n(sort-by :age [{:age 99}, {:age 13}, {:age 7}])\n;;=> ({:age 7} {:age 13} {:age 99})","author":{"login":"foxlog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/150418?v=3"},"created-at":1429710293523,"updated-at":1429710293523,"_id":"5537a5d5e4b033f34014b770"},{"updated-at":1551027269645,"created-at":1471045254496,"author":{"login":"egracer","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/4086884?v=3"},"body":";; you can pass a comparator to specify the order to sort in\n\n;; typical sort, low to high\n(sort-by :value [{:value 1 :label \"a\"} {:value 3 :label \"c\"} {:value 2 :label \"b\"}])\n;=> ({:value 1, :label \"a\"} {:value 2, :label \"b\"} {:value 3, :label \"c\"})\n\n;; override the default comparator to sort high to low\n(sort-by :value #(> %1 %2) [{:value 1 :label \"a\"} {:value 3 :label \"c\"} {:value 2 :label \"b\"}])\n;=> ({:value 3 :label \"c\"} {:value 2, :label \"b\"} {:value 1, :label \"a\"})\n\n;; sort-by behavior when :value is absent\n(sort-by :value [{:value 1 :label \"a\"} {:label \"c\"} {:value 2 :label \"b\"}])\n=> ({:label \"c\"} {:value 1, :label \"a\"} {:value 2, :label \"b\"})\n\n;; now if you provide custom comparator when :value is absent you will get NullPointerException\n(sort-by :value #(> %1 %2) [{:value 1 :label \"a\"} {:label \"c\"} {:value 2 :label \"b\"}])\n=> Execution error (NullPointerException) at user/eval1515$fn (form-init71750676547201835.clj:1).\nnull\n\n;; make above working by simple or; considering absence of \"value\" as invaluable or highest value :)\n(sort-by :value #(> (or %1 Integer/MAX_VALUE) (or %2 Integer/MAX_VALUE)) [{:value 1 :label \"a\"} {:label \"c\"} {:value 2 :label \"b\"}])\n=> ({:label \"c\"} {:value 2, :label \"b\"} {:value 1, :label \"a\"})","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/4086884?v=3","account-source":"github","login":"egracer"},{"login":"gautamr","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/70894?v=4"}],"_id":"57ae5e86e4b0bafd3e2a04f1"},{"editors":[{"login":"overset","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/34342?v=3"}],"body":";; to sort by nested hash-map values\n;; with the help of get-in and custom comparator\n\n> (sort-by #(get-in (val %) [:price]) {:chair {:price 10} :table {:price 9} :lamp {:price 9}})\n;;=> ([:table {:price 9}] [:lamp {:price 9}] [:chair {:price 10}])\n","author":{"avatar-url":"https://avatars.githubusercontent.com/u/34342?v=3","account-source":"github","login":"overset"},"created-at":1488583557264,"updated-at":1488842435985,"_id":"58b9fb85e4b01f4add58fe69"},{"updated-at":1557361208644,"created-at":1557361208644,"author":{"login":"fdhenard","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/884972?v=4"},"body":";; sort-by descending (reverse)\n\nuser=> (sort-by :rank #(compare %2 %1) [{:rank 2} {:rank 3} {:rank 1}])\n({:rank 3} {:rank 2} {:rank 1})","_id":"5cd37238e4b0ca44402ef71d"},{"editors":[{"login":"cgaustin","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/16307176?v=4"}],"body":";; Warning: sort-by will not apply the keyfn on coll's of length 1\n\nuser=> (sort-by (fn [i] (nth i) 4) [[1 2 3]])\n([1 2 3])\n\nuser=> (nth [1 2 3] 4)\n; IndexOutOfBoundsException clojure.lang.PersistentVector.arrayFor (PersistentVector.java:158)...","author":{"avatar-url":"https://avatars2.githubusercontent.com/u/16307176?v=4","account-source":"github","login":"cgaustin"},"created-at":1602184227139,"updated-at":1602184337489,"_id":"5f7f6423e4b0b1e3652d73cf"},{"editors":[{"login":"naxels","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/3195443?v=4"}],"body":";; Using comp as a way to sort descending\n(def unordered '({:created_at 1612637437}\n {:created_at 1610998684}\n {:created_at 1622245799}))\n\n(sort-by (comp - :created_at) unordered)\n;;=> ({:created_at 1622245799} {:created_at 1612637437} {:created_at 1610998684})\n\n;; Note: using the negative - as a comparator won't work\n;; so you need to combine the functions\n;; same example without comp:\n(sort-by #(- (:created_at %)) unordered)\n;;=> ({:created_at 1622245799} {:created_at 1612637437} {:created_at 1610998684})","author":{"avatar-url":"https://avatars.githubusercontent.com/u/3195443?v=4","account-source":"github","login":"naxels"},"created-at":1622382371391,"updated-at":1622382870076,"_id":"60b39723e4b0b1e3652d7504"},{"updated-at":1743452569601,"created-at":1743452569601,"author":{"login":"arcanjoaq","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1619912?v=4"},"body":";; Using a comparator to compare LocalDateTime\n(def to-be-sorted\n [{:time (java.time.LocalDateTime/parse \"2025-01-29T11:26:00\")}\n {:time (java.time.LocalDateTime/parse \"2025-01-29T11:27:00\")}\n {:time (java.time.LocalDateTime/parse \"2025-01-29T11:23:00\")}])\n\n;; sort asc\n(sort-by :time to-be-sorted)\n\n;; sort desc\n(sort-by :time #(.compareTo %2 %1) to-be-sorted)","_id":"67eaf999cd84df5de54e2085"}],"notes":null,"arglists":["keyfn coll","keyfn comp coll"],"doc":"Returns a sorted sequence of the items in coll, where the sort\n order is determined by comparing (keyfn item). If no comparator is\n supplied, uses compare. comparator must implement\n java.util.Comparator. Guaranteed to be stable: equal elements will\n not be reordered. If coll is a Java array, it will be modified. To\n avoid this, sort a copy of the array.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/sort-by"},{"added":"1.0","ns":"clojure.core","name":"macroexpand","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1284957731000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"macroexpand-1","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d2e"},{"created-at":1304099187000,"author":{"login":"pauldoo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5cb916d3c8abc9f45a093209e72489fb?r=PG&default=identicon"},"to-var":{"ns":"clojure.walk","name":"macroexpand-all","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d2f"}],"line":4052,"examples":[{"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"editors":[],"body":";; It is useful to combine macroexpand with pprint as the\n;; default output can be hard to read.\nuser=> (clojure.pprint/pprint (macroexpand '(time (print \"timing\"))))\n(let*\n [start__3917__auto__\n (. java.lang.System (clojure.core/nanoTime))\n ret__3918__auto__\n (print \"timing\")]\n (clojure.core/prn\n (clojure.core/str\n \"Elapsed time: \"\n (clojure.core//\n (clojure.core/double\n (clojure.core/-\n (. java.lang.System (clojure.core/nanoTime))\n start__3917__auto__))\n 1000000.0)\n \" msecs\"))\n ret__3918__auto__)\n\n;; Even after pretty printing you may benefit from some\n;; manual cleanup.\n\n;; Also worth noting that most of the time macroexpand-1 is\n;; a better alternative to avoid over expanding down too \n;; many levels.","created-at":1286272649000,"updated-at":1286272649000,"_id":"542692ccc026201cdc326c5e"},{"author":{"login":"BertrandDechoux","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3"},"editors":[{"login":"raxod502","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/6559064?v=3"}],"body":"user=> (macroexpand '(-> c (+ 3) (* 2))) \n(* (+ c 3) 2)\n","created-at":1339248908000,"updated-at":1457991523840,"_id":"542692d4c026201cdc326ff9"}],"notes":null,"arglists":["form"],"doc":"Repeatedly calls macroexpand-1 on form until it no longer\n represents a macro form, then returns it. Note neither\n macroexpand-1 nor macroexpand expand macros in subforms.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/macroexpand"},{"added":"1.0","ns":"clojure.core","name":"ensure","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1299215930000,"author":{"login":"TimMc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5d532e51427ef2f4ded31aaca16c8baf?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"commute","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bfa"},{"created-at":1299215941000,"author":{"login":"TimMc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5d532e51427ef2f4ded31aaca16c8baf?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"ref-set","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bfb"},{"created-at":1364879934000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"ref","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bfc"},{"created-at":1371688442000,"author":{"login":"juan.facorro","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d6f59d93cc17c698f16e550034a2d1ad?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"alter","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bfd"}],"line":2505,"examples":[{"updated-at":1553541533678,"created-at":1553536468220,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"body":";; Count votes to elect the favorite color.\n;; Batches of votes are processed concurrently using a map of shared refs.\n;; The competition stops immediately if there are more than 3 \"honeypots\" votes.\n;; \"ensure\" ensures other transactions cannot change the honeypot count,\n;; guaranteeing no votes are counted after a possible fraud.\n\n(def colors\n {:blue (ref 0)\n :green (ref 0)\n :red (ref 0)\n :honeypots (ref 0)})\n\n(defn batch [prefs]\n (future\n (dosync\n (ensure (:honeypots colors))\n (doseq [color prefs\n :while (< @(:honeypots colors) 3)]\n (update colors color commute inc)))))\n\n(let [b1 (batch [:red :honeypots :green :blue :blue :red :honeypots])\n b2 (batch [:green :blue :blue :green :red :blue :red :red])\n b3 (batch [:honeypots :blue :red :red :blue :green :green :red])]\n [@b1 @b2 @b3]\n {:total-votes (reduce + (map deref (vals colors)))\n :winner (ffirst (sort-by (comp deref second) > colors))\n :fraud? (= @(:honeypots colors) 3)})\n\n;; {:total-votes 16, :winner :blue, :fraud? true}","editors":[{"avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"}],"_id":"5c9915d4e4b0ca44402ef6c2"}],"notes":[{"updated-at":1299280980000,"body":"This is for preventing [write skew](http://clojure.higher-order.net/?p=50), which Clojure's concurrency model is susceptible to. If you have a transaction where several refs' values must remain in some consistent relationship to each other, but you are only writing to some of them, you should use ensure on the other refs to prevent other transactions from writing to them in the meantime.","created-at":1299215917000,"author":{"login":"TimMc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5d532e51427ef2f4ded31aaca16c8baf?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fb6"},{"author":{"login":"glts","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/1483271?v=4"},"updated-at":1574323395658,"created-at":1574323395658,"body":"The doc string says:\n\n> Allows for more concurrency than (ref-set ref @ref)\n\nWhat it doesn’t say is that `ensure` may degrade performance very seriously, as\nit is prone to livelock: see\n[CLJ-2301](https://clojure.atlassian.net/projects/CLJ/issues/CLJ-2301).\n`(ref-set ref @ref)` is certainly more reliable than `(ensure ref)`.\n","_id":"5dd644c3e4b0ca44402ef7e1"}],"arglists":["ref"],"doc":"Must be called in a transaction. Protects the ref from modification\n by other transactions. Returns the in-transaction-value of\n ref. Allows for more concurrency than (ref-set ref @ref)","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/ensure"},{"ns":"clojure.core","name":"chunk-first","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1443934291486,"author":{"login":"devn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"chunk-next","ns":"clojure.core"},"_id":"5610b053e4b08e404b6c1c93"},{"created-at":1443934297249,"author":{"login":"devn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"chunk-rest","ns":"clojure.core"},"_id":"5610b059e4b0686557fcbd44"}],"line":703,"examples":[{"updated-at":1443934874463,"created-at":1443934874463,"author":{"login":"devn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3"},"body":"(let [chunked-cons (seq (range 1 42))\n first-chunk (chunk-first chunked-cons)]\n\n (class chunked-cons)\n ;; => clojure.lang.ChunkedCons\n\n (class first-chunk)\n ;; clojure.lang.ArrayChunk\n\n ;; Demonstrating chunk size of 32.\n (.nth first-chunk 0)\n ;; => 1\n (.nth first-chunk 31)\n ;; => 32\n)","_id":"5610b29ae4b08e404b6c1c94"}],"notes":null,"tag":"clojure.lang.IChunk","arglists":["s"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core/chunk-first"},{"added":"1.7","ns":"clojure.core","name":"eduction","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1496674622028,"author":{"login":"vspinu","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/1363467?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"transduce","ns":"clojure.core"},"_id":"5935713ee4b06e730307db2a"},{"created-at":1496674683706,"author":{"login":"vspinu","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/1363467?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"reduce","ns":"clojure.core"},"_id":"5935717be4b06e730307db2b"},{"created-at":1496674762346,"author":{"login":"vspinu","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/1363467?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"reductions","ns":"clojure.core"},"_id":"593571cae4b06e730307db2c"},{"created-at":1520634073209,"author":{"login":"glts","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/1483271?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"sequence","ns":"clojure.core"},"_id":"5aa308d9e4b0316c0f44f918"}],"line":7886,"examples":[{"editors":[{"login":"freckletonj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8399149?v=3"},{"login":"JoshAaronJones","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/19951591?v=3"},{"avatar-url":"https://avatars0.githubusercontent.com/u/1363467?v=3","account-source":"github","login":"vspinu"},{"login":"Bost","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/1174677?v=4"}],"body":";; `eduction` calls the stack of transformers on each element, each time.\n;; `->>` calls the transformer named 'left' on a collection, then the transformer\n;; named 'right' on the result, etc.\n\n(def cnt (atom nil))\n\n;; inc with debugging output\n(defn inc-with-print [fn-id coll-idx x]\n (printf \";; fn-id: %s; coll-idx: %s; cnt: %s; x: %s\\n\" fn-id coll-idx @cnt x)\n (swap! cnt inc)\n (inc x))\n\n(reset! cnt 0)\n(eduction\n (map-indexed (fn [coll-idx x] (inc-with-print \" left\" coll-idx x)))\n (map-indexed (fn [coll-idx x] (inc-with-print \"right\" coll-idx x)))\n (range 3))\n\n;; fn-id: left; coll-idx: 0; cnt: 0; x: 0\n;; fn-id: right; coll-idx: 0; cnt: 1; x: 1\n;; fn-id: left; coll-idx: 1; cnt: 2; x: 1\n;; fn-id: right; coll-idx: 1; cnt: 3; x: 2\n;; fn-id: left; coll-idx: 2; cnt: 4; x: 2\n;; fn-id: right; coll-idx: 2; cnt: 5; x: 3\n;;=> (2 3 4)\n\n(reset! cnt 0)\n(->> (range 3)\n (map-indexed (fn [coll-idx x] (inc-with-print \" left\" coll-idx x)))\n (map-indexed (fn [coll-idx x] (inc-with-print \"right\" coll-idx x))))\n\n;; fn-id: left; coll-idx: 0; cnt: 0; x: 0\n;; fn-id: left; coll-idx: 1; cnt: 1; x: 1\n;; fn-id: left; coll-idx: 2; cnt: 2; x: 2\n;; fn-id: right; coll-idx: 0; cnt: 3; x: 1\n;; fn-id: right; coll-idx: 1; cnt: 4; x: 2\n;; fn-id: right; coll-idx: 2; cnt: 5; x: 3\n;;=> (2 3 4)","author":{"avatar-url":"https://avatars.githubusercontent.com/u/17842?v=3","account-source":"github","login":"ghiden"},"created-at":1452742324167,"updated-at":1608819387090,"_id":"569716b4e4b060004fc217ad"},{"editors":[{"login":"freckletonj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8399149?v=3"},{"login":"JoshAaronJones","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/19951591?v=3"}],"body":";; eduction: just run an xform over a collection\n\n(eduction (map inc) [1 2 3]) ; => (2 3 4)\n(eduction (filter even?) (range 5)) ; => (0 2 4)\n\n;; several transducers can be given, without using 'comp'\n(eduction (filter even?) (map inc)\n (range 5)) ; => (1 3 5)\n\n","author":{"avatar-url":"https://avatars.githubusercontent.com/u/8399149?v=3","account-source":"github","login":"freckletonj"},"created-at":1480456257096,"updated-at":1485277360753,"_id":"583df841e4b0782b632278cd"},{"updated-at":1483046915116,"created-at":1483046915116,"author":{"login":"jvanderhyde","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/6516608?v=3"},"body":";; This will run out of memory eventually,\n;; because the entire seq is realized, \n;; because the head of the lazy seq is retained.\n(let \n [s (range 100000000)] \n (do (apply print s) (first s)))\n\n;; This iterates through the lazy seq without realizing the seq.\n(let \n [s (eduction identity (range 100000000))] \n (do (apply print s) (first s)))\n\n","_id":"58658003e4b0fd5fb1cc964c"},{"editors":[{"login":"vspinu","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/1363467?v=3"},{"avatar-url":"https://avatars0.githubusercontent.com/u/1174677?v=4","account-source":"github","login":"Bost"},{"login":"jngbng","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/552977?v=4"}],"body":";; Result of eduction is of the `clojure.core.Eduction` type which acts as a\n;; lazy collection that re-executes all the steps again and again. This could be\n;; useful when you don't want to store the collection separately.\n;;\n;; Eductions can be efficiently used with `reduce` and `transduce`.\n\n(defn inc-with-print [x]\n (println \";;\" x)\n (inc x))\n\n(def ed (eduction (map inc-with-print) (map inc-with-print) (range 3)))\n\n(defn identity-with-print [x]\n (println \"identity:\" x)\n x)\n\n(map identity-with-print ed)\n;; 0\n;; 1\n;; 1\n;; 2\n;; 2\n;; 3\n;; identity: 2\n;; identity: 3\n;; identity: 4\n;; => (2 3 4)\n\n(defn sum-with-print [x y]\n (println \"sum:\" x \"+\" y)\n (+ x y))\n\n(reduce sum-with-print ed)\n;; 0\n;; 1\n;; 1\n;; 2\n;; sum: 2 + 3\n;; 2\n;; 3\n;; sum: 5 + 4\n;; => 9\n\n;; The above line does not work in Clojure 1.10.1\n;; Execution error (ClassCastException) at user/eval193 (REPL:1).\n;; clojure.core.Eduction cannot be cast to clojure.lang.IReduce\n\n\n(transduce (map identity-with-print) + ed)\n;; 0\n;; 1\n;; identity: 2\n;; 1\n;; 2\n;; identity: 3\n;; 2\n;; 3\n;; identity: 4\n;; => 9\n","author":{"avatar-url":"https://avatars0.githubusercontent.com/u/1363467?v=3","account-source":"github","login":"vspinu"},"created-at":1496674440865,"updated-at":1633576431878,"_id":"59357088e4b06e730307db26"},{"editors":[{"login":"onionpancakes","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/639985?v=4"}],"body":";; Converting from seqs to transducers is trivial with eduction.\n\n(->> (range 100) ; <- coll source\n (map inc)\n (remove odd?)\n (reduce + 0)) ; <- reduction target\n\n;; Refactor by placing an eduction in the middle.\n\n(->> (range 100)\n (eduction (map inc)\n (remove odd?))\n (reduce + 0)) ; => 2550\n\n;; Because Eduction type implements clojure.lang.IReduceInit,\n;; and its reduce implementation calls transduce,\n;; it is equivalent to this.\n\n(transduce (comp (map inc) (remove odd?)) + 0 (range 100)) ; => 2550\n\n;; So long as the target is a reduce, or is implemented by reduce,\n;; transduce will be called. It is a good idea to use clojure.repl/source\n;; to check.\n\n(source mapv)\n\n;; Examples functions implemented by reduce include:\n;; - into\n;; - mapv\n;; - filterv\n;; - frequencies\n;; - group-by\n;; - run!\n\n;; Since Eduction calls transduce on the given coll,\n;; for maximum performance, the coll passed to eduction should\n;; ideally implement clojure.lang.IReduceInit.\n;; Having both a clojure.lang.IReduceInit coll and a reduce target\n;; cause the reduce to be executed on the internal fast path.\n;; It is a good idea to verify with the instance? function.\n\n(instance? clojure.lang.IReduceInit (range 100)) ; => true\n\n;; Example clojure.lang.IReduceInit types include:\n;; - range\n;; - vector\n;; - iterate\n;; - eduction","author":{"avatar-url":"https://avatars.githubusercontent.com/u/639985?v=4","account-source":"github","login":"onionpancakes"},"created-at":1706956793157,"updated-at":1706989734012,"_id":"65be17f969fbcc0c2261749c"},{"updated-at":1708402273803,"created-at":1708402135061,"author":{"login":"onionpancakes","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/639985?v=4"},"body":";; Use eduction within mapcat transducers\n;; to avoid intermediate allocations.\n\n(->> [1 2 2 2 3 4 4 4 4 5 5]\n (eduction (partition-by identity)\n (mapcat (fn [nums]\n ;; This makes a intermediate vector!\n (into [] (map #(* (count nums) %)) nums))))\n (vec))\n;; => [1 6 6 6 3 16 16 16 16 10 10]\n\n;; Refactor using eduction inside mapcat instead!\n\n(->> [1 2 2 2 3 4 4 4 4 5 5]\n (eduction (partition-by identity)\n (mapcat (fn [nums]\n ;; Allocates a cheaper intermediate eduction\n ;; in place of a collection\n (eduction (map #(* (count nums) %)) nums))))\n (vec))\n;; => [1 6 6 6 3 16 16 16 16 10 10]\n\n;; This works because cat (and by extension mapcat) is implemented with reduce.\n;; See the source\n\n(source cat)\n\n;; In general, pass IReduceInit types into cat transducers for maximum performance.\n;; Use eduction in particular to create a non-coll-allocating IReduceInit.\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/639985?v=4","account-source":"github","login":"onionpancakes"}],"_id":"65d425d769fbcc0c226174a1"}],"notes":[{"author":{"login":"glts","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/1483271?v=4"},"updated-at":1520634037505,"created-at":1520634037505,"body":"`eduction` is particularly useful as an adapter for collection-processing functions that don’t have a transducers arity. For example, you might want to transform a collection before passing it to `frequencies`. `eduction` makes that possible and efficient:\n\n
\n(->> coll\n     (eduction (map #(quot % 5))\n               (filter odd?))\n     frequencies)\n
\n\nSo `eduction` turns out to be quite powerful in that it brings the benefits of transducers to all collection-processing functions, even those that predate transducers: `first`, `last`, `group-by`, `run!`, `str/join`, …\n","_id":"5aa308b5e4b0316c0f44f917"},{"author":{"login":"glts","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/1483271?v=4"},"updated-at":1520634630501,"created-at":1520634630501,"body":"Interesting background about `sequence` versus `eduction`: https://groups.google.com/d/msg/clojure/9I6MtgOTD0w/NiG5PimBCP8J","_id":"5aa30b06e4b0316c0f44f919"},{"body":"`eduction` does not cache the result while `sequence` does. `eduction` is intended to be used when you are eventually going to `reduce` over the sequence.\n\nhttps://groups.google.com/d/msg/clojure/9I6MtgOTD0w/NiG5PimBCP8J","created-at":1577794782807,"updated-at":1577824559009,"author":{"avatar-url":"https://avatars0.githubusercontent.com/u/705227?v=4","account-source":"github","login":"Hindol"},"_id":"5e0b3cdee4b0ca44402ef803"}],"arglists":["xform* coll"],"doc":"Returns a reducible/iterable application of the transducers\n to the items in coll. Transducers are applied in order as if\n combined with comp. Note that these applications will be\n performed every time reduce/iterator is called.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/eduction"},{"added":"1.0","ns":"clojure.core","name":"tree-seq","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1454531860990,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"walk","ns":"clojure.walk"},"_id":"56b26514e4b060004fc217bb"},{"created-at":1519124143092,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"file-seq","ns":"clojure.core"},"_id":"5a8bfeafe4b0316c0f44f8d5"}],"line":4984,"examples":[{"updated-at":1454531766626,"created-at":1280776531000,"body":";; Each node is a number or a seq, \n;; so branch?==seq? and children==identity\n;; \n;; .\n;; / \\\n;; . .\n;; /|\\ |\n;; 1 2 . 4\n;; | \n;; 3\n;;\n;; ... each sub-tree is serialized in depth-first order\n(tree-seq seq? identity '((1 2 (3)) (4)))\n\n;;=> (((1 2 (3)) (4)) \n;; (1 2 (3)) \n;; 1 \n;; 2 \n;; (3) \n;; 3 \n;; (4) \n;; 4)\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"avatar-url":"https://www.gravatar.com/avatar/4b71cdf53bc76edd1a2ab66c446954b5?r=PG&default=identicon","account-source":"clojuredocs","login":"algal"},{"avatar-url":"https://www.gravatar.com/avatar/4b71cdf53bc76edd1a2ab66c446954b5?r=PG&default=identicon","account-source":"clojuredocs","login":"algal"},{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3","account-source":"github","login":"phreed"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3","account-source":"github","login":"devn"},"_id":"542692ccc026201cdc326c82"},{"updated-at":1454531340455,"created-at":1321413864000,"body":"(tree-seq map? #(interleave (keys %) (vals %)) {:a 1 :b {:c 3 :d 4 :e {:f 6 :g 7}}})\n;;=> ({:a 1, :b {:c 3, :d 4, :e {:f 6, :g 7}}} \n;; :a 1 :b {:c 3, :d 4, :e {:f 6, :g 7}} \n;; :c 3 :d 4 :e {:f 6, :g 7} \n;; :f 6 :g 7)","editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/d790f5851d80da498e475ece4487e92?r=PG&default=identicon","account-source":"clojuredocs","login":"patazj"},"_id":"542692d5c026201cdc3270aa"},{"updated-at":1454530812433,"created-at":1321841153000,"body":";; Each node is a (node-root child1 child2 ...),\n;; so branch?==next and children==rest\n;;\n;; A\n;; / \\\n;; B C\n;; / \\ |\n;; D E F\n;;\n(map first (tree-seq next rest '(:A (:B (:D) (:E)) (:C (:F)))))\n;;=> (:A :B :D :E :C :F)","editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/4b71cdf53bc76edd1a2ab66c446954b5?r=PG&default=identicon","account-source":"clojuredocs","login":"algal"},"_id":"542692d5c026201cdc3270ab"},{"author":{"login":"gregginca","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bad5f5cb177b0968d4288596691ec3cd?r=PG&default=identicon"},"editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3","account-source":"github","login":"phreed"}],"body":";; The previous example seems to be a flatten function,\n;; where every node's value is added to the returned sequence\n;; as it is visited in a depth first search.\n;; That is not the case as the following example illustrates: \n;; *\n;; / \\\n;; * 4\n;; /|\\\n;; 1 2 *\n;; |\n;; 3\n(map first (tree-seq next rest '((1 2 (3)) (4))))\n;;=> ((1 2 (3)) 4)\n\n;; For a proper 'flatten' function see below.","created-at":1334020823000,"updated-at":1454531099621,"_id":"542692d5c026201cdc3270ac"},{"updated-at":1471103831802,"created-at":1335429840000,"body":";; The nodes are filtered based on their collection type, \n;; here they must be a list.\n(tree-seq seq? seq [[1 2 [3]] [4]])\n;;=> ([[1 2 [3]] [4]])\n\n;; notice the difference between seq? and sequential?\n(tree-seq sequential? seq [[1 2 [3]] [4]])\n;;=> ([[1 2 [3]] [4]] [1 2 [3]] 1 2 [3] 3 [4] 4)\n\n;; If the nodes in the tree are a specific type of collection...\n;; a vector\n(tree-seq vector? seq [[1 2 [3]] [4]])\n([[1 2 [3]] [4]] [1 2 [3]] 1 2 [3] 3 [4] 4)\n\n;; ... or a list\n(tree-seq seq? seq '((1 2 (3)) (4)))\n(((1 2 (3)) (4)) (1 2 (3)) 1 2 (3) 3 (4) 4)\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3","account-source":"github","login":"phreed"},{"login":"bbakersmith","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1828358?v=3"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3","account-source":"github","login":"devn"},"_id":"542692d5c026201cdc3270ad"},{"editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/89076?v=3","account-source":"github","login":"shark8me"},{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"}],"updated-at":1519124120018,"created-at":1423128977650,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/89076?v=3","account-source":"github","login":"shark8me"},"body":";; Use tree-seq to recursively find all files \n;; given a root directory (here for didactic purposes. See file-seq)\n(let [directory (clojure.java.io/file \"/path/to/directory/\")\n dir? #(.isDirectory %)]\n ;we want only files, therefore filter items that are not directories.\n (filter (comp not dir?) \n (tree-seq dir? #(.listFiles %) directory)))","_id":"54d33991e4b0e2ac61831d15"},{"editors":[{"login":"zackteo","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/7510179?v=4"}],"body":"\n(def t '((1 2 (3)) (4)))\n;;=> #'user/t\n\n;; Here the tree-seq uses 'sequential?' as the 'branch?' predicate.\n;; This causes the 'children' function to run for any collection.\n;; The 'seq' ('children') function recurses on all items in the collection.\n;; This results in a sequence of sub-trees, rooted at each node.\n(tree-seq sequential? seq t)\n;;=> (((1 2 (3)) (4))\n;; (1 2 (3)) 1 2 \n;; (3) 3 (4) 4)\n\n;; (The following example is from 4Clojure)\n;; It returns the leaves of a tree as a sequence.\n;; \n(defn flatten [x]\n (filter (complement sequential?)\n (rest (tree-seq sequential? seq x))))\n(flatten t)\n;;=> (1 2 3 4)\n","author":{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3","account-source":"github","login":"phreed"},"created-at":1454529390718,"updated-at":1603927166586,"_id":"56b25b6ee4b060004fc217b6"},{"updated-at":1503909100023,"created-at":1503908769269,"author":{"login":"MokkeMeguru","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/30849444?v=4"},"body":"(tree-seq seq? identity '(1 2 (3 (4))))\n;; ((1 2 (3 (4))) 1 2 (3 (4)) 3 (4) 4)\n\n;; It's same as ...\n(tree-seq seq? seq '(1 2 (3 (4))))\n(tree-seq sequential? seq '(1 2 (3 (4))))\n;; ((1 2 (3 (4))) 1 2 (3 (4)) 3 (4) 4)\n\n;; This processing ...\n(sequential? '(1 2 (3 (4)))) ;; returns true ... -> (1 2 (3 (4))) <--- !!!\n(sequential? 1) ;; returns false ... -> 1\n(sequential? 2) ;; returns false ... -> 2\n(sequential? '(3 (4)) ;; returns true ... -> (3 (4)) <--- !!! \n(sequential? 3) ;; returns false ... -> 3\n(sequential? '(4)) ;; returns true ... -> (4) <--- !!!\n(sequential? 4) ;; return false ... -> 4\n\n;; so, #tree-seq returns...\n;; ((1 2 (3 (4))) 1 2 (3 (4)) 3 (4) 4)","editors":[{"avatar-url":"https://avatars2.githubusercontent.com/u/30849444?v=4","account-source":"github","login":"MokkeMeguru"}],"_id":"59a3d3a1e4b09f63b945ac54"},{"editors":[{"login":"kovasap","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8763010?v=4"}],"body":";; When traversing a map tree, it's sometimes useful to have a back-reference\n;; to the parent. This tree-seq variant provides that.\n\n(defn tree-seq-adding-parent\n \"Like tree-seq, but takes in a tree of maps and a unique :parent key to each map.\"\n [branch? children root]\n (let [walk (fn walk [parent node]\n (lazy-seq\n (cons (assoc node :parent parent)\n (when (branch? node)\n (mapcat (partial walk node) (children node))))))]\n (walk nil root)))\n\n(def map-tree\n {:name \"root\"\n :children [{:name \"child1\"\n :children [{:name \"grandchild1\"}\n {:name \"grandchild2\"}]}\n {:name \"child2\"}]})\n\n(tree-seq-adding-parent associative? :children map-tree)\n;; =>\n;; ({:name \"root\",\n;; :children\n;; [{:name \"child1\",\n;; :children [{:name \"grandchild1\"} {:name \"grandchild2\"}]}\n;; {:name \"child2\"}],\n;; :parent nil\n;; {:name \"child1\",\n;; :children [{:name \"grandchild1\"} {:name \"grandchild2\"}],\n;; :parent\n;; {:name \"root\",\n;; :children\n;; [{:name \"child1\",\n;; :children [{:name \"grandchild1\"} {:name \"grandchild2\"}]}\n;; {:name \"child2\"}]}}\n;; {:name \"grandchild1\",\n;; :parent\n;; {:name \"child1\",\n;; :children [{:name \"grandchild1\"} {:name \"grandchild2\"}]}}\n;; {:name \"grandchild2\",\n;; :parent\n;; {:name \"child1\",\n;; :children [{:name \"grandchild1\"} {:name \"grandchild2\"}]}}\n;; {:name \"child2\",\n;; :parent\n;; {:name \"root\",\n;; :children\n;; [{:name \"child1\",\n;; :children [{:name \"grandchild1\"} {:name \"grandchild2\"}]}\n;; {:name \"child2\"}]}})\n\n","author":{"avatar-url":"https://avatars.githubusercontent.com/u/8763010?v=4","account-source":"github","login":"kovasap"},"created-at":1652035527222,"updated-at":1652035548192,"_id":"62780fc7e4b0b1e3652d75ea"},{"updated-at":1698404778459,"created-at":1698404778459,"author":{"login":"jacobmendoza","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2363912?v=4"},"body":";; Tree-seq uses depth-first search (DFS), pre-order traversal, to explore the \n;; tree. \n;;\n;; 1\n;; / \\\n;; 2 3\n;; | \n;; 4\n;; |\n;; 5\n\n(let [tree {:value 1 \n :children [{:value 2\n :children [{:value 4\n :children [{:value 5}]}]}\n {:value 3}]}]\n (map :value\n (tree-seq\n #(contains? % :children) ;branch?\n #(get % :children) ;children\n tree)))\n\n=> (1 2 4 5 3)\n","_id":"653b99aa69fbcc0c226173f4"}],"notes":[{"body":"The 'branch?' and 'children' functions perform different types of filtering.\nThe 'branch?' function examines a node and determines whether there are children that need to be included in the processing.\nThe 'children' function selects (or generates) the children to be included in the returned sequence.","created-at":1454529614571,"updated-at":1508445428109,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3","account-source":"github","login":"phreed"},"_id":"56b25c4ee4b0ceed88ce8d21"},{"author":{"login":"lostdiaspora","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/4893998?v=3"},"updated-at":1462851110244,"created-at":1462851110244,"body":"Example 5 has for the second example \n(tree-seq seq? seq [[1 2 [3]] [4]])\nwhen it should be \n(tree-seq sequential? seq [[1 2 [3]] [4]])","_id":"57315626e4b012fa59bdb2ed"}],"arglists":["branch? children root"],"doc":"Returns a lazy sequence of the nodes in a tree, via a depth-first walk.\n branch? must be a fn of one arg that returns true if passed a node\n that can have children (but may not). children must be a fn of one\n arg that returns a sequence of the children. Will only be called on\n nodes for which branch? returns true. Root is the root node of the\n tree.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/tree-seq"},{"added":"1.0","ns":"clojure.core","name":"unchecked-remainder-int","file":"clojure/core.clj","type":"function","column":1,"see-alsos":null,"line":1254,"examples":null,"notes":null,"arglists":["x y"],"doc":"Returns the remainder of division of x by y, both int.\n Note - uses a primitive operator subject to truncation.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/unchecked-remainder-int"},{"added":"1.0","ns":"clojure.core","name":"seq","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1323104884000,"author":{"login":"mmwaikar","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/29d36f4c9f39c9f8ff61c07033b13118?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"seq?","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f01"},{"created-at":1350272113000,"author":{"login":"dansalmo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e33ee460f5f61bc5ba9b598934766215?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"empty?","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f02"},{"created-at":1398980077000,"author":{"login":"ryo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3f7913b563c72083c74030d928ba407e?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"iterator-seq","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f03"},{"created-at":1495638720841,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"seqable?","ns":"clojure.core"},"_id":"5925a2c0e4b093ada4d4d727"},{"created-at":1550706027921,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"sequential?","ns":"clojure.core"},"_id":"5c6de56be4b0ca44402ef69d"},{"created-at":1550706149555,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"sequence","ns":"clojure.core"},"_id":"5c6de5e5e4b0ca44402ef69e"}],"line":128,"examples":[{"updated-at":1552553839711,"created-at":1280777400000,"body":"(seq '(1)) ;;=> (1)\n(seq [1 2]) ;;=> (1 2)\n(seq \"abc\") ;;=> (\\a \\b \\c)\n\n;; Corner cases\n(seq nil) ;;=> nil\n(seq '()) ;;=> nil\n(seq []) ;;=> nil\n(seq \"\") ;;=> nil","editors":[{"login":"devn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3"},{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3","account-source":"github","login":"phreed"},{"avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3","account-source":"github","login":"Dimagog"},{"login":"notake","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/17588518?v=4"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3","account-source":"github","login":"devn"},"_id":"542692cac026201cdc326b53"},{"author":{"login":"dansalmo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e33ee460f5f61bc5ba9b598934766215?r=PG&default=identicon"},"editors":[{"login":"dansalmo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e33ee460f5f61bc5ba9b598934766215?r=PG&default=identicon"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":";; (seq x) is the recommended idiom for testing if a collection is not empty\n(every? seq [\"1\" [1] '(1) {:1 1} #{1}])\n;;=> true","created-at":1350272074000,"updated-at":1422038529310,"_id":"542692d5c026201cdc327079"},{"author":{"login":"rafmagana","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/92894?v=3"},"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"},{"login":"osipaandr","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/14186734?v=4"}],"body":";; 'seq' can be used to turn a map into a list of vectors.\n;; Notice how the list is built adding elements to the beginning \n;; of the seq (list) not to the end, as with vectors.\n;; (Of course, the order that items are \n;; taken from a map should not be relied upon\n;; unless a deterministic 'sorted-map' is used.)\n(seq {:key1 \"value1\" :key2 \"value2\"})\n;;=> ([:key2 \"value2\"] [:key1 \"value1\"])","created-at":1380601368000,"updated-at":1616180554494,"_id":"542692d5c026201cdc32707b"},{"updated-at":1585288063944,"created-at":1470910164741,"author":{"login":"ertugrulcetin","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8271291?v=3"},"body":";; Here is the difference between seq and sequence\n\n(seq nil)\n;;=> nil\n\n(seq ())\n;;=> nil\n\n(sequence ())\n;;=> ()\n\n(sequence nil)\n;;=> ()","editors":[{"avatar-url":"https://avatars1.githubusercontent.com/u/598193?v=4","account-source":"github","login":"green-coder"}],"_id":"57ac4ed4e4b0bafd3e2a04e1"},{"editors":[{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"},{"login":"osipaandr","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/14186734?v=4"}],"body":";; seq is very similar to not-empty:\n\n(every? seq [\"1\" [1] '(1) {:1 1} #{1}])\n;;=> true\n(every? not-empty [\"1\" [1] '(1) {:1 1} #{1}])\n;;=> true\n\n(seq '(1)) ;;=> (1)\n(not-empty '(1)) ;;=> (1)\n\n(seq [1 2]) ;;=> (1 2)\n(not-empty [1 2]) ;;=> [1 2]\n\n\n(seq \"abc\") ;;=> (\\a \\b \\c)\n(not-empty \"abc\") ;;=> \"abc\"\n\n(map seq [nil '() [] \"\" {}])\n;;=> (nil nil nil nil nil)\n\n(map not-empty [nil '() [] \"\" {}])\n;;=> (nil nil nil nil nil)","author":{"avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4","account-source":"github","login":"bfontaine"},"created-at":1602257369027,"updated-at":1616180682337,"_id":"5f8081d9e4b0b1e3652d73d1"}],"notes":null,"tag":"clojure.lang.ISeq","arglists":["coll"],"doc":"Returns a seq on the collection. If the collection is\n empty, returns nil. (seq nil) returns nil. seq also works on\n Strings, native Java arrays (of reference types) and any objects\n that implement Iterable. Note that seqs cache values, thus seq\n should not be used on any Iterable whose iterator repeatedly\n returns the same mutable object.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/seq"},{"added":"1.0","ns":"clojure.core","name":"reduce","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1289800599000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"reductions","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e01"},{"created-at":1289816968000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"apply","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e02"},{"created-at":1289816979000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"frequencies","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e03"},{"created-at":1416151510249,"author":{"login":"ljos","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/585174?v=2"},"to-var":{"ns":"clojure.core","name":"reduced","library-url":"https://github.com/clojure/clojure"},"_id":"5468c1d6e4b0dc573b892fd2"},{"created-at":1416151518003,"author":{"login":"ljos","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/585174?v=2"},"to-var":{"ns":"clojure.core","name":"reduced?","library-url":"https://github.com/clojure/clojure"},"_id":"5468c1dee4b03d20a10242aa"},{"created-at":1461185368746,"author":{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/94482?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"reduce-kv","ns":"clojure.core"},"_id":"5717eb58e4b0fc95a97eab4f"},{"created-at":1514410007011,"author":{"login":"jcburley","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/430319?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"fold","ns":"clojure.core.reducers"},"_id":"5a441017e4b0a08026c48cdf"},{"created-at":1550086607808,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"partition-by","ns":"clojure.core"},"_id":"5c6471cfe4b0ca44402ef683"}],"line":6947,"examples":[{"updated-at":1453975469787,"created-at":1278185820000,"body":"(reduce + [1 2 3 4 5]) ;;=> 15\n(reduce + []) ;;=> 0\n(reduce + [1]) ;;=> 1\n(reduce + [1 2]) ;;=> 3\n(reduce + 1 []) ;;=> 1\n(reduce + 1 [2 3]) ;;=> 6","editors":[{"avatar-url":"https://www.gravatar.com/avatar/bcacd00a7f05c4772329cf9f446c7987?r=PG&default=identicon","account-source":"clojuredocs","login":"dakrone"},{"avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3","account-source":"github","login":"jafingerhut"},{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3","account-source":"github","login":"phreed"},{"login":"mobyte","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/207296?v=3"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/43db6edb2c82a7c76cb5b5911391f02a?r=PG&default=identicon","account-source":"clojuredocs","login":"cody"},"_id":"542692ccc026201cdc326c36"},{"updated-at":1561377314389,"created-at":1278632532000,"body":";; Converting a vector to a set:\n\n(reduce conj #{} [:a :b :c])\n;; => #{:a :c :b}\n","editors":[{"avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon","account-source":"clojuredocs","login":"boxie"},{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3","account-source":"github","login":"phreed"},{"login":"IwoHerka","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/9204550?v=4"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/693b9bfd287e55741c2a4af6f7de0d72?r=PG&default=identicon","account-source":"clojuredocs","login":"jkkramer"},"_id":"542692ccc026201cdc326c39"},{"updated-at":1343775932000,"created-at":1279060391000,"body":";; Create a word frequency map out of a large string s.\n\n;; `s` is a long string containing a lot of words :)\n(reduce #(assoc %1 %2 (inc (%1 %2 0)))\n {}\n (re-seq #\"\\w+\" s))\n\n; (This can also be done using the `frequencies` function.)\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon","account-source":"clojuredocs","login":"boxie"},{"avatar-url":"https://www.gravatar.com/avatar/34f159f89cbd1d9beac0276f5a7af552?r=PG&default=identicon","account-source":"clojuredocs","login":"uvtc"},{"avatar-url":"https://www.gravatar.com/avatar/34f159f89cbd1d9beac0276f5a7af552?r=PG&default=identicon","account-source":"clojuredocs","login":"uvtc"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/1453?v=4","account-source":"github","login":"ghoseb"},"_id":"542692ccc026201cdc326c3b"},{"author":{"login":"devijvers","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/81018e4231ac1ce8b7a9e6d377092656?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"goodmike","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/42e0998c3077ba0ac435423941a3978e?r=PG&default=identicon"},{"login":"goodmike","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/42e0998c3077ba0ac435423941a3978e?r=PG&default=identicon"},{"login":"goodmike","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/42e0998c3077ba0ac435423941a3978e?r=PG&default=identicon"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":";; Calculate primes until 1000\n\n(reduce\n (fn [primes number]\n (if (some zero? (map (partial mod number) primes))\n primes\n (conj primes number)))\n [2]\n (take 1000 (iterate inc 3)))\n\n;;=> [2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 \n;; 83 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163 \n;; 167 173 179 181 191 193 197 199 211 223 227 229 233 239 241 251 \n;; 257 263 269 271 277 281 283 293 307 311 313 317 331 337 347 349 \n;; 353 359 367 373 379 383 389 397 401 409 419 421 431 433 439 443 \n;; 449 457 461 463 467 479 487 491 499 503 509 521 523 541 547 557 \n;; 563 569 571 577 587 593 599 601 607 613 617 619 631 641 643 647 \n;; 653 659 661 673 677 683 691 701 709 719 727 733 739 743 751 757 \n;; 761 769 773 787 797 809 811 821 823 827 829 839 853 857 859 863 \n;; 877 881 883 887 907 911 919 929 937 941 947 953 967 971 977 983 \n;; 991 997]","created-at":1279066766000,"updated-at":1420654061502,"_id":"542692ccc026201cdc326c40"},{"author":{"login":"devijvers","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/81018e4231ac1ce8b7a9e6d377092656?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":";; Add one collection to another (combining sequences is done with cons):\n(reduce conj [1 2 3] [4 5 6])\n;;=> [1 2 3 4 5 6]\n\n(reduce #(cons %2 %1) [1 2 3] [4 5 6])\n;;=> '(6 5 4 1 2 3)","created-at":1279163552000,"updated-at":1420654295036,"_id":"542692ccc026201cdc326c46"},{"author":{"login":"gradysw","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a2d549191f2863bf87489949edebb548?r=PG&default=identicon"},"editors":[{"login":"gradysw","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a2d549191f2863bf87489949edebb548?r=PG&default=identicon"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":";; Combine a vector of collections into a single collection \n;; of the type of the first collection in the vector.\n(reduce into [[1 2 3] [:a :b :c] '([4 5] 6)])\n;;=> [1 2 3 :a :b :c [4 5] 6]\n\n;; The flatten function can be used to completely fuse \n;; all of the items of a nested tree into a single sequence.\n;; Sometimes all that is needed is to fuse the first level\n;; of a tree. This can be done with 'reduce' and 'into'.\n(reduce into [] '([] [[10 18]] [[8 18]] [[10 12]] [[0 -6]] [[2 6]]))\n;;=> [[10 18] [8 18] [10 12] [0 -6] [2 6]]\n","created-at":1325573490000,"updated-at":1426023239324,"_id":"542692d5c026201cdc327064"},{"author":{"login":"octopusgrabbus","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/fd31b8bcea99fa7b0711fbc424587774?r=PG&default=identicon"},"editors":[],"body":"(defn key-pres?\n \"This function accepts a value (cmp-val) and a vector of vectors\n (parsed output from clojure-csv) and returns the match value\n back if found and nil if not found. \n\n Using reduce, the function searches every vector row to see \n if cmp-val is at the col-idx location in the vector.\"\n\n [cmp-val cmp-idx csv-data]\n (reduce\n (fn [ret-rc csv-row]\n (if (= cmp-val (nth csv-row col-idx nil))\n (conj ret-rc cmp-val)))\n [] \n csv-data))","created-at":1334260928000,"updated-at":1334260928000,"_id":"542692d5c026201cdc327066"},{"author":{"login":"octopusgrabbus","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/fd31b8bcea99fa7b0711fbc424587774?r=PG&default=identicon"},"editors":[{"login":"octopusgrabbus","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/fd31b8bcea99fa7b0711fbc424587774?r=PG&default=identicon"}],"body":"(defn reduce-csv-row\n \"Accepts a csv-row (a vector) a list of columns to extract, \n and reduces (and returns) a csv-row to a subset based on \n selection using the values in col-nums (a vector of integer \n vector positions.)\"\n\n [csv-row col-nums]\n\n (reduce\n (fn [out-csv-row col-num]\n ; Don't consider short vectors containing junk.\n (if-not (<= (count csv-row) 1)\n (conj out-csv-row (nth csv-row col-num nil))))\n []\n col-nums))\n\n","created-at":1334261221000,"updated-at":1334261450000,"_id":"542692d5c026201cdc327067"},{"editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3","account-source":"github","login":"phreed"},{"login":"IwoHerka","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/9204550?v=4"}],"updated-at":1561323174151,"created-at":1426023157581,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3","account-source":"github","login":"phreed"},"body":";; Some functions update a collection with a single item.\n;; A number of functions have a 'more' argument which lets\n;; them work over collections.\n;; These functions can benefit 'reduce' which lets them work \n;; a collection of items...\n(into {} {:dog :food})\n\n(reduce into {} [{:dog :food} {:cat :chow}])\n;;=> {:dog :food, :cat :chow}","_id":"54ff62f5e4b0b716de7a6539"},{"updated-at":1561377338656,"created-at":1441139931232,"author":{"login":"lwm","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1991377?v=3"},"body":";; The reduction will terminate early if an intermediate result uses the \n;; `reduced` function.\n\n(defn limit [x y] \n (let [sum (+ x y)] \n (if (> sum 10) (reduced sum) sum)))\n\n(reduce + 0 (range 10))\n;; => 45\n\n(reduce limit 0 (range 10))\n;; => 15","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/25400?v=3","account-source":"github","login":"miner"},{"login":"IwoHerka","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/9204550?v=4"}],"_id":"55e60cdbe4b072d7f27980f5"},{"editors":[{"login":"teymuri","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/13352033?v=3"},{"login":"IwoHerka","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/9204550?v=4"}],"body":";; This will generate the first 100 Fibonacci numbers\n;; (size of (range) + 2):\n\n(reduce \n (fn [a b] (conj a (+' (last a) (last (butlast a))))) \n [0 1] \n (range 98))\n\n;; [0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040 1346269 2178309 3524578 5702887 9227465 14930352 24157817 39088169 63245986 102334155 165580141 267914296 433494437 701408733 1134903170 1836311903 2971215073 4807526976 7778742049 12586269025 20365011074 32951280099 53316291173 86267571272 139583862445 225851433717 365435296162 591286729879 956722026041 1548008755920 2504730781961 4052739537881 6557470319842 10610209857723 17167680177565 27777890035288 44945570212853 72723460248141 117669030460994 190392490709135 308061521170129 498454011879264 806515533049393 1304969544928657 2111485077978050 3416454622906707 5527939700884757 8944394323791464 14472334024676221 23416728348467685 37889062373143906 61305790721611591 99194853094755497 160500643816367088 259695496911122585 420196140727489673 679891637638612258 1100087778366101931 1779979416004714189 2880067194370816120 4660046610375530309 7540113804746346429 12200160415121876738N 19740274219868223167N 31940434634990099905N 51680708854858323072N 83621143489848422977N 135301852344706746049N 218922995834555169026N]","author":{"avatar-url":"https://avatars.githubusercontent.com/u/13352033?v=3","account-source":"github","login":"teymuri"},"created-at":1443219853505,"updated-at":1561377380394,"_id":"5605c98de4b08e404b6c1c85"},{"editors":[{"login":"IwoHerka","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/9204550?v=4"}],"body":";; Reduce can be used to reimplement a map function:\n\n(defn map* [f & c]\n (let [c* (partition (count c)\n (apply interleave c))]\n (reduce (fn [s k] (conj s (apply f k))) [] c*)))\n\n;; user=> (map* * [0.5 0.5 0.5] (range))\n;; [0.0 0.5 1.0]\n;; user=> (map* str \"clojure\" (range))\n;; [\"c0\" \"l1\" \"o2\" \"j3\" \"u4\" \"r5\" \"e6\"]\n","author":{"avatar-url":"https://avatars.githubusercontent.com/u/13352033?v=3","account-source":"github","login":"teymuri"},"created-at":1447891132480,"updated-at":1561323290402,"_id":"564d10bce4b0538444398272"},{"editors":[{"login":"IwoHerka","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/9204550?v=4"}],"body":";; Update map entries:\n(defn update-map-entries [m e]\n (reduce #(update-in %1 [(first %2)] (fn [_] (last %2))) m e))\n\n;; => (update-map-entries {:a 1 :b 2 :c 3} {:a 5 :b 9})\n;; {:a 5, :b 9, :c 3}\n;; => (update-map-entries {:a 1 :b 2 :c 3} {:a 5 :b 9 :d 8})\n;; {:a 5, :b 9, :c 3, :d 8}","author":{"avatar-url":"https://avatars.githubusercontent.com/u/1223207?v=3","account-source":"github","login":"hadielmougy"},"created-at":1470237574017,"updated-at":1561377421060,"_id":"57a20b86e4b0bafd3e2a04c5"},{"editors":[{"login":"IwoHerka","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/9204550?v=4"}],"body":";; Flatten values in a map.\n(reduce\n (fn [flattened [k v]]\n (clojure.set/union flattened v))\n #{}\n {:e #{:m :f}, :c #{:f}, :b #{:c :f}, :d #{:m :f}, :a #{:c :f}})\n\n;; => #{:m :c :f}","author":{"avatar-url":"https://avatars.githubusercontent.com/u/528932?v=3","account-source":"github","login":"sleyzerzon"},"created-at":1471131155930,"updated-at":1561323131079,"_id":"57afae13e4b02d8da95c26fa"},{"editors":[{"login":"IwoHerka","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/9204550?v=4"}],"body":";; A simple factorial function using reduce:\n\n(defn fact\n [x] \n (reduce * (range 1 (inc x))))","author":{"avatar-url":"https://avatars.githubusercontent.com/u/2006175?v=3","account-source":"github","login":"cloxure"},"created-at":1479851336416,"updated-at":1561377519723,"_id":"5834bd48e4b0782b632278c7"},{"updated-at":1561377553253,"created-at":1485475889351,"author":{"login":"mahonbaldwin","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2431381?v=3"},"body":";; Reduce over maps by destructuring keys:\n(def x {:a 1 :b 2})\n\n(reduce (fn [p [k v]]\n (into p {k (+ 1 v)}))\n {} ; First value for p\n x)\n\n;; => {:a 2, :b 3}","editors":[{"avatar-url":"https://avatars0.githubusercontent.com/u/838526?v=3","account-source":"github","login":"isaacm"},{"login":"IwoHerka","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/9204550?v=4"}],"_id":"588a9031e4b01f4add58fe32"},{"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"}],"body":";; conj! over transient array for speed.\n;; This example flattens over one level.\n;; To do so uses reduce twice.\n(persistent!\n (reduce\n (fn [acc0 item-vector]\n (reduce \n (fn [acc1 item]\n (conj! acc1 item))\n acc0 item-vector))\n (transient [])\n [[:foo :bar :baz] [] [:fred :barney]]))\n ;;=> [:foo :bar :baz :fred :barney] ","author":{"avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4","account-source":"github","login":"phreed"},"created-at":1508890297162,"updated-at":1508890336628,"_id":"59efd6b9e4b0a08026c48c76"},{"updated-at":1516050550051,"created-at":1516050550051,"author":{"login":"ibercode","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/31028993?v=4"},"body":";;reduce with side effects\n;;given a collection return a new collection\n\n(def initial-coll [1 2 3 4 5])\n\n(defn byten\n [coll]\n (reduce (fn [new-coll unit]\n (into new-coll [(* 10 unit)]))\n []\n coll))\n\n(byten initial-coll)\n;;[10 20 30 40 50]\n\n\n","_id":"5a5d1876e4b0a08026c48cf5"},{"editors":[{"login":"IwoHerka","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/9204550?v=4"}],"body":";; Reduce with side effects using an anonymous function\n;; given a collection return a new collection:\n\n(def initial-coll [1 2 3 4 5])\n\n(defn byten\n [coll]\n (reduce #(into %1 [(* 10 %2)])\n []\n coll))\n\n(byten initial-coll)\n;; => [10 20 30 40 50]","author":{"avatar-url":"https://avatars0.githubusercontent.com/u/31028993?v=4","account-source":"github","login":"ibercode"},"created-at":1516050752043,"updated-at":1561377738301,"_id":"5a5d1940e4b0a08026c48cf6"},{"editors":[{"login":"IwoHerka","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/9204550?v=4"}],"body":";; A practical example of mapping over values\n;; in a hash-map with the `upper-case` function:\n\n(reduce\n (fn [acc [k v]]\n (assoc acc k (clojure.string/upper-case v)))\n {}\n {:a \"aaaaaaa\" :b \"bbbbbbb\"})\n\n;; => {:a \"AAAAAAA\", :b \"BBBBBBB\"}","author":{"avatar-url":"https://avatars0.githubusercontent.com/u/31028993?v=4","account-source":"github","login":"ibercode"},"created-at":1517738937897,"updated-at":1561377698196,"_id":"5a76dbb9e4b0e2d9c35f7418"},{"editors":[{"login":"ftravers","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/443507?v=4"}],"body":"(reduce\n (fn [accumulator current-item] ; <-- accumulator is FIRST argument to function\n ...) ; <-- your fn definition goes here\n [] ; <-- initial value for your accumulator \n [:a :b]) ; <-- collection to operate on\n","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/443507?v=4","account-source":"github","login":"ftravers"},"created-at":1555521629477,"updated-at":1555521659756,"_id":"5cb7605de4b0ca44402ef70b"},{"editors":[{"login":"tanrax","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/4553672?v=4"}],"body":"(reduce #(str %1 %2) \"\" [\"Woody\" \"Potato\" \"Buzz\"])\n;;=> \"WoodyPotatoBuzz\"\n\n;; or\n\n(reduce (fn [accumulator current-item] (str accumulator current-item)) \"\" [\"Woody\" \"Potato\" \"Buzz\"])\n;;=> \"WoodyPotatoBuzz\"\n\n","author":{"avatar-url":"https://avatars3.githubusercontent.com/u/4553672?v=4","account-source":"github","login":"tanrax"},"created-at":1583079460917,"updated-at":1584265812224,"_id":"5e5be024e4b087629b5a18b0"},{"updated-at":1693707759326,"created-at":1693707759326,"author":{"login":"burinc","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/19825136?v=4"},"body":"; Nice use of reduce from some version of medley library \n; https://github.com/weavejester/medley\n\n(defn assoc-some\n \"Associates a key k, with a value v in a map m, if and only if v is not nil.\"\n ([m k v]\n (if (nil? v) m (assoc m k v)))\n ([m k v & kvs]\n (reduce (fn [m [k v]] (assoc-some m k v))\n (assoc-some m k v)\n (partition 2 kvs))))\n\n(assoc-some {} :a 1)\n;;=> {:a 1}\n\n(assoc-some {} :a nil :b 2)\n;;=> {:b 2}\n\n(assoc-some {:a 1 :b 2} :a 10 :c 3)\n;;=> {:a 10, :b 2, :c 3}\n\n","_id":"64f3edefe4b08cf8563f4be7"},{"updated-at":1694309383597,"created-at":1694309383597,"author":{"login":"burinc","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/19825136?v=4"},"body":";; Transform key/value pairs\n(reduce (fn [acc [k v]]\n (assoc acc (str (name k)) v))\n {}\n [[:a 1] [:b 2] [:c 3]])\n;;=> {\"a\" 1, \"b\" 2, \"c\" 3}\n\n(reduce (fn [acc [k v]]\n (assoc acc (str \"k\" k) (* v 2)))\n {}\n (partition 2 (range 10)))\n;;=> {\"k0\" 2, \"k2\" 6, \"k4\" 10, \"k6\" 14, \"k8\" 18}","_id":"64fd1c07e4b08cf8563f4bf7"},{"updated-at":1736155857640,"created-at":1736155857640,"author":{"login":"vasanth53","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/95751113?v=4"},"body":";; Function to generate permutations using reduce\n(defn permutations [coll]\n (reduce\n (fn [acc x]\n (for [perm acc\n i (range (inc (count perm)))]\n (concat (take i perm) [x] (drop i perm))))\n [[]] ; Start with an empty permutation\n coll))\n\n;; Example usage\n(permutations [1 2 3])\n\n;; => ((3 2 1) (2 3 1) (2 1 3) (3 1 2) (1 3 2) (1 2 3))\n","_id":"677ba2d1cd84df5de54e2068"}],"notes":[{"updated-at":1278794710000,"body":"clojure.core/reduce seems to be a special case of a function that's defined twice in core.clj, and the first definition (at the line cited above: 773) is just a temporary definition; the real definition is later at line 5323, which contains the docstring.","created-at":1278794710000,"author":{"login":"JoshuaEckroth","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/ef8bb10e14b41f71f8ea9ed9d66d07b7?r=PG&default=identicon"},"_id":"542692ebf6e94c6970521f80"},{"author":{"login":"didibus","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/601540?v=3"},"updated-at":1505006701520,"created-at":1505006701520,"body":"The reducing function f is of shape:\n\n(f [accumulator next-element] ...)","_id":"59b4946de4b09f63b945ac67"},{"author":{"login":"iljaf","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/35742698?v=4"},"updated-at":1598124872512,"created-at":1598124872512,"body":"The 4th example (generating prime numbers) is kind of nice conceptually, but running it for the first 1m integers is taking 2 min on i7 2.7GHz machine, so it seems to be a very inefficient way of generating prime numbers. ","_id":"5f417348e4b0b1e3652d7385"}],"arglists":["f coll","f val coll"],"doc":"f should be a function of 2 arguments. If val is not supplied,\n returns the result of applying f to the first 2 items in coll, then\n applying f to that result and the 3rd item, etc. If coll contains no\n items, f must accept no arguments as well, and reduce returns the\n result of calling f with no arguments. If coll has only 1 item, it\n is returned and f is not called. If val is supplied, returns the\n result of applying f to val and the first item in coll, then\n applying f to that result and the 2nd item, etc. If coll contains no\n items, returns val and f is not called.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/reduce"},{"added":"1.0","ns":"clojure.core","name":"when-first","file":"clojure/core.clj","type":"macro","column":1,"see-alsos":[{"created-at":1405367822000,"author":{"login":"ryo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3f7913b563c72083c74030d928ba407e?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"when-let","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b77"},{"created-at":1713010008086,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"when","ns":"clojure.core"},"_id":"661a755869fbcc0c226174bd"}],"line":4649,"examples":[{"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"}],"body":"user=> (when-first [a [1 2 3]] a)\n1\nuser=> (when-first [a []] :x)\nnil\nuser=> (when-first [a nil] :x)\nnil","created-at":1280737783000,"updated-at":1423524033466,"_id":"542692cac026201cdc326b30"},{"editors":[{"login":"totorigolo","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/1183296?v=4"}],"body":";; Note that the 'when' switches on the truthiness of the sequence, not the\n;; truthiness of the elements within the sequence.\n\nuser=> (when-first [a [nil 2 3]] \n (print (str \"Picked: \" (prn-str a))))\nPicked: nil\nnil","author":{"avatar-url":"https://avatars3.githubusercontent.com/u/1634344?v=3","account-source":"github","login":"peterwestmacott"},"created-at":1490868547686,"updated-at":1542136234692,"_id":"58dcd943e4b01f4add58fe80"},{"updated-at":1522689850199,"created-at":1522689850199,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"body":";; A concise way to write the basic lazy loop.\n\n(defn dechunk [xs]\n (lazy-seq\n (when-first [x xs]\n (cons x\n (dechunk (rest xs))))))\n\n;; would print 32 dots otherwise:\n(first (map #(do (print \".\") %) (dechunk (range 100))))\n;; .0","_id":"5ac2673ae4b045c27b7fac2e"}],"macro":true,"notes":null,"arglists":["bindings & body"],"doc":"bindings => x xs\n\n Roughly the same as (when (seq xs) (let [x (first xs)] body)) but xs is evaluated only once","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/when-first"},{"added":"1.0","ns":"clojure.core","name":"find-ns","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1284970272000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"create-ns","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bd5"},{"created-at":1284970279000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"remove-ns","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bd6"},{"created-at":1489760484301,"author":{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/94482?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"ns-map","ns":"clojure.core"},"_id":"58cbf0e4e4b01f4add58fe76"}],"line":4152,"examples":[{"author":{"login":"teyc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bd6e62afb4881ab0f617611b8b65d003?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"},{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"}],"body":"(find-ns 'clojure.string)\n;;=> nil\n\n(require 'clojure.string)\n;;=> nil\n\n(find-ns 'clojure.string)\n;;=> #","created-at":1283925753000,"updated-at":1422932795101,"_id":"542692ccc026201cdc326c90"}],"notes":null,"arglists":["sym"],"doc":"Returns the namespace named by the symbol or nil if it doesn't exist.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/find-ns"},{"added":"1.1","ns":"clojure.core","name":"get-thread-bindings","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1350609423000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"bound-fn","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cbb"},{"created-at":1350609426000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"bound-fn*","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cbc"}],"line":1956,"examples":[{"updated-at":1615494273716,"created-at":1615493864771,"author":{"login":"Crowbrammer","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/19522656?v=4"},"body":"(get-thread-bindings) \n;;=> {#'cider.nrepl.middleware.debug/*skip-breaks* #atom[nil 0x6683434], \n;; #'clojure.core/*unchecked-math* false, \n;; # nil, # 1, \n... \n;; #'clojure.test/*test-out* #object[java.io.PrintWriter 0x7aa21648 \n;; \"java.io.PrintWriter@7aa21648\"], # true}\n;; # true}","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/19522656?v=4","account-source":"github","login":"Crowbrammer"}],"_id":"604a7ae8e4b0b1e3652d7482"}],"notes":null,"arglists":[""],"doc":"Get a map with the Var/value pairs which is currently in effect for the\n current thread.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/get-thread-bindings"},{"added":"1.0","ns":"clojure.core","name":"contains?","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1307097029000,"author":{"login":"stand","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d7f9ed2753f8b3517f1539f6129f0a17?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"some","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d35"},{"created-at":1354058314000,"author":{"login":"uvtc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/34f159f89cbd1d9beac0276f5a7af552?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"get","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d36"}],"line":1498,"examples":[{"updated-at":1708137384759,"created-at":1278821806000,"body":";; `contains?` is straightforward for maps:\n(contains? {:a 1} :a) ;=> true\n(contains? {:a nil} :a) ;=> true\n(contains? {:a 1} :b) ;=> false\n\n;; It's likely to surprise you for other sequences because it's \n;; about *indices* or *keys*, not *contents*:\n\n(contains? [:a :b :c] :b) ;=> false\n(contains? [:a :b :c] 2) ;=> true\n(contains? [\"a\" \"b\"] \"b\") ;=> false\n(contains? \"f\" 0) ;=> true\n(contains? \"f\" 1) ;=> false\n\n;; Although lists are sequences, they are not keyed sequences.\n;; `contains?` should not be used for lists.\n\n(contains? '(1 2 3) 1) \n;; IllegalArgumentException (Clojure >=1.5)\n\n;; It also works on native arrays, HashMaps or HashSets:\n(import '[java.util HashMap HashSet])\n(contains? (doto (HashSet.) (.add 1)) 1) ;=> true\n(contains? (doto (HashMap.) (.put \"a\" 1)) \"a\") ;=> true\n(contains? (int-array [1 2 3]) 0) ;=> true\n\n;; For nils:\n(contains? nil 1)\n;=> false\n\n(contains? nil nil)\n;=> false","editors":[{"avatar-url":"https://www.gravatar.com/avatar/a523012f661f603806ab1c22d855216f?r=PG&default=identicon","account-source":"clojuredocs","login":"Brian Marick"},{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"avatar-url":"https://www.gravatar.com/avatar/a684c0fd4f27597437de953e92a15d4b?r=PG&default=identicon","account-source":"clojuredocs","login":"Phalphalak"},{"avatar-url":"https://www.gravatar.com/avatar/289cf5fb7dc48bc0d1237a779b8b107?r=PG&default=identicon","account-source":"clojuredocs","login":"alex_ndc"},{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3","account-source":"github","login":"phreed"},{"login":"reborg","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/20086?v=3"},{"avatar-url":"https://avatars.githubusercontent.com/u/15642321?v=4","account-source":"github","login":"mdave16"},{"login":"siddharthjain-in","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/6537820?v=4"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/a523012f661f603806ab1c22d855216f?r=PG&default=identicon","account-source":"clojuredocs","login":"Brian Marick"},"_id":"542692cdc026201cdc326d2a"},{"author":{"login":"stand","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d7f9ed2753f8b3517f1539f6129f0a17?r=PG&default=identicon"},"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":";; Can be used to test set membership\n(def s #{\"a\" \"b\" \"c\"})\n\n;; The members of a set are the keys of those elements.\n(contains? s \"a\") ;=> true\n(contains? s \"z\") ;=> false","created-at":1307097549000,"updated-at":1422318705818,"_id":"542692cdc026201cdc326d2f"},{"updated-at":1498597995922,"created-at":1498584367639,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/20086?v=3"},"body":";; When \"key\" is a number, it is expected to be an integer. \n;; Beyond that limit, lossy truncation may result in unexpected results:\n\n(contains? [1 2 3] 4294967296) ;=> true","editors":[{"avatar-url":"https://avatars2.githubusercontent.com/u/20086?v=3","account-source":"github","login":"reborg"}],"_id":"5952952fe4b06e730307db46"}],"notes":[{"updated-at":1279546429000,"body":"If like me you wanted to find a value in a collection and read this article then you'll need to find an alternative. So instead of:\r\n
\r\n(contains (1 2 3) 1)\r\n
\r\nI used:\r\n
\r\n(some #(= 1 %) (1 2 3))\r\n
\r\n\r\nHope that helps.","created-at":1279546429000,"author":{"login":"robertpostill","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/16aae57aa6b16e96fa81089bea6acad8?r=PG&default=identicon"},"_id":"542692ebf6e94c6970521f81"},{"updated-at":1279552212000,"body":"For collections I use the `java.util.Collection#contains()` method:\r\n\r\n
\r\nuser=> (.contains [1 2 3] 1)\r\ntrue\r\nuser=> (.contains [1 2 3] 4)\r\nfalse\r\n
","created-at":1279552212000,"author":{"login":"devijvers","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/81018e4231ac1ce8b7a9e6d377092656?r=PG&default=identicon"},"_id":"542692ebf6e94c6970521f82"},{"updated-at":1354058595000,"body":"As Rich points out on the ML: \r\n\r\n`contains?` tells you whether or not `get` will succeed. It is not a \"rummager\".\r\n\r\n`contains?` and `get` abstract over fast lookup.\r\n","created-at":1354058595000,"author":{"login":"uvtc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/34f159f89cbd1d9beac0276f5a7af552?r=PG&default=identicon"},"_id":"542692edf6e94c6970521ff5"},{"updated-at":1388617095000,"body":"If you have a vector or list and want to check whether a *value* is contained in it, you will find that `contains?` does not work.\r\n\r\n
; does not work as you might expect\r\n(contains? [:a :b :c] :b) ; = false
\r\n\r\nThere are four things you can try in this case:\r\n\r\n1. Consider whether you really need a vector or list. If you use a set instead, `contains?` will work.\r\n
(contains? #{:a :b :c} :b) ; = true
\r\n2. Use [`some`](http://clojuredocs.org/clojure_core/clojure.core/some) instead, wrapping the target in a set, as follows:\r\n
(some #{:b} [:a :b :c]) ; = :b, which is truthy
\r\n3. The set-as-function shortcut will not work if you might be searching for a falsy value (`false` or `nil`).\r\n
; will not work\r\n(some #{false} [true false true]) ; = nil
\r\n In that case, you will have to write the predicate function the long way:\r\n
(some #(= false %) [true false true]) ; = true
\r\n4. If you will need to do this kind of search a lot, write a function for it:\r\n
(defn seq-contains? [coll target] (some #(= target %) coll))\r\n(seq-contains? [true false true] false) ; = true
","created-at":1385323398000,"author":{"login":"roryokane","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5b2b185c814bb25f2f95a1152e58f033?r=PG&default=identicon"},"_id":"542692edf6e94c697052200f"},{"author":{"login":"cloojure","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7083783?v=3"},"updated-at":1462902144512,"created-at":1462902144512,"body":"In order to determine if an element is contained in the collection, it may be easiest to use the `Vector.indexOf()` function from java:\n\n (.indexOf (range 10) 5)\n ;=> 5\n (.indexOf [:a :b :c] :b)\n ;=> 1\n\n[Java API Docs are here](http://docs.oracle.com/javase/7/docs/api/java/util/Vector.html#indexOf%28java.lang.Object%29)","_id":"57321d80e4b012fa59bdb2f1"},{"body":"You may wonder why this statement evaluates to true:
\n\n(contains? [1 1 1 1 1] 4)
\n;=> true\n
\n\nLet's do some investigation to find the answer. First we start by finding out the type of [1 1 1 1 1]:\n\n(class [1 1 1 1 1])
\n;=> clojure.lang.PersistentVector\n
\n\nSo when the statement (contains? [1 1 1 1 1] 4) is evaluated, the function contains? in
core.clj is called.\n\nThis function delegates to the static Java function contains(Object coll, Object key) in clojure.lang.RT, which discovers that the incoming vector is an instance of Associative (PersistentVector > APersistentVector > IPersistentVector > Associative) and exits with:
\n\nreturn ((Associative) coll).containsKey(key)\n\n\nThis means that these two statements are equivalent, based on the current implementation of PersistentVector:
\n\n(contains? [1 1 1 1 1] 4) ; true
\n(.containsKey [1 1 1 1 1 1] 4) ; true\n
\n\nThe method containsKey of APersistentVector is finally called. It checks if the vector has at least four elements (size >= 4) which it has (5) and that's why it returns true. Mystery solved!\n","created-at":1469650697268,"updated-at":1469653287748,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/631272?v=3","account-source":"github","login":"tengstrand"},"_id":"57991709e4b0bafd3e2a04c1"},{"author":{"login":"coutego","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/86327033?v=4"},"updated-at":1670094879509,"created-at":1670094709380,"body":"This `in?` function could be a convenient one line replacement for `contains?` implementing the expected semantics for containers:\n \n
\n(defn in? [xs el] (some #(= % el) xs))\n
","_id":"638b9f75e4b0b1e3652d7693"}],"arglists":["coll key"],"doc":"Returns true if key is present in the given collection, otherwise\n returns false. Note that for numerically indexed collections like\n vectors and Java arrays, this tests if the numeric key is within the\n range of indexes. 'contains?' operates constant or logarithmic time;\n it will not perform a linear search for a value. See also 'some'.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/contains_q"},{"added":"1.0","ns":"clojure.core","name":"every?","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1302013840000,"author":{"login":"pauldoo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5cb916d3c8abc9f45a093209e72489fb?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"some","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d9e"},{"created-at":1315793054000,"author":{"login":"wdkrnls","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/6d08a2f792f289b95fe1d982d4133d71?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"not-any?","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d9f"},{"created-at":1422932256217,"author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"to-var":{"ns":"clojure.core","name":"not-every?","library-url":"https://github.com/clojure/clojure"},"_id":"54d03920e4b081e022073c43"}],"line":2689,"examples":[{"author":{"login":"dpritchett","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/147981?v=3"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":"user=> (every? even? '(2 4 6))\ntrue\nuser=> (every? even? '(1 2 3))\nfalse","created-at":1279073869000,"updated-at":1332951153000,"_id":"542692cfc026201cdc326e56"},{"author":{"login":"shockbob","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon"},"editors":[{"login":"Rich_Morin","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d4d28bd014f9e7324bad99dcc3b0d390?r=PG&default=identicon"}],"body":";; you can use every? with a set as the predicate to return true if \n;; every member of a collection is in the set\nuser=> (every? #{1 2} [1 2 3])\nfalse\nuser=> (every? #{1 2} [1 2])\ntrue\n\n;; or use a hash-map as the predicate with every? to return true \n;; if every member of a collection is a key within the map\nuser=> (every? {1 \"one\" 2 \"two\"} [1 2])\ntrue\nuser=> (every? {1 \"one\" 2 \"two\"} [1 2 3])\nfalse","created-at":1310851356000,"updated-at":1358775095000,"_id":"542692cfc026201cdc326e58"},{"author":{"login":"dkvasnicka","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/55c9f4624d94a0c87c4f4fcb7f152393?r=PG&default=identicon"},"editors":[{"login":"dkvasnicka","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/55c9f4624d94a0c87c4f4fcb7f152393?r=PG&default=identicon"},{"avatar-url":"https://avatars3.githubusercontent.com/u/1195619?v=3","account-source":"github","login":"jeffi"},{"login":"beoliver","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1413969?v=4"},{"avatar-url":"https://avatars2.githubusercontent.com/u/22192927?v=4","account-source":"github","login":"elenacanovi"},{"login":"PEZ","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/30010?v=4"}],"body":";; this is kind of weird IMO... but it works that way (the same for vectors)\n;; See: https://en.wikipedia.org/wiki/Vacuous_truth\nuser=> (every? true? '())\ntrue\nuser=> (every? false? '())\ntrue\n\n;; and similarly\nuser=> (every? map? '())\ntrue\nuser=> (every? vector? '())\ntrue\nuser=> (every? string? '())\ntrue\nuser=> (every? number? '())\ntrue\n\n;; and even\nuser=> (every? :foo nil)\ntrue\n\n;; As such a better description of every? would be\n\n;; Returns false if there exists a value x in coll \n;; such that (pred? x) is false, else true.\" \n","created-at":1356575084000,"updated-at":1670431457567,"_id":"542692d3c026201cdc326fa1"},{"updated-at":1512078155897,"created-at":1512078155897,"author":{"login":"chbrown","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/360279?v=4"},"body":";; every? can replace clojure.set/subset? if and only if\n;; the sets do not contain false / nil values\n\n(subset? #{1} #{1 2}) ;;=> true\n(every? #{1 2} #{1} ) ;;=> true ✔\n\n(subset? #{1 3} #{1 2}) ;;=> false\n(every? #{1 2} #{1 3}) ;;=> false ✔\n\n;; however, invoking a set with a value returns the matched element,\n;; causing the comparison below to fail\n\n(subset? #{true false} #{true false}) ;;=> true\n(every? #{true false} #{true false}) ;;=> false ✘ 😦\n","_id":"5a207b4be4b0a08026c48cca"}],"notes":null,"tag":"java.lang.Boolean","arglists":["pred coll"],"doc":"Returns true if (pred x) is logical true for every x in coll, else\n false.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/every_q"},{"added":"1.0","ns":"clojure.core","name":"proxy-mappings","file":"clojure/core_proxy.clj","type":"function","column":1,"see-alsos":[{"created-at":1708775042567,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"proxy","ns":"clojure.core"},"_id":"65d9d68269fbcc0c226174a9"}],"line":328,"examples":[{"updated-at":1683032923886,"created-at":1683032784200,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":"(def my-proxy\n (proxy [java.lang.Object] []\n (equals [_] false)\n (toString [] \"I'm an object\")))\n;; => #'user/my-proxy\n\n(proxy-mappings my-proxy)\n;; => {\"equals\" #function[user/fn--43785/fn--43786],\n;; \"toString\" #function[user/fn--43785/fn--43788]}\n\n(let [to-string-fn (-> my-proxy proxy-mappings (get \"toString\"))]\n (to-string-fn :foo))\n;; => \"I'm an object\"\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4","account-source":"github","login":"tomdl89"}],"_id":"64510ad0e4b08cf8563f4ba9"}],"notes":null,"arglists":["proxy"],"doc":"Takes a proxy instance and returns the proxy's fn map.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/proxy-mappings"},{"added":"1.2","ns":"clojure.core","name":"keep-indexed","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1324314274000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.core","name":"map-indexed","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b55"},{"created-at":1337189104000,"author":{"login":"SoniaH","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/56a007a4b2c47b141bd39790278f88a7?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"keep","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b56"}],"line":7538,"examples":[{"updated-at":1718839142351,"created-at":1282318865000,"body":"user=> (keep-indexed #(when (odd? %1) %2) [:a :b :c :d :e])\n(:b :d)","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3","account-source":"github","login":"jafingerhut"},{"avatar-url":"https://www.gravatar.com/avatar/56a007a4b2c47b141bd39790278f88a7?r=PG&default=identicon","account-source":"clojuredocs","login":"SoniaH"},{"login":"arcanjoaq","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1619912?v=4"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/10b2fd3c0a4cc46dc241a48468dc551?r=PG&default=identicon","account-source":"clojuredocs","login":"pkolloch"},"_id":"542692c9c026201cdc326a84"},{"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"editors":[],"body":"user=> (keep-indexed #(if (pos? %2) %1) [-9 0 29 -7 45 3 -8])\n(2 4 5)\n;; f takes 2 args: 'index' and 'value' where index is 0-based\n;; when f returns nil the index is not included in final result\nuser=> (keep-indexed (fn [idx v]\n (if (pos? v) idx)) [-9 0 29 -7 45 3 -8])\n(2 4 5)","created-at":1292177237000,"updated-at":1292177237000,"_id":"542692c9c026201cdc326a87"},{"author":{"login":"yasuto","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cacfb7ecf08cb6461767e514c93b7bf9?r=PG&default=identicon"},"editors":[{"login":"yasuto","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cacfb7ecf08cb6461767e514c93b7bf9?r=PG&default=identicon"},{"login":"yasuto","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cacfb7ecf08cb6461767e514c93b7bf9?r=PG&default=identicon"},{"login":"clojureking","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/92625b8a6be91bb8c688d0d07b4e2a32?r=PG&default=identicon"},{"login":"clojureking","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/92625b8a6be91bb8c688d0d07b4e2a32?r=PG&default=identicon"}],"body":"(defn position [x coll & {:keys [from-end all] :or {from-end false all false}}]\n (let [all-idxs (keep-indexed (fn [idx val] (when (= val x) idx)) coll)]\n (cond\n (true? from-end) (last all-idxs)\n (true? all) all-idxs\n :else (first all-idxs))))\n\nuser> (position [1 1] [[1 0][1 1][2 3][1 1]])\n1\nuser> (position [1 1] [[1 0][1 1][2 3][1 1]] :from-end true)\n3\nuser> (position [1 1] [[1 0][1 1][2 3][1 1]] :all true)\n(1 3)\n\nuser> (def foo (shuffle (range 10)))\n#'user/foo\nuser> foo\n(5 8 9 1 2 7 0 6 3 4)\nuser> (position 5 foo)\n0\nuser> (position 0 foo)\n6","created-at":1306319468000,"updated-at":1409547666000,"_id":"542692c9c026201cdc326a88"},{"updated-at":1444409466360,"created-at":1444409466360,"author":{"login":"PetrGlad","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/124476?v=3"},"body":";; Simpler version of \"position\" above\n;; Get position of first element that satisfies the predicate\n(let [predicate #(= 1 %)\n sequence [3 2 4 1 5 6 7]]\n (first (keep-indexed (fn [i x] (when (predicate x) i)) \n sequence)))\n\n;; The same logic but implemented with map-indexed\n(let [predicate #(= 1 %)\n sequence [3 2 4 1 5 6 7]]\n (some identity \n (map-indexed (fn [i x] (when (predicate x) i)) \n sequence)))","_id":"5617f07ae4b084e61c76ecbf"},{"updated-at":1528067828447,"created-at":1528067828447,"author":{"login":"statcompute","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/4590938?v=4"},"body":"(require '[clojure.pprint :as p]\n '[clojure.java.jdbc :as j])\n \n(def db\n {:classname \"org.sqlite.JDBC\"\n :subprotocol \"sqlite\"\n :subname \"/home/liuwensui/Downloads/chinook.db\"})\n \n(def orders (j/query db \"select billingcountry as country, count(*) as orders from invoices group by billingcountry;\"))\n \n(def clist '(\"USA\" \"India\" \"Canada\" \"France\")\n\n(def country (map #(get % :country) orders))\n\n(p/print-table \n (map #(nth orders %) \n (flatten (pmap (fn [c] (keep-indexed (fn [i v] (if (= v c) i)) country)) clist))))\n\n;| :country | :orders |\n;|----------+---------|\n;| USA | 91 |\n;| India | 13 |\n;| Canada | 56 |\n;| France | 35 |","_id":"5b1476f4e4b00ac801ed9e0a"},{"updated-at":1545622986549,"created-at":1542944952784,"author":{"login":"gluer","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/22495106?v=4"},"body":";; a simple example\n(map-indexed #(when (< % 2) (str % %2)) [:a :b :c])\n;;=> (\"0:a\" \"1:b\" nil)\n\n(keep-indexed #(when (< % 2) (str % %2)) [:a :b :c])\n;;=> (\"0:a\" \"1:b\")","editors":[{"avatar-url":"https://avatars3.githubusercontent.com/u/22495106?v=4","account-source":"github","login":"gluer"}],"_id":"5bf778b8e4b0ca44402ef5c8"},{"editors":[{"login":"kevinmungai","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/23656776?v=4"}],"body":";; returns a new list by removing the elements at odd positions\n(defn filter-list-by-position\n [lst]\n (into []\n (keep-indexed #(when (odd? %1) %2)) ;; transducer\n lst))\n\n;; 0 1 2 3 4 5 6 8\n(def nums [2 5 3 4 6 7 9 8])\n\n(filter-list-by-position nums)\n;;=> [5 4 7 8]","author":{"avatar-url":"https://avatars3.githubusercontent.com/u/23656776?v=4","account-source":"github","login":"kevinmungai"},"created-at":1594505780319,"updated-at":1594505852298,"_id":"5f0a3a34e4b0b1e3652d731f"}],"notes":null,"arglists":["f","f coll"],"doc":"Returns a lazy sequence of the non-nil results of (f index item). Note,\n this means false return values will be included. f must be free of\n side-effects. Returns a stateful transducer when no collection is\n provided.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/keep-indexed"},{"added":"1.5","ns":"clojure.core","name":"cond->>","file":"clojure/core.clj","type":"macro","column":1,"see-alsos":[{"created-at":1432152383427,"author":{"login":"x","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/693546?v=3"},"to-var":{"ns":"clojure.core","name":"cond->","library-url":"https://github.com/clojure/clojure"},"_id":"555ce93fe4b01ad59b65f4d4"},{"created-at":1432152404184,"author":{"login":"x","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/693546?v=3"},"to-var":{"ns":"clojure.core","name":"as->","library-url":"https://github.com/clojure/clojure"},"_id":"555ce954e4b03e2132e7d165"},{"created-at":1432152431951,"author":{"login":"x","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/693546?v=3"},"to-var":{"ns":"clojure.core","name":"->","library-url":"https://github.com/clojure/clojure"},"_id":"555ce96fe4b01ad59b65f4d6"},{"created-at":1432152437689,"author":{"login":"x","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/693546?v=3"},"to-var":{"ns":"clojure.core","name":"->>","library-url":"https://github.com/clojure/clojure"},"_id":"555ce975e4b03e2132e7d167"},{"created-at":1537310356172,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"cond","ns":"clojure.core"},"_id":"5ba17e94e4b00ac801ed9ea0"},{"created-at":1537310390943,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"case","ns":"clojure.core"},"_id":"5ba17eb6e4b00ac801ed9ea1"}],"line":7747,"examples":[{"editors":[{"login":"x","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/693546?v=3"}],"updated-at":1458757086103,"created-at":1432152126897,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/693546?v=3","account-source":"github","login":"x"},"body":";; useful for when you want to control doing a bunch of things to a lazy sequence \n;; based on some conditions or, commonly, keyword arguments to a function.\n\n(defn do-stuff\n [coll {:keys [map-fn max-num-things batch-size]}]\n (cond->> coll\n map-fn (map map-fn)\n max-num-things (take max-num-things)\n batch-size (partition batch-size)))\n\nuser=> (do-stuff [1 2 3 4] {})\n[1 2 3 4]\nuser=> (do-stuff [1 2 3 4] {:map-fn str})\n(\"1\" \"2\" \"3\" \"4\")\nuser=> (do-stuff [1 2 3 4] {:map-fn str :batch-size 2})\n((\"1\" \"2\") (\"3\" \"4\"))\nuser=> (do-stuff [1 2 3 4] {:map-fn str :max-num-things 3})\n(\"1\" \"2\" \"3\")","_id":"555ce83ee4b01ad59b65f4d2"}],"macro":true,"notes":null,"arglists":["expr & clauses"],"doc":"Takes an expression and a set of test/form pairs. Threads expr (via ->>)\n through each form for which the corresponding test expression\n is true. Note that, unlike cond branching, cond->> threading does not short circuit\n after the first true test expression.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/cond->>"},{"added":"1.0","ns":"clojure.core","name":"subs","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1318625011000,"author":{"login":"mmwaikar","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/29d36f4c9f39c9f8ff61c07033b13118?r=PG&default=identicon"},"to-var":{"ns":"clojure.string","name":"replace","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f3a"},{"created-at":1318625250000,"author":{"login":"mmwaikar","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/29d36f4c9f39c9f8ff61c07033b13118?r=PG&default=identicon"},"to-var":{"ns":"clojure.string","name":"split","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f3b"},{"created-at":1379039766000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.string","name":"replace-first","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f3c"},{"created-at":1379039915000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.core","name":"re-find","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f3d"},{"created-at":1379039920000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.core","name":"re-seq","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f3e"},{"created-at":1379039970000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.core","name":"re-matches","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f3f"}],"line":5034,"examples":[{"author":{"login":"citizen428","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/b3881a28fe402dd2d1de44717486cae8?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":"user=> (subs \"Clojure\" 1) \n\"lojure\"\nuser=> (subs \"Clojure\" 1 3)\n\"lo\"\n\n\n;; String indexes have to be between 0 and (.length s)\n\nuser=> (subs \"Clojure\" 1 20)\njava.lang.StringIndexOutOfBoundsException: String index out of range: 20 (NO_SOURCE_FILE:0)\n","created-at":1280470619000,"updated-at":1285496389000,"_id":"542692ccc026201cdc326cab"},{"updated-at":1513303984796,"created-at":1379039736000,"body":";; Note that subs uses method java.lang.String/substring\n;; http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#substring%28int,%20int%29\n\n;; See this link for more details:\n\n;; https://dzone.com/articles/changes-stringsubstring-java-7\n\n;; This link was the original, but seems to no longer exist as of Nov 2017:\n;; http://www.javaadvent.com/2012/12/changes-to-stringsubstring-in-java-7.html\n\n;; Briefly, before Java version 7u6, Java's substring method was\n;; guaranteed to work in O(1) time, by creating a String that refers\n;; to the original string's characters, rather than copying them.\n\n;; After Java 7u6, substring was changed to copy the string's original\n;; characters, thus taking time linear in the length of the substring,\n;; but it never refers to the original string.\n\n;; The potential disadvantage of the pre-version-7u6 behavior is that\n;; if you read in one or more strings with a large total size, and then\n;; use methods based on substring to keep only a small subset of that,\n;; e.g., because you parsed and found a small collection of substrings of\n;; interest for your computation, the large strings will still have\n;; references to them, and thus cannot be garbage collected, even if you\n;; have no other references to them.\n\n;; You can use the Java constructor (String. s) to guarantee that you\n;; copy a string s. (String. (subs s 5 20)) will copy the substring once\n;; pre-version-7u6, but it will copy the substring twice\n;; post-version-7u6.\n\n;; I believe java.util.regex.Matcher method group, and\n;; java.util.regex.Pattern method split, also have the same\n;; behavior as substring.\n\n;; This affects the behavior of Clojure functions such as:\n\n;; In clojure.core:\n;; subs, re-find, re-matches, re-seq\n;; In clojure.string:\n;; replace replace-first split\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3","account-source":"github","login":"jafingerhut"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3","account-source":"github","login":"jafingerhut"},"_id":"542692d5c026201cdc32709d"},{"updated-at":1517506971847,"created-at":1517506971847,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"},"body":";; Suppose you want to shorten a string of blanks [outdent]\n;; Starting with a string of length 5\n;; [Here I do not use blanks to illustrate what is happening]\n(def s5 \"abcdef\")\n;; and reducing its length by 2\n(subs s5 (min 2 (count s5))) \n;=> \"cdef\"\n(subs s5 (min 10 (count s5))) \n;=> \"\"","_id":"5a73519be4b0c974fee49d19"},{"updated-at":1767193509472,"created-at":1767193509472,"author":{"login":"wdhowe","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/4631165?v=4"},"body":";; Remove the last character in a string\n(def s \"/my/dir/path/\")\n\n(subs s 0 (dec (count s)))\n\n;=> \"/my/dir/path\"","_id":"69553ba5b7956e24e4cb4ec7"}],"notes":null,"arglists":["s start","s start end"],"doc":"Returns the substring of s beginning at start inclusive, and ending\n at end (defaults to length of string), exclusive.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/subs"},{"added":"1.1","ns":"clojure.core","name":"ref-min-history","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1364770283000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"ref","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c63"},{"created-at":1364770288000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"ref-max-history","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c64"},{"created-at":1364770294000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"ref-history-count","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c65"}],"line":2487,"examples":[{"editors":[{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"}],"body":"(def r (ref 0))\n(ref-min-history r)\n;; 0\n\n(ref-min-history r 1) ; setter\n;; #object[clojure.lang.Ref 0x1f3f02ee {:status :ready, :val 0}]\n\n(ref-min-history r) ; getter\n;; 1\n","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"},"created-at":1550443391880,"updated-at":1553683971669,"_id":"5c69e37fe4b0ca44402ef68d"},{"updated-at":1550443972155,"created-at":1550443972155,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"body":";; Setting the min history > 0 \n;; prevents read faults and related TX restart.\n;; Here T2 changes r after T1 started but haven't deref r yet.\n\n(def r (ref 0)) ; min-history is zero\n\n(future\n (dosync\n (println \"-Tx starting-\")\n (Thread/sleep 10000)\n (println \"T1:\" @r)))\n;; -Tx starting-\n\n(future\n (dosync\n (println \"T2:\" (alter r inc))))\n;; T2: 1\n;; -Tx starting-\n;; T1: 1\n\n;; Here T1 has one ref history value available and\n;; does not restart.\n(def r (ref 0))\n(ref-min-history r 1)\n\n(future\n (dosync\n (println \"-Tx starting-\")\n (Thread/sleep 10000)\n (println \"T1:\" @r)))\n;; -Tx starting-\n\n(future\n (dosync\n (println \"T2:\" (alter r inc))))\n;; T2: 1\n;; T1: 0","_id":"5c69e5c4e4b0ca44402ef68e"}],"notes":null,"arglists":["ref","ref n"],"doc":"Gets the min-history of a ref, or sets it and returns the ref","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/ref-min-history"},{"added":"1.0","ns":"clojure.core","name":"set","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1289811222000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"hash-set","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f12"},{"created-at":1289811227000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"sorted-set","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f13"},{"created-at":1289811237000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"conj","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f14"},{"created-at":1313621942000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.set","name":"join","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f15"},{"created-at":1313621949000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.set","name":"select","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f16"},{"created-at":1313621954000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.set","name":"difference","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f17"},{"created-at":1313621961000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.set","name":"intersection","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f18"},{"created-at":1313621965000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.set","name":"union","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f19"},{"created-at":1313621977000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.set","name":"index","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f1a"},{"created-at":1313621988000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.set","name":"project","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f1b"},{"created-at":1313621999000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.set","name":"rename","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f1c"},{"created-at":1313622003000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.set","name":"rename-keys","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f1d"},{"created-at":1313622018000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.set","name":"map-invert","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f1e"},{"created-at":1313622048000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"disj","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f1f"},{"created-at":1315819885000,"author":{"login":"wdkrnls","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/6d08a2f792f289b95fe1d982d4133d71?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"distinct","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f20"}],"line":4131,"examples":[{"author":{"avatar-url":"https://avatars2.githubusercontent.com/u/22608?v=4","account-source":"github","login":"MrHus"},"editors":[{"login":"seancorfield","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9354eec0679e2d3b36b77ff62165f717?r=PG&default=identicon"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"rafmagana","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/92894?v=3"},{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"}],"body":";; returns distinct elements\nuser=> (set '(1 1 2 3 2 4 5 5))\n#{1 2 3 4 5}\n\n;; returns distinct elements (different nomenclature)\nuser=> (set [1 1 2 3 2 4 5 5])\n#{1 2 3 4 5}\n\nuser=> (set [1 2 3 4 5]) \n#{1 2 3 4 5}\n\nuser=> (set \"abcd\")\n#{\\a \\b \\c \\d}\n\nuser=> (set '(\"a\" \"b\" \"c\" \"d\"))\n#{\"a\" \"b\" \"c\" \"d\"}\n\nuser=> (set {:one 1 :two 2 :three 3})\n#{[:two 2] [:three 3] [:one 1]}\n\nuser=> (set nil)\n#{}","created-at":1279417897000,"updated-at":1423275927213,"_id":"542692cbc026201cdc326bfb"},{"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"editors":[{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"}],"body":"(set [1 2 3 2 1 2 3])\n-> #{1 2 3}\n\n#{:a :b :c :d}\n-> #{:d :a :b :c}\n\n(hash-set :a :b :c :d)\n-> #{:d :a :b :c}\n \n(sorted-set :a :b :c :d)\n-> #{:a :b :c :d}\n\n;------------------------------------------------\n\n(def s #{:a :b :c :d})\n(conj s :e)\n-> #{:d :a :b :e :c}\n \n(count s)\n-> 4\n \n(seq s)\n-> (:d :a :b :c)\n \n(= (conj s :e) #{:a :b :c :d :e})\n-> true\n\n(s :b)\n-> :b\n \n(s :k)\n-> nil","created-at":1289811205000,"updated-at":1289811299000,"_id":"542692cbc026201cdc326bff"}],"notes":[{"updated-at":1316747546000,"body":"The documentation doesn't mention the order, is it undefined?\r\n\r\n#{:a :b :c :d}\r\n-> #{:d :a :b :c}\r\n","created-at":1316747546000,"author":{"login":"icefox","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/dc848256f8954abd612cbe7e81859f91?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fce"},{"author":{"login":"venantius","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1824859?v=3"},"updated-at":1476386802865,"created-at":1476386802865,"body":"Sets are a core data structure that by definition do not store elements in a sorted order. The actual order will ultimately be determined by the specific hashing function underpinning the data structure. ","_id":"57ffdff2e4b001179b66bdcc"},{"author":{"login":"dhbarnett","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/1676252?v=4"},"updated-at":1568233525282,"created-at":1568233525282,"body":"Is the order guaranteed to be consistent if so is it not ordered (just not asc/desc)? ","_id":"5d795835e4b0ca44402ef7b2"},{"author":{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"},"updated-at":1573849219982,"created-at":1573849219982,"body":"Sets are not ordered, so there’s not guarantee on their “order”.","_id":"5dcf0883e4b0ca44402ef7e0"}],"arglists":["coll"],"doc":"Returns a set of the distinct elements of coll.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/set"},{"added":"1.1","ns":"clojure.core","name":"take-last","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1306817623000,"author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"to-var":{"ns":"clojure.core","name":"last","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d0d"},{"created-at":1306817710000,"author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"to-var":{"ns":"clojure.core","name":"butlast","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d0e"},{"created-at":1306817740000,"author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"to-var":{"ns":"clojure.core","name":"drop-last","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d0f"},{"created-at":1473271791957,"author":{"login":"mars0i","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1836941?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"subvec","ns":"clojure.core"},"_id":"57d057efe4b0709b524f04ea"}],"line":2964,"examples":[{"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"}],"body":"user=> (take-last 2 [1 2 3 4])\n(3 4)\n\nuser=> (take-last 2 [4])\n(4)\n\nuser=> (take-last 2 [])\nnil\n\nuser=> (take-last 2 nil)\nnil\n\nuser=> (take-last 0 [1])\nnil\n\nuser=> (take-last -1 [1])\nnil","created-at":1280323099000,"updated-at":1423278794590,"_id":"542692cec026201cdc326de0"},{"editors":[{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"}],"body":";; take-last is rarely what you want from a pure performance perspective,\n;; although for small collections, it's not worth worrying about\n;; unless it's on a hot path.\n\n;; let's make an alternative version, using drop:\n(defn my-take-last [n coll]\n (drop (- (count coll) n) coll))\n\n(require '[criterium.core :as c])\n;; For lazy-sequences, where we are taking a small number of elements,\n;; take-last can be faster:\n(->> (c/benchmark-round-robin [(dorun (take-last 2 (map inc (range 100))))\n (dorun (my-take-last 2 (map inc (range 100))))]\n c/*default-benchmark-opts*)\n (map (comp first :mean)))\n;; => (1.968E-6 2.613E-6)\n;; So, they both take a few microseconds. Rarely important.\n;; But take-last is ~25% faster\n\n;; For lazy-sequences where we are taking a large number of elemnts,\n;; the advantage disappears:\n(->> (c/benchmark-round-robin [(dorun (take-last 92 (map inc (range 100))))\n (dorun (my-take-last 92 (map inc (range 100))))]\n c/*default-benchmark-opts*)\n (map (comp first :mean)))\n;; => (2.517E-6 2.150E-6)\n;; take-last is ~17% slower here. But we're still on microsecond scales.\n\n;; For counted collections, take-last is noticeably slower:\n(->> (c/benchmark-round-robin [(dorun (take-last 2 (mapv inc (range 100))))\n (dorun (my-take-last 2 (mapv inc (range 100))))]\n c/*default-benchmark-opts*)\n (map (comp first :mean)))\n;; => (2.183E-6 1.230E-6)\n;; take-last is ~77% slower here, and it only gets worse the larger collections get\n\n;; For vectors specifically, subvec can be even faster:\n(defn my-vec-take-last [n v]\n (subvec v (- (count v) n)))\n\n(->> (c/benchmark-round-robin [(dorun (take-last 2 (mapv inc (range 100))))\n (dorun (my-vec-take-last 2 (mapv inc (range 100))))]\n c/*default-benchmark-opts*)\n (map (comp first :mean)))\n;; => (2.075E-6 1.133E-6)\n;; take-last is ~83% slower here\n\n;; For readability, take-last communicates intent well, but for hot-paths,\n;; it's worth knowing it's (sometimes significantly) slower than alternatives\n","author":{"avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4","account-source":"github","login":"tomdl89"},"created-at":1765584527875,"updated-at":1765589793404,"_id":"693cae8fb7956e24e4cb4ec0"}],"notes":[{"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"updated-at":1521555189789,"created-at":1521555189789,"body":"Unlike \"drop-last\" (but like \"last\"), \"take-last\" is not lazy:\n\n
\n(def bomb (take-last 1 (range))) ;; infinite evaluation, never returns\n(def lazy-bomb (drop-last 1 (range))) ;; good, but don't use!\n
","_id":"5ab116f5e4b045c27b7fac1a"}],"arglists":["n coll"],"doc":"Returns a seq of the last n items in coll. Depending on the type\n of coll may be no better than linear time. For vectors, see also subvec.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/take-last"},{"added":"1.0","ns":"clojure.core","name":"bit-set","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1461359248259,"author":{"login":"fasiha","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/37649?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"bit-test","ns":"clojure.core"},"_id":"571a9290e4b0e6b5e3f27e5c"},{"created-at":1527805055459,"author":{"login":"NealEhardt","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/1338977?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"bit-clear","ns":"clojure.core"},"_id":"5b10747fe4b045c27b7fac8a"}],"line":1351,"examples":[{"updated-at":1461359232399,"created-at":1280337241000,"body":"user=> (bit-set 2r1011 2) ; index is 0-based\n15 \n;; 15 = 2r1111\n\n;; the same in decimal\nuser=> (bit-set 11 2) \n15","editors":[{"avatar-url":"https://www.gravatar.com/avatar/68dd6f50915854aa04fefcf4d6fa5c8e?r=PG&default=identicon","account-source":"clojuredocs","login":"zmila"},{"avatar-url":"https://www.gravatar.com/avatar/68dd6f50915854aa04fefcf4d6fa5c8e?r=PG&default=identicon","account-source":"clojuredocs","login":"zmila"},{"login":"fasiha","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/37649?v=3"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/68dd6f50915854aa04fefcf4d6fa5c8e?r=PG&default=identicon","account-source":"clojuredocs","login":"zmila"},"_id":"542692c7c026201cdc32696f"},{"editors":[{"login":"fasiha","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/37649?v=3"}],"body":";; Returns a long, like all Clojure bit operations\nuser=> (bit-set 0 63)\n-9223372036854775808\n; A signed 64-bit number with only the sign bit (most significant bit) on.\n; This is the most negative number representable by signed 64 bits: -(2**63).\n; Same as:\nuser=> (bit-shift-left 1 63)\n-9223372036854775808\n\n;; And in case you forget your common powers to two, here's a reference ^^\nuser=> (bit-set 0 32)\n4294967296\nuser=> (bit-set 0 16)\n65536\nuser=> (bit-set 0 8)\n256\nuser=> (bit-set 0 4)\n16","author":{"avatar-url":"https://avatars.githubusercontent.com/u/37649?v=3","account-source":"github","login":"fasiha"},"created-at":1461359743597,"updated-at":1461359793455,"_id":"571a947fe4b0e6b5e3f27e5d"}],"notes":null,"arglists":["x n"],"doc":"Set bit at index n","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/bit-set"},{"added":"1.7","ns":"clojure.core","name":"reader-conditional","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1495962203638,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"reader-conditional?","ns":"clojure.core"},"_id":"592a925be4b093ada4d4d776"},{"created-at":1495962209101,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"read","ns":"clojure.core"},"_id":"592a9261e4b093ada4d4d777"},{"created-at":1495962222485,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"read-string","ns":"clojure.core"},"_id":"592a926ee4b093ada4d4d778"}],"line":7976,"examples":[{"updated-at":1495962191755,"created-at":1495962191755,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"body":";;;; The data representation for reader conditionals is used by Clojure\n;;;; when reading a string/file into Clojure data structures but choosing \n;;;; to preserve the conditionals themselves (instead of replacing them with\n;;;; the appropriate platform-specific code)\n\n;;;; Create a data representation for a NON-SPLICING reader conditional\n\n(def r-cond (reader-conditional '(:clj (Math/random)) false))\n;;=> #'user/r-cond\nr-cond\n;;=> #?(:clj (Math/random))\n(:form r-cond)\n;;=> (:clj (Math/random))\n(:splicing? r-cond)\n;;=> false\n\n;;;; Data representation is same as the one produced by (read-string)\n;;;; and (read) when provided with the option to preserve data conditionals\n\n(= r-cond (read-string {:read-cond :preserve} \"#?(:clj (Math/random))\"))\n;;=> true\n\n;;;; Create a data representation for a SPLICING reader conditional\n\n(def r-cond (reader-conditional '(:clj [Math/PI Math/E]) true))\n;;=> #'user/r-cond\n(:clj [Math/PI Math/E])\n;;=> #?@(:clj [Math/PI Math/E])\n(:form r-cond)\n;;=> (:clj [Math/PI Math/E])\n(:splicing? r-cond)\n;;=> true\n\n;;;; Data representation is same as the one produced by (read-string)\n;;;; and (read) when provided with the option to preserve data conditionals\n\n(= r-cond (read-string {:read-cond :preserve} \"#?@(:clj [Math/PI Math/E])\"))\n;;=> true","_id":"592a924fe4b093ada4d4d775"}],"notes":null,"arglists":["form splicing?"],"doc":"Construct a data representation of a reader conditional.\n If true, splicing? indicates read-cond-splicing.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/reader-conditional"},{"added":"1.0","ns":"clojure.core","name":"gen-class","file":"clojure/genclass.clj","type":"macro","column":1,"see-alsos":[{"created-at":1360270663000,"author":{"login":"AtKaaZ","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e10dfa345f44b0fe72bbe081fd51b83?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"proxy","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bd7"},{"created-at":1360270670000,"author":{"login":"AtKaaZ","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e10dfa345f44b0fe72bbe081fd51b83?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"gen-interface","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bd8"}],"line":518,"examples":[{"author":{"login":"devijvers","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/81018e4231ac1ce8b7a9e6d377092656?r=PG&default=identicon"},"editors":[{"login":"devijvers","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/81018e4231ac1ce8b7a9e6d377092656?r=PG&default=identicon"},{"login":"devijvers","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/81018e4231ac1ce8b7a9e6d377092656?r=PG&default=identicon"},{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":"(gen-class\n\t:name \"some.package.RefMap\"\n\t:implements [java.util.Map]\n\t:state \"state\"\n\t:init \"init\"\n\t:constructors {[] []}\n\t:prefix \"ref-map-\")\n\n(defn ref-map-init []\n\t[[] (ref {})])\n\n(defn ref-map-size [this]\n\t(let [state (.state this)] (.size @state)))\n\t\n(defn ref-map-isEmpty [this]\n\t(let [state (.state this)] (.isEmpty @state)))\n\n(defn ref-map-containsKey [this o]\n\t(let [state (.state this)] (.containsKey @state o)))\n\t\n(defn ref-map-containsValue [this o]\n\t(let [state (.state this)] (.containsValue @state o)))\n\t\n(defn ref-map-get [this o]\n\t(let [state (.state this)] (.get @state o)))\n\t\n(defn ref-map-keySet [this]\n\t(let [state (.state this)] (.keySet @state)))\n\t\n(defn ref-map-values [this]\n\t(let [state (.state this)] (.values @state)))\n\t\n(defn ref-map-entrySet [this]\n\t(let [state (.state this)] (.entrySet @state)))\n\t\n(defn ref-map-equals [this o]\n\t(let [state (.state this)] (.equals @state o)))\n\t\n(defn ref-map-hashCode [this]\n\t(let [state (.state this)] (.hashCode @state)))\n\t\n(defn ref-map-put [this k v]\n\t(let [state (.state this)] \n\t\t(dosync (alter state assoc k v)) v))\n\t\n(defn ref-map-putAll [this m]\n\t(let [state (.state this)]\n\t\t(doseq [[k v] (map identity m)] (.put this k v))))\n\t\t\n(defn ref-map-remove [this o]\n\t(let [state (.state this) v (get @state o)] \n\t\t(dosync (alter state dissoc o)) v))\n\t\n(defn ref-map-clear [this]\n\t(let [state (.state this)] \n\t\t(dosync (ref-set state {}))))\n\t\n(defn ref-map-toString [this]\n\t(let [state (.state this)] (.toString @state)))","created-at":1279770352000,"updated-at":1332952789000,"_id":"542692cec026201cdc326dab"},{"author":{"login":"daviddurand","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1316941?v=2"},"editors":[],"body":";; I found managing state a bit confusing at first.\n;; here's a dumb little class with a getter and setter for a \"location\" field.\n\n(ns com.example )\n\n(gen-class\n :name com.example.Demo\n :state state\n :init init\n :prefix \"-\"\n :main false\n ;; declare only new methods, not superclass methods\n :methods [[setLocation [String] void]\n [getLocation [] String]])\n\n;; when we are created we can set defaults if we want.\n(defn -init []\n \"store our fields as a hash\"\n [[] (atom {:location \"default\"})])\n\n;; little functions to safely set the fields.\n(defn setfield\n [this key value]\n (swap! (.state this) into {key value}))\n\n(defn getfield\n [this key]\n (@(.state this) key))\n\n;; \"this\" is just a parameter, not a keyword\n(defn -setLocation [this loc]\n (setfield this :location loc))\n\n(defn -getLocation\n [this]\n (getfield this :location))\n\n;; running it -- you must compile and put output on the classpath\n;; create a Demo, check the default value, then set it and check again.\nuser=> (def ex (com.example.Demo.))\n#'user/ex\nuser=> (.getLocation ex)\n\"default\"\nuser=> (.setLocation ex \"time\")\nnil\nuser=> (.getLocation ex)\n\"time\"\n","created-at":1325884685000,"updated-at":1325884685000,"_id":"542692d3c026201cdc326fbb"},{"editors":[{"login":"mars0i","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/1836941?v=4"}],"body":";; This example illustrates the syntax intended by the docstring's remark that \n;; \"Static methods can be specified with ^{:static true} in the signature's \n;; metadata\", and notes a case in which you might not think that you need to use\n;; :methods.\n\n;; The docs say, about :methods, \"Do not repeat superclass/interface\n;; signatures here.\" That applies to non-static methods. If you want to\n;; define a static method to hide a static method in the superclass, you\n;; are not overriding the superclass method (the behavior is different).\n;; You are simply defining a new method with the same name. In this case,\n;; you should add a signature to :methods if you want your function to be\n;; visible to Java, with metadata indicating that it is static placed\n;; before the signature vector:\n\n(ns \n ...\n (:gen-class \n ...\n :methods [[...] ...\n ^{:static true} [name [] java.lang.String]\n [...] ...]\n ...))\n\n(defn -name [] \"My name is Foo\")\n\n;; Also note that you can replace \"^{:static true}\" with \"^:static\".","author":{"avatar-url":"https://avatars0.githubusercontent.com/u/1836941?v=4","account-source":"github","login":"mars0i"},"created-at":1554533983608,"updated-at":1554575687135,"_id":"5ca84e5fe4b0ca44402ef6fe"},{"updated-at":1558971581245,"created-at":1558971581245,"author":{"login":"holyjak","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/624958?v=4"},"body":";; It is possible to attach Java annotations to the class,\n;; constructors, and methods \n;; Source: https://github.com/clojure/clojure/blob/8af7e9a92570eb28c58b15481ae9c271d891c028/test/clojure/test_clojure/genclass/examples.clj#L34\n(gen-class :name ^{Deprecated {}\n SuppressWarnings [\"Warning1\"] ; discarded\n java.lang.annotation.Target []}\n clojure.test_clojure.genclass.examples.ExampleAnnotationClass\n :prefix \"annot-\"\n :methods [[^{Deprecated {}\n Override {}} ;discarded\n foo [^{java.lang.annotation.Retention java.lang.annotation.RetentionPolicy/SOURCE\n java.lang.annotation.Target [java.lang.annotation.ElementType/TYPE\n java.lang.annotation.ElementType/PARAMETER]}\n String] void]])\n","_id":"5cec04bde4b0ca44402ef72b"},{"updated-at":1625726462164,"created-at":1625726462164,"author":{"login":"mattiuusitalo","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/47240847?v=4"},"body":";; Defining a custom constructor which calls a superclass constructor:\n(ns my.CustomException\n (:gen-class\n :implements [clojure.lang.IExceptionInfo]\n :extends java.lang.RuntimeException\n :constructors {[String Throwable clojure.lang.IPersistentMap] [String Throwable]} ; mapping of my-constructor -> superclass constuctor\n :init init\n :state state ; name for the var that holds your internal state\n :main false\n :prefix \"my-ex-\"))\n\n(defn my-ex-init [msg t context]\n ;; first element of vector contains parameters for the superclass constructor\n ;; Second element will be your internal state \n [[msg t] context]) \n\n(defn my-ex-getData [this]\n (.state this)) ; accessing the internal state\n","_id":"60e69dfee4b0b1e3652d7513"}],"macro":true,"notes":[{"updated-at":1280115806000,"body":"When implementing interface methods with `gen-class` (when using `:implements`) watch out for primitive return types in interface methods.\r\n\r\nWhen you get weird `NullPointerException`s or `ClassPathException`s then make sure whether the value returned by your functions can be converted by Clojure to the primitive return type defined in the interface for that method.\r\n\r\nExample:\r\n\r\nGiven:\r\n\r\n
\r\ninterface Test {\r\n   boolean isTest();\r\n}\r\n
\r\n\r\nClojure implementation:\r\n\r\n
\r\n(gen-class :name \"MyTest\" :implements [Test])\r\n\r\n; Will throw NPE when executed, \r\n; can't be converted to boolean\r\n(defn -isTest [this] nil) \r\n
\r\n\r\n
\r\n(gen-class :name \"MyTest\" :implements [Test])\r\n\r\n; Will throw ClassCastExcpetion when executed, \r\n; can't be converted to boolean\r\n(defn -isTest [this] (Object.)) \r\n
","created-at":1280115806000,"author":{"login":"devijvers","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/81018e4231ac1ce8b7a9e6d377092656?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521f8a"},{"updated-at":1311325790000,"body":"When implementing an interface or extending an abstract class that implements an interface, be careful to implement all methods in the implemented interfaces. Note: The abstract class is not required to implement all methods in the interface. The clojure compiler does not throw compiler errors if you do not implement a method. A runtime error will be thrown when someone tries to use the function. The documentation suggests that you will receive UnsupportedOperationException, however in the case of the abstract class a java.lang.AbstractMethodError is thrown. \r\n\r\n**example:**\r\n\r\nLog4j appender - Extending AppenderSkeleton will fail with runtime error\r\n
(gen-class :name clj.TestAppender :extends  org.apache.log4j.AppenderSkeleton)\r\n\r\n(defn -append [this event]\r\n  (println (.getMessage event)))\r\n
\r\n\r\n\r\nNeed to implement close and requireLayout. These are not in AppenderSkeleton but are required by the interface Appender.\r\n
(gen-class :name TstAppender :extends org.apache.log4j.AppenderSkeleton)\r\n\r\n(defn -append [this event]\r\n  (println (.getMessage event)))\r\n\r\n(defn -close [this]) ;nothing to clean up\r\n\r\n(defn -requireLayout [this] false)\r\n\r\n
\r\n\r\n\r\n","created-at":1306791528000,"author":{"login":"ckirkendall","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/c29cd3a5f182e6de85cbd172fb9b5ab8?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fbf"},{"body":"If your namespace has dashes in it, then the class name will be mangled so the dashes become underscores, unless you have a :name directive. Your naive instantiation will fail with ClassNotFoundException.\n\n (ns my-project.MyClass\n (:gen-class))\n\n (my-project.MyClass.) ;;=> java.lang.ClassNotFoundException\n (my_project.MyClass.) ;;=> #","created-at":1418209544515,"updated-at":1418209661100,"author":{"login":"alilee","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/16739?v=3"},"_id":"54882908e4b04e93c519ffa1"},{"author":{"login":"staypufd","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/10730?v=4"},"updated-at":1518392816391,"created-at":1518392816391,"body":"Note: If you are using :extends you must use the fully qualified class name even if the class is in the :import list for the namespace. ","_id":"5a80d5f0e4b0316c0f44f8b8"},{"author":{"login":"mars0i","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/1836941?v=4"},"updated-at":1554575508996,"created-at":1554575508996,"body":"Not strictly speaking a `gen-class` issue, but if you need to override a Java method that's overloaded by specifying different classes for its arguments, this can be done by incorporating the class names into Clojure function names. See:\n\nhttps://groups.google.com/forum/#!topic/clojure/TVRsy4Gnf70\n\nhttps://puredanger.github.io/tech.puredanger.com/2011/08/12/subclassing-in-clojure\n\nhttp://stackoverflow.com/questions/32773861/clojure-gen-class-for-overloaded-and-overridden-methods\n\nhttp://dishevelled.net/Tricky-uses-of-Clojure-gen-class-and-AOT-compilation.html\n","_id":"5ca8f094e4b0ca44402ef705"}],"arglists":["& options"],"doc":"When compiling, generates compiled bytecode for a class with the\n given package-qualified :name (which, as all names in these\n parameters, can be a string or symbol), and writes the .class file\n to the *compile-path* directory. When not compiling, does\n nothing. The gen-class construct contains no implementation, as the\n implementation will be dynamically sought by the generated class in\n functions in an implementing Clojure namespace. Given a generated\n class org.mydomain.MyClass with a method named mymethod, gen-class\n will generate an implementation that looks for a function named by \n (str prefix mymethod) (default prefix: \"-\") in a\n Clojure namespace specified by :impl-ns\n (defaults to the current namespace). All inherited methods,\n generated methods, and init and main functions (see :methods, :init,\n and :main below) will be found similarly prefixed. By default, the\n static initializer for the generated class will attempt to load the\n Clojure support code for the class as a resource from the classpath,\n e.g. in the example case, ``org/mydomain/MyClass__init.class``. This\n behavior can be controlled by :load-impl-ns\n\n Note that methods with a maximum of 18 parameters are supported.\n\n In all subsequent sections taking types, the primitive types can be\n referred to by their Java names (int, float etc), and classes in the\n java.lang package can be used without a package qualifier. All other\n classes must be fully qualified.\n\n Options should be a set of key/value pairs, all except for :name are optional:\n\n :name aname\n\n The package-qualified name of the class to be generated\n\n :extends aclass\n\n Specifies the superclass, the non-private methods of which will be\n overridden by the class. If not provided, defaults to Object.\n\n :implements [interface ...]\n\n One or more interfaces, the methods of which will be implemented by the class.\n\n :init name\n\n If supplied, names a function that will be called with the arguments\n to the constructor. Must return [ [superclass-constructor-args] state] \n If not supplied, the constructor args are passed directly to\n the superclass constructor and the state will be nil\n\n :constructors {[param-types] [super-param-types], ...}\n\n By default, constructors are created for the generated class which\n match the signature(s) of the constructors for the superclass. This\n parameter may be used to explicitly specify constructors, each entry\n providing a mapping from a constructor signature to a superclass\n constructor signature. When you supply this, you must supply an :init\n specifier. \n\n :post-init name\n\n If supplied, names a function that will be called with the object as\n the first argument, followed by the arguments to the constructor.\n It will be called every time an object of this class is created,\n immediately after all the inherited constructors have completed.\n Its return value is ignored.\n\n :methods [ [name [param-types] return-type], ...]\n\n The generated class automatically defines all of the non-private\n methods of its superclasses/interfaces. This parameter can be used\n to specify the signatures of additional methods of the generated\n class. Static methods can be specified with ^{:static true} in the\n signature's metadata. Do not repeat superclass/interface signatures\n here.\n\n :main boolean\n\n If supplied and true, a static public main function will be generated. It will\n pass each string of the String[] argument as a separate argument to\n a function called (str prefix main).\n\n :factory name\n\n If supplied, a (set of) public static factory function(s) will be\n created with the given name, and the same signature(s) as the\n constructor(s).\n \n :state name\n\n If supplied, a public final instance field with the given name will be\n created. You must supply an :init function in order to provide a\n value for the state. Note that, though final, the state can be a ref\n or agent, supporting the creation of Java objects with transactional\n or asynchronous mutation semantics.\n\n :exposes {protected-field-name {:get name :set name}, ...}\n\n Since the implementations of the methods of the generated class\n occur in Clojure functions, they have no access to the inherited\n protected fields of the superclass. This parameter can be used to\n generate public getter/setter methods exposing the protected field(s)\n for use in the implementation.\n\n :exposes-methods {super-method-name exposed-name, ...}\n\n It is sometimes necessary to call the superclass' implementation of an\n overridden method. Those methods may be exposed and referred in \n the new method implementation by a local name.\n\n :prefix string\n\n Default: \"-\" Methods called e.g. Foo will be looked up in vars called\n prefixFoo in the implementing ns.\n\n :impl-ns name\n\n Default: the name of the current ns. Implementations of methods will be \n looked up in this namespace.\n\n :load-impl-ns boolean\n\n Default: true. Causes the static initializer for the generated class\n to reference the load code for the implementing namespace. Should be\n true when implementing-ns is the default, false if you intend to\n load the code via some other method.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/gen-class"},{"added":"1.9","ns":"clojure.core","name":"qualified-keyword?","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1495715351421,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"keyword?","ns":"clojure.core"},"_id":"5926ce17e4b093ada4d4d766"},{"created-at":1495715368644,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"simple-keyword?","ns":"clojure.core"},"_id":"5926ce28e4b093ada4d4d767"}],"line":1657,"examples":[{"editors":[{"login":"troglotit","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/10955264?v=4"}],"body":"(qualified-keyword? :user/:keyword)\n;;=> true\n(qualified-keyword? ::keyword)\n;;=> true\n\n(qualified-keyword? :keyword)\n;;=> false\n\n(qualified-keyword? \"string\")\n;;=> false\n(qualified-keyword? 42)\n;;=> false\n(qualified-keyword? nil)\n;;=> false","author":{"avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3","account-source":"github","login":"svenschoenung"},"created-at":1495722029967,"updated-at":1525876162343,"_id":"5926e82de4b093ada4d4d768"}],"notes":null,"arglists":["x"],"doc":"Return true if x is a keyword with a namespace","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/qualified-keyword_q"},{"added":"1.0","ns":"clojure.core","name":"while","file":"clojure/core.clj","type":"macro","column":1,"see-alsos":[{"created-at":1360216659000,"author":{"login":"Phalphalak","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a684c0fd4f27597437de953e92a15d4b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"loop","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e4c"},{"created-at":1423524433851,"author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"to-var":{"ns":"clojure.core","name":"dotimes","library-url":"https://github.com/clojure/clojure"},"_id":"54d94251e4b081e022073c7c"},{"created-at":1502829799304,"author":{"login":"huahaiy","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/889685?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"repeatedly","ns":"clojure.core"},"_id":"59935ce7e4b0d19c2ce9d718"},{"created-at":1608681273224,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"swap!","ns":"clojure.core"},"_id":"5fe28739e4b0b1e3652d741d"},{"created-at":1608681301934,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"atom","ns":"clojure.core"},"_id":"5fe28755e4b0b1e3652d741e"}],"line":6404,"examples":[{"updated-at":1608681521678,"created-at":1280547677000,"body":";; a var to be used for its side effects\n(def a (atom 10)) \n;; #'user/a\n\n(while (pos? @a)\n (println @a)\n (swap! a dec))\n;; 10\n;; 9\n;; 8\n;; 7\n;; 6\n;; 5\n;; 4\n;; 3\n;; 2\n;; 1\n;;=> nil","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3","account-source":"github","login":"jafingerhut"},{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3","account-source":"github","login":"phreed"},{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/bcacd00a7f05c4772329cf9f446c7987?r=PG&default=identicon","account-source":"clojuredocs","login":"dakrone"},"_id":"542692ccc026201cdc326c69"},{"editors":[{"login":"slipset","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/5894926?v=3"},{"avatar-url":"https://avatars2.githubusercontent.com/u/87162?v=4","account-source":"github","login":"rafaelrinaldi"},{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"}],"body":";; calculate the MD5 of a file incrementally:\n\n(import\n 'java.io.File\n 'javax.xml.bind.DatatypeConverter\n 'java.security.MessageDigest\n 'java.security.DigestInputStream)\n\n(require '[clojure.java.io :as io])\n\n(defn md5-file [file]\n (let [sha (MessageDigest/getInstance \"MD5\")] \n (with-open [dis (DigestInputStream. (io/input-stream file) sha)] \n (while (> (.read dis) -1))) \n (DatatypeConverter/printHexBinary (.digest sha)))) \n\n(md5-file (File. \"/etc/hosts\"))\n;; \"04F186E74288A10E09DFBF8A88D64A1F33C0E698AAA6B75CDB0AC3ABA87D5644\"","author":{"avatar-url":"https://avatars.githubusercontent.com/u/20086?v=3","account-source":"github","login":"reborg"},"created-at":1469865962017,"updated-at":1518975645400,"_id":"579c5feae4b0bafd3e2a04c3"}],"macro":true,"notes":null,"arglists":["test & body"],"doc":"Repeatedly executes body while test expression is true. Presumes\n some side-effect will cause test to become false/nil. Returns nil","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/while"},{"ns":"clojure.core","name":"->Eduction","file":"clojure/core.clj","type":"function","column":1,"see-alsos":null,"line":7874,"examples":null,"notes":null,"arglists":["xform coll"],"doc":"Positional factory function for class clojure.core.Eduction.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/->Eduction"},{"added":"1.0","ns":"clojure.core","name":"butlast","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1289038922000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"first","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c0b"},{"created-at":1289038928000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"rest","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c0c"},{"created-at":1289038933000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"last","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c0d"},{"created-at":1289038937000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"next","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c0e"},{"created-at":1322055950000,"author":{"login":"mmwaikar","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/29d36f4c9f39c9f8ff61c07033b13118?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"drop-last","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c0f"},{"created-at":1360842503000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"take-last","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c10"},{"created-at":1442106939048,"author":{"login":"miner","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/25400?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"pop","ns":"clojure.core"},"_id":"55f4ce3be4b06a9ffaad4fbd"}],"line":274,"examples":[{"author":{"login":"dpritchett","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/147981?v=3"},"editors":[{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"}],"body":"user=> (butlast [1 2 3])\n(1 2)\nuser=> (butlast (butlast [1 2 3]))\n(1)\nuser=> (butlast (butlast (butlast [1 2 3])))\nnil","created-at":1279073589000,"updated-at":1289038906000,"_id":"542692c8c026201cdc326a4c"},{"updated-at":1438337824330,"created-at":1289038828000,"body":";really slow reverse\n;put the last item of the list at the start of a new list, and recur over all but the last item of the list.\n;butlast acts similar to next in that it returns null for a 1-item list.\n\n(defn my-reverse [xs]\n (when xs\n (cons (last xs) (my-reverse (butlast xs)))))","editors":[{"login":"danneu","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/529580?v=3"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon","account-source":"clojuredocs","login":"boxie"},"_id":"542692c8c026201cdc326a4e"},{"editors":[{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"}],"body":";; A version of (into) that doesn't require (comp)\n;; for multiple transducers.\n\n(defn into* [to & args]\n (into to\n (apply comp (butlast args))\n (last args)))\n\n(into* [] (range 10))\n;; [0 1 2 3 4 5 6 7 8 9]\n\n(into* [] (map inc) (range 10))\n;; [1 2 3 4 5 6 7 8 9 10]\n\n(into* [] (map inc) (filter odd?) (range 10))\n;; [1 3 5 7 9]","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"},"created-at":1521202617879,"updated-at":1765624981872,"_id":"5aabb5b9e4b0316c0f44f926"},{"updated-at":1615302673505,"created-at":1615235547686,"author":{"login":"Crowbrammer","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/19522656?v=4"},"body":";; `butlast` (linear time) vs. `drop-last` (lazy, efficient, more flexible, \n;; constant time(?)) vs. `pop` (fast but requires a vector).\n\n(def r (range 10000))\n\n(time (butlast r)) ;;=> \"Elapsed time: 6.379 msecs\"\n(time (drop-last r)) ;;=> \"Elapsed time: 0.0475 msecs\"\n(time (drop-last 2 r)) ;;=> \"Elapsed time: 0.0569 msecs\"\n(time (drop-last 0 r)) ;;=> \"Elapsed time: 0.098 msecs\"\n(time (drop-last -1 r)) ;;=> \"Elapsed time: 0.0615 msecs\"\n\n(def r-vec (vec r)) ;; to work like `butlast` pop needs a vector \n(time (pop r-vec)) ;;=> \"Elapsed time: 0.062 msecs\"","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/19522656?v=4","account-source":"github","login":"Crowbrammer"}],"_id":"604689dbe4b0b1e3652d7477"}],"notes":[{"author":{"login":"miner","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/25400?v=3"},"updated-at":1442107338476,"created-at":1442107338476,"body":"When using a vector, `pop` is faster than `butlast`.","_id":"55f4cfcae4b05246bdf20a8c"},{"author":{"login":"huahaiy","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/889685?v=4"},"updated-at":1524422433918,"created-at":1524422433918,"body":"`pop` will throw exception if the vector is empty, whereas `butlast` will return `nil`","_id":"5adcd721e4b045c27b7fac4c"},{"author":{"login":"Crowbrammer","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/19522656?v=4"},"updated-at":1615236256681,"created-at":1615235954399,"body":"In my example, `but-last` is ~100 x slower than `drop-last`. `butlast` cannot remove multiple elements from the end, but `drop-last` can. `butlast` seems eager, and `drop-last` seems lazy. 'butlast' will return nil when empty, and `drop-last` will return `'()` when empty. ","_id":"60468b72e4b0b1e3652d747b"}],"arglists":["coll"],"doc":"Return a seq of all but the last item in coll, in linear time","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/butlast"},{"added":"1.2","ns":"clojure.core","name":"satisfies?","file":"clojure/core_deftype.clj","type":"function","column":1,"see-alsos":[{"created-at":1326611358000,"author":{"login":"Claj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5fd658a8d2ef549071cb5286b1b874aa?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"extend","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b64"},{"created-at":1345918796000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"defprotocol","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b65"},{"created-at":1432578777116,"author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"to-var":{"ns":"clojure.core","name":"instance?","library-url":"https://github.com/clojure/clojure"},"_id":"55636ad9e4b03e2132e7d16e"},{"created-at":1501651305911,"author":{"login":"chbrown","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/360279?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"extends?","ns":"clojure.core"},"_id":"59816169e4b0d19c2ce9d706"},{"created-at":1542365684479,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"extenders","ns":"clojure.core"},"_id":"5beea1f4e4b00ac801ed9efe"}],"line":571,"examples":[{"author":{"login":"Jeff Rose","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/567898c496278341be69087507d5ed24?r=PG&default=identicon"},"editors":[],"body":"(ns foo)\n\n(defprotocol Foo\n (foo [this]))\n\n(defprotocol Bar\n (bar [this]))\n\n(extend java.lang.Number\n Bar\n {:bar (fn [this] 42)})\n\n(extend java.lang.String\n Foo\n {:foo (fn [this] \"foo\")}\n Bar\n {:bar (fn [this] \"forty two\")})\n\n(satisfies? Foo \"zam\") ; => true\n(satisfies? Bar \"zam\") ; => true\n(satisfies? Foo 123) ; => false\n(satisfies? Bar 123) ; => true","created-at":1294900425000,"updated-at":1294900425000,"_id":"542692cfc026201cdc326e5a"},{"updated-at":1557925978004,"created-at":1557925978004,"author":{"login":"thenonameguy","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/2217181?v=4"},"body":";; Note that protocol argument should be the var generated by the \n;; defprotocol call, not the Java interface.\n\n(ns a)\n\n(defprotocol Foo\n (foo [this]))\n\n(ns b\n (:require [a])\n (:import a.Foo))\n\n;; bad\n(satisfies? Foo :test) ; => NPE\n;; good\n(satisfies? a/Foo :test) ; => false","_id":"5cdc105ae4b0ca44402ef725"}],"notes":[{"author":{"login":"huahaiy","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/889685?v=4"},"updated-at":1593310454862,"created-at":1593310294294,"body":"Unless this issue is resolved, do not use this function in a hot path, for it is extremely slow. See also this post ","_id":"5ef7fc56e4b0b1e3652d7313"}],"arglists":["protocol x"],"doc":"Returns true if x satisfies the protocol","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/satisfies_q"},{"added":"1.0","ns":"clojure.core","name":"line-seq","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1420222290902,"author":{"login":"kappa","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/47310?v=3"},"to-var":{"ns":"clojure.core","name":"read-line","library-url":"https://github.com/clojure/clojure"},"_id":"54a6df52e4b09260f767ca82"}],"line":3093,"examples":[{"author":{"login":"juergenhoetzel","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2736dfffc803c704dcf25b45ff63cede?r=PG&default=identicon"},"editors":[{"login":"juergenhoetzel","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2736dfffc803c704dcf25b45ff63cede?r=PG&default=identicon"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":";; Count lines of a file (loses head):\nuser=> (with-open [rdr (clojure.java.io/reader \"/etc/passwd\")]\n (count (line-seq rdr)))\n\n","created-at":1279948343000,"updated-at":1285497370000,"_id":"542692cec026201cdc326de3"},{"author":{"login":"TimMc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5d532e51427ef2f4ded31aaca16c8baf?r=PG&default=identicon"},"editors":[],"body":"(import '(java.io BufferedReader StringReader))\n\n;; line terminators are stripped\nuser=> (line-seq (BufferedReader. (StringReader. \"1\\n2\\n\\n3\")))\n(\"1\" \"2\" \"\" \"3\")\n\n;; empty string gives nil\nuser=> (line-seq (BufferedReader. (StringReader. \"\")))\nnil\n","created-at":1301874056000,"updated-at":1301874056000,"_id":"542692cec026201cdc326de7"},{"body":";; read from standard input\nuser=> (nth (line-seq (java.io.BufferedReader. *in*)) 2)\n #_=> 0\n #_=> 1\n #_=> 2\n\"2\"\n","author":{"login":"kappa","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/47310?v=3"},"created-at":1420222563716,"updated-at":1420222563716,"_id":"54a6e063e4b04e93c519ffb0"},{"editors":[{"login":"jimka2001","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/6414129?v=4"},{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"}],"body":";; read a list of lines from a file in the resource directory\n;; suppose the resource file xyzzy/names.csv has lines of the following form,\n;; and we'd like to collect all the male names from year 1966\n;;\n;; gender;name;year;occurrences\n;; F;mary;1965;12\n;; M;john;1966;56\n;; F;sally;1971;5\n;;\n(let [s (clojure.java.io/resource \"xyzzy/names.csv\")]\n (with-open [r (clojure.java.io/reader s)]\n (into #{} (for [line (rest (line-seq r))\n :let [[gender name year _] (clojure.string/split line #\";\")]\n :when (and (= \"1966\" year) (= \"M\" gender))]\n name))))","author":{"avatar-url":"https://avatars.githubusercontent.com/u/6414129?v=4","account-source":"github","login":"jimka2001"},"created-at":1714463468360,"updated-at":1716736918432,"_id":"6630a2ec69fbcc0c226174c3"}],"notes":[{"body":"Documentation says that `line-seq` returns a lazy sequence, however
\nthe actual return value is a `Cons` cell of the first line to a `LazySeq` of
\nthe second line. Calling `realized?` on the `Cons` cell will fail with an exception.\n\n`(cons (.readLine rdr) (lazy-seq (line-seq rdr)))`
\n\nExample:
\n`(def rdr (BufferedReader. (StringReader. \" 1\\n 2\\n 3\")))`
\n`(def x (line-seq rdr))`
\n`(class x)`
\n`=> clojure.lang.Cons`\n\n`(realized? x)`
\n`=> Execution error (ClassCastException) class clojure.lang.Cons cannot be cast to class clojure.lang.IPending`\n\nThe first line was eagerly realized by the initial call to the `line-seq`.
\n`(.readLine rdr)`
\n`=> \" 2\"`","created-at":1620895381108,"updated-at":1620896615263,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/28925709?v=4","account-source":"github","login":"nxtk"},"_id":"609ce695e4b0b1e3652d74fa"}],"arglists":["rdr"],"doc":"Returns the lines of text from rdr as a lazy sequence of strings.\n rdr must implement java.io.BufferedReader.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/line-seq"},{"added":"1.0","ns":"clojure.core","name":"unchecked-subtract-int","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1488034774618,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"unchecked-add-int","ns":"clojure.core"},"_id":"58b19bd6e4b01f4add58fe65"}],"line":1219,"examples":[{"updated-at":1488034725028,"created-at":1488034725028,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10583730?v=3"},"body":";; Subtracting two int-range Longs works\n(unchecked-subtract-int 1 1)\n;;=> 0\n\n;; Subtracting two int-range BigInts works\n(unchecked-subtract-int 1N 1N)\n;;=> 0\n\n;; Doubles are truncated\n(unchecked-subtract-int 1 1.9)\n;;=> 0\n\n;; BigDecimals are truncated\n(unchecked-subtract-int 1 1.9M)\n;;=> 0\n\n;; Uncaught integer overflow\n(unchecked-subtract-int Integer/MAX_VALUE -1)\n;;=> -2147483648\n\n;; Uncaught integer underflow\n(unchecked-subtract-int Integer/MIN_VALUE 1)\n;;=> 2147483647\n\n;; Fails for Longs outside of int range\n(unchecked-subtract-int 2147483648 0)\n;;=> IllegalArgumentException Value out of range for int: 2147483648 clojure.lang.RT.intCast (RT.java:1205)\n\n;; Fails for BigInts outside of int range\n(unchecked-subtract-int 2147483648N 0)\n;;=> IllegalArgumentException Value out of range for int: 2147483648 clojure.lang.RT.intCast (RT.java:1205)\n\n;; Fails for Doubles outside of int range\n(unchecked-subtract-int 2147483648.0 0)\n;;=> IllegalArgumentException Value out of range for int: 2147483648 clojure.lang.RT.intCast (RT.java:1205)\n\n;; Fails for BigDecimals outside of int range\n(unchecked-subtract-int 2147483648.0M 0)\n;;=> IllegalArgumentException Value out of range for int: 2147483648 clojure.lang.RT.intCast (RT.java:1205)","_id":"58b19ba5e4b01f4add58fe64"}],"notes":null,"arglists":["x y"],"doc":"Returns the difference of x and y, both int.\n Note - uses a primitive operator subject to overflow.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/unchecked-subtract-int"},{"added":"1.9","ns":"clojure.core","name":"*print-namespace-maps*","file":"clojure/core_print.clj","type":"var","column":1,"see-alsos":null,"dynamic":true,"line":41,"examples":[{"updated-at":1540400673371,"created-at":1540400673371,"author":{"login":"mainej","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/6774?v=4"},"body":";; In a REPL:\n\n(prn {:num/val 1 :num/name \"one\"})\n;; #:num{:val 1, :name \"one\"}\n;;=> nil\n\n(binding [*print-namespace-maps* false] \n (prn {:num/val 1 :num/name \"one\"}))\n;; {:num/val 1, :num/name \"one\"}\n;;=> nil\n","_id":"5bd0a621e4b00ac801ed9ee9"}],"notes":[{"author":{"login":"katox","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/287639?v=4"},"updated-at":1588435708523,"created-at":1588435708523,"body":"In the Cursive or CIDER REPL the dynamic var is already set (defaults to `true`). Changing the binding would only work within bound expressions but it won't change the behaviour of the REPL itself.\n\nChanging the printing multi-method allows you to \"turn it off\" completely:\n```\n; don't use namespaced maps by default in the REPL\n(defmethod print-method clojure.lang.IPersistentMap [m, ^java.io.Writer w]\n (#'clojure.core/print-meta m w)\n (#'clojure.core/print-map m #'clojure.core/pr-on w))\n```","_id":"5ead9afce4b087629b5a18fc"}],"arglists":[],"doc":"*print-namespace-maps* controls whether the printer will print\n namespace map literal syntax. It defaults to false, but the REPL binds\n to true.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/*print-namespace-maps*"},{"added":"1.0","ns":"clojure.core","name":"take-nth","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1421519147165,"author":{"login":"kappa","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/47310?v=3"},"to-var":{"ns":"clojure.core","name":"partition","library-url":"https://github.com/clojure/clojure"},"_id":"54baa92be4b0e2ac61831cbb"},{"created-at":1544035011111,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"nth","ns":"clojure.core"},"_id":"5c081ac3e4b0ca44402ef5db"},{"created-at":1544035026986,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"rand-nth","ns":"clojure.core"},"_id":"5c081ad2e4b0ca44402ef5dc"}],"line":4314,"examples":[{"updated-at":1285495759000,"created-at":1280776443000,"body":"user=> (take-nth 2 (range 10))\n(0 2 4 6 8)\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3","account-source":"github","login":"devn"},"_id":"542692cec026201cdc326dd9"},{"body":";; N <= 0 is a special case\n(take 3 (take-nth 0 (range 2)))\n;;=> (0 0 0)\n\n(take 3 (take-nth -10 (range 2)))\n;;=> (0 0 0)","author":{"login":"miner","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/25400?v=3"},"created-at":1432222807506,"updated-at":1432222807506,"_id":"555dfc57e4b03e2132e7d169"}],"notes":[{"body":"`(take-nth 0 (range 10))` will loop forever.","created-at":1423278929350,"updated-at":1423278929350,"author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"_id":"54d58351e4b081e022073c6c"},{"body":"(take-nth 0 coll) will return an infinite sequence repeating for first item from coll. A negative N is treated the same as 0.","created-at":1432222489733,"updated-at":1432222489733,"author":{"login":"miner","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/25400?v=3"},"_id":"555dfb19e4b03e2132e7d168"},{"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"updated-at":1522313231902,"created-at":1522253561476,"body":"
\n;; In case you are searching for it, drop-nth is not in core.\n\n(defn drop-nth [n coll]\n  (lazy-seq\n    (when-let [s (seq coll)]\n      (concat (take (dec n) (rest s))\n              (drop-nth n (drop n s))))))\n\n(drop-nth 3 (range 10))\n;; (1 2 4 5 7 8)\n\n;; or alternatively: (keep-indexed #(when-not (zero? (rem %1 n)) %2) coll)\n
","_id":"5abbbef9e4b045c27b7fac29"}],"arglists":["n","n coll"],"doc":"Returns a lazy seq of every nth item in coll. Returns a stateful\n transducer when no collection is provided.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/take-nth"},{"added":"1.0","ns":"clojure.core","name":"first","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1289038142000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"rest","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f64"},{"created-at":1289038147000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"next","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f65"},{"created-at":1303125616000,"author":{"login":"Havvy","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e799a79441c7543be48562403411cd13?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"nth","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f66"},{"created-at":1303125622000,"author":{"login":"Havvy","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e799a79441c7543be48562403411cd13?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"second","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f67"},{"created-at":1328341708000,"author":{"login":"Claj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5fd658a8d2ef549071cb5286b1b874aa?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"take","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f68"},{"created-at":1348637402000,"author":{"login":"dansalmo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e33ee460f5f61bc5ba9b598934766215?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"ffirst","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f69"},{"created-at":1493777583103,"author":{"login":"Juve-yescas","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/26342224?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"butlast","ns":"clojure.core"},"_id":"59093cafe4b01f4add58fea4"},{"created-at":1775094196090,"author":{"login":"wlkr","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/5406568?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"peek","ns":"clojure.core"},"_id":"69cdc9b47955605a202df29f"}],"line":49,"examples":[{"author":{"login":"dpritchett","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/147981?v=3"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":"(first '(:alpha :bravo :charlie))\n;;=> :alpha","created-at":1279071245000,"updated-at":1420735684016,"_id":"542692ccc026201cdc326c6c"},{"updated-at":1545256959607,"created-at":1303680354000,"body":";; nil is a valid (but empty) collection.\n(first nil)\n;;=> nil\n\n;; if collection is empty, returns nil.\n(first [])\n;;=> nil\n\n;; if first item in collection is nil, returns nil\n(first [nil])\n;;=> nil","editors":[{"avatar-url":"https://www.gravatar.com/avatar/69ad2af1f028b1b7e76c14f83bdf26cb?r=PG&default=identicon","account-source":"clojuredocs","login":"jszakmeister"},{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3","account-source":"github","login":"phreed"},{"login":"vaer-k","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/4069456?v=4"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/8d3c423e74750fa42c0386833e4b8209?r=PG&default=identicon","account-source":"clojuredocs","login":"belun"},"_id":"542692ccc026201cdc326c6e"},{"updated-at":1493775730548,"created-at":1493775730548,"author":{"login":"Juve-yescas","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/26342224?v=3"},"body":"=> (first [1 2])\n1\n\n=> (first [ [1 2] [3 4] ])\n[1 2]","_id":"59093572e4b01f4add58fea3"},{"updated-at":1661100444310,"created-at":1661100444310,"author":{"login":"zuzhi","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/11850845?v=4"},"body":"=> (first \"j\")\n\\j\n\n=> (int (first \"j\"))\n106","_id":"6302619ce4b0b1e3652d7647"}],"notes":null,"arglists":["coll"],"doc":"Returns the first item in the collection. Calls seq on its\n argument. If coll is nil, returns nil.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/first"},{"added":"1.0","ns":"clojure.core","name":"re-groups","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1282039215000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"re-find","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e6a"},{"created-at":1444479086186,"author":{"login":"muhuk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/40178?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"re-matcher","ns":"clojure.core"},"_id":"5619006ee4b084e61c76ecc1"}],"line":4911,"examples":[{"author":{"login":"OnesimusUnbound","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2fa4c391db0d2d1744cc2cd0d787dd3d?r=PG&default=identicon"},"editors":[],"body":"user=> (def phone-number \"672-345-456-3212\")\n#'user/phone-number\n\nuser=> (def matcher (re-matcher #\"((\\d+)-(\\d+))\" phone-number))\n#'user/matcher\n\nuser=> (re-find matcher)\n[\"672-345\" \"672-345\" \"672\" \"345\"]\n\n;; re-groups gets the most recent find or matches\nuser=> (re-groups matcher)\n[\"672-345\" \"672-345\" \"672\" \"345\"]\nuser=> (re-groups matcher)\n[\"672-345\" \"672-345\" \"672\" \"345\"]\n\n\nuser=> (re-find matcher)\n[\"456-3212\" \"456-3212\" \"456\" \"3212\"]\n\nuser=> (re-groups matcher)\n[\"456-3212\" \"456-3212\" \"456\" \"3212\"]\nuser=> (re-groups matcher)\n[\"456-3212\" \"456-3212\" \"456\" \"3212\"]\n\n\nuser=> (re-find matcher)\nnil\n\nuser=> (re-groups matcher)\nIllegalStateException No match found java.util.regex.Matcher.group (Matcher.java:468)","created-at":1312374649000,"updated-at":1312374649000,"_id":"542692c9c026201cdc326a7f"},{"editors":[{"login":"jgrodziski","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/408494?v=4"}],"body":";;given a string to match\nuser=> (def flight \"AF-22-CDG-JFK-2017-09-08\")\n#'User/flight\n;; groups and give a name to matches\nuser=> (def flight-regex #\"(?[A-Z0-9]+)-(?[0-9]+[A-Z]?)-(?[A-Z]+)-(?[A-Z]+)-(?[0-9]+)-(?[0-9]+)-(?[0-9]+)\")\n#'user/flight-regex\nuser=> (def matcher (re-matcher flight-regex flight))\n#'user/matcher\n;; it allows good grasp of meaning and understanding of the data extraction from the regex\nuser=> (if (.matches matcher)\n {:airline-code (.group matcher \"airlineCode\") \n :flight-number (.group matcher \"flightNumber\") \n :from (.group matcher \"from\") \n :to (.group matcher \"to\") \n :year (.group matcher \"year\") \n :month (.group matcher \"month\") \n :day (.group matcher \"day\")}\n (throw (ex-info (str \"Can't extract detailed value from flight\"))))\n{:airline-code \"AF\", :flight-number \"22\", :from \"CDG\", :to \"JFK\", :year \"2017\", :month \"09\", :day \"08\"}\nuser=>\n;;Beware that groups are available in Java Regex not in Javascript ones...","author":{"avatar-url":"https://avatars3.githubusercontent.com/u/408494?v=4","account-source":"github","login":"jgrodziski"},"created-at":1504879066415,"updated-at":1504880637927,"_id":"59b2a1dae4b09f63b945ac64"},{"editors":[{"login":"cloojure","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7083783?v=4"}],"body":";\n; Java supports named capture groups\n;\n; Define a phone number pattern with some named groups\n(let [patt (re-pattern \"(?\\\\d{3})-(?\\\\d{3})-(?\\\\d{4})\")]\n ; `re-matches` will find the capturing groups and stick them in a vector\n ; after the full match The capture groups are numbered starting with 1.\n ; The full match is like group zero.\n (is= [\"619-239-5464\" \"619\" \"239\" \"5464\"] (re-matches patt \"619-239-5464\"))\n\n ; Construct a java.util.regex.Matcher. Keep in mind that it is a mutable object!\n (let [matcher (re-matcher patt \"619-239-5464\")]\n ; Execute the Matcher via `re-find`. It returns all 4 groups and caches them\n (is= [\"619-239-5464\" \"619\" \"239\" \"5464\"] (re-find matcher))\n\n ; `re-groups` simply returns the cached result from the Matcher\n (is= [\"619-239-5464\" \"619\" \"239\" \"5464\"] (re-groups matcher))\n\n ; We need the instance function Matcher.group( ) to\n ; extract the named group\n (is= \"619\" (.group matcher \"area\"))\n (is= \"239\" (.group matcher \"prefix\"))\n (is= \"5464\" (.group matcher \"tail\"))))\n","author":{"avatar-url":"https://avatars.githubusercontent.com/u/7083783?v=4","account-source":"github","login":"cloojure"},"created-at":1622895257068,"updated-at":1622895336509,"_id":"60bb6a99e4b0b1e3652d7506"}],"notes":null,"arglists":["m"],"doc":"Returns the groups from the most recent match/find. If there are no\n nested groups, returns a string of the entire match. If there are\n nested groups, returns a vector of the groups, the first element\n being the entire match.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/re-groups"},{"added":"1.0","ns":"clojure.core","name":"seq?","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1286870491000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"seq","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bc7"},{"created-at":1304804140000,"author":{"login":"0x89","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/56bc4acd59315ed4dc1cb99c3be71102?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"sequential?","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bc8"},{"created-at":1304804146000,"author":{"login":"0x89","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/56bc4acd59315ed4dc1cb99c3be71102?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"vector?","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bc9"},{"created-at":1304804161000,"author":{"login":"0x89","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/56bc4acd59315ed4dc1cb99c3be71102?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"coll?","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bca"},{"created-at":1304804189000,"author":{"login":"0x89","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/56bc4acd59315ed4dc1cb99c3be71102?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"list?","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bcb"},{"created-at":1304804202000,"author":{"login":"0x89","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/56bc4acd59315ed4dc1cb99c3be71102?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"map?","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bcc"},{"created-at":1304804206000,"author":{"login":"0x89","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/56bc4acd59315ed4dc1cb99c3be71102?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"set?","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bcd"},{"created-at":1495638773577,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"seqable?","ns":"clojure.core"},"_id":"5925a2f5e4b093ada4d4d728"}],"line":148,"examples":[{"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"editors":[],"body":"user> (seq? 1)\nfalse\nuser> (seq? [1])\nfalse\nuser> (seq? (seq [1]))\ntrue","created-at":1286870431000,"updated-at":1286870431000,"_id":"542692c8c026201cdc326a5e"},{"author":{"login":"gregginca","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bad5f5cb177b0968d4288596691ec3cd?r=PG&default=identicon"},"editors":[{"avatar-url":"https://avatars3.githubusercontent.com/u/1922297?v=4","account-source":"github","login":"allentiak"},{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=4"}],"body":";; contrast to example code for sequential?\n;; You may also find this useful: https://insideclojure.org/2015/01/02/sequences\n;;\nuser> (seq? '(1 2 3))\ntrue\nuser=> (seq? #{1 2 3})\nfalse\nuser> (seq? [1 2 3]) ; for sequential?, returns true\nfalse\nuser> (seq? (range 1 5))\ntrue\nuser> (seq? 1)\nfalse\nuser> (seq? {:a 2 :b 1})\nfalse\nuser> ","created-at":1334018590000,"updated-at":1694799181917,"_id":"542692d5c026201cdc32707c"},{"updated-at":1485952236986,"created-at":1485952236986,"author":{"login":"yochannah","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/9271438?v=3"},"body":";; Don't use seq? when you want to check for a vector.\n;; you may have intended to use seq instead\n\ncljs.user=> (def x [:a :b :c])\n#'cljs.user/x\ncljs.user=> (if (seq x) \"Seq ok\" \"No Seqing here\")\n\"Seq ok\"\ncljs.user=> (if (seq? x) \"Seq ok\" \"No Seqing here\")\n\"No Seqing here\"","_id":"5891d4ece4b01f4add58fe35"}],"notes":null,"arglists":["x"],"doc":"Return true if x implements ISeq","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/seq_q"},{"added":"1.0","ns":"clojure.core","name":"dec'","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1415177726472,"author":{"login":"rvlieshout","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/139665?v=2"},"to-var":{"ns":"clojure.core","name":"dec","library-url":"https://github.com/clojure/clojure"},"_id":"5459e5fee4b0dc573b892fb9"},{"created-at":1495706257856,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"inc'","ns":"clojure.core"},"_id":"5926aa91e4b093ada4d4d753"}],"line":1149,"examples":[{"author":{"login":"szemek","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/78b14dbb96afe3befc04757dc5e06225?r=PG&default=identicon"},"editors":[],"body":"user=> (dec' 0.1)\n-0.9\n\nuser=> (dec' 1)\n0\n\nuser=> (dec' 1.0)\n0.0","created-at":1335130392000,"updated-at":1335130392000,"_id":"542692d2c026201cdc326f77"},{"updated-at":1495706067200,"created-at":1495706067200,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"body":";;;; (dec') auto-promotes on integer overflow:\n\n(dec' (Long/MIN_VALUE))\n;;=> -9223372036854775809N\n\n;;;; Unlike (dec) which does not:\n\n(dec (Long/MIN_VALUE))\n;;=> ArithmeticException integer overflow","_id":"5926a9d3e4b093ada4d4d751"}],"notes":null,"arglists":["x"],"doc":"Returns a number one less than num. Supports arbitrary precision.\n See also: dec","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/dec'"},{"added":"1.0","ns":"clojure.core","name":"ns-unmap","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1288683645000,"author":{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},"to-var":{"ns":"clojure.core","name":"remove-ns","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d33"},{"created-at":1341280172000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"ns-map","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d34"},{"created-at":1426949911751,"author":{"login":"ryoakg","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/23413?v=3"},"to-var":{"ns":"clojure.core","name":"def","library-url":"https://github.com/clojure/clojure"},"_id":"550d8717e4b056ca16cfecf9"},{"created-at":1484215112470,"author":{"login":"rauhs","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/11081351?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"intern","ns":"clojure.core"},"_id":"58775348e4b09108c8545a57"},{"created-at":1512578699260,"author":{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"ns-unalias","ns":"clojure.core"},"_id":"5a281e8be4b0a08026c48cd1"}],"line":4204,"examples":[{"author":{"login":"james","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/4b163432c99a124feee4be046a3f9d66?r=PG&default=identicon"},"editors":[{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/159047?v=3"}],"body":"user=> (def foo 1)\n#'user/foo\n\nuser=> foo\n1\n\nuser=> (ns-unmap 'user 'foo) ; explicit\nnil\n\nuser=> (ns-unmap *ns* 'foo) ; convenient\nnil\n\nuser=> foo\n\"Unable to resolve symbol: foo in this context\"\n","created-at":1290213451000,"updated-at":1335243941000,"_id":"542692c7c026201cdc3269a3"}],"notes":[{"author":{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"},"updated-at":1512036603446,"created-at":1512036603446,"body":"Note this function doesn’t work for namespaces aliases; you need to use `ns-unalias` if you want to remove one.","_id":"5a1fd8fbe4b0a08026c48cc8"}],"arglists":["ns sym"],"doc":"Removes the mappings for the symbol from the namespace.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/ns-unmap"},{"added":"1.0","ns":"clojure.core","name":"println-str","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1318573842000,"author":{"login":"haplo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/890d46f8c0e24dd6fb8546095b1144e?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"println","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e07"},{"created-at":1374264235000,"author":{"login":"lbeschastny","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/416170465e4045f810f09a9300dda4dd?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"print-str","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e08"},{"created-at":1592850187673,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"str","ns":"clojure.core"},"_id":"5ef0f70be4b0b1e3652d730d"}],"line":4812,"examples":[{"author":{"login":"Miles","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bbb26d2a5e856c4fba0f72c3f7250f3f?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"Miles","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bbb26d2a5e856c4fba0f72c3f7250f3f?r=PG&default=identicon"},{"login":"philos99","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1de5617efb013ca7c9cf8e5646818ffa?r=PG&default=identicon"},{"login":"philos99","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1de5617efb013ca7c9cf8e5646818ffa?r=PG&default=identicon"},{"login":"matthewg","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/b29dd31d183124d9e87d8037bb30e326?r=PG&default=identicon"}],"body":";; Create a newline-terminated string from the items and store it in x.\nuser=> (def x (println-str 1 \"foo\" \\b \\a \\r {:a 2}))\n#'user/x\n\n;; It's a string.\nuser=> (string? x)\ntrue\n\n;; Notice that the items are separated by a space. Also, the newline string is\n;; platform-specific. See clojure.core/newline.\nuser=> x\n\"1 foo b a r {:a 2}\\r\\n\"\n","created-at":1284257337000,"updated-at":1323234147000,"_id":"542692cfc026201cdc326e4c"}],"notes":null,"tag":"java.lang.String","arglists":["& xs"],"doc":"println to a string, returning it","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/println-str"},{"added":"1.1","ns":"clojure.core","name":"with-bindings*","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1374313837000,"author":{"login":"alilee","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2fb0196dc5a7cd3a5cc73f1b9941c209?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"with-bindings","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bb4"}],"line":1990,"examples":[{"updated-at":1335591761000,"created-at":1335591761000,"body":"user=> (let [f (fn [] *warn-on-reflection*)]\n (with-bindings* {#'*warn-on-reflection* true} f))\ntrue","editors":[],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3","account-source":"github","login":"devn"},"_id":"542692d6c026201cdc3270b8"}],"notes":null,"arglists":["binding-map f & args"],"doc":"Takes a map of Var/value pairs. Installs for the given Vars the associated\n values as thread-local bindings. Then calls f with the supplied arguments.\n Pops the installed bindings after f returned. Returns whatever f returns.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/with-bindings*"},{"added":"1.9","ns":"clojure.core","name":"inst-ms","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1495635499100,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"inst?","ns":"clojure.core"},"_id":"5925962be4b093ada4d4d721"}],"line":6916,"examples":[{"updated-at":1495636375815,"created-at":1495636375815,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"body":"(inst-ms (java.util.Date.))\n;;=> 1495636054438\n(inst-ms (java.time.Instant/now))\n;;=> 1495636054438\n\n(inst-ms (java.sql.Date. 1495636054438))\n;;=> 1495636054438\n(inst-ms (java.sql.Timestamp. 1495636054438))\n;;=> 1495636054438","_id":"59259997e4b093ada4d4d723"}],"notes":null,"arglists":["inst"],"doc":"Return the number of milliseconds since January 1, 1970, 00:00:00 GMT","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/inst-ms"},{"added":"1.0","ns":"clojure.core","name":"iterator-seq","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1398980083000,"author":{"login":"ryo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3f7913b563c72083c74030d928ba407e?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"seq","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e96"}],"line":5774,"examples":[{"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":";; Note this is not strictly necessary since keySet is a collection\n;; implementing Iterable but it does show the usage.\n\nuser=> (iterator-seq (.iterator (.keySet (java.lang.System/getProperties))))\n\n(\"java.runtime.name\" \"sun.boot.library.path\" \"java.vm.version\" \"java.vm.vendor\" \"java.vendor.url\" \"path.separator\" \"java.vm.name\" \"file.encoding.pkg\" \"sun.java.launcher\" \"user.country\" \"sun.os.patch.level\" \"java.vm.specification.name\" \"user.dir\" \"java.runtime.version\" \"java.awt.graphicsenv\" \"java.endorsed.dirs\" \"os.arch\" \"javax.accessibility.assistive_technologies\" \"java.io.tmpdir\" \"line.separator\" \"java.vm.specification.vendor\" \"os.name\" \"cljr.home\" \"sun.jnu.encoding\" \"java.library.path\" \"java.specification.name\" \"java.class.version\" \"sun.management.compiler\" \"os.version\" \"user.home\" \"user.timezone\" \"java.awt.printerjob\" \"file.encoding\" \"java.specification.version\" \"include.cljr.repo.jars\" \"java.class.path\" \"user.name\" \"java.vm.specification.version\" \"java.home\" \"sun.arch.data.model\" \"user.language\" \"java.specification.vendor\" \"java.vm.info\" \"java.version\" \"java.ext.dirs\" \"sun.boot.class.path\" \"java.vendor\" \"file.separator\" \"java.vendor.url.bug\" \"clojure.home\" \"sun.io.unicode.encoding\" \"sun.cpu.endian\" \"sun.desktop\" \"sun.cpu.isalist\")\n","created-at":1284711960000,"updated-at":1287995124000,"_id":"542692cdc026201cdc326d15"},{"updated-at":1519828356542,"created-at":1519828356542,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"body":";; Java 8 streams as sequences\n(->> \"Clojure is the best language\"\n (.splitAsStream #\"\\s+\")\n .iterator\n iterator-seq)\n\n;; (\"Clojure\" \"is\" \"the\" \"best\" \"language\")","_id":"5a96bd84e4b0316c0f44f903"}],"notes":[{"updated-at":1287834466000,"body":"I've noticed that I needed to use iterator-seq when trying to map over a Java function that returns an AbstractList Iterator. It was not directly seq-able.","created-at":1287834466000,"author":{"login":"dakrone","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bcacd00a7f05c4772329cf9f446c7987?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521f9d"}],"arglists":["iter"],"doc":"Returns a seq on a java.util.Iterator. Note that most collections\n providing iterators implement Iterable and thus support seq directly.\n Seqs cache values, thus iterator-seq should not be used on any\n iterator that repeatedly returns the same mutable object.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/iterator-seq"},{"added":"1.0","ns":"clojure.core","name":"iterate","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1291953286000,"author":{"login":"alimoeeny","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e8dd06976ead4082d2181f3807117e1?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"cycle","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b0d"},{"created-at":1335482527000,"author":{"login":"metajack","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/194d8437f5baed192c90be27369c4922?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"repeatedly","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b0e"},{"created-at":1343152603000,"author":{"login":"john.r.woodward","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/22b6fbc4a386291e45b1cb4449377086?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"repeat","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b0f"},{"created-at":1455301227264,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"take","ns":"clojure.core"},"_id":"56be226be4b060004fc217c1"},{"created-at":1455301237712,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"nth","ns":"clojure.core"},"_id":"56be2275e4b060004fc217c2"},{"created-at":1709250181756,"author":{"login":"djblue","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1986211?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"iteration","ns":"clojure.core"},"_id":"65e1168569fbcc0c226174b3"}],"line":3036,"examples":[{"author":{"avatar-url":"https://avatars.githubusercontent.com/u/142529?v=3","account-source":"github","login":"nipra"},"editors":[{"login":"devijvers","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/81018e4231ac1ce8b7a9e6d377092656?r=PG&default=identicon"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"rafmagana","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/92894?v=3"},{"login":"rafmagana","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/92894?v=3"},{"login":"rafmagana","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/92894?v=3"},{"login":"rafmagana","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/92894?v=3"},{"avatar-url":"https://avatars.githubusercontent.com/u/2746668?v=4","account-source":"github","login":"victoraldecoa"},{"login":"stoat1","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2543524?v=4"}],"body":";; iterate Ad Infinitum starting at 5 using the inc (increment) function\nuser=> (iterate inc 5)\n(5 6 7 8 9 10 11 12 13 14 15 ... n ...\n\n;; limit results\nuser=> (take 3 (iterate inc 5))\n(5 6 7)\n\nuser=> (take 10 (iterate (partial + 2) 0))\n(0 2 4 6 8 10 12 14 16 18)\n\nuser=> (take 20 (iterate (partial + 2) 0))\n(0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38)\n\n","created-at":1279048785000,"updated-at":1615738001527,"_id":"542692cac026201cdc326b22"},{"author":{"login":"citizen428","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/b3881a28fe402dd2d1de44717486cae8?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":"user=> (def powers-of-two (iterate (partial * 2) 1))\n#'user/powers-of-two\n\nuser=> (nth powers-of-two 10)\n1024\nuser=> (take 10 powers-of-two)\n(1 2 4 8 16 32 64 128 256 512)\n","created-at":1280707793000,"updated-at":1285496060000,"_id":"542692cac026201cdc326b29"},{"author":{"login":"shockbob","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon"},"editors":[{"login":"shockbob","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon"},{"login":"Bobby","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/c0541baac8a638e07f5895c7224f8b7e?r=PG&default=identicon"},{"login":"Bobby","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/c0541baac8a638e07f5895c7224f8b7e?r=PG&default=identicon"},{"login":"maacl","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8ff89765136c38707e0f57cf48679a13?r=PG&default=identicon"}],"body":";; demonstrating the power of iterate\n;; to generate the Fibonacci sequence\n;; uses +' to promote to BigInt\nuser=> (def fib (map first (iterate (fn [[a b]] [b (+' a b)]) [0 1])))\n#'user/fib\n\nuser=> (take 10 fib)\n(0 1 1 2 3 5 8 13 21 34)","created-at":1310850870000,"updated-at":1388690059000,"_id":"542692cac026201cdc326b2b"},{"updated-at":1520938144240,"created-at":1520938144240,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"body":";; iterate (also range, repeat and cycle) have a reduce\n;; fast path. Use with reduce, transduce, eduction etc.\n\n(defn pi\n \"Approximate Pi to the 1/n decimal with Leibniz formula\"\n [n]\n (transduce\n (comp (map #(/ 4 %)) (take n))\n +\n (iterate #(* ((if (pos? %) + -) % 2) -1) 1.0)))\n\n(time (pi 1e8))\n\"Elapsed time: 9776.924934 msecs\"\n;; 3.141592643589326","_id":"5aa7aca0e4b0316c0f44f923"}],"notes":null,"arglists":["f x"],"doc":"Returns a lazy (infinite!) sequence of x, (f x), (f (f x)) etc.\n f must be free of side-effects","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/iterate"},{"added":"1.0","ns":"clojure.core","name":"slurp","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1330170507000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.java.io","name":"reader","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521efd"},{"created-at":1314301885000,"author":{"login":"Havvy","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e799a79441c7543be48562403411cd13?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"spit","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f54"},{"created-at":1529010527201,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"resource","ns":"clojure.java.io"},"_id":"5b22d95fe4b00ac801ed9e16"}],"line":7089,"examples":[{"author":{"login":"pkolloch","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/10b2fd3c0a4cc46dc241a48468dc551?r=PG&default=identicon"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":"user=> (spit \"blubber.txt\" \"test\")\nnil\nuser=> (slurp \"blubber.txt\")\n\"test\"","created-at":1280458838000,"updated-at":1332952657000,"_id":"542692cac026201cdc326b32"},{"updated-at":1603841965576,"created-at":1314221982000,"body":";; To access web page. Note the use of https://\n;; prefix\n\nuser=> (slurp \"https://clojuredocs.org\")\n; This will return the html content of clojuredocs.org","editors":[{"login":"fhightower","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/3599813?v=4"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/2fa4c391db0d2d1744cc2cd0d787dd3d?r=PG&default=identicon","account-source":"clojuredocs","login":"OnesimusUnbound"},"_id":"542692cac026201cdc326b34"},{"author":{"login":"Havvy","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e799a79441c7543be48562403411cd13?r=PG&default=identicon"},"editors":[],"body":";; Access absolute location on Windows\n\nuser=> (slurp \"C:\\\\tasklists.xml\")\n","created-at":1314301837000,"updated-at":1314301837000,"_id":"542692cac026201cdc326b35"},{"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"editors":[],"body":";; On Linux, some JVMs have a bug where they cannot read a file in the /proc\n;; filesystem as a buffered stream or reader. A workaround to this JVM issue\n;; is to open such a file as unbuffered:\n(slurp (java.io.FileReader. \"/proc/cpuinfo\"))","created-at":1330170476000,"updated-at":1330170476000,"_id":"542692d5c026201cdc327086"},{"author":{"login":"nils.grunwald","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/6c7661b3ea6397abbf5a2048ee07d995?r=PG&default=identicon"},"editors":[{"login":"nils.grunwald","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/6c7661b3ea6397abbf5a2048ee07d995?r=PG&default=identicon"},{"login":"nils.grunwald","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/6c7661b3ea6397abbf5a2048ee07d995?r=PG&default=identicon"}],"body":";; You can specify what encoding to use by giving a :encoding param, and an encoding string recognized by your JVM\n\nuser=> (slurp \"/path/to/file\" :encoding \"ISO-8859-1\")","created-at":1342145976000,"updated-at":1342146268000,"_id":"542692d5c026201cdc327087"},{"updated-at":1464367678770,"created-at":1464367678770,"author":{"login":"freckletonj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8399149?v=3"},"body":";; you can fetch URLs\n\n(slurp \"http://www.example.com\")","_id":"57487a3ee4b0bafd3e2a0467"},{"updated-at":1485689448487,"created-at":1485689448487,"author":{"login":"mhmdsalem1993","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10787314?v=3"},"body":";; you can read bytes also\n\n(def arr-bytes (into-array Byte/TYPE (range 128)))\n(slurp arr-bytes)","_id":"588dd268e4b01f4add58fe33"}],"notes":[{"updated-at":1309555971000,"body":"Use slurp also to read an input stream into a string.","created-at":1309555971000,"author":{"login":"mjg123","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2d7180cd610e068c47d3ba7337f1425c?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fc3"},{"updated-at":1387184994000,"body":"With link: “See [`clojure.java.io/reader`](http://clojuredocs.org/clojure_core/clojure.java.io/reader) for a complete list of supported arguments.â€�\r\n\r\nAccording to those docs, here are the supported types for `f`, the object to read:\r\n\r\n* [`Reader`](http://docs.oracle.com/javase/7/docs/api/java/io/Reader.html)\r\n* [`BufferedReader`](http://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html)\r\n* [`InputStream`](http://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html)\r\n* [`File`](http://docs.oracle.com/javase/7/docs/api/java/io/File.html)\r\n* [`URI`](http://docs.oracle.com/javase/7/docs/api/java/net/URI.html)\r\n* [`URL`](http://docs.oracle.com/javase/7/docs/api/java/net/URL.html)\r\n* [`Socket`](http://docs.oracle.com/javase/7/docs/api/java/net/Socket.html)\r\n* byte arrays (`byte[]`)\r\n* character arrays (`char[]`)\r\n* [`String`](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html)\r\n\r\n`slurp` can read objects of any of these types into a string.","created-at":1387183993000,"author":{"login":"roryokane","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5b2b185c814bb25f2f95a1152e58f033?r=PG&default=identicon"},"_id":"542692edf6e94c6970522015"},{"body":"
\n(defn slurp-bytes\n  \"Slurp the bytes from a slurpable thing\"\n  [x]\n  (with-open [out (java.io.ByteArrayOutputStream.)]\n    (clojure.java.io/copy (clojure.java.io/input-stream x) out)\n    (.toByteArray out)))\n
","created-at":1522121921297,"updated-at":1522121998843,"author":{"avatar-url":"https://avatars0.githubusercontent.com/u/13529973?v=4","account-source":"github","login":"nevesjorgelucio"},"_id":"5ab9bcc1e4b045c27b7fac27"},{"author":{"login":"didibus","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/601540?v=4"},"updated-at":1585180980301,"created-at":1585180980301,"body":"Valid options include:\n\n :encoding string name of encoding to use, e.g. \\\"UTF-8\\\".","_id":"5e7bf134e4b087629b5a18c3"},{"body":"```\n(defn slurp-norm\n \"When the file is incoming with \\r\\n newlines\"\n [file]\n (with-open [rdr (io/reader file)]\n (str/join \"\\n\" (line-seq rdr))))\n```","created-at":1738166701645,"updated-at":1738166712945,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/6553?v=4","account-source":"github","login":"piranha"},"_id":"679a51adcd84df5de54e2075"}],"tag":"java.lang.String","arglists":["f & opts"],"doc":"Opens a reader on f and reads all its contents, returning a string.\n See clojure.java.io/reader for a complete list of supported arguments.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/slurp"},{"added":"1.0","ns":"clojure.core","name":"newline","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1721397185771,"author":{"login":"Kaspazza","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/36607370?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"println","ns":"clojure.core"},"_id":"669a6fc169fbcc0c226174dd"}],"line":3723,"examples":[{"author":{"login":"jjcomer","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/ef581bba2f97adb539c67a35465b3e1b?r=PG&default=identicon"},"editors":[{"login":"cloojure","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1ad3de25d00d953de6e8c82f554cdbf5?r=PG&default=identicon"}],"body":";; This is equivalent to System.out.println() in Java\nuser=> (newline)\n\nnil\n; Calling println w/o args is equivalent.\nuser=> (println)\n\nnil\nuser=>","created-at":1330655016000,"updated-at":1402384428000,"_id":"542692d4c026201cdc327012"}],"notes":null,"arglists":[""],"doc":"Writes a platform-specific newline to *out*","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/newline"},{"added":"1.1","ns":"clojure.core","name":"short-array","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"to-var":{"library-url":"https://github.com/clojure/clojure","name":"shorts","ns":"clojure.core"},"author":{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},"created-at":1342917718000,"_id":"542692eaf6e94c6970521ad6"}],"line":5362,"examples":[{"author":{"login":"shockbob","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon"},"editors":[{"login":"shockbob","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon"}],"body":";; create an array of shorts using short-array\n;; and demonstrate how it can be used with the java Arrays functions\n;; (note the needed coercions)\n\nuser=> (def ss (short-array (map short (range 3 10))))\n#'user/ss\nuser=> (type ss)\n[S\nuser=> (vec ss)\n[3 4 5 6 7 8 9]\nuser=> (java.util.Arrays/binarySearch ss (short 6))\n3\nuser=> (java.util.Arrays/fill ss (short 99))\nnil\nuser=> (vec ss)\n[99 99 99 99 99 99 99]\nuser=>","created-at":1313908642000,"updated-at":1313962982000,"_id":"542692c7c026201cdc326987"}],"notes":null,"arglists":["size-or-seq","size init-val-or-seq"],"doc":"Creates an array of shorts","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/short-array"},{"added":"1.0","ns":"clojure.core","name":"fn?","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1321052077000,"author":{"login":"mmwaikar","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/29d36f4c9f39c9f8ff61c07033b13118?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"ifn?","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b3c"}],"line":6293,"examples":[{"author":{"login":"dpritchett","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/147981?v=3"},"editors":[{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},{"login":"replore","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e7869fe1a48cb1814c657eaca6bea3eb?r=PG&default=identicon"},{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":"user=> (fn? 5)\nfalse\nuser=> (fn? inc)\ntrue\nuser=> (fn? (fn []))\ntrue\nuser=> (fn? #(5))\ntrue","created-at":1279073964000,"updated-at":1332952252000,"_id":"542692c6c026201cdc3268f8"},{"author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"editors":[{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":";; Even though maps, sets, vectors and keywords behave as functions:\nuser=> ({:a 1} :a)\n1\n\n;; fn? still returns false for them because they are not created using fn:\nuser=> (fn? {:a 1})\nfalse\n","created-at":1279155323000,"updated-at":1285500252000,"_id":"542692c6c026201cdc3268fc"}],"notes":[{"author":{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"},"updated-at":1504887813989,"created-at":1504887813989,"body":"Note `fn?` only tests if something was created using `fn`, *not* if it’s a function. Use [`ifn?`](https://clojuredocs.org/clojure.core/ifn_q) for that. Some things are functions even though they weren’t created with `fn`, such as maps, vectors and keywords.","_id":"59b2c405e4b09f63b945ac66"}],"arglists":["x"],"doc":"Returns true if x implements Fn, i.e. is an object created via fn.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/fn_q"},{"added":"1.0","ns":"clojure.core","name":"doall","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1289672752000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"dorun","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521a8b"},{"created-at":1289672768000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"doseq","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521a8c"},{"created-at":1659463132215,"author":{"login":"puredanger","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/171129?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"run!","ns":"clojure.core"},"_id":"62e965dce4b0b1e3652d7636"}],"line":3156,"examples":[{"author":{"login":"dakrone","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bcacd00a7f05c4772329cf9f446c7987?r=PG&default=identicon"},"editors":[{"login":"philos99","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1de5617efb013ca7c9cf8e5646818ffa?r=PG&default=identicon"},{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"login":"AtKaaZ","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e10dfa345f44b0fe72bbe081fd51b83?r=PG&default=identicon"},{"login":"orivej","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cab90c7de5efde92a29f1eacb603ba9a?r=PG&default=identicon"}],"body":";; Nothing is printed because map returns a lazy-seq\nuser=> (def foo (map println [1 2 3]))\n#'user/foo\n\n;; doall forces the seq to be realized\nuser=> (def foo (doall (map println [1 2 3])))\n1\n2\n3\n#'user/foo\n\n;; where\n(doall (map println [1 2 3]))\n1\n2\n3\n(nil nil nil)","created-at":1280548280000,"updated-at":1362554691000,"_id":"542692cbc026201cdc326ba2"},{"updated-at":1436248770172,"created-at":1436248770172,"author":{"login":"gdeer81","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1340575?v=3"},"body":";;map a function which makes database calls to either retrieve or \n;;create and retrieves records from the database over a vector of values. \n;;The function returns a map of fields and values\nuser=> (map #(db/make-n-get-or-get :person {:name %}) [\"Fred\" \"Ethel\" \"Lucy\" \"Ricardo\"])\nJdbcSQLException The object is already closed [90007-170] org.h2.message.DbE\nxception.getJdbcSQLException (DbException.java:329)\n\n;;database connection was closed before we got a chance to do our transactions\n;;lets wrap it in doall\nuser=> (doall (map #(db/make-n-get-or-get :person {:name %}) \n[\"Fred\" \"Ethel\" \"Lucy\" \"Ricardo\"]))\nDEBUG :db insert into person values name = 'Fred'\nDEBUG :db insert into person values name = 'Ethel'\nDEBUG :db insert into person values name = 'Lucy'\nDEBUG :db insert into person values name = 'Ricardo'\n({:name \"Fred\"} {:name \"Ethel\"} {:name \"Lucy\"} {:name \"Ricardo\"})\n\n;;notice that unlike using dorun, this returns a list of maps","_id":"559b6ac2e4b020189d740548"},{"updated-at":1493187295161,"created-at":1493187295161,"author":{"login":"chbrown","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/360279?v=3"},"body":";; The (doall n coll) form only forces the first n (or more) items in coll to\n;; be realized, but still returns the entire coll.\n(def pr-123 (lazy-seq (cons (pr 1)\n (lazy-seq (cons (pr 2)\n (lazy-seq (cons (pr 3) nil)))))))\n#'user/pr-123\n\n;; Since doall returns the collection, be careful not to let the REPL realize\n;; the whole thing, as it would if we were to call (doall 1 pr-123) instead.\nuser=> (do (doall 1 pr-123) (println))\n12\nnil\n;; The 1 is triggered when (seq pr-123) is called, then the 2 is triggered\n;; when (next pr-123) is called (both inside dorun, via doall).\n\nuser=> pr-123\n3(nil nil nil)\n;; The 3 is finally triggered when the REPL realizes the entirety of pr-123\n\n;; pr-123 is built of nested lazy-seq's because (map pr coll) isn't very lazy:\n(do (doall 1 (map pr (range 100))) (println))\n012345678910111213141516171819202122232425262728293031\nnil\n;; Due to occult clojure.lang.RT/JVM internals (?), (next coll) on this sort\n;; of coll realizes the items in batches of 32 each.\n","_id":"59003adfe4b01f4add58fe9c"},{"updated-at":1510465598561,"created-at":1510464241601,"author":{"login":"elect000","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/18697629?v=4"},"body":";; #'for is create lazy-seq\n(def x (for [i (range 10)]\n i)\n\n(type x) ;;=> clojure.lang.LazySeq\n\n;; doall return evaluated value\n(doall x) ;;=> (0 1 2 3 4 ...)\n\n\n;; Notice!\n;; but it is clojure.lang.LazySeq\n(type (doall x)) ;;=> clojure.lang.LazySeq\n\n;; if you want to get list ...\n(into-array x)\n(type (into-array x)) ;;=> [Ljava.lang.Long;","editors":[{"avatar-url":"https://avatars3.githubusercontent.com/u/18697629?v=4","account-source":"github","login":"elect000"}],"_id":"5a07daf1e4b0a08026c48cb1"}],"notes":[{"updated-at":1341951212000,"body":"Shouldn't we use seq instead of coll in the function signature since we should really pass a sequence?","created-at":1341951200000,"author":{"login":"johnnyluu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1ba99f2dc1064733c7badbb16db9254a?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fe5"},{"updated-at":1390120527000,"body":"'seq' is a function; using it in the function args as a value would shadow the function (and thereby making the function seq unusable in that scope)","created-at":1390120527000,"author":{"login":"zephjc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/47639b1aa7a7ccb90000a3ea12b84d7e?r=PG&default=identicon"},"_id":"542692edf6e94c697052201a"}],"arglists":["coll","n coll"],"doc":"When lazy sequences are produced via functions that have side\n effects, any effects other than those needed to produce the first\n element in the seq do not occur until the seq is consumed. doall can\n be used to force any effects. Walks through the successive nexts of\n the seq, retains the head and returns it, thus causing the entire\n seq to reside in memory at one time.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/doall"},{"added":"1.0","ns":"clojure.core","name":"prefers","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1337584993000,"author":{"login":"abrooks","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/69976?v=2"},"to-var":{"ns":"clojure.core","name":"prefer-method","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b6f"},{"created-at":1337585000000,"author":{"login":"abrooks","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/69976?v=2"},"to-var":{"ns":"clojure.core","name":"methods","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b70"},{"created-at":1337585004000,"author":{"login":"abrooks","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/69976?v=2"},"to-var":{"ns":"clojure.core","name":"get-method","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b71"}],"line":1841,"examples":[{"updated-at":1475527508775,"created-at":1475527508775,"author":{"login":"ertugrulcetin","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8271291?v=3"},"body":"(def m {:os ::osx})\n\n(defmulti ex :os)\n\n(defmethod ex ::unix\n [_]\n \"unix\")\n\n(derive ::osx ::unix)\n\n(defmethod ex ::bsd\n [_]\n \"bsd\")\n\n(derive ::osx ::bsd)\n\n(prefer-method ex ::unix ::bsd)\n\n(prefers ex)\n;;=> {:user/unix #{:user/bsd}}","_id":"57f2c354e4b0709b524f051d"}],"notes":null,"arglists":["multifn"],"doc":"Given a multimethod, returns a map of preferred value -> set of other values","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/prefers"},{"added":"1.0","ns":"clojure.core","name":"enumeration-seq","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":null,"line":5784,"examples":[{"author":{"login":"leifp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d2f37720f063404ef83b987d2824353d?r=PG&default=identicon"},"editors":[],"body":"user=> (enumeration-seq (java.util.StringTokenizer. \"exciting example\"))\n(\"exciting\" \"example\")\n","created-at":1342527173000,"updated-at":1342527173000,"_id":"542692d2c026201cdc326f9d"},{"editors":[{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"}],"body":";; A parallel distinct, using ConcurrentHashMap as a\n;; set of keys to get rid of duplicates. \n;; Keys at the end can be retrieved as an enumeration, \n;; and from that as a sequence, thanks to enumeration-seq\n\n(import '[java.util.concurrent ConcurrentHashMap])\n(require '[clojure.core.reducers :refer [fold]])\n\n(defn parallel-distinct [v]\n (let [m (ConcurrentHashMap.)\n combinef (fn ([] m) ([_ _]))\n reducef (fn [^ConcurrentHashMap m k] (.put m k 1) m)]\n (fold combinef reducef v)\n (enumeration-seq (.keys m))))\n\n(defn many-repeating-numbers [n]\n (into [] (take n (apply concat (repeat (range 10))))))\n\n(parallel-distinct (many-repeating-numbers 1e6))\n;; (0 1 2 3 4 5 6 7 8 9)","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"},"created-at":1519838098877,"updated-at":1519838192224,"_id":"5a96e392e4b0316c0f44f904"}],"notes":null,"arglists":["e"],"doc":"Returns a seq on a java.util.Enumeration","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/enumeration-seq"},{"added":"1.7","ns":"clojure.core","name":"dedupe","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1440188329568,"author":{"login":"blx","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/887504?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"distinct","ns":"clojure.core"},"_id":"55d787a9e4b072d7f27980ea"}],"line":7847,"examples":[{"editors":[{"login":"blx","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/887504?v=3"}],"body":"user=> (dedupe [1 2 3 3 3 1 1 6])\n(1 2 3 1 6)","author":{"avatar-url":"https://avatars.githubusercontent.com/u/887504?v=3","account-source":"github","login":"blx"},"created-at":1440188225498,"updated-at":1440188473719,"_id":"55d78741e4b0831e02cddf18"},{"updated-at":1558989991424,"created-at":1558989991424,"author":{"login":"AMacGregor27","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/46518023?v=4"},"body":";; This is taken from a problem on 4Clojure (30. Compress a sequence).\nuser=> (dedupe \"Leeeeroy\")\n(\\L \\e \\r \\o \\y)\n\nuser=> (dedupe [[1 2] [1 2] [3 4] [1 2]])\n([1 2] [3 4] [1 2])\n\nuser=> (dedupe [[1 [1 2]] [1 [2 3]] [1 [1 2]] [1 [1 2]]])\n([1 [1 2]] [1 [2 3]] [1 [1 2]])\n\n;; This does not remove all duplicates from a collection, only consecutive ones.\nuser=> (dedupe [1 2 2 1 1 1 2 1 2 2])\n(1 2 1 2 1 2)\n\n;; To remove all duplicates, use distinct.\nuser=> (distinct [1 2 2 1 1 1 2 1 2 2])\n(1 2)","_id":"5cec4ca7e4b0ca44402ef72f"},{"updated-at":1607179810709,"created-at":1607179810709,"author":{"login":"siddharthjain-in","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/6537820?v=4"},"body":"user=> (dedupe [1/2 2/4])\n(1/2)\n\nuser=>(dedupe [1/2 2/6])\n(1/2 1/3)\n\nuser=>(dedupe [1/2 0.5 2/4])\n(1/2 0.5 1/2)","_id":"5fcb9e22e4b0b1e3652d7416"},{"editors":[{"login":"huahaiy","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/889685?v=4"}],"body":";; parentheses can be omitted in thread macro \nuser> (->> [1 1 2 2] (map inc) dedupe)\n(2 3)\n;; transducer version that does not work, parentheses cannot be omitted\nuser> (sequence (comp (map inc) dedupe) [1 1 2 2])\nExecution error (IllegalArgumentException) at user/eval15380 (form-init7517833771916228311.clj:104).\nDon't know how to create ISeq from: clojure.lang.TransformerIterator$1\n;; transducer that works\nuser> (sequence (comp (map inc) (dedupe)) [1 1 2 2])\n(2 3)","author":{"avatar-url":"https://avatars.githubusercontent.com/u/889685?v=4","account-source":"github","login":"huahaiy"},"created-at":1639422117065,"updated-at":1639422160521,"_id":"61b798a5e4b0b1e3652d7589"}],"notes":null,"arglists":["","coll"],"doc":"Returns a lazy sequence removing consecutive duplicates in coll.\n Returns a transducer when no collection is provided.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/dedupe"},{"added":"1.0","ns":"clojure.core","name":"dissoc","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1293866784000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"assoc","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c5a"},{"created-at":1351064004000,"author":{"login":"TimMc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5d532e51427ef2f4ded31aaca16c8baf?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"disj","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c5c"},{"created-at":1367625873000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"select-keys","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c5d"},{"created-at":1696605582468,"author":{"login":"maria-silvia","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/57308135?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"update-in","ns":"clojure.core"},"_id":"6520258ee4b08cf8563f4bfc"},{"created-at":1713480532424,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"remove","ns":"clojure.core"},"_id":"6621a35469fbcc0c226174c0"}],"line":1519,"examples":[{"updated-at":1565336715281,"created-at":1280340610000,"body":"(dissoc {:a 1 :b 2 :c 3}) ; dissoc nothing \n;;=> {:a 1, :b 2, :c 3} \n\n(dissoc {:a 1 :b 2 :c 3} :b) ; dissoc key :b\n;;=> {:a 1, :c 3} \n\n(dissoc {:a 1 :b 2 :c 3} :d) ; dissoc not existing key\n;;=> {:a 1, :b 2, :c 3} \n\n(dissoc {:a 1 :b 2 :c 3} :c :b) ; several keys at once\n;;=> {:a 1} \n","editors":[{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/94482?v=3"},{"avatar-url":"https://avatars.githubusercontent.com/u/201852?v=3","account-source":"github","login":"michaelcameron"},{"login":"dominem","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/11671382?v=4"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/68dd6f50915854aa04fefcf4d6fa5c8e?r=PG&default=identicon","account-source":"clojuredocs","login":"zmila"},"_id":"542692cfc026201cdc326e63"},{"updated-at":1442111008755,"created-at":1442111008755,"author":{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/94482?v=3"},"body":";; There is no (dissoc-in) analogous to (get-in) or (assoc-in), but \n;; you can achieve a similar effect using (update-in):\n\n(update-in {:a {:b {:x 3} :c 1}} [:a :b] dissoc :x)\n;;=> {:a {:b {}, :c 1}}","_id":"55f4de20e4b05246bdf20a8e"},{"updated-at":1492776031769,"created-at":1492776031769,"author":{"login":"skuro","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/186085?v=3"},"body":";; When applied to a record and one of its base fields, \n;; dissoc produces a plain map instead of a record\n\n(defrecord Widget [id])\n(def w (->Widget \"id\"))\n\n(class w)\n;; user.Widget\n\n(class (dissoc w :id))\n;; clojure.lang.PersistentArrayMap","_id":"58f9f45fe4b01f4add58fe99"},{"updated-at":1516223401897,"created-at":1516223370479,"author":{"login":"RobinNagpal","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/745748?v=4"},"body":";; Removing multiple from nested map\n(update-in {:a {:b {:x 3 :y 5} :c 1}} [:a :b] \n (fn [nested] (apply dissoc nested [:x :y] )) )\n=> {:a {:b {}, :c 1}} ","editors":[{"avatar-url":"https://avatars3.githubusercontent.com/u/745748?v=4","account-source":"github","login":"RobinNagpal"}],"_id":"5a5fbb8ae4b0a08026c48cfc"},{"editors":[{"login":"TuggyNE","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/218900?v=4"}],"body":";; dissoc keys in a coll\nuser=> (reduce dissoc {:a 1 :b 2 :c 3} [:b :c])\n{:a 1}\n;; Can also use apply, a bit slower; any seqable works for either of these\nuser=> (apply dissoc {:a 1 :b 2 :c 3} #{:b :c})\n{:a 1}","author":{"avatar-url":"https://avatars0.githubusercontent.com/u/1518393?v=4","account-source":"github","login":"Em-AK"},"created-at":1608027071533,"updated-at":1736267760815,"_id":"5fd88bbfe4b0b1e3652d7418"}],"notes":[{"author":{"login":"u473t8","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/17592435?v=4"},"updated-at":1629458054605,"created-at":1629458054605,"body":"`(update {} :a dissoc :b) => {:a nil}`","_id":"611f8e86e4b0b1e3652d7533"}],"arglists":["map","map key","map key & ks"],"doc":"dissoc[iate]. Returns a new map of the same (hashed/sorted) type,\n that does not contain a mapping for key(s).","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/dissoc"},{"added":"1.0","ns":"clojure.core","name":"atom","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1281849237000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"reset!","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521eeb"},{"created-at":1281849248000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"swap!","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521eec"},{"created-at":1341623864000,"author":{"login":"johnnyluu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1ba99f2dc1064733c7badbb16db9254a?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"compare-and-set!","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521eed"},{"created-at":1349392634000,"author":{"login":"eric","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2b0c9ae6f1da9716451e7c86bc87230b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"add-watch","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521eee"},{"created-at":1349392638000,"author":{"login":"eric","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2b0c9ae6f1da9716451e7c86bc87230b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"remove-watch","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521eef"},{"created-at":1364873735000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"set-validator!","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ef0"},{"created-at":1527705006799,"author":{"login":"agarman","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/138454?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"swap-vals!","ns":"clojure.core"},"_id":"5b0eedaee4b045c27b7fac7d"},{"created-at":1527705359815,"author":{"login":"agarman","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/138454?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"reset-vals!","ns":"clojure.core"},"_id":"5b0eef0fe4b045c27b7fac84"},{"created-at":1712651107449,"author":{"login":"ghoseb","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1453?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"ref-set","ns":"clojure.core"},"_id":"6614fb6369fbcc0c226174ba"}],"line":2344,"examples":[{"author":{"login":"devn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"devn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3"}],"body":"user=> (def my-atom (atom 0))\n#'user/my-atom\n\nuser=> @my-atom\n0\n\nuser=> (swap! my-atom inc)\n1\n\nuser=> @my-atom\n1\n\nuser=> (swap! my-atom (fn [n] (* (+ n n) 2)))\n4\n\nuser=> (reset! my-atom 0)\n0\n\nuser=> @my-atom\n0","created-at":1281460949000,"updated-at":1476155071423,"_id":"542692cec026201cdc326db7"},{"body":"user=> (def a (atom #{}))\n#'user/a\n\nuser=>(swap! a conj :tag)\n#{:tag}\n\nuser=> @a\n#{:tag}","author":{"login":"mzenzie","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1862891?v=3"},"created-at":1433438207582,"updated-at":1433438207582,"_id":"557087ffe4b01ad59b65f4ee"},{"updated-at":1450892672375,"created-at":1450892672375,"author":{"login":"bostonaholic","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/362146?v=3"},"body":"user=> (def my-atom (atom 0 :validator even?))\n#'user/my-atom\n\nuser=> @my-atom\n0\n\nuser=> (swap! my-atom inc)\nIllegalStateException Invalid reference state clojure.lang.ARef.validate (ARef.java:33)\n\nuser=> (swap! my-atom (partial + 2))\n2\n\nuser=> @my-atom\n2","_id":"567add80e4b01f598e267e8f"},{"updated-at":1518532012281,"created-at":1518532012281,"author":{"login":"ibercode","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/31028993?v=4"},"body":"(def car\n (atom {:make \"Audi\"\n :model \"Q3\"}))\n\n@car\n;;{:make \"Audi\", :model \"Q3\"}\n\n(swap!\n car\n assoc :model \"Q5\")\n;;{:make \"Audi\", :model \"Q5\"}\n\n(reset! car {:make \"\" :model \"\"})\n;;{:make \"\", :model \"\"}","_id":"5a82f5ace4b0316c0f44f8bc"},{"editors":[{"login":"djblue","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1986211?v=4"}],"body":"(defn atom? [v]\n #?(:clj (instance? clojure.lang.Atom v)\n :cljs (satisfies? cljs.core/IAtom v)))\n\n(atom? (atom nil)) ;; => true","author":{"avatar-url":"https://avatars.githubusercontent.com/u/1986211?v=4","account-source":"github","login":"djblue"},"created-at":1661551176193,"updated-at":1661551230443,"_id":"63094248e4b0b1e3652d7658"}],"notes":null,"arglists":["x","x & options"],"doc":"Creates and returns an Atom with an initial value of x and zero or\n more options (in any order):\n\n :meta metadata-map\n\n :validator validate-fn\n\n If metadata-map is supplied, it will become the metadata on the\n atom. validate-fn must be nil or a side-effect-free fn of one\n argument, which will be passed the intended new state on any state\n change. If the new state is unacceptable, the validate-fn should\n return false or throw an exception.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/atom"},{"added":"1.0","ns":"clojure.core","name":"import","file":"clojure/core.clj","type":"macro","column":1,"see-alsos":[{"created-at":1291627622000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"require","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521ace"},{"created-at":1291628363000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"use","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521acf"},{"created-at":1291628388000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"ns","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521ad0"}],"line":3451,"examples":[{"author":{"login":"nipra","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/142529?v=3"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"YizhePKU","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/42838469?v=4"}],"body":"user=> (import java.util.Date)\njava.util.Date\n\nuser=> (def now (Date.))\n#'user/now\n\nuser=> (str now)\n\"Tue Jul 13 17:53:54 IST 2010\"\n","created-at":1279049126000,"updated-at":1588421112835,"_id":"542692c8c026201cdc326a01"},{"author":{"login":"dale","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a7a1eca257c6cea943fea41e5cc3e9a3?r=PG&default=identicon"},"editors":[{"avatar-url":"https://avatars1.githubusercontent.com/u/169654?v=4","account-source":"github","login":"noisesmith"},{"login":"YizhePKU","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/42838469?v=4"}],"body":";; You can import multiple classes at once.\n(import (java.util Date Calendar)\n (java.net URI ServerSocket)\n java.sql.DriverManager)","created-at":1294019024000,"updated-at":1588421172276,"_id":"542692c8c026201cdc326a03"},{"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"editors":[],"body":";; importing multiple classes in a namespace\n(ns foo.bar\n (:import (java.util Date\n Calendar)\n (java.util.logging Logger\n Level)))","created-at":1320992711000,"updated-at":1320992711000,"_id":"542692d3c026201cdc326fce"},{"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"},{"login":"Rooke","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/1158538?v=4"},{"avatar-url":"https://avatars1.githubusercontent.com/u/42838469?v=4","account-source":"github","login":"YizhePKU"}],"body":";; For cases when 'import' does not do it for you, i.e. \"live-coding\"\n;; You can use the DynamicClassLoader, ClassReader and the Resolver.\n\n(def dcl (clojure.lang.DynamicClassLoader.))\n\n(defn dynamically-load-class! \n [class-loader class-name]\n (let [class-reader (clojure.asm.ClassReader. class-name)]\n (when class-reader\n (let [bytes (.-b class-reader)]\n (.defineClass class-loader \n class-name \n bytes\n \"\")))))\n\n(dynamically-load-class! dcl \"java.lang.Long\")\n(dynamically-load-class! dcl 'org.joda.time.DateTime)\n\n;; From that point the dynamically loaded class can be\n;; used by the Reflector to invoke constructors, methods and to get fields. ","author":{"avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4","account-source":"github","login":"phreed"},"created-at":1508173740564,"updated-at":1588421462200,"_id":"59e4e7ace4b03026fe14ea8d"},{"editors":[{"login":"ooooak","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/1457253?v=4"}],"body":"(import [org.apache.commons.codec.digest DigestUtils])\n\n(defn md5-hash [input] \n (DigestUtils/md5Hex input))\n\n(md5-hash \"hello world!\") \n;; fc3ff98e8c6a0d3087d515c0473f8677","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/1457253?v=4","account-source":"github","login":"ooooak"},"created-at":1580227890599,"updated-at":1580227900588,"_id":"5e305d32e4b0ca44402ef824"}],"macro":true,"notes":[{"updated-at":1291628547000,"body":"Good description of use/require/import here:\r\n\r\nhttp://blog.8thlight.com/articles/2010/12/6/clojure-libs-and-namespaces-require-use-import-and-ns","created-at":1291628547000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fa9"},{"updated-at":1403035286000,"body":"`import` will also accept vectors instead of lists, but I would discourage folks from doing so:\r\n\r\n* It's undocumented.\r\n* Lists and vectors have different meanings for `require`, so there's precedent for making a distinction.\r\n* Lists have a distinguished first element, and so they indent more meaningfully here. :-P","created-at":1403035286000,"author":{"login":"TimMc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5d532e51427ef2f4ded31aaca16c8baf?r=PG&default=identicon"},"_id":"542692edf6e94c697052202a"},{"author":{"login":"YizhePKU","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/42838469?v=4"},"updated-at":1588421551270,"created-at":1588421551270,"body":"You don't need to use `import` if you fully qualify the class name, e.g. `(java.util.Date.)`.","_id":"5ead63afe4b087629b5a18fb"}],"arglists":["& import-symbols-or-lists"],"doc":"import-list => (package-symbol class-name-symbols*)\n\n For each name in class-name-symbols, adds a mapping from name to the\n class named by package.name to the current namespace. Use :import in the ns\n macro in preference to calling this directly.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/import"},{"added":"1.12","ns":"clojure.core","name":"splitv-at","file":"clojure/core.clj","type":"function","column":1,"see-alsos":null,"line":7422,"examples":null,"notes":null,"arglists":["n coll"],"doc":"Returns a vector of [(into [] (take n) coll) (drop n coll)]","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/splitv-at"},{"added":"1.0","ns":"clojure.core","name":"bit-shift-right","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1405719667000,"author":{"login":"phreed","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3a0c739cf289be18be932dc3022e6fd3?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"bit-shift-left","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521aaf"},{"created-at":1405719682000,"author":{"login":"phreed","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3a0c739cf289be18be932dc3022e6fd3?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"bit-xor","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521ab0"},{"created-at":1405719694000,"author":{"login":"phreed","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3a0c739cf289be18be932dc3022e6fd3?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"bit-or","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521ab1"},{"created-at":1405719700000,"author":{"login":"phreed","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3a0c739cf289be18be932dc3022e6fd3?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"bit-and","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521ab2"},{"created-at":1405719706000,"author":{"login":"phreed","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3a0c739cf289be18be932dc3022e6fd3?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"bit-set","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521ab3"},{"created-at":1405719712000,"author":{"login":"phreed","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3a0c739cf289be18be932dc3022e6fd3?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"bit-test","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521ab4"},{"created-at":1405719724000,"author":{"login":"phreed","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3a0c739cf289be18be932dc3022e6fd3?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"bit-flip","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521ab5"},{"created-at":1405719732000,"author":{"login":"phreed","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3a0c739cf289be18be932dc3022e6fd3?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"bit-and-not","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521ab6"},{"created-at":1405719739000,"author":{"login":"phreed","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3a0c739cf289be18be932dc3022e6fd3?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"bit-clear","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521ab7"},{"created-at":1412094678691,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=2"},"to-var":{"ns":"clojure.core","name":"unsigned-bit-shift-right","library-url":"https://github.com/clojure/clojure"},"_id":"542adad6e4b0df9bb778a5a4"}],"line":1376,"examples":[{"author":{"login":"devijvers","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/81018e4231ac1ce8b7a9e6d377092656?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":";; Convert number into list of bits:\n(defn bits [n s]\n (take s\n (map\n (fn [i] (bit-and 0x01 i))\n (iterate\n (fn [i] (bit-shift-right i 1))\n n))))\n;; #'user/bits\n\n(map (fn [n] (bits n 3)) (range 8))\n;;=> ((0 0 0) (1 0 0) (0 1 0) (1 1 0) (0 0 1) (1 0 1) (0 1 1) (1 1 1))\n","created-at":1280029081000,"updated-at":1421878196402,"_id":"542692cec026201cdc326dbb"},{"author":{"login":"zmila","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/68dd6f50915854aa04fefcf4d6fa5c8e?r=PG&default=identicon"},"editors":[{"login":"replore","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e7869fe1a48cb1814c657eaca6bea3eb?r=PG&default=identicon"},{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":"(bit-shift-right 2r1101 0) ;;=> 13\n(bit-shift-right 2r1101 1) ;;=> 6\n(bit-shift-right 2r1101 2) ;;=> 3\n(bit-shift-right 2r1101 3) ;;=> 1\n(bit-shift-right 2r1101 4) ;;=> 0","created-at":1280339098000,"updated-at":1421877723171,"_id":"542692cec026201cdc326dbe"},{"editors":[{"login":"fasiha","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/37649?v=3"}],"body":";; Warning: bit-shift-right upcasts arguments to Long and returns Long\n(format \"0x%x\" (byte -128))\n; => \"0x80\"\n(format \"0x%x\" (bit-shift-right (byte -128) 1)) ; You'd expect 0x40?\n; => \"0xffffffffffffffc0\"\n; You'd expect 0x40, but (byte -128) was converted to (long -128) and then\n; right-shifted, with the negative sign bit of 1 propagated.\n\n; This can't be avoided by using unsigned-bit-shift-right:\n(format \"0x%x\" (unsigned-bit-shift-right (byte -128) 1))\n; => \"0x7fffffffffffffc0\"\n\n; If you want unsigned \"byte\" operations, upcast the byte yourself via bit-and:\n(format \"0x%x\" (bit-shift-right (bit-and 0xff (byte -128)) 1))\n; => \"0x40\"\n\n; This works because the output of bit-and is always Long:\n(type (bit-and 0xff (byte -128)))\n; => java.lang.Long\n; Note that bit-and returns Long even if both arguments are smaller:\n(type (bit-and (short 0xff) (byte -128)))\n; => java.lang.Long","author":{"avatar-url":"https://avatars.githubusercontent.com/u/37649?v=3","account-source":"github","login":"fasiha"},"created-at":1460044794475,"updated-at":1460044978009,"_id":"570683fae4b0fc95a97eab30"},{"editors":[{"login":"Sophia-Gold","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/19278114?v=3"}],"body":";; floating point bit-shifting\n;; thanks to Gary Fredericks: https://github.com/gfredericks/doubles\n(defn bit-shift-double [x shifts]\n (let [x-long (Double/doubleToRawLongBits x)]\n (Double/longBitsToDouble\n (bit-or (bit-and 1 x-long)\n (bit-shift-left (- (bit-shift-right x-long 52) shifts) 52)\n (bit-and 0xfffffffffffff x-long)))))","author":{"avatar-url":"https://avatars.githubusercontent.com/u/19278114?v=3","account-source":"github","login":"Sophia-Gold"},"created-at":1483958434391,"updated-at":1484376283481,"_id":"587368a2e4b09108c8545a53"}],"notes":[{"updated-at":1326789497000,"body":"From the IRC channel, a way to get zero-fill bit-shift-right:\r\n\r\n
06:08 < mikera> (defn >>> [v bits] (bit-shift-right (bit-and 0xFFFFFFFF v) bits))
\r\n\r\nThere's also an open ticket for a [built-in version](http://dev.clojure.org/jira/browse/CLJ-827).","created-at":1326786313000,"author":{"login":"TimMc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5d532e51427ef2f4ded31aaca16c8baf?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fd7"},{"body":"unsigned-bit-shift-right was added in Clojure 1.6.0. Click the link in the See Also section above.","created-at":1415350996576,"updated-at":1415350996576,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=2"},"_id":"545c8ad4e4b03d20a102429f"}],"arglists":["x n"],"doc":"Bitwise shift right","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/bit-shift-right"},{"ns":"clojure.core","name":"print-method","file":"clojure/core.clj","type":"var","column":1,"see-alsos":[{"created-at":1340861043000,"author":{"login":"abrooks","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/69976?v=2"},"to-var":{"ns":"clojure.core","name":"print-dup","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521dda"}],"line":3689,"examples":[{"author":{"login":"pangloss","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1202c95dec14eee416717e8c0add0f0c?r=PG&default=identicon"},"editors":[],"body":"(deftype XYZ [])\n\n; without custom print-method defined:\nuser=> (prn (XYZ.))\n# \n\n(defmethod print-method XYZ [v ^java.io.Writer w]\n (.write w \"<<-XYZ->>\"))\n\n; with print-method\nuser=> (prn (XYZ.))\n<<-XYZ->>\n","created-at":1369992423000,"updated-at":1369992423000,"_id":"542692d4c026201cdc327037"},{"updated-at":1618155203105,"created-at":1618155203105,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/20086?v=4"},"body":"(import '[java.net URL] [java.io File])\n\n;; Extends pr-str to URL objects with a form suitable for \n;; read-string to read back into an URL with the related\n;; https://clojuredocs.org/clojure.core/*data-readers* binding:\n\n(defmethod print-method URL [url writer]\n (doto writer\n (.write \"#url \")\n (.write \"\\\"\")\n (.write (.toString url))\n (.write \"\\\"\")))\n\n(-> \"/etc/hosts\" File. .toURL pr-str)\n;; \"#url \\\"file:/etc/hosts\\\"\"\n","_id":"607316c3e4b0b1e3652d74c3"}],"notes":[{"author":{"login":"mrzor","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/54230?v=3"},"updated-at":1471957106762,"created-at":1471957106762,"body":"Take care when writing things that look like a reader macro, like `#mything<42 42 42>`.\nIt may break your AOT compilations with a `java.lang.RuntimeException: No reader function for tag mything`.\n\nA quick workaround is not to emit a `#` character.\nThe thorough solution starts by reading https://clojuredocs.org/clojure.core/*data-readers* and is beyond the scope of this note.","_id":"57bc4872e4b0709b524f04d3"}],"arglists":[],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core/print-method"},{"added":"1.0","ns":"clojure.core","name":"peek","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1400493737000,"author":{"login":"ryo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3f7913b563c72083c74030d928ba407e?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"first","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521ab8"},{"created-at":1400493750000,"author":{"login":"ryo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3f7913b563c72083c74030d928ba407e?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"pop","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521ab9"},{"created-at":1400493759000,"author":{"login":"ryo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3f7913b563c72083c74030d928ba407e?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"conj","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521aba"}],"line":1474,"examples":[{"author":{"login":"pkolloch","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/10b2fd3c0a4cc46dc241a48468dc551?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":"user=> (def large-vec (vec (range 0 10000)))\n#'user/large-vec\n\nuser=> (time (last large-vec))\n\"Elapsed time: 1.279841 msecs\"\n9999\n\nuser=> (time (peek large-vec))\n\"Elapsed time: 0.049238 msecs\"\n9999\n","created-at":1282321027000,"updated-at":1285494456000,"_id":"542692ccc026201cdc326c33"},{"author":{"login":"TravisHeeter","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/fe491d07493e45af083b89b767342c6?r=PG&default=identicon"},"editors":[],"body":"user=> (peek '(:a :b :c))\n:a","created-at":1385176400000,"updated-at":1385176400000,"_id":"542692d4c026201cdc32702f"},{"updated-at":1470911342408,"created-at":1470911342408,"author":{"login":"ertugrulcetin","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8271291?v=3"},"body":"user=> (peek [1 2 3 4])\n;;=> 4\n\nuser=> (peek [])\n;;=> nil\n\nuser=> (peek '(1 2 3 4))\n;;=> 1\n\nuser=> (peek '())\n;;=> nil\n\nuser=> (peek nil)\n;;=> nil","_id":"57ac536ee4b0bafd3e2a04e2"},{"editors":[{"login":"daveliepmann","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/974443?v=4"}],"body":";;peek on vector returns the last element\n(peek [1 2 3])\n;; 3\n\n;;peek on list returns the first element\n(peek '(1 2 3))\n;; 1","author":{"avatar-url":"https://avatars0.githubusercontent.com/u/31028993?v=4","account-source":"github","login":"ibercode"},"created-at":1518706830878,"updated-at":1757525008124,"_id":"5a85a08ee4b0316c0f44f8bd"}],"notes":[{"updated-at":1349888814000,"body":"Small reminder:\r\n\r\n
\r\nDo not work for arbitrary seq but just for persistent types implementing clojure.lang.IPersistentStack (like clojure.lang.Persistent*).\r\n\r\n
\r\nExample:\r\n
user> (peek (cons 1 '()))\r\n; Evaluation aborted.\r\n
\r\ndo not work because type is clojure.lang.Cons but\r\n\r\n
user> (peek (conj '() 1))\r\n1\r\n
\r\nworks because type is clojure.lang.PersistentList.","created-at":1349884718000,"author":{"login":"tomby42","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/305033855efb82d6041586b874b5bb24?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fea"}],"arglists":["coll"],"doc":"For a list or queue, same as first, for a vector, same as, but much\n more efficient than, last. If the collection is empty, returns nil.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/peek"},{"added":"1.0","ns":"clojure.core","name":"aget","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1359687973000,"author":{"login":"mmwaikar","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/29d36f4c9f39c9f8ff61c07033b13118?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"aclone","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521af2"},{"created-at":1389744326000,"author":{"login":"jw0","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/ca45063da41a9f3aa9028295d8b66d89?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"get","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521af3"},{"created-at":1389744330000,"author":{"login":"jw0","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/ca45063da41a9f3aa9028295d8b66d89?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"nth","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521af4"},{"created-at":1454023320808,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"contains?","ns":"clojure.core"},"_id":"56aaa298e4b060004fc217b3"},{"created-at":1593147984636,"author":{"login":"huahaiy","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/889685?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"aset","ns":"clojure.core"},"_id":"5ef58250e4b0b1e3652d7310"}],"line":3938,"examples":[{"updated-at":1454082671521,"created-at":1284178036000,"body":"\n;; create two arrays\n(def a1 (double-array '(1.0 2.0 3.0 4.0)))\n;;=> #'user/a1\n(def a2 (int-array '(9 8 7 6)))\n;;=> #'user/a2\n\n;; get an item by index\n(aget a1 2)\n;;=> 3.0\n(aget a2 3)\n;;=> 6\n\n;; 2d array and 2 indicies\n(def a3 (make-array Integer/TYPE 100 100))\n;;=> #'user/a3\n(aget a3 23 42)\n;;=> 0","editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/363fd6c774471e207b327fda11b246c7?r=PG&default=identicon","account-source":"clojuredocs","login":"dermatthias"},"_id":"542692cec026201cdc326da0"},{"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":";; aget can be used to check the existence of an element\n;; this approach works with documents in ClojureScript where core/contains? does not\n(aget js/document \"getElementById\")\n;;=> #object[getElementById \"function getElementById() { [native code] }\"]\n(contains? js/document \"getElementById\")\n;;=> false","author":{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3","account-source":"github","login":"phreed"},"created-at":1454022947998,"updated-at":1454082875581,"_id":"56aaa123e4b0ceed88ce8d19"}],"notes":null,"arglists":["array idx","array idx & idxs"],"doc":"Returns the value at the index/indices. Works on Java arrays of all\n types.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/aget"},{"added":"1.0","ns":"clojure.core","name":"pvalues","file":"clojure/core.clj","static":true,"type":"macro","column":1,"see-alsos":[{"created-at":1329792245000,"author":{"login":"cmccoy","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cf46d3ffedb153a97fe69cb4719e0fd?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"pmap","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e7d"},{"created-at":1336537825000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.core","name":"future","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e7e"},{"created-at":1423019380983,"author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"to-var":{"ns":"clojure.core","name":"pcalls","library-url":"https://github.com/clojure/clojure"},"_id":"54d18d74e4b0e2ac61831d0a"}],"line":7191,"examples":[{"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":";; expressions are calculated in parallel\n\nuser=> (pvalues (expensive-calc-1) (expensive-calc-2))\n(2330 122)\n","created-at":1280322280000,"updated-at":1285496725000,"_id":"542692cac026201cdc326b59"},{"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":";; pvalues is implemented using Clojure futures. See examples for 'future'\n;; for discussion of an undesirable 1-minute wait that can occur before\n;; your standalone Clojure program exits if you do not use shutdown-agents.","created-at":1336537820000,"updated-at":1406853126000,"_id":"542692d4c026201cdc327046"}],"macro":true,"notes":null,"arglists":["& exprs"],"doc":"Returns a lazy sequence of the values of the exprs, which are\n evaluated in parallel","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/pvalues"},{"added":"1.1","ns":"clojure.core","name":"bound-fn","file":"clojure/core.clj","type":"macro","column":1,"see-alsos":[{"created-at":1331766568000,"author":{"login":"metajack","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/194d8437f5baed192c90be27369c4922?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"bound-fn*","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d55"}],"line":2023,"examples":[{"author":{"login":"metajack","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/194d8437f5baed192c90be27369c4922?r=PG&default=identicon"},"editors":[],"body":"(def ^:dynamic *some-var* nil)\n\n(defn f [] (println *some-var*))\n\n;; run f without a new binding\nuser=> (f)\nnil\nnil\n\n;; run f with a new binding\nuser=> (binding [*some-var* \"hello\"]\n (f))\nhello\nnil\n\n;; run f in a thread with a new binding\nuser=> (binding [*some-var* \"goodbye\"]\n (.start (Thread. f)))\nnil\nnil\n\n;; run a bound f in a thread with a new binding\nuser=> (binding [*some-var* \"goodbye\"]\n (.start (Thread. (bound-fn [] (f)))))\ngoodbye\nnil\n","created-at":1331769907000,"updated-at":1331769907000,"_id":"542692d2c026201cdc326f5c"}],"macro":true,"notes":null,"arglists":["& fntail"],"doc":"Returns a function defined by the given fntail, which will install the\n same bindings in effect as in the thread at the time bound-fn was called.\n This may be used to define a helper function which runs on a different\n thread, but needs the same bindings in place.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/bound-fn"},{"added":"1.7","ns":"clojure.core","name":"vswap!","file":"clojure/core.clj","type":"macro","column":1,"see-alsos":[{"created-at":1469617377040,"author":{"login":"kumarshantanu","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109792?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"volatile!","ns":"clojure.core"},"_id":"579894e1e4b0bafd3e2a04bf"},{"created-at":1492398573657,"author":{"login":"didibus","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/601540?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"vreset!","ns":"clojure.core"},"_id":"58f431ede4b01f4add58fe91"},{"created-at":1492398581193,"author":{"login":"didibus","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/601540?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"volatile?","ns":"clojure.core"},"_id":"58f431f5e4b01f4add58fe92"},{"created-at":1492398620716,"author":{"login":"didibus","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/601540?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"swap!","ns":"clojure.core"},"_id":"58f4321ce4b01f4add58fe93"}],"line":2556,"examples":[{"updated-at":1492398484318,"created-at":1492398484318,"author":{"login":"didibus","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/601540?v=3"},"body":"(let [interrupt (volatile! false)\n f1 (future (Thread/sleep 1000)\n (vswap! interrupt not))\n f2 (future (while (not @interrupt)\n (println \"Another cycle!\")\n (Thread/sleep 100)))]\n @f1\n @f2)","_id":"58f43194e4b01f4add58fe90"}],"macro":true,"notes":null,"arglists":["vol f & args"],"doc":"Non-atomically swaps the value of the volatile as if:\n (apply f current-value-of-vol args). Returns the value that\n was swapped in.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/vswap!"},{"added":"1.0","ns":"clojure.core","name":"last","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1289038378000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"first","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e58"},{"created-at":1289038381000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"next","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e59"},{"created-at":1289038385000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"rest","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e5a"},{"created-at":1289038414000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"butlast","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e5b"},{"created-at":1306817792000,"author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"to-var":{"ns":"clojure.core","name":"take-last","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e5c"},{"created-at":1436712121100,"author":{"login":"sindux","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1397898?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"peek","ns":"clojure.core"},"_id":"55a27cb9e4b020189d740550"}],"line":264,"examples":[{"updated-at":1473264230717,"created-at":1279416204000,"body":"user=> (last [1 2 3 4 5])\n5\nuser=> (last [\"a\" \"b\" \"c\" \"d\" \"e\"])\n\"e\"\nuser=> (last {:one 1 :two 2 :three 3})\n[:three 3]\nuser=> (last [])\nnil\n\n;; but be careful with what you expect from a map (or set):\nuser=> (last {:a 1 :b 2 :c 3 :d 4 :e 5 :f 6 :g 7 :h 8 :i 9})\n[:a 1]","editors":[{"avatar-url":"https://avatars2.githubusercontent.com/u/22608?v=4","account-source":"github","login":"MrHus"},{"avatar-url":"https://www.gravatar.com/avatar/69ad2af1f028b1b7e76c14f83bdf26cb?r=PG&default=identicon","account-source":"clojuredocs","login":"jszakmeister"},{"avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3","account-source":"github","login":"Dimagog"},{"login":"reborg","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/20086?v=3"}],"author":{"login":"MrHus","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/22608?v=4"},"_id":"542692c8c026201cdc326a2c"},{"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"editors":[],"body":";really slow reverse\n;put the last item of the list at the start of a new list, and recur over all but the last item of the list.\n;butlast acts similar to next in that it returns null for a 1-item list.\n\n(defn my-reverse\n ([a-list]\n (cond (= a-list nil) nil\n :else (cons (last a-list)\n (my-reverse (butlast a-list))))))","created-at":1289038818000,"updated-at":1289038818000,"_id":"542692c8c026201cdc326a2f"},{"updated-at":1499968174976,"created-at":1499966780539,"author":{"login":"webappzero","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1661060?v=3"},"body":";; Prefer clojure.core/peek over `last` for potentially large vectors.\n\nuser=> (def v (into [] (take 900900 (range))))\n#'user/v\n\nuser=> (time (last v))\n\"Elapsed time: 24.460958 msecs\"\n900899\n\nuser=> (def v2 (into [] (take 900900 (range))))\n#'user/v2\n\nuser=> (time (peek v2))\n\"Elapsed time: 0.020498 msecs\"\n900899\n\n;; For a deep dive into why Rich Hickey chose not to make `last` performant\n;; for large vectors, please see:\n;; https://gist.github.com/reborg/dc8b0c96c397a56668905e2767fd697f\n\n","editors":[{"avatar-url":"https://avatars2.githubusercontent.com/u/1661060?v=3","account-source":"github","login":"webappzero"}],"_id":"5967ad3ce4b0d19c2ce9d6f9"},{"editors":[{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"}],"body":";; last is also inefficient for sorted-sets and sorted-maps, and\n;; peek doesn't work for these, so we can combine `first` with `rseq`\n;; to efficiently get the last element on large sorted- collections instead\n\n(def sm (into (sorted-map)\n (map vector (range 1e6) (repeatedly #(rand-int 100)))))\n\n(time (last sm))\n\"Elapsed time: 144.298867 msecs\"\n;; => [999999 42]\n\n(time (first (rseq sm)))\n\"Elapsed time: 0.024408 msecs\"\n;; => [999999 42]","author":{"avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4","account-source":"github","login":"tomdl89"},"created-at":1680193851632,"updated-at":1680196828207,"_id":"6425b93be4b08cf8563f4b89"},{"updated-at":1728637092443,"created-at":1728637092443,"author":{"login":"sanel","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/213914?v=4"},"body":";; Beside using clojure.core/peek for fast access to the last element in\n;; a large vector, you can also use (first (rseq)) which is performant as well\n\n(def v (into [] (take 900900 (range))))\n(time (last v))\n\"Elapsed time: 24.825208 msecs\"\n900899\n\n(def v2 (into [] (take 900900 (range))))\n(time (peek v2))\n\"Elapsed time: 0.02343 msecs\"\n900899\n\n(def v3 (into [] (take 900900 (range))))\n(time (first (rseq v3)))\n\"Elapsed time: 0.02581 msecs\"\n900899","_id":"6708e8a469fbcc0c22617505"}],"notes":null,"arglists":["coll"],"doc":"Return the last item in coll, in linear time","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/last"},{"added":"1.0","ns":"clojure.core","name":"pr","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1290689171000,"author":{"login":"dale","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a7a1eca257c6cea943fea41e5cc3e9a3?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"print","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bd2"},{"created-at":1299623874000,"author":{"login":"TimMc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5d532e51427ef2f4ded31aaca16c8baf?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"prn","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bd3"},{"created-at":1299623879000,"author":{"login":"TimMc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5d532e51427ef2f4ded31aaca16c8baf?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"pr-str","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bd4"},{"created-at":1470508478634,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"read","ns":"clojure.edn"},"_id":"57a62dbee4b0bafd3e2a04ca"}],"dynamic":true,"line":3703,"examples":[{"author":{"login":"srid","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bd3a68d670372cd09876c26270a4299a?r=PG&default=identicon"},"editors":[],"body":"user=> (pr \"foo\")\n\"foo\"nil","created-at":1315392482000,"updated-at":1315392482000,"_id":"542692cec026201cdc326da1"},{"author":{"login":"srid","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bd3a68d670372cd09876c26270a4299a?r=PG&default=identicon"},"editors":[],"body":"user=> (pr {:foo \"hello\" :bar 34.5})\n{:foo \"hello\", :bar 34.5}nil","created-at":1315392515000,"updated-at":1315392515000,"_id":"542692cec026201cdc326da2"},{"body":";; Difference between pr and print\n\nuser=> (pr ['a :b \"\\n\" \\space \"c\"])\n[a :b \"\\n\" \\space \"c\"]nil\n\nuser=> (print ['a :b \"\\n\" \\space \"c\"])\n[a :b\n c]nil\n","author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"created-at":1423019089923,"updated-at":1423019089923,"_id":"54d18c51e4b0e2ac61831d09"},{"updated-at":1470507649207,"created-at":1470507649207,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"body":";; WARNING: Clojure's keyword and symbol functions allow you to create\n;; values that cannot be printed then later read and recreate those same\n;; values.\n\n;; For most common symbols and keywords, they round-trip through pr\n;; then read-string, as this example shows.\nuser=> (read-string (with-out-str (pr {:a 1, :b 2})))\n{:a 1, :b 2}\n\n;; But these values do not round-trip through the same steps:\nuser=> (def kw1 (keyword \"foo bar\"))\n#'user/kw1\nuser=> kw1\n:foo bar\nuser=> (def s2 (with-out-str (pr {kw1 1, :b 2})))\n#'user/s2\nuser=> s2\n\"{:foo bar 1, :b 2}\"\nuser=> (read-string s2)\n\nRuntimeException Map literal must contain an even number of forms clojure.lang.Util.runtimeException (Util.java:221)\n\n;; Similarly for a symbol like (symbol \"a;b\")\nuser=> (def sym1 (symbol \"a;b\"))\n#'user/sym1\nuser=> sym1\na;b\nuser=> (def s3 (with-out-str (pr sym1)))\n#'user/s3\nuser=> s3\n\"a;b\"\nuser=> (read-string s3)\na\n\n;; If you wish to transmit data that may contain such values, one suggestion\n;; is to use the transit library: https://github.com/cognitect/transit-format\n\n;; It is much faster and formally specified.","_id":"57a62a81e4b0bafd3e2a04c9"}],"notes":[{"author":{"login":"jcburley","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/430319?v=4"},"updated-at":1514410889866,"created-at":1514410889866,"body":"\"Readable by the reader\" means, for example, that a string is printed with surrounding double quotes and with quotes, backslashes, and nonprinting characters being escaped via a backslash prefix.","_id":"5a441389e4b0a08026c48ce2"}],"arglists":["","x","x & more"],"doc":"Prints the object(s) to the output stream that is the current value\n of *out*. Prints the object(s), separated by spaces if there is\n more than one. By default, pr and prn print in a way that objects\n can be read by the reader","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/pr"},{"added":"1.0","ns":"clojure.core","name":"namespace","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1366844136000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"ns","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d8a"},{"created-at":1385200446000,"author":{"login":"abrooks","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/69976?v=2"},"to-var":{"ns":"clojure.core","name":"name","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d8b"},{"created-at":1523484084873,"author":{"login":"delonnewman","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/10404?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"def","ns":"clojure.core"},"_id":"5ace85b4e4b045c27b7fac3d"}],"line":1612,"examples":[{"author":{"login":"Miles","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bbb26d2a5e856c4fba0f72c3f7250f3f?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"Miles","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bbb26d2a5e856c4fba0f72c3f7250f3f?r=PG&default=identicon"}],"body":"user=> (def x \"Foobar\")\n#'user/x\n\nuser=> (namespace 'user/x)\n\"user\"\n","created-at":1284256918000,"updated-at":1287791961000,"_id":"542692cbc026201cdc326c1d"},{"editors":[{"login":"dominem","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/11671382?v=4"}],"body":"(namespace :admin/live-playlist-details)\n;;=> \"admin\"\n\n(namespace :about)\n;;=> nil","author":{"avatar-url":"https://avatars3.githubusercontent.com/u/11671382?v=4","account-source":"github","login":"dominem"},"created-at":1565335391711,"updated-at":1565335408498,"_id":"5d4d1f5fe4b0ca44402ef795"}],"notes":[{"body":"Note this does not try to be \"smart\"\n\n```\nuser=>(namespace 'no-such-name/no-such-var)\n\"no-such-name\"\n\nuser=>(def a-var)\n#'user-a-var\n\nuser=>(namespace 'a-var)\nnil\n```","created-at":1443303990722,"updated-at":1443304019556,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/159998?v=3","account-source":"github","login":"merriam"},"_id":"56071236e4b08e404b6c1c89"}],"tag":"java.lang.String","arglists":["x"],"doc":"Returns the namespace String of a symbol or keyword, or nil if not present.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/namespace"},{"added":"1.1","ns":"clojure.core","name":"push-thread-bindings","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1374313643000,"author":{"login":"alilee","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2fb0196dc5a7cd3a5cc73f1b9941c209?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"pop-thread-bindings","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d2b"},{"created-at":1374313651000,"author":{"login":"alilee","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2fb0196dc5a7cd3a5cc73f1b9941c209?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"binding","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d2c"},{"created-at":1374313699000,"author":{"login":"alilee","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2fb0196dc5a7cd3a5cc73f1b9941c209?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"with-bindings","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d2d"}],"line":1930,"examples":null,"notes":null,"arglists":["bindings"],"doc":"WARNING: This is a low-level function. Prefer high-level macros like\n binding where ever possible.\n\n Takes a map of Var/value pairs. Binds each Var to the associated value for\n the current thread. Each call *MUST* be accompanied by a matching call to\n pop-thread-bindings wrapped in a try-finally!\n \n (push-thread-bindings bindings)\n (try\n ...\n (finally\n (pop-thread-bindings)))","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/push-thread-bindings"},{"added":"1.0","ns":"clojure.core","name":"bases","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1519504605797,"author":{"login":"didibus","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/601540?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"supers","ns":"clojure.core"},"_id":"5a91ccdde4b0316c0f44f8ee"},{"created-at":1519504691579,"author":{"login":"didibus","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/601540?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"type","ns":"clojure.core"},"_id":"5a91cd33e4b0316c0f44f8ef"}],"line":5596,"examples":[{"author":{"login":"teyc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bd6e62afb4881ab0f617611b8b65d003?r=PG&default=identicon"},"editors":[],"body":"
user=> (import 'java.io.File)\r\n\r\nuser=> (bases java.io.File)\r\n(java.lang.Object java.io.Serializable java.lang.Comparable)
","created-at":1283977099000,"updated-at":1283977099000,"_id":"542692c9c026201cdc326ac4"},{"body":";; what is a hash-map?\n(bases (class {}))\n;;=> (clojure.lang.APersistentMap \n;;+> clojure.lang.IObj \n;;+> clojure.lang.IEditableCollection)\n\n;; what is a set?\n(bases (class #{}))\n;;=> (clojure.lang.APersistentSet \n;;+> clojure.lang.IObj \n;;+> clojure.lang.IEditableCollection)\n\n;; what is a vector?\n(bases (class []))\n;;=> (clojure.lang.APersistentVector \n;;+> clojure.lang.IObj \n;;+> clojure.lang.IEditableCollection)\n\n;; what is a list? \n(bases (class ()))\n;;=> (clojure.lang.Obj \n;;+> clojure.lang.IPersistentList \n;;+> java.util.List \n;;+> clojure.lang.ISeq \n;;+> clojure.lang.Counted \n;;+> clojure.lang.IHashEq)","author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"},"created-at":1414510940403,"updated-at":1414510965758,"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"}],"_id":"544fb95ce4b03d20a102428b"},{"updated-at":1598220307317,"created-at":1598220307317,"author":{"login":"berczeck","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/1321842?v=4"},"body":";; what is a defrecord\n\nuser=> (defprotocol Fly\n (fly [this]))\n\nuser=> (defrecord Bird [name] Fly\n (fly [this] (str (:name this) \" flies....\")))\n\nuser=> (ancestors Bird)\n;; (java.lang.Object \n;; user.Fly \n;; clojure.lang.IRecord \n;; clojure.lang.IHashEq \n;; clojure.lang.IObj \n;; clojure.lang.ILookup \n;; clojure.lang.IKeywordLookup \n;; clojure.lang.IPersistentMap \n;; java.util.Map \n;; java.io.Serializable)\n","_id":"5f42e813e4b0b1e3652d73a5"}],"notes":null,"arglists":["c"],"doc":"Returns the immediate superclass and direct interfaces of c, if any","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/bases"},{"added":"1.0","ns":"clojure.core","name":"=","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1287469623000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"==","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f25"},{"created-at":1291975060000,"author":{"login":"alimoeeny","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e8dd06976ead4082d2181f3807117e1?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"not=","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f26"},{"created-at":1298162787000,"author":{"login":"TimMc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5d532e51427ef2f4ded31aaca16c8baf?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"identical?","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f27"}],"line":785,"examples":[{"updated-at":1474477801279,"created-at":1280470020000,"body":"user=> (= 1)\ntrue\nuser=> (= 1 1)\ntrue\nuser=> (= 1 2)\nfalse\nuser=> (= 1 1 1)\ntrue\nuser=> (= 1 1 2)\nfalse\nuser=> (= '(1 2) [1 2])\ntrue\nuser=> (= nil nil)\ntrue\nuser=> (= (sorted-set 2 1) (sorted-set 1 2))\ntrue\n\n;; It should be noted that equality is not defined for Java arrays.\n;; Instead you can convert them into sequences and compare them that way.\n;; (= (seq array1) (seq array2))\n","editors":[{"avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon","account-source":"clojuredocs","login":"gstamp"},{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"login":"reborg","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/20086?v=3"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/b3881a28fe402dd2d1de44717486cae8?r=PG&default=identicon","account-source":"clojuredocs","login":"citizen428"},"_id":"542692ccc026201cdc326c72"},{"editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2","account-source":"github","login":"phreed"},{"login":"iammegatron","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/406013?v=3"}],"updated-at":1450298371193,"created-at":1412883142742,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2","account-source":"github","login":"phreed"},"body":";; There are functional differences between = and == \n;; = may introduce java autoboxing \n\n;; true:\n(= 1)\n(= 1 1) \n(= 1/1, 2/2, 3/3, 4/4) \n(= :foo)\n(= nil anything) ; anything = nil\n\n\n;; false:\n(= 1, 1.0, 1/1) ; differs from ==\n(= 1 2)\n(= 1 \\1) ; differs from ==\n(= 1 \"1\") ; differs from ==\n\n","_id":"5436e2c6e4b06dbffbbb00c7"},{"body":";; If passed a single value (= x) the result is always true.\n(= 1)\n(= nil)\n(= false)\n(= true)\n(= {:a 1 :b2})\n(= 'false)\n;;=> true \n","author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"},"created-at":1418923922664,"updated-at":1418923922664,"_id":"54930f92e4b04e93c519ffa9"},{"updated-at":1543388969936,"created-at":1543388779355,"author":{"login":"huahaiy","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/889685?v=4"},"body":";; = can be used to compare the equality of nested Clojure data structures\n(= {:a [1 {1 2}] :b 'ok :c \"string\"} \n {:b 'ok :c \"string\" :a '(1 {1 2})})\n;;=> true","editors":[{"avatar-url":"https://avatars3.githubusercontent.com/u/889685?v=4","account-source":"github","login":"huahaiy"}],"_id":"5bfe3e6be4b0ca44402ef5cc"},{"editors":[{"login":"huahaiy","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/889685?v=4"},{"avatar-url":"https://avatars2.githubusercontent.com/u/109629?v=4","account-source":"github","login":"jafingerhut"}],"body":";; See the Clojure Equality guide for more details:\n;; https://clojure.org/guides/equality\n\n;; One perhaps surprising case is comparing regular expressions.\n;; In Clojure, regular expressions only equal one another if they are\n;; the same object in memory, i.e. if (identical? x y) is also true.\n;; Therefore, any data structure containing regular expression will \n;; only be equal to one another if the corresponding regular expressions are\n;; identical.\n;; See https://dev.clojure.org/jira/browse/CLJ-1182\n(= #\"fav*\" #\"fav*\")\n;;=> false\n\n;; Another exception is the special floating point value ##NaN for \"Not a Number\".\n;; In Clojure on Java, this value is never equal to itself, and any collections\n;; containing such \"values\" are never equal to any other collections, either:\n(= ##NaN ##NaN)\n;;=> false\n\n(= [1 2 3 ##NaN] [1 2 3 ##NaN])\n;;=> false\n\n;; There are a few other minor exceptions where clojure.core/= might behave in\n;; ways that surprise you. You can find an article describing the known cases\n;; for Clojure on Java here: https://clojure.org/guides/equality","author":{"avatar-url":"https://avatars3.githubusercontent.com/u/889685?v=4","account-source":"github","login":"huahaiy"},"created-at":1543389091657,"updated-at":1565641554721,"_id":"5bfe3fa3e4b0ca44402ef5cf"},{"updated-at":1645209415531,"created-at":1645209415531,"author":{"login":"mars0i","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1836941?v=4"},"body":";; You can test for a Java infinity, but there are quirks to know about. \n\n;; Note particularly that Double/POSITIVE_INFINITY and Float/POSITIVE_INFINITY\n;; are = and ==, but they are neither identical? nor .equals. However, the\n;; value these Java objects return has the same representation, ##Inf, in\n;; Clojure. Further, the literal ##Inf is parsed as something that is\n;; .equals to Double/POSITIVE_INFINITY but not identical? to it. Similar\n;; points hold for the Java NEGATIVE_INFINITY's and their Clojure\n;; representation, ##-Inf.\n\nuser=> Double/POSITIVE_INFINITY\n;;=> ##Inf\nuser=> Float/POSITIVE_INFINITY\n;;=> ##Inf\nuser=> (= Double/POSITIVE_INFINITY Float/POSITIVE_INFINITY)\n;;=> true\nuser=> (= ##Inf ##Inf)\n;;=> true\nuser=> (== Double/POSITIVE_INFINITY Float/POSITIVE_INFINITY)\n;;=> true\nuser=> (== ##Inf ##Inf)\n;;=> true\nuser=> (identical? Double/POSITIVE_INFINITY Float/POSITIVE_INFINITY)\n;;=> false\nuser=> (identical? ##Inf ##Inf)\n;;=> true\nuser=> (.equals Double/POSITIVE_INFINITY Float/POSITIVE_INFINITY)\n;;=> false\nuser=> (.equals ##Inf ##Inf)\n;;=> true\nuser=> (identical? ##Inf Double/POSITIVE_INFINITY)\n;;=> false\nuser=> (identical? ##Inf Float/POSITIVE_INFINITY)\n;;=> false\nuser=> (.equals ##Inf Double/POSITIVE_INFINITY)\n;;=> true\nuser=> (.equals ##Inf Float/POSITIVE_INFINITY)\n;;=> false\n\n;; (Tested with Clojure 1.10.3.)","_id":"620fe747e4b0b1e3652d75a8"},{"updated-at":1655019041411,"created-at":1655019041411,"author":{"login":"clojer","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/107184681?v=4"},"body":"user=> (= + +)\ntrue\nuser=> (= = =)\ntrue\nuser=> (= inc inc)\ntrue\nuser=> (= #() #())\nfalse","_id":"62a59621e4b0b1e3652d75fd"}],"notes":[{"updated-at":1287470783000,"body":"There is a difference between \"=\" and \"==\". For primitives you definitely want to use \"==\" as \"=\" will result in a cast to the wrapped types for it's arguments. \r\n\r\nThis may not be the case come Clojure 1.3 (see [1])\r\n\r\n[1] http://github.com/clojure/clojure/commit/df8c65a286e90e93972bb69392bc106128427dde","created-at":1287470783000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521f9b"},{"author":{"login":"domokato","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2388832?v=4"},"updated-at":1674772771853,"created-at":1674772771853,"body":"`=` compares collections in a type-independent manner but not numbers, despite what the docs say. See examples above.","_id":"63d30123e4b08cf8563f4b6c"}],"arglists":["x","x y","x y & more"],"doc":"Equality. Returns true if x equals y, false if not. Same as\n Java x.equals(y) except it also works for nil, and compares\n numbers and collections in a type-independent manner. Clojure's immutable data\n structures define equals() (and thus =) as a value, not an identity,\n comparison.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/="},{"added":"1.10","ns":"clojure.core","name":"read+string","file":"clojure/core.clj","type":"function","column":1,"see-alsos":null,"line":3796,"examples":[{"updated-at":1638567988480,"created-at":1638567988480,"author":{"login":"earthfail","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/21296448?v=4"},"body":";; read from *in*\n;; notice that whitespace is trimmed\nuser=> (read+string)\n :a\n[:a \":a\"]\nuser=> (read+string)\n 1234 56 7\n[1234 \"1234\"]\nuser=> (read+string)\n[56 \"56\"]\nuser=> (read+string)\n[7 \"7\"]\n\n;; if there is a comment it is included in the string read\nuser=> (read+string)\n;comment\n:value\n[:value \";comment\\n:value\"] ","_id":"61aa9034e4b0b1e3652d757f"}],"notes":null,"arglists":["","stream","stream eof-error? eof-value","stream eof-error? eof-value recursive?","opts stream"],"doc":"Like read, and taking the same args. stream must be a LineNumberingPushbackReader.\n Returns a vector containing the object read and the (whitespace-trimmed) string read.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/read+string"},{"added":"1.0","ns":"clojure.core","name":"dosync","file":"clojure/core.clj","type":"macro","column":1,"see-alsos":[{"created-at":1285922303000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"sync","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cdf"},{"created-at":1326521625000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"ref","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ce0"},{"created-at":1343102755000,"author":{"login":"TimMc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5d532e51427ef2f4ded31aaca16c8baf?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"locking","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ce1"}],"line":5129,"examples":[{"author":{"login":"devijvers","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/81018e4231ac1ce8b7a9e6d377092656?r=PG&default=identicon"},"editors":[{"login":"devijvers","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/81018e4231ac1ce8b7a9e6d377092656?r=PG&default=identicon"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":";; Keep dosync body free of side-effects:\n(defn my-thread-unsafe-fn [important-ref]\n (let [start-work (ref false)]\n (dosync\n (when (not @important-ref)\n ;\"If a conflict occurs between 2 transactions \n ;trying to modify the same reference, \n ;one of them will be retried.\"\n ;http://clojure.org/concurrent_programming\n (ref-set important-ref true)\n (ref-set start-work true)))\n (when @start-work \n ;launch side-effects here\n )))\n","created-at":1279380650000,"updated-at":1285500150000,"_id":"542692c7c026201cdc32698d"},{"body":";; Create 2 bank accounts\n(def acc1 (ref 100))\n(def acc2 (ref 200))\n\n;; How much money is there?\n(println @acc1 @acc2)\n;; => 100 200\n\n;; Either both accounts will be changed or none\n(defn transfer-money [a1 a2 amount]\n (dosync\n (alter a1 - amount)\n (alter a2 + amount)\n amount)) ; return amount from dosync block and function (just for fun)\n\n;; Now transfer $20\n(transfer-money acc1 acc2 20)\n;; => 20\n\n;; Check account balances again\n(println @acc1 @acc2)\n;; => 80 220\n\n;; => We can see that transfer was successful","author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"created-at":1423044726004,"updated-at":1423044726004,"_id":"54d1f076e4b081e022073c5b"}],"macro":true,"notes":null,"arglists":["& exprs"],"doc":"Runs the exprs (in an implicit do) in a transaction that encompasses\n exprs and any nested calls. Starts a transaction if none is already\n running on this thread. Any uncaught exception will abort the\n transaction and flow out of dosync. The exprs may be run more than\n once, but any effects on Refs will be atomic.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/dosync"},{"added":"1.0","ns":"clojure.core","name":"remove-ns","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1284970244000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"create-ns","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b5c"},{"created-at":1284970256000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"find-ns","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b5d"}],"line":4166,"examples":[{"author":{"login":"belun","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8d3c423e74750fa42c0386833e4b8209?r=PG&default=identicon"},"editors":[{"login":"belun","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8d3c423e74750fa42c0386833e4b8209?r=PG&default=identicon"},{"login":"belun","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8d3c423e74750fa42c0386833e4b8209?r=PG&default=identicon"},{"login":"belun","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8d3c423e74750fa42c0386833e4b8209?r=PG&default=identicon"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"sillitor","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/c6e7b175eb48c8e3db32f3ff7c2a205d?r=PG&default=identicon"}],"body":";; Let's create a namespace and then remove it\n\nuser=> (create-ns 'my-new-namespace)\n#\n\n;; removing a namespace will give you the namespace you just deleted, if one existed\nuser=> (remove-ns 'my-new-namespace)\n#\n\n;; removing a namespace that does not exist, will tell you that nothing was removed, \n;; by returning nil, and won't give any errors\nuser=> (remove-ns 'my-new-namespace)\nnil\n","created-at":1284948400000,"updated-at":1375854900000,"_id":"542692c9c026201cdc326a90"},{"updated-at":1546107636355,"created-at":1546107636355,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"body":";; Unlikely you'll ever want to use \"remove-ns\" unless you know what you're\n;; doing. Prefer libs like tools.namespace whenever possible. For example,\n;; here we are preventing garbage collecting the namespace and getting a\n;; stale read.\n\n(create-ns 'go-away)\n(intern 'go-away 'my-var 0)\n(refer 'go-away :only ['my-var])\n(remove-ns 'go-away)\n\n;; nope, still here:\n(.ns #'my-var)\n;; #object[clojure.lang.Namespace 0x1f658731 \"go-away\"]\n\n;; replace\n(create-ns 'go-away)\n(intern 'go-away 'my-var 1)\n\n;; stale\nmy-var\n;; 0\n\n;; correct\n@#'go-away/my-var\n;; 1","_id":"5c27baf4e4b0ca44402ef607"}],"notes":null,"arglists":["sym"],"doc":"Removes the namespace named by the symbol. Use with caution.\n Cannot be used to remove the clojure namespace.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/remove-ns"},{"added":"1.0","ns":"clojure.core","name":"take","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1288872407000,"author":{"login":"jartur","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8eae7b45fd8d383bc1a49e24bee51c9b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"drop","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521db2"},{"created-at":1288872422000,"author":{"login":"jartur","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8eae7b45fd8d383bc1a49e24bee51c9b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"take-while","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521db3"},{"created-at":1288872427000,"author":{"login":"jartur","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8eae7b45fd8d383bc1a49e24bee51c9b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"take-last","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521db4"},{"created-at":1288872434000,"author":{"login":"jartur","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8eae7b45fd8d383bc1a49e24bee51c9b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"take-nth","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521db5"}],"line":2878,"examples":[{"author":{"login":"jandot","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/90df4ddea707147ac2ac11383108d700?r=PG&default=identicon"},"editors":[{"login":"jandot","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/90df4ddea707147ac2ac11383108d700?r=PG&default=identicon"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"login":"jszakmeister","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/69ad2af1f028b1b7e76c14f83bdf26cb?r=PG&default=identicon"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"},{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"}],"body":";; return a lazy seq of the first 3 items\n(take 3 '(1 2 3 4 5 6))\n;;=> (1 2 3)\n\n(take 3 [1 2 3 4 5 6])\n;;=> (1 2 3)\n\n;; returns all items if there are fewer than n\n(take 3 [1 2])\n;;=> (1 2)\n\n(take 1 [])\n;;=> ()\n\n(take 1 nil)\n;;=> ()\n\n(take 0 [1])\n;;=> ()\n\n(take -1 [1])\n;;=> ()","created-at":1278905054000,"updated-at":1423278637171,"_id":"542692cec026201cdc326de8"},{"author":{"login":"citizen428","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/b3881a28fe402dd2d1de44717486cae8?r=PG&default=identicon"},"editors":[{"login":"citizen428","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/b3881a28fe402dd2d1de44717486cae8?r=PG&default=identicon"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":";; similar to subvec but lazy and with seqs\n(take 3 (drop 5 (range 1 11)))\n;;=> (6 7 8)","created-at":1280469743000,"updated-at":1420736101515,"_id":"542692cec026201cdc326ded"},{"updated-at":1435879568191,"created-at":1435879568191,"author":{"login":"bsvingen","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1647562?v=3"},"body":";; Used without a collection, take will create a transducer:\n(def xf (take 5))\n\n;; We can now apply this transducer to a sequence:\n(transduce xf conj (range 5))\n;; => [0 1 2 3 4]\n","_id":"5595c890e4b00f9508fd66f3"},{"editors":[{"login":"cljlc","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/36645452?v=4"}],"body":";; Note that usually more items are realized than needed.\n;; In the example below we want a lazy sequence of 1 item\n;; (the first item of the range), but actually the first 32 items are calculated.\n;; This can be especially important when this extra realization requires a lot of\n;; resources (CPU, time, memory, etc.) and at the end not needed at all.\n;; Tip: try 32 and 33 instead of 1 in the take below.\n\nuser=> (let [x (map (fn [i]\n (println i)\n (Thread/sleep 100)\n i)\n (range 50))]\n (take 1 x))\n0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\n17\n18\n19\n20\n21\n22\n23\n24\n25\n26\n27\n28\n29\n30\n31\n(0)\n\n;; Another interesting case (especially for debugging) when\n;; an exception is thrown during this extra realization.\n\nuser=> (let [x (map (fn [i]\n (when (> i 40)\n (throw (Exception. (str i \" is not accepted!\")))))\n (range 50))]\n (take 33 x))\n\n;; result: Exception 41 is not accepted!\n\n;; When pmap is used instead of map, then not only one, but many exceptions might\n;; be thrown during this extra realization. However, all of them are \"swallowed\"\n;; by pmap: they are thrown inside, but never get out:\n\nuser=> (let [x (pmap (fn [i]\n (when (> i 40)\n (println \"Exception is thrown...\")\n (throw (Exception. (str i \" is not accepted!\")))))\n (range 50))]\n (take 33 x))\n(nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil\nException is thrown...Exception is thrown...\n\nException is thrown...Exception is thrown...\n\nException is thrown...\nException is thrown...\nnil nil nil nil nil nil nil nil nil nil nil nil)\nException is thrown...\nException is thrown...Exception is thrown...\n;; Note: the REPL sees no exception!\n\n;; \"Normal\" exceptions arrive as expected:\nuser=> (let [x (pmap (fn [i]\n (when (> i 40)\n (println \"Exception is thrown...\" i)\n (throw (Exception. (str i \" is not accepted!\")))))\n (range 50))]\n (take 42 x))\n(nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil\nException is thrown... Exception is thrown...Exception is thrown... 42\n44Exception is thrown...Exception is thrown... 46 \nnilException is thrown... Exception is thrown...47 45\nException is thrown... 49\n43\n\n\n 48nil nil \nnil nil nil nil Exception is thrown...nil nil 41nil nil \nnil Exception 41 is not accepted! user/eval9941/fn--9942 (NO_SOURCE_FILE:337)\nnil nil nil nil nil nil\n;; We can see above, that several exceptions are thrown, but only the one for i=41\n;; arrives to the REPL.\n","author":{"avatar-url":"https://avatars0.githubusercontent.com/u/36645452?v=4","account-source":"github","login":"cljlc"},"created-at":1538951205102,"updated-at":1539004143896,"_id":"5bba8825e4b00ac801ed9eac"}],"notes":null,"arglists":["n","n coll"],"doc":"Returns a lazy sequence of the first n items in coll, or all items if\n there are fewer than n. Returns a stateful transducer when\n no collection is provided.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/take"},{"added":"1.0","ns":"clojure.core","name":"vector?","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1414508335557,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"},"to-var":{"ns":"clojure.core","name":"set?","library-url":"https://github.com/clojure/clojure"},"_id":"544faf2fe4b03d20a1024280"},{"created-at":1414508362039,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"},"to-var":{"ns":"clojure.core","name":"vec","library-url":"https://github.com/clojure/clojure"},"_id":"544faf4ae4b03d20a1024281"},{"created-at":1414508375671,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"},"to-var":{"ns":"clojure.core","name":"map?","library-url":"https://github.com/clojure/clojure"},"_id":"544faf57e4b03d20a1024282"},{"created-at":1414508715616,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"},"to-var":{"ns":"clojure.core","name":"list?","library-url":"https://github.com/clojure/clojure"},"_id":"544fb0abe4b03d20a1024285"},{"created-at":1420231002263,"author":{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=3"},"to-var":{"ns":"clojure.core","name":"sequential?","library-url":"https://github.com/clojure/clojure"},"_id":"54a7015ae4b09260f767ca84"}],"line":176,"examples":[{"author":{"login":"dpritchett","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/147981?v=3"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"},{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"}],"body":";; this is the idiomatic vector \n(vector? [1 2 3])\n;;=> true\n\n;; a list is not a vector\n(vector? '(1 2 3))\n;;=> false\n\n;; a list may be converted into a vector\n(vector? (vec '(1 2 3)))\n;;=> true\n\n;; a map is not a vector\n(vector? {:a 1 :b 2 :c 3})\n;;=> false\n\n;; a set is not a vector\n(vector? #{:a :b :c})\n;;=> false\n\n(first {:a 1 :b 2 :c 3})\n;;=> [:c 3]\n(vector? (first {:a 1 :b 2 :c 3}))\n;;=> true","created-at":1279075424000,"updated-at":1423523910620,"_id":"542692c9c026201cdc326af5"},{"updated-at":1518959452052,"created-at":1518959452052,"author":{"login":"humorless","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/3061798?v=4"},"body":";; an quoted vector is still a vector\n(vector? '[])\n;;=> true","_id":"5a897b5ce4b0316c0f44f8cb"},{"updated-at":1660931660559,"created-at":1660931660559,"author":{"login":"KGOH","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/11963737?v=4"},"body":";; Be careful while traversing data:\n;; map entries are vectors!\n\nuser=> (vector? (first {:a 1}))\ntrue\n\nuser=> (vector? (clojure.lang.MapEntry. :a 1))\ntrue\n\nuser=> (clojure.walk/postwalk\n #(cond-> % (vector? %) set)\n {:a [1 1 2 3]})\n; Unhandled java.lang.ClassCastException\n; class clojure.lang.PersistentHashSet cannot be cast to class\n; java.util.Map$Entry (clojure.lang.PersistentHashSet is in unnamed module of\n; loader 'app'; java.util.Map$Entry is in module java.base of loader\n; 'bootstrap')\n\nuser=> (clojure.walk/postwalk\n #(cond-> %\n (and (vector? %)\n (not (map-entry? %)))\n set)\n {:a [1 1 2 3]})\n{:a #{1 3 2}}","_id":"62ffce4ce4b0b1e3652d7640"}],"notes":null,"arglists":["x"],"doc":"Return true if x implements IPersistentVector","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/vector_q"},{"added":"1.11","ns":"clojure.core","name":"seq-to-map-for-destructuring","file":"clojure/core.clj","type":"function","column":1,"see-alsos":null,"line":4417,"examples":[{"updated-at":1727613608037,"created-at":1727613608037,"author":{"login":"conao3","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/4703128?v=4"},"body":"(seq-to-map-for-destructuring [:a 1 :b 2])\n;;=> {:a 1, :b 2}\n\n(seq-to-map-for-destructuring [:a 1 :b 2 {:a 99 :c 3}])\n;;=> {:a 99, :b 2, :c 3}\n","_id":"66f94aa869fbcc0c226174fb"}],"notes":null,"arglists":["s"],"doc":"Builds a map from a seq as described in\n https://clojure.org/reference/special_forms#keyword-arguments","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/seq-to-map-for-destructuring"},{"added":"1.12","ns":"clojure.core","name":"stream-transduce!","file":"clojure/core.clj","type":"function","column":1,"see-alsos":null,"line":6877,"examples":null,"notes":null,"arglists":["xform f stream","xform f init stream"],"doc":"Works like transduce but takes a java.util.stream.BaseStream as its source.\n This is a terminal operation on the stream.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/stream-transduce!"},{"added":"1.2","ns":"clojure.core","name":"thread-bound?","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1350609443000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"bound-fn","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ec5"},{"created-at":1350609447000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"bound-fn*","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ec6"}],"line":5573,"examples":[{"body":"user=> (thread-bound? #'map)\nfalse\n\nuser=> (thread-bound? #'*warn-on-reflection*)\ntrue","author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"created-at":1423279051775,"updated-at":1423279051775,"_id":"54d583cbe4b081e022073c6d"}],"notes":null,"arglists":["& vars"],"doc":"Returns true if all of the vars provided as arguments have thread-local bindings.\n Implies that set!'ing the provided vars will succeed. Returns true if no vars are provided.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/thread-bound_q"},{"added":"1.5","ns":"clojure.core","name":"send-via","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1553627520247,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"send","ns":"clojure.core"},"_id":"5c9a7980e4b0ca44402ef6d1"},{"created-at":1553627525447,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"send-off","ns":"clojure.core"},"_id":"5c9a7985e4b0ca44402ef6d2"}],"line":2118,"examples":[{"editors":[{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"}],"body":";; \"send\" (FixedThreadPool) or \"send-off\" (CachedThreadPool) \n;; covers most of the thread pooling strategies.\n;; But in case you want a different one, use \"send-via\" to pass\n;; a different pool, for example ForkJoin.\n\n(import '[java.util.concurrent Executors])\n(def fj-pool (Executors/newWorkStealingPool))\n\n(defn send-fj [^clojure.lang.Agent a f & args]\n (apply send-via fj-pool a f args))\n\n(def a (agent 1))\n(send-fj a inc)\n(await a)\n@a\n;; 2","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"},"created-at":1553627490834,"updated-at":1553627508594,"_id":"5c9a7962e4b0ca44402ef6cf"}],"notes":null,"arglists":["executor a f & args"],"doc":"Dispatch an action to an agent. Returns the agent immediately.\n Subsequently, in a thread supplied by executor, the state of the agent\n will be set to the value of:\n\n (apply action-fn state-of-agent args)","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/send-via"},{"added":"1.0","ns":"clojure.core","name":"boolean","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1525123909893,"author":{"login":"zk","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/7194?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"boolean?","ns":"clojure.core"},"_id":"5ae78b45e4b045c27b7fac5a"},{"created-at":1734339384669,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"parse-boolean","ns":"clojure.core"},"_id":"675feb3869fbcc0c22617529"}],"line":1620,"examples":[{"updated-at":1445064419614,"created-at":1279063882000,"body":";; Everything except `false' and `nil' is true in boolean context.\nuser=> (into {} (map #(vector % (boolean %)) [true false nil [] {} '() #{} \"\"]))\n{true true, false false, nil false, [] true, {} true, #{} true, \"\" true}\n\nuser=> (clojure.pprint/pp)\n{true true,\n false false,\n nil false,\n [] true,\n {} true,\n #{} true,\n \"\" true}\nnil\n\n;; Unrelated to `boolean`, but notice that the `'()` entry is missing. This\n;; due to Clojure treating `[]` and `'()` as equal. When combined into the map \n;; the `'() => true` key-value pair is overwritten by the `[] => true` key-value\n;; pair. See https://github.com/zk/clojuredocs/issues/114#issuecomment-132153637\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/142529?v=3","account-source":"github","login":"nipra"},"_id":"542692c9c026201cdc326ad4"},{"body":";; Beware that boolean returns true for numbers 0 and 1\nuser=> (boolean 0)\ntrue\nuser=> (boolean 1)\ntrue","author":{"login":"nickzam","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/89377?v=3"},"created-at":1425054691862,"updated-at":1425054691862,"_id":"54f09be3e4b0b716de7a652d"},{"editors":[{"login":"Jarzka","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/5528061?v=3"}],"body":";; Simply defined: Everything except false and nil is logically true in Clojure.","author":{"avatar-url":"https://avatars.githubusercontent.com/u/5528061?v=3","account-source":"github","login":"Jarzka"},"created-at":1475227100143,"updated-at":1475227191121,"_id":"57ee2ddce4b0709b524f0510"},{"updated-at":1496248789165,"created-at":1496248789165,"author":{"login":"dottedmag","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/16120?v=3"},"body":";; Corrected definition:\n;; returns `false' for `false', `nil' and `(Boolean. false)`.\n;; returns `true' for everything else.\n","_id":"592ef1d5e4b06e730307db16"}],"notes":null,"arglists":["x"],"doc":"Coerce to boolean","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/boolean"},{"added":"1.0","ns":"clojure.core","name":"bit-shift-left","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1405720522000,"author":{"login":"phreed","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3a0c739cf289be18be932dc3022e6fd3?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"bit-shift-left","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d80"},{"created-at":1412094597343,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=2"},"to-var":{"ns":"clojure.core","name":"unsigned-bit-shift-right","library-url":"https://github.com/clojure/clojure"},"_id":"542ada85e4b0df9bb778a5a1"},{"created-at":1412094642694,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=2"},"to-var":{"ns":"clojure.core","name":"bit-shift-right","library-url":"https://github.com/clojure/clojure"},"_id":"542adab2e4b0df9bb778a5a2"}],"line":1370,"examples":[{"updated-at":1717403308837,"created-at":1280339401000,"body":"user=> (bit-shift-left 1 10)\n1024\n\nuser=> (bit-shift-left 2r1101 2) ; fill rightmost bits with 0s\n52 \n;; 52 = 2r110100","editors":[{"avatar-url":"https://www.gravatar.com/avatar/c0c2f195479ae4a71cb6484679f6f49?r=PG&default=identicon","account-source":"clojuredocs","login":"tomas"},{"avatar-url":"https://www.gravatar.com/avatar/c0c2f195479ae4a71cb6484679f6f49?r=PG&default=identicon","account-source":"clojuredocs","login":"tomas"},{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/68dd6f50915854aa04fefcf4d6fa5c8e?r=PG&default=identicon","account-source":"clojuredocs","login":"zmila"},"_id":"542692ccc026201cdc326cc2"},{"author":{"login":"Claj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5fd658a8d2ef549071cb5286b1b874aa?r=PG&default=identicon"},"editors":[{"login":"Claj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5fd658a8d2ef549071cb5286b1b874aa?r=PG&default=identicon"}],"body":";;a bogus bit-array implementation\n\n(def ba (atom (long 0)))\n\n(defn set-ba \n\"sets bit n in long atom ba\"\n [n]\n (let [number-set (bit-shift-left 1 n)\n\t_ (println \"number to set: \" number-set)\n\tnew-array (bit-or @ba number-set)]\n (reset! ba new-array)))\n\n(defn get-ba \n\"gets bit n in long atom ba\"\n[n]\n (not (zero? (bit-and (bit-shift-left 1 n) @ba))))\n\n(comment\n (set-ba 0) ;; 0 [....0001]\n (set-ba 3) ;; 2^3 = 8 [....1001]\n (get-ba 0) ;; (bit-and ba 2^0) = 1\n (get-ba 1) ;; (bit-and ba 2^1) = 0\n (get-ba 3) ;; (bit-and ba 2^3) = 1\n ;;but:\n (set-ba 65) ;; [....1011]\n ;;number to set: 2\n ;;modulo because long has only 64 bit\n ;;also note that long always is two-complemented (signed) in java implementation\n )","created-at":1334315926000,"updated-at":1334316062000,"_id":"542692d2c026201cdc326f59"}],"notes":null,"arglists":["x n"],"doc":"Bitwise shift left","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/bit-shift-left"},{"added":"1.11","ns":"clojure.core","name":"random-uuid","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1698255200980,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"uuid?","ns":"clojure.core"},"_id":"6539516069fbcc0c226173d8"},{"created-at":1698255208318,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"parse-uuid","ns":"clojure.core"},"_id":"6539516869fbcc0c226173d9"}],"line":6939,"examples":[{"updated-at":1698255187893,"created-at":1698255187893,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":"(dotimes [_ 10]\n (println (random-uuid)))\n#uuid \"66d96ab4-9834-40db-a3cd-42b361503ab9\"\n#uuid \"b555744b-ecfc-4a20-9b2a-84f2b533381e\"\n#uuid \"1435bf8a-4116-4688-97fe-a95f0f86c42d\"\n#uuid \"f2f909b7-97fd-42a3-81de-53bd2c4d5f63\"\n#uuid \"20e3fb86-1c61-4053-a4a4-4beea8163c12\"\n#uuid \"c882f060-87fe-4bd6-9821-f28637c24b7d\"\n#uuid \"1c53f839-e670-4c65-8744-00431ca7f7cc\"\n#uuid \"84609f30-9b70-40c3-a89f-5cf598de011a\"\n#uuid \"3d65a591-08bb-488e-9c31-af74048c31d3\"\n#uuid \"52b18528-bece-4a3b-93a1-9f131508e323\"\n\n;; Notice that the first digit in the 3rd block is always 4\n;; Notice that the first digit in the 4th block is always 8, 9, a, or b\n","_id":"6539515369fbcc0c226173d7"}],"notes":null,"arglists":[""],"doc":"Returns a pseudo-randomly generated java.util.UUID instance (i.e. type 4).\n\n See: https://docs.oracle.com/javase/8/docs/api/java/util/UUID.html#randomUUID--","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/random-uuid"},{"added":"1.9","ns":"clojure.core","name":"any?","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1505768957277,"author":{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/94482?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"constantly","ns":"clojure.core"},"_id":"59c035fde4b09f63b945ac78"},{"created-at":1509371215117,"author":{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"some?","ns":"clojure.core"},"_id":"59f72d4fe4b0a08026c48c8b"},{"created-at":1732104697985,"author":{"login":"iGEL","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/36442?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"some","ns":"clojure.core"},"_id":"673dd1f969fbcc0c2261751b"}],"line":540,"examples":[{"updated-at":1525874416827,"created-at":1525874416827,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"},"body":";; All known practical uses are in the context of core.spec\n;; Specifically indicates that any type is allowed.\n\n;; https://clojure.org/guides/spec#_macros\n(s/fdef clojure.core/declare\n :args (s/cat :names (s/* simple-symbol?))\n :ret any?)\n","_id":"5af2fef0e4b045c27b7fac5e"},{"updated-at":1598160436994,"created-at":1598160436994,"author":{"login":"berczeck","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/1321842?v=4"},"body":";; any? never returns false\n\nuser=> (any? {})\n;; true\nuser=> (any? [])\n;; true\nuser=> (any? nil)\n;; true\nuser=> (any? true)\n;; true\nuser=> (any? false)\n;; true","_id":"5f41fe34e4b0b1e3652d739b"},{"updated-at":1667213535374,"created-at":1667213535374,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":";; Combined with `halt-when` to make a \"first\" transducer\n(transduce (comp (filter even?) (halt-when any?)) identity nil [1 3 5 6 7 8 9])\n;; => 6\n","_id":"635fa8dfe4b0b1e3652d767e"}],"notes":[{"author":{"login":"kofrasa","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/941969?v=4"},"updated-at":1537520319116,"created-at":1537520319116,"body":"The current implementation of [any?](https://github.com/clojure/clojure/blob/clojure-1.9.0/src/clj/clojure/core.clj#L538-L542) is incorrect and must be fixed IMO.\nThere was a [PR](https://github.com/clojure/clojure/pull/49) (copied below) submitted in 2014 to add a correct implementation which is consistent with behaviour in other languages. \n\n```\n(def\n ^{:tag Boolean\n :doc \"Returns true if (pred x) is logical true for any x in coll,\n else false.\"\n :arglists '([pred coll])\n :added \"1.7\"}\n any? (comp boolean some))\n```","_id":"5ba4b2bfe4b00ac801ed9ea2"},{"author":{"login":"berczeck","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/1321842?v=4"},"updated-at":1598160591335,"created-at":1598160591335,"body":"any? never returns false. Is this a bug?","_id":"5f41fecfe4b0b1e3652d739c"},{"author":{"login":"KyleErhabor","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/40676441?v=4"},"updated-at":1635468134571,"created-at":1635468134571,"body":"You can think of this function as a non-variadic `(constantly true)`.","_id":"617b4366e4b0b1e3652d7561"},{"body":"[Explanation by Alex Miller:](https://ask.clojure.org/index.php/11260/does-the-any-function-have-the-correct-behavior?show=11261#a11261)\n\n> \n`any?` is a predicate that is intended to always return true, so yes it is the correct behavior. `any?` was added as a predicate to use with spec in the case where any value is valid. It is not a complement to `not-any?`, despite that obvious assumption. There are, in the end, only so many words and despite a lot of care in this regard, there are times when these confusions exist.\n\n> ...this is similar to `and` (for N args) but that does have limits as a macro, or `every?` (for a coll), or the higher-order function `every-pred` for creating a composite pred. Depending on your case, one of those probably makes sense.","created-at":1636499571628,"updated-at":1636499796804,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/77174844?v=4","account-source":"github","login":"wildwestrom"},"_id":"618b0073e4b0b1e3652d7569"}],"tag":"java.lang.Boolean","arglists":["x"],"doc":"Returns true given any argument.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/any_q"},{"added":"1.0","ns":"clojure.core","name":"find-var","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":null,"line":2032,"examples":[{"author":{"login":"franks42","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/b3ee701dd6c481e5d310467ddfe62c48?r=PG&default=identicon"},"editors":[{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"}],"body":"user=> (find-var 'clojure.core/map)\n#'clojure.core/map\nuser=> (find-var 'clojure.core/qwerty)\nnil\nuser=> (find-var 'map)\nIllegalArgumentException Symbol must be namespace-qualified clojure.lang.Var.find (Var.java:150)\n","created-at":1353813768000,"updated-at":1422932885283,"_id":"542692d3c026201cdc326fa5"}],"notes":[{"author":{"login":"kumarshantanu","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/109792?v=4"},"updated-at":1520862872705,"created-at":1520862872705,"body":"For namespaces other than those in Clojure, you must do `(require 'the-ns)` first, followed by `(find-var 'the-ns/the-name)`. Failing to do this leads to `IllegalArgumentException` thrown complaining about no such namespace.","_id":"5aa68698e4b0316c0f44f921"}],"arglists":["sym"],"doc":"Returns the global var named by the namespace-qualified symbol, or\n nil if no var with that name.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/find-var"},{"added":"1.0","ns":"clojure.core","name":"rand-int","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1311342554000,"author":{"login":"Havvy","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e799a79441c7543be48562403411cd13?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"rand","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b5a"},{"created-at":1343068893000,"author":{"login":"john.r.woodward","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/22b6fbc4a386291e45b1cb4449377086?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"int","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b5b"}],"line":4972,"examples":[{"author":{"login":"devn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"john.r.woodward","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/22b6fbc4a386291e45b1cb4449377086?r=PG&default=identicon"},{"login":"green-coder","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/598193?v=4"}],"body":"user=> (rand-int 30)\n10\n\nuser=> (rand-int 30)\n7\n\n; is equivalent to\nuser=> (int (rand 30))\n","created-at":1280776684000,"updated-at":1527060379971,"_id":"542692cac026201cdc326b17"},{"body":"(require '[clojure.set :as set])\n\n; random generation of unique series of random numbers from 0 to n-1 \n\n(defn unique-random-numbers [n]\n (let [a-set (set (take n (repeatedly #(rand-int n))))]\n (concat a-set (set/difference (set (take n (range)))\n a-set))))\n\nuser=> (unique-random-numbers 20)\n(0 1 3 6 7 8 9 12 14 16 17 19 2 4 5 10 11 13 15 18)\n\n","author":{"login":"rsachdeva","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/232903?v=2"},"created-at":1412614831110,"updated-at":1412617449373,"editors":[{"login":"rsachdeva","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/232903?v=2"}],"_id":"5432caafe4b0edc37b198867"},{"editors":[{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"}],"body":";; It'll allow you to supply an arg > Integer/MAX_VALUE, but the incidence of\n;; integer overflow is proportional to how far you go over…\n(dotimes [n 10]\n (try (println (rand-int (* Integer/MAX_VALUE 2.0)))\n (catch ArithmeticException _ (println \"A\"))))\nA\nA\n1854263459\n83487894\n629497223\nA\n1311192557\nA\nA\n2112963130\n\n;; The docstring uses the word \"integer\" to mean a Java integer, rather than a\n;; math integer, confusingly unlike `integer?`\n\n;; If you want to extend into the full Long range, repimplement like so…\n(defn rand-long [n] (long (rand n)))\n\n(dotimes [n 10]\n (try (println (rand-long (* Integer/MAX_VALUE 2.0)))\n (catch ArithmeticException _ (println \"A\"))))\n2843734446\n3705237344\n2260635666\n1353888982\n2353595107\n1511365943\n2605201990\n2533357711\n2501246267\n1330427847","author":{"avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4","account-source":"github","login":"tomdl89"},"created-at":1699633453215,"updated-at":1699643605959,"_id":"654e592d69fbcc0c22617445"}],"notes":null,"arglists":["n"],"doc":"Returns a random integer between 0 (inclusive) and n (exclusive).","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/rand-int"},{"added":"1.0","ns":"clojure.core","name":"aclone","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1359687987000,"author":{"login":"mmwaikar","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/29d36f4c9f39c9f8ff61c07033b13118?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"aget","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d98"},{"created-at":1454082909781,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"int-array","ns":"clojure.core"},"_id":"56ab8b5de4b0ceed88ce8d1d"}],"line":3931,"examples":[{"author":{"login":"shockbob","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon"},"editors":[{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"}],"body":";; create an Java integer array, then clone it\n;; note that when you modify b, a remains the same\n;; showing that b is not just a reference to a\nuser=> (def a (int-array [1 2 3 4]))\n#'user/a\n\nuser=> (def b (aclone a))\n#'user/b\n\nuser=> (aset b 0 23)\n23\n\nuser=> (vec b)\n[23 2 3 4]\n\nuser=> (vec a)\n[1 2 3 4]","created-at":1313834307000,"updated-at":1422928355436,"_id":"542692cec026201cdc326db4"}],"notes":null,"arglists":["array"],"doc":"Returns a clone of the Java array. Works on arrays of known\n types.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/aclone"},{"added":"1.10","ns":"clojure.core","name":"PrintWriter-on","file":"clojure/core_print.clj","type":"function","column":1,"see-alsos":null,"line":561,"examples":[{"updated-at":1589185851017,"created-at":1589185851017,"author":{"login":"pwojnowski","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/433664?v=4"},"body":"(with-open [writer (PrintWriter-on\n (fn [s] (printf \"Flushing: '%s'%n\" s))\n (fn [] (printf \"Closing.%n\")))]\n (.write writer \"Hello\")\n (.flush writer)\n (.write writer \"World!\")\n (println \"About to finish...\"))\n;; Flushing: 'Hello'\n;; About to finish...\n;; Flushing: 'World!'\n;; Closing.\n;; nil\n","_id":"5eb90d3be4b087629b5a190a"}],"notes":null,"tag":"java.io.PrintWriter","arglists":["flush-fn close-fn","flush-fn close-fn autoflush?"],"doc":"implements java.io.PrintWriter given flush-fn, which will be called\n when .flush() is called, with a string built up since the last call to .flush().\n if not nil, close-fn will be called with no arguments when .close is called.\n autoflush? determines if the PrintWriter will autoflush, false by default.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/PrintWriter-on"},{"added":"1.7","ns":"clojure.core","name":"vreset!","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1469617409269,"author":{"login":"kumarshantanu","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109792?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"volatile!","ns":"clojure.core"},"_id":"57989501e4b0bafd3e2a04c0"}],"line":2549,"examples":[{"editors":[{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"}],"body":";; A lightweight (but low level) syncrhonization solution with volatile!\n;; Prefer promise/deliver for this (unless you know what you're doing).\n;; vars/atoms is also possible but they're heavier\n;; (locking and CAS respectively).\n\n(def ready (volatile! false))\n(def result (volatile! nil))\n\n(defn start-consumer []\n (future\n (while (not @ready) ; consumer starts spinning\n (Thread/yield)) ; release control for other threads\n (println \"Consumer getting result:\" @result)))\n\n(defn start-producer []\n (future\n (vreset! result :done) ; change the 1st volatile, no reordering (guaranteed).\n (vreset! ready true))) ; change the ready state. \n\n(start-consumer)\n(start-producer)\n;; Consumer getting result: :done","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"},"created-at":1554052433589,"updated-at":1554114281037,"_id":"5ca0f551e4b0ca44402ef6f3"}],"notes":null,"arglists":["vol newval"],"doc":"Sets the value of volatile to newval without regard for the\n current value. Returns newval.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/vreset!"},{"ns":"clojure.core","name":"chunk","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1443935937870,"author":{"login":"devn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"chunk-buffer","ns":"clojure.core"},"_id":"5610b6c1e4b0686557fcbd48"},{"created-at":1443935945637,"author":{"login":"devn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"chunk-cons","ns":"clojure.core"},"_id":"5610b6c9e4b08e404b6c1c9a"},{"created-at":1443935949789,"author":{"login":"devn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"chunk-first","ns":"clojure.core"},"_id":"5610b6cde4b0686557fcbd49"},{"created-at":1443935953838,"author":{"login":"devn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"chunk-rest","ns":"clojure.core"},"_id":"5610b6d1e4b0686557fcbd4a"},{"created-at":1443935959010,"author":{"login":"devn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"chunked-seq?","ns":"clojure.core"},"_id":"5610b6d7e4b0686557fcbd4b"}],"line":700,"examples":[{"updated-at":1443936068915,"created-at":1443936068915,"author":{"login":"devn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3"},"body":"(chunk-rest\n (chunk-cons (chunk (chunk-buffer 32))\n (seq (range 42))))\n\n;; => (32 33 34 35 36 37 38 39 40 41)\n\n;; Or if you'd prefer to read it threaded:\n(-> (chunk-buffer 32)\n (chunk)\n (chunk-cons (seq (range 42)))\n (chunk-rest))\n\n;; => (32 33 34 35 36 37 38 39 40 41)","_id":"5610b744e4b0686557fcbd4c"},{"editors":[{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"}],"body":";; re-chunk takes a sequence (already chunked or not)\n;; and produces another sequence with different chunking size.\n\n(defn re-chunk [n xs]\n (lazy-seq\n (when-let [s (seq (take n xs))]\n (let [cb (chunk-buffer n)]\n (doseq [x s] (chunk-append cb x))\n (chunk-cons (chunk cb) (re-chunk n (drop n xs)))))))\n\n(def s (pmap f (re-chunk 1000 (range 1000)))) ; a 1000+ concurrent threads pmap\n\n(def s (map #(println %) (re-chunk 3 (range 50)))) ; chunk-size = 3\n\n(first s) ; moves ahead 3 on first access\n;; 0\n;; 1\n;; 2\n\n(second s) ; already cached\nnil\n\n(first (drop 3 s)) ; 3 more\n;; 3\n;; 4\n;; 5\n","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"},"created-at":1553787843289,"updated-at":1553805164827,"_id":"5c9cebc3e4b0ca44402ef6ec"}],"notes":null,"tag":"clojure.lang.IChunk","arglists":["b"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core/chunk"},{"added":"1.2","ns":"clojure.core","name":"dec","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1318548547000,"author":{"login":"arkh","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1c6ed9b963d758914c2744befd4974ca?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"dec'","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b3e"},{"created-at":1415177846727,"author":{"login":"rvlieshout","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/139665?v=2"},"to-var":{"ns":"clojure.core","name":"inc","library-url":"https://github.com/clojure/clojure"},"_id":"5459e676e4b03d20a102429e"},{"created-at":1423522396091,"author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"to-var":{"ns":"clojure.core","name":"unchecked-dec","library-url":"https://github.com/clojure/clojure"},"_id":"54d93a5ce4b0e2ac61831d30"}],"line":1156,"examples":[{"author":{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":"user=> (dec 2)\n1\n\nuser=> (dec 2.0)\n1.0\n\nuser=> (dec 1)\n0\n\nuser=> (dec -1)\n-2","created-at":1279992356000,"updated-at":1411919526590,"_id":"542692cec026201cdc326d98"}],"notes":null,"arglists":["x"],"doc":"Returns a number one less than num. Does not auto-promote\n longs, will throw on overflow. See also: dec'","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/dec"},{"added":"1.1","ns":"clojure.core","name":"future-call","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1300437112000,"author":{"login":"ninjudd","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/7ced25585a7556e9b9b975c1f9e136e3?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"future","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f43"}],"line":7110,"examples":[{"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"editors":[],"body":";; future-call is used to implement 'future'. See examples for 'future'\n;; for discussion of an undesirable 1-minute wait that can occur before\n;; your standalone Clojure program exits if you do not use shutdown-agents.","created-at":1336538018000,"updated-at":1336538018000,"_id":"542692d3c026201cdc326fb2"}],"notes":[{"author":{"login":"guyboltonking","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/98294?v=4"},"updated-at":1524654131544,"created-at":1524654131544,"body":"`future-call` will also preserve the calling thread's dynamic bindings in the thread that executes f.","_id":"5ae06033e4b045c27b7fac52"}],"arglists":["f"],"doc":"Takes a function of no args and yields a future object that will\n invoke the function in another thread, and will cache the result and\n return it on all subsequent calls to deref/@. If the computation has\n not yet finished, calls to deref/@ will block, unless the variant\n of deref with timeout is used. See also - realized?.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/future-call"},{"added":"1.0","ns":"clojure.core","name":"resultset-seq","file":"clojure/core.clj","type":"function","column":1,"see-alsos":null,"line":5755,"examples":[{"updated-at":1519728015058,"created-at":1519728015058,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"body":";; To run this you need [mysql/mysql-connector-java \"5.1.x\"] dependency \n;; in the classpath and a running MySql instance. The statement is set\n;; to enable streaming and go fully lazy with restultset-seq.\n;; \"f\" is expected to produce the required results *before* exiting \n;; the try-finally block that closes the connection.\n\n(import '[java.sql DriverManager ResultSet])\n\n(defn with-mysql-query [url query f]\n (Class/forName \"com.mysql.jdbc.Driver\")\n (let [db url\n conn (DriverManager/getConnection db)\n stmt (doto\n (.createStatement conn\n ResultSet/TYPE_FORWARD_ONLY\n ResultSet/CONCUR_READ_ONLY)\n (.setFetchSize Integer/MIN_VALUE))\n rs (.executeQuery stmt query)]\n (try\n (f (resultset-seq rs))\n (finally\n (.close stmt)\n (.close conn)))))\n\n(with-mysql-query\n \"jdbc:mysql://localhost/mysql?user=root&password=\"\n \"SELECT * FROM user\"\n (comp count keys first))\n\n;; 45\n","_id":"5a95358fe4b0316c0f44f900"}],"notes":null,"arglists":["rs"],"doc":"Creates and returns a lazy sequence of structmaps corresponding to\n the rows in the java.sql.ResultSet rs","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/resultset-seq"},{"added":"1.0","ns":"clojure.core","name":"struct","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1293674730000,"author":{"login":"dakrone","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bcacd00a7f05c4772329cf9f446c7987?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"defstruct","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bb5"},{"created-at":1605645636792,"author":{"login":"metasoarous","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/88556?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"create-struct","ns":"clojure.core"},"_id":"5fb43544e4b0b1e3652d7407"}],"line":4088,"examples":[{"author":{"login":"dakrone","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bcacd00a7f05c4772329cf9f446c7987?r=PG&default=identicon"},"editors":[],"body":"user> (defstruct mystruct :foo :bar)\n#'user/mystruct\n\nuser> (struct mystruct \"eggplant\" \"pizza\")\n{:foo \"eggplant\", :bar \"pizza\"}","created-at":1293674725000,"updated-at":1293674725000,"_id":"542692cec026201cdc326d8b"},{"updated-at":1605645959161,"created-at":1605645773188,"author":{"login":"metasoarous","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/88556?v=4"},"body":";; You can use an \"anonymous\" struct like so\n\n(let [structure (create-struct :foo :bar)]\n (struct structure \"pop\" \"fizz\"))\n\n;; This can be useful if you want to dynamically create/use structs, and don't\n;; know the field names at compile time (e.g. when reading CSV files)","editors":[{"avatar-url":"https://avatars3.githubusercontent.com/u/88556?v=4","account-source":"github","login":"metasoarous"}],"_id":"5fb435cde4b0b1e3652d7408"}],"notes":[{"body":"Structs are becoming obsolete. Use records instead. See `defrecord`.","created-at":1423277999196,"updated-at":1423277999196,"author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"_id":"54d57fafe4b0e2ac61831d27"},{"body":"In _general_, records should be preferred over structs. However, structs aren't _entirely_ obsolete.\n\nThey can still be useful when you need/want to create record-like objects dynamically; That is, when you don't know the field names at compile time. A typical example of this might be loading rows from a CSV (as [semantic-csv](https://github.com/metasoarous/semantic-csv) does). The advantage in this case over using regular maps is significantly improved performance creating and using these objects.","created-at":1605646073997,"updated-at":1605646085033,"author":{"avatar-url":"https://avatars3.githubusercontent.com/u/88556?v=4","account-source":"github","login":"metasoarous"},"_id":"5fb436f9e4b0b1e3652d740b"}],"arglists":["s & vals"],"doc":"Returns a new structmap instance with the keys of the\n structure-basis. vals must be supplied for basis keys in order -\n where values are not supplied they will default to nil.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/struct"},{"added":"1.0","ns":"clojure.core","name":"map","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1318598944000,"author":{"login":"mmwaikar","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/29d36f4c9f39c9f8ff61c07033b13118?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"map-indexed","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b92"},{"created-at":1346930884000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"pmap","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b93"},{"created-at":1346930913000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"amap","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b94"},{"created-at":1371842453000,"author":{"login":"adereth","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5ad11b4e208a6cdb3bd45fe01dea59b7?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"mapcat","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b95"},{"created-at":1399907437000,"author":{"login":"ryo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3f7913b563c72083c74030d928ba407e?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"keep","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b96"},{"created-at":1407836917000,"author":{"login":"Thomas Stephens","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/40024617164314f70f7584ac09b96c1d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"juxt","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b97"},{"created-at":1413326075136,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"},"to-var":{"ns":"clojure.core","name":"mapv","library-url":"https://github.com/clojure/clojure"},"_id":"543da4fbe4b02688d208b1b9"},{"created-at":1449762409201,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"reduce","ns":"clojure.core"},"_id":"56699e69e4b09a2675a0ba73"},{"created-at":1516403401772,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/109629?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"run!","ns":"clojure.core"},"_id":"5a627ac9e4b0a08026c48d07"},{"created-at":1655305687140,"author":{"login":"zackteo","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7510179?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"filter","ns":"clojure.core"},"_id":"62a9f5d7e4b0b1e3652d7601"}],"line":2744,"examples":[{"author":{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"tomas","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/c0c2f195479ae4a71cb6484679f6f49?r=PG&default=identicon"},{"login":"tomas","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/c0c2f195479ae4a71cb6484679f6f49?r=PG&default=identicon"},{"login":"tomas","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/c0c2f195479ae4a71cb6484679f6f49?r=PG&default=identicon"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"},{"avatar-url":"https://avatars.githubusercontent.com/u/35314270?v=4","account-source":"github","login":"ricardodalarme"}],"body":"(map inc [1 2 3 4 5])\n;;=> (2 3 4 5 6)\n\n\n;; map can be used with multiple collections. Collections will be consumed\n;; and passed to the mapping function in parallel:\n(map + [1 2 3] [4 5 6])\n;;=> (5 7 9)\n\n\n;; When map is passed more than one collection, the mapping function will\n;; be applied until one of the collections runs out:\n(map + [1 2 3] (iterate inc 1))\n;;=> (2 4 6)\n\n\n\n;; map is often used in conjunction with the # reader macro:\n(map #(str \"Hello \" % \"!\" ) [\"Ford\" \"Arthur\" \"Tricia\"])\n;;=> (\"Hello Ford!\" \"Hello Arthur!\" \"Hello Tricia!\")\n\n;; A useful idiom to pull \"columns\" out of a collection of collections. \n;; Note, it is equivalent to:\n;; user=> (map vector [:a :b :c] [:d :e :f] [:g :h :i])\n\n(apply map vector [[:a :b :c]\n [:d :e :f]\n [:g :h :i]])\n\n;;=> ([:a :d :g] [:b :e :h] [:c :f :i])\n\n;; From http://clojure-examples.appspot.com/clojure.core/map\n","created-at":1278720977000,"updated-at":1665566175477,"_id":"542692cac026201cdc326b01"},{"updated-at":1515774677373,"created-at":1279062371000,"body":";; map sends key-value pairs from a hash-map\n(map #(vector (first %) (* 2 (second %)))\n {:a 1 :b 2 :c 3})\n;;=> ([:a 2] [:b 4] [:c 6])\n\n;; or the same thing using destructuring\n(map (fn [[key value]] [key (* 2 value)])\n {:a 1 :b 2 :c 3})\n;;=> ([:a 2] [:b 4] [:c 6])\n\n(into {} *1)\n;;=> {:a 2, :b 4, :c 6}\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4","account-source":"github","login":"phreed"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/142529?v=3","account-source":"github","login":"nipra"},"_id":"542692cac026201cdc326b09"},{"updated-at":1636744366940,"created-at":1310850029000,"body":";; Use a hash-map as a function to translate values in a collection from the \n;; given key to the associated value\n\nuser=> (map {2 \"two\" 3 \"three\"} [5 3 2])\n(nil \"three\" \"two\")\n\n;; then use (filter identity... to remove the nils\nuser=> (filter identity (map {2 \"two\" 3 \"three\"} [5 3 2]))\n(\"three\" \"two\")\n\n;; an alternative to the above map+filter steps is keep.\n(keep {2 \"two\" 3 \"three\"} [5 3 2])\n;;=> (\"three\" \"two\")","editors":[{"login":"wdhowe","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/4631165?v=4"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon","account-source":"clojuredocs","login":"shockbob"},"_id":"542692cac026201cdc326b0b"},{"updated-at":1471132085931,"created-at":1320357817000,"body":";; mapping over a hash-map applies (into) first. \n;; need to use functions that deal with arrays (fn [[key val]] ...)\n(map pprint {:key :val :key1 :val1})\n([:key :val]\n[:key1 :val1]\nnil nil)\n\n;;above, the pprint output appears to be part of the return value but it's not:\n(hash-set (map pprint {:key :val :key1 :val1}))\n[:key :val]\n[:key1 :val1]\n#{(nil nil)}\n\n(map second {:key :val :key1 :val1})\n;;=>(:val :val1)\n\n(map last {:x 1 :y 2 :z 3})\n;;=> (1 2 3)","editors":[{"avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon","account-source":"clojuredocs","login":"boxie"},{"avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon","account-source":"clojuredocs","login":"boxie"},{"avatar-url":"https://www.gravatar.com/avatar/9e10dfa345f44b0fe72bbe081fd51b83?r=PG&default=identicon","account-source":"clojuredocs","login":"AtKaaZ"},{"avatar-url":"https://www.gravatar.com/avatar/9e10dfa345f44b0fe72bbe081fd51b83?r=PG&default=identicon","account-source":"clojuredocs","login":"AtKaaZ"},{"login":"sleyzerzon","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/528932?v=3"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon","account-source":"clojuredocs","login":"boxie"},"_id":"542692d4c026201cdc326ffb"},{"author":{"login":"dansalmo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e33ee460f5f61bc5ba9b598934766215?r=PG&default=identicon"},"editors":[{"login":"dansalmo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e33ee460f5f61bc5ba9b598934766215?r=PG&default=identicon"},{"login":"dansalmo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e33ee460f5f61bc5ba9b598934766215?r=PG&default=identicon"},{"login":"dansalmo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e33ee460f5f61bc5ba9b598934766215?r=PG&default=identicon"}],"body":"(map fn [a 4 x]\n [b 5 y]\n [c 6]) \n; ^ ^\n; applies fn to a b c as (fn a b c)\n; applies fn to 4 5 6 as (fn 4 5 6)\n; ignores (x y)\n; returns a list of results\n; equivalent to (list (fn a b c) (fn 4 5 6))\n\n;example\n(map list [1 2 3]\n '(a b c)\n '(4 5))\n\nuser=> (map list [1 2 3] '(a b c) '(4 5))\n((1 a 4) (2 b 5))\n;same as\nuser=> (list (list 1 'a 4) (list 2 'b 5))\n((1 a 4) (2 b 5))","created-at":1345087524000,"updated-at":1345087844000,"_id":"542692d4c026201cdc327000"},{"author":{"login":"octopusgrabbus","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/fd31b8bcea99fa7b0711fbc424587774?r=PG&default=identicon"},"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"}],"body":"; map passed two collection arguments. From 4Clojure Problem #157\n\n(def d1 [:a :b :c])\n(#(map list % (range)) d1)\n;;=> ((:a 0) (:b 1) (:c 2))","created-at":1371168552000,"updated-at":1413325797212,"_id":"542692d4c026201cdc327004"},{"updated-at":1435879364197,"created-at":1435879364197,"author":{"login":"bsvingen","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1647562?v=3"},"body":";; Used without a collection, map will create a transducer:\n(def xf (map inc))\n\n;; We can now apply this transducer to a sequence:\n(transduce xf conj (range 5))\n;; => [1 2 3 4 5]\n","_id":"5595c7c4e4b020189d740546"},{"updated-at":1450108764352,"created-at":1450108764352,"author":{"login":"ha0ck","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/3716736?v=3"},"body":";; Extract keyword from a collection of obj\n(map :a '({:a 1 :b 0} {:a 2 :b 0} {:a 3 :b 1} {:a 3 :b 0}))\n;; =>(1 2 3 3)","_id":"566ee75ce4b09a2675a0ba77"},{"updated-at":1471132864529,"created-at":1471132864529,"author":{"login":"sleyzerzon","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/528932?v=3"},"body":";;get the keys from a map with entries of certain values\n(let [m {:x 1 :y 2 :z 3}\n vset #{2 3}]\n (map first (filter (comp vset last) m)))\n;;=> (:y :z)\n\n(filter (comp #{2 3} last) {:x 1 :y 2 :z 3})\n;;=> ([:y 2] [:z 3])\n\n","_id":"57afb4c0e4b02d8da95c26ff"},{"updated-at":1515775349661,"created-at":1515775349661,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"},"body":";; deeper destructuring\n(def ds [ {:a 1 :b 2 :c [:foo :bar]}\n {:a 9 :b 8 :c [:baz :zoo]}\n {:a 1 :b 2 :c [:dog :cat]} ])\n\n(->> ds \n (map (fn [{a :a, b :b, [lhs rhs] :c}] \n [(str \"a:\" a \" c2:\" rhs)])))\n;;=> ([\"a:1 c2::bar\"] [\"a:9 c2::zoo\"] [\"a:1 c2::cat\"])","_id":"5a58e575e4b0a08026c48cf2"},{"updated-at":1516657644067,"created-at":1516657644067,"author":{"login":"ibercode","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/31028993?v=4"},"body":";;map taking a collection of functions as an argument\n\n(def sum #(reduce + %))\n\n(def average #(/ (sum %) (count %)))\n\n;;apply a function to a collection\n(defn results [coll]\n (map #(% coll) [sum average count]))\n\n(results [10 20 30 40 50])\n;;[150 30 5]","_id":"5a665bece4b09621d9f53a74"},{"updated-at":1517039150366,"created-at":1517039150366,"author":{"login":"ibercode","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/31028993?v=4"},"body":"(def my-coll [\n {:m 1, :val 12}\n {:m 2, :val 3}\n {:m 3, :val 32}])\n\n(map #(:val %) my-coll)\n;;(12 3 32)\n\n;;get total:\n(reduce + (map #(:val %) my-coll))\n;;47","_id":"5a6c2e2ee4b076dac5a728a8"},{"updated-at":1517738681040,"created-at":1517738681040,"author":{"login":"ibercode","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/31028993?v=4"},"body":";;map practical example\n\n(def months [\"jan\" \"feb\" \"mar\"])\n\n(def temps [5 7 12])\n\n(defn unify\n [month temp]\n {:month month\n :temp temp})\n\n(map unify months temps)\n\n;;({:month \"jan\", :temp 5}\n;; {:month \"feb\", :temp 7}\n;; {:month \"mar\", :temp 12})\n","_id":"5a76dab9e4b0e2d9c35f7417"},{"updated-at":1518710042333,"created-at":1518710042333,"author":{"login":"ibercode","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/31028993?v=4"},"body":";;map Function collection1 collection2\n\n(map vector '(1 2 3 4) [:a :b :c :d])\n\n;;([1 :a] [2 :b] [3 :c] [4 :d])","_id":"5a85ad1ae4b0316c0f44f8c0"},{"updated-at":1560011503684,"created-at":1560011503684,"author":{"login":"sodesu99","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/31072774?v=4"},"body":" ;multiplication of rows and columns\n(def matrix\n [\n [1 2 3 4 5];=>120\n [1 2 3 4 5];=>120\n [1 2 3 4 5];=>120\n [1 2 3 4 5]]);120 \n ;(1 16 81 256 625)\n\n;;columns multiplication\n(apply map * matrix)\n;;(1 16 81 256 625)\n\n;;rows multiplication\n(map #(reduce * %) matrix)\n;;(120 120 120 120)","_id":"5cfbe2efe4b0ca44402ef753"},{"updated-at":1631296227373,"created-at":1631296227373,"author":{"login":"cloudbuck3t","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/90472507?v=4"},"body":";; Notice how the args of each collection are processed in parallel by the\n;; function provided to `map` -- in this case, an #(anonymous function) \n;;that takes %1 = the first coll elements and %2 the second coll elements.\n;; map will process the collections in parallel and will terminate when it reaches \n;; the end of the shortest collection. In this case, they are equal length.\n\n (map #(str \"Hello \" %1 %2) [\"Tennessee \" \"James \" \"John \"] [\"Ernie Ford\" \"Bond\" \"Smith\"])\n\noutput> (\"Hello Tennessee Ernie Ford\" \"Hello James Bond\" \"Hello John Smith\")","_id":"613b9ae3e4b0b1e3652d753a"},{"editors":[{"login":"aQuaYi","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/6028869?v=4"}],"body":";; running several functions on the same argument\n\n(map #(% 0) (list inc dec zero?))\n;=> (1 -1 true)\n\n(map #(% 0) [inc dec zero?])\n;=> (1 -1 true)\n\n;; but not\n\n(map #(% 0) `(inc dec zero?))\n;=> (nil nil nil)\n\n(map #(% 0) '(inc dec zero?))\n;=> (nil nil nil)\n\n;; https://stackoverflow.com/questions/69925317/why-map-fn-f-f-0-inc-returns-nil-in-clojure","author":{"avatar-url":"https://avatars.githubusercontent.com/u/6028869?v=4","account-source":"github","login":"aQuaYi"},"created-at":1636796097196,"updated-at":1636954237105,"_id":"618f86c1e4b0b1e3652d7574"},{"updated-at":1650196591875,"created-at":1650196591875,"author":{"login":"holtzermann17","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/179958?v=4"},"body":";; Be careful with `map`, closures, and anonymous functions\n\n(defn typical-closure []\n (let [names (atom [])]\n (fn [arg] (swap! names conj arg) @names)))\n\n;; This works as expected: one function gets created and mapped\n\n(defmacro list-maker [fun args & body]\n `(defn ~fun ~args\n (map (typical-closure) '~body)))\n\n(list-maker foo [x] 1 2 3 4 5)\n(foo 100) ; ([1] [1 2] [1 2 3] [1 2 3 4] [1 2 3 4 5])\n\n;; This version recomputes the function for each mappand!\n\n(defmacro list-maker-oops [fun args & body]\n `(defn ~fun ~args\n (map #((typical-closure) %) '~body)))\n\n;; facepalm\n(list-maker-oops foo [x] 1 2 3 4 5)\n(foo 100) ; ([1] [2] [3] [4] [5])","_id":"625c006fe4b0b1e3652d75d4"}],"notes":[{"updated-at":1361257529000,"body":"To create a *hashmap*, use the [`hash-map`](hash-map) function, or the `{...}` sugar:\r\n\r\n (= {:a 1 :b 2 :c 3} (hash-map :a 1 :b 2 :c 3))","created-at":1361257529000,"author":{"login":"Howard Abrams","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/eef504f83cde9913a37eefa515de56a8?r=PG&default=identicon"},"_id":"542692edf6e94c6970521ffd"}],"arglists":["f","f coll","f c1 c2","f c1 c2 c3","f c1 c2 c3 & colls"],"doc":"Returns a lazy sequence consisting of the result of applying f to\n the set of first items of each coll, followed by applying f to the\n set of second items in each coll, until any one of the colls is\n exhausted. Any remaining items in other colls are ignored. Function\n f should accept number-of-colls arguments. Returns a transducer when\n no collection is provided.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/map"},{"added":"1.1","ns":"clojure.core","name":"juxt","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1297561266000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"partial","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f05"},{"created-at":1297561270000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"comp","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f06"},{"created-at":1647648153954,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"every-pred","ns":"clojure.core"},"_id":"62351d99e4b0b1e3652d75bf"}],"line":2593,"examples":[{"author":{"login":"kotarak","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5db30f607f0b5fa70d690311aa3bfd3b?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":";; Extract values from a map, treating keywords as functions.\n((juxt :a :b) {:a 1 :b 2 :c 3 :d 4})\n;;=> [1 2]\n","created-at":1279213578000,"updated-at":1420743412507,"_id":"542692cfc026201cdc326e0a"},{"updated-at":1469518181621,"created-at":1279213673000,"body":";; \"Explode\" a value.\n\n((juxt identity name) :keyword)\n;;=> [:keyword \"keyword\"]\n\n(juxt identity name)\n...is the same as:\n(fn [x] [(identity x) (name x)])\n\n;; eg. to create a map:\n\n(into {} (map (juxt identity name) [:a :b :c :d]))\n;;=> {:a \"a\" :b \"b\" :c \"c\" :d \"d\"}\n","editors":[{"avatar-url":"https://www.gravatar.com/avatar/5db30f607f0b5fa70d690311aa3bfd3b?r=PG&default=identicon","account-source":"clojuredocs","login":"kotarak"},{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3","account-source":"github","login":"phreed"},{"login":"tengstrand","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/631272?v=3"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/5db30f607f0b5fa70d690311aa3bfd3b?r=PG&default=identicon","account-source":"clojuredocs","login":"kotarak"},"_id":"542692cfc026201cdc326e0c"},{"author":{"login":"adie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/26a4d75105ed437cdba82981ff7c78f6?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":";; Get the first character and length of string\n\n((juxt first count) \"Clojure Rocks\")\n;;=> [\\C 13]\n","created-at":1280240324000,"updated-at":1420743526351,"_id":"542692cfc026201cdc326e0f"},{"updated-at":1450881233579,"created-at":1342498131000,"body":";; sort list of maps by multiple values\n(sort-by (juxt :a :b) [{:a 1 :b 3} {:a 1 :b 2} {:a 2 :b 1}])\n;;=> [{:a 1 :b 2} {:a 1 :b 3} {:a 2 :b 1}]","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3","account-source":"github","login":"phreed"},{"login":"liango2","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/5696817?v=3"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/47018db2b156f6c7f606950e19cf6134?r=PG&default=identicon","account-source":"clojuredocs","login":"ordnungswidrig"},"_id":"542692d3c026201cdc326fdd"},{"author":{"login":"Phalphalak","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a684c0fd4f27597437de953e92a15d4b?r=PG&default=identicon"},"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":";; Create lookup maps via a specific key\n\n(defn index-by [coll key-fn]\n (into {} (map (juxt key-fn identity) coll)))\n;; #'user/index-by\n\n(index-by [{:id 1 :name \"foo\"} \n {:id 2 :name \"bar\"} \n {:id 3 :name \"baz\"}] :id)\n;;=> {1 {:name \"foo\", :id 1}, \n;; 2 {:name \"bar\", :id 2}, \n;; 3 {:name \"baz\", :id 3}}\n\n(index-by [{:id 1 :name \"foo\"} \n {:id 2 :name \"bar\"} \n {:id 3 :name \"baz\"}] :name)\n;;=> {\"foo\" {:name \"foo\", :id 1}, \n;; \"bar\" {:name \"bar\", :id 2}, \n;; \"baz\" {:name \"baz\", :id 3}}\n","created-at":1392423622000,"updated-at":1420743620071,"_id":"542692cfc026201cdc326e12"},{"body":"((juxt + * min max) 3 4 6)\n;;=> [13 72 3 6]","author":{"login":"d9k","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7331988?v=3"},"created-at":1428349759385,"updated-at":1428349759385,"_id":"5522e33fe4b033f34014b765"},{"updated-at":1443524546728,"created-at":1443524546728,"author":{"login":"frolovv","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2934915?v=3"},"body":";; split a sequence into two parts\n\nuser=> ((juxt take drop) 3 [1 2 3 4 5 6])\n;; => [(1 2 3) (4 5 6)]","_id":"560a6fc2e4b08e404b6c1c8b"},{"updated-at":1463687667792,"created-at":1463687667792,"author":{"login":"clojurianix","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/19415437?v=3"},"body":";; Segregate even and odd numbers in collection.\n\n((juxt (partial filter even?) (partial filter odd?)) (range 0 9))\n;;=> [(0 2 4 6 8) (1 3 5 7)]","_id":"573e19f3e4b0227798e72da1"},{"updated-at":1465311839158,"created-at":1465311839158,"author":{"login":"sleyzerzon","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/528932?v=3"},"body":";;keywords serve as getter functions to produce an ordered vector\n\n((juxt :lname :fname) {:fname \"Bill\" :lname \"Gates\"})\n=> [\"Gates\" \"Bill\"]","_id":"5756e25fe4b0bafd3e2a047f"},{"updated-at":1477172912305,"created-at":1477172912305,"author":{"login":"lmccombes","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2421085?v=3"},"body":";; sort by two values\n\n(sort-by (juxt :a :b) [{:a 2 :b 4} {:a 1 :b 2} {:a 2 :b 1}])\n=> ({:a 1, :b 2} {:a 2, :b 1} {:a 2, :b 4})","_id":"580bdeb0e4b001179b66bdda"},{"editors":[{"login":"abyala","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/1930104?v=4"}],"body":";; something similar to group-by\n\n(def split-by (juxt filter remove))\n\n(split-by pos? [-1 -2 4 5 3 -9])\n=> [(4 5 3) (-1 -2 -9)]\n","author":{"avatar-url":"https://avatars2.githubusercontent.com/u/380618?v=4","account-source":"github","login":"smnplk"},"created-at":1539468521882,"updated-at":1609110202738,"_id":"5bc26ce9e4b00ac801ed9eda"},{"updated-at":1652253340151,"created-at":1652253340151,"author":{"login":"AbhishekJaiswal123","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10753944?v=4"},"body":";; Extract nested value from the map\n\n((juxt :a #(get-in % [:c :d])) {:a 1 :b 2 :c {:d 2}})\n=> [1 2]","_id":"627b629ce4b0b1e3652d75ee"}],"notes":[{"updated-at":1291541271000,"body":"I kinda love this fn =)","created-at":1291541271000,"author":{"login":"Nevena","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/fa0e495ccb6ed2997e14f687817e9299?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fa8"},{"updated-at":1359899617000,"body":"\"reduce1\" -> \"reduce\"\r\n\r\ncore sources from 33 line to 37 line","created-at":1359899617000,"author":{"login":"lispro06","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/20c3faad6f66a434dae42b5ed8ad305?r=PG&default=identicon"},"_id":"542692edf6e94c6970521ffc"}],"arglists":["f","f g","f g h","f g h & fs"],"doc":"Takes a set of functions and returns a fn that is the juxtaposition\n of those fns. The returned fn takes a variable number of args, and\n returns a vector containing the result of applying each fn to the\n args (left-to-right).\n ((juxt a b c) x) => [(a x) (b x) (c x)]","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/juxt"},{"added":"1.0","ns":"clojure.core","name":"ns-publics","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1288055164000,"author":{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},"to-var":{"ns":"clojure.core","name":"ns-map","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d13"},{"created-at":1298556634000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.core","name":"ns-interns","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d14"},{"created-at":1303419098000,"author":{"login":"TimMc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5d532e51427ef2f4ded31aaca16c8baf?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"resolve","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d15"}],"line":4215,"examples":[{"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":";; create the namespace and switch to it\nuser=> (in-ns 'demo.ns)\n#\n\n;; Make sure all of the good stuff in clojure.core is usable here, too.\ndemo.ns=> (clojure.core/use 'clojure.core)\nnil\n\n;; define some public functions\ndemo.ns=> (defn public-fn1 [x y] (+ x y))\n#'demo.ns/public-fn1\ndemo.ns=> (defn public-fn2 [t] (* t t t))\n#'demo.ns/public-fn2\n\n;; define a private function with defn-\ndemo.ns=> (defn- private-fn [s] (/ s 5))\n#'demo.ns/private-fn\n\n;; Switch back to the user namespace\ndemo.ns=> (in-ns 'user)\n#\n\n;; Get a map of all intern mappings for namespace demo.ns\nuser=> (ns-interns 'demo.ns)\n{public-fn1 #'demo.ns/public-fn1, private-fn #'demo.ns/private-fn, public-fn2 #'demo.ns/public-fn2}\n\n;; Now get a map of only the public mappings. No private-fn here.\nuser=> (ns-publics 'demo.ns)\n{public-fn1 #'demo.ns/public-fn1, public-fn2 #'demo.ns/public-fn2}\n","created-at":1298556164000,"updated-at":1298556944000,"_id":"542692c7c026201cdc326989"},{"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"editors":[],"body":";; See also http://clojure.org/namespaces for information on namespaces in Clojure and how to inspect and manipulate them","created-at":1348479386000,"updated-at":1348479386000,"_id":"542692d4c026201cdc32701d"}],"notes":null,"arglists":["ns"],"doc":"Returns a map of the public intern mappings for the namespace.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/ns-publics"},{"added":"1.0","ns":"clojure.core","name":"<","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1291975111000,"author":{"login":"alimoeeny","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e8dd06976ead4082d2181f3807117e1?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"=","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ef6"},{"created-at":1291975116000,"author":{"login":"alimoeeny","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e8dd06976ead4082d2181f3807117e1?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"not=","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ef7"},{"created-at":1291975125000,"author":{"login":"alimoeeny","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e8dd06976ead4082d2181f3807117e1?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":">","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ef8"},{"created-at":1391516309000,"author":{"login":"rob","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/89cc77a97a299e2e6295b2d7be194b2b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"<=","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ef9"},{"created-at":1391516316000,"author":{"login":"rob","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/89cc77a97a299e2e6295b2d7be194b2b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":">=","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521efa"}],"line":902,"examples":[{"updated-at":1598154611072,"created-at":1280321780000,"body":"user=> (< 1 2)\ntrue\nuser=> (< 2 1)\nfalse\nuser=> (< 1.5 2)\ntrue\nuser=> (< 2 3 4 5 6)\ntrue\nuser=> (< 1 1/2)\nfalse","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3","account-source":"github","login":"jafingerhut"},{"login":"berczeck","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/1321842?v=4"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/ee24aacb65359196b0a1bad050f9a62f?r=PG&default=identicon","account-source":"clojuredocs","login":"mattdw"},"_id":"542692cbc026201cdc326c25"}],"notes":[{"updated-at":1391516536000,"body":"I think the docstring for < should say \"strictly increasing\" instead of \"monotonically increasing.\" In contrast, I think <= is the function that tests for \"monotonically increasing.\"\r\n\r\nHere's a quote from wikitionary...\r\n\r\nmonotonic increasing: (mathematics, of a function) always increasing or remaining constant, and never decreasing; contrast this with strictly increasing\r\n","created-at":1391516536000,"author":{"login":"rob","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/89cc77a97a299e2e6295b2d7be194b2b?r=PG&default=identicon"},"_id":"542692edf6e94c697052201b"}],"arglists":["x","x y","x y & more"],"doc":"Returns non-nil if nums are in monotonically increasing order,\n otherwise false.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/<"},{"ns":"clojure.core","name":"*source-path*","type":"var","see-alsos":null,"examples":[{"editors":[{"login":"reborg","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/20086?v=4"}],"body":";; Contains the name (not the full path, for that see \n;; https://clojuredocs.org/clojure.core/*file*) \n;; of the compilation unit that is currently being compiled.\n;; Given a file named \"examples/example.clj\" is available in the \"examples\" \n;; folder starting at \".\":\n\n(ns examples.example)\n(when *compile-files* \n (println \"Compiling:\" *source-path*))\n\n;; If we start a REPL adding \".\" as part of the classpath,\n;; we can see the following:\n\n(binding [*compile-path* \".\"]\n (compile 'examples.example))\n;; Compiling: example.clj\n;; examples.example\n","author":{"avatar-url":"https://avatars.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"},"created-at":1615736593501,"updated-at":1615737031070,"_id":"604e2f11e4b0b1e3652d7491"}],"notes":null,"arglists":[],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core/*source-path*"},{"ns":"clojure.core","name":"with-loading-context","file":"clojure/core.clj","type":"macro","column":1,"see-alsos":null,"line":5808,"examples":null,"macro":true,"notes":null,"arglists":["& body"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core/with-loading-context"},{"added":"1.0","ns":"clojure.core","name":"test","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1289286348000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"var","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521beb"},{"created-at":1289286374000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"meta","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bec"},{"created-at":1289286382000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"assert","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bed"},{"created-at":1289287269000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.test","name":"with-test","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bee"}],"line":4882,"examples":[{"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"editors":[{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"}],"body":"(defn my-function\n \"this function adds two numbers\"\n {:test #(do\n (assert (= (my-function 2 3) 5))\n (assert (= (my-function 4 4) 8)))}\n ([x y] (+ x y)))\n\n(test #'my-function) ;equal to (test (var my-function))\n=> :ok\n\n-----------------------------------------------------------------------\n\n(defn my-function\n \"this function adds two numbers\"\n {:test #(do\n (assert (= (my-function 2 3) 5))\n (assert (= (my-function 99 4) 8)))}\n ([x y] (+ x y)))\n\n(test #'my-function)\n=> java.lang.AssertionError: Assert failed: (= (my-function 99 4) 8) (NO_SOURCE_FILE:0\n\n---------------------------------------------------------------------------\n\n(defn my-function\n \"this function adds two numbers\"\n ([x y] (+ x y)))\n\n(test #'my-function)\n=> :no-test","created-at":1289286249000,"updated-at":1289286329000,"_id":"542692cac026201cdc326b8a"}],"notes":null,"arglists":["v"],"doc":"test [v] finds fn at key :test in var metadata and calls it,\n presuming failure will throw exception","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/test"},{"added":"1.0","ns":"clojure.core","name":"rest","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1300352361000,"author":{"login":"TimMc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5d532e51427ef2f4ded31aaca16c8baf?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"next","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b01"},{"created-at":1302912314000,"author":{"login":"hoornet","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5834f829a9def19620d4014c46642172?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"first","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b02"},{"created-at":1328341652000,"author":{"login":"Claj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5fd658a8d2ef549071cb5286b1b874aa?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"drop","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b03"},{"created-at":1399433624000,"author":{"login":"Yun","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/f18708f979ad613ab134cb5002558965?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"pop","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b04"},{"created-at":1505013526855,"author":{"login":"didibus","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/601540?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"nthrest","ns":"clojure.core"},"_id":"59b4af16e4b09f63b945ac6a"},{"created-at":1505013535788,"author":{"login":"didibus","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/601540?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"nthnext","ns":"clojure.core"},"_id":"59b4af1fe4b09f63b945ac6b"}],"line":66,"examples":[{"updated-at":1422037239311,"created-at":1279416340000,"body":"(rest [1 2 3 4 5]) ;;=> (2 3 4 5)\n(rest [\"a\" \"b\" \"c\" \"d\" \"e\"]) ;;=> (\"b\" \"c\" \"d\" \"e\")","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/1488134?v=2","account-source":"github","login":"douglarek"},{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3","account-source":"github","login":"phreed"}],"author":{"avatar-url":"https://avatars2.githubusercontent.com/u/22608?v=4","account-source":"github","login":"MrHus"},"_id":"542692cec026201cdc326d69"},{"author":{"login":"hoornet","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5834f829a9def19620d4014c46642172?r=PG&default=identicon"},"editors":[{"login":"steveminer","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d28543d134185d12d4006a74738d233e?r=PG&default=identicon"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":";; For the most part rest must take a collection as its argument.\n;; It always returns a seq.\n(rest '())\n;;=> ()","created-at":1302100429000,"updated-at":1422037351252,"_id":"542692cec026201cdc326d6a"},{"author":{"login":"steveminer","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d28543d134185d12d4006a74738d233e?r=PG&default=identicon"},"editors":[{"login":"steveminer","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d28543d134185d12d4006a74738d233e?r=PG&default=identicon"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":";; There is one case where the input is not required to be a collection.\n;; But, 'rest' still returns a list.\n(rest nil)\n;;=> ()","created-at":1306983166000,"updated-at":1422037405420,"_id":"542692cec026201cdc326d6c"},{"author":{"login":"steveminer","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d28543d134185d12d4006a74738d233e?r=PG&default=identicon"},"editors":[{"login":"steveminer","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d28543d134185d12d4006a74738d233e?r=PG&default=identicon"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":";; A simple (re-)implementation of 'map' using 'rest' for recursing over a collection. \n;; Note that (seq coll) is used as the test.\n(defn my-map [func coll]\n (when-let [s (seq coll)]\n (cons (func (first s))\n (my-map func (rest s)))))\n\n(my-map #(* % %) [2 3 5 7 11 13])\n;;=> (4 9 25 49 121 169)","created-at":1306983565000,"updated-at":1422038005534,"_id":"542692cec026201cdc326d6e"},{"author":{"login":"TravisHeeter","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/fe491d07493e45af083b89b767342c6?r=PG&default=identicon"},"editors":[{"login":"douglarek","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1488134?v=2"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":";; Any collection can be used\n(rest '(1 2 3 4 5)) ;;=> (2 3 4 5)\n(rest [1 2 3 4 5]) ;;=> (2 3 4 5)\n(rest #{1 2 3 4 5}) ;;=> (2 3 4 5)\n\n(rest {1 nil 2 nil 3 nil 4 nil 5 nil}) ;;=> ([2 nil] [3 nil] [4 nil] [5 nil])","created-at":1385175807000,"updated-at":1422037689911,"_id":"542692d5c026201cdc327075"},{"body":";; Difference between next and rest:\n(rest [:a])\n;; => ()\n(next [:a])\n;; => nil\n\n(rest [])\n;; => ()\n(next [])\n;; => nil\n\n(rest nil)\n;; => ()\n(next nil)\n;; => nil","author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"created-at":1423016919214,"updated-at":1423094910932,"editors":[{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"}],"_id":"54d183d7e4b0e2ac61831d06"}],"notes":[{"updated-at":1306987831000,"body":"rest is generally preferred over [next](../clojure.core/next). See the Clojure.org documentation on writing [lazy](http://clojure.org/lazy) functions.\r\n\r\nAlso, the topic is covered on StackOverflow.com: [rest vs. next](http://stackoverflow.com/questions/4288476/clojure-rest-vs-next).\r\n","created-at":1306985238000,"author":{"login":"steveminer","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d28543d134185d12d4006a74738d233e?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fc1"}],"tag":"clojure.lang.ISeq","arglists":["coll"],"doc":"Returns a possibly empty seq of the items after the first. Calls seq on its\n argument.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/rest"},{"added":"1.4","ns":"clojure.core","name":"ex-data","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1424029639635,"author":{"login":"claj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/353113?v=3"},"to-var":{"ns":"clojure.core","name":"ex-info","library-url":"https://github.com/clojure/clojure"},"_id":"54e0f7c7e4b01ed96c93c87c"},{"created-at":1517506162614,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"try","ns":"clojure.core"},"_id":"5a734e72e4b0c974fee49d18"},{"created-at":1517620509698,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"throw","ns":"clojure.core"},"_id":"5a750d1de4b0e2d9c35f7409"},{"created-at":1517620517637,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"catch","ns":"clojure.core"},"_id":"5a750d25e4b0e2d9c35f740a"},{"created-at":1517620899901,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"finally","ns":"clojure.core"},"_id":"5a750ea3e4b0e2d9c35f740e"},{"created-at":1602605116458,"author":{"login":"m0smith","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/398808?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"ex-message","ns":"clojure.core"},"_id":"5f85d03ce4b0b1e3652d73dd"},{"created-at":1636597659206,"author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"ex-cause","ns":"clojure.core"},"_id":"618c7f9be4b0b1e3652d756b"}],"line":4841,"examples":[{"editors":[{"login":"Luckvery","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1178168?v=3"}],"body":"(try\n (let [response (http/post\n \"http://localhost:8080/v1/leads\"\n {:form-params {:foo \"somethingBad\"}})]\n (prn \"This is the response\" response))\n (catch Exception e\n (prn \"This is the error\" (ex-data e))))\n\n-------\n\n> \"This is the error\" {:status 500, :headers {\"Content-Type\" \"application/json; \ncharset=utf-8\", \"Content-Length\" \"73\", \"Server\" \"http-kit\", \"Date\" \"Mon, 10 Oct 2016\n 16:53:12 GMT\"}, :body \"{\\\"type\\\":\\\"unknown-\nexception\\\",\\\"class\\\":\\\"java.lang.IllegalArgumentException\\\"}\", :request-time 7,\n :trace-redirects [\"http://localhost:8080/v1/leads\"], :orig-content-encoding nil}","author":{"avatar-url":"https://avatars.githubusercontent.com/u/1178168?v=3","account-source":"github","login":"Luckvery"},"created-at":1476118193302,"updated-at":1476118224718,"_id":"57fbc6b1e4b0709b524f052b"},{"updated-at":1538989157962,"created-at":1538989157962,"author":{"login":"cljlc","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/36645452?v=4"},"body":";; See also: Throwable->map","_id":"5bbb1c65e4b00ac801ed9eb8"}],"notes":null,"arglists":["ex"],"doc":"Returns exception data (a map) if ex is an IExceptionInfo.\n Otherwise returns nil.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/ex-data"},{"added":"1.11","ns":"clojure.core","name":"NaN?","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1698254081125,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"not=","ns":"clojure.core"},"_id":"65394d0169fbcc0c226173d6"}],"line":8214,"examples":[{"updated-at":1698253967456,"created-at":1698253967456,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":"(NaN? (Math/sqrt -1))\n;; => true\n\n(NaN? (* ##Inf 0))\n;; => true\n\n(NaN? (clojure.math/asin 2))\n;; => true\n\n(NaN? (clojure.math/acos -2))\n;; => true\n\n(NaN? (- ##Inf ##Inf))\n;; => true\n\n(NaN? (clojure.math/log -1))\n;; => true\n\n;; Note, NaN is, somewhat confusingly, a property only of numbers (floats and doubles)\n;; So even though a string is \"not a number\" it is not ##NaN…\n(NaN? \"a string\")\n;; => : java.lang.String cannot be cast to java.lang.Number…\n\n;; You'll want to use `number?` for that…\n(def actually-not-a-number? (complement number?))\n(actually-not-a-number? \"string\")\n;; => true\n\n;; But remember…\n(actually-not-a-number? ##NaN)\n;; => false","_id":"65394c8f69fbcc0c226173d5"}],"notes":null,"arglists":["num"],"doc":"Returns true if num is NaN, else false","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/NaN_q"},{"added":"1.0","ns":"clojure.core","name":"compile","file":"clojure/core.clj","type":"function","column":1,"see-alsos":null,"line":6191,"examples":[{"author":{"login":"rafmagana","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/92894?v=3"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"KyleErhabor","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/40676441?v=4"}],"body":"user=> (compile (symbol \"clojure.java.io\"))\nclojure.java.io\n\nuser=> (compile (symbol \"nonexistent.namespace\"))\nFileNotFoundException Could not locate unexistent/namespace__init.class or unexistent/namespace.clj on classpath: clojure.lang.RT.load (RT.java:432)","created-at":1406012047000,"updated-at":1635093299873,"_id":"542692d2c026201cdc326f65"},{"updated-at":1599838419576,"created-at":1599838419576,"author":{"login":"souenzzo","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/3241703?v=4"},"body":";; Using compile with deps.edn:\n{,,,\n :aliases {:aot {:main-opts [\"-e\" \"(compile,(symbol,:demo-app.main)\"]}\n :demo-app {:extra-paths [\"classes\"]\n :main-opts [\"-m\" \"demo-app.main\"]}}}\n;; :aot profile use commas and `(symbol :kw)` to avoid spliting\n\n;; Then in your build process (Dockerfile for example):\n;RUN mkdir -p classes && clojure -A:aot\n;CMD [\"clojure\", \"-A:demo-app\"]\n","_id":"5f5b98d3e4b0b1e3652d73bc"}],"notes":null,"arglists":["lib"],"doc":"Compiles the namespace named by the symbol lib into a set of\n classfiles. The source for the lib must be in a proper\n classpath-relative directory. The output files will go into the\n directory specified by *compile-path*, and that directory too must\n be in the classpath.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/compile"},{"added":"1.0","ns":"clojure.core","name":"isa?","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1302036060000,"author":{"login":"TimMc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5d532e51427ef2f4ded31aaca16c8baf?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"derive","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e89"},{"created-at":1327820991000,"author":{"login":"Chouser","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/7a0192050ed6488670acfd3f59405c10?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"instance?","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e8a"},{"created-at":1341101444000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"underive","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e8b"},{"created-at":1341101451000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"ancestors","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e8c"},{"created-at":1341101454000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"parents","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e8d"},{"created-at":1341101462000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"descendants","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e8e"},{"created-at":1341101476000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"make-hierarchy","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e8f"}],"line":5617,"examples":[{"author":{"login":"OnesimusUnbound","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2fa4c391db0d2d1744cc2cd0d787dd3d?r=PG&default=identicon"},"editors":[{"login":"Magomimmo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/dafac6cd52df3a895b8375ed6b4fe8ee?r=PG&default=identicon"}],"body":"user=> (import 'java.util.PriorityQueue)\njava.util.PriorityQueue\n\nuser=> (bases PriorityQueue)\n(java.util.AbstractQueue java.io.Serializable)\n\nuser=> (import 'java.util.AbstractQueue)\njava.util.AbstractQueue\n\nuser=> (isa? PriorityQueue AbstractQueue)\ntrue\n\nuser=> (bases AbstractQueue)\n(java.util.AbstractCollection java.util.Queue)\n\nuser=> (isa? PriorityQueue java.util.AbstractCollection)\ntrue\n\nuser=> (isa? PriorityQueue java.util.Queue)\ntrue\n\nuser=> (isa? java.util.PriorityQueue java.util.TreeMap)\nfalse","created-at":1312394065000,"updated-at":1342891952000,"_id":"542692c9c026201cdc326ae2"},{"author":{"login":"OnesimusUnbound","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2fa4c391db0d2d1744cc2cd0d787dd3d?r=PG&default=identicon"},"editors":[{"login":"Magomimmo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/dafac6cd52df3a895b8375ed6b4fe8ee?r=PG&default=identicon"}],"body":"user=> (derive ::Feline ::Animal)\nnil\nuser=> (derive ::Cat ::Feline)\nnil\n\nuser=> (derive ::Lion ::Feline)\nnil\n\nuser=> (isa? ::Lion ::Feline)\ntrue\n\nuser=> (isa? ::Lion ::Animal)\ntrue\n\nuser=> (isa? ::Tuna ::Feline)\nfalse","created-at":1313009767000,"updated-at":1342892300000,"_id":"542692c9c026201cdc326ae4"},{"updated-at":1529960051700,"created-at":1529960051700,"author":{"login":"jbswetnam","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/17225739?v=4"},"body":";; you can use vectors to test multiple child/parent pairs\n\nuser=> (derive ::child-1 ::parent-1)\nnil\n\nuser=> (derive ::child-2 ::parent-2)\nnil\n\nuser=> (isa? [::child-1 ::child-2] [::parent-1 ::parent-2])\ntrue","_id":"5b315673e4b00ac801ed9e1f"}],"notes":null,"arglists":["child parent","h child parent"],"doc":"Returns true if (= child parent), or child is directly or indirectly derived from\n parent, either via a Java type inheritance relationship or a\n relationship established via derive. h must be a hierarchy obtained\n from make-hierarchy, if not supplied defaults to the global\n hierarchy","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/isa_q"},{"added":"1.9","ns":"clojure.core","name":"boolean?","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1498919413826,"author":{"login":"vspinu","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/1363467?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"true?","ns":"clojure.core"},"_id":"5957b1f5e4b06e730307db4c"}],"line":521,"examples":[{"editors":[{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"}],"body":"(boolean? true)\n;;=> true\n(boolean? false)\n;;=> true\n(boolean? (new Boolean \"true\"))\n;;=> true\n(boolean? (new Boolean \"false\"))\n;;=> true\n\n(boolean? nil)\n;;=> false","author":{"avatar-url":"https://avatars0.githubusercontent.com/u/5004262?v=3","account-source":"github","login":"bowbahdoe"},"created-at":1491242456017,"updated-at":1496000159055,"_id":"58e28dd8e4b01f4add58fe82"}],"notes":null,"arglists":["x"],"doc":"Return true if x is a Boolean","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/boolean_q"},{"added":"1.0","ns":"clojure.core","name":"..","file":"clojure/core.clj","type":"macro","column":1,"see-alsos":[{"created-at":1509596350797,"author":{"login":"didibus","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/601540?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"->","ns":"clojure.core"},"_id":"59fa9cbee4b0a08026c48c93"},{"created-at":1528234653568,"author":{"login":"manawardhana","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/1821789?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"doto","ns":"clojure.core"},"_id":"5b17029de4b00ac801ed9e0d"}],"line":1676,"examples":[{"author":{"login":"dakrone","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bcacd00a7f05c4772329cf9f446c7987?r=PG&default=identicon"},"editors":[{"login":"OnesimusUnbound","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2fa4c391db0d2d1744cc2cd0d787dd3d?r=PG&default=identicon"}],"body":"user> (.. \"fooBAR\" (toLowerCase) (contains \"ooba\"))\ntrue\n\n;; use macroexpand to see how the form above will appear\nuser> (macroexpand '(.. \"fooBAR\" (toLowerCase) (contains \"ooba\")))\n(. (. \"fooBAR\" (toLowerCase)) (contains \"ooba\"))","created-at":1286507932000,"updated-at":1313788944000,"_id":"542692c8c026201cdc326a65"},{"updated-at":1471000821870,"created-at":1471000821870,"author":{"login":"ertugrulcetin","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8271291?v=3"},"body":"user=> (.. \"abc\" toUpperCase (equals \"ABC\"))\n;;=> true","_id":"57adb0f5e4b0bafd3e2a04ea"},{"updated-at":1509596480853,"created-at":1509596480853,"author":{"login":"didibus","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/601540?v=4"},"body":";; With .. you do not need to add a . to your method.\n(.. \"fooBAR\" (toLowerCase) (contains \"ooba\"))\n\n;; Which you do if using -> instead.\n(-> \"fooBAR\" (.toLowerCase) (.contains \"ooba\"))","_id":"59fa9d40e4b0a08026c48c94"}],"macro":true,"notes":null,"arglists":["x form","x form & more"],"doc":"form => fieldName-symbol or (instanceMethodName-symbol args*)\n\n Expands into a member access (.) of the first member on the first\n argument, followed by the next member on the result, etc. For\n instance:\n\n (.. System (getProperties) (get \"os.name\"))\n\n expands to:\n\n (. (. System (getProperties)) (get \"os.name\"))\n\n but is easier to write, read, and understand.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/_.."},{"ns":"clojure.core","name":"munge","file":"clojure/core_deftype.clj","type":"function","column":1,"see-alsos":[{"created-at":1559571481129,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"demunge","ns":"clojure.repl"},"_id":"5cf52c19e4b0ca44402ef73e"},{"created-at":1683030268272,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"namespace-munge","ns":"clojure.core"},"_id":"645100fce4b08cf8563f4ba6"}],"line":131,"examples":[{"author":{"login":"dakrone","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bcacd00a7f05c4772329cf9f446c7987?r=PG&default=identicon"},"editors":[],"body":"user> (defn foo [] (println \"foo\"))\n#'user/foo\n\nuser> foo\n#\n\nuser> (munge foo)\n\"user_DOLLARSIGN_foo_CIRCA_a0dc71\"","created-at":1293673710000,"updated-at":1293673710000,"_id":"542692c8c026201cdc3269ef"},{"editors":[{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"}],"updated-at":1683030821820,"created-at":1423016370373,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3","account-source":"github","login":"Dimagog"},"body":"(doseq [c (remove #(Character/isLetterOrDigit ^char %) (map char (range 32 127)))]\n (println c \"->\" (munge c)))\n;; Prints:\n ->\n! -> _BANG_\n\" -> _DOUBLEQUOTE_\n# -> _SHARP_\n$ -> $\n% -> _PERCENT_\n& -> _AMPERSAND_\n' -> _SINGLEQUOTE_\n( -> (\n) -> )\n* -> _STAR_\n+ -> _PLUS_\n, -> ,\n- -> _\n. -> .\n/ -> _SLASH_\n: -> _COLON_\n; -> ;\n< -> _LT_\n= -> _EQ_\n> -> _GT_\n? -> _QMARK_\n@ -> _CIRCA_\n[ -> _LBRACK_\n\\ -> _BSLASH_\n] -> _RBRACK_\n^ -> _CARET_\n_ -> _\n` -> `\n{ -> _LBRACE_\n| -> _BAR_\n} -> _RBRACE_\n~ -> _TILDE_","_id":"54d181b2e4b081e022073c4f"}],"notes":null,"arglists":["s"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core/munge"},{"added":"1.0","ns":"clojure.core","name":"delay","file":"clojure/core.clj","type":"macro","column":1,"see-alsos":[{"created-at":1342465174000,"author":{"login":"sergey","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/fbf950615302e00a14bceec914af32ca?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"force","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b78"},{"created-at":1350107212000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.core","name":"realized?","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b79"},{"created-at":1358780682000,"author":{"login":"AtKaaZ","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e10dfa345f44b0fe72bbe081fd51b83?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"memoize","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b7a"},{"created-at":1291441377000,"author":{"login":"pauldoo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5cb916d3c8abc9f45a093209e72489fb?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"future","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d7e"},{"created-at":1291473063000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"delay?","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d7f"}],"line":748,"examples":[{"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":";; In this example you can see that the first time the delay is forced\n;; the println is executed however the second dereference shows just the\n;; precomputed value.\n\nuser=> (def my-delay (delay (println \"did some work\") 100))\n#'user/my-delay\n\nuser=> @my-delay\ndid some work\n100\n\nuser=> @my-delay\n100\n","created-at":1280737965000,"updated-at":1285495988000,"_id":"542692cdc026201cdc326d44"},{"body":";; Note that the implementation of deref for delays makes it impossible for the\n;; body of the delay to be executed more than once, even if the derefs occur\n;; from multiple threads near the same time, because it is a synchronized method\n;; in Java.","author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=2"},"created-at":1415462290966,"updated-at":1415669412668,"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"_id":"545e3d92e4b0dc573b892fc0"},{"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=3"}],"body":";; test example","author":{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=3","account-source":"github","login":"zk"},"created-at":1470667496739,"updated-at":1470667534222,"_id":"57a89ae8e4b0bafd3e2a04ce"},{"updated-at":1606796544954,"created-at":1606796544954,"author":{"login":"humorless","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/3061798?v=4"},"body":";; If you are coming from OOP background, think about a OOP pattern - singleton.\n;; delay and singleton can serve the same purpose. ","_id":"5fc5c500e4b0b1e3652d7414"}],"macro":true,"notes":null,"arglists":["& body"],"doc":"Takes a body of expressions and yields a Delay object that will\n invoke the body only the first time it is forced (with force or deref/@), and\n will cache the result and return it on all subsequent force\n calls. See also - realized?","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/delay"},{"added":"1.2","ns":"clojure.core","name":"set-error-mode!","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1553641061009,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"error-handler","ns":"clojure.core"},"_id":"5c9aae65e4b0ca44402ef6de"},{"created-at":1553641085825,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"error-mode","ns":"clojure.core"},"_id":"5c9aae7de4b0ca44402ef6df"}],"line":2229,"examples":[{"updated-at":1553641014153,"created-at":1553641014153,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"body":";; The agent `:continue` processing even in case of errors. \n;; Errors are ignored and the internal state remains the same.\n;; Use when it's acceptable to miss a few messages.\n\n(def a (agent 2))\n(set-error-mode! a :continue)\n(send-off a #(/ % 0))\n@a\n;; 2\n","_id":"5c9aae36e4b0ca44402ef6dd"}],"notes":null,"arglists":["a mode-keyword"],"doc":"Sets the error-mode of agent a to mode-keyword, which must be\n either :fail or :continue. If an action being run by the agent\n throws an exception or doesn't pass the validator fn, an\n error-handler may be called (see set-error-handler!), after which,\n if the mode is :continue, the agent will continue as if neither the\n action that caused the error nor the error itself ever happened.\n \n If the mode is :fail, the agent will become failed and will stop\n accepting new 'send' and 'send-off' actions, and any previously\n queued actions will be held until a 'restart-agent'. Deref will\n still work, returning the state of the agent before the error.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/set-error-mode!"},{"added":"1.0","ns":"clojure.core","name":"re-seq","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1289192565000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"re-find","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521eb9"},{"created-at":1289192579000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"re-groups","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521eba"},{"created-at":1289192595000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"re-pattern","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ebb"},{"created-at":1289192599000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"re-matcher","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ebc"},{"created-at":1289192606000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"re-matches","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ebd"},{"created-at":1309320690000,"author":{"login":"pauldoo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5cb916d3c8abc9f45a093209e72489fb?r=PG&default=identicon"},"to-var":{"ns":"clojure.string","name":"split","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ebe"},{"created-at":1379040134000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.core","name":"subs","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ebf"}],"line":4927,"examples":[{"updated-at":1285501878000,"created-at":1279050384000,"body":"user=> (re-seq #\"\\d\" \"clojure 1.1.0\")\n(\"1\" \"1\" \"0\")\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/142529?v=3","account-source":"github","login":"nipra"},"_id":"542692cac026201cdc326b6a"},{"updated-at":1285501890000,"created-at":1279060112000,"body":";; Get a sequence of words out of a string.\nuser=> (re-seq #\"\\w+\" \"mary had a little lamb\")\n(\"mary\" \"had\" \"a\" \"little\" \"lamb\")\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/1453?v=4","account-source":"github","login":"ghoseb"},"_id":"542692cac026201cdc326b6c"},{"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"editors":[],"body":";; Parenthesized groups in the regex cause each returned match to be a\n;; vector of matched strings. See re-find for more examples.\nuser=> (def line \" RX pkts:18 err:5 drop:48\")\n#'user/line\n\nuser=> (re-seq #\"(\\S+):(\\d+)\" line)\n([\"pkts:18\" \"pkts\" \"18\"] [\"err:5\" \"err\" \"5\"] [\"drop:48\" \"drop\" \"48\"])\n","created-at":1324028413000,"updated-at":1324028413000,"_id":"542692d4c026201cdc327054"},{"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"editors":[],"body":";; Note: See clojure.core/subs for discussion of behavior of substrings\n;; holding onto references of the original strings, which can\n;; significantly affect your memory usage in some cases.","created-at":1379040138000,"updated-at":1379040138000,"_id":"542692d4c026201cdc327055"},{"editors":[{"login":"manishkumarmdb","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/9373950?v=3"}],"body":";; separate with Camel case words and digits and\n;; join with single white-space character\n\nuser=> (clojure.string/join \" \" (re-seq #\"[A-Z][a-z]+|[0-9]+\" \"ManishKumar12332\"))\n\"Manish Kumar 12332\"","author":{"avatar-url":"https://avatars.githubusercontent.com/u/9373950?v=3","account-source":"github","login":"manishkumarmdb"},"created-at":1470894996348,"updated-at":1470895041360,"_id":"57ac1394e4b0bafd3e2a04df"},{"editors":[{"login":"jeffallen","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1131456?v=4"}],"body":";; re-seq requires the string to be in memory. What if the string is in a file\n;; many GB in size? You can roll a \"line-seq of re-seq each line\" or use:\n\n(defn restream-seq\n[^java.util.regex.Pattern re ^java.io.InputStream is]\n (let [s (java.util.Scanner. is)]\n ((fn step []\n (if-let [token (.findInLine s re)]\n (cons token (lazy-seq (step)))\n (when (.hasNextLine s) (.nextLine s) (step)))))))\n\n;; first 10 digits of Pi out of the book (1M available)\n(let [pi-book \"https://www.gutenberg.org/files/50/50.txt\"]\n (with-open [is (.openStream (java.net.URL. pi-book))]\n (doall\n (sequence\n (comp cat (map str) (take 10))\n (restream-seq #\"\\d{10}\" is)))))\n; (\"1\" \"4\" \"1\" \"5\" \"9\" \"2\" \"6\" \"5\" \"3\" \"5\")","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"},"created-at":1519395370457,"updated-at":1705007052095,"_id":"5a90222ae4b0316c0f44f8ed"}],"notes":null,"arglists":["re s"],"doc":"Returns a lazy sequence of successive matches of pattern in string,\n using java.util.regex.Matcher.find(), each such match processed with\n re-groups.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/re-seq"},{"added":"1.0","ns":"clojure.core","name":"char?","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1321310793000,"author":{"login":"mmwaikar","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/29d36f4c9f39c9f8ff61c07033b13118?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"char","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b4e"}],"line":155,"examples":[{"author":{"login":"mattdw","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/ee24aacb65359196b0a1bad050f9a62f?r=PG&default=identicon"},"editors":[{"login":"philos99","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1de5617efb013ca7c9cf8e5646818ffa?r=PG&default=identicon"}],"body":"user=> (char? \\a)\ntrue\n\nuser=> (char? 22)\nfalse\n\nuser=> (char? \"a\")\nfalse\n\nuser=> (char? (first \"abc\"))\ntrue","created-at":1280322160000,"updated-at":1317219140000,"_id":"542692c9c026201cdc326a8d"}],"notes":null,"arglists":["x"],"doc":"Return true if x is a Character","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/char_q"},{"added":"1.0","ns":"clojure.core","name":"make-hierarchy","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1324008864000,"author":{"login":"stand","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d7f9ed2753f8b3517f1539f6129f0a17?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"isa?","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b84"},{"created-at":1332885418000,"author":{"login":"luskwater","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/f3b2650c3d4aa47c9e22bf9ba5596a9f?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"derive","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b85"},{"created-at":1341101551000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"underive","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b86"},{"created-at":1341101555000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"parents","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b87"},{"created-at":1341101559000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"descendants","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b88"},{"created-at":1341101563000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"ancestors","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b89"}],"line":5581,"examples":[{"author":{"login":"shockbob","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon"},"editors":[],"body":";; use make-hierarchy to build your own local hierarchy for derive, isa?, etc. \n;; instead of using the global hierarchy\n;; note that the first ancestors call returns a nil since that type does not \n;; exist in the global hierarchy\n\nuser=> (def h (make-hierarchy))\n#'user/h\nuser=> (def h (derive h ::rect ::shape))\n#'user/h\nuser=> (def h (derive h ::square ::rect))\n#'user/h\nuser=> h\n{:parents {:user/square #{:user/rect}, :user/rect #{:user/shape}}, :ancestors {:\nuser/square #{:user/shape :user/rect}, :user/rect #{:user/shape}}, :descendants\n{:user/rect #{:user/square}, :user/shape #{:user/square :user/rect}}}\nuser=> (ancestors ::square)\nnil\nuser=> (ancestors h ::square)\n#{:user/shape :user/rect}\nuser=>","created-at":1313896274000,"updated-at":1313896274000,"_id":"542692c8c026201cdc326a17"},{"editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/889685?v=3","account-source":"github","login":"huahaiy"},{"avatar-url":"https://avatars.githubusercontent.com/u/331939?v=3","account-source":"github","login":"arr-ee"},{"login":"cloojure","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/7083783?v=4"}],"updated-at":1604524760718,"created-at":1418345729815,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/889685?v=3","account-source":"github","login":"huahaiy"},"body":"; the above hierarchy can be built together with a thread macro:\n\n(ns demo.core\n (:require [clojure.pprint :refer [pprint]]))\n\n(defn shapes-hierarchy []\n (-> (make-hierarchy)\n (derive ::rect ::shape)\n (derive ::square ::rect)))\n\n(defn -main [& args]\n (pprint (shapes-hierarchy)))\n\n;-------------------------------------------------------\n; result (Clojure 1.10.2-alpha1 + Java 15)\n\n {:parents #:demo.core{:rect #{:demo.core/shape},\n :square #{:demo.core/rect}},\n :ancestors #:demo.core{:rect #{:demo.core/shape},\n :square #{:demo.core/rect :demo.core/shape}},\n :descendants #:demo.core{:shape #{:demo.core/rect :demo.core/square},\n :rect #{:demo.core/square}}}\n","_id":"548a3d01e4b04e93c519ffa5"},{"updated-at":1516316641016,"created-at":1516315086236,"author":{"login":"fmnoise","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/4033391?v=4"},"body":";; hierarchy can be stored in atom for more flexibility\n(def service-types (atom (make-hierarchy)))\n\n(defn add-local! [service-type]\n (swap! service-types derive service-type ::local)\n\n(defn add-remote! [service-type]\n (swap! service-types derive service-type ::remote)\n\n(defmulti connect :service-type :hierarchy service-types)\n(defmethod connect ::remote [service] \"Connecting to remote service\")\n(defmethod connect ::local [service] \"Connecting to local service\")\n \n(add-remote! ::rest)\n(add-local! ::com+)\n\n(connect {:service-type ::rest}) \n;; => \"Connecting to remote service\"\n\n(connect {:service-type ::com+}) \n;; => \"Connecting to local service\"","editors":[{"avatar-url":"https://avatars2.githubusercontent.com/u/4033391?v=4","account-source":"github","login":"fmnoise"}],"_id":"5a6121cee4b0a08026c48d00"}],"notes":null,"arglists":[""],"doc":"Creates a hierarchy object for use with derive, isa? etc.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/make-hierarchy"},{"added":"1.5","ns":"clojure.core","name":"set-agent-send-executor!","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1553631443978,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"set-agent-send-off-executor!","ns":"clojure.core"},"_id":"5c9a88d3e4b0ca44402ef6d6"},{"created-at":1553631454256,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"send-via","ns":"clojure.core"},"_id":"5c9a88dee4b0ca44402ef6d7"},{"created-at":1559240484735,"author":{"login":"pdbrown","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/1607096?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"shutdown-agents","ns":"clojure.core"},"_id":"5cf01f24e4b0ca44402ef739"}],"line":2106,"examples":[{"updated-at":1553631431158,"created-at":1553631366167,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"body":";; This permanently change the thread pool used\n;; by agents receiving tasks with \"send\"\n(import '[java.util.concurrent Executors])\n(def fj-pool (Executors/newWorkStealingPool 20))\n(set-agent-send-executor! fj-pool)","editors":[{"avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"}],"_id":"5c9a8886e4b0ca44402ef6d3"}],"notes":null,"arglists":["executor"],"doc":"Sets the ExecutorService to be used by send","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/set-agent-send-executor!"},{"added":"1.9","ns":"clojure.core","name":"swap-vals!","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1527705116275,"author":{"login":"agarman","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/138454?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"swap!","ns":"clojure.core"},"_id":"5b0eee1ce4b045c27b7fac80"},{"created-at":1527705122171,"author":{"login":"agarman","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/138454?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"reset!","ns":"clojure.core"},"_id":"5b0eee22e4b045c27b7fac81"},{"created-at":1527705131382,"author":{"login":"agarman","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/138454?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"compare-and-set!","ns":"clojure.core"},"_id":"5b0eee2be4b045c27b7fac82"},{"created-at":1527705150896,"author":{"login":"agarman","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/138454?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"atom","ns":"clojure.core"},"_id":"5b0eee3ee4b045c27b7fac83"},{"created-at":1699735269568,"author":{"login":"mars0i","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1836941?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"pop!","ns":"clojure.core"},"_id":"654fe6e569fbcc0c2261744c"},{"created-at":1699735291408,"author":{"login":"mars0i","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1836941?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"peek","ns":"clojure.core"},"_id":"654fe6fb69fbcc0c2261744d"},{"created-at":1699735313134,"author":{"login":"mars0i","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1836941?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"pop","ns":"clojure.core"},"_id":"654fe71169fbcc0c2261744e"},{"created-at":1722240810813,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"reset-vals!","ns":"clojure.core"},"_id":"66a74f2a69fbcc0c226174e5"}],"line":2374,"examples":[{"updated-at":1519158674293,"created-at":1519158674293,"author":{"login":"dane-johnson","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/10768827?v=4"},"body":";; You can use `swap-vals` to perform an atomic `deref`\n;; and `swap!` without a race condition.\n\n(def queue (atom '(1 2 3)))\n(let [head (ffirst (swap-vals! queue pop))]\n (println head) ;; 1\n (println @queue)) ;; (2 3)","_id":"5a8c8592e4b0316c0f44f8d7"}],"notes":null,"arglists":["atom f","atom f x","atom f x y","atom f x y & args"],"doc":"Atomically swaps the value of atom to be:\n (apply f current-value-of-atom args). Note that f may be called\n multiple times, and thus should be free of side effects.\n Returns [old new], the value of the atom before and after the swap.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/swap-vals!"},{"added":"1.2","ns":"clojure.core","name":"keep","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1337189081000,"author":{"login":"SoniaH","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/56a007a4b2c47b141bd39790278f88a7?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"keep-indexed","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c71"},{"created-at":1399907394000,"author":{"login":"ryo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3f7913b563c72083c74030d928ba407e?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"map","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c72"},{"created-at":1399907399000,"author":{"login":"ryo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3f7913b563c72083c74030d928ba407e?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"filter","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c73"},{"created-at":1549573085436,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"remove","ns":"clojure.core"},"_id":"5c5c9bdde4b0ca44402ef663"}],"line":7505,"examples":[{"author":{"login":"dpritchett","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/147981?v=3"},"editors":[{"login":"yasuto","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cacfb7ecf08cb6461767e514c93b7bf9?r=PG&default=identicon"},{"login":"yasuto","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cacfb7ecf08cb6461767e514c93b7bf9?r=PG&default=identicon"},{"login":"miner","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/25400?v=3"}],"body":"(keep even? (range 1 10))\n;;=> (false true false true false true false true false)\n","created-at":1279071510000,"updated-at":1419105723874,"_id":"542692cfc026201cdc326e7f"},{"author":{"login":"yasuto","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cacfb7ecf08cb6461767e514c93b7bf9?r=PG&default=identicon"},"editors":[{"login":"yasuto","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cacfb7ecf08cb6461767e514c93b7bf9?r=PG&default=identicon"},{"login":"yasuto","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cacfb7ecf08cb6461767e514c93b7bf9?r=PG&default=identicon"},{"login":"yasuto","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cacfb7ecf08cb6461767e514c93b7bf9?r=PG&default=identicon"},{"login":"miner","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/25400?v=3"},{"avatar-url":"https://avatars.githubusercontent.com/u/889685?v=3","account-source":"github","login":"huahaiy"},{"login":"cstml","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/29694576?v=4"}],"body":";; comparisons among keep, filter, map and for.\n\n(keep #(when (odd? %) %) (range 10))\n;;=> (1 3 5 7 9)\n\n(map #(when (odd? %) %) (range 10))\n;;=> (nil 1 nil 3 nil 5 nil 7 nil 9)\n\n(for [ x (range 10) :when (odd? x)] x)\n;;=> (1 3 5 7 9)\n\n(filter odd? (range 10))\n;;=> (1 3 5 7 9)","created-at":1306319295000,"updated-at":1704910773103,"_id":"542692cfc026201cdc326e82"},{"author":{"login":"yasuto","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cacfb7ecf08cb6461767e514c93b7bf9?r=PG&default=identicon"},"editors":[{"login":"yasuto","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cacfb7ecf08cb6461767e514c93b7bf9?r=PG&default=identicon"},{"login":"yasuto","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cacfb7ecf08cb6461767e514c93b7bf9?r=PG&default=identicon"},{"login":"yasuto","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cacfb7ecf08cb6461767e514c93b7bf9?r=PG&default=identicon"},{"login":"yasuto","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cacfb7ecf08cb6461767e514c93b7bf9?r=PG&default=identicon"},{"login":"yasuto","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cacfb7ecf08cb6461767e514c93b7bf9?r=PG&default=identicon"},{"login":"miner","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/25400?v=3"}],"body":";; Sieve of Eratosthenes by using 'keep'.\n\n(defn keep-mcdr [f coll]\n (lazy-seq\n (when-let [x (first coll)]\n (cons x (keep-mcdr f (f x (rest coll)))))))\n\n(defn prime-number [n]\n (cons 1\n\t(keep-mcdr\n\t (fn[x xs] (if (not-empty xs)\n\t\t (keep #(if-not (zero? (rem % x)) %)\n\t\t\t xs)))\n\t (range 2 n))))\n\n(prime-number 100)\n;;=> (1 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97)\n","created-at":1306319303000,"updated-at":1419105742633,"_id":"542692cfc026201cdc326e86"},{"body":"(keep seq [() [] '(1 2 3) [:a :b] nil])\n;;=> ((1 2 3) (:a :b))","author":{"login":"miner","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/25400?v=3"},"created-at":1419105688396,"updated-at":1419105688396,"_id":"5495d598e4b09260f767ca7b"},{"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=3"}],"updated-at":1445895401925,"created-at":1428277632781,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/466333?v=3","account-source":"github","login":"num1"},"body":";; `keep` is useful with maps:\n\n(keep {:a 1, :b 2, :c 3} [:a :b :d])\n;;=> (1 2)\n","_id":"5521c980e4b0b96203a0d59d"},{"body":";; A set will work as a predicate for another set.\n(keep #{0 1 2 3} #{2 3 4 5})\n;;=> (3 2)","author":{"login":"dkinzer","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/444215?v=3"},"created-at":1434506225681,"updated-at":1434506225681,"_id":"5580d3f1e4b01ad59b65f4ff"},{"updated-at":1473382005602,"created-at":1473382005602,"author":{"login":"huahaiy","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/889685?v=3"},"body":";; keep returns the results of predicates, \n;; filter returns the original values of collection\n\n(keep (fn [[k _]] (#{:a :b} k)) {:a 1 :b 2 :c 3})\n;;=> (:a :b)\n\n(filter (fn [[k _]] (#{:a :b} k)) {:a 1 :b 2 :c 3})\n;;=> ([:a 1] [:b 2])","_id":"57d20675e4b0709b524f04f0"},{"updated-at":1590766979030,"created-at":1590766721487,"author":{"login":"blue0513","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/8979468?v=4"},"body":";; keep rejects nil from results\n\n(keep #(when (number? %) %) [1 \"a\" 2 \"c\"])\n;; => (1 2)\n\n(map #(when (number? %) %) [1 \"a\" 2 \"c\"])\n;; => (1 nil 2 nil)\n\n(remove nil? (map #(when (number? %) %) [1 \"a\" 2 \"c\"]))\n;; => (1 2)","editors":[{"avatar-url":"https://avatars1.githubusercontent.com/u/8979468?v=4","account-source":"github","login":"blue0513"}],"_id":"5ed12c81e4b087629b5a191d"}],"notes":[{"body":"Note the difference between `filter` and `keep`. `filter` returns the original items in a collection that satisfy the predicate. `keep` returns the non-nil *results* of the given function.","created-at":1419105930894,"updated-at":1419105930894,"author":{"login":"miner","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/25400?v=3"},"_id":"5495d68ae4b09260f767ca7c"},{"body":"`keep` is like a `map` that filters out `nil` values produced by `f` and could be defined as:\n
\n(def my-keep (comp (partial remove nil?) map))\n
\nor, perhaps more traditionally:\n
\n\n(defn my-keep [& args]\n  (remove nil? (apply map args)))\n
\n","created-at":1422938659514,"updated-at":1422939155762,"author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"_id":"54d05223e4b0e2ac61831cfa"},{"author":{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"},"updated-at":1530020021260,"created-at":1530020021260,"body":"Note that, unlike `map`, `keep` doesn’t accept multiple collections:\n\n```clojure\n(filter identity (map get [{:a 1} {:b 2} {:d 3}] [:a :b :c]))\n; => (1 2)\n\n(keep get [{:a 1} {:b 2} {:d 3}] [:a :b :c])\n; => ArityException Wrong number of args (3) passed to: core/keep\n```","_id":"5b3240b5e4b00ac801ed9e20"},{"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"updated-at":1582729216279,"created-at":1582729216279,"body":"It's useful to consider `filter` and `remove` as a pair of complementary/similar functions that both return the original items, whereas `keep` is rather specialized/different.","_id":"5e568800e4b087629b5a18a9"}],"arglists":["f","f coll"],"doc":"Returns a lazy sequence of the non-nil results of (f item). Note,\n this means false return values will be included. f must be free of\n side-effects. Returns a transducer when no collection is provided.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/keep"},{"added":"1.1","ns":"clojure.core","name":"char","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1321310785000,"author":{"login":"mmwaikar","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/29d36f4c9f39c9f8ff61c07033b13118?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"char?","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b80"},{"created-at":1333595214000,"author":{"login":"Ljos","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/45b996a79abca465acaf6c0f10b0437?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"int","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b81"},{"to-var":{"library-url":"https://github.com/clojure/clojure","name":"chars","ns":"clojure.core"},"author":{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},"created-at":1342917303000,"_id":"542692eaf6e94c6970521b82"},{"to-var":{"library-url":"https://github.com/clojure/clojure","name":"char-array","ns":"clojure.core"},"author":{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},"created-at":1342917307000,"_id":"542692eaf6e94c6970521b83"}],"line":3536,"examples":[{"author":{"login":"mattdw","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/ee24aacb65359196b0a1bad050f9a62f?r=PG&default=identicon"},"editors":[{"login":"philos99","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1de5617efb013ca7c9cf8e5646818ffa?r=PG&default=identicon"}],"body":";; can coerce an int (or similar)\nuser=> (char 97)\n\\a\n\n;; a byte can be coerced to a char\nuser=> (let [bytes-array (.getBytes \"abc\")]\n (char (first bytes-array)))\n\\a\n\n;; char is just a function\nuser=> (map char [65 66 67 68])\n(\\A \\B \\C \\D)","created-at":1280322589000,"updated-at":1317219055000,"_id":"542692cdc026201cdc326d01"},{"updated-at":1444162460695,"created-at":1444162460695,"author":{"login":"teymuri","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/13352033?v=3"},"body":"(->> [67 108 111 106 117 114 101]\n (map char)\n (apply str))\n\n\"Clojure\"","_id":"56142b9ce4b084e61c76ecbd"},{"updated-at":1562515072023,"created-at":1562515072023,"author":{"login":"loeschzwerg","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/24317401?v=4"},"body":";; backslash\nuser=> (char 92)\n\\\\\n\n;; String madness:\nuser=> (map str [\\n \\newline \\\\])\n[\"n\" \"\\n\" \"\\\\\"]\n\n;; convert back to int:\nuser=> (int \\\\)\n92\n\n;; whoops! this will expect additional input because it char's the bracket\nuser=> (char \\)\n #=> \n\n;; don't you dare this!\nuser=> (char \\ )\n\\space\n\n;; make it readable\nuser=> (char \\space)\n\\space\n\n;; it gets uglier! Mark the text to see the difference\nuser=> \\\n #=>\n\nuser=> \\ \n\\space\n\n;; MaDnEsS!1!\nuser=> \\\\\\\\\\\\\\\\\n\\\\\n\\\\\n\\\\\n\\\\","_id":"5d221680e4b0ca44402ef77e"},{"updated-at":1575989957857,"created-at":1575989957857,"author":{"login":"vladkotu","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/389119?v=4"},"body":";; string to code round trip\n;; input string\n(def in-string \"鬼\")\n;; single char from string\n(def in-char (.charAt in-string 0)) ;;=> \\鬼\n;; code from char\n(def code (int in-char)) ;;=> 39740\n;; char from code\n(def out-char (char code)) ;;=> \\鬼\n;; back to input string\n(def out-string (str out-char)) ;;=> \"鬼\"\n","_id":"5defb2c5e4b0ca44402ef7f5"},{"updated-at":1674282378834,"created-at":1674282378834,"author":{"login":"mars0i","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1836941?v=4"},"body":"(defn u-sub-char\n \"If n is a single-digit integer in [0, ..., 9], returns the\n Unicode supscript character for n. Returns nil for other numbers.\"\n [n]\n (if (and (>= n 0) (<= n 9))\n (char (+ 0x2080 n))\n nil))","_id":"63cb858ae4b08cf8563f4b68"}],"notes":null,"arglists":["x"],"doc":"Coerce to char","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/char"},{"added":"1.0","ns":"clojure.core","name":"mapcat","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1294988622000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"map","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cb4"},{"created-at":1294988628000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"concat","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cb5"},{"created-at":1580338264619,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"flatten","ns":"clojure.core"},"_id":"5e320c58e4b0ca44402ef827"}],"line":2800,"examples":[{"updated-at":1285501773000,"created-at":1279063141000,"body":"user=> (mapcat reverse [[3 2 1 0] [6 5 4] [9 8 7]])\n(0 1 2 3 4 5 6 7 8 9)\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/142529?v=3","account-source":"github","login":"nipra"},"_id":"542692cac026201cdc326b36"},{"updated-at":1337333286000,"created-at":1337333286000,"body":"user=> (mapcat (fn [[k v]] \n (for [[k2 v2] v] \n (concat [k k2] v2)))\n '{:a {:x (1 2) :y (3 4)}\n :b {:x (1 2) :z (5 6)}})\n\n((:a :x 1 2) (:a :y 3 4) (:b :x 1 2) (:b :z 5 6))","editors":[],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3","account-source":"github","login":"devn"},"_id":"542692d4c026201cdc327006"},{"author":{"login":"uvtc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/34f159f89cbd1d9beac0276f5a7af552?r=PG&default=identicon"},"editors":[{"login":"uvtc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/34f159f89cbd1d9beac0276f5a7af552?r=PG&default=identicon"}],"body":"user=> (require '[clojure.string :as cs])\nnil\n\n;; Suppose you have a fn in a `map` that itself returns\n;; multiple values.\nuser=> (map #(cs/split % #\"\\d\") [\"aa1bb\" \"cc2dd\" \"ee3ff\"])\n([\"aa\" \"bb\"] [\"cc\" \"dd\"] [\"ee\" \"ff\"])\n\n;; Now, if you want to concat them all together, you *could*\n;; do this:\nuser=> (apply concat (map #(cs/split % #\"\\d\") [\"aa1bb\" \"cc2dd\" \"ee3ff\"]))\n(\"aa\" \"bb\" \"cc\" \"dd\" \"ee\" \"ff\")\n\n;; But `mapcat` can save you a step:\nuser=> (mapcat #(cs/split % #\"\\d\") [\"aa1bb\" \"cc2dd\" \"ee3ff\"])\n(\"aa\" \"bb\" \"cc\" \"dd\" \"ee\" \"ff\")\n","created-at":1340097786000,"updated-at":1340099694000,"_id":"542692d4c026201cdc327007"},{"author":{"login":"uvtc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/34f159f89cbd1d9beac0276f5a7af552?r=PG&default=identicon"},"editors":[],"body":";; Suppose you've got a function that takes a value\n;; and returns a list of things from it, for example:\n(defn f1\n [n]\n [(- n 1) n (+ n 1)])\n\n(f1 1)\n;=> [0 1 2]\n\n;; Perhaps you'd like to map it onto each item in a collection:\n(map f1 [1 2 3])\n;=> ([0 1 2] [1 2 3] [2 3 4])\n\n;; But suppose you wanted them all concatenated? You could do this:\n(apply concat (map f1 [1 2 3]))\n;=> (0 1 2 1 2 3 2 3 4)\n\n;; Or you could get the same thing with `mapcat`:\n(mapcat f1 [1 2 3])\n;=> (0 1 2 1 2 3 2 3 4)\n","created-at":1343650918000,"updated-at":1343650918000,"_id":"542692d4c026201cdc327009"},{"author":{"login":"devth","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/70c7535cbb9fea0353250a4edda155be?r=PG&default=identicon"},"editors":[],"body":"; Flatten a map, consing keys on to each nested vector \n(mapcat (fn [[k vs]] (map (partial cons k) vs)) {:foo [[1 2] [3 2]] :bar [[3 1]]})\n;=> ((:foo 1 2) (:foo 3 2) (:bar 3 1))\n","created-at":1357801138000,"updated-at":1357801138000,"_id":"542692d4c026201cdc32700a"},{"body":";; A very useful feature of mapcat is that it allows function f to produce no result\n;; by returning nil or an empty collection:\n(mapcat #(remove even? %) [[1 2] [2 2] [2 3]])\n;; => (1 3)\n\n;; note that applying (remove even?) to [2 2] produced () which was \"eaten\"\n;; and ignored by mapcat.","author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"created-at":1423014103873,"updated-at":1423014118164,"editors":[{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"}],"_id":"54d178d7e4b081e022073c4d"},{"updated-at":1505377247866,"created-at":1505377247866,"author":{"login":"buzzdan","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/18007791?v=4"},"body":";; map vs. mapcat -\n;; For duplicating each item in a sequence\n\n;; Using map:\n(map #(repeat 2 %) [1 2])\n;; => ((1 1) (2 2))\n\n;; Using mapcat:\n(mapcat #(repeat 2 %) [1 2])\n;; => (1 1 2 2)\n","_id":"59ba3bdfe4b09f63b945ac75"},{"updated-at":1557893179267,"created-at":1557893179267,"author":{"login":"humorless","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/3061798?v=4"},"body":";; I think it is cool to use juxt together with mapcat\n;; mapcat requires element to be collection and the result of juxt will be collection. \n\n(mapcat (juxt inc dec) [1 2 3 4])\n;; => (2 0 3 1 4 2 5 3)","_id":"5cdb903be4b0ca44402ef724"},{"updated-at":1559995255249,"created-at":1559995255249,"author":{"login":"sodesu99","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/31072774?v=4"},"body":";;(mapcat f & colls)\n(mapcat list [:a :b :c] [1 2 3])\n;;=> (:a 1 :b 2 :c 3)","_id":"5cfba377e4b0ca44402ef750"}],"notes":[{"body":"
\n;; mapcat always evaluates the first 4 arguments.\n(def a (mapcat range (map #(do (print \".\") %) (into () (range 10)))))\n;; ....\n\n;; it can be solved avoiding 'apply' to handle varargs\n(defn mapcat* [f & colls]\n  (letfn [(step [colls]\n            (lazy-seq\n              (when-first [c colls]\n                (concat c (step (rest colls))))))]\n    (step (apply map f colls))))\n\n(def a (mapcat* range (map #(do (print \".\") %) (into () (range 10)))))\n;; nothing prints\n
","created-at":1521801795650,"updated-at":1521801813945,"author":{"avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"},"_id":"5ab4da43e4b045c27b7fac1f"}],"arglists":["f","f & colls"],"doc":"Returns the result of applying concat to the result of applying map\n to f and colls. Thus function f should return a collection. Returns\n a transducer when no collections are provided","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/mapcat"},{"added":"1.3","ns":"clojure.core","name":"unchecked-long","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1496088171964,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"long","ns":"clojure.core"},"_id":"592c7e6be4b093ada4d4d79b"}],"line":3566,"examples":[{"updated-at":1496088165852,"created-at":1496088165852,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"body":"(unchecked-long 1)\n;;=> 1\n(unchecked-long 1N)\n;;=> 1\n(unchecked-long 1.1)\n;;=> 1\n(unchecked-long 1.9)\n;;=> 1\n(unchecked-long 5/3)\n;;=> 1\n\n(unchecked-long -1)\n;;=> -1\n(unchecked-long -1N)\n;;=> -1\n(unchecked-long -1.1)\n;;=> -1\n(unchecked-long -1.9)\n;;=> -1\n(unchecked-long -5/3)\n;;=> -1\n\n;;;; Note that (unchecked-long) does not range check its argument\n;;;; so integer overflow or rounding may occur. \n;;;; Use (long) if you want to throw an exception in such cases.\n\n(unchecked-long 9223372036854775808N)\n;;=> -9223372036854775808\n(unchecked-long -9223372036854775809N)\n;;=> 9223372036854775807\n\n(long 9223372036854775808N)\n;;=> IllegalArgumentException Value out of range for long: 922337203685477580\n(long -9223372036854775809N)\n;;=> IllegalArgumentException Value out of range for long: -9223372036854775809\n\n(unchecked-long 1.0E18)\n;;=> 1000000000000000000\n(unchecked-long 1.0E19)\n;;=> 9223372036854775807\n(unchecked-long 1.0E20)\n;;=> 9223372036854775807\n\n(long 1.0E18)\n;;=> 1000000000000000000\n(long 1.0E19)\n;;=> IllegalArgumentException Value out of range for long: 1.0E19\n(long 1.0E20)\n;;=> IllegalArgumentException Value out of range for long: 1.0E20","_id":"592c7e65e4b093ada4d4d79a"}],"notes":null,"arglists":["x"],"doc":"Coerce to long. Subject to rounding or truncation.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/unchecked-long"},{"added":"1.0","ns":"clojure.core","name":"aset-long","file":"clojure/core.clj","type":"function","column":1,"see-alsos":null,"line":3977,"examples":[{"author":{"login":"shockbob","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon"},"editors":[],"body":";; create an array of 10 longs and set one of the values to 31415\n\nuser=> (def ls (long-array 10))\n#'user/ls\nuser=> (vec ls)\n[0 0 0 0 0 0 0 0 0 0]\nuser=> (aset-long ls 3 31415)\n31415\nuser=> (vec ls)\n[0 0 0 31415 0 0 0 0 0 0]\nuser=>","created-at":1313915173000,"updated-at":1313915173000,"_id":"542692cec026201cdc326d8a"}],"notes":[{"body":"See [aset](http://clojuredocs.org/clojure.core/aset) for illustrations of multi-dimensional syntax.","created-at":1432829151791,"updated-at":1432829151791,"author":{"login":"mars0i","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1836941?v=3"},"_id":"55673cdfe4b01ad59b65f4df"}],"arglists":["array idx val","array idx idx2 & idxv"],"doc":"Sets the value at the index/indices. Works on arrays of long. Returns val.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/aset-long"},{"added":"1.6","ns":"clojure.core","name":"some?","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1431460708707,"author":{"login":"mmavko","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1064539?v=3"},"to-var":{"ns":"clojure.core","name":"nil?","library-url":"https://github.com/clojure/clojure"},"_id":"55525b64e4b03e2132e7d160"},{"created-at":1434787747213,"author":{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/94482?v=3"},"to-var":{"ns":"clojure.core","name":"some","library-url":"https://github.com/clojure/clojure"},"_id":"55851fa3e4b05f167dcf233f"}],"line":533,"examples":[{"editors":[{"login":"klimenko-serj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2082879?v=3"}],"body":"user> (some? nil)\n;; => false\n\nuser> (some? 42)\n;; => true\nuser> (some? false)\n;; => true\nuser> (some? [])\n;; => true\nuser> (some? {})\n;; => true\nuser> (some? '())\n;; => true","author":{"avatar-url":"https://avatars.githubusercontent.com/u/2082879?v=3","account-source":"github","login":"klimenko-serj"},"created-at":1438944110688,"updated-at":1438944205513,"_id":"55c48b6ee4b0080a1b79cdb7"},{"updated-at":1514328933133,"created-at":1514328933133,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"},"body":";; equivalent to implementing not-nil?\n(some? :kw)\n;; => true\n(not (nil? :kw))\n;; => true\n\n(some? nil)\n;; => false\n(not (nil? nil))\n;; => false","_id":"5a42d365e4b0a08026c48cda"},{"updated-at":1719752674225,"created-at":1719752674225,"author":{"login":"surferHalo","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/11332464?v=4"},"body":";; good companion with \"some\" if you want boolean return\n\n(some #{1 2 3} [4])\n;; => nil\n(some? (some #{1 2 3} [4]))\n;; => false\n\n(some #{1 2 3} [1])\n;; => 1\n(some? (some #{1 2 3} [1]))\n;; => true","_id":"668157e269fbcc0c226174da"},{"updated-at":1722802000534,"created-at":1722802000534,"author":{"login":"jacoobes","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/76754747?v=4"},"body":"(some? 0)\n;; => true","_id":"66afdf5069fbcc0c226174e7"}],"notes":null,"tag":"java.lang.Boolean","arglists":["x"],"doc":"Returns true if x is not nil, false otherwise.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/some_q"},{"added":"1.0","ns":"clojure.core","name":"unchecked-negate","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1289217312000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"unchecked-add","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c21"},{"created-at":1289217314000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"unchecked-dec","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c22"},{"created-at":1289217316000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"unchecked-inc","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c23"},{"created-at":1289217318000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"unchecked-negate","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c24"},{"created-at":1289217321000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"unchecked-divide","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c25"},{"created-at":1289217324000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"unchecked-subtract","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c26"},{"created-at":1289217326000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"unchecked-multiply","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c27"},{"created-at":1289217329000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"unchecked-remainder","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c28"},{"created-at":1423522476536,"author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"to-var":{"ns":"clojure.core","name":"-","library-url":"https://github.com/clojure/clojure"},"_id":"54d93aace4b0e2ac61831d32"}],"line":1198,"examples":[{"editors":[{"login":"reborg","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/20086?v=3"}],"body":";; *Almost* always the same as \"-\"\nuser=> (= (- 2) (unchecked-negate 2))\ntrue\nuser=> (= (- (Long/MAX_VALUE)) (unchecked-negate (Long/MAX_VALUE)))\ntrue\n\n;; Except when it's not, because (- (Long/MIN_VALUE)) overflows:\nuser=> (= (- (Long/MIN_VALUE)) (unchecked-negate (Long/MIN_VALUE)))\nArithmeticException integer overflow clojure.lang.Numbers.throwIntOverflow (Numbers.java:1501)\n\n;; Indeed:\nuser=> (unchecked-negate (Long/MIN_VALUE))\n-9223372036854775808\n\n;; Careful!\nuser=> (= (Long/MIN_VALUE) (unchecked-negate (Long/MIN_VALUE)))\ntrue","author":{"avatar-url":"https://avatars.githubusercontent.com/u/20086?v=3","account-source":"github","login":"reborg"},"created-at":1458063308020,"updated-at":1458063919478,"_id":"56e847cce4b0b41f39d96ce4"}],"notes":null,"arglists":["x"],"doc":"Returns the negation of x, a long.\n Note - uses a primitive operator subject to overflow.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/unchecked-negate"},{"added":"1.10","ns":"clojure.core","name":"remove-tap","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1590688377580,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/109629?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"tap>","ns":"clojure.core"},"_id":"5ecffa79e4b087629b5a191a"},{"created-at":1590688383018,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/109629?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"add-tap","ns":"clojure.core"},"_id":"5ecffa7fe4b087629b5a191b"}],"line":8117,"examples":null,"notes":null,"arglists":["f"],"doc":"Remove f from the tap set.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/remove-tap"},{"added":"1.0","ns":"clojure.core","name":"gen-interface","file":"clojure/genclass.clj","type":"macro","column":1,"see-alsos":[{"created-at":1360270679000,"author":{"login":"AtKaaZ","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e10dfa345f44b0fe72bbe081fd51b83?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"proxy","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521dbf"},{"created-at":1360270682000,"author":{"login":"AtKaaZ","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e10dfa345f44b0fe72bbe081fd51b83?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"gen-class","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521dc0"}],"line":700,"examples":[{"updated-at":1542284408999,"created-at":1542284408999,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"body":";; gen-interface defines the class in memory, but does not spit it to disk\n;; (unless AOT-ing). Note: this is different from gen-class (that actually does\n;; nothing unless it's AOT compiling).\n\n(gen-interface :name \"user.IFoo\" :extends [clojure.lang.IPersistentMap])\n;; user.IFoo\n\n(reify user.IFoo (seq [_]) (empty [_]))\n;; {}","_id":"5bed6478e4b00ac801ed9efa"}],"macro":true,"notes":null,"arglists":["& options"],"doc":"When compiling, generates compiled bytecode for an interface with\n the given package-qualified :name (which, as all names in these\n parameters, can be a string or symbol), and writes the .class file\n to the *compile-path* directory. When not compiling, does nothing.\n \n In all subsequent sections taking types, the primitive types can be\n referred to by their Java names (int, float etc), and classes in the\n java.lang package can be used without a package qualifier. All other\n classes must be fully qualified.\n \n Options should be a set of key/value pairs, all except for :name are\n optional:\n\n :name aname\n\n The package-qualified name of the class to be generated\n\n :extends [interface ...]\n\n One or more interfaces, which will be extended by this interface.\n\n :methods [ [name [param-types] return-type], ...]\n\n This parameter is used to specify the signatures of the methods of\n the generated interface. Do not repeat superinterface signatures\n here.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/gen-interface"},{"added":"1.0","ns":"clojure.core","name":"*command-line-args*","type":"var","see-alsos":null,"examples":[{"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"editors":[],"body":";; If you save this program as showargs.clj on a Unix-like system, then the\n;; following command will produce the output shown.\n\n;; % java -classpath clojure-1.2.0.jar clojure.main showargs.clj arg1 2 \"whitespace in most command shells if you quote\"\n;; arg='arg1'\n;; arg='2'\n;; arg='whitespace in most command shells if you quote'\n;; \n;; \n;; Second arg is string 2, not number 2.\n\n(ns com.demo.showargs)\n\n(doseq [arg *command-line-args*]\n (printf \"arg='%s'\\n\" arg))\n\n(if (= \"2\" (second *command-line-args*))\n (println \"\\n\\nSecond arg is string 2, not number 2.\"))\n","created-at":1298557801000,"updated-at":1298557801000,"_id":"542692c8c026201cdc326a6a"}],"notes":[{"body":"To see which JVM command line parameters were used to start Clojure, execute:\n```\n(into [] (.getInputArguments\n (java.lang.management.ManagementFactory/getRuntimeMXBean)))\n```","created-at":1647721826905,"updated-at":1647721856269,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/1836941?v=4","account-source":"github","login":"mars0i"},"_id":"62363d62e4b0b1e3652d75c0"}],"arglists":[],"doc":"A sequence of the supplied command line arguments, or nil if\n none were supplied","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/*command-line-args*"},{"added":"1.0","ns":"clojure.core","name":"reverse","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1293103264000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"rseq","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521de3"}],"line":949,"examples":[{"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":"user=> (reverse '(1 2 3))\n(3 2 1)\n","created-at":1280321963000,"updated-at":1285496763000,"_id":"542692cbc026201cdc326bf7"},{"updated-at":1568496474720,"created-at":1568496474720,"author":{"login":"rosineygp","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/5224519?v=4"},"body":"(reverse \"clojure\")\n; (\\e \\r \\u \\j \\o \\l \\c)\n\n(apply str (reverse \"clojure\"))\n; \"erujolc\"","_id":"5d7d5b5ae4b0ca44402ef7b4"},{"updated-at":1613699240347,"created-at":1613699240347,"author":{"login":"Crowbrammer","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/19522656?v=4"},"body":";; Comparison between `reverse` and `rseq` for a vector.\n\n(def nums (vec (range 1000000)))\n(time (reverse nums))\n;; \"Elapsed time: 30.1222 msecs\"\n(time (rseq nums))\n;; \"Elapsed time: 0.0664 msecs\"","_id":"602f18a8e4b0b1e3652d745b"}],"notes":[{"updated-at":1293103337000,"body":"If you've got a vector rseq is a good option instead of reverse.","created-at":1293103337000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fb0"},{"body":"For vectors, `rseq` is to `reverse` what `peek` is to `last`. `rseq` reverses in constant time (!) where `reverse` is in linear time, as it appears to pull everything into a new seq, one at a time instead of ... reversing the keys? I don't know the implementation details, but I do know that `rseq` is magnitudes faster than `reverse` for vectors and sorted maps. ","created-at":1613699495793,"updated-at":1613699637662,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/19522656?v=4","account-source":"github","login":"Crowbrammer"},"_id":"602f19a7e4b0b1e3652d745d"}],"arglists":["coll"],"doc":"Returns a seq of the items in coll in reverse order. Not lazy.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/reverse"},{"added":"1.9","ns":"clojure.core","name":"inst?","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1495635485203,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"inst-ms","ns":"clojure.core"},"_id":"5925961de4b093ada4d4d720"}],"line":6922,"examples":[{"updated-at":1495635467250,"created-at":1495635467250,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"body":"(inst? (java.util.Date.))\n;;=> true\n(inst? (java.util.Calendar/getInstance))\n;;=> false\n\n(inst? (java.sql.Timestamp. 0))\n;;=> true\n(inst? (java.sql.Date. 0))\n;;=> true\n\n(inst? (java.time.Instant/now))\n;;=> true\n(inst? (java.time.LocalDateTime/now))\n;;=> false","_id":"5925960be4b093ada4d4d71f"}],"notes":null,"arglists":["x"],"doc":"Return true if x satisfies Inst","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/inst_q"},{"added":"1.0","ns":"clojure.core","name":"range","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1611082428123,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"take","ns":"clojure.core"},"_id":"60072abce4b0b1e3652d743a"},{"created-at":1611082519863,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"iterate","ns":"clojure.core"},"_id":"60072b17e4b0b1e3652d743b"}],"line":3043,"examples":[{"author":{"avatar-url":"https://avatars.githubusercontent.com/u/142529?v=3","account-source":"github","login":"nipra"},"editors":[{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"avatar-url":"https://avatars2.githubusercontent.com/u/22608?v=4","account-source":"github","login":"MrHus"},{"login":"rafmagana","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/92894?v=3"},{"login":"rafmagana","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/92894?v=3"},{"avatar-url":"https://avatars1.githubusercontent.com/u/22159831?v=4","account-source":"github","login":"yuxuan813"}],"body":";; default value of 'end' is infinity\nuser=> (range)\n(0 1 2 3 4 5 6 7 8 9 10 ... 12770 12771 12772 12773 ... n)\n\n;; Since clojure 1.2:\nuser=> (take 10 (range))\n(0 1 2 3 4 5 6 7 8 9)\n\nuser=> (range 10)\n(0 1 2 3 4 5 6 7 8 9)\n\nuser=> (range -5 5)\n(-5 -4 -3 -2 -1 0 1 2 3 4)\n\nuser=> (range -100 100 10)\n(-100 -90 -80 -70 -60 -50 -40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90)\n\nuser=> (range 0 4 2)\n(0 2)\n\nuser=> (range 0 5 2)\n(0 2 4)\n\nuser=> (range 0 6 2)\n(0 2 4)\n\nuser=> (range 0 7 2)\n(0 2 4 6)\n\nuser=> (range 100 0 -10)\n(100 90 80 70 60 50 40 30 20 10)\n\nuser=> (range 10 -10 -1)\n(10 9 8 7 6 5 4 3 2 1 0 -1 -2 -3 -4 -5 -6 -7 -8 -9)\n \n\n","created-at":1279160563000,"updated-at":1523435961458,"_id":"542692ccc026201cdc326c77"},{"author":{"login":"pkolloch","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/10b2fd3c0a4cc46dc241a48468dc551?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":";; Since clojure 1.2:\n\nuser=> (take 10 (range))\n(0 1 2 3 4 5 6 7 8 9)\n","created-at":1282319317000,"updated-at":1285494502000,"_id":"542692ccc026201cdc326c80"},{"author":{"login":"rebcabin","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/880b0bb3a4be9237326dd69565444dee?r=PG&default=identicon"},"editors":[],"body":";; finite range over java Integers\nuser=> (take 5 (range 42 (java.lang.Integer/MAX_VALUE)))\n(42 43 44 45 46)\n\n;; infinite range starting at a certain point\nuser=> (take 5 (drop 42 (range)))\n(42 43 44 45 46)\n","created-at":1374181746000,"updated-at":1374181746000,"_id":"542692d4c026201cdc327048"},{"editors":[{"login":"mars0i","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1836941?v=3"}],"body":";; Using a double as the value of step can produce an unexpected extra value.\n;; In the second example below, there's an extra final value that's almost = 0.8.\n\n(range 0 0.8 1/10)\n(0 1/10 1/5 3/10 2/5 1/2 3/5 7/10)\n\nuser=> (range 0 0.8 0.1)\n(0 0.1 0.2 0.30000000000000004 0.4 0.5 0.6 0.7 0.7999999999999999)\n\n;; It's difficult to guess when this behavior will occur, unless you know\n;; whether the double representation of step plus what \"should\" be the\n;; last number is in fact less than end. From the second example above, you \n;; can see that the extra value won't be included if you replace 0.8 by a \n;; number in 0.1, ..., 0.7 (e.g. since 0.7 is not less than 0.7) but you \n;; wouldn't necessarily know that you will get the extra value for end = 0.9,\n;; 1.0, 1.1, but not for end = 1.2.\n","author":{"avatar-url":"https://avatars.githubusercontent.com/u/1836941?v=3","account-source":"github","login":"mars0i"},"created-at":1438100731938,"updated-at":1438101658841,"_id":"55b7acfbe4b0080a1b79cdaf"},{"updated-at":1494572384501,"created-at":1494572384501,"author":{"login":"st-keller","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/476463?v=3"},"body":"user=> (range 0 0)\n()\n\nuser=> (range 0 1)\n(0)","_id":"59155d60e4b01920063ee059"}],"notes":null,"arglists":["","end","start end","start end step"],"doc":"Returns a lazy seq of nums from start (inclusive) to end\n (exclusive), by step, where start defaults to 0, step to 1, and end to\n infinity. When step is equal to 0, returns an infinite sequence of\n start. When start is equal to end, returns empty list.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/range"},{"added":"1.0","ns":"clojure.core","name":"sort","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1285265346000,"author":{"login":"morphling","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/90ffa70a579c3e0c398b7523ecdc6a87?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"sort-by","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e7c"},{"created-at":1548624421040,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/109629?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"compare","ns":"clojure.core"},"_id":"5c4e2225e4b0ca44402ef654"}],"line":3110,"examples":[{"updated-at":1624481253798,"created-at":1281550866000,"body":"user=> (sort [3 1 2 4])\n(1 2 3 4)\n\nuser=> (sort > (vals {:foo 5, :bar 2, :baz 10}))\n(10 5 2)\n\n;; do not do this, use sort-by instead because it handles calling the fn (e.g last) and compare for you.\nuser=> (sort #(compare (last %1) (last %2)) {:b 1 :c 3 :a 2})\n([:b 1] [:a 2] [:c 3])\n\n;; like this:\nuser=> (sort-by last {:b 1 :c 3 :a 2})\n([:b 1] [:a 2] [:c 3])","editors":[{"avatar-url":"https://www.gravatar.com/avatar/90ffa70a579c3e0c398b7523ecdc6a87?r=PG&default=identicon","account-source":"clojuredocs","login":"morphling"},{"avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3","account-source":"github","login":"jafingerhut"},{"login":"drewverlee","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1130688?v=4"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/68dd6f50915854aa04fefcf4d6fa5c8e?r=PG&default=identicon","account-source":"clojuredocs","login":"zmila"},"_id":"542692cfc026201cdc326e5b"},{"updated-at":1602514013062,"created-at":1306322169000,"body":";; make a struct 'goods'. it assumes that every goods has\n;; its id number and price.\n(defstruct goods :id :price)\n\n;; generate data.\n(def data (map #(struct goods %1 %2)\n\t (shuffle (range 0 10)) (shuffle\n\t\t\t\t (into (range 100 500 100)\n\t\t\t\t\t (range 100 500 100)))))\n\n(defn comp-goods-price\n \"a compare function by :price of the struct 'goods.' the sort order \n is superior to the lower price and if the price is same, it is \n superior to the lower id.\"\n [el1 el2]\n (or (< (:price el1) (:price el2))\n (and (= (:price el1) (:price el2))(< (:id el1) (:id el2)))))\n\nuser=> data\n({:id 1, :price 300} {:id 6, :price 100} {:id 3, :price 100} {:id 4, :price 400} {:id 0, :price 300} {:id 2, :price 200} {:id 5, :price 200} {:id 8, :price 400})\nuser=> (sort comp-goods-price data)\n({:id 3, :price 100} {:id 6, :price 100} {:id 2, :price 200} {:id 5, :price 200} {:id 0, :price 300} {:id 1, :price 300} {:id 4, :price 400} {:id 8, :price 400})\nuser=> (sort-by :price < data) ; compare this with the above.\n({:id 6, :price 100} {:id 3, :price 100} {:id 2, :price 200} {:id 5, :price 200} {:id 1, :price 300} {:id 0, :price 300} {:id 4, :price 400} {:id 8, :price 400})\n\n\n","editors":[{"avatar-url":"https://www.gravatar.com/avatar/cacfb7ecf08cb6461767e514c93b7bf9?r=PG&default=identicon","account-source":"clojuredocs","login":"yasuto"},{"avatar-url":"https://www.gravatar.com/avatar/cacfb7ecf08cb6461767e514c93b7bf9?r=PG&default=identicon","account-source":"clojuredocs","login":"yasuto"},{"avatar-url":"https://www.gravatar.com/avatar/cacfb7ecf08cb6461767e514c93b7bf9?r=PG&default=identicon","account-source":"clojuredocs","login":"yasuto"},{"avatar-url":"https://www.gravatar.com/avatar/cacfb7ecf08cb6461767e514c93b7bf9?r=PG&default=identicon","account-source":"clojuredocs","login":"yasuto"},{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/cacfb7ecf08cb6461767e514c93b7bf9?r=PG&default=identicon","account-source":"clojuredocs","login":"yasuto"},"_id":"542692cfc026201cdc326e5e"},{"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":";; Warning: You can sort a Java array and get back a sorted immutable Clojure\n;; data structure, but it will also change the input Java array, by sorting it.\n;; Copy the array before sorting if you want to avoid this.\n\nuser=> (def x (to-array [32 11]))\n#'user/x\n\nuser=> (seq x)\n(32 11)\n\nuser=> (def y (sort x))\n#'user/y\n\n;; Return sorted sequence\nuser=> y\n(11 32)\n\nuser=> (class y)\nclojure.lang.ArraySeq\n\n;; but also modifies x, because it used the array to do the sorting.\nuser=> (seq x)\n(11 32)\n\n;; One way to avoid this is copying the array before sorting:\nuser=> (def y (sort (aclone x)))\n#'user/y","created-at":1331771749000,"updated-at":1332833601000,"_id":"542692d5c026201cdc32708e"},{"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/109629?v=4"}],"body":";; Sorting with > only works for numbers, whereas sort\n;; also works for other types such as vectors.\n;; To sort any data in reverse (descending) order,\n;; use a negated comparator:\n\nuser=> (sort (comp - compare) [[1 0] [0 0] [0 3] [2 1]])\n([2 1] [1 0] [0 3] [0 0])\n\n;; There are subtle cases where negating a comparator can give the wrong sort order.\n;; See this article for details, and a more robust suggestion of reversing the\n;; order of arguments given to the comparator:\n;; https://clojure.org/guides/comparators\n\nuser=> (sort #(compare %2 %1) [[1 0] [0 0] [0 3] [2 1]])\n([2 1] [1 0] [0 3] [0 0])","author":{"avatar-url":"https://avatars.githubusercontent.com/u/23474334?v=3","account-source":"github","login":"ferdinand-beyer"},"created-at":1479202684434,"updated-at":1548624336544,"_id":"582ad77ce4b0782b632278c1"},{"updated-at":1483387364837,"created-at":1483387364837,"author":{"login":"Invertisment","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1641263?v=3"},"body":";; Reverse the collection\n\nuser=> (sort #(compare %2 %1) '(:a :b :c :d))\n(:d :c :b :a)","_id":"586ab1e4e4b0fd5fb1cc9651"},{"editors":[{"login":"ertugrulcetin","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/8271291?v=3"}],"body":"(def data [{:v 12, :a 10} {:v 21, :a 113} {:v 1, :a 2} {:v 12, :a 223} {:v 100, :a 23} {:v 1, :a 113}])\n\n(defn multi-comp\n ([fns a b]\n (multi-comp fns < a b))\n ([[f & others :as fns] order a b]\n (if (seq fns)\n (let [result (compare (f a) (f b))\n f-result (if (= order >) (* -1 result) result)]\n (if (= 0 f-result)\n (recur others order a b)\n f-result))\n 0)))\n\n(sort #(multi-comp [:a :v] > %1 %2) data)\n;;=> ({:v 12, :a 223} {:v 21, :a 113} {:v 1, :a 113} {:v 100, :a 23} {:v 12, :a 10} {:v 1, :a 2}) \n\n(sort #(multi-comp [:a :v] < %1 %2) data)\n;;=> ({:v 1, :a 2} {:v 12, :a 10} {:v 100, :a 23} {:v 1, :a 113} {:v 21, :a 113} {:v 12, :a 223})","author":{"avatar-url":"https://avatars2.githubusercontent.com/u/8271291?v=3","account-source":"github","login":"ertugrulcetin"},"created-at":1491607217680,"updated-at":1491607544907,"_id":"58e81eb1e4b01f4add58fe88"},{"editors":[{"login":"malloryerik","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10395849?v=4"}],"body":";; Sort strings into ordered character lists\n\nuser=> (sort \"alphabet!321\") \n(\\! \\1 \\2 \\3 \\a \\a \\b \\e \\h \\l \\p \\t)\n\nuser=> (sort \"안녕하세요\") \n(\\녕 \\세 \\안 \\요 \\하)\n\nuser=> (sort \"花间一壶酒,独酌无相亲。\") \n(\\。 \\一 \\亲 \\壶 \\无 \\独 \\相 \\花 \\酌 \\酒 \\间 \\,)","author":{"avatar-url":"https://avatars3.githubusercontent.com/u/10395849?v=4","account-source":"github","login":"malloryerik"},"created-at":1566135485015,"updated-at":1566176013086,"_id":"5d5954bde4b0ca44402ef7a4"}],"notes":null,"arglists":["coll","comp coll"],"doc":"Returns a sorted sequence of the items in coll. If no comparator is\n supplied, uses compare. comparator must implement\n java.util.Comparator. Guaranteed to be stable: equal elements will\n not be reordered. If coll is a Java array, it will be modified. To\n avoid this, sort a copy of the array.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/sort"},{"ns":"clojure.core","name":"-cache-protocol-fn","file":"clojure/core_deftype.clj","type":"function","column":1,"see-alsos":null,"line":577,"examples":null,"notes":null,"arglists":["pf x c interf"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core/-cache-protocol-fn"},{"added":"1.0","ns":"clojure.core","name":"unchecked-inc-int","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1678034683900,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"unchecked-dec-int","ns":"clojure.core"},"_id":"6404c6fbe4b08cf8563f4b79"},{"created-at":1721984960738,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"unchecked-inc","ns":"clojure.core"},"_id":"66a367c069fbcc0c226174e0"}],"line":1163,"examples":[{"updated-at":1658482040938,"created-at":1658482040938,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":"(unchecked-inc-int 42);; => 43\n(unchecked-inc-int 42.8);; => 43\n(unchecked-inc-int Integer/MAX_VALUE);; => -2147483648","_id":"62da6d78e4b0b1e3652d762d"}],"notes":null,"arglists":["x"],"doc":"Returns a number one greater than x, an int.\n Note - uses a primitive operator subject to overflow.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/unchecked-inc-int"},{"added":"1.2","ns":"clojure.core","name":"map-indexed","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1290495691000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"map","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e3e"},{"created-at":1324314182000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.core","name":"keep-indexed","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e3f"}],"line":7475,"examples":[{"updated-at":1596522358724,"created-at":1280778877000,"body":"user=> (map-indexed (fn [idx itm] [idx itm]) \"foobar\")\n([0 \\f] [1 \\o] [2 \\o] [3 \\b] [4 \\a] [5 \\r])\n","editors":[{"avatar-url":"https://www.gravatar.com/avatar/4c1869a83a1bf9c5090b07b0db6fb450?r=PG&default=identicon","account-source":"clojuredocs","login":"kredaxx"},{"avatar-url":"https://www.gravatar.com/avatar/4c1869a83a1bf9c5090b07b0db6fb450?r=PG&default=identicon","account-source":"clojuredocs","login":"kredaxx"},{"avatar-url":"https://www.gravatar.com/avatar/4c1869a83a1bf9c5090b07b0db6fb450?r=PG&default=identicon","account-source":"clojuredocs","login":"kredaxx"},{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"login":"zackteo","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/7510179?v=4"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/4c1869a83a1bf9c5090b07b0db6fb450?r=PG&default=identicon","account-source":"clojuredocs","login":"kredaxx"},"_id":"542692cdc026201cdc326d25"},{"author":{"login":"mmwaikar","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/29d36f4c9f39c9f8ff61c07033b13118?r=PG&default=identicon"},"editors":[],"body":";; or simply\nuser=> (map-indexed vector \"foobar\")\n([0 \\f] [1 \\o] [2 \\o] [3 \\b] [4 \\a] [5 \\r])","created-at":1324306400000,"updated-at":1324306400000,"_id":"542692d4c026201cdc327005"},{"editors":[{"login":"zackteo","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/7510179?v=4"}],"body":"(map-indexed hash-map \"foobar\")\n;;=> ({0 \\f} {1 \\o} {2 \\o} {3 \\b} {4 \\a} {5 \\r})","author":{"avatar-url":"https://avatars2.githubusercontent.com/u/2665931?v=4","account-source":"github","login":"freetonik"},"created-at":1540845475652,"updated-at":1596521745408,"_id":"5bd76fa3e4b00ac801ed9eea"},{"editors":[{"login":"gluer","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/22495106?v=4"}],"body":";; a simple example\n(map-indexed #(when (< % 2) (str % %2)) [:a :b :c])\n;;=> (\"0:a\" \"1:b\" nil)\n\n(keep-indexed #(when (< % 2) (str % %2)) [:a :b :c])\n;;=> (\"0:a\" \"1:b\")","author":{"avatar-url":"https://avatars3.githubusercontent.com/u/22495106?v=4","account-source":"github","login":"gluer"},"created-at":1542944994140,"updated-at":1545622964814,"_id":"5bf778e2e4b0ca44402ef5ca"},{"updated-at":1596521989649,"created-at":1596521989649,"author":{"login":"zackteo","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/7510179?v=4"},"body":";; Join the index and elements with list\n(map-indexed list [:a :b :c])\n;;=> ((0 :a) (1 :b) (2 :c))","_id":"5f28fe05e4b0b1e3652d734c"},{"updated-at":1616528771927,"created-at":1616528756028,"author":{"login":"Crowbrammer","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/19522656?v=4"},"body":"(= (map-indexed #(when (= 2 %2) [%1 \"Hi\"]) [1 1 2 2]) \n '(nil nil [2 \"Hi\"] [3 \"Hi\"])) ;;=>true","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/19522656?v=4","account-source":"github","login":"Crowbrammer"}],"_id":"605a4574e4b0b1e3652d74a8"}],"notes":null,"arglists":["f","f coll"],"doc":"Returns a lazy sequence consisting of the result of applying f to 0\n and the first item of coll, followed by applying f to 1 and the second\n item in coll, etc, until coll is exhausted. Thus function f should\n accept 2 arguments, index and item. Returns a stateful transducer when\n no collection is provided.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/map-indexed"},{"added":"1.1","ns":"clojure.core","name":"with-bindings","file":"clojure/core.clj","type":"macro","column":1,"see-alsos":[{"created-at":1365637665000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"with-bindings*","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521ade"},{"created-at":1374310477000,"author":{"login":"alilee","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2fb0196dc5a7cd3a5cc73f1b9941c209?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"with-local-vars","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521adf"},{"created-at":1374313569000,"author":{"login":"alilee","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2fb0196dc5a7cd3a5cc73f1b9941c209?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"binding","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521ae0"},{"created-at":1375792510000,"author":{"login":"alilee","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2fb0196dc5a7cd3a5cc73f1b9941c209?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"with-redefs","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521ae1"}],"line":2003,"examples":[{"body":"(def ^:dynamic x 1)\n;;=> #'user/x\n\nx\n;;=> 1\n\n(with-bindings {#'x 2}\n x)\n;;=> 2","author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"created-at":1423525132511,"updated-at":1423525132511,"_id":"54d9450ce4b0e2ac61831d40"}],"macro":true,"notes":null,"arglists":["binding-map & body"],"doc":"Takes a map of Var/value pairs. Installs for the given Vars the associated\n values as thread-local bindings. Then executes body. Pops the installed\n bindings after body was evaluated. Returns the value of body.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/with-bindings"},{"added":"1.2","ns":"clojure.core","name":"rand-nth","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1292321208000,"author":{"login":"alimoeeny","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e8dd06976ead4082d2181f3807117e1?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"rand","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f63"},{"created-at":1434034859003,"author":{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/94482?v=3"},"to-var":{"ns":"clojure.core","name":"shuffle","library-url":"https://github.com/clojure/clojure"},"_id":"5579a2abe4b01ad59b65f4f1"},{"created-at":1586185491703,"author":{"login":"green-coder","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/598193?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"nth","ns":"clojure.core"},"_id":"5e8b4513e4b087629b5a18cc"}],"line":7379,"examples":[{"author":{"login":"pkolloch","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/10b2fd3c0a4cc46dc241a48468dc551?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"XPherior","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/656a48d6bef2a9f034af0e8b2b4d588d?r=PG&default=identicon"}],"body":"user=> (def food [:ice-cream :steak :apple])\n#'user/food\n\nuser=> (rand-nth food)\n:apple\nuser=> (rand-nth food)\n:ice-cream\n","created-at":1282319178000,"updated-at":1352188362000,"_id":"542692cec026201cdc326dfe"},{"updated-at":1507688537707,"created-at":1507688537707,"author":{"login":"parkeristyping","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/9487556?v=4"},"body":"user=> (def food [:ice-cream :steak :apple])\n#'user/food\n\nuser=> (rand-nth food)\n:ice-cream\nuser=> (rand-nth food)\n:ice-cream","_id":"59dd8059e4b03026fe14ea5f"},{"editors":[{"login":"jnriver","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/2074698?v=4"}],"body":"user=> (rand-nth [])\nIndexOutOfBoundsException clojure.lang.PersistentVector.arrayFor (PersistentVector.java:158)\n\nuser=>\n(let [xs []]\n (when (not (empty? xs))\n (rand-nth xs)))\nnil\n","author":{"avatar-url":"https://avatars2.githubusercontent.com/u/2074698?v=4","account-source":"github","login":"jnriver"},"created-at":1527215870505,"updated-at":1527216042499,"_id":"5b0776fee4b045c27b7fac79"}],"notes":null,"arglists":["coll"],"doc":"Return a random element of the (sequential) collection. Will have\n the same performance characteristics as nth for the given\n collection.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/rand-nth"},{"added":"1.0","ns":"clojure.core","name":"comp","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1358904701000,"author":{"login":"Ljos","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/45b996a79abca465acaf6c0f10b0437?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"partial","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ec3"},{"created-at":1358904763000,"author":{"login":"Ljos","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/45b996a79abca465acaf6c0f10b0437?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"juxt","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ec4"},{"created-at":1427713283146,"author":{"login":"peter-courcoux","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1872022?v=3"},"to-var":{"ns":"clojure.core","name":"every-pred","library-url":"https://github.com/clojure/clojure"},"_id":"55192d03e4b056ca16cfecfc"}],"line":2574,"examples":[{"author":{"login":"citizen428","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/b3881a28fe402dd2d1de44717486cae8?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":"(def negative-quotient (comp - /))\n;; #'user/negative-quotient\n\n(negative-quotient 8 3) ;;=> -8/3\n\n(def concat-and-reverse (comp (partial apply str) reverse str)) \n;; #'user/concat-and-reverse\n\n(concat-and-reverse \"hello\" \"clojuredocs\")\n;;=> \"scoderujolcolleh\"\n","created-at":1280554862000,"updated-at":1420648866563,"_id":"542692cbc026201cdc326c04"},{"updated-at":1486787503828,"created-at":1292499977000,"body":"((comp str +) 8 8 8) \n;;=> \"24\"\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3","account-source":"github","login":"phreed"},{"login":"bsifou","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8908139?v=3"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/e8a89e26df41f3dd921ff1de2afa4db7?r=PG&default=identicon","account-source":"clojuredocs","login":"zpinter"},"_id":"542692cbc026201cdc326c06"},{"author":{"login":"semperos","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/edeae8e7534b3d554e4ec2c35ffc68d?r=PG&default=identicon"},"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":"(map\n (comp - (partial + 3) (partial * 2))\n [1 2 3 4])\n;;=> (-5 -7 -9 -11)","created-at":1296193214000,"updated-at":1420649045506,"_id":"542692cbc026201cdc326c07"},{"updated-at":1420649083250,"created-at":1305843170000,"body":"(filter (comp not zero?) [0 1 0 2 0 3 0 4])\n;;=> (1 2 3 4)","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3","account-source":"github","login":"phreed"}],"author":{"avatar-url":"https://avatars2.githubusercontent.com/u/22608?v=4","account-source":"github","login":"MrHus"},"_id":"542692cbc026201cdc326c08"},{"author":{"login":"yasuto","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cacfb7ecf08cb6461767e514c93b7bf9?r=PG&default=identicon"},"editors":[{"login":"yasuto","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cacfb7ecf08cb6461767e514c93b7bf9?r=PG&default=identicon"},{"login":"yasuto","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cacfb7ecf08cb6461767e514c93b7bf9?r=PG&default=identicon"},{"login":"yasuto","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cacfb7ecf08cb6461767e514c93b7bf9?r=PG&default=identicon"},{"login":"yasuto","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cacfb7ecf08cb6461767e514c93b7bf9?r=PG&default=identicon"},{"login":"yasuto","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cacfb7ecf08cb6461767e514c93b7bf9?r=PG&default=identicon"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":";; make a struct 'goods'. it assumes that every goods has\n;; its id number and price.\n(defstruct goods :id :price)\n\n;; generate data.\n(def data (map #(struct goods %1 %2)\n\t (shuffle (range 0 10)) \n (shuffle\n\t (into (range 100 500 100)\n\t\t\t(range 100 500 100)))))\n\n(defn comp-goods-price\n \"a compare function by :price of the struct 'goods.' the sort order \n is that the lower price is superior to the higher one and if the \n price is same, the lower id is superior to the higher one.\"\n [el1 el2]\n (if (or (< (:price el1) (:price el2))\n (and (= (:price el1) (:price el2)) (< (:id el1) (:id el2))))\n true\n false))\n\n;; The shuffle will cause your results to differ.\ndata \n;;=> ({:id 1, :price 300} {:id 6, :price 100} \n;; {:id 3, :price 100} {:id 4, :price 400}\n;; {:id 0, :price 300} {:id 2, :price 200} \n;; {:id 5, :price 200} {:id 8, :price 400})\n\n(sort (comp comp-goods-price) data)\n;;=> ({:id 3, :price 100} {:id 6, :price 100} \n;; {:id 2, :price 200} {:id 5, :price 200} \n;; {:id 0, :price 300} {:id 1, :price 300}\n;; {:id 4, :price 400} {:id 8, :price 400})\n\n(sort-by :price < data) ; compare this with the above.\n;;=> ({:id 6, :price 100} {:id 3, :price 100} \n;; {:id 2, :price 200} {:id 5, :price 200} \n;; {:id 1, :price 300} {:id 0, :price 300} \n;; {:id 4, :price 400} {:id 8, :price 400})\n\n;; Yet another example of 'comp' by PriorityBlockingQueue.\n\n(import [java.util.concurrent PriorityBlockingQueue])\n;; java.util.concurrent.PriorityBlockingQueue\n\n(def pqdata (new PriorityBlockingQueue 8\n\t\t (comp comp-goods-price)))\n;; #'user/pqdata\n\n(doseq [x data] (.add pqdata x))\n;;=> nil\n\n(dotimes [_ 8] (println (.poll pqdata)))\n;; {:id 3, :price 100}\n;; {:id 6, :price 100}\n;; {:id 2, :price 200}\n;; {:id 5, :price 200}\n;; {:id 0, :price 300}\n;; {:id 1, :price 300}\n;; {:id 4, :price 400}\n;; {:id 8, :price 400}\n;;=> nil\n","created-at":1306322829000,"updated-at":1420650298514,"_id":"542692cbc026201cdc326c09"},{"author":{"login":"shockbob","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon"},"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":"(def countif (comp count filter))\n#'user/countif\n\n(countif even? [2 3 1 5 4])\n;;=> 2","created-at":1313975540000,"updated-at":1420649227225,"_id":"542692cbc026201cdc326c0f"},{"author":{"login":"Will","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a449004e52cfddd142e63a1d317b191d?r=PG&default=identicon"},"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":"; Get 2nd to last element from a list\n( (comp second reverse) '(\"a\" 2 7 \"b\")) \n;;=> 7","created-at":1344506218000,"updated-at":1420649237526,"_id":"542692d2c026201cdc326f64"},{"updated-at":1449761968315,"created-at":1449761968315,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"},"body":"; We need an example that composes more than just two functions.\n; The following example is an overly complicated reimplementation of 'nth'\n; but it does show the composition of an arbitrary number of functions (rest).\n( #((apply comp first (repeat %2 rest)) %1) [1 2 3 4 5 6] 3 ) \n;;=> 4","_id":"56699cb0e4b09a2675a0ba72"},{"updated-at":1536867551060,"created-at":1486454398076,"author":{"login":"purukaushik","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/5105099?v=3"},"body":"; `comp`-ing maps, filters with a little help from our friend `partial`\n; the following function filters numbers in a `coll` if it is divisible by 3\n; then on that filtered `coll`, multiplies all by 2\n\n; a little helper to find if a number is div by 3 \n; also comp-ed\n\n(def mod3nz? (comp not zero? #(mod % 3)))\n\n; now for that elusive function that muls by 2 after filter those not div by 3\n(def mul-2-nd-3\n \"Takes a seq of numbers, filters those not divisible by 3 and muls them by 2\"\n (comp (partial map #(* % 2))\n (partial filter mod3nz?)))\n\n(mul-2-nd-3 [16 15 30 43]) ;; => (32 86)\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/5105099?v=3","account-source":"github","login":"purukaushik"},{"login":"Jjunior130","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/7597818?v=4"}],"_id":"58997e7ee4b01f4add58fe3d"},{"updated-at":1486787324018,"created-at":1486787324018,"author":{"login":"bsifou","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8908139?v=3"},"body":"; Split a number into sequence of it's digits\n((comp (partial map (comp read-string str)) str) 33)\n;;=> (3 3)","_id":"589e92fce4b01f4add58fe46"},{"updated-at":1497863678341,"created-at":1497863678341,"author":{"login":"merliecat","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/27359194?v=3"},"body":";; Keywords are used as functions to access data in maps.\n\n(:foo {:foo \"bar\"})\n;;=> \"bar\"\n\n;; With a nested data structure, it is common to use\n;; several keywords in sequence to navigate the hierarchy.\n\n(def my-data {:this {:that {:the-other \"val\"}}})\n;;=> #'user/my-data\n\n(-> my-data :this :that :the-other)\n;;=> \"val\"\n\n;; Since keywords are functions,\n;; they can be 'comp'ed just like any other function.\n\n(def those (comp :the-other :that :this)) ; Note: reverse order\n;;=> #'user/those\n\n(those my-data)\n;;=> \"val\"\n\n;; The composed keyword-sequence can be used with other keywords: -\n\n(def my-data-2\n {:this {:that {:the-other {:a \"apple\" :b \"banana\"}}}})\n;;=> #'user/my-data-2\n\n(let [a (-> my-data-2 those :a)\n b (-> my-data-2 those :b)]\n (str \"These: \" a \", \" b))\n;;=> \"These: apple, banana\"","_id":"594795fee4b06e730307db3a"},{"updated-at":1508821937862,"created-at":1508821937862,"author":{"login":"elect000","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/18697629?v=4"},"body":";; ((comp func1 func2) data) mean ...\n;; (-> data func2 func1)\n;; so,\n((comp (partial * 3) inc) 1)\n;; means\n(* 3 (inc 1))\n\n;; advanced ...\n\n((comp seq re-seq) #\"(\\w+)=(\\S+)\" \"foo=bar\")\n;; ([\"foo=bar\" \"foo\" \"bar\"])\n(seq (re-seq #\"(\\w+)=(\\S+)\" \"foo=bar\"))\n\n;; * \"#(\\w+)...\" and \"foo=...\" are arguments for #re-seq","_id":"59eecbb1e4b0a08026c48c73"},{"updated-at":1510097526774,"created-at":1510097526774,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"},"body":";; comp is the transducer equivalent to thrush \n\n;; An example of using the \"thread-last\" macro to get\n;; the sum of the first 10 even squares.\n(->> (range)\n (map #(* % %))\n (filter even?)\n (take 10)\n (reduce +))\n;;=> 1140\n\n;; Many the seq functions now produce transducers.\n;; `reduce` does not but has been replaced with `transduce`.\n(transduce \n (comp\n (map #(* % %))\n (filter even?)\n (take 10))\n + 0 (range) )\n;;=> 1140","_id":"5a024276e4b0a08026c48c9b"},{"updated-at":1517927616519,"created-at":1517927616519,"author":{"login":"ibercode","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/31028993?v=4"},"body":";;trim will remove the white spaces and return a new string which will be passed ;;to the second function capitalize which will return a new string\n\n((comp clojure.string/capitalize clojure.string/trim) \" london \")\n;;\"London\"\n","_id":"5a79bcc0e4b0e2d9c35f7419"},{"updated-at":1517928532967,"created-at":1517928532967,"author":{"login":"ibercode","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/31028993?v=4"},"body":"(def my-car\n {:name \"audi\"\n :data {:cc 2990\n :bhp 350}})\n\n((comp :bhp :data) my-car)\n;;350\n\n;;which is the equivalent of\n\n(:bhp (:data my-car))\n;;350","_id":"5a79c054e4b0e2d9c35f741a"},{"editors":[{"login":"Jjunior130","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/7597818?v=4"}],"body":"(require '[reagent.core :as r])\n\n(def float-parsable? (comp not js/isNaN js/parseFloat))\n(def find-parsable-or-nil \n (comp first \n (partial re-find \n #\"(\\-?\\d+\\.)?\\d+([eE][-+]?\\d+)?\")))\n\n(defn number-input\n \"HTML input element for number only input\"\n [value]\n [:input\n {:value @value\n :type \"text\"\n :on-change (comp\n #(when-let [new-value %]\n (reset! value new-value))\n (fn [new-value]\n (cond\n (empty? new-value) \"\"\n (float-parsable? new-value) new-value\n :otherwise (find-parsable-or-nil new-value)))\n (fn [target]\n (.-value target))\n (fn [event]\n (.-target event)))}])\n\n(def value (r/atom \"\"))\n\n(defn demo []\n [:div\n ; Displays NaN when value is \"\", displays a number otherwise.\n (-> @value js/parseFloat str) [:br]\n [number-input value]])","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/7597818?v=4","account-source":"github","login":"Jjunior130"},"created-at":1536856092993,"updated-at":1536879826363,"_id":"5b9a901ce4b00ac801ed9e9c"},{"editors":[{"login":"luontola","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/42678?v=4"}],"body":"; Demonstrating the order of parameters vs. normal function application.\n\n(def x {:bar {:foo 42}})\n\n(:foo (:bar x))\n;;=> 42\n\n((comp :foo :bar) x)\n;;=> 42","author":{"avatar-url":"https://avatars0.githubusercontent.com/u/42678?v=4","account-source":"github","login":"luontola"},"created-at":1552650253291,"updated-at":1552650469262,"_id":"5c8b900de4b0ca44402ef6b6"},{"updated-at":1615715410336,"created-at":1615715410336,"author":{"login":"nbardiuk","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/381992?v=4"},"body":"; Without arguments returns identity function\n\n(identical? (comp) identity)\n;;=> true\n\n((comp) :arg)\n;;=> :arg","_id":"604ddc52e4b0b1e3652d748f"}],"notes":null,"arglists":["","f","f g","f g & fs"],"doc":"Takes a set of functions and returns a fn that is the composition\n of those fns. The returned fn takes a variable number of args,\n applies the rightmost of fns to the args, the next\n fn (right-to-left) to the result, etc.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/comp"},{"added":"1.0","ns":"clojure.core","name":"await","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1298860359000,"author":{"login":"ninjudd","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/7ced25585a7556e9b9b975c1f9e136e3?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"await-for","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521a8a"}],"line":3292,"examples":[{"updated-at":1435096085344,"created-at":1283693589000,"body":";; construct a simple agent\n(def *agnt* (agent {}))\n\n(send-off *agnt* (fn [state] \n (Thread/sleep 10000)\n (assoc state :done true)))\n;;=> \n\n;; blocks till the agent action is finished\n(await *agnt*) \n;;=> nil","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3","account-source":"github","login":"phreed"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/1453?v=4","account-source":"github","login":"ghoseb"},"_id":"542692cdc026201cdc326cdb"},{"body":"(import '(java.io BufferedWriter FileWriter))\n\n;; Generally the agent can be sent messages asynchronously, send and forget.\n;; In some cases a rendezvous is needed, e.g. in the case of an output file.\n\n(def write-out \n (agent {:handle (clojure.java.io/writer \"results.txt\" )\n :last-msg [\"init\"]}\n :validator (fn [state] \n (and (contains? state :handle) (contains? state :last-msg))) \n :error-handler (fn [result] \n (println \"invalid result\") )))\n\n(defn write-a-line [state msg nap] \n (.write (:handle state) (str msg \" line \" \"\\n\")) \n (let [new-state (update-in state [:last-msg] into [msg])]\n (println \"message : \" msg \" : \" new-state)\n (Thread/sleep nap)\n new-state))\n\n\n\n;; these all have the same return value\n(send-off write-out write-a-line \"first\" 2000)\n(send-off write-out write-a-line \"second\" 1000)\n(send-off write-out write-a-line \"third\" 5000)\n(send-off write-out write-a-line \"fourth\" 1000)\n@write-out\n;;=> {:handle #, :last-msg [\"init\"]}\n\n(time (await write-out))\n;; 9000.307 msecs\n\n;; here we can see that the await causes the thread to block\n;; until the agent's queue is empty.\n@write-out\n;;=> {:handle #, \n;; :last-msg [\"init\" \"first\" \"second\" \"third\" \"fourth\"]}\n\n;; But wait the \"result.txt\" file is empty!\n;; We need to close the file handle.\n;; And now that we know the agent's queue is empty we\n;; are free to close it.\n;; This could do this in the current thread with the dereferenced\n;; agents :handle '(.close (:handle @write-out))' \n;; but it is probably better to be formal and let the agent do it.\n(defn close-the-agent [state] \n (.close (:handle state)) \n state)\n\n(send-off write-out close-the-agent)\n\n;; And the contents of \"result.txt\" are: (less the leading '; ')\n; first line\n; second line\n; third line\n; fourth line","author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"},"created-at":1435098875036,"updated-at":1435102514521,"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"_id":"5589defbe4b05f167dcf2341"}],"notes":[{"author":{"login":"andrewni420","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/77020120?v=4"},"updated-at":1690255271897,"created-at":1690255271897,"body":" ;;It is not actually allowed to await on an action dispatched from an agent to an agent\n\n (def m (agent 0))\n (def n (agent 0))\n\n (defn step \n [agent1 agent2]\n (try (await (send agent2 inc))\n (catch Exception e (println e)))\n agent1)\n\n ;;Evaluating this throws an error saying \"Can't await in agent action\"\n (send m #(step % n))\n ","_id":"64bf3fa7e4b08cf8563f4bd6"}],"arglists":["& agents"],"doc":"Blocks the current thread (indefinitely!) until all actions\n dispatched thus far, from this thread or agent, to the agent(s) have\n occurred. Will block on failed agents. Will never return if\n a failed agent is restarted with :clear-actions true or shutdown-agents was called.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/await"},{"added":"1.2","ns":"clojure.core","name":"spit","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1330170569000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.core","name":"slurp","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e97"},{"created-at":1330170573000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.java.io","name":"writer","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e98"},{"created-at":1350073135000,"author":{"login":"AtKaaZ","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e10dfa345f44b0fe72bbe081fd51b83?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"load-file","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e99"},{"created-at":1515622120441,"author":{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/94482?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"make-parents","ns":"clojure.java.io"},"_id":"5a568ee8e4b0a08026c48cec"}],"line":7101,"examples":[{"author":{"login":"pkolloch","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/10b2fd3c0a4cc46dc241a48468dc551?r=PG&default=identicon"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"}],"body":"user=> (spit \"flubber.txt\" \"test\")\nnil\nuser=> (slurp \"flubber.txt\")\n\"test\"","created-at":1280458792000,"updated-at":1366325983000,"_id":"542692c7c026201cdc326972"},{"author":{"login":"megapatch","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9a9b25017146e62801acc97861d74c4e?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":"user=> (spit \"event.log\" \"test 1\\n\" :append true)\nnil\n\nuser=> (spit \"event.log\" \"test 2\\n\" :append true)\nnil\n\nuser=> (println (slurp \"event.log\"))\ntest 1\ntest 2\n\nnil\n","created-at":1283972766000,"updated-at":1285487376000,"_id":"542692c7c026201cdc326975"},{"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"editors":[{"login":"Juxtaspiral","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1b0546af898df8046160d0ed80e13165?r=PG&default=identicon"}],"body":"(defn append-to-file\n \"Uses spit to append to a file specified with its name as a string, or\n anything else that writer can take as an argument. s is the string to\n append.\" \n [file-name s]\n (spit file-name s :append true))","created-at":1334796093000,"updated-at":1348351258000,"_id":"542692d5c026201cdc32709b"},{"updated-at":1510413046445,"created-at":1510413046445,"author":{"login":"ibercode","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/31028993?v=4"},"body":";;Create a record and save a log message to a log file\n;;Constructor with side effects\n\n;;define a Person record\n(defrecord Person [fname lname])\n\n;;define a function to save a log message into the log.txt using spit and :append\n(defn log-entry [msg] (spit \"log.txt\" (apply str msg \"\\n\") :append true))\n\n;;build the constructor which: 1) log the message; 2)create a Person\n(defn make-person [fname lname]\n (log-entry (apply str \"[log] New Person created : \" lname \",\" fname))\n (->Person fname lname))\n\n;;create a person\n(def person (make-person \"John\" \"Smith\"))\n\n;;print the content of the log.txt to the console\n(println (slurp \"log.txt\"))","_id":"5a0712f6e4b0a08026c48cb0"},{"updated-at":1543709529631,"created-at":1543709529631,"author":{"login":"messinm","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/1719572?v=4"},"body":"; ClojureCLR doesn't use :append, use this instead\n(spit \"hi.txt\" \"Test 1\\n\" :file-mode System.IO.FileMode/Append)\n","_id":"5c032359e4b0ca44402ef5d5"},{"editors":[{"login":"Kaspazza","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/36607370?v=4"}],"body":";; Spitting map, adds \",\" between key-value pairs\n(spit \"hi.txt\" {:a 1 :b 2})\n\n;; Now let's read it\n(slurp \"hello.txt\")\n;; => \"{:a 1, :b 2}\"\n","author":{"avatar-url":"https://avatars.githubusercontent.com/u/36607370?v=4","account-source":"github","login":"Kaspazza"},"created-at":1706202862280,"updated-at":1706202883715,"_id":"65b296ee69fbcc0c22617490"}],"notes":[{"author":{"login":"flyboarder","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/147004?v=3"},"updated-at":1469398101037,"created-at":1469398101037,"body":"The only valid options for `spit` are `:append` and `:encoding`.","_id":"57953c55e4b0bafd3e2a04b6"},{"author":{"login":"didibus","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/601540?v=4"},"updated-at":1585180895729,"created-at":1585180895729,"body":"Valid options include:\n\n :append true to open stream in append mode\n :encoding string name of encoding to use, e.g. \\\"UTF-8\\\".","_id":"5e7bf0dfe4b087629b5a18c2"}],"arglists":["f content & options"],"doc":"Opposite of slurp. Opens f with writer, writes content, then\n closes f. Options passed to clojure.java.io/writer.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/spit"},{"added":"1.1","ns":"clojure.core","name":"future-done?","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1297120552000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"future","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521df0"},{"to-var":{"library-url":"https://github.com/clojure/clojure","name":"future-cancel","ns":"clojure.core"},"author":{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},"created-at":1339251476000,"_id":"542692ebf6e94c6970521df1"},{"to-var":{"library-url":"https://github.com/clojure/clojure","name":"future?","ns":"clojure.core"},"author":{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},"created-at":1339252213000,"_id":"542692ebf6e94c6970521df2"},{"to-var":{"library-url":"https://github.com/clojure/clojure","name":"future-cancelled?","ns":"clojure.core"},"author":{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},"created-at":1339252225000,"_id":"542692ebf6e94c6970521df3"}],"line":6615,"examples":[{"updated-at":1339251719000,"created-at":1339251719000,"body":"user=> (def f (future (Thread/sleep 5000) (inc 0)))\n\nuser=> (future-done? f) \nfalse\n\nuser=> (Thread/sleep 5000)\nnil\n\nuser=> (future-done? f)\ntrue\n\n","editors":[],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},"_id":"542692d3c026201cdc326fb7"},{"updated-at":1339252193000,"created-at":1339252193000,"body":";; beware of cancellation !!!\n\nuser=> (def f (future (Thread/sleep 5000) (inc 0)))\n#'user/f\n\nuser=> (future-cancel f) \ntrue\n\nuser=> (future-cancelled? f) \ntrue\n\nuser=> (future-done? f) \ntrue\n\nuser=> @f \njava.util.concurrent.CancellationException (NO_SOURCE_FILE:0)","editors":[],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},"_id":"542692d3c026201cdc326fb8"},{"updated-at":1669054840067,"created-at":1668769697257,"author":{"login":"sundaramss","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1131710?v=4"},"body":";; removed unhelpful example","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/1131710?v=4","account-source":"github","login":"sundaramss"},{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"}],"_id":"637767a1e4b0b1e3652d7686"}],"notes":[{"updated-at":1300164452000,"body":"Future \"done\" returns true even for abnormal termination like being cancelled or throwing an exception.\r\n\r\nhttp://download.oracle.com/javase/6/docs/api/java/util/concurrent/Future.html#isDone()","created-at":1300164452000,"author":{"login":"pauldoo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5cb916d3c8abc9f45a093209e72489fb?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fb8"}],"arglists":["f"],"doc":"Returns true if future f is done","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/future-done_q"},{"added":"1.0","ns":"clojure.core","name":"*read-eval*","type":"var","see-alsos":[{"created-at":1352963695000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.core","name":"read","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d50"},{"created-at":1352963701000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.core","name":"read-string","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d51"},{"created-at":1352963704000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.core","name":"load","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d52"}],"examples":[{"author":{"login":"Claj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5fd658a8d2ef549071cb5286b1b874aa?r=PG&default=identicon"},"editors":[{"login":"Claj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5fd658a8d2ef549071cb5286b1b874aa?r=PG&default=identicon"}],"body":";;just from the doc\n\n(binding [*read-eval* false] (read-string \"#=(eval (def x 3))\"))\n=> EvalReader not allowed when *read-eval* is false.\n [Thrown class java.lang.RuntimeException]\n\n;;remove the anonymous function:\n\n(binding [*read-eval* false] (read-string \"(def x 3)\"))\n=> (def x 3)\n\n;;which is evaluable\n\n(eval (binding [*read-eval* false] (read-string \"(def x 3)\")))\n=> #'user/x\n\nx\n=>3","created-at":1327090750000,"updated-at":1327090760000,"_id":"542692d1c026201cdc326f3a"}],"notes":[{"body":"This dynamic Var defines if `read` and `read-string` will be allowed to evaluate code using the eval reader `#=`. That said, the way that the eval reader will evaluate things within the context of reading is very strange, here are the rules (credit to p-himik from Slack):\n\nEvaluation done by `read` and `read-string` using the eval reader is very limited and supports only the following cases:\n\n1. The form is a symbol naming a Java class, `(read-string \"#=java.lang.String\")`\n2. The form is a list and the first symbol is a symbol\n 2. that is var and the next one is a fully qualified symbol, `(def x) (read-string \"#=(var user/x)\")`\n 2. that denotes a constructor calling, `(read-string \"#=(java.lang.String. \\\"x\\\")\")`\n 2. that denotes a static member calling, `(read-string \"#=(java.lang.Integer/parseInt \\\"1\\\")\")`\n 2. that names something in the current NS, and the rest are quoted entities, `(read-string \"#=(inc 1)\")`\n\nAs you can see, everything after the first symbol is left untouched. This makes the eval reader extremely limited by itself in comparison to normal eval, but you can use eval there to circumvent that: `(def x 1) (read-string \"#=(eval x)\")`\n\nTo be more clear, in the given example:\n\n```\n(read-string \"#=(+ 1 (+ 2 3))\")\n```\n\nEverything after the first `+` are read as if quoted, so the above is equivalent to:\n\n```\n(+ '1 '(+ 2 3))\n```\n\nWhich will throw an exception:\n\n> PersistentList cannot be cast to class java.lang.Number\n\nThat's why the trick if you want to use the eval reader to evaluate arbitrary code is to use `eval` inside it like so:\n\n```\n(read-string \"#=(eval (+ 1 (+ 2 3)))\")\n```\n\nWhich will even let you reference a value in the current context:\n\n```\n(def x 1)\n#=(eval (+ 1 x))\n;;=> 2\n```","created-at":1627197824169,"updated-at":1627198605717,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/601540?v=4","account-source":"github","login":"didibus"},"_id":"60fd1180e4b0b1e3652d751d"}],"arglists":[],"doc":"Defaults to true (or value specified by system property, see below)\n ***This setting implies that the full power of the reader is in play,\n including syntax that can cause code to execute. It should never be\n used with untrusted sources. See also: clojure.edn/read.***\n\n When set to logical false in the thread-local binding,\n the eval reader (#=) and record/type literal syntax are disabled in read/load.\n Example (will fail): (binding [*read-eval* false] (read-string \"#=(* 2 21)\"))\n\n The default binding can be controlled by the system property\n 'clojure.read.eval' System properties can be set on the command line\n like this:\n\n java -Dclojure.read.eval=false ...\n\n The system property can also be set to 'unknown' via\n -Dclojure.read.eval=unknown, in which case the default binding\n is :unknown and all reads will fail in contexts where *read-eval*\n has not been explicitly bound to either true or false. This setting\n can be a useful diagnostic tool to ensure that all of your reads\n occur in considered contexts. You can also accomplish this in a\n particular scope by binding *read-eval* to :unknown\n ","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/*read-eval*"},{"added":"1.0","ns":"clojure.core","name":"dorun","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1296708499000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"doall","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d8c"},{"created-at":1520117044268,"author":{"login":"finalfantasia","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/2316604?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"doseq","ns":"clojure.core"},"_id":"5a9b2534e4b0316c0f44f908"},{"created-at":1520117066852,"author":{"login":"finalfantasia","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/2316604?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"run!","ns":"clojure.core"},"_id":"5a9b254ae4b0316c0f44f909"}],"line":3141,"examples":[{"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"editors":[{"login":"fyquah95","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/6006469?v=3"}],"body":"user=> (dorun 5 (repeatedly #(println \"hi\")))\nhi\nhi\nhi\nhi\nhi\nhi\nnil","created-at":1281092803000,"updated-at":1434450783133,"_id":"542692c6c026201cdc326907"},{"updated-at":1335431834000,"created-at":1335431834000,"body":"user=> (let [x (atom 0)]\n (dorun (take 10 (repeatedly #(swap! x inc))))\n @x)\n10","editors":[],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3","account-source":"github","login":"devn"},"_id":"542692d2c026201cdc326f8e"},{"author":{"login":"john.r.woodward","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/22b6fbc4a386291e45b1cb4449377086?r=PG&default=identicon"},"editors":[{"login":"AtKaaZ","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e10dfa345f44b0fe72bbe081fd51b83?r=PG&default=identicon"},{"login":"orivej","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cab90c7de5efde92a29f1eacb603ba9a?r=PG&default=identicon"},{"login":"orivej","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cab90c7de5efde92a29f1eacb603ba9a?r=PG&default=identicon"}],"body":"user=> (dorun (map #(println \"hi\" %) [\"mum\" \"dad\" \"sister\"]))\nhi mum\nhi dad\nhi sister\nnil","created-at":1343166324000,"updated-at":1362554649000,"_id":"542692d2c026201cdc326f8f"},{"updated-at":1436247797064,"created-at":1436247797064,"author":{"login":"gdeer81","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1340575?v=3"},"body":";;map a function which makes database calls over a vector of values \nuser=> (map #(db/insert :person {:name %}) [\"Fred\" \"Ethel\" \"Lucy\" \"Ricardo\"])\nJdbcSQLException The object is already closed [90007-170] org.h2.message.DbE\nxception.getJdbcSQLException (DbException.java:329)\n\n;;database connection was closed before we got a chance to do our transactions\n;;lets wrap it in dorun\nuser=> (dorun (map #(db/insert :person {:name %}) [\"Fred\" \"Ethel\" \"Lucy\" \"Ricardo\"]))\nDEBUG :db insert into person values name = 'Fred'\nDEBUG :db insert into person values name = 'Ethel'\nDEBUG :db insert into person values name = 'Lucy'\nDEBUG :db insert into person values name = 'Ricardo'\nnil","_id":"559b66f5e4b00f9508fd66f6"}],"notes":[{"author":{"login":"finalfantasia","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/2316604?v=4"},"updated-at":1520197531487,"created-at":1520115866563,"body":"`clojure.core/run!` can take the place of `(dorun (map ...))`.","_id":"5a9b209ae4b0316c0f44f907"}],"arglists":["coll","n coll"],"doc":"When lazy sequences are produced via functions that have side\n effects, any effects other than those needed to produce the first\n element in the seq do not occur until the seq is consumed. dorun can\n be used to force any effects. Walks through the successive nexts of\n the seq, does not retain the head and returns nil.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/dorun"},{"added":"1.9","ns":"clojure.core","name":"simple-symbol?","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1495715090890,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"symbol?","ns":"clojure.core"},"_id":"5926cd12e4b093ada4d4d75d"},{"created-at":1495715101981,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"qualified-symbol?","ns":"clojure.core"},"_id":"5926cd1de4b093ada4d4d75e"}],"line":1642,"examples":[{"updated-at":1495723255240,"created-at":1495723255240,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"body":"(simple-symbol? 'symbol)\n;;=> true\n\n(simple-symbol? 'clojure.core/symbol)\n;;=> false\n\n(simple-symbol? \"string\")\n;;=> false\n(simple-symbol? 42)\n;;=> false\n(simple-symbol? nil)\n;;=> false","_id":"5926ecf7e4b093ada4d4d76a"}],"notes":null,"arglists":["x"],"doc":"Return true if x is a symbol without a namespace","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/simple-symbol_q"},{"added":"1.0","ns":"clojure.core","name":"disj","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1351063996000,"author":{"login":"TimMc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5d532e51427ef2f4ded31aaca16c8baf?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"dissoc","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e31"},{"created-at":1351064021000,"author":{"login":"TimMc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5d532e51427ef2f4ded31aaca16c8baf?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"disj!","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e32"},{"created-at":1405367718000,"author":{"login":"ryo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3f7913b563c72083c74030d928ba407e?r=PG&default=identicon"},"to-var":{"ns":"clojure.set","name":"difference","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e33"},{"created-at":1561679596230,"author":{"login":"huahaiy","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/889685?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"conj","ns":"clojure.core"},"_id":"5d1556ece4b0ca44402ef777"}],"line":1533,"examples":[{"updated-at":1462050216483,"created-at":1280340321000,"body":"user=> (disj #{1 2 3}) ; disjoin nothing \n#{1 2 3} \n\nuser=> (disj #{1 2 3} 2) ; disjoin 2\n#{1 3} \n\nuser=> (disj #{1 2 3} 4) ; disjoin non-existent item\n#{1 2 3} \n\nuser=> (disj #{1 2 3} 1 3) ; disjoin several items at once\n#{2}","editors":[{"avatar-url":"https://www.gravatar.com/avatar/68dd6f50915854aa04fefcf4d6fa5c8e?r=PG&default=identicon","account-source":"clojuredocs","login":"zmila"},{"avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3","account-source":"github","login":"jafingerhut"},{"login":"bkovitz","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/4142015?v=3"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/68dd6f50915854aa04fefcf4d6fa5c8e?r=PG&default=identicon","account-source":"clojuredocs","login":"zmila"},"_id":"542692cec026201cdc326dc6"},{"editors":[{"login":"Hamido-san","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/27916344?v=4"}],"body":"user=> (apply disj #{1 2 3} [1 3]) ; disjoin keys in a coll\n#{2}","author":{"avatar-url":"https://avatars2.githubusercontent.com/u/5283430?v=4","account-source":"github","login":"randomizedthinking"},"created-at":1602141980639,"updated-at":1620639101734,"_id":"5f7ebf1ce4b0b1e3652d73ce"}],"notes":null,"arglists":["set","set key","set key & ks"],"doc":"disj[oin]. Returns a new set of the same (hashed/sorted) type, that\n does not contain key(s).","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/disj"},{"added":"1.0","ns":"clojure.core","name":"*2","file":"clojure/core.clj","type":"var","column":1,"see-alsos":[{"created-at":1303109714000,"author":{"login":"Havvy","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e799a79441c7543be48562403411cd13?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"*1","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521ad4"},{"created-at":1303109726000,"author":{"login":"Havvy","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e799a79441c7543be48562403411cd13?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"*3","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521ad5"}],"dynamic":true,"line":6350,"examples":[{"updated-at":1285502123000,"created-at":1279048024000,"body":"user=> \"Hello!\"\n\"Hello!\"\n\nuser=> \"Hello World!\"\n\"Hello World!\"\n\nuser=> [*1 *2]\n[\"Hello World!\" \"Hello!\"]\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/142529?v=3","account-source":"github","login":"nipra"},"_id":"542692c7c026201cdc326960"}],"notes":null,"arglists":[],"doc":"bound in a repl thread to the second most recent value printed","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/*2"},{"added":"1.0","ns":"clojure.core","name":"eval","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1318930260000,"author":{"login":"mmwaikar","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/29d36f4c9f39c9f8ff61c07033b13118?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"read-string","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ea3"}],"line":3228,"examples":[{"author":{"login":"dakrone","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bcacd00a7f05c4772329cf9f446c7987?r=PG&default=identicon"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":"user=> (def *foo* \"(println [1 2 3])\")\n#'user/*foo*\n\nuser=> *foo*\n\"(println [1 2 3])\"\n\nuser=> (eval *foo*) ; Notice eval'ing a string does not work.\n\"(println [1 2 3])\"\n\nuser=> (eval (read-string *foo*))\n[1 2 3]\nnil","created-at":1280547525000,"updated-at":1332949962000,"_id":"542692cec026201cdc326daf"},{"author":{"login":"steveminer","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d28543d134185d12d4006a74738d233e?r=PG&default=identicon"},"editors":[],"body":"user=> (eval '(let [a 10] (+ 3 4 a)))\n17\n","created-at":1308973342000,"updated-at":1308973342000,"_id":"542692cec026201cdc326db1"},{"updated-at":1458054160560,"created-at":1458054160560,"author":{"login":"APOS80","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/6387252?v=3"},"body":"(def x '(+ 2 3))\n(println x) \n=> (+ 2 3)\n(println (eval x))\n=> 5","_id":"56e82410e4b0507458dcf5a7"}],"notes":[{"updated-at":1308973573000,"body":"In normal code, `eval` is rarely used.","created-at":1308973573000,"author":{"login":"steveminer","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d28543d134185d12d4006a74738d233e?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fc2"},{"author":{"login":"eengebruiker","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/31795546?v=4"},"updated-at":1521045003085,"created-at":1521045003085,"body":"Once you get used to eval you will use it more often. You can make nifty things with it.","_id":"5aa94e0be4b0316c0f44f924"}],"arglists":["form"],"doc":"Evaluates the form data structure (not text!) and returns the result.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/eval"},{"added":"1.0","ns":"clojure.core","name":"cons","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1297212928000,"author":{"login":"TimMc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5d532e51427ef2f4ded31aaca16c8baf?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"conj","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d54"},{"created-at":1617817312569,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"seq","ns":"clojure.core"},"_id":"606deee0e4b0b1e3652d74b4"}],"line":22,"examples":[{"author":{"login":"dpritchett","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/147981?v=3"},"editors":[{"login":"dpritchett","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/147981?v=3"},{"login":"OnesimusUnbound","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2fa4c391db0d2d1744cc2cd0d787dd3d?r=PG&default=identicon"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":";; prepend 1 to a list\n(cons 1 '(2 3 4 5 6))\n;;=> (1 2 3 4 5 6)\n\n;; notice that the first item is not expanded\n(cons [1 2] [4 5 6])\n;;=> ([1 2] 4 5 6)","created-at":1279071078000,"updated-at":1420651535055,"_id":"542692ccc026201cdc326c5b"},{"body":";; may return results of different types but always a seq\n(map (juxt identity type seq? list?)\n [(cons 1 nil)\n (cons 1 '())])\n;; => ([(1) clojure.lang.PersistentList true true] \n;; [(1) clojure.lang.Cons true false])\n","author":{"login":"phalphalak","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/438136?v=3"},"created-at":1425547438764,"updated-at":1425547666700,"editors":[{"login":"phalphalak","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/438136?v=3"}],"_id":"54f820aee4b0b716de7a6530"},{"editors":[{"login":"TheCodingGent","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1191123?v=3"}],"body":";; Cons new-element into nested structures \"cons-in\"\n\n(def db {:users [{:name \"Eduardo\"}]})\n(def new-element {:name \"Eva\"})\n\n(assoc db :users (cons new-element (:users db)))\n;; => {:users ({:name \"Eva\"} {:name \"Eduardo\"})}","author":{"avatar-url":"https://avatars.githubusercontent.com/u/782909?v=3","account-source":"github","login":"edcaceres"},"created-at":1479822182560,"updated-at":1483975426262,"_id":"58344b66e4b0782b632278c4"},{"updated-at":1486154226776,"created-at":1486154226776,"author":{"login":"belun","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/282287?v=3"},"body":"(defn zeros [] \n (lazy-seq (cons 0 (zeros))))\n;; \"cons\" does not realize second parameter, \n;; opening the world for recursive functions that create lazy sequences\n\n(first (zeroes))\n0\n\n(first (rest (zeroes)))\n0\n\n(first (rest (rest (zeroes))))\n0\n\n;; example stolen from youtuber : \n;; https://youtu.be/iaph8m63HQw?list=PLAC43CFB134E85266","_id":"5894e9f2e4b01f4add58fe3b"},{"editors":[{"login":"earthfail","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/21296448?v=4"}],"body":";; this example might not work\n;; conj behave differently with \"set\" like structures.\n\n(def a-set #{1 2 3})\n\n(conj a-set 3) ;; will add 3 to the set\n;; => #{1 3 2}\n\n(conj a-set 4)\n;; => #{1 4 3 2}\n\n(first (conj a-set 4))\n;; => 1","author":{"avatar-url":"https://avatars2.githubusercontent.com/u/3019924?v=4","account-source":"github","login":"didiercrunch"},"created-at":1527347046020,"updated-at":1621162590490,"_id":"5b097766e4b045c27b7fac7b"}],"notes":[{"body":"useful for creating lazy sequences, because it does not need to realize the param \"seq\" (it just appends the whole thing to param \"x\"\n\nhttp://stackoverflow.com/questions/12389303/clojure-cons-vs-conj-with-lazy-seq","created-at":1486153640658,"updated-at":1486153936827,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/282287?v=3","account-source":"github","login":"belun"},"_id":"5894e7a8e4b01f4add58fe3a"}],"arglists":["x seq"],"doc":"Returns a new seq where x is the first element and seq is\n the rest.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/cons"},{"added":"1.0","ns":"clojure.core","name":"refer","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1327515389000,"author":{"login":"mmwaikar","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/29d36f4c9f39c9f8ff61c07033b13118?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"refer-clojure","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f2c"},{"created-at":1351990184000,"author":{"login":"Mark Addleman","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/768de71b6c873394290733acf422b4d5?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"ns","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f2d"}],"line":4243,"examples":[{"author":{"login":"teyc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bd6e62afb4881ab0f617611b8b65d003?r=PG&default=identicon"},"editors":[{"login":"teyc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bd6e62afb4881ab0f617611b8b65d003?r=PG&default=identicon"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"}],"body":"user=> (refer 'clojure.string :only '[capitalize trim])\nnil\n\nuser=> (capitalize (trim \" hOnduRAS \"))\n\"Honduras\"","created-at":1283925242000,"updated-at":1321967031000,"_id":"542692cdc026201cdc326d0b"},{"author":{"login":"ryo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3f7913b563c72083c74030d928ba407e?r=PG&default=identicon"},"editors":[{"login":"ryo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3f7913b563c72083c74030d928ba407e?r=PG&default=identicon"}],"body":"user=> (refer 'clojure.string\n :rename '{capitalize cap, trim trm})\nWARNING: replace already refers to: #'clojure.core/replace in namespace: user, being replaced by: #'clojure.string/replace\nWARNING: reverse already refers to: #'clojure.core/reverse in namespace: user, being replaced by: #'clojure.string/reverse\nnil\n\nuser=> (cap (trm \" hOnduRAS \"))\n\"Honduras\"\n\nuser=> (join \\, [1 2 3])\n\"1,2,3\"","created-at":1399370253000,"updated-at":1399636313000,"_id":"542692d5c026201cdc32706a"},{"author":{"login":"ryo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3f7913b563c72083c74030d928ba407e?r=PG&default=identicon"},"editors":[{"login":"ryo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3f7913b563c72083c74030d928ba407e?r=PG&default=identicon"},{"login":"ryo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3f7913b563c72083c74030d928ba407e?r=PG&default=identicon"}],"body":";;; `:only' accepts only original names.\n;; wrong\nuser=> (refer 'clojure.string\n :rename '{capitalize cap, trim trm}\n :only '[cap trm])\nIllegalAccessError cap does not exist clojure.core/refer (core.clj:3849)\n\n;; right\nuser=> (refer 'clojure.string\n :rename '{capitalize cap, trim trm}\n :only '[capitalize trim])\nnil\n\n;; work well\nuser=> (cap (trm \" hOnduRAS \"))\n\"Honduras\"\n\n;; and also, cannot use either of them.\nuser=> (join \\, [1 2 3])\nCompilerException java.lang.RuntimeException: Unable to resolve symbol: join in this context, compiling:(NO_SOURCE_PATH:1:1)","created-at":1399370354000,"updated-at":1399662756000,"_id":"542692d5c026201cdc32706c"}],"notes":[{"author":{"login":"KingMob","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/946421?v=4"},"updated-at":1671686270847,"created-at":1671686270847,"body":"Warning: the referral of a var isn't transitive. \n\n`refer` only works with a var's original namespace.\n\nIf you refer `A/foo` from `B`, you can't then refer `B/foo` from `C`.\n\n`foo` it will appear in `B`'s `ns-map`, but not `ns-publics` or `ns-interns`, unintuitively.","_id":"63a3e87ee4b08cf8563f4b54"}],"arglists":["ns-sym & filters"],"doc":"refers to all public vars of ns, subject to filters.\n filters can include at most one each of:\n\n :exclude list-of-symbols\n :only list-of-symbols\n :rename map-of-fromsymbol-tosymbol\n\n For each public interned var in the namespace named by the symbol,\n adds a mapping from the name of the var to the var to the current\n namespace. Throws an exception if name is already mapped to\n something else in the current namespace. Filters can be used to\n select a subset, via inclusion or exclusion, or to provide a mapping\n to a symbol different from the var's name, in order to prevent\n clashes. Use :use in the ns macro in preference to calling this directly.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/refer"},{"ns":"clojure.core","name":"print-dup","file":"clojure/core.clj","type":"var","column":1,"see-alsos":[{"created-at":1300959285000,"author":{"login":"TimMc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5d532e51427ef2f4ded31aaca16c8baf?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"print-ctor","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e2a"},{"created-at":1332539534000,"author":{"login":"abrooks","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/69976?v=2"},"to-var":{"ns":"clojure.core","name":"print-method","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e2b"}],"line":3692,"examples":[{"author":{"login":"cdorrat","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5dedcb7069d39421760f6d255def10c3?r=PG&default=identicon"},"editors":[{"login":"cdorrat","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5dedcb7069d39421760f6d255def10c3?r=PG&default=identicon"}],"body":";; print-dup can be used for basic serialization\n;; the following methods write/read clojure forms to/from a file\n\n(defn to-file\n \"Save a clojure form to a file\"\n [#^java.io.File file form]\n (with-open [w (java.io.FileWriter. file)]\n (print-dup form w)))\n \n(defn from-file\n \"Load a clojure form from file.\"\n [#^java.io.File file]\n (with-open [r (java.io.PushbackReader. (java.io.FileReader. file))]\n (read r)))","created-at":1300104716000,"updated-at":1300104999000,"_id":"542692cac026201cdc326b8c"},{"author":{"login":"cdorrat","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5dedcb7069d39421760f6d255def10c3?r=PG&default=identicon"},"editors":[],"body":";; print-dup is a multimethod, you can extend it to support new types.\n;; The following statement adds print-dup support to \n;; the java.util.Date class\n(defmethod print-dup java.util.Date [o w]\n (print-ctor o (fn [o w] (print-dup (.getTime o) w)) w)) ","created-at":1300104973000,"updated-at":1300104973000,"_id":"542692cac026201cdc326b8e"}],"notes":[{"updated-at":1300480179000,"body":"This is a multimethod that can be implemented to define the printing of various values when \\*print-dup\\* is bound to true.","created-at":1299414938000,"author":{"login":"TimMc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5d532e51427ef2f4ded31aaca16c8baf?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fb7"}],"arglists":[],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core/print-dup"},{"ns":"clojure.core","name":"-reset-methods","file":"clojure/core_deftype.clj","type":"function","column":1,"see-alsos":null,"line":630,"examples":null,"notes":null,"arglists":["protocol"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core/-reset-methods"},{"added":"1.0","ns":"clojure.core","name":"floats","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1658139428172,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"float-array","ns":"clojure.core"},"_id":"62d53324e4b0b1e3652d7624"}],"line":5421,"examples":[{"updated-at":1658139411698,"created-at":1658139411698,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":";; float-array will convert where possible\n(float-array [1 2 3]);; => [1.0, 2.0, 3.0]\n\n;; floats will not\n(try (floats [1 2 3])\n (catch ClassCastException e (ex-message e)))\n;; => \"clojure.lang.PersistentVector cannot be cast to [F\"","_id":"62d53313e4b0b1e3652d7623"},{"updated-at":1682271661910,"created-at":1682271661910,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":";; Casting avoids expensive reflection, so to see the benefit, enable warning:\n(set! *warn-on-reflection* true)\n\n;; We'll def a float-array but won't type-hint the var:\n(def my-array (float-array [10.0 20.0 30.0 40.0 50.0 60.0]))\n\n;; and try to amap over it without using `floats` or type hinting:\n(amap my-array i _ (unchecked-float (unchecked-inc (aget my-array i))))\n;; Reflection warning… call to static method alength on clojure.lang.RT can't be resolved (argument types: unknown).\n;; Reflection warning… call to static method aclone on clojure.lang.RT can't be resolved (argument types: unknown).\n;; Reflection warning… call to static method aget on clojure.lang.RT can't be resolved (argument types: unknown, int).\n;; Reflection warning… call to static method aset on clojure.lang.RT can't be resolved (argument types: unknown, int, float).\n;; => [11.0, 21.0, 31.0, 41.0, 51.0, 61.0]\n\n;; We can use `floats` to avoid reflection:\n(amap (floats my-array) i _ (unchecked-float (unchecked-inc (aget (floats my-array) i))))\n;; => [11.0, 21.0, 31.0, 41.0, 51.0, 61.0]\n\n;; Just as we can type hint in place:\n(amap ^floats my-array i _ (unchecked-float (unchecked-inc (aget ^floats my-array i))))\n;; => [11.0, 21.0, 31.0, 41.0, 51.0, 61.0]\n\n;; Or type hint the var:\n(def ^\"[F\" my-array (float-array [10 20 30 40 50 60]))\n(amap my-array i _ (unchecked-float (unchecked-inc (aget my-array i))))\n;; => [11.0, 21.0, 31.0, 41.0, 51.0, 61.0]\n","_id":"64456dade4b08cf8563f4b93"}],"notes":null,"arglists":["xs"],"doc":"Casts to float[]","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/floats"},{"added":"1.12","ns":"clojure.core","name":"partitionv","file":"clojure/core.clj","type":"function","column":1,"see-alsos":null,"line":7428,"examples":null,"notes":null,"arglists":["n coll","n step coll","n step pad coll"],"doc":"Returns a lazy sequence of vectors of n items each, at offsets step\n apart. If step is not supplied, defaults to n, i.e. the partitions\n do not overlap. If a pad collection is supplied, use its elements as\n necessary to complete last partition upto n items. In case there are\n not enough padding elements, return a partition with less than n items.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/partitionv"},{"added":"1.0","ns":"clojure.core","name":"pos?","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1345518606000,"author":{"login":"cbare","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/b394e97f24f3576861239e2b839703a4?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"neg?","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e09"},{"created-at":1400618875000,"author":{"login":"ryo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3f7913b563c72083c74030d928ba407e?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"zero?","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e0a"},{"created-at":1587669222475,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"nat-int?","ns":"clojure.core"},"_id":"5ea1e8e6e4b087629b5a18e1"},{"created-at":1609194007084,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"pos-int?","ns":"clojure.core"},"_id":"5fea5a17e4b0b1e3652d7424"}],"line":1261,"examples":[{"author":{"login":"dpritchett","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/147981?v=3"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"avatar-url":"https://avatars.githubusercontent.com/u/7412474?v=3","account-source":"github","login":"Lacty"}],"body":"user=> (pos? 1)\ntrue\nuser=> (pos? 0)\nfalse\nuser=> (pos? -1)\nfalse","created-at":1279074734000,"updated-at":1471000907146,"_id":"542692cdc026201cdc326cff"},{"updated-at":1471000959608,"created-at":1471000959608,"author":{"login":"Lacty","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7412474?v=3"},"body":"user=> (pos? 0.1)\ntrue\nuser=> (pos? -0.1)\nfalse","_id":"57adb17fe4b0bafd3e2a04ec"},{"updated-at":1598394302046,"created-at":1598394302046,"author":{"login":"berczeck","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/1321842?v=4"},"body":"user=> (pos? 1/2)\n;; true\n\nuser=> (pos? -1/2)\n;; false\n\nuser=> (pos? {})\n;; Execution error (ClassCastException) at user/eval3795 (REPL:1).\n;; clojure.lang.PersistentArrayMap cannot be cast to java.lang.Number","_id":"5f458fbee4b0b1e3652d73ab"}],"notes":null,"arglists":["num"],"doc":"Returns true if num is greater than zero, else false","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/pos_q"},{"added":"1.2","ns":"clojure.core","name":"fnil","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1548717313952,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"partial","ns":"clojure.core"},"_id":"5c4f8d01e4b0ca44402ef656"},{"created-at":1548717329309,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"comp","ns":"clojure.core"},"_id":"5c4f8d11e4b0ca44402ef657"},{"created-at":1548717337353,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"juxt","ns":"clojure.core"},"_id":"5c4f8d19e4b0ca44402ef658"},{"created-at":1608656139520,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"or","ns":"clojure.core"},"_id":"5fe2250be4b0b1e3652d741a"},{"created-at":1609357960896,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"some-fn","ns":"clojure.core"},"_id":"5fecda88e4b0b1e3652d7426"}],"line":6635,"examples":[{"author":{"login":"looselytyped","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9bfc2e772db334c8b8516c86b9da7a0c?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"}],"body":";; a function that expects a non-nil value\n(defn say-hello [name] (str \"Hello \" name))\n;;=> #'user/say-hello\n\n;; fnil lets you create another function with a default\n;; arg in case it is passed a nil\n(def say-hello-with-defaults (fnil say-hello \"World\"))\n;;=> #'user/say-hello-with-defaults\n\n;; the happy path works as you would expect\n(say-hello-with-defaults \"Sir\")\n;;=> \"Hello Sir\"\n\n;; but in the case that the function is passed a nil it will use the \n;; default supplied to fnil\n(say-hello-with-defaults nil)\n;;=> \"Hello World\"\n\n;; this works with different arities too\n(defn say-hello [first other] (str \"Hello \" first \" and \" other))\n;;=> #'user/say-hello\n\n;; lets create it with defaults\n(def say-hello-with-defaults (fnil say-hello \"World\" \"People\"))\n;;=> #'user/say-hello-with-defaults\n\n;; call the function with all nil args - notice it uses the defaults\n;; supplied to fnil\n(say-hello-with-defaults nil nil)\n;;=> \"Hello World and People\"\n\n;; any of the args can be nil - the function will supply \n;; the default supplied with fnil\n(say-hello-with-defaults \"Sir\" nil)\n;;=> \"Hello Sir and People\"\n\n;; and again - notice that \"World\" is the default here\n(say-hello-with-defaults nil \"Ma'am\")\n;;=> \"Hello World and Ma'am\"\n\n;; or pass all args \n(say-hello-with-defaults \"Sir\" \"Ma'am\")\n;;=> \"Hello Sir and Ma'am\"\n","created-at":1284845008000,"updated-at":1412880276286,"_id":"542692cdc026201cdc326ce4"},{"body":";; Treat nil as 0 for the purposes of incrementing\n((fnil inc 0) nil)\n;;=> 1\n;; While the following would not work:\n(inc nil)\n;;=> NullPointerException clojure.lang.Numbers.ops (Numbers.java:961)\n\n;; fnil is very useful for specifying default values when updating maps\n;; For a map containing counters of keys:\n(update-in {:a 1} [:a] inc)\n;;=> {:a 2}\n\n;; Oops, our map does not have a key :b and update-in passes nil to inc\n(update-in {:a 1} [:b] inc)\n;;=> NullPointerException clojure.lang.Numbers.ops (Numbers.java:961)\n\n;; But if we use fnil it works:\n(update-in {:a 1} [:b] (fnil inc 0))\n;;=> {:b 1, :a 1}\n\n;; Another example is when map values are collections and we don't want\n;; default behavior of conj with nil that produces a list\n(conj nil 1)\n;;=> (1)\n;; I.e.\n(update-in {} [:a] conj 1)\n;;=> {:a (1)}\n\n;; But say we want map values to be vectors instead:\n(update-in {} [:a] (fnil conj []) 1)\n;;=> {:a [1]}","author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"created-at":1422935102507,"updated-at":1422935102507,"_id":"54d0443ee4b0e2ac61831cf7"},{"editors":[{"login":"KyleErhabor","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/40676441?v=4"}],"body":";;; Note that `fnil` still requires the appropriate number of arguments for an\n;;; arity (i.e. no \"implicit\" default)\n\n(def tempids {-1 1\n -2 2\n -3 3})\n\n(def id (fnil get nil -1))\n\n;; You may expect `fnil` to implicitly add -1 as the last argument, but that's\n;; not true.\n(id tempids)\n;;=> ArityException: Wrong number of args (1) passed to: clojure.core/fnil/fn--...\n\n;; But it will here, since the argument is there (as `nil`).\n(id tempids nil)\n;;=> 1\n\n;; Of course, you can supply it explicitly.\n(id tempids -1)\n;;=> 1","author":{"avatar-url":"https://avatars.githubusercontent.com/u/40676441?v=4","account-source":"github","login":"KyleErhabor"},"created-at":1642980269186,"updated-at":1642980293301,"_id":"61ede3ade4b0b1e3652d75a1"}],"notes":null,"arglists":["f x","f x y","f x y z"],"doc":"Takes a function f, and returns a function that calls f, replacing\n a nil first argument to f with the supplied value x. Higher arity\n versions can replace arguments in the second and third\n positions (y, z). Note that the function f can take any number of\n arguments, not just the one(s) being nil-patched.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/fnil"},{"added":"1.0","ns":"clojure.core","name":"merge-with","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1294676734000,"author":{"login":"Nebulus","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/61aa4140c24b0cded6b20d88200e7f16?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"merge","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e16"}],"line":3075,"examples":[{"author":{"avatar-url":"https://avatars.githubusercontent.com/u/142529?v=3","account-source":"github","login":"nipra"},"editors":[{"login":"nipra","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/142529?v=3"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"},{"avatar-url":"https://avatars.githubusercontent.com/u/39192?v=3","account-source":"github","login":"mlanza"}],"body":"(merge-with into\n\t {\"Lisp\" [\"Common Lisp\" \"Clojure\"]\n\t \"ML\" [\"Caml\" \"Objective Caml\"]}\n\t {\"Lisp\" [\"Scheme\"]\n\t \"ML\" [\"Standard ML\"]})\n;;=> {\"Lisp\" [\"Common Lisp\" \"Clojure\" \"Scheme\"], \"ML\" [\"Caml\" \"Objective Caml\" \"Standard ML\"]}","created-at":1279052705000,"updated-at":1495768299408,"_id":"542692cec026201cdc326dce"},{"author":{"login":"fogus","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5aa24eee4238e1e964210ed447e8dc91?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":";; merge two maps using the addition function\n\n(merge-with + \n {:a 1 :b 2}\n {:a 9 :b 98 :c 0}) \n;;=> {:c 0, :a 10, :b 100}","created-at":1279058935000,"updated-at":1422375185880,"_id":"542692cec026201cdc326dd1"},{"updated-at":1422375228363,"created-at":1279059124000,"body":";; 'merge-with' works with an arbitrary number of maps:\n\n(merge-with + \n {:a 1 :b 2}\n {:a 9 :b 98 :c 0}\n {:a 10 :b 100 :c 10}\n {:a 5}\n {:c 5 :d 42})\n \n;;=> {:d 42, :c 15, :a 25, :b 200}","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/142529?v=3","account-source":"github","login":"nipra"},{"avatar-url":"https://avatars.githubusercontent.com/u/142529?v=3","account-source":"github","login":"nipra"},{"avatar-url":"https://www.gravatar.com/avatar/5aa24eee4238e1e964210ed447e8dc91?r=PG&default=identicon","account-source":"clojuredocs","login":"fogus"},{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3","account-source":"github","login":"phreed"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/5aa24eee4238e1e964210ed447e8dc91?r=PG&default=identicon","account-source":"clojuredocs","login":"fogus"},"_id":"542692cec026201cdc326dd3"},{"author":{"login":"jaley","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d8dc27aff613e5972bb6af8521a07891?r=PG&default=identicon"},"editors":[{"login":"Iceland_jack","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/c889e0a95a3bb07f90ab28ad442f1127?r=PG&default=identicon"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":";; Use union to merge sets of elements\n(use 'clojure.set)\n(merge-with union\n {:a #{1 2 3}, :b #{4 5 6}}\n {:a #{2 3 7 8}, :c #{1 2 3}})\n\n;;=> {:c #{1 2 3}, :a #{1 2 3 7 8}, :b #{4 5 6}}","created-at":1325882151000,"updated-at":1422375252797,"_id":"542692d4c026201cdc32700f"},{"body":";; Demonstrating difference between merge and merge-with\n\n;; For merge the value from the right-most map wins:\n(merge {:a 1} {:a 2} {:a 3})\n;;=> {:a 3}\n\n;; while for merge-with values are merged (with function + in this example):\n(merge-with + {:a 1} {:a 2} {:a 3})\n;;=> {:a 6}","author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"created-at":1422935798019,"updated-at":1423014440333,"editors":[{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"}],"_id":"54d046f6e4b0e2ac61831cf8"},{"body":";; Use merge-with and merge to merge values that are one level deep maps.\n\n(merge-with merge {:x {:y 1}} {:x {:z 2}})\n;;=> {:x {:z 2, :y 1}}\n\n;; Deeper maps are not merged:\n(merge-with merge {:x {:y {:a 1}}} {:x {:y {:b 2}}})\n;;=>{:x {:y {:b 2}}}","author":{"login":"dmos62","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2715476?v=3"},"created-at":1427644396920,"updated-at":1427644529515,"editors":[{"login":"dmos62","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2715476?v=3"}],"_id":"55181fece4b08eb9aa0a8d3c"},{"updated-at":1448314167339,"created-at":1448313757814,"author":{"login":"mlanza","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/39192?v=3"},"body":";;Use into to avoid losing the shape (i.e. a vector) of the original data:\n(merge-with into\n\t {\"Lisp\" [\"Common Lisp\" \"Clojure\"]\n\t \"ML\" [\"Caml\" \"Objective Caml\"]}\n\t {\"Lisp\" [\"Scheme\"]\n\t \"ML\" [\"Standard ML\"]})\n;;=> {\"Lisp\" [\"Common Lisp\" \"Clojure\" \"Scheme\"], \"ML\" [\"Caml\" \"Objective Caml\" \"Standard ML\"]}\n\n;;No need to use type-specific verbs such as union:\n(merge-with into\n {:a #{1 2 3}, :b #{4 5 6}}\n {:a #{2 3 7 8}, :c #{1 2 3}})\n;;=> {:c #{1 2 3}, :a #{1 2 3 7 8}, :b #{4 5 6}}","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/39192?v=3","account-source":"github","login":"mlanza"}],"_id":"5653839de4b0be225c0c4799"},{"editors":[{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/94482?v=3"}],"body":";; Note that merge-with is fundamentally additive, which can have unintuitive\n;; consequences if you are using a subtractive operation.\n(require '[clojure.set :as set])\n\n;; Subtract members of one set from another with the same keys:\n\n(merge-with set/difference {:a #{1 2 3}} {:a #{1}})\n;;=> {:a #{3 2}}\n\n(merge-with set/difference {:a #{1 2 3} :b #{2}} {:a #{1} :b #{4}})\n;;=> {:a #{3 2}, :b #{2}}\n\n;; If a key in the second map doesn't occur in the first, (merge-with) will \n;; simply copy it as in (merge), and the passed-in function will not be called:\n\n(merge-with set/difference {:a #{1 2 3}} {:a #{1} :z #{4}})\n;;=> {:a #{3 2}, :z #{4}}\n\n;; The solution in this case is to ensure that both maps have the same keys:\n\n(merge-with set/difference {:a #{1 2 3} :z #{}} {:a #{1} :z #{4}})\n;;=> {:a #{3 2}, :z #{}}","author":{"avatar-url":"https://avatars.githubusercontent.com/u/94482?v=3","account-source":"github","login":"timgilbert"},"created-at":1488321014610,"updated-at":1488321184789,"_id":"58b5f9f6e4b01f4add58fe67"},{"updated-at":1535151143457,"created-at":1535149114035,"author":{"login":"dijonkitchen","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/11434205?v=4"},"body":"(defn deep-merge-with\n \"Like merge-with, but merges maps recursively, applying the given fn\n only when there's a non-map at a particular level.\n (deep-merge-with + {:a {:b {:c 1 :d {:x 1 :y 2}} :e 3} :f 4}\n {:a {:b {:c 2 :d {:z 9} :z 3} :e 100}})\n -> {:a {:b {:z 3, :c 3, :d {:z 9, :x 1, :y 2}}, :e 103}, :f 4}\"\n [f & maps]\n (apply\n (fn m [& maps]\n (if (every? map? maps)\n (apply merge-with m maps)\n (apply f maps)))\nmaps))\n\n(deep-merge-with + {:a {:b {:c 1 :d {:x 1 :y 2}} :e 3} :f 4}\n {:a {:b {:c 2 :d {:z 9} :z 3} :e 100}})\n;; {:a {:b {:z 3, :c 3, :d {:z 9, :x 1, :y 2}}, :e 103}, :f 4}\n\n(deep-merge-with + {:foo {:bar {:baz 1}}}\n {:foo {:bar {:baz 6 :qux 42}}})\n;; {:foo {:bar {:baz 7, :qux 42}}}\n\n;; Source: https://clojure.github.io/clojure-contrib/map-utils-api.html#clojure.contrib.map-utils/deep-merge-with","editors":[{"avatar-url":"https://avatars3.githubusercontent.com/u/11434205?v=4","account-source":"github","login":"dijonkitchen"}],"_id":"5b80843ae4b00ac801ed9e74"},{"updated-at":1590172835865,"created-at":1590172728020,"author":{"login":"themustafabasit","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/24441401?v=4"},"body":"\n;; I will be explaining it From java perspective\n\n;; merge-with is like conflict resolver function that \n;; we have in java - map.merge(key, val, (v1, v2)-> ...... )\n\n;; resolve conflict by discarding second value\n(defn conflict-resolver\n [v1 v2]\n (println \"conflict is between these values: \" v1 v2 ) \n v1)\n\n(merge-with conflict-resolver\n {:a 2 :b 4 :c 5}\n {:a 1}\n {:a 9 :b 3 :c 10 :d 3})\n;; => conflict is between these values: 2 1 - a,a\n;; conflict is between these values: 2 9 - new a, a\n;; conflict is between these values: 4 3 - b,b\n;; conflict is between these values: 5 10 - c,c\n;; {:a 2, :b 4, :c 5, :d 3}\n\n\n;; example - 2\n\n;; resolve conflict by adding both values\n(defn conflict-resolver\n [v1 v2]\n (println \"conflict is between these values: \" v1 v2)\n (+ v1 v2))\n\n(merge-with conflict-resolver\n {:a 2 :b 4 :c 5}\n {:a 1}\n {:a 9 :b 3 :c 10 :d 3})\n;; => conflict is between these values: 2 1 - a,a\n;; conflict is between these values: 3 9 - new a, a\n;; conflict is between these values: 4 3 - b,b\n;; conflict is between these values: 5 10 - c,c\n;; {:a 12, :b 7, :c 15, :d 3}\n\n","editors":[{"avatar-url":"https://avatars2.githubusercontent.com/u/24441401?v=4","account-source":"github","login":"themustafabasit"}],"_id":"5ec81c38e4b087629b5a1912"},{"updated-at":1637867197307,"created-at":1637867197307,"author":{"login":"joshuamzm","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10285345?v=4"},"body":";; deep-merge version of clojure.core/merge\n\n(defn deep-merge [& maps]\n (letfn [(reconcile-keys [val-in-result val-in-latter]\n (if (and (map? val-in-result)\n (map? val-in-latter))\n (merge-with reconcile-keys val-in-result val-in-latter)\n val-in-latter))\n (reconcile-maps [result latter]\n (merge-with reconcile-keys result latter))]\n (reduce reconcile-maps maps)))\n\n(deep-merge\n {:a 1 :b {:c {:g 99} :d 3}}\n {:a 10 :b {:c {:g 98} :e 4}}\n {:a 100 :b {:c {:g 97} :e 40 :f 5}})\n\n;; => {:a 100, :b {:c {:g 97}, :d 3, :e 40, :f 5}}\n\n;; Take into account processing latter maps with non-maps values \"override\"\n;; previously seen map values.\n\n(deep-merge\n {:deep {:deeep {:a 1}}}\n {:deep {:deeep {:b 2}}}\n {:a 34 :deep 8 :v 3})\n\n;; => {:deep 8, :a 34, :v 3}\n\n;; We decided to define reconcile-maps, which is the then-branch expression\n;; of the if within reconcile-keys. This way, using reduce will throw errors\n;; as when using merge-with with non-map arguments.\n\n(deep-merge 1 {:a 1})\n\n;; IllegalArgumentException contains? not supported on type: java.lang.Long ...\n\n(deep-merge {:a 1} 2)\n\n;; IllegalArgumentException Don't know how to create ISeq from: java.lang.Long ...\n\n\n\n;; Reviewed and help received from github.com/datz","_id":"619fdebde4b0b1e3652d757a"}],"notes":null,"arglists":["f & maps"],"doc":"Returns a map that consists of the rest of the maps conj-ed onto\n the first. If a key occurs in more than one map, the mapping(s)\n from the latter (left-to-right) will be combined with the mapping in\n the result by calling (f val-in-result val-in-latter).","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/merge-with"},{"added":"1.3","ns":"clojure.core","name":"nthrest","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1356088808000,"author":{"login":"TimMc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5d532e51427ef2f4ded31aaca16c8baf?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"drop","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ddb"},{"created-at":1356088885000,"author":{"login":"TimMc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5d532e51427ef2f4ded31aaca16c8baf?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"nthnext","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ddc"},{"created-at":1356088888000,"author":{"login":"TimMc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5d532e51427ef2f4ded31aaca16c8baf?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"nth","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ddd"},{"created-at":1505013505146,"author":{"login":"didibus","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/601540?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"rest","ns":"clojure.core"},"_id":"59b4af01e4b09f63b945ac68"},{"created-at":1505013511258,"author":{"login":"didibus","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/601540?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"next","ns":"clojure.core"},"_id":"59b4af07e4b09f63b945ac69"}],"line":3186,"examples":[{"author":{"login":"jmglov","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/67e9a6f766dc4b30bd5e9ff3e77c1777?r=PG&default=identicon"},"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":"(nthrest (range 10) 5)\n;;=> (5 6 7 8 9)\n\n;; in many cases gives the same result as nthnext\n(nthnext (range 10) 5)\n;;=> (5 6 7 8 9)\n\n;; here is a case where the results differ\n(nthrest [] 3) ;;=> []\n(nthnext [] 3) ;;=> nil\n\n(nthrest [1 2 3 4 5 6 7] 4)\n;;=> (5 6 7)","created-at":1338817014000,"updated-at":1420737060810,"_id":"542692d4c026201cdc327021"},{"body":";; drop is also similar, but lazy \n(nthrest (range 10) 5) ;;=> (5 6 7 8 9)\n(drop 5 (range 10)) ;;=> (5 6 7 8 9)\n\n;; here is a case where the results differ\n(nthrest [] 3) ;;=> []\n(drop 3 []) ;;=> () ; returning a lazy sequence","author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"},"created-at":1420737465554,"updated-at":1420737465554,"_id":"54aebbb9e4b0e2ac61831c98"},{"editors":[{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"}],"body":";; nthrest eagerly evaluates the dropped items:\n\n(def a (nthrest (map #(do (print \".\") %) (iterate inc 0)) 10))\n;; ..........#'user/a (note: processing already started)\n\n(def b (drop 10 (map #(do (print \".\") %) (iterate inc 0))))\n;; #'user/b (note: no evaluation)\n\n;; Possible use: always produce side effects (if any) independently \n;; from evaluation of kept items.","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"},"created-at":1521467358474,"updated-at":1521467381232,"_id":"5aafbfdee4b0316c0f44f92d"},{"updated-at":1661527937101,"created-at":1661527937101,"author":{"login":"jimka2001","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/6414129?v=4"},"body":";; nthrest returns a suffix of the given sequence","_id":"6308e781e4b0b1e3652d7652"}],"notes":[{"updated-at":1356088840000,"body":"This differs from clojure.core/drop in that it immediately drops the head of the seq, instead of doing so on the first call to first or seq.","created-at":1356088381000,"author":{"login":"TimMc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5d532e51427ef2f4ded31aaca16c8baf?r=PG&default=identicon"},"_id":"542692edf6e94c6970521ff9"}],"arglists":["coll n"],"doc":"Returns the nth rest of coll, coll when n is 0.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/nthrest"},{"added":"1.0","ns":"clojure.core","name":"load","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1286271399000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"load-file","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c29"},{"created-at":1352963712000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.core","name":"*read-eval*","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c2a"},{"created-at":1519290672082,"author":{"login":"witek","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/209520?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"load-string","ns":"clojure.core"},"_id":"5a8e8930e4b0316c0f44f8ea"}],"line":6172,"examples":[{"updated-at":1546453955894,"created-at":1307936370000,"body":";; file located at src/address_book/core.clj and current namespace\n;; located at root of the classpath, such as \"user\".\n\n(load \"address_book/core\")","editors":[{"avatar-url":"https://www.gravatar.com/avatar/1c0c20072f52de3a6335cae183b865f6?r=PG&default=identicon","account-source":"clojuredocs","login":"lambder"},{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/1c0c20072f52de3a6335cae183b865f6?r=PG&default=identicon","account-source":"clojuredocs","login":"lambder"},"_id":"542692cbc026201cdc326c1b"},{"updated-at":1546454215490,"created-at":1546454215490,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"body":";; Loading from root of the classpath, such as user namespace\n\n(ns user)\n(load \"/clojure/set\")\n;; nil\n\n;; Loading \"clojure/xml.clj\" from a relative location in the classpath \n;; does not want the \"/\"\n\n(ns clojure.set)\n(load \"xml\")\n;; nil","_id":"5c2d04c7e4b0ca44402ef60b"}],"notes":null,"arglists":["& paths"],"doc":"Loads Clojure code from resources in classpath. A path is interpreted as\n classpath-relative if it begins with a slash or relative to the root\n directory for the current namespace otherwise.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/load"},{"added":"1.0","ns":"clojure.core","name":"if-not","file":"clojure/core.clj","type":"macro","column":1,"see-alsos":[{"created-at":1334293416000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.core","name":"if","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e44"},{"created-at":1374149749000,"author":{"login":"alilee","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2fb0196dc5a7cd3a5cc73f1b9941c209?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"when-not","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e45"}],"line":769,"examples":[{"author":{"login":"zmila","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/68dd6f50915854aa04fefcf4d6fa5c8e?r=PG&default=identicon"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":"user=> (defn has-neg [coll] \n (if-not (empty? coll) ;; = (if (not (empty? coll)) ...\n (or (neg? (first coll)) (recur (rest coll)))))\n#'user/has-neg\n\nuser=> (has-neg [])\nnil \n\nuser=> (has-neg [1 2 -3 4])\ntrue","created-at":1280505406000,"updated-at":1332951095000,"_id":"542692c6c026201cdc32692d"},{"author":{"login":"zmila","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/68dd6f50915854aa04fefcf4d6fa5c8e?r=PG&default=identicon"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":"user=> (if-not (zero? 0) :then :else)\n:else","created-at":1280506136000,"updated-at":1332951114000,"_id":"542692c6c026201cdc32692f"},{"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"editors":[],"body":";; See examples for \"if\" explaining Clojure's idea of logical true\n;; and logical false.","created-at":1334293411000,"updated-at":1334293411000,"_id":"542692d3c026201cdc326fcd"}],"macro":true,"notes":null,"arglists":["test then","test then else"],"doc":"Evaluates test. If logical false, evaluates and returns then expr, \n otherwise else expr, if supplied, else nil.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/if-not"},{"added":"1.12","ns":"clojure.core","name":"stream-into!","file":"clojure/core.clj","type":"function","column":1,"see-alsos":null,"line":6887,"examples":null,"notes":null,"arglists":["to stream","to xform stream"],"doc":"Returns a new coll consisting of coll with all of the items of the\n stream conjoined. This is a terminal operation on the stream.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/stream-into!"},{"ns":"clojure.core","name":"*verbose-defrecords*","file":"clojure/core_print.clj","type":"var","column":1,"see-alsos":null,"dynamic":true,"line":39,"examples":null,"notes":null,"arglists":[],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core/*verbose-defrecords*"},{"added":"1.0","ns":"clojure.core","name":"sequential?","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1304804232000,"author":{"login":"0x89","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/56bc4acd59315ed4dc1cb99c3be71102?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"seq?","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d22"},{"created-at":1304804263000,"author":{"login":"0x89","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/56bc4acd59315ed4dc1cb99c3be71102?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"coll?","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d23"},{"created-at":1521067928760,"author":{"login":"glts","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/1483271?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"seqable?","ns":"clojure.core"},"_id":"5aa9a798e4b0316c0f44f925"}],"line":6306,"examples":[{"author":{"login":"rustem.suniev","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e2051c4ebaaa8c22fa9c0bb2f32f64fd?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},{"login":"pmbauer","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/65f765955a0a25d112d33528ae6f811b?r=PG&default=identicon"},{"avatar-url":"https://avatars.githubusercontent.com/u/1296500?v=3","account-source":"github","login":"lijunle"},{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=4"}],"body":";; You may also find this useful: https://insideclojure.org/2015/01/02/sequences\n\nuser=> (sequential? '(1 2 3))\ntrue\n\nuser=> (sequential? [1 2 3])\ntrue\n\nuser=> (sequential? (range 1 5))\ntrue\n\nuser=> (sequential? '())\ntrue\n\nuser=> (sequential? [])\ntrue\n\nuser=> (sequential? nil)\nfalse\n\nuser=> (sequential? 1)\nfalse\n\nuser=> (sequential? \"abc\")\nfalse\n\nuser=> (sequential? {:a 2 :b 1})\nfalse\n\nuser=> (sequential? #{1 2 3})\nfalse","created-at":1284875508000,"updated-at":1694799209057,"_id":"542692c6c026201cdc3268f4"},{"updated-at":1660931114232,"created-at":1660931114232,"author":{"login":"KGOH","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/11963737?v=4"},"body":";; Be careful while traversing data:\n;; map entries are vectors and thus sequential!\n\nuser=> (sequential? (first {:a 1}))\ntrue\n\nuser=> (sequential? (clojure.lang.MapEntry. :a 1))\ntrue\n\nuser=> (vector? (first {:a 1}))\ntrue\n\nuser=> (vector? (clojure.lang.MapEntry. :a 1))\ntrue\n\nuser=> (clojure.walk/postwalk\n #(cond-> % (sequential? %) set)\n {:a [1 1 2 3]})\n; Unhandled java.lang.ClassCastException\n; class clojure.lang.PersistentHashSet cannot be cast to class\n; java.util.Map$Entry (clojure.lang.PersistentHashSet is in unnamed module of\n; loader 'app'; java.util.Map$Entry is in module java.base of loader\n; 'bootstrap')\n\nuser=> (clojure.walk/postwalk\n #(cond-> %\n (and (sequential? %)\n (not (map-entry? %)))\n set)\n {:a [1 1 2 3]})\n{:a #{1 3 2}}\n","_id":"62ffcc2ae4b0b1e3652d763f"}],"notes":[{"author":{"login":"zackteo","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/7510179?v=4"},"updated-at":1603928204513,"created-at":1603927987239,"body":"Of the four key collection types, vectors and lists are ordered (aka sequential). Sets and maps are not.","_id":"5f99ffb3e4b0b1e3652d73f9"}],"arglists":["coll"],"doc":"Returns true if coll implements Sequential","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/sequential_q"},{"added":"1.0","ns":"clojure.core","name":"*print-level*","file":"clojure/core_print.clj","type":"var","column":1,"see-alsos":[{"created-at":1767373647556,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"*print-length*","ns":"clojure.core"},"_id":"6957fb4fb7956e24e4cb4ec9"}],"dynamic":true,"line":27,"examples":[{"body":"user=> *print-level*\nnil\nuser=> [1 [2 [3]]]\n[1 [2 [3]]]\n\nuser=> (set! *print-level* 2)\n2\nuser=> [1 [2 [3]]]\n[1 [2 #]]","author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"created-at":1423526085099,"updated-at":1423526085099,"_id":"54d948c5e4b081e022073c7f"}],"notes":null,"arglists":[],"doc":"*print-level* controls how many levels deep the printer will\n print nested objects. If it is bound to logical false, there is no\n limit. Otherwise, it must be bound to an integer indicating the maximum\n level to print. Each argument to print is at level 0; if an argument is a\n collection, its items are at level 1; and so on. If an object is a\n collection and is at a level greater than or equal to the value bound to\n *print-level*, the printer prints '#' to represent it. The root binding\n is nil indicating no limit.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/*print-level*"},{"added":"1.12","ns":"clojure.core","name":"stream-reduce!","file":"clojure/core.clj","type":"function","column":1,"see-alsos":null,"line":6861,"examples":null,"notes":null,"arglists":["f s","f init s"],"doc":"Works like reduce but takes a java.util.stream.BaseStream as its source.\n Honors 'reduced', is a terminal operation on the stream","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/stream-reduce!"},{"added":"1.2","ns":"clojure.core","name":"shuffle","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1434034887985,"author":{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/94482?v=3"},"to-var":{"ns":"clojure.core","name":"rand-nth","library-url":"https://github.com/clojure/clojure"},"_id":"5579a2c7e4b03e2132e7d18b"},{"created-at":1554235245442,"author":{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/94482?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"random-sample","ns":"clojure.core"},"_id":"5ca3bf6de4b0ca44402ef6fa"}],"line":7466,"examples":[{"updated-at":1578337855496,"created-at":1282319846000,"body":";; Make five permutations of the [1 2 3] vector.\n;; Always returns a vector.\n(repeatedly 5 (partial shuffle [1 2 3]))\n;;=> ([2 3 1] [2 1 3] [2 3 1] [3 2 1] [3 1 2])\n\n(shuffle (list 1 2 3))\n;;=> [2 1 3]","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3","account-source":"github","login":"jafingerhut"},{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3","account-source":"github","login":"phreed"},{"avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3","account-source":"github","login":"Dimagog"},{"login":"Hindol","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/705227?v=4"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/10b2fd3c0a4cc46dc241a48468dc551?r=PG&default=identicon","account-source":"clojuredocs","login":"pkolloch"},"_id":"542692cac026201cdc326b48"}],"notes":null,"arglists":["coll"],"doc":"Return a random permutation of coll","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/shuffle"},{"added":"1.1","ns":"clojure.core","name":"boolean-array","file":"clojure/core.clj","type":"function","column":1,"see-alsos":null,"line":5338,"examples":[{"author":{"login":"shockbob","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon"},"editors":[{"login":"shockbob","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon"}],"body":";; create an array of Java boolean's using boolean-array\n;; and demonstrate that it can be used for input into the standard\n;; Java Arrays.fill function\n\nuser=> (def bs (boolean-array (map even? (range 3 10))))\n#'user/bs\nuser=> (type bs)\n[Z\nuser=> (vec bs)\n[false true false true false true false]\nuser=> (java.util.Arrays/fill bs 3 7 false)\nnil\nuser=> (vec bs)\n[false true false false false false false]\nuser=>","created-at":1313908154000,"updated-at":1313963403000,"_id":"542692c7c026201cdc326947"}],"notes":null,"arglists":["size-or-seq","size init-val-or-seq"],"doc":"Creates an array of booleans","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/boolean-array"},{"added":"1.0","ns":"clojure.core","name":"find","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1360286923000,"author":{"login":"AtKaaZ","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e10dfa345f44b0fe72bbe081fd51b83?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"get","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e77"},{"created-at":1360286926000,"author":{"login":"AtKaaZ","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e10dfa345f44b0fe72bbe081fd51b83?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"get-in","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e78"},{"created-at":1527108492940,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"contains?","ns":"clojure.core"},"_id":"5b05d38ce4b045c27b7fac76"},{"created-at":1548452405616,"author":{"login":"cljlc","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/36645452?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"select-keys","ns":"clojure.core"},"_id":"5c4b8235e4b0ca44402ef62d"}],"line":1549,"examples":[{"author":{"login":"zmila","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/68dd6f50915854aa04fefcf4d6fa5c8e?r=PG&default=identicon"},"editors":[{"login":"alexander-yakushev","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/468477?v=2"},{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},{"avatar-url":"https://avatars0.githubusercontent.com/u/36645452?v=4","account-source":"github","login":"cljlc"}],"body":"(find {:a 1 :b 2 :c 3} :a)\n;;=> [:a 1]\n\n(find {:a nil} :a)\n;;=> [:a nil]\n\n(find {:a 1 :b 2 :c 3} :d)\n;;=> nil \n","created-at":1280345792000,"updated-at":1548452497936,"_id":"542692cfc026201cdc326e3e"},{"author":{"login":"Nevena","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/fa0e495ccb6ed2997e14f687817e9299?r=PG&default=identicon"},"editors":[{"avatar-url":"https://avatars0.githubusercontent.com/u/36645452?v=4","account-source":"github","login":"cljlc"},{"avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"}],"body":";; Note for these examples: as the authoritative documentation speaks only about\n;; map (as first parameter), passing anything else (e.g. a vector, like below)\n;; uses an undocumented behavior, which can change anytime and so is unreliable and\n;; should be avoided.\n\nuser=> (find [:a :b :c :d] 2)\n[2 :c]\n\nuser=> (find [:a :b :c :d] 5)\nnil\n\nuser=> (find [1 2 3] 4294967296)\n[4294967296 1]","created-at":1305594606000,"updated-at":1582483198869,"_id":"542692cfc026201cdc326e3f"},{"updated-at":1751722154078,"created-at":1751721881285,"author":{"login":"elias-sw","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/60688955?v=4"},"body":";; The resulting map entry is not a vector, although it is printed like that. \n;; It is a MapEntry, so you can do: \n\n(val (find {:a 5 :b 6} :b))\n;; 6\n\n;; which of course you cannot do with a vector:\n(val ([:b 6]))\n;; Execution error (ArityException)...","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/60688955?v=4","account-source":"github","login":"elias-sw"}],"_id":"68692799cd84df5de54e208b"}],"notes":null,"arglists":["map key"],"doc":"Returns the map entry for key, or nil if key not present.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/find"},{"added":"1.0","ns":"clojure.core","name":"alength","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1512468544768,"author":{"login":"tentamen","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/58513?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"into-array","ns":"clojure.core"},"_id":"5a267040e4b0a08026c48ccc"}],"line":3924,"examples":[{"author":{"login":"dakrone","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bcacd00a7f05c4772329cf9f446c7987?r=PG&default=identicon"},"editors":[],"body":"user=> (def my-array (into-array Integer/TYPE [1 2 3]))\n#'user/my-array\n\nuser=> (alength my-array)\n3","created-at":1286508271000,"updated-at":1286508271000,"_id":"542692cfc026201cdc326e13"},{"editors":[{"login":"zezhenyan","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8064559?v=3"}],"body":"2D simple array example\nuser=> (def a (to-array-2d [[1 2] [3 4 5] [1]]))\n#'user/a\nuser=> (alength a)\n3\n","author":{"avatar-url":"https://avatars.githubusercontent.com/u/8064559?v=3","account-source":"github","login":"zezhenyan"},"created-at":1486712507911,"updated-at":1486712552508,"_id":"589d6ebbe4b01f4add58fe42"}],"notes":null,"arglists":["array"],"doc":"Returns the length of the Java array. Works on arrays of all\n types.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/alength"},{"added":"1.0","ns":"clojure.core","name":"bit-xor","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1414514653495,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"},"to-var":{"ns":"clojure.core","name":"bit-and","library-url":"https://github.com/clojure/clojure"},"_id":"544fc7dde4b03d20a1024293"},{"created-at":1414514668964,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"},"to-var":{"ns":"clojure.core","name":"bit-or","library-url":"https://github.com/clojure/clojure"},"_id":"544fc7ece4b03d20a1024294"}],"line":1325,"examples":[{"author":{"login":"zmila","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/68dd6f50915854aa04fefcf4d6fa5c8e?r=PG&default=identicon"},"editors":[{"login":"zmila","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/68dd6f50915854aa04fefcf4d6fa5c8e?r=PG&default=identicon"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":";; set bits to 1 where bits of the arguments are different\nuser=> (bit-xor 2r1100 2r1001) \n5 \n;; 5 = 2r0101\n\n","created-at":1280338778000,"updated-at":1285496577000,"_id":"542692c7c026201cdc3269b3"},{"body":";; here is the truth table for XOR \n(Integer/toBinaryString (bit-xor 2r1100 2r1010) )\n;;=> \"110\"\n;; or 2r0110","author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"},"created-at":1414514637281,"updated-at":1414514637281,"_id":"544fc7cde4b03d20a1024292"}],"notes":null,"arglists":["x y","x y & more"],"doc":"Bitwise exclusive or","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/bit-xor"},{"added":"1.1","ns":"clojure.core","name":"deliver","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1324962689000,"author":{"login":"neotyk","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/366ff985977b3aab09510bc335cd44a4?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"promise","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bba"}],"line":7275,"examples":[{"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":"user=> (def x (promise))\n#'user/x\n;; Trying to deref at this point will make your repl wait forever\n\n\nuser=> (deliver x 100)\n#<core$promise$reify__5534@4369a50b: 100>\n\n;; the promise has been delivered, deref x will return immediately\nuser=> @x\n100\n","created-at":1280748782000,"updated-at":1285495947000,"_id":"542692c8c026201cdc326a04"},{"author":{"login":"neotyk","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/366ff985977b3aab09510bc335cd44a4?r=PG&default=identicon"},"editors":[],"body":";; Create a promise\nuser> (def p (promise))\n#'user/p ; p is our promise\n\n;; Check if was delivered/realized\nuser> (realized? p)\nfalse ; No yet\n\n;; Delivering the promise\nuser> (deliver p 42)\n#\n\n;; Check again if it was delivered\nuser> (realized? p)\ntrue ; Yes!\n\n;; Deref to see what has been delivered\nuser> @p\n42\n\n;; Note that @ is shorthand for deref\nuser> (deref p)\n42","created-at":1324962699000,"updated-at":1324962699000,"_id":"542692d2c026201cdc326f8c"},{"editors":[{"login":"JoshAaronJones","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/19951591?v=3"}],"body":";; Illustrates how threads can work together via promises\n;; First, an example to show a future that delivers\n\nuser=> (def p (promise))\n#'user/p\n\n;; future that will deliver the promise from another thread after 10 sec delay\nuser=> (future\n (Thread/sleep 10000)\n (deliver p 123))\n#future[{:status :pending, :val nil} 0x9a51df1]\n\n;; within 10 seconds dereference p, and wait for delivery of the value\nuser=> @p\n123\n\n\n;; Now, an example to show a future that blocks while waiting for a promise\n;; to be delivered -- this is used to achieve callback-style functionality\n\n;; redefine p\nuser=> (def p (promise))\n#'user/p\n\n;; create a new 'callback' thread that will wait for a promise to be delivered\nuser=> (future\n (println \"About to block while waiting for 'p'\")\n (println \"Now I can do some work with the value \" @p))\nAbout to block while waiting for 'p'\n#future[{:status :pending, :val nil} 0x1737df29]\n\n;; deliver the promise, triggering the blocking callback thread\nuser=> (deliver p 123)\nNow I can do some work with the value 123\n#promise[{:status :ready, :val 123} 0x674a4c4a]","author":{"avatar-url":"https://avatars.githubusercontent.com/u/19951591?v=3","account-source":"github","login":"JoshAaronJones"},"created-at":1474382307145,"updated-at":1474387055629,"_id":"57e149e3e4b0709b524f0503"},{"editors":[{"login":"sanel","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/213914?v=4"}],"body":";; `deliver` returns the promise and can be dereffed directly.\n\n(def my-prom (promise)) \nmy-prom ;;=> #promise[{:status :pending, :val nil} 0x2570a72d]\n@(deliver my-prom \"Huzzah!\") ;;=> \"Huzzah!\"\nmy-prom ;;=> #promise[{:status :ready, :val \"Huzzah!\"} 0x2570a72d]\n@my-prom ;;=> \"Huzzah!\"","author":{"avatar-url":"https://avatars.githubusercontent.com/u/19522656?v=4","account-source":"github","login":"Crowbrammer"},"created-at":1618026011033,"updated-at":1699560966036,"_id":"60711e1be4b0b1e3652d74bf"}],"notes":[{"updated-at":1385511406000,"body":"As of Clojure 1.3 `deliver` does not throw an exception when it is called multiple times on the same promise. See [CLJ-1038](http://dev.clojure.org/jira/browse/CLJ-1038).","created-at":1385511406000,"author":{"login":"gyim","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/14df9ffd78d1e7062ac317d8bcfcde9f?r=PG&default=identicon"},"_id":"542692edf6e94c6970522012"}],"arglists":["promise val"],"doc":"Delivers the supplied value to the promise, releasing any pending\n derefs. A subsequent call to deliver on a promise will have no effect.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/deliver"},{"added":"1.0","ns":"clojure.core","name":"doseq","file":"clojure/core.clj","type":"macro","column":1,"see-alsos":[{"created-at":1296708559000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"doall","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d9a"},{"created-at":1296708565000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"dorun","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d9b"},{"created-at":1318959035000,"author":{"login":"mmwaikar","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/29d36f4c9f39c9f8ff61c07033b13118?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"for","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d9c"},{"created-at":1340037689000,"author":{"login":"Parijat Mishra","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e3aba44539a78ea92373418456f090e3?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"dotimes","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d9d"},{"created-at":1502125400318,"author":{"login":"mars0i","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/1836941?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"run!","ns":"clojure.core"},"_id":"59889d58e4b0d19c2ce9d70c"}],"line":3234,"examples":[{"updated-at":1639218963535,"created-at":1279807621000,"body":";; Multiplies every x by every y.\n\n(doseq [x [-1 0 1]\n y [1 2 3]] \n (prn (* x y)))\n-1 ; x -1 y 1\n-2 ; x -1 y 2\n-3 ; x -1 y 3\n0 ; x 0 y 1\n0 ; x 0 y 2\n0 ; x 0 y 3\n1 ; x 1 y 1\n2 ; x 1 y 2\n3 ; x 1 y 3\nnil\n\n;; Notice that y is iterated over for every x. x could be seen as the 'outer' loop","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"avatar-url":"https://avatars.githubusercontent.com/u/164033?v=3","account-source":"github","login":"justgage"},{"login":"bkovitz","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/4142015?v=3"},{"login":"loeschzwerg","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/24317401?v=4"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/81018e4231ac1ce8b7a9e6d377092656?r=PG&default=identicon","account-source":"clojuredocs","login":"devijvers"},"_id":"542692c6c026201cdc326919"},{"author":{"login":"devijvers","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/81018e4231ac1ce8b7a9e6d377092656?r=PG&default=identicon"},"editors":[{"login":"belun","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8d3c423e74750fa42c0386833e4b8209?r=PG&default=identicon"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":"user=> (doseq [[x y] (map list [1 2 3] [1 2 3])] \n (prn (* x y)))\n1\n4\n9\nnil\n\n;; where\nuser=> (map list [1 2 3] [1 2 3])\n((1 1) (2 2) (3 3))","created-at":1279807704000,"updated-at":1285651402000,"_id":"542692c6c026201cdc32691b"},{"author":{"login":"devijvers","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/81018e4231ac1ce8b7a9e6d377092656?r=PG&default=identicon"},"editors":[{"login":"devijvers","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/81018e4231ac1ce8b7a9e6d377092656?r=PG&default=identicon"},{"login":"belun","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8d3c423e74750fa42c0386833e4b8209?r=PG&default=identicon"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"edbond","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/671af8c4a2d223c7d2e2ede3a0154975?r=PG&default=identicon"},{"login":"edbond","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/671af8c4a2d223c7d2e2ede3a0154975?r=PG&default=identicon"},{"login":"JavierJF","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2714593?v=3"}],"body":"user=> (doseq [[[a b] [c d]] (map list (sorted-map :1 1 :2 2) (sorted-map :3 3 :4 4))]\n (prn (* b d)))\n3\n8\nnil\n\n;; where\nuser=> (map list (sorted-map :1 1 :2 2) (sorted-map :3 3 :4 4))\n(([:1 1] [:3 3]) ([:2 2] [:4 4]))","created-at":1279808561000,"updated-at":1427017735128,"_id":"542692c6c026201cdc32691e"},{"author":{"login":"devijvers","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/81018e4231ac1ce8b7a9e6d377092656?r=PG&default=identicon"},"editors":[{"login":"belun","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8d3c423e74750fa42c0386833e4b8209?r=PG&default=identicon"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"Parijat Mishra","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e3aba44539a78ea92373418456f090e3?r=PG&default=identicon"}],"body":"user=> (doseq [[k v] (map identity {:1 1 :2 2 :3 3})] \n (prn k v))\n:1 1\n:2 2\n:3 3\nnil\n\n;; where\nuser=> (map identity {:1 1 :2 2 :3 3})\n([:1 1] [:2 2] [:3 3])\n\n;; or simply\nuser=> (doseq [[k v] {:1 1 :2 2 :3 3}]\n (prn k v))\n:1 1\n:3 3\n:2 2\nnil","created-at":1279817912000,"updated-at":1340037554000,"_id":"542692c6c026201cdc326924"},{"author":{"login":"TimMc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5d532e51427ef2f4ded31aaca16c8baf?r=PG&default=identicon"},"editors":[{"login":"justgage","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/164033?v=3"}],"body":";; Multiple sequences results in a Cartesian cross of their values.\nuser=> (doseq [a [1 2]\n b [3 4]]\n (println a b))\n1 3\n1 4\n2 3\n2 4\nnil","created-at":1297827822000,"updated-at":1430494032223,"_id":"542692c6c026201cdc326928"},{"author":{"login":"cloojure","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1ad3de25d00d953de6e8c82f554cdbf5?r=PG&default=identicon"},"editors":[{"login":"justgage","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/164033?v=3"}],"body":";; Keywords :let, :when, and :while are supported, the same as \"for\"\nuser=> (doseq [x (range 6)\n :when (odd? x)\n :let [y (* x x)] ]\n (println [x y]) )\n[1 1]\n[3 9]\n[5 25]\nnil\n\nuser=> (doseq [x (range 99)\n :let [y (* x x)] \n :while (< y 30)\n ]\n (println [x y]) )\n[0 0]\n[1 1]\n[2 4]\n[3 9]\n[4 16]\n[5 25]\nnil\nuser=> \n","created-at":1403073333000,"updated-at":1430494049365,"_id":"542692d2c026201cdc326f93"},{"editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/164033?v=3","account-source":"github","login":"justgage"},{"login":"bkovitz","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/4142015?v=3"}],"updated-at":1463546941294,"created-at":1427932426392,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/11763041?v=3","account-source":"github","login":"rezomegrelidze"},"body":";; ClojureCLR example\n;; Prints names of running processes\n\nuser=> (doseq [x (System.Diagnostics.Process/GetProcesses)] \n (println (.get_ProcessName x)))\navgnt\nSearchIndexer\nsvchost\nchrome\naudiodg\nsvchost\nmbamscheduler\nspoolsv\nnvxdsync\navwebg7\nGoogleCrashHandler64\nsvchost\nCCleaner64\nViakaraokeSrv\n...","_id":"551c850ae4b08eb9aa0a8d3d"},{"body":";; simplest use\n\nuser=> (doseq [x [1 2 3 4 5]] (prn x))\n1\n2\n3\n4\n5\nnil","author":{"login":"justgage","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/164033?v=3"},"created-at":1430431275365,"updated-at":1430494090363,"editors":[{"login":"justgage","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/164033?v=3"}],"_id":"5542a62be4b01bb732af0a8e"},{"updated-at":1510587865249,"created-at":1510587865249,"author":{"login":"ibercode","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/31028993?v=4"},"body":";;looping over a collection \n\n;;define CarMaker record\n(defrecord CarMaker [cm-name])\n\n;;define CarModel record\n(defrecord CarModel [model-name cmaker doors color])\n\n;;create a car-makes\n(def car-maker {\"cm1\" (->CarMaker \"Renault\")})\n\n;;createa models and add an CarMaker identifier to which model\n(def models {\n \"m1\" (->CarModel \"Megane\" \"cm1\" 3 \"Black\")\n \"m2\" (->CarModel \"Zoe\" \"cm1\" 5 \"White\")\n })\n;;println all model-name in the collection\n(doseq [[k v] models] (println (:model-name (get models k))))","_id":"5a09bdd9e4b0a08026c48cb6"},{"editors":[{"login":"ibercode","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/31028993?v=4"}],"body":";;doseq on vector\n(def my-vector [1 2 3 \"a\" \"b\" \"c\" :a :b :c])\n(doseq [v my-vector] (println v))\n\n;;doseq on hash-map\n(def my-map {:a \"A\" :b \"B\" :c \"C\" :d 1 :e 2 :f 3})\n(doseq [[k v] my-map] (println k \"->\" v))","author":{"avatar-url":"https://avatars0.githubusercontent.com/u/31028993?v=4","account-source":"github","login":"ibercode"},"created-at":1510917150459,"updated-at":1511258586059,"_id":"5a0ec41ee4b0a08026c48cbc"},{"editors":[{"login":"huahaiy","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/889685?v=4"}],"body":"user=> (doseq [y (range 10)] \n (dotimes [z y] (print (inc z)))\n (newline))\n\n1\n12\n123\n1234\n12345\n123456\n1234567\n12345678\n123456789\nnil","author":{"avatar-url":"https://avatars3.githubusercontent.com/u/46395055?v=4","account-source":"github","login":"akhuramazda"},"created-at":1546681885708,"updated-at":1613255160130,"_id":"5c307e1de4b0ca44402ef613"},{"updated-at":1691699072668,"created-at":1691699072668,"author":{"login":"nimitmaru","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/915615?v=4"},"body":";; nothing will print\n(doseq [x []\n y [1 2 3]]\n (prn x y))\n\n;; if any bindings have empty sequences, the body will never execute\n","_id":"64d54780e4b08cf8563f4be0"},{"updated-at":1706780972483,"created-at":1706780972483,"author":{"login":"jimka2001","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/6414129?v=4"},"body":";; to iterate across a map\n(doseq [[k v] {:a 1 :b 10 :c 100}]\n (println (list k v)))\n\n;; outputs\n(:a 1)\n(:b 10)\n(:c 100)\nnil","_id":"65bb692c69fbcc0c22617495"},{"updated-at":1718149543811,"created-at":1718149543811,"author":{"login":"ReneGV","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/31145813?v=4"},"body":";; Iterate through a simple list\n(doseq [number [1 2 3 4]] \n (println number))\n;; Output\n1\n2\n3\n4\nnil\n","_id":"6668e1a769fbcc0c226174d4"},{"updated-at":1719775361027,"created-at":1719775361027,"author":{"login":"jimka2001","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/6414129?v=4"},"body":";; The `:while` modifier triggers the inner-most loop to be aborted.\n;; (to break out of the inner most loop).\n\n(doseq [a (range 5)\n b (range 5)\n :while (even? b) ;; when be fails to be even, then break out of b loop\n ]\n (println {:a a :b b})\n;; Output\n{:a 0, :b 0}\n{:a 1, :b 0}\n{:a 2, :b 0}\n{:a 3, :b 0}\n{:a 4, :b 0}","_id":"6681b08169fbcc0c226174db"}],"macro":true,"notes":null,"arglists":["seq-exprs & body"],"doc":"Repeatedly executes body (presumably for side-effects) with\n bindings and filtering as provided by \"for\". Does not retain\n the head of the sequence. Returns nil.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/doseq"},{"added":"1.6","ns":"clojure.core","name":"unsigned-bit-shift-right","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1412094407161,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=2"},"to-var":{"ns":"clojure.core","name":"bit-shift-right","library-url":"https://github.com/clojure/clojure"},"_id":"542ad9c7e4b0df9bb778a59f"}],"line":1382,"examples":[{"body":"user=> (format \"%016x\" -1)\n\"ffffffffffffffff\"\n\n;; bit-shift-right sign extends most significant bit while right shifting.\nuser=> (format \"%016x\" (bit-shift-right -1 10))\n\"ffffffffffffffff\"\n\n;; unsigned-bit-shift-right fills most significant bits of result with 0.\n;; No sign extension.\nuser=> (format \"%016x\" (unsigned-bit-shift-right -1 10))\n\"003fffffffffffff\"\n","author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=2"},"created-at":1412094902885,"updated-at":1412094902885,"_id":"542adbb6e4b0df9bb778a5a5"},{"updated-at":1460044954951,"created-at":1460044954951,"author":{"login":"fasiha","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/37649?v=3"},"body":";; Warning: unsigned-bit-shift-right, like bit-shift-right, treats inputs as\n;; type Long. Smaller types like byte, short, and int will not behave as such.\n(format \"0x%x\" (byte -128))\n; => \"0x80\"\n(format \"0x%x\" (unsigned-bit-shift-right (byte -128) 1))\n; => \"0x7fffffffffffffc0\"\n(format \"0x%x\" (bit-shift-right (byte -128) 1))\n; => \"0xffffffffffffffc0\"\n\n; If you expected 0x40, you need to upcast your byte yourself, via bit-and,\n; and only then shift:\n(format \"0x%x\" (bit-shift-right (bit-and 0xff (byte -128)) 1))\n; => \"0x40\"","_id":"5706849ae4b0fc95a97eab31"},{"editors":[{"login":"Sophia-Gold","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/19278114?v=3"}],"body":";; Stein's Algorithm (Binary GCD)\n;; https://en.wikipedia.org/wiki/Binary_GCD_algorithm\n\n\n(defn gcd [a b]\n (cond\n (zero? a) b\n (zero? b) a\n (neg? a) (- a)\n (neg? b) (- b)\n (and (even? a) (even? b)) (* 2\n (gcd (unsigned-bit-shift-right a 1)\n (unsigned-bit-shift-right b 1)))\n (and (even? a) (odd? b)) (recur (unsigned-bit-shift-right a 1) b)\n (and (odd? a) (even? b)) (recur a (unsigned-bit-shift-right b 1))\n (and (odd? a) (odd? b)) (recur (unsigned-bit-shift-right\n (Math/abs (long (- a b))) ;; coerce to avoid reflection\n 1) (min a b))))\n","author":{"avatar-url":"https://avatars.githubusercontent.com/u/19278114?v=3","account-source":"github","login":"Sophia-Gold"},"created-at":1482925072354,"updated-at":1505598794504,"_id":"5863a410e4b0fd5fb1cc9646"}],"notes":null,"arglists":["x n"],"doc":"Bitwise shift right, without sign-extension.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/unsigned-bit-shift-right"},{"added":"1.0","ns":"clojure.core","name":"neg?","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1345518618000,"author":{"login":"cbare","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/b394e97f24f3576861239e2b839703a4?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"pos?","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521dd6"},{"created-at":1400618884000,"author":{"login":"ryo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3f7913b563c72083c74030d928ba407e?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"zero?","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521dd7"}],"line":1268,"examples":[{"author":{"login":"dpritchett","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/147981?v=3"},"editors":[{"login":"replore","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e7869fe1a48cb1814c657eaca6bea3eb?r=PG&default=identicon"},{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"avatar-url":"https://avatars.githubusercontent.com/u/7412474?v=3","account-source":"github","login":"Lacty"}],"body":"user=> (neg? -1)\ntrue\nuser=> (neg? 0)\nfalse\nuser=> (neg? 1)\nfalse","created-at":1279074335000,"updated-at":1471000975948,"_id":"542692c9c026201cdc326add"},{"updated-at":1471001005614,"created-at":1471001005614,"author":{"login":"Lacty","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7412474?v=3"},"body":"user=> (neg? -0.1)\ntrue\nuser=> (neg? 0.1)\nfalse","_id":"57adb1ade4b0bafd3e2a04ee"},{"updated-at":1598394369395,"created-at":1598394369395,"author":{"login":"berczeck","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/1321842?v=4"},"body":"user=> (neg? 1/2)\n;; false\n\nuser=> (neg? -1/2)\n;; true\n\nuser=> (neg? {})\n;; Execution error (ClassCastException) at user/eval3801 (REPL:1).\n;; clojure.lang.PersistentArrayMap cannot be cast to java.lang.Number","_id":"5f459001e4b0b1e3652d73ac"}],"notes":null,"arglists":["num"],"doc":"Returns true if num is less than zero, else false","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/neg_q"},{"added":"1.0","ns":"clojure.core","name":"var-set","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1331249164000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.core","name":"with-local-vars","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521df8"},{"created-at":1550004038668,"author":{"login":"cljlc","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/36645452?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"var-get","ns":"clojure.core"},"_id":"5c632f46e4b0ca44402ef67d"},{"created-at":1701598357801,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"binding","ns":"clojure.core"},"_id":"656c549569fbcc0c22617469"}],"line":4359,"examples":[{"editors":[{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=4"}],"updated-at":1638151161315,"created-at":1423523544753,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3","account-source":"github","login":"Dimagog"},"body":"(with-local-vars [x 1]\n (println @x)\n (var-set x 2)\n (println @x))\n;;=> 1\n;;=> 2\n","_id":"54d93ed8e4b0e2ac61831d3b"},{"updated-at":1701598233685,"created-at":1701598233685,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":";; This can also be used with `binding`…\n(def ^:dynamic *foo* 42)\n\n*foo*\n;; => 42\n\n(binding [*foo* 43]\n (print *foo*)\n (var-set #'*foo* 44)\n *foo*)\n;; 43\n;; => 44\n\n*foo*\n;; => 42","_id":"656c541969fbcc0c22617468"}],"notes":null,"arglists":["x val"],"doc":"Sets the value in the var object to val. The var must be\n thread-locally bound.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/var-set"},{"added":"1.3","ns":"clojure.core","name":"unchecked-float","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1496072900762,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"float","ns":"clojure.core"},"_id":"592c42c4e4b093ada4d4d793"}],"line":3572,"examples":[{"editors":[{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"}],"body":"(unchecked-float 1)\n;;=> 1.0\n(unchecked-float 1.11)\n;;=> 1.11\n(unchecked-float 1.111111111111111111111111111M)\n;;=> 1.1111112\n\n;;;; Note that (unchecked-float) doesn't range check its argument.\n;;;; Use (float) instead if you want an exception to be thrown in such a case.\n\n(unchecked-float Double/MAX_VALUE)\n;;=> Infinity\n(float Double/MAX_VALUE)\n;;=> IllegalArgumentException Value out of range for float: 1.7976931348623157E308","author":{"avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3","account-source":"github","login":"svenschoenung"},"created-at":1496072892226,"updated-at":1496073090370,"_id":"592c42bce4b093ada4d4d792"}],"notes":null,"arglists":["x"],"doc":"Coerce to float. Subject to rounding.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/unchecked-float"},{"added":"1.0","ns":"clojure.core","name":"pmap","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1281948332000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"map","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e0d"},{"created-at":1336536733000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.core","name":"future","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e0e"},{"created-at":1518042635832,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"pcalls","ns":"clojure.core"},"_id":"5a7b7e0be4b0316c0f44f8a8"},{"created-at":1518042700360,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"pvalues","ns":"clojure.core"},"_id":"5a7b7e4ce4b0316c0f44f8a9"},{"created-at":1518042942025,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"partition","ns":"clojure.core"},"_id":"5a7b7f3ee4b0316c0f44f8af"}],"line":7159,"examples":[{"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":";; This function operates just like map. See\n;; clojure.core/map for more details.\nuser=> (pmap inc [1 2 3 4 5])\n(2 3 4 5 6)","created-at":1281948454000,"updated-at":1332952345000,"_id":"542692cdc026201cdc326cf2"},{"updated-at":1462726187473,"created-at":1313254319000,"body":";; A function that simulates a long-running process by calling Thread/sleep:\n(defn long-running-job [n]\n (Thread/sleep 3000) ; wait for 3 seconds\n (+ n 10))\n\n;; Use `doall` to eagerly evaluate `map`, which evaluates lazily by default.\n\n;; With `map`, the total elapsed time is just under 4 * 3 seconds:\nuser=> (time (doall (map long-running-job (range 4))))\n\"Elapsed time: 11999.235098 msecs\"\n(10 11 12 13)\n\n;; With `pmap`, the total elapsed time is just over 3 seconds:\nuser=> (time (doall (pmap long-running-job (range 4))))\n\"Elapsed time: 3200.001117 msecs\"\n(10 11 12 13)","editors":[{"login":"bkovitz","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/4142015?v=3"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/2fa4c391db0d2d1744cc2cd0d787dd3d?r=PG&default=identicon","account-source":"clojuredocs","login":"OnesimusUnbound"},"_id":"542692cdc026201cdc326cf4"},{"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":";; pmap is implemented using Clojure futures. See examples for 'future'\n;; for discussion of an undesirable 1-minute wait that can occur before\n;; your standalone Clojure program exits if you do not use shutdown-agents.","created-at":1336536727000,"updated-at":1336536842000,"_id":"542692d4c026201cdc327030"},{"updated-at":1539009726653,"created-at":1538954059979,"author":{"login":"cljlc","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/36645452?v=4"},"body":";; Parallel application (of 'f') does NOT mean that the result collection would\n;; be sorted according to calculation time. The result collection is sorted\n;; in the same way as for map, i.e. it \"preserves\" the items' order in the 'coll'\n;; (or 'colls') parameter(s) of pmap. In other words: calculation is done parallel,\n;; but the result is delivered in the order the input came (in 'coll'/'colls').\n\n;; So, e.g. if the first item of 'coll' takes 1 hour to be processed (by 'f'), and\n;; the rest requires 1 sec, nothing is delivered by pmap during the 1st hour:\n;; the 1st item \"blocks\" the appearence of the others in the result of pmap,\n;; even if the others are already calculated. E.g. (take 5 (pmap ...) will not \n;; return in 5 secs (but in 1 hour), even if we calculated 5 items in 5 secs\n;; -- we wait for the calculations of the first five in 'coll'.\n\n;; In contrast, side effects of 'f' (if any) are coming in \"random\" order (due to\n;; parallelism): in the example above, we might see the side effects (e.g. swap!-s)\n;; of many appliactions of 'f' to different elements of 'coll', long before we \n;; get the result of (take 1 (pmap ...)).\n\n;; To illustrate the statements above, run this:\n(defn proc\n [i]\n (println \"processing: \" i \"(\" (System/currentTimeMillis) \")\")\n (Thread/sleep\n (if (= i 0)\n 5000\n 10)))\n\n(take 1 (pmap proc (range 5)))\n;; output:\n(processing: processing: processing: processing: processing: 3 42 ( ((1 \n 1539007947561( 1539007947561 ) )1539007947561 0 )\n\n1539007947561( ) 1539007947561 )\n\nnil)\n;; We can see that 5 threads are started at the same time, immediately, in parallel.\n;; 4 of them must be finished in 10 msecs, but we get back the REPL prompt\n;; only after 5 secs, because we wait for the result of the i=0 item.","editors":[{"avatar-url":"https://avatars0.githubusercontent.com/u/36645452?v=4","account-source":"github","login":"cljlc"}],"_id":"5bba934be4b00ac801ed9eb3"},{"updated-at":1539007541878,"created-at":1539007541878,"author":{"login":"cljlc","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/36645452?v=4"},"body":";; pmap is implemented using Clojure futures. Futures run in threads. \n;; These threads of a pmap's evaluation run independently from each other.\n;; This means that even if one of these threads already determined the result\n;; of the whole pmap*, all the other, already started threads keep running\n;; until they finish their own calculations. (Although these calcualtions might\n;; already be absolutely unnecessary.)\n;; This can be especially important, when these threads have side effects:\n;; these side effects (e.g. swap!-s) might happen later, when they are not\n;; expected anymore.\n;; Moreover, these \"cowboy\" threads keep occuping the resources (CPU, memory...)\n;; they need.\n;; *: this is the case e.g. when one of the threads throws an exception.","_id":"5bbb6435e4b00ac801ed9ec9"}],"notes":[{"updated-at":1288191025000,"body":"for insight into how pmap does stuff see this presentation: \"From Concurrency to Parallelism\", by David Edgar Liebke @ http://incanter.org/downloads/fjclj.pdf","created-at":1288191025000,"author":{"login":"belun","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8d3c423e74750fa42c0386833e4b8209?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521f9f"},{"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"updated-at":1553851026351,"created-at":1553789805408,"body":"The following can be used to understand how many threads `pmap` runs at once (assuming tasks are roughly the same computational cost). The min level correspond to the situation where the consumer is slower than the producer, while the max level is when the consumer is faster than the producer:\n\n* When the sequence is not chunked (for example subvec) the min parallelism is 1 and the max parallelism is `(+ 2 N-cores)`. Example: with 12 cores, `(doall (pmap #(Thread/sleep %) (subvec (into [] (range 1000)) 0 999)))` keeps 12+2 threads busy.\n* In case of chunked sequences (vast majority are size 32), the min parallelism is `(min chunk-size (+ 2 n-cores))`, while the max amount is equal to `(+ chunk-size 2 N-cores)`. Example: with 12 cores, `(doall (pmap #(Thread/sleep %) (range 1000)))` keeps 12+2+32 threads busy.","_id":"5c9cf36de4b0ca44402ef6ed"}],"arglists":["f coll","f coll & colls"],"doc":"Like map, except f is applied in parallel. Semi-lazy in that the\n parallel computation stays ahead of the consumption, but doesn't\n realize the entire result unless required. Only useful for\n computationally intensive functions where the time of f dominates\n the coordination overhead.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/pmap"},{"added":"1.2","ns":"clojure.core","name":"error-mode","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1658139699593,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"set-error-mode!","ns":"clojure.core"},"_id":"62d53433e4b0b1e3652d7625"}],"line":2246,"examples":[{"updated-at":1658139926101,"created-at":1658139926101,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":"(def a (agent 42))\n(error-mode a);; => :fail\n\n(set-error-mode! a :continue)\n(error-mode a);; => :continue","_id":"62d53516e4b0b1e3652d7626"}],"notes":null,"arglists":["a"],"doc":"Returns the error-mode of agent a. See set-error-mode!","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/error-mode"},{"added":"1.0","ns":"clojure.core","name":"num","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"to-var":{"library-url":"https://github.com/clojure/clojure","name":"number?","ns":"clojure.core"},"author":{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},"created-at":1342917500000,"_id":"542692ebf6e94c6970521da3"}],"line":3499,"examples":[{"author":{"login":"Miles","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bbb26d2a5e856c4fba0f72c3f7250f3f?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"Miles","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bbb26d2a5e856c4fba0f72c3f7250f3f?r=PG&default=identicon"}],"body":"user=> (num 2048)\n2048\n\n\n;; Calling a Number http://download.oracle.com/javase/6/docs/api/ method:\n\nuser=> (def x (num 2048))\n#'user/x\n\nuser=> (.floatValue x)\n2048.0\n","created-at":1283819688000,"updated-at":1287791370000,"_id":"542692cec026201cdc326dc3"}],"notes":[{"author":{"login":"didibus","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/601540?v=4"},"updated-at":1560228092431,"created-at":1560228092431,"body":"`num` is used to coerce a primitive Java number type such as int, float, long, double, etc., into its boxed version such as Float, Long, Double, etc. If given an existing boxed Number type, as opposed to a primitive number type, it will just return it as is.","_id":"5cff30fce4b0ca44402ef754"},{"body":"If you are trying to parse a String into a Number, this is not the function you are looking for. `num` only coerces from other primitive or boxed number types. For coercing from a String, you want to use Java interop such as:\n\n```\n(Long/parseLong \"333\")\n(Float/parseFloat \"333.33\")\n(Double/parseDouble \"333.3333333333332\")\n(Integer/parseInt \"-333\")\n(Integer/parseUnsignedInt \"333\")\n(BigInteger. \"3333333333333333333333333332\")\n(BigDecimal. \"3.3333333333333333333333333332\")\n(Short/parseShort \"400\")\n(Byte/parseByte \"120\")\n```\n\nYou can also alternatively, if you want to parse the String into a Number the same way that the Clojure reader does so, use the edn reader.\n\n```\n(require '[clojure.edn :as edn])\n(edn/read-string \"333\")\n```","created-at":1560228951511,"updated-at":1560229176287,"author":{"avatar-url":"https://avatars3.githubusercontent.com/u/601540?v=4","account-source":"github","login":"didibus"},"_id":"5cff3457e4b0ca44402ef756"}],"tag":"java.lang.Number","arglists":["x"],"doc":"Coerce to Number","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/num"},{"added":"1.5","ns":"clojure.core","name":"reduced?","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1416151592590,"author":{"login":"ljos","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/585174?v=2"},"to-var":{"ns":"clojure.core","name":"reduced","library-url":"https://github.com/clojure/clojure"},"_id":"5468c228e4b0dc573b892fd5"},{"created-at":1416151598149,"author":{"login":"ljos","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/585174?v=2"},"to-var":{"ns":"clojure.core","name":"reduce","library-url":"https://github.com/clojure/clojure"},"_id":"5468c22ee4b0dc573b892fd6"},{"created-at":1456683959806,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"unreduced","ns":"clojure.core"},"_id":"56d33bb7e4b02a6769b5a4bb"},{"created-at":1464286428199,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"ensure-reduced","ns":"clojure.core"},"_id":"57473cdce4b0af2c9436d1f2"}],"line":2859,"examples":[{"updated-at":1456683476601,"created-at":1456683476601,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10583730?v=3"},"body":"(reduced? :foo)\n;;=> false\n\n(reduced? (reduced :foo))\n;;=> true\n\n(reduced? (clojure.lang.Reduced. :foo))\n;;=> true","_id":"56d339d4e4b0b41f39d96cd7"}],"notes":null,"arglists":["x"],"doc":"Returns true if x is the result of a call to reduced","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/reduced_q"},{"added":"1.1","ns":"clojure.core","name":"disj!","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1329970249000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.core","name":"assoc!","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e49"},{"created-at":1329970254000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.core","name":"dissoc!","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e4a"},{"created-at":1533850473558,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"disj","ns":"clojure.core"},"_id":"5b6cb369e4b00ac801ed9e4f"},{"created-at":1577916225137,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/109629?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"conj!","ns":"clojure.core"},"_id":"5e0d1741e4b0ca44402ef80c"}],"line":3426,"examples":[{"updated-at":1577916108217,"created-at":1307739693000,"body":";; Note how we always use the return value of disj! and conj! in these examples\n;; for all future modifications, rather than (incorrectly) ignoring the return\n;; value and continuing to modify the original transient set. See examples for\n;; assoc! and dissoc! for more discussion and examples of this.\n;; Also see one example for conj! that contains a detailed example\n;; of a wrong result that can occur if you do not use its return value.\n\nuser=> (def foo (transient #{'pore-pore 'slow 'yukkuri}))\n#'user/foo\nuser=> (count foo)\n3\nuser=> (def foo (disj! foo 'yukkuri))\n#'user/foo\nuser=> foo\n#\nuser=> (count foo)\n2\nuser=> (def foo (conj! foo 'yukkuri))\n#'user/foo\nuser=> foo\n#\nuser=> (count foo)\n3\nuser=> (def foo (persistent! foo))\n#'user/foo\nuser=> foo\n#{yukkuri slow pore-pore}\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3","account-source":"github","login":"jafingerhut"},{"avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3","account-source":"github","login":"jafingerhut"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/cacfb7ecf08cb6461767e514c93b7bf9?r=PG&default=identicon","account-source":"clojuredocs","login":"yasuto"},"_id":"542692cfc026201cdc326e8c"},{"updated-at":1533850455152,"created-at":1533850455152,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"body":";; A faster implementation of disj for a large number of keys to disjoin:\n\n(defn disj* [s & ks]\n (persistent!\n (reduce disj! (transient s) ks)))\n\n(let [s (set (range 1000))\n xs (range 400 600)]\n (count (apply disj* s xs)))\n;; 800","_id":"5b6cb357e4b00ac801ed9e4e"}],"notes":null,"arglists":["set","set key","set key & ks"],"doc":"disj[oin]. Returns a transient set of the same (hashed/sorted) type, that\n does not contain key(s).","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/disj!"},{"added":"1.0","ns":"clojure.core","name":"float?","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1496006168817,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"double?","ns":"clojure.core"},"_id":"592b3e18e4b093ada4d4d78e"},{"created-at":1496006177347,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"bigdec?","ns":"clojure.core"},"_id":"592b3e21e4b093ada4d4d78f"},{"created-at":1496006182111,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"decimal?","ns":"clojure.core"},"_id":"592b3e26e4b093ada4d4d790"}],"line":3630,"examples":[{"author":{"login":"dpritchett","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/147981?v=3"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":"user=> (float? 0)\nfalse\nuser=> (float? 0.0)\ntrue","created-at":1279073915000,"updated-at":1332951058000,"_id":"542692cbc026201cdc326bc6"},{"updated-at":1462076465809,"created-at":1454839923274,"author":{"login":"guruma","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/534540?v=3"},"body":";; float? returns true for both float and double.\nuser=> (map (juxt type float?) [(float 1) (double 1)])\n([java.lang.Float true] [java.lang.Double true])\n\n;; Call instance? to check if the value is specifically float or double.\nuser=> (map (juxt type #(instance? Float %)) [(float 1) (double 1)])\n([java.lang.Float true] [java.lang.Double false])","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/534540?v=3","account-source":"github","login":"guruma"},{"login":"bkovitz","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/4142015?v=3"}],"_id":"56b71873e4b0e8f8f33875d4"},{"updated-at":1592827825230,"created-at":1592827825230,"author":{"login":"zoren","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/84688?v=4"},"body":";; BigDecimal is not float\nuser=> (float? 0.0M)\nfalse","_id":"5ef09fb1e4b0b1e3652d730a"}],"notes":null,"arglists":["n"],"doc":"Returns true if n is a floating point number","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/float_q"},{"added":"1.0","ns":"clojure.core","name":"aset-float","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1627064336075,"author":{"login":"rosejn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/36590?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"aget","ns":"clojure.core"},"_id":"60fb0810e4b0b1e3652d751c"}],"line":3987,"examples":[{"author":{"login":"shockbob","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon"},"editors":[],"body":";; create an array of 10 floats and set one of the values to 3.1415\n\nuser=> (def fs (float-array 10))\n#'user/fs\nuser=> (vec fs)\n[0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0]\nuser=> (aset-float fs 3 3.1415)\n3.1415\nuser=> (vec fs)\n[0.0 0.0 0.0 3.1415 0.0 0.0 0.0 0.0 0.0 0.0]\nuser=>","created-at":1313914809000,"updated-at":1313914809000,"_id":"542692c7c026201cdc3269d2"}],"notes":[{"body":"See [aset](http://clojuredocs.org/clojure.core/aset) for illustrations of multi-dimensional syntax.","created-at":1432829158905,"updated-at":1432829158905,"author":{"login":"mars0i","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1836941?v=3"},"_id":"55673ce6e4b01ad59b65f4e0"}],"arglists":["array idx val","array idx idx2 & idxv"],"doc":"Sets the value at the index/indices. Works on arrays of float. Returns val.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/aset-float"},{"added":"1.2","ns":"clojure.core","name":"deftype","file":"clojure/core_deftype.clj","type":"macro","column":1,"see-alsos":[{"created-at":1361948459000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"definterface","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e0b"},{"created-at":1361948592000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"defprotocol","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e0c"},{"created-at":1446587002611,"author":{"login":"delonnewman","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10404?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"defrecord","ns":"clojure.core"},"_id":"56392a7ae4b04b157a6648e2"}],"line":424,"examples":[{"author":{"login":"Kototama","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a54a4dc204925d397ca010b9a332e74d?r=PG&default=identicon"},"editors":[{"login":"Kototama","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a54a4dc204925d397ca010b9a332e74d?r=PG&default=identicon"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":"user=> (import (java.awt.datatransfer Transferable DataFlavor)\n javax.swing.ImageIcon)\n\n;; create a Transferable Image from an array of bytes\nuser=> (deftype ImageSelection [data]\n Transferable\n (getTransferDataFlavors\n [this]\n (into-array DataFlavor [DataFlavor/imageFlavor]))\n \n (isDataFlavorSupported\n [this flavor]\n (= DataFlavor/imageFlavor flavor))\n\n (getTransferData\n [this flavor]\n (when (= DataFlavor/imageFlavor flavor)\n (.getImage (ImageIcon. data)))))\n\n;; create a new image selection:\nuser=> (def *selection* (ImageSelection. somedata))","created-at":1285784862000,"updated-at":1285841395000,"_id":"542692ccc026201cdc326cc9"},{"updated-at":1613242656022,"created-at":1462490574656,"author":{"login":"elsaturnino","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/571496?v=3"},"body":";; define a couple of shape types\n(deftype Circle [radius])\n(deftype Square [length width])\n\n;; multimethod to calculate the area of a shape\n(defmulti area class)\n(defmethod area Circle [c]\n (* Math/PI (.radius c) (.radius c)))\n(defmethod area Square [s]\n (* (.length s) (.width s)))\n\n;; create a couple shapes and get their area\n(def myCircle (Circle. 10))\n(def mySquare (Square. 5 11))\n\n(area myCircle)\n(area mySquare)","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/5796449?v=3","account-source":"github","login":"freezhan"},{"login":"stoat1","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2543524?v=4"}],"_id":"572bd5cee4b050526f331422"},{"updated-at":1462539789757,"created-at":1462539789757,"author":{"login":"jzwolak","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/285725?v=3"},"body":"(deftype Person [first-name last-name])\n\n;; use the factory function instead of the constructor, \"Person.\",\n;; to create a Person\n(->Person \"John\" \"Smith\")","_id":"572c960de4b050526f331423"},{"updated-at":1539060553178,"created-at":1539060553178,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"body":";; How :load-ns works.\n;; deftype can be used for AOT generation of classes (with gen-class that would be\n;; the only option). For example:\n\n(spit \"foo.clj\"\n \"(ns foo)\n (defn bar [] :bar)\n (defprotocol P (foo [p]))\n (deftype Foo [] :load-ns true P\n (foo [this] (bar)))\")\n\n(binding [*compile-path* \".\"] (compile 'foo))\n\n;; Now close and re-open the REPL to import the newly created class. Note that the\n;; call to (.foo p) doesn't throw exception here because we used \":load-ns true\"\n;; option in deftype. This makes sure that the namespace 'foo is also loaded \n;; forcing the evaluation of the \"bar\" function. This makes especially sense\n;; if Foo is used from a Java application:\n\n(import 'foo.Foo)\n(def p (Foo.))\n(.foo p)\n;; \"bar\"","_id":"5bbc3349e4b00ac801ed9ecb"},{"updated-at":1552943737414,"created-at":1552943737414,"author":{"login":"huahaiy","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/889685?v=4"},"body":";; To refer to a deftype in another namespace, the deftype needs to be imported \n;; because deftype generate a class.\n;; Using the Foo type defined above:\n(ns bar \n (:import [foo Foo]))\n\n(defn foo? [x]\n (instance? Foo x))","_id":"5c900a79e4b0ca44402ef6b8"},{"editors":[{"login":"huahaiy","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/889685?v=4"}],"body":";; deftype allow mutable fields, and their values can be changed with set!.\n;; This works:\n(deftype Test [^:unsynchronized-mutable x]\n ITestProtocol\n (act [this o] (set! x o)))\n\n;; Note that these mutable fields are private, so they are not accessible outside,\n;; and they are not even accessible inside nested functions within the type.\n;; This does not compile, throws error about assigning to non-mutable field x:\n(deftype Test [^:unsynchronized-mutable x]\n ITestProtocol\n (act [this] (fn [o] (set! x o))))\n\n;; Need to define a set function in a protocol and implement it in the type \n(defprotocol ISetX (set-x [this o]))\n\n(deftype Test [^:unsynchronized-mutable x]\n ISetX\n (set-x [this o] (set! x o))\n \n ITestProtocol\n (act [this] (fn [o] (set-x o))))\n","author":{"avatar-url":"https://avatars.githubusercontent.com/u/889685?v=4","account-source":"github","login":"huahaiy"},"created-at":1611856836020,"updated-at":1611856923228,"_id":"6012fbc4e4b0b1e3652d743f"},{"updated-at":1658251111297,"created-at":1658251111297,"author":{"login":"quoll","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/358875?v=4"},"body":";; unlike defrecord, deftype does not include extra method definitions\n;; the following will not compile:\n(defrecord Nr [n]\n Object\n (toString [_] (str \"#\" n)) ;; This does work\n (hashCode [_] (+ 10 n))) ;; defrecord already generates this function\n\n;; Syntax error (ClassFormatError) compiling deftype* at (REPL:1:1).\n;; Duplicate method name \"hashCode\" with signature \"()I\" in class file user/Nr\n\n\n;; deftype does not implement methods like hashCode, so it can be overridden\n(deftype Nr [n]\n Object\n (toString [_] (str \"#\" n))\n (hashCode [_] (+ 10 n)))\n\n(def v (->Nr 5))\n\n(str \"The number is: \" v)\n;; \"The number is #5\"\n\n(hash v)\n;; 15","_id":"62d6e767e4b0b1e3652d7629"},{"editors":[{"login":"JduPreez","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/514562?v=4"}],"body":"(ns my-favorite-drinks.beer)\n\n(deftype Beer [malt hops yeast water])\n\n;; When you do `:import`, Clojure doesn't munge the path names. \n;; So \"my-favorite-drinks.pub Beer\" should be \"my_favorite_drinks.pub Beer\" \n;; for all the imports.\n;; Also note that you have to `require` the ns as well.\n(ns my-favorite-drinks.pub\n (:require [my-favorite-drinks.beer])\n (:import [my_favorite_drinks.beer Beer]))\n\n","author":{"avatar-url":"https://avatars.githubusercontent.com/u/514562?v=4","account-source":"github","login":"JduPreez"},"created-at":1699457369448,"updated-at":1699522083060,"_id":"654ba95969fbcc0c22617428"}],"macro":true,"notes":[{"updated-at":1330691996000,"body":"There's also some undocumented support for annotations:\r\n\r\n","created-at":1330691996000,"author":{"login":"TimMc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5d532e51427ef2f4ded31aaca16c8baf?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fda"},{"author":{"login":"eoliphan","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1065736?v=4"},"updated-at":1665156668525,"created-at":1665156668525,"body":"Annotation docs now available in the reference: https://clojure.org/reference/datatypes#_java_annotation_support","_id":"6340463ce4b0b1e3652d7671"}],"arglists":["name [& fields] & opts+specs"],"doc":"(deftype name [fields*] options* specs*)\n\n Options are expressed as sequential keywords and arguments (in any order).\n\n Supported options:\n :load-ns - if true, importing the type class will cause the\n namespace in which the type was defined to be loaded.\n Defaults to false.\n\n Each spec consists of a protocol or interface name followed by zero\n or more method bodies:\n\n protocol-or-interface-or-Object\n (methodName [args*] body)*\n\n Dynamically generates compiled bytecode for class with the given\n name, in a package with the same name as the current namespace, the\n given fields, and, optionally, methods for protocols and/or\n interfaces. \n\n The class will have the (by default, immutable) fields named by\n fields, which can have type hints. Protocols/interfaces and methods\n are optional. The only methods that can be supplied are those\n declared in the protocols/interfaces. Note that method bodies are\n not closures, the local environment includes only the named fields,\n and those fields can be accessed directly. Fields can be qualified\n with the metadata :volatile-mutable true or :unsynchronized-mutable\n true, at which point (set! afield aval) will be supported in method\n bodies. Note well that mutable fields are extremely difficult to use\n correctly, and are present only to facilitate the building of higher\n level constructs, such as Clojure's reference types, in Clojure\n itself. They are for experts only - if the semantics and\n implications of :volatile-mutable or :unsynchronized-mutable are not\n immediately apparent to you, you should not be using them.\n\n Method definitions take the form:\n\n (methodname [args*] body)\n\n The argument and return types can be hinted on the arg and\n methodname symbols. If not supplied, they will be inferred, so type\n hints should be reserved for disambiguation.\n\n Methods should be supplied for all methods of the desired\n protocol(s) and interface(s). You can also define overrides for\n methods of Object. Note that a parameter must be supplied to\n correspond to the target object ('this' in Java parlance). Thus\n methods for interfaces will take one more argument than do the\n interface declarations. Note also that recur calls to the method\n head should *not* pass the target object, it will be supplied\n automatically and can not be substituted.\n\n In the method bodies, the (unqualified) name can be used to name the\n class (for calls to new, instance? etc).\n\n When AOT compiling, generates compiled bytecode for a class with the\n given name (a symbol), prepends the current ns as the package, and\n writes the .class file to the *compile-path* directory.\n\n One constructor will be defined, taking the designated fields. Note\n that the field names __meta, __extmap, __hash and __hasheq are currently\n reserved and should not be used when defining your own types.\n\n Given (deftype TypeName ...), a factory function called ->TypeName\n will be defined, taking positional parameters for the fields","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/deftype"},{"added":"1.0","ns":"clojure.core","name":"bean","file":"clojure/core_proxy.clj","type":"function","column":1,"see-alsos":null,"line":403,"examples":[{"updated-at":1691941141913,"created-at":1279049231000,"body":"user=> (import java.util.Date)\njava.util.Date\n\nuser=> (bean (Date.))\n{:seconds 57, :date 13, :class java.util.Date, :minutes 55, :hours 17, :year 110, :timezoneOffset -330, :month 6, :day 2, :time 1279023957492}\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"login":"ode79","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/227520?v=3"},{"login":"daemianmack","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/24476?v=4"}],"author":{"login":"nipra","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/142529?v=3"},"_id":"542692ccc026201cdc326c70"},{"updated-at":1477395581762,"created-at":1348995044000,"body":";; although not reference-able in Clojuredocs, \n;; org.clojure/java.data provides a useful, alternative 'from-java' function \n;; that works similarly to bean, but more customizable.\n;; See https://github.com/clojure/java.data for more info.","editors":[{"login":"G1enY0ung","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/15034155?v=3"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon","account-source":"clojuredocs","login":"klauern"},"_id":"542692d2c026201cdc326f4e"}],"notes":null,"arglists":["x"],"doc":"Takes a Java object and returns a read-only implementation of the\n map abstraction based upon its JavaBean properties.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/bean"},{"added":"1.1","ns":"clojure.core","name":"booleans","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"to-var":{"library-url":"https://github.com/clojure/clojure","name":"boolean-array","ns":"clojure.core"},"author":{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},"created-at":1358052913000,"_id":"542692eaf6e94c6970521c0a"}],"line":5401,"examples":[{"author":{"login":"leifp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d2f37720f063404ef83b987d2824353d?r=PG&default=identicon"},"editors":[],"body":";; for fast interop\nuser=> (set! *warn-on-reflection* true)\ntrue\nuser=> (defn get-a-bool [bs] (aget bs 1))\nReflection warning, NO_SOURCE_PATH:1 - call to aget can't be resolved.\n#'user/get-a-bool\nuser=> (defn get-a-bool [bs] (let [bs (booleans bs)] (aget bs 1)))\n#'user/get-a-bool\n","created-at":1342528439000,"updated-at":1342528439000,"_id":"542692d2c026201cdc326f5b"},{"body":";; can also be used as type hint to avoid reflection:\nuser=> (set! *warn-on-reflection* true)\ntrue\nuser=> (defn get-a-bool [^booleans bs] (aget bs 1))\n#'user/get-a-bool","author":{"login":"mars0i","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1836941?v=3"},"created-at":1432832819657,"updated-at":1432832851114,"editors":[{"login":"mars0i","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1836941?v=3"}],"_id":"55674b33e4b01ad59b65f4e2"}],"notes":null,"arglists":["xs"],"doc":"Casts to boolean[]","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/booleans"},{"added":"1.0","ns":"clojure.core","name":"ns-unalias","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1390616196000,"author":{"login":"abrooks","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/69976?v=2"},"to-var":{"ns":"clojure.core","name":"alias","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ea7"},{"created-at":1390616206000,"author":{"login":"abrooks","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/69976?v=2"},"to-var":{"ns":"clojure.core","name":"ns-aliases","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ea8"},{"created-at":1512578712943,"author":{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"ns-unmap","ns":"clojure.core"},"_id":"5a281e98e4b0a08026c48cd2"}],"line":4307,"examples":[{"author":{"login":"daviddurand","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1316941?v=2"},"editors":[],"body":";; You are having a problem loading a redefined namespace:\nuser=> (load \"src/clj/com/tizra/layout_expander.clj\")\n#\n\n;; ns-unalias to the rescue!\nuser=> (ns-unalias (find-ns 'com.tizra.layout-expander) 'xml)\nnil\n\nuser=> (load \"src/clj/com/tizra/layout_expander.clj\")\n#'com.tizra.layout-expander/junk\n","created-at":1326025800000,"updated-at":1326025800000,"_id":"542692d4c026201cdc327020"},{"body":"user=> (ns-aliases *ns*)\n{}\nuser=> (alias 'string 'clojure.string)\nnil\nuser=> (ns-aliases *ns*)\n{string #}\nuser=> (ns-unalias *ns* 'string)\nnil\nuser=> (ns-aliases *ns*)\n{}","author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"created-at":1423017698483,"updated-at":1423017698483,"_id":"54d186e2e4b081e022073c52"},{"updated-at":1512578611261,"created-at":1512471675948,"author":{"login":"ivarref","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/74075?v=4"},"body":";; To wipe aliases of current namespace:\n*my-ns*=> (map (partial ns-unalias *ns*) (keys (ns-aliases *ns*)))","editors":[{"avatar-url":"https://avatars1.githubusercontent.com/u/74075?v=4","account-source":"github","login":"ivarref"},{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"}],"_id":"5a267c7be4b0a08026c48ccd"}],"notes":null,"arglists":["ns sym"],"doc":"Removes the alias for the symbol from the namespace.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/ns-unalias"},{"added":"1.0","ns":"clojure.core","name":"when-let","file":"clojure/core.clj","type":"macro","column":1,"see-alsos":[{"created-at":1293436133000,"author":{"login":"0x89","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/56bc4acd59315ed4dc1cb99c3be71102?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"if-let","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e2c"},{"created-at":1315004448000,"author":{"login":"srid","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bd3a68d670372cd09876c26270a4299a?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"when","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e2d"},{"created-at":1323280128000,"author":{"login":"mmwaikar","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/29d36f4c9f39c9f8ff61c07033b13118?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"when-not","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e2e"},{"created-at":1334293387000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.core","name":"if","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e2f"},{"created-at":1405367841000,"author":{"login":"ryo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3f7913b563c72083c74030d928ba407e?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"when-first","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e30"},{"created-at":1440455896228,"author":{"login":"brunchboy","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2228869?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"when-some","ns":"clojure.core"},"_id":"55db9cd8e4b072d7f27980f1"},{"created-at":1602614484757,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"let","ns":"clojure.core"},"_id":"5f85f4d4e4b0b1e3652d73df"}],"line":1878,"examples":[{"author":{"login":"kotarak","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5db30f607f0b5fa70d690311aa3bfd3b?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"Confusion","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/ca054e9c7aecbfac1d99af1fd0a6d72c?r=PG&default=identicon"}],"body":";; Very useful when working with sequences. Capturing the return value \n;; of `seq` brings a performance gain in subsequent `first`/`rest`/`next`\n;; calls. Also the block is guarded by `nil` punning.\n\n(defn drop-one\n [coll]\n (when-let [s (seq coll)]\n (rest s)))\n\nuser=> (drop-one [1 2 3])\n(2 3)\nuser=> (drop-one [])\nnil\n","created-at":1281553976000,"updated-at":1342493536000,"_id":"542692cbc026201cdc326c01"},{"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"editors":[],"body":";; See examples for \"if\" explaining Clojure's idea of logical true\n;; and logical false.","created-at":1334293395000,"updated-at":1334293395000,"_id":"542692d6c026201cdc3270b6"},{"editors":[{"login":"mkorvas","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2321069?v=3"}],"updated-at":1438294296617,"created-at":1428550770303,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/367789?v=3","account-source":"github","login":"mattvvhat"},"body":";; Works well with collections\n\n(def x {:whatever 1})\n\n(when-let [value (:whatever x)]\n (println \"x+1 = \" (inc value)))\n\n;; Prints: \"x+1 = 2\"","_id":"5525f472e4b01bb732af0a7b"},{"updated-at":1469577527836,"created-at":1469577480181,"author":{"login":"ertugrulcetin","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8271291?v=3"},"body":";; when-let multiple bindings version\n\n(defmacro when-let*\n ([bindings & body]\n (if (seq bindings)\n `(when-let [~(first bindings) ~(second bindings)]\n (when-let* ~(drop 2 bindings) ~@body))\n `(do ~@body))))\n\n(when-let* [a 1 \n b 2 \n c (+ a b)]\n (println \"yeah!\")\n c)\n;;=>yeah!\n;;=>3\n\n(when-let* [a 1 \n b nil \n c 3]\n (println \"damn! b is nil\")\n a)\n;;=>nil\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/8271291?v=3","account-source":"github","login":"ertugrulcetin"}],"_id":"5797f908e4b0bafd3e2a04bb"},{"editors":[{"login":"pikariop","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1998952?v=4"}],"body":";; test is evaluated before values are bound to binding, so destructuring works \n(when-let [[a] nil] [a])\n=> nil\n(when-let [[a] [:a]] [a])\n=> [:a]\n(when-let [{:keys [a]} nil] [a])\n=> nil\n\n;; but empty collections present a gotcha\n(when-let [[a] []] [a])\n=> [nil]\n(when-let [{:keys [a]} {}] [a])\n=> [nil]","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/29587?v=4","account-source":"github","login":"bfabry"},"created-at":1505500848933,"updated-at":1768812397274,"_id":"59bc1eb0e4b09f63b945ac76"},{"updated-at":1629082196288,"created-at":1536030316104,"author":{"login":"arlicle","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/153773?v=4"},"body":";; when-let multiple bindings version\n;; all bindings are evaluated before checking for falsyness\n\n(defmacro when-let*\n [bindings & body]\n `(let ~bindings\n (if (and ~@(take-nth 2 bindings))\n (do ~@body)\n )))\n\n(when-let* [a 1 \n b 2 \n c (+ a b)]\n (println \"yeah!\")\n c)\n;;yeah!\n;;=> 3\n\n(when-let* [a 1 \n b nil \n c 3]\n (println \"damn! b is nil\")\n a)\n;;=> nil","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/8340498?v=4","account-source":"github","login":"justintaft"}],"_id":"5b8df66ce4b00ac801ed9e85"},{"editors":[{"login":"Jjunior130","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/7597818?v=4"}],"body":"(require '[reagent.core :as r])\n\n(def float-parsable? (comp not js/isNaN js/parseFloat))\n(def find-parsable-or-nil \n (comp first \n (partial re-find \n #\"(\\-?\\d+\\.)?\\d+([eE][-+]?\\d+)?\")))\n\n(defn number-input\n \"HTML input element for number only input\"\n [value]\n [:input\n {:value @value\n :type \"text\"\n :on-change (comp\n #(when-let [new-value %]\n (reset! value new-value))\n (fn [value]\n (cond\n (empty? value) \"\"\n (float-parsable? value) value\n :otherwise (find-parsable-or-nil value)))\n (fn [target]\n (.-value target))\n (fn [event]\n (.-target event)))}])\n\n(def value (r/atom \"\"))\n\n(defn demo []\n [:div\n ; Displays NaN when value is \"\", displays a number otherwise.\n (-> @value js/parseFloat str) [:br]\n [number-input value]])","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/7597818?v=4","account-source":"github","login":"Jjunior130"},"created-at":1536532957930,"updated-at":1536815925378,"_id":"5b95a1dde4b00ac801ed9e93"},{"editors":[{"login":"arcanjoaq","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1619912?v=4"}],"body":";; when-let with boolean values and nil\n\n(when-let [f true] \n (println \"Hello world!!!\"))\n\n;; prints Hello world!!!\n\n;;=>Hello world!!!\n;;=>nil\n\n(when-let [f false] \n (println \"Hi!!!\"))\n\n;; prints nothing\n\n;;=>nil\n\n(when-let [f nil] \n (println \"Wassup!!!\"))\n\n;; prints nothing\n\n;;=>nil","author":{"avatar-url":"https://avatars.githubusercontent.com/u/1619912?v=4","account-source":"github","login":"arcanjoaq"},"created-at":1718914544203,"updated-at":1718914615396,"_id":"66748df069fbcc0c226174d6"}],"macro":true,"notes":[{"updated-at":1299054268000,"body":"The difference between when-let and if-let is that when-let doesn't have an else clause and and also accepts multiple forms so you don't need to use a (do...).","created-at":1299054268000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fb4"},{"updated-at":1393879475000,"body":"The word \"bindings\" seems not to be correct here. In fact `when-let` only accepts **one** binding and not multiple ones.\r\nSo \"bindings\" might be confusing, at least it was for me.","created-at":1393879360000,"author":{"login":"n2o","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/73a59429cbc559fd77e9ec50fd99006b?r=PG&default=identicon"},"_id":"542692edf6e94c697052201f"},{"updated-at":1405477326000,"body":"Agreed. It ought to be \"binding\" for clarity.","created-at":1405477326000,"author":{"login":"Dave Y.","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/10d4977e847588cb4b461de4eb9d1646?r=PG&default=identicon"},"_id":"542692edf6e94c697052202c"},{"author":{"login":"HomoEfficio","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/17228983?v=3"},"updated-at":1486864109909,"created-at":1486864109909,"body":"```clojure\n(when-let [name test]\n (do-something-with-name))\n```\n\nIn the example above, `test` does not have to be a predicate.\n`test` can be any value which is like `(seq coll)` or `3`, `[1 2]`, or so.\n\nIf `test` is neither `false` nor `nil`, `test` is bound to `name`.\n","_id":"589fbeede4b01f4add58fe4c"}],"arglists":["bindings & body"],"doc":"bindings => binding-form test\n\n When test is true, evaluates body with binding-form bound to the value of test","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/when-let"},{"added":"1.0","ns":"clojure.core","name":"int-array","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"to-var":{"library-url":"https://github.com/clojure/clojure","name":"ints","ns":"clojure.core"},"author":{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},"created-at":1342917413000,"_id":"542692ebf6e94c6970521d57"},{"created-at":1349125778000,"author":{"login":"Ljos","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/45b996a79abca465acaf6c0f10b0437?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"aget","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d58"},{"created-at":1349125782000,"author":{"login":"Ljos","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/45b996a79abca465acaf6c0f10b0437?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"aset","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d59"},{"created-at":1349125888000,"author":{"login":"Ljos","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/45b996a79abca465acaf6c0f10b0437?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"aset-int","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d5a"}],"line":5385,"examples":[{"updated-at":1454083049116,"created-at":1284747822000,"body":";; if you have a sequence, perhaps lazy, int-array will figure out the size\n(aget (int-array [1 2 3]) 0)\n;;=> 1\n(int-array [1 2 3])\n;;=> \n\n;; if you need a certain size, with a constant initial value\n(aget (int-array 5 1) 4)\n;;=> 1\n(alength (int-array 5))\n;;=> 5\n\n;; finally, you can specify a size + a sequence, which will initialize the array \n;; by taking size from the sequence\n(alength (int-array 5 (range 10)))\n;;=> 5\n;; which is equivalent to\n(alength (int-array (take 5 (range 10)))\n;;=> 5\n","editors":[{"avatar-url":"https://www.gravatar.com/avatar/d543a7491b7b47ec7c3e8f259a75d2dd?r=PG&default=identicon","account-source":"clojuredocs","login":"apgwoz"},{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/d543a7491b7b47ec7c3e8f259a75d2dd?r=PG&default=identicon","account-source":"clojuredocs","login":"apgwoz"},"_id":"542692c9c026201cdc326afa"}],"notes":null,"arglists":["size-or-seq","size init-val-or-seq"],"doc":"Creates an array of ints","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/int-array"},{"added":"1.0","ns":"clojure.core","name":"set?","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1293674593000,"author":{"login":"dakrone","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bcacd00a7f05c4772329cf9f446c7987?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"set","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d8f"},{"created-at":1414508276593,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"},"to-var":{"ns":"clojure.core","name":"map?","library-url":"https://github.com/clojure/clojure"},"_id":"544faef4e4b0dc573b892faa"},{"created-at":1414508317723,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"},"to-var":{"ns":"clojure.core","name":"vector?","library-url":"https://github.com/clojure/clojure"},"_id":"544faf1de4b03d20a102427f"}],"line":4125,"examples":[{"author":{"login":"dakrone","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bcacd00a7f05c4772329cf9f446c7987?r=PG&default=identicon"},"editors":[{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"}],"body":"user> (set? #{1 2 3})\ntrue\n\nuser> (set? (hash-set 1 2 3))\ntrue\n\nuser> (set? (sorted-set 1 2 3))\ntrue\n\nuser> (set? [1 2 3])\nfalse\n\nuser> (set? {:a 1 :b 2})\nfalse","created-at":1293674587000,"updated-at":1423276284407,"_id":"542692cec026201cdc326dfa"}],"notes":null,"arglists":["x"],"doc":"Returns true if x implements IPersistentSet","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/set_q"},{"added":"1.0","ns":"clojure.core","name":"inc'","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1444304838174,"author":{"login":"andreloureiro","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2106717?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"inc","ns":"clojure.core"},"_id":"561657c6e4b0b41dac04c955"},{"created-at":1495706268555,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"dec'","ns":"clojure.core"},"_id":"5926aa9ce4b093ada4d4d754"}],"line":917,"examples":[{"updated-at":1444305445453,"created-at":1444305445453,"author":{"login":"andreloureiro","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2106717?v=3"},"body":"> (inc' 1)\n2\n\n> (inc' 3.14)\n4.140000000000001\n\n> (inc' 4/5)\n9/5\n\n> (inc' -1)\n0\n\n> (inc' -3/2)\n-1/2\n\n> (inc' -0.2)\n0.8","_id":"56165a25e4b0b41dac04c956"},{"updated-at":1495706130653,"created-at":1495706130653,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"body":";;;; (inc') auto-promotes on integer overflow:\n\n(inc' (Long/MAX_VALUE))\n;;=> 9223372036854775808N\n\n;;;; Unlike (inc) which does not:\n\n(inc (Long/MAX_VALUE))\n;;=> ArithmeticException integer overflow","_id":"5926aa12e4b093ada4d4d752"}],"notes":null,"arglists":["x"],"doc":"Returns a number one greater than num. Supports arbitrary precision.\n See also: inc","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/inc'"},{"added":"1.7","ns":"clojure.core","name":"cat","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1462880190642,"author":{"login":"achesnais","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/6626105?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"cat","ns":"clojure.core.reducers"},"_id":"5731c7bee4b012fa59bdb2ef"},{"created-at":1462880208677,"author":{"login":"achesnais","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/6626105?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"foldcat","ns":"clojure.core.reducers"},"_id":"5731c7d0e4b012fa59bdb2f0"},{"created-at":1679512700855,"author":{"login":"mars0i","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1836941?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"into","ns":"clojure.core"},"_id":"641b547ce4b08cf8563f4b84"},{"created-at":1685378198294,"author":{"login":"mars0i","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1836941?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"concat","ns":"clojure.core"},"_id":"6474d496e4b08cf8563f4bc1"}],"line":7811,"examples":[{"updated-at":1462880149225,"created-at":1462880149225,"author":{"login":"achesnais","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/6626105?v=3"},"body":";; cat is handy for untangling nested collections when using transducers\n\n(into [] (comp cat cat (map inc)) [[[1] [2]] [[3] [4]]])\n;; => [2 3 4 5]","_id":"5731c795e4b012fa59bdb2ee"},{"updated-at":1699438071633,"created-at":1510050037744,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"body":";; Remove the need of (mapcat identity coll) idiom:\n(def rota (sequence cat (repeat [\"tom\" \"nick\" \"jane\"])))\n(nth rota 7) ; who's up next week?\n;; nick\n\n;; Although `cycle` would have done just fine here","editors":[{"avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"},{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"}],"_id":"5a0188f5e4b0a08026c48c95"},{"editors":[{"login":"stanislas","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/240862?v=4"}],"body":";; combining map-indexed with cat for a \"mapcat-indexed\"\n(into []\n (comp\n (map-indexed (fn [index val]\n (repeat index val)))\n cat)\n (range 5))\n;; => [1 2 2 3 3 3 4 4 4 4]","author":{"avatar-url":"https://avatars.githubusercontent.com/u/240862?v=4","account-source":"github","login":"stanislas"},"created-at":1629989634908,"updated-at":1629989697016,"_id":"6127ab02e4b0b1e3652d7535"},{"updated-at":1659698277633,"created-at":1659698047207,"author":{"login":"ghoseb","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1453?v=4"},"body":";;; a concise and performant way to concat into a vector\n\n(into [] cat [[1 2 3] [4] [5 6 7]])\n;; => [1 2 3 4 5 6 7]\n\n(defn concatv\n \"Concatenate `xs` and return the result as a vector.\"\n [& xs]\n (into [] cat xs))\n\n(concatv '(1 2) [3] [4 5])\n;; => [1 2 3 4 5]\n\n;;; this xducer form is equivalent to the `(vec (concat...` pattern\n(let [x [1 2 3]\n y 4\n z [5 6 7]]\n (= \n (into [] cat [x [y] z])\n (vec (concat x [y] z))))\n\n;; => true","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/1453?v=4","account-source":"github","login":"ghoseb"}],"_id":"62ecfb7fe4b0b1e3652d7638"}],"notes":null,"arglists":["rf"],"doc":"A transducer which concatenates the contents of each input, which must be a\n collection, into the reduction.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/cat"},{"added":"1.9","ns":"clojure.core","name":"StackTraceElement->vec","file":"clojure/core_print.clj","type":"function","column":1,"see-alsos":null,"line":467,"examples":[{"editors":[{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"}],"body":";;;; StackTraceElements look like vectors when printed, but they\n;;;; are actually a completely different type. \n;;;; (StackTraceElement->vec) turns them into normal Clojure vectors.\n\n(try \n (/ 1 0)\n (catch Exception e \n (let [cause (->> e .getStackTrace seq first)]\n (pprint cause)\n (class cause))))\n;;=> [clojure.lang.Numbers divide \"Numbers.java\" 158]\n;;=> java.lang.StackTraceElement\n\n(try \n (/ 1 0)\n (catch Exception e \n (let [cause (->> e .getStackTrace seq first StackTraceElement->vec)]\n (pprint cause)\n (class cause))))\n;;=> [clojure.lang.Numbers divide \"Numbers.java\" 158]\n;;=> clojure.lang.PersistentVector\n","author":{"avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3","account-source":"github","login":"svenschoenung"},"created-at":1495970721085,"updated-at":1495970798753,"_id":"592ab3a1e4b093ada4d4d77e"}],"notes":null,"arglists":["o"],"doc":"Constructs a data representation for a StackTraceElement: [class method file line]","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/StackTraceElement->vec"},{"ns":"clojure.core","name":"*suppress-read*","type":"var","see-alsos":null,"examples":null,"notes":[{"body":"Not meant for public consumption, implementation detail of reader-conditional feature to skip unreadable forms. See https://clojure.atlassian.net/browse/CLJ-1424","created-at":1618077877511,"updated-at":1618078788123,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"},"_id":"6071e8b5e4b0b1e3652d74c0"}],"arglists":[],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core/*suppress-read*"},{"added":"1.0","ns":"clojure.core","name":"flush","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":null,"line":3731,"examples":[{"updated-at":1556307726395,"created-at":1556307726395,"author":{"login":"pauloaug","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/804447?v=4"},"body":";; iteratively prints the value of x (after a pause of 100ms) \n(doseq [x (range 20)]\n (Thread/sleep 100)\n (pr x)\n (flush))\n\n;; without a `flush` at each iteration,\n;; we'll get all the output stream at once flushed and printed only at the end \n;; of `doseq` evaluation. \n(doseq [x (range 20)]\n (Thread/sleep 100)\n (pr x))","_id":"5cc35f0ee4b0ca44402ef711"}],"notes":null,"arglists":[""],"doc":"Flushes the output stream that is the current value of\n *out*","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/flush"},{"added":"1.0","ns":"clojure.core","name":"take-while","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1301365974000,"author":{"login":"pauldoo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5cb916d3c8abc9f45a093209e72489fb?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"drop-while","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c3f"},{"created-at":1347077874000,"author":{"login":"dansalmo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e33ee460f5f61bc5ba9b598934766215?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"split-with","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c40"},{"created-at":1473454417291,"author":{"login":"huahaiy","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/889685?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"some","ns":"clojure.core"},"_id":"57d32151e4b0709b524f04f2"},{"created-at":1538951674784,"author":{"login":"cljlc","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/36645452?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"take","ns":"clojure.core"},"_id":"5bba89fae4b00ac801ed9ead"}],"line":2905,"examples":[{"author":{"login":"dpritchett","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/147981?v=3"},"editors":[{"login":"dpritchett","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/147981?v=3"},{"login":"devijvers","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/81018e4231ac1ce8b7a9e6d377092656?r=PG&default=identicon"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"Airwoz","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/47391748e84575258520e85e3725d144?r=PG&default=identicon"}],"body":";; Calculate the sum of all numbers under 1000:\nuser=> (reduce + (take-while (partial > 1000) (iterate inc 0)))\n499500","created-at":1279591693000,"updated-at":1385275768000,"_id":"542692cdc026201cdc326d03"},{"author":{"login":"patazj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d790f5851d80da498e475ece4487e92?r=PG&default=identicon"},"editors":[{"login":"patazj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d790f5851d80da498e475ece4487e92?r=PG&default=identicon"},{"login":"patazj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d790f5851d80da498e475ece4487e92?r=PG&default=identicon"},{"login":"Matt","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/af7cad0e010feb68f651cb61c54424b4?r=PG&default=identicon"},{"login":"Kejia","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1039073?v=3"}],"body":"user=> (take-while neg? [-2 -1 0 1 2 3])\n(-2 -1)\n\nuser=> (take-while neg? [-2 -1 0 -1 -2 3]) ; note: `take-while' stops traversing the collection when the predicate is false, as is different from `filter'.\n(-2 -1)\n\nuser=> (take-while neg? [ 0 1 2 3])\n()\n\nuser=> (take-while neg? [])\n()\n\nuser=> (take-while neg? nil)\n()","created-at":1321607184000,"updated-at":1434723642888,"_id":"542692d5c026201cdc3270a2"},{"editors":[{"login":"henghuang","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/5959826?v=3"}],"body":";;take the item while it's included in the set \nuser=> (take-while #{[1 2][3 4]} #{[1 2]})\n([1 2])\nuser=> (take-while #{[1 2][3 4]} #{[3 4]})\n([3 4])\nuser=> (take-while #{[1 2][3 4]} #{[4 5]})\n()\nuser=>(take-while #{[1 2][3 4]} #{[5 6] [1 2]}); return nil while any item is not included in the set\n()","author":{"avatar-url":"https://avatars.githubusercontent.com/u/5959826?v=3","account-source":"github","login":"henghuang"},"created-at":1458044677653,"updated-at":1458044982206,"_id":"56e7ff05e4b0507458dcf5a6"},{"updated-at":1517038741181,"created-at":1517038741181,"author":{"login":"ibercode","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/31028993?v=4"},"body":";;take-while practical example\n\n(def entries [{:month 1 :val 12}\n {:month 2 :val 3}\n {:month 3 :val 32}\n {:month 4 :val 18}\n {:month 5 :val 32}\n {:month 6 :val 62}\n {:month 7 :val 12}\n {:month 8 :val 142}\n {:month 9 :val 52}\n {:month 10 :val 18}\n {:month 11 :val 23}\n {:month 12 :val 56}])\n\n(defn get-result\n [coll m]\n (take-while\n #(<= (:month %) m) coll))\n\n(get-result entries 3)\n;;({:m 1, :val 12} {:m 2, :val 3} {:m 3, :val 32})\n","_id":"5a6c2c95e4b076dac5a728a7"},{"editors":[{"login":"cljlc","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/36645452?v=4"}],"body":";; Note that usually more items are realized than needed.\n;; In the example below the first 32 items are calculated,\n;; though the first 2 would be enough.\n;; This can be especially important when this extra realization\n;; leads to an exception (see example at 'take') or requires a lot of\n;; resources (CPU, time, memory, etc.) and at the end not needed at all.\n\nuser=> (let [x (map (fn [i]\n (println i)\n (Thread/sleep 100)\n i)\n (range 50))]\n (take-while #(< % 1) x))\n0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\n17\n18\n19\n20\n21\n22\n23\n24\n25\n26\n27\n28\n29\n30\n31\n(0)","author":{"avatar-url":"https://avatars0.githubusercontent.com/u/36645452?v=4","account-source":"github","login":"cljlc"},"created-at":1538951863286,"updated-at":1538953447395,"_id":"5bba8ab7e4b00ac801ed9eae"}],"notes":null,"arglists":["pred","pred coll"],"doc":"Returns a lazy sequence of successive items from coll while\n (pred item) returns logical true. pred must be free of side-effects.\n Returns a transducer when no collection is provided.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/take-while"},{"added":"1.0","ns":"clojure.core","name":"vary-meta","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1301486152000,"author":{"login":"ninjudd","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/7ced25585a7556e9b9b975c1f9e136e3?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"with-meta","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d19"},{"created-at":1375213046000,"author":{"login":"alilee","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2fb0196dc5a7cd3a5cc73f1b9941c209?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"alter-meta!","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d1a"}],"line":677,"examples":[{"updated-at":1285495771000,"created-at":1280776393000,"body":"user=> (meta (vary-meta 'foo assoc :a 1))\n{:a 1}\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3","account-source":"github","login":"devn"},"_id":"542692c8c026201cdc326a68"},{"author":{"login":"mmwaikar","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/29d36f4c9f39c9f8ff61c07033b13118?r=PG&default=identicon"},"editors":[],"body":";; continuing from the previous with-meta example\nuser=> (def wm (with-meta [1 2 3] {:my \"meta\"}))\n#'user/wm\n\nuser=> wm\n[1 2 3]\n\nuser=> (meta wm)\n{:my \"meta\"}\n\nuser=> (def new-wm (vary-meta wm assoc :your \"new meta\"))\n#'user/new-wm\n\nuser=> new-wm\n[1 2 3]\n\nuser=> (meta new-wm)\n{:my \"meta\", :your \"new meta\"}\n\n","created-at":1359718168000,"updated-at":1359718168000,"_id":"542692d5c026201cdc3270b3"}],"notes":null,"arglists":["obj f & args"],"doc":"Returns an object of the same type and value as obj, with\n (apply f (meta obj) args) as its metadata.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/vary-meta"},{"added":"1.0","ns":"clojure.core","name":"<=","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1451249730987,"author":{"login":"justCxx","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/6506296?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":">=","ns":"clojure.core"},"_id":"56805042e4b0e0706e05bd90"},{"created-at":1588958577321,"author":{"login":"alexandreaquiles","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/258331?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"<","ns":"clojure.core"},"_id":"5eb59571e4b087629b5a1907"},{"created-at":1588958583491,"author":{"login":"alexandreaquiles","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/258331?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"=","ns":"clojure.core"},"_id":"5eb59577e4b087629b5a1908"}],"line":1057,"examples":[{"author":{"login":"mattdw","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/ee24aacb65359196b0a1bad050f9a62f?r=PG&default=identicon"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":"user=> (<= 1 2)\ntrue\nuser=> (<= 2 2)\ntrue\nuser=> (<= 3 2)\nfalse\nuser=> (<= 2 3 4 5 6)\ntrue","created-at":1280321906000,"updated-at":1332950755000,"_id":"542692cdc026201cdc326cd9"},{"editors":[{"login":"dijonkitchen","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/11434205?v=4"}],"body":"user=> (<= 1 2 3 2)\nfalse\n\nuser=> (<= 1 2 3 3)\ntrue","author":{"avatar-url":"https://avatars3.githubusercontent.com/u/11434205?v=4","account-source":"github","login":"dijonkitchen"},"created-at":1534460808910,"updated-at":1534460833681,"_id":"5b760388e4b00ac801ed9e62"},{"editors":[{"login":"berczeck","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/1321842?v=4"}],"body":"user=> (<= 1/4 1/3 1/2)\ntrue\n\nuser=> (<= 1/2 1/3 1/4)\nfalse\n\nuser=> (>= 1/2 0.5)\ntrue","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/1321842?v=4","account-source":"github","login":"berczeck"},"created-at":1598154740865,"updated-at":1598156861827,"_id":"5f41e7f4e4b0b1e3652d738c"}],"notes":null,"arglists":["x","x y","x y & more"],"doc":"Returns non-nil if nums are in monotonically non-decreasing order,\n otherwise false.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/<="},{"added":"1.0","ns":"clojure.core","name":"alter","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1326053288000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"ref","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cb7"},{"created-at":1350716275000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"commute","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cb8"},{"created-at":1460613552329,"author":{"login":"fasiha","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/37649?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"ref-set","ns":"clojure.core"},"_id":"570f31b0e4b075f5b2c864e8"}],"line":2460,"examples":[{"author":{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"TimMc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5d532e51427ef2f4ded31aaca16c8baf?r=PG&default=identicon"},{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":";; alter is a way to change the value of a reference.\n\n;; Here we're defining a ref named 'names' and setting its value to\n;; an empty vector.\n(def names (ref []))\n;;=> #'user/names\n\n;; A function to add a name to the vector (notice the meat's wrapped\n;; in a dosync\n(defn add-name [name]\n (dosync\n (alter names conj name)))\n;;=> #'user/add-name\n\n(add-name \"zack\")\n;;=> [\"zack\"]\n\n(add-name \"shelley\")\n;;=> [\"zack\" \"shelley\"]\n\n;; Notice that the var 'names' points to the reference that we created\n(println names)\n;; #\n\n;; To get the actual value of the ref, you use the '@' symbol, or deref\n(println @names)\n;; [zack shelley]\n\n(println (deref names))\n;; [zack shelley]","created-at":1279456650000,"updated-at":1420669157673,"_id":"542692c8c026201cdc326a3c"}],"notes":[{"updated-at":1325053153000,"body":"I was fooling around with how exactly ref works with maps. Since the example here uses a vector, I thought maybe some of you might want to see a short example using a map.\r\n\r\nIn an aggregator I'm working on, I want to keep a record of how many sources and how many articles I've aggregated. Instead of using an atom for each, I'll reference a map called \"counts.\" Here's a simple little function that increments and returns the new value of the counter stored in the map:\r\n\r\n
 (def counts (ref {:articles 0 :sources 0}))\r\n(defn inc-ref [ref type]\r\n\"increment a map value with key type stored in ref\"\r\n\t(dosync\r\n\t (alter ref assoc type (inc (type @ref)))\r\n\t (type @ref)))\r\nuser> (inc-ref counts :sources)\r\n=>1\r\nuser> counts\r\n=>{:articles 0, :sources 1}\r\n
\r\n\r\nand if you wanted to be able to add counters dynamically (one of the advantages of using a map in this context) you could redefine the function employ an optional argument, which if present instructs the function to create a new key-value pair using the name and initial value provided:\r\n\r\n
(defn inc-ref [ref type & [init-value]]\r\n  (if init-value\r\n    (dosync\r\n     (alter ref assoc type init-value)\r\n     (type @ref))\r\n    (dosync\r\n     (alter ref assoc type (inc (name @ref)))\r\n     (type @ref))))\r\n\r\nuser> (inc-ref counts :articles)\r\n=>1\r\nuser> (inc-ref counts :magazines 1)\r\n=>1\r\nuser> (:magazines @counts)\r\n=>1
","created-at":1325048179000,"author":{"login":"borg","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/91d340132e883c02020ccd56946b2b91?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fd4"},{"updated-at":1349979324000,"body":"In the previous example at row 07 has a reference to 'name @ref':\r\n
(alter ref assoc type (inc (name @ref)))
\r\nmaybe is incorrect and the correct mode is: \r\n
 (alter ref assoc type (inc (type @ref)))
","created-at":1349979324000,"author":{"login":"grayzone","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/261286ad984a83e1b0c5e0d7695d58fc?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fec"}],"arglists":["ref fun & args"],"doc":"Must be called in a transaction. Sets the in-transaction-value of\n ref to:\n\n (apply fun in-transaction-value-of-ref args)\n\n and returns the in-transaction-value of ref.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/alter"},{"added":"1.0","ns":"clojure.core","name":"-'","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1412882360420,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"},"to-var":{"ns":"clojure.core","name":"-","library-url":"https://github.com/clojure/clojure"},"_id":"5436dfb8e4b0ae7956031578"},{"created-at":1423527625657,"author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"to-var":{"ns":"clojure.core","name":"unchecked-subtract","library-url":"https://github.com/clojure/clojure"},"_id":"54d94ec9e4b081e022073c86"},{"created-at":1423527647730,"author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"to-var":{"ns":"clojure.core","name":"unchecked-negate","library-url":"https://github.com/clojure/clojure"},"_id":"54d94edfe4b081e022073c87"}],"line":1033,"examples":[{"body":";; unlike the * and + functions there is no 0 arity form\n(-')\n;; ArityException: wrong number of args (0)\n\n(-' 1)\n;;=> -1 \n\n(-' 6 3) \n;;=> 3\n\n(-' 10 3 2) \n;;=> 5\n\n(- 0 9000000000000000000 1000000000000000000)\n;; ArithmeticException: integer overflow\n\n(-' 0 9000000000000000000 1000000000000000000)\n;;=> 10000000000000000000N ","author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"},"created-at":1412882316521,"updated-at":1412882316521,"_id":"5436df8ce4b06dbffbbb00c3"}],"notes":null,"arglists":["x","x y","x y & more"],"doc":"If no ys are supplied, returns the negation of x, else subtracts\n the ys from x and returns the result. Supports arbitrary precision.\n See also: -","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/-'"},{"added":"1.6","ns":"clojure.core","name":"if-some","file":"clojure/core.clj","type":"macro","column":1,"see-alsos":[{"created-at":1417641557196,"author":{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/94482?v=3"},"to-var":{"ns":"clojure.core","name":"when-some","library-url":"https://github.com/clojure/clojure"},"_id":"547f7e55e4b03d20a10242bd"},{"created-at":1440455816295,"author":{"login":"brunchboy","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2228869?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"if-let","ns":"clojure.core"},"_id":"55db9c88e4b072d7f27980ef"},{"created-at":1528840542254,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"some","ns":"clojure.core"},"_id":"5b20415ee4b00ac801ed9e12"}],"line":1893,"examples":[{"body":"(if-some [a 10] :true :false) ; => :true\n(if-some [a true] :true :false) ; => :true\n(if-some [a false] :true :false) ; => :true\n(if-some [a nil] :true :false) ; => :false\n\n;; for comparison\n(if-let [a 10] :true :false) ; => :true\n(if-let [a true] :true :false) ; => :true \n(if-let [a false] :true :false) ; => :false\n(if-let [a nil] :true :false) ; => :false\n","author":{"login":"philoskim","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/5637280?v=3"},"created-at":1420603516061,"updated-at":1420603516061,"_id":"54acb07ce4b09260f767ca8e"}],"macro":true,"notes":[{"body":"See [this Jira ticket](http://dev.clojure.org/jira/browse/CLJ-1343) for some background on this.\n\n (if-some [var test] then else)\n\nis essentially equivalent to:\n\n (if-let [var (not (nil? test))] then else)\n","created-at":1417641857996,"updated-at":1417641857996,"author":{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/94482?v=3"},"_id":"547f7f81e4b03d20a10242be"},{"author":{"login":"titogarcia","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/699549?v=4"},"updated-at":1634126821797,"created-at":1634126821797,"body":"> `(if-some [var test] then else)`\n>\n> is essentially equivalent to:\n>\n> `(if-let [var (not (nil? test))] then else)`\n\nThis is incorrect. Notice that `nil?` will return a boolean. This equivalency would only be true if `test` is a boolean value.","_id":"6166cbe5e4b0b1e3652d7559"}],"arglists":["bindings then","bindings then else & oldform"],"doc":"bindings => binding-form test\n\n If test is not nil, evaluates then with binding-form bound to the\n value of test, if not, yields else","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/if-some"},{"added":"1.1","ns":"clojure.core","name":"conj!","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1286870227000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"transient","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d6f"},{"created-at":1329969779000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.core","name":"assoc!","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d70"},{"created-at":1329969851000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.core","name":"dissoc!","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d71"},{"created-at":1473091049902,"author":{"login":"mars0i","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1836941?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"conj","ns":"clojure.core"},"_id":"57cd95e9e4b0709b524f04e3"}],"line":3384,"examples":[{"updated-at":1577915992503,"created-at":1286870264000,"body":";; As seen on http://clojure.org/transients\n;; array is initially made transient, modified then\n;; finally made persistent.\n\n;; Note: This example correctly always uses the return value of conj! for\n;; future modifications, not the original value of v. See assoc! examples,\n;; and another example for conj!, for some discussion of why this is important.\n\n(defn vrange2 [n]\n (loop [i 0 v (transient [])]\n (if (< i n)\n (recur (inc i) (conj! v i))\n (persistent! v))))\n\nuser=> (vrange2 10)\n[0 1 2 3 4 5 6 7 8 9]","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3","account-source":"github","login":"jafingerhut"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon","account-source":"clojuredocs","login":"gstamp"},"_id":"542692cac026201cdc326b43"},{"updated-at":1577915639084,"created-at":1577915639084,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/109629?v=4"},"body":";; The next function below uses conj! incorrectly, ignoring its return\n;; value.\n\nuser=> (defn into-bad-example-bash-in-place [to-coll from-coll]\n (let [t (transient to-coll)]\n (loop [f (seq from-coll)]\n (if-let [s (seq f)]\n (do\n (conj! t (first s))\n (recur (next s)))\n (persistent! t)))))\n\n;; The first example call below returns the desired value.\n\nuser=> (into-bad-example-bash-in-place {:a 1, :b 2, :c 3} {:d 4, :e 5})\n{:a 1, :b 2, :c 3, :d 4, :e 5}\n\n;; However, it is by accident that it is correct. This effect can be\n;; subtle and surprising to many, because many experiments will return\n;; the desired values, as the example above does.\n\n;; The return value is correct for these inputs because all of these\n;; calls to conj! not only return the mutated object that we should be\n;; using, but they also happen to mutate the object in place that it\n;; is passed. Thus ignoring the return value happens not to lead to\n;; incorrect behavior here.\n\n;; However, conj! _can_ in some cases return a different object than\n;; the one it was passed, and _not_ mutate the object it is passed.\n;; Look at this return value.\n\nuser=> (into-bad-example-bash-in-place\n {:a 1, :b 2, :c 3, :d 4, :e 5, :f 6, :g 7, :h 8}\n {:i 9})\n{:a 1, :b 2, :c 3, :d 4, :e 5, :f 6, :g 7, :h 8}\n\n;; This result is not what we want, because key :i is not present in\n;; the result anywhere. conj! returned a different object than the\n;; one it was given, but the function above does not use the return\n;; value, instead discarding it.\n\n;; The function below uses conj! as it should be, always using its\n;; return value in future calls on the transient collection.\n\nuser=> (defn into-better-use-return-value [to-coll from-coll]\n (loop [t (transient to-coll)\n f (seq from-coll)]\n (if-let [s (seq f)]\n (recur (conj! t (first s))\n (next s))\n (persistent! t))))\n\nuser=> (into-better-use-return-value {:a 1, :b 2, :c 3} {:d 4, :e 5})\n{:a 1, :b 2, :c 3, :d 4, :e 5}\n\nuser=> (into-better-use-return-value\n {:a 1, :b 2, :c 3, :d 4, :e 5, :f 6, :g 7, :h 8}\n {:i 9})\n{:e 5, :g 7, :c 3, :h 8, :b 2, :d 4, :f 6, :i 9, :a 1}\n\n;; The keys are not in the same order, but recall that regular Clojure\n;; maps are not sorted in any predictable way, as opposed to\n;; sorted-map's. However, all 9 of the keys that we expect to be\n;; there, are there.","_id":"5e0d14f7e4b0ca44402ef804"}],"notes":null,"arglists":["","coll","coll x"],"doc":"Adds x to the transient collection, and return coll. The 'addition'\n may happen at different 'places' depending on the concrete type.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/conj!"},{"added":"1.0","ns":"clojure.core","name":"repeatedly","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1286264111000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"repeat","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c8e"},{"created-at":1289359620000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"iterate","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c8f"},{"created-at":1289359625000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"lazy-seq","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c90"},{"created-at":1295239829000,"author":{"login":"TimMc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5d532e51427ef2f4ded31aaca16c8baf?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"dotimes","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c91"},{"created-at":1295239907000,"author":{"login":"TimMc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5d532e51427ef2f4ded31aaca16c8baf?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"doall","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c92"},{"created-at":1343151093000,"author":{"login":"john.r.woodward","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/22b6fbc4a386291e45b1cb4449377086?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"rand-int","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c93"},{"created-at":1345605379000,"author":{"login":"abrooks","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/69976?v=2"},"to-var":{"ns":"clojure.core","name":"constantly","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c94"},{"created-at":1502829747775,"author":{"login":"huahaiy","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/889685?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"while","ns":"clojure.core"},"_id":"59935cb3e4b0d19c2ce9d717"}],"line":5196,"examples":[{"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"editors":[{"login":"citizen428","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/b3881a28fe402dd2d1de44717486cae8?r=PG&default=identicon"},{"login":"citizen428","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/b3881a28fe402dd2d1de44717486cae8?r=PG&default=identicon"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},{"login":"nyashh","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2254461eab79d5d84a021414e8e36dba?r=PG&default=identicon"},{"login":"john.r.woodward","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/22b6fbc4a386291e45b1cb4449377086?r=PG&default=identicon"},{"login":"john.r.woodward","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/22b6fbc4a386291e45b1cb4449377086?r=PG&default=identicon"},{"login":"tomas","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/c0c2f195479ae4a71cb6484679f6f49?r=PG&default=identicon"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":";; these two functions are equivalent \n\n(take 5 (repeatedly #(rand-int 11)))\n;;=> (6 6 3 9 8)\n\n;; this version only returns the first five elements\n(repeatedly 5 #(rand-int 11))\n;;=> (1 8 6 9 6)\n\n;; compare with repeat, which\n;; only calls the 'rand-int' function once,\n;; repeating the value five times.\n(repeat 5 (rand-int 100))\n(94 94 94 94 94)","created-at":1279093287000,"updated-at":1421872565837,"_id":"542692cfc026201cdc326e2f"},{"author":{"login":"Jeff Rose","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/567898c496278341be69087507d5ed24?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"philos99","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1de5617efb013ca7c9cf8e5646818ffa?r=PG&default=identicon"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":"(defn counter [] \n (let [tick (atom 0)]\n #(swap! tick inc)))\n\n(def tick (counter))\n\n(take 10 (repeatedly tick))\n;;=> (1 2 3 4 5 6 7 8 9 10)\n\n;; or equivalently\n(repeatedly 10 (counter))\n;;=> (1 2 3 4 5 6 7 8 9 10)","created-at":1283550417000,"updated-at":1421872865341,"_id":"542692cfc026201cdc326e38"},{"editors":[{"login":"Jjunior130","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7597818?v=3"}],"body":";;;; If you want random values for each element in repeatedly\n;; don't call rand as an argument in partial\n(= true\n (every? true?\n [(apply = (flatten\n (repeatedly 2 (partial vector (rand)))))\n (apply = (flatten\n (repeatedly 2 (partial (partial vector (rand))))))]))\n\n;; but do call it within a #(...) or (fn [] ...)\n(= true\n (every? false?\n [(apply = (repeatedly 2 rand)) \n (apply = (repeatedly 2 #(rand))) \n (apply = (repeatedly 2 (partial rand))) ; passing the rand function works\n (apply = (flatten\n (repeatedly 2 (fn [] (vector (rand))))))\n (apply = (flatten\n (repeatedly 2 #((partial vector (rand))))))\n (apply = (flatten\n (repeatedly 2 #(vector (rand)))))]))","author":{"avatar-url":"https://avatars.githubusercontent.com/u/7597818?v=3","account-source":"github","login":"Jjunior130"},"created-at":1483821463432,"updated-at":1483821506915,"_id":"58715197e4b09108c8545a50"},{"updated-at":1520597247645,"created-at":1520595747920,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"body":";; \"repeatedly\" used to build a infinite sequence of side-effecting futures.\n;; Futures are taken in batch of \"parallel\" concurrent threads. The queue\n;; can be fed while the loop is running. \"done?\" determines the exit condition.\n\n(import '[java.util.concurrent ConcurrentLinkedQueue])\n(def q (ConcurrentLinkedQueue. (range 100)))\n\n(let [parallel 5\n done? #(> (reduce + (remove nil? %)) 30)\n task #(do (println \"start\" %) (Thread/sleep 1000) (inc %))]\n (loop [workers (repeatedly\n #(let [out *out*]\n (future\n (binding [*out* out]\n (when-let [item (.poll q)]\n (task item))))))]\n (println \"-> starting\" parallel \"new workers\")\n (let [futures (doall (take parallel workers))\n results (mapv deref futures)]\n (cond\n (done? results) results\n (.isEmpty q) (println \"Empty.\")\n :else (recur (drop parallel workers))))))\n\n;; -> starting 5 new workers\n;; startstart 03\n;;\n;; startstart 1\n;; 2start 4\n;;\n;; -> starting 5 new workers\n;; start 5start\n;; start start7start\n;; 6\n;; 8\n;; 9\n[6 7 8 9 10]\n","editors":[{"avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"}],"_id":"5aa27323e4b0316c0f44f914"},{"updated-at":1576431818434,"created-at":1576431818434,"author":{"login":"loeschzwerg","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/24317401?v=4"},"body":";; CLI app to return the type of a line\n\n(doseq [val (repeatedly read-line)]\n (prn\n (type\n (clojure.edn/read-string val))))\n\n;; $\nHello\nclojure.lang.Symbol\n15\njava.lang.Long\n:keyword\nclojure.lang.Keyword\n{}\nclojure.lang.PersistentArrayMap","_id":"5df670cae4b0ca44402ef7fb"}],"notes":[{"updated-at":1289359893000,"body":"if the function you want to repeat doesn't have side effects and has an argument, 'iterate' may be what you are looking for.","created-at":1289359893000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fa1"}],"arglists":["f","n f"],"doc":"Takes a function of no args, presumably with side effects, and\n returns an infinite (or length n if supplied) lazy sequence of calls\n to it","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/repeatedly"},{"added":"1.0","ns":"clojure.core","name":"zipmap","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1325197673000,"author":{"login":"mmwaikar","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/29d36f4c9f39c9f8ff61c07033b13118?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"interleave","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e62"},{"created-at":1652060861458,"author":{"login":"KyleErhabor","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/40676441?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"into","ns":"clojure.core"},"_id":"627872bde4b0b1e3652d75ec"}],"line":6660,"examples":[{"author":{"avatar-url":"https://avatars.githubusercontent.com/u/142529?v=3","account-source":"github","login":"nipra"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"avatar-url":"https://avatars.githubusercontent.com/u/5696817?v=3","account-source":"github","login":"liango2"}],"body":"user=> (zipmap [:a :b :c :d :e] [1 2 3 4 5])\n{:a 1, :b 2, :c 3, :d 4, :e 5}\n","created-at":1279388151000,"updated-at":1451234587672,"_id":"542692c7c026201cdc3269a8"},{"author":{"login":"devn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3"},"editors":[{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},{"login":"liango2","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/5696817?v=3"}],"body":";; 4 is not included in the result\nuser=> (zipmap [:a :b :c] [1 2 3 4])\n{:a 1, :b 2, :c 3}\n\n;; :c is not included in the result\nuser=> (zipmap [:a :b :c] [1 2])\n{:a 1, :b 2}","created-at":1335331821000,"updated-at":1451234612952,"_id":"542692d6c026201cdc3270cb"},{"editors":[{"login":"ys-achinta","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/10450478?v=4"}],"body":"user=> (pprint \n (zipmap [:html :body :div] (repeat {:margin 0 :padding 0})))\n{:html {:margin 0, :padding 0},\n :body {:margin 0, :padding 0},\n :div {:margin 0, :padding 0}}","author":{"avatar-url":"https://avatars.githubusercontent.com/u/4471727?v=3","account-source":"github","login":"edbedbe"},"created-at":1439315700433,"updated-at":1566311402870,"_id":"55ca36f4e4b0080a1b79cdb9"},{"editors":[{"login":"tecigo","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/13831422?v=3"}],"body":";; transform a CSV file to an array of maps using the header line as keys\nuser=> (defn csv-map\n \"ZipMaps header as keys and values from lines.\"\n [head & lines]\n (map #(zipmap (map keyword head) %1) lines))\n\nuser=> (apply csv-map [[\"FirstName\", \"LastName\"], [\"John\", \"Doe\"], [\"Jill\", \"Doh\"]])\n({:FirstName \"John\", :LastName \"Doe\"}, {:FirstName \"Jill\", :LastName \"Doh\"})","author":{"avatar-url":"https://avatars.githubusercontent.com/u/13831422?v=3","account-source":"github","login":"tecigo"},"created-at":1459353469570,"updated-at":1459354350134,"_id":"56fbf77de4b069b77203b858"},{"updated-at":1472949315282,"created-at":1472949315282,"author":{"login":"d-lord","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/6218499?v=3"},"body":";; initialize with 0 for all values\nuser=> (zipmap [:a :b :c] (repeat 0))\n{:a 0, :b 0, :c 0}","_id":"57cb6c43e4b0709b524f04e1"},{"updated-at":1488306683395,"created-at":1488306683395,"author":{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/94482?v=3"},"body":";; Note that if the keys are not unique, you can potentially lose data:\nuser=> (zipmap [:a :b :c :a] [1 2 3 4])\n{:a 4, :b 2, :c 3}\n","_id":"58b5c1fbe4b01f4add58fe66"},{"editors":[{"login":"zyxmn-rvu","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/53867608?v=4"}],"body":";; Note the generated map is meant to be un-ordered and can be noticed only for sizes greater than 8\n\n;; Ordered as key coll argument\nuser=> (zipmap [:key1 :key2 :key3 :key4 :key5 :key6 :key7 :key8] [1 2 3 4 5 6 7 8])\n{:key1 1, :key2 2, :key3 3, :key4 4, :key5 5, :key6 6, :key7 7, :key8 8}\n\n;; Un-ordered\nuser=> (zipmap [:key1 :key2 :key3 :key4 :key5 :key6 :key7 :key8 :key9] [1 2 3 4 5 6 7 8 9])\n{:key3 3, :key2 2, :key8 8, :key6 6, :key9 9, :key7 7, :key4 4, :key1 1, :key5 5}\n","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/53867608?v=4","account-source":"github","login":"zyxmn-rvu"},"created-at":1574963248718,"updated-at":1574963310117,"_id":"5de00830e4b0ca44402ef7ed"},{"updated-at":1649862774454,"created-at":1649862774454,"author":{"login":"stindrago","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/69054881?v=4"},"body":";; Alternative logic for `cond` scenarios\n\n;; `zipmap` returns a map paring each value in the range (1-4) to a percentage (50%)\n(def rates\n (conj {0 0/100}\n (zipmap (range 1 5) (repeat 50/100))\n {5 90/100}))\n;; => {0 0, 1 1/2, 2 1/2, 3 1/2, 4 1/2, 5 9/10}\n\n(* 2.0 (rates 3))\n;; => 1.0","_id":"6256e876e4b0b1e3652d75d3"}],"notes":[{"author":{"login":"seeeturtle","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/22187719?v=4"},"updated-at":1553308608008,"created-at":1553308608008,"body":"`zipmap` always leave last key & val if keys are duplicated\nlike the last example code.\n\nYou can know them from source code which `assoc` key & val to result map in left-to-right order.","_id":"5c959bc0e4b0ca44402ef6c0"}],"arglists":["keys vals"],"doc":"Returns a map with the keys mapped to the corresponding vals.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/zipmap"},{"added":"1.9","ns":"clojure.core","name":"reset-vals!","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1722240797007,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"swap-vals!","ns":"clojure.core"},"_id":"66a74f1d69fbcc0c226174e4"}],"line":2400,"examples":[{"updated-at":1539313237640,"created-at":1539312224752,"author":{"login":"WinfieldHill","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/4356515?v=4"},"body":";; An atom is defined\n(def open-sockets (atom []))\n;;=> #'user/open-sockets\n\n;; Conjoin a value or two onto the atom\n(swap! open-sockets conj socket)\n;;=> [<< stream: 1 >> << stream: 2 >>]\n\n;; Knock the first socket out of open-sockets\n(reset-vals! open-sockets (subvec @open-sockets 1))\n;;=> [[<< stream: 1 >> << stream: 2 >>][<< stream: 2 >>]]\n\n;; Knock the last socket out of open-sockets\n(reset-vals! open-sockets (pop @open-sockets))\n;;=> [[<< stream: 2 >>] []]","editors":[{"avatar-url":"https://avatars0.githubusercontent.com/u/4356515?v=4","account-source":"github","login":"WinfieldHill"}],"_id":"5bc00a60e4b00ac801ed9ed2"}],"notes":null,"arglists":["atom newval"],"doc":"Sets the value of atom to newval. Returns [old new], the value of the\n atom before and after the reset.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/reset-vals!"},{"added":"1.0","ns":"clojure.core","name":"alter-var-root","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1322088086000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"with-redefs","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f28"},{"created-at":1322088098000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"with-redefs-fn","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f29"},{"created-at":1360641932000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"intern","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f2a"},{"created-at":1374167327000,"author":{"login":"alilee","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2fb0196dc5a7cd3a5cc73f1b9941c209?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"var","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f2b"},{"created-at":1501312693026,"author":{"login":"didibus","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/601540?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"set!","ns":"clojure.core"},"_id":"597c36b5e4b0d19c2ce9d702"}],"line":5558,"examples":[{"updated-at":1607409758219,"created-at":1283913245000,"body":"(defn sqr [n] \n \"Squares a number\"\n (* n n))\n\nuser=> (sqr 5)\n25\n\nuser=> (alter-var-root \n (var sqr) ; var to alter\n (fn [f] ; fn to apply to the var's value\n (fn [n] ; returns a new fn wrapping old fn\n (println \"Squaring\" n)\n (f n))))\n\nuser=> (sqr 5)\nSquaring 5\n25\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"login":"liuchong","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/236058?v=4"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/5aa24eee4238e1e964210ed447e8dc91?r=PG&default=identicon","account-source":"clojuredocs","login":"fogus"},"_id":"542692cfc026201cdc326e70"},{"updated-at":1472301721034,"created-at":1472301721034,"author":{"login":"manishkumarmdb","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/9373950?v=3"},"body":";;change the value of a var, instead of (def varName value)\nuser=> (def string \"abcd\")\n#'user/string\n\nuser=> string\n\"abcd\"\n\nuser=> (alter-var-root #'string (constantly \"wxyz\"))\n\"wxyz\"\n\nuser=> string\n\"wxyz\"","_id":"57c18a99e4b0709b524f04d6"},{"editors":[{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"}],"body":";; alter-var-root does not play well with inlined vars\n\n(definline timespi [x] `(* ~x 3.14))\n(alter-var-root #'timespi (fn [_] (constantly 1)))\n(timespi 10)\n;; 31.400000000000002\n\n;; Remove the inlining to pass through the var indirection (credits @bronsa)\n(alter-meta! #'timespi dissoc :inline-arities :inline)\n(timespi 10)\n;; 1","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"},"created-at":1546020626144,"updated-at":1546020907201,"_id":"5c266712e4b0ca44402ef601"},{"updated-at":1648587095817,"created-at":1648587095817,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/159047?v=4"},"body":"(defn instrument-ns\n \"Add some basic instrumentation to each var in a given namespace `sut`.\n A poor man's profiler, this simply prints out the name of each\n fn (var) when run.\"\n [sut]\n (let [fs (vals (ns-interns sut))]\n (println \"Instrumenting fns to be printed as run for NS:\" sut)\n (doseq [curf fs]\n (when (some? (:arglists (meta curf))) ; ensure a fn\n (alter-var-root\n curf\n (fn [f]\n (fn [& args]\n ;; Just print out the name of the function evaluated\n (println (:name (meta curf)))\n ;; (System/currentTimeMillis) ; could add timing info before/after\n (apply f args))))))))\n","_id":"62437157e4b0b1e3652d75c4"},{"editors":[{"login":"Crowbrammer","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/19522656?v=4"}],"body":";; `alter-var-root` uses the same signature as `swap!` and `update`. \n;; It has uncomfortable, persistent effects if you're not careful. \n\nuser=> (def x \"Hi\")\n#'user/x\nuser=> (alter-var-root #'x #(str % \", world!\"))\n\"Hi, world!\"\nuser=> (alter-var-root #'x #(str % \", world!\"))\n\"Hi, world!, world!\"\nuser=> (alter-var-root #'x #(str % \", world!\"))\n\"Hi, world!, world!, world!\"\n","author":{"avatar-url":"https://avatars.githubusercontent.com/u/19522656?v=4","account-source":"github","login":"Crowbrammer"},"created-at":1653498578027,"updated-at":1653498619629,"_id":"628e62d2e4b0b1e3652d75f1"}],"notes":null,"arglists":["v f & args"],"doc":"Atomically alters the root binding of var v by applying f to its\n current value plus any args","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/alter-var-root"},{"added":"1.0","ns":"clojure.core","name":"biginteger","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1509577866305,"author":{"login":"chrm","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/448995?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"bigint","ns":"clojure.core"},"_id":"59fa548ae4b0a08026c48c92"}],"line":3659,"examples":[{"author":{"login":"linxiangyu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2c7492645426ece4ae86fde83d61bd03?r=PG&default=identicon"},"editors":[],"body":"user=> (def x (biginteger 19931029))\n#'user/x\nuser=> (class x)\njava.math.BigInteger\n\n\n\n","created-at":1370558225000,"updated-at":1370558225000,"_id":"542692d2c026201cdc326f53"},{"updated-at":1509577857859,"created-at":1509577857859,"author":{"login":"chrm","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/448995?v=4"},"body":";; There is a difference between `BigInt` and `BigInteger`. The first is from\n;; Clojure and should be better for performace, because less unboxing is\n;; necessary. The second is from Java and has more functionality.\n;; https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html\n\n(type 123N)\n;; => clojure.lang.BigInt\n\n(type (bigint 123))\n;; => clojure.lang.BigInt\n\n(type (biginteger 123))\n;; => java.math.BigInteger\n\n(.modInverse (bigint 123) (bigint 4))\n;; IllegalArgumentException No matching method found: modInverse for class\n;; clojure.lang.BigInt\n\n(.modInverse (biginteger 123) (biginteger 4))\n;; => 3","_id":"59fa5481e4b0a08026c48c91"},{"editors":[{"login":"cloojure","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/7083783?v=4"}],"body":"; It also works for strings\n(biginteger \"12345\") => 12345 ; java.math.BigInteger\n","author":{"avatar-url":"https://avatars0.githubusercontent.com/u/7083783?v=4","account-source":"github","login":"cloojure"},"created-at":1535909938405,"updated-at":1535910003220,"_id":"5b8c2032e4b00ac801ed9e7f"},{"updated-at":1598221345110,"created-at":1598221345110,"author":{"login":"berczeck","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/1321842?v=4"},"body":";; Take care with ratios the decimal part is removed not rounded\nuser=> (biginteger 5/4) ; 1.25\n;; 1\n\nuser=> (biginteger 5/2) ; 2.5\n;; 2","_id":"5f42ec21e4b0b1e3652d73a8"}],"notes":null,"tag":"java.math.BigInteger","arglists":["x"],"doc":"Coerce to BigInteger","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/biginteger"},{"added":"1.0","ns":"clojure.core","name":"remove","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1282310768000,"author":{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},"to-var":{"ns":"clojure.core","name":"filter","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cee"},{"created-at":1487135935513,"author":{"login":"chrismurrph","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10278575?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"group-by","ns":"clojure.core"},"_id":"58a3e4bfe4b01f4add58fe55"},{"created-at":1501184742340,"author":{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/94482?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"keep","ns":"clojure.core"},"_id":"597a42e6e4b0d19c2ce9d701"},{"created-at":1713480509845,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"dissoc","ns":"clojure.core"},"_id":"6621a33d69fbcc0c226174bf"}],"line":2843,"examples":[{"author":{"login":"zmila","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/68dd6f50915854aa04fefcf4d6fa5c8e?r=PG&default=identicon"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"login":"sir-pinecone","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/40753?v=3"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":"(remove pos? [1 -2 2 -1 3 7 0])\n;;=> (-2 -1 0)\n\n(remove nil? [1 nil 2 nil 3 nil])\n;;=> (1 2 3)\n\n;; remove items that are evenly divisible by 3\n(remove #(zero? (mod % 3)) (range 1 21))\n;;=> (1 2 4 5 7 8 10 11 13 14 16 17 19 20)","created-at":1281548721000,"updated-at":1420744145542,"_id":"542692cfc026201cdc326e3c"},{"body":";; compare to filter\n\n(remove even? (range 10))\n;;=> (1 3 5 7 9)\n\n(remove (fn [x]\n (= (count x) 1))\n [\"a\" \"aa\" \"b\" \"n\" \"f\" \"lisp\" \"clojure\" \"q\" \"\"])\n;;=> (\"aa\" \"lisp\" \"clojure\" \"\")\n\n; When coll is a map, pred is called with key/value pairs.\n(remove #(> (second %) 100)\n {:a 1\n :b 2\n :c 101\n :d 102\n :e -1})\n;;=> ([:a 1] [:b 2] [:e -1])\n","author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"},"created-at":1420744060322,"updated-at":1420744060322,"_id":"54aed57ce4b0e2ac61831ca0"},{"updated-at":1453292141320,"created-at":1453292141320,"author":{"login":"esumitra","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/98965?v=3"},"body":";; remove items from a set/list\n\n(remove #{:a} #{:b :c :d :a :e})\n;;=> (:e :c :b :d)\n\n(remove #{:a} [:b :c :d :a :e :a :f])\n;;=> (:b :c :d :e :f)\n","_id":"569f7a6de4b060004fc217af"},{"updated-at":1516533045589,"created-at":1516533045589,"author":{"login":"vastus","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/199064?v=4"},"body":";; use map as a pred\n\n(remove {:a 42 :b 69} #{:a :b :c})\n;;=> (:c)","_id":"5a647535e4b0637c3b2baf4c"},{"updated-at":1594561061837,"created-at":1594561061837,"author":{"login":"kevinmungai","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/23656776?v=4"},"body":";; remove all the hyphens in an ISBN Number\n\n(into [] (remove #{\\-}) \"3-598-21508-8\")\n;;=> [\\3 \\5 \\9 \\8 \\2 \\1 \\5 \\0 \\8 \\8]\n\n;; remove is used in the capacity of a transducer","_id":"5f0b1225e4b0b1e3652d7321"},{"updated-at":1601477483307,"created-at":1601477483307,"author":{"login":"E-A-Griffin","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/53583563?v=4"},"body":";; remove unique elements from collection\n\n(def nums (concat (range 10) (range 5 15)))\n\n(keys (remove (fn [[k v]] (= v 1))\n (frequencies nums)))\n;;=> (7 6 9 5 8)\n\n;; remove unique elements from collection, preserving order\n(defn keep-duplicates [coll]\n (sort-by #((into {} (map-indexed vector coll)) %) \n (keys (remove (fn [[k v]] (= v 1))\n (frequencies coll)))))\n\n(keep-duplicates nums)\n;; => (5 6 7 8 9)\n\n(def rev-nums (reverse nums))\n\n(keep-duplicates rev-nums)\n;;=> (9 8 7 6 5)","_id":"5f749b6be4b0b1e3652d73c6"}],"notes":null,"arglists":["pred","pred coll"],"doc":"Returns a lazy sequence of the items in coll for which\n (pred item) returns logical false. pred must be free of side-effects.\n Returns a transducer when no collection is provided.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/remove"},{"added":"1.2","ns":"clojure.core","name":"*","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1323065497000,"author":{"login":"Claj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5fd658a8d2ef549071cb5286b1b874aa?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"*'","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ca8"},{"created-at":1423527840855,"author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"to-var":{"ns":"clojure.core","name":"unchecked-multiply","library-url":"https://github.com/clojure/clojure"},"_id":"54d94fa0e4b081e022073c88"}],"line":1010,"examples":[{"author":{"login":"samaaron","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/ee3512261f38df2541b9adca77f025cb?r=PG&default=identicon"},"editors":[{"login":"OnesimusUnbound","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2fa4c391db0d2d1744cc2cd0d787dd3d?r=PG&default=identicon"},{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"login":"jmglov","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/67e9a6f766dc4b30bd5e9ff3e77c1777?r=PG&default=identicon"},{"login":"rafmagana","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/92894?v=3"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"},{"login":"berczeck","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/1321842?v=4"}],"body":";; there is an implicit 1\n(*)\n;;=> 1 \n\n;; the implicit 1 comes into play\n(* 6)\n;;=> 6\n\n(* 2 3)\n;;=> 6\n\n(* 2 3 4)\n;;=> 24\n\n(* 0.5 200)\n;;=> 100.0\n\n(* 8 1/2)\n;;=> 4N\n\n(* 1234567890 9876543210)\n;; ArithmeticException integer overflow","created-at":1278738436000,"updated-at":1598154236190,"_id":"542692c8c026201cdc326a45"}],"notes":[{"author":{"login":"ClemRz","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1130946?v=4"},"updated-at":1721779674549,"created-at":1721779674549,"body":"Beware of floating-point related issues:\n\n```\n=> (* 155.39 100)\n15538.999999999998\n```","_id":"66a045da69fbcc0c226174df"}],"arglists":["","x","x y","x y & more"],"doc":"Returns the product of nums. (*) returns 1. Does not auto-promote\n longs, will throw on overflow. See also: *'","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/*"},{"added":"1.0","ns":"clojure.core","name":"re-pattern","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1289146513000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"re-find","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b2f"},{"created-at":1324450178000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.string","name":"replace","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b30"},{"created-at":1324450182000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.string","name":"replace-first","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b31"}],"line":4892,"examples":[{"author":{"login":"dakrone","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bcacd00a7f05c4772329cf9f446c7987?r=PG&default=identicon"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"login":"NielsK","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/11ab6518d419df03c4883af80b5697ee?r=PG&default=identicon"}],"body":"user=> (re-pattern \"\\\\d+\")\n#\"\\d+\"\n\nuser=> (re-find (re-pattern \"\\\\d+\") \"abc123def\") \n\"123\"\n\n;; If you want to construct a regex pattern dynamically at run time,\n;; then you need to use re-pattern to convert a string to a pattern\n;; that can be used for matching. But if your pattern is one you\n;; write into the source code, it is more convenient to use the\n;; #\"pattern\" syntax. The previous example can be written as follows.\nuser=> (re-find #\"\\d+\" \"abc123def\") \n\"123\"\n\n;; Below are two examples that are equivalent in the patterns they\n;; use, but the #\"pattern\" syntax helps significantly, because it lets\n;; us avoid the requirement to escape every \\ character with another \\\n;; character. See the example with embedded comments below for more\n;; detail on what the pattern matches.\nuser=> (re-find #\"\\\\\\d+\\s+\\S+\" \"\\\\ it sh0uld match in \\\\5 here somewhere.\")\n\"\\\\5 here\"\n\nuser=> (re-find (re-pattern \"\\\\\\\\\\\\d+\\\\s+\\\\S+\")\n \"\\\\ it sh0uld match in \\\\5 here somewhere.\")\n\"\\\\5 here\"\n\n;; If you want to embed (ignored) whitespace and comments from #\n;; characters until end-of-line in your regex patterns, start the\n;; pattern with (?x)\nuser=> (re-find #\"(?x) # allow embedded whitespace and comments\n \\\\ # backslash\n \\d+ # one or more digits\n \\s+ # whitespace\n \\S+ # non-whitespace\"\n \"\\\\ it sh0uld match in \\\\5 here somewhere.\")\n\"\\\\5 here\"\n\n;; Other pattern flags like Java's DOTALL, MULTILINE and UNICODE_CASE\n;; pattern matching modes, can be set by combining these embedded flags\n\n;; (?d) Unix lines (only match \\newline)\n;; (?i) Case-insensitive\n;; (?u) Unicode-aware Case\n;; (?m) Multiline\n;; (?s) Dot matches all (including newline)\n;; (?x) Ignore Whitespace and comments\n\nuser=> (re-seq #\"(?ix) test #Case insensitive and comments allowed\"\n \"Testing,\\n testing,\\n 1 2 3\")\n(\"Test\" \"test\")\n","created-at":1280547138000,"updated-at":1365007458000,"_id":"542692c6c026201cdc3268c7"}],"notes":[{"author":{"login":"nuggets510","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/5713182?v=4"},"updated-at":1567898080855,"created-at":1567898080855,"body":"You can access documentation for the regex pattern \"language\" using (javadoc java.util.regex.Pattern) at the repl prompt. it should take you here: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/regex/Pattern.html","_id":"5d7439e0e4b0ca44402ef7ae"}],"tag":"java.util.regex.Pattern","arglists":["s"],"doc":"Returns an instance of java.util.regex.Pattern, for use, e.g. in\n re-matcher.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/re-pattern"},{"added":"1.0","ns":"clojure.core","name":"min","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1371841114000,"author":{"login":"adereth","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5ad11b4e208a6cdb3bd45fe01dea59b7?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"max","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f10"},{"created-at":1371841126000,"author":{"login":"adereth","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5ad11b4e208a6cdb3bd45fe01dea59b7?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"min-key","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f11"}],"line":1127,"examples":[{"updated-at":1332951489000,"created-at":1279417619000,"body":"user=> (min 1 2 3 4 5) \n1\nuser=> (min 5 4 3 2 1)\n1\nuser=> (min 100)\n100","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3","account-source":"github","login":"jafingerhut"}],"author":{"avatar-url":"https://avatars2.githubusercontent.com/u/22608?v=4","account-source":"github","login":"MrHus"},"_id":"542692cfc026201cdc326e7a"},{"author":{"login":"jmglov","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/67e9a6f766dc4b30bd5e9ff3e77c1777?r=PG&default=identicon"},"editors":[],"body":";; If elements are already in a sequence, use apply\nuser=> (apply min [1 2 3 4 3])\n1\nuser=> (apply min '(4 3 5 6 2))\n2","created-at":1392661837000,"updated-at":1392661837000,"_id":"542692d4c026201cdc327011"}],"notes":null,"arglists":["x","x y","x y & more"],"doc":"Returns the least of the nums.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/min"},{"added":"1.1","ns":"clojure.core","name":"pop!","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1329970267000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.core","name":"assoc!","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521dcf"},{"created-at":1329970271000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.core","name":"dissoc!","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521dd0"},{"created-at":1577916147025,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/109629?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"conj!","ns":"clojure.core"},"_id":"5e0d16f3e4b0ca44402ef80a"}],"line":3418,"examples":[{"updated-at":1577916129615,"created-at":1307739212000,"body":";; Note how we always use the return value of pop! in these examples\n;; for all future modifications, rather than (incorrectly) ignoring the return\n;; value and continuing to modify the original transient set. See examples for\n;; assoc! and dissoc! for more discussion and examples of this.\n;; Also see one example for conj! that contains a detailed example\n;; of a wrong result that can occur if you do not use its return value.\n\nuser=> (def foo (transient [1 2 3]))\n#'user/foo\nuser=> (count foo)\n3\nuser=> (def foo (pop! foo))\n#'user/foo\nuser=> foo\n#\nuser=> (count foo)\n2\nuser=> (def foo (pop! foo))\n#'user/foo\nuser=> (count foo)\n1\nuser=> (def foo (persistent! foo))\n#'user/foo\nuser=> (count foo)\n1\nuser=> foo\n[1]\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3","account-source":"github","login":"jafingerhut"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/cacfb7ecf08cb6461767e514c93b7bf9?r=PG&default=identicon","account-source":"clojuredocs","login":"yasuto"},"_id":"542692c7c026201cdc3269ce"}],"notes":null,"arglists":["coll"],"doc":"Removes the last item from a transient vector. If\n the collection is empty, throws an exception. Returns coll","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/pop!"},{"ns":"clojure.core","name":"chunk-append","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1443937484077,"author":{"login":"devn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"chunk-buffer","ns":"clojure.core"},"_id":"5610bccce4b0686557fcbd51"},{"created-at":1443937492439,"author":{"login":"devn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"chunk","ns":"clojure.core"},"_id":"5610bcd4e4b08e404b6c1ca4"}],"line":697,"examples":[{"updated-at":1443937472462,"created-at":1443937472462,"author":{"login":"devn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3"},"body":"(let [buf (chunk-buffer 16)]\n ;; Mutably append elements to the ChunkedBuffer\n (dotimes [n 10]\n (chunk-append buf n))\n\n ;; Demonstrate pulling elements out.\n ;; Note that the `capacity` we set above (16) for `buf`.\n (let [ch (chunk buf)]\n (for [n (range 0 17)]\n (try (.nth ch n)\n (catch ArrayIndexOutOfBoundsException e\n \"too far!\")))))\n\n;; => (0 1 2 3 4 5 6 7 8 9 nil nil nil nil nil nil \"too far!\")","_id":"5610bcc0e4b08e404b6c1ca3"}],"notes":null,"arglists":["b x"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core/chunk-append"},{"added":"1.0","ns":"clojure.core","name":"prn-str","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1315392416000,"author":{"login":"srid","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bd3a68d670372cd09876c26270a4299a?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"prn","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521aca"},{"created-at":1412284928324,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"},"to-var":{"ns":"clojure.edn","name":"read-string","library-url":"https://github.com/clojure/clojure"},"_id":"542dc200e4b05f4d257a299a"}],"line":4794,"examples":[{"updated-at":1495025858123,"created-at":1284257994000,"body":"user=> (def x \"Hello!\\nMy name is George.\\n\")\n#'user/x\n\nuser=> (prn-str x)\n=> \"\\\"Hello!\\\\nMy name is George.\\\\n\\\"\\n\"\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"avatar-url":"https://www.gravatar.com/avatar/7c45f63f61e478233f0c2ad3006b178c?r=PG&default=identicon","account-source":"clojuredocs","login":"mdemare"},{"avatar-url":"https://www.gravatar.com/avatar/bbb26d2a5e856c4fba0f72c3f7250f3f?r=PG&default=identicon","account-source":"clojuredocs","login":"Miles"},{"avatar-url":"https://www.gravatar.com/avatar/890d46f8c0e24dd6fb8546095b1144e?r=PG&default=identicon","account-source":"clojuredocs","login":"haplo"},{"login":"flyjwayur","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/11784820?v=3"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/bbb26d2a5e856c4fba0f72c3f7250f3f?r=PG&default=identicon","account-source":"clojuredocs","login":"Miles"},"_id":"542692cac026201cdc326b1d"},{"updated-at":1522767399827,"created-at":1522767399827,"author":{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"},"body":";; Be aware that prn-str and friends are influenced by a couple global variables\n;; such as *print-length*:\n\n(set! *print-length* 10)\n(prn-str (range 15))\n;=> \"(0 1 2 3 4 5 6 7 8 9 ...)\\n\"\n\n(set! *print-length* -1)\n(prn-str (range 15))\n;=> \"(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14)\\n\"","_id":"5ac39627e4b045c27b7fac33"},{"updated-at":1664293623051,"created-at":1664293623051,"author":{"login":"jzwolak","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/285725?v=4"},"body":";; Also, set! cannot change the root binding for *print-length*.\n;; Try the following instead.\n\n(def v [1 2 3 4 5 6 7 8 9 10])\n\n(binding [*print-length* 5] (prn-str v))\n;;=> \"[1 2 3 4 5 ...]\\n\"\n\n(binding [*print-length* -1] (prn-str v))\n;;=> \"[1 2 3 4 5 6 7 8 9 10]\\n\"","_id":"63331af7e4b0b1e3652d766a"}],"notes":null,"tag":"java.lang.String","arglists":["& xs"],"doc":"prn to a string, returning it","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/prn-str"},{"added":"1.0","ns":"clojure.core","name":"with-precision","file":"clojure/core.clj","type":"macro","column":1,"see-alsos":[{"created-at":1635281422222,"author":{"login":"Chouser","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/36110?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"*math-context*","ns":"clojure.core"},"_id":"61786a0ee4b0b1e3652d755b"},{"created-at":1698761796665,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"round","ns":"clojure.math"},"_id":"65410c4469fbcc0c2261741c"}],"line":5139,"examples":[{"author":{"login":"Miles","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bbb26d2a5e856c4fba0f72c3f7250f3f?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"Miles","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bbb26d2a5e856c4fba0f72c3f7250f3f?r=PG&default=identicon"},{"login":"wdkrnls","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/6d08a2f792f289b95fe1d982d4133d71?r=PG&default=identicon"}],"body":";; The \"M\" suffix denotes a BigDecimal instance\n;; http://download.oracle.com/javase/6/docs/api/java/math/BigDecimal.html\n\nuser=> (with-precision 10 (/ 1M 6))\n0.1666666667M\n\nuser=> (.floatValue 0.1666666667M)\n0.16666667\n","created-at":1283812216000,"updated-at":1310865949000,"_id":"542692cbc026201cdc326bb1"},{"editors":[{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"}],"body":";; This may come in handy for example when you use JDBC to grab data\n;; from a database, and numbers comes in as BigDecimal. Notice the\n;; following ArithmeticException, and solution:\n\n(/ 2M 3M) ; => ArithmeticException\n(with-precision 2 (/ 2M 3M)) ; => 0.67M\n\n;; To make this error more searchable, here's what it is, exactly:\n;;\n;; Non-terminating decimal expansion; no exact representable decimal result. \n;; java.lang.ArithmeticException: Non-terminating decimal expansion; no exact\n;; representable decimal result.\n","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/8399149?v=3","account-source":"github","login":"freckletonj"},"created-at":1490739966308,"updated-at":1524219715125,"_id":"58dae2fee4b01f4add58fe7e"},{"editors":[{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"}],"body":"(with-precision 1 :rounding UP (* 1.1M 1M)) ;; => 2M\n(with-precision 1 :rounding CEILING (* 1.1M 1M)) ;; => 2M\n(with-precision 1 :rounding UP (* -1.1M 1M)) ;; => -2M\n(with-precision 1 :rounding CEILING (* -1.1M 1M)) ;; => -1M\n\n(with-precision 1 :rounding DOWN (* 1.9M 1M)) ;; => 1M\n(with-precision 1 :rounding FLOOR (* 1.9M 1M)) ;; => 1M\n(with-precision 1 :rounding DOWN (* -1.9M 1M)) ;; => -1M\n(with-precision 1 :rounding FLOOR (* -1.9M 1M)) ;; => -2M\n\n(with-precision 1 :rounding HALF_EVEN (* 1.5M 1M)) ;; => 2M\n(with-precision 1 :rounding HALF_EVEN (* 2.5M 1M)) ;; => 2M\n(with-precision 1 :rounding HALF_EVEN (* -1.5M 1M)) ;; => -2M\n(with-precision 1 :rounding HALF_EVEN (* -2.5M 1M)) ;; => -2M\n\n(with-precision 1 :rounding HALF_UP (* 1.5M 1M)) ;; => 2M\n(with-precision 1 :rounding HALF_DOWN (* 1.5M 1M)) ;; => 1M\n(with-precision 1 :rounding HALF_UP (* -1.5M 1M)) ;; => -2M\n(with-precision 1 :rounding HALF_DOWN (* -1.5M 1M)) ;; => -1M\n\n(with-precision 1 :rounding UNNECESSARY (* 1.5M 1M))\n;; => Execution error (ArithmeticException) at…\n;; Rounding necessary\n(with-precision 1 :rounding UNNECESSARY (* 2M 1M))\n;; => 2M","author":{"avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4","account-source":"github","login":"tomdl89"},"created-at":1698761369860,"updated-at":1698761730891,"_id":"65410a9969fbcc0c2261741a"}],"macro":true,"notes":null,"arglists":["precision & exprs"],"doc":"Sets the precision and rounding mode to be used for BigDecimal operations.\n\n Usage: (with-precision 10 (/ 1M 3))\n or: (with-precision 10 :rounding HALF_DOWN (/ 1M 3))\n\n The rounding mode is one of CEILING, FLOOR, HALF_UP, HALF_DOWN,\n HALF_EVEN, UP, DOWN and UNNECESSARY; it defaults to HALF_UP.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/with-precision"},{"added":"1.0","ns":"clojure.core","name":"format","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1330170781000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.core","name":"printf","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521dbc"},{"created-at":1330170789000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.pprint","name":"cl-format","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521dbd"},{"created-at":1330170796000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.pprint","name":"print-table","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521dbe"}],"line":5791,"examples":[{"author":{"login":"Jacolyte","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1703a0c3ed358b787f4b1bf3b2799472?r=PG&default=identicon"},"editors":[{"login":"Jacolyte","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1703a0c3ed358b787f4b1bf3b2799472?r=PG&default=identicon"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"philos99","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1de5617efb013ca7c9cf8e5646818ffa?r=PG&default=identicon"}],"body":";; See http://download.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html\n;; for formatting options.\nuser=> (format \"Hello there, %s\" \"bob\")\n\"Hello there, bob\"\n","created-at":1279854390000,"updated-at":1317218923000,"_id":"542692c6c026201cdc3268ef"},{"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"login":"thethomaseffect","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/b4330b8e3ed048b2aa3b50183c42e600?r=PG&default=identicon"}],"body":"user=> (format \"%5d\" 3)\n\" 3\"\n\nuser=> (format \"Pad with leading zeros %07d\" 5432)\n\"Pad with leading zeros 0005432\"\n\nuser=> (format \"Left justified :%-7d:\" 5432)\n\"Left justified :5432 :\"\n\nuser=> (format \"Locale-specific group separators %,12d\" 1234567)\n\"Locale-specific group separators 1,234,567\"\n\nuser=> (format \"decimal %d octal %o hex %x upper-case hex %X\" 63 63 63 63)\n\"decimal 63 octal 77 hex 3f upper-case hex 3F\"\n\nuser=> (format \"%2$d %1$s\" \"Positional arguments\" 23)\n\"23 Positional arguments\"\n\n;; ====== Clojure format/printf and large integers =====\n\n;; This big number doesn't fit in a Long. It is a\n;; clojure.lang.BigInt, which format cannot handle directly.\nuser=> (format \"%5d\" 12345678901234567890)\nIllegalFormatConversionException d != clojure.lang.BigInt java.util.Formatter$FormatSpecifier.failConversion (Formatter.java:3999)\n\n;; You can convert it to a java.math.BigInteger, which format does handle.\nuser=> (format \"%5d\" (biginteger 12345678901234567890))\n\"12345678901234567890\"\n\n;; If you do this very often, you might want to use something like\n;; format-plus to avoid sprinkling your code with calls to biginteger.\n(defn coerce-unformattable-types [args]\n (map (fn [x]\n (cond (instance? clojure.lang.BigInt x) (biginteger x)\n (instance? clojure.lang.Ratio x) (double x)\n :else x))\n args))\n\n(defn format-plus [fmt & args]\n (apply format fmt (coerce-unformattable-types args)))\n\n;; Now this works:\nuser=> (format-plus \"%5d\" 12345678901234567890)\n\"12345678901234567890\"","created-at":1331440228000,"updated-at":1389568458000,"_id":"542692d3c026201cdc326fab"},{"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":";; ==== Clojure format/printf and floating-point formats ====\nuser=> (format \"%.3f\" 2.0)\n\"2.000\"\n\n;; format doesn't handle integers or ratios with %e, %f, %g, or %a\nuser=> (format \"%.3f\" 2)\nIllegalFormatConversionException f != java.lang.Long java.util.Formatter$FormatSpecifier.failConversion (Formatter.java:3999)\n\n;; In general, if you want to use floating-point formats %e, %f, %g,\n;; or %a with format or printf, and you don't know whether the values\n;; you want to format are floats or doubles, you should convert them:\nuser=> (format \"%.3f\" (double 2))\n\"2.000\"\n\nuser=> (format \"%.3f\" (double (/ 5 2)))\n\"2.500\"\n\n;; One could make a function that parses the format string to look for\n;; %f and other floating-point formats and automatically coerces the\n;; corresponding arguments to doubles, but such a function probably\n;; wouldn't fit into a short example. You could also consider using\n;; cl-format which does handle these kinds of things for you. The main\n;; disadvantage to doing so is that you have to learn a different syntax\n;; for format specifiers.","created-at":1331440712000,"updated-at":1332477536000,"_id":"542692d3c026201cdc326fb0"},{"editors":[{"login":"mars0i","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1836941?v=3"}],"body":";; format doesn't know what nil should look like:\nuser=> (format \"%s\" nil)\n\"null\"\n;; You can use cl-format in this situation:\nuser=> (clojure.pprint/cl-format nil \"~s\" nil)\n\"nil\"\n","author":{"avatar-url":"https://avatars.githubusercontent.com/u/1836941?v=3","account-source":"github","login":"mars0i"},"created-at":1437887089127,"updated-at":1437887151600,"_id":"55b46a71e4b06a85937088b4"},{"updated-at":1647195081731,"created-at":1647195081731,"author":{"login":"andreasguther","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/9425214?v=4"},"body":";; To use the percent sign % you need to escape it with %: %%\nuser=> (format \"%.2f %%\" 2.5)\n\"2.50 %\"","_id":"622e33c9e4b0b1e3652d75ba"},{"updated-at":1663142162249,"created-at":1663142162249,"author":{"login":"Kynde","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1169360?v=4"},"body":";; Do notice that it uses the host locale for formatting.\n;; E.g. With Finnish locale it uses comma for separator.\nuser=> (format \"%.2f\" 1.23)\n\"1,23\"\n\n;; You can use the java.lang.String/format to force it.\nuser=> (java.lang.String/format java.util.Locale/US \"%.2f\" (to-array [1.23]))\n\"1.23\"\n\n;; You can override the default, but this affects other things, too.\nuser=> (java.util.Locale/setDefault java.util.Locale/US)\nnil\n\nuser=> (format \"%.2f\" 1.23)\n\"1.23\"\n\n\n","_id":"63218912e4b0b1e3652d7662"}],"notes":[{"body":"Note that `(format)` is [not currently supported](http://dev.clojure.org/jira/browse/CLJS-324) in ClojureScript, only in Clojure.","created-at":1438119290177,"updated-at":1438119315501,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/94482?v=3","account-source":"github","login":"timgilbert"},"_id":"55b7f57ae4b0080a1b79cdb4"},{"author":{"login":"PEZ","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/30010?v=4"},"updated-at":1663758017937,"created-at":1663758017937,"body":"For ClojureScript there is https://github.com/quoll/clormat. As of this writing it is new and because of that maybe not always fully compliant. Afaiu the goal is to make it fully compliant.","_id":"632aeec1e4b0b1e3652d7664"},{"author":{"login":"grav","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/119222?v=4"},"updated-at":1691054508569,"created-at":1691054508569,"body":"There's also [Google Closure's format](https://google.github.io/closure-library/api/goog.string.format.html) for ClojureScript. [Example usage](https://tech.toryanderson.com/2020/10/22/zero-padding-and-truncating-with-string-formats-in-clojurescript/).","_id":"64cb71ace4b08cf8563f4bd8"}],"arglists":["fmt & args"],"doc":"Formats a string using java.lang.String.format, see java.util.Formatter for format\n string syntax","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/format"},{"added":"1.0","ns":"clojure.core","name":"reversible?","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":null,"line":6334,"examples":[{"author":{"login":"replore","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e7869fe1a48cb1814c657eaca6bea3eb?r=PG&default=identicon"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"}],"body":"user=> (reversible? [])\ntrue\nuser=> (reversible? (sorted-map))\ntrue\nuser=> (reversible? (sorted-set))\ntrue\nuser=> (reversible? '())\nfalse\nuser=> (reversible? {})\nfalse\nuser=> (reversible? #{})\nfalse","created-at":1321359686000,"updated-at":1423095216846,"_id":"542692d5c026201cdc327076"}],"notes":null,"arglists":["coll"],"doc":"Returns true if coll implements Reversible","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/reversible_q"},{"added":"1.0","ns":"clojure.core","name":"shutdown-agents","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1285923562000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"send","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521ae5"},{"created-at":1285923568000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"send-off","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521ae6"},{"created-at":1285923576000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"agent","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521ae7"},{"created-at":1285923589000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"agent-error","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521ae8"},{"created-at":1559240451680,"author":{"login":"pdbrown","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/1607096?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"set-agent-send-executor!","ns":"clojure.core"},"_id":"5cf01f03e4b0ca44402ef737"},{"created-at":1559240460246,"author":{"login":"pdbrown","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/1607096?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"set-agent-send-off-executor!","ns":"clojure.core"},"_id":"5cf01f0ce4b0ca44402ef738"}],"line":2271,"examples":[{"author":{"login":"taylor.sando","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/c127297f5548f7275ded1428aa5518bb?r=PG&default=identicon"},"editors":[],"body":";; Creating an agent\nuser> (def a (agent 1))\n#'user/a\n\n;; Create a function that can handle an agent\n\nuser> (defn agent-action [a]\n\t33)\n#'user/agent-action\n\n;; The agent will become 33\nuser> (send-off a agent-action)\n#\n\nuser> @a\n33\n;; Create another agent before shutdown\nuser> (def c (agent 3))\n#'user/c\n\n;; Shutdown agents is called\nuser> (shutdown-agents)\nnil\n\n;; Attempt to turn c into 33\nuser> (send c agent-action)\n#\n\n;; The result is that it is still the same value it was initialized with\nuser> @c\n3\n\n;; Agent created after shutdown\nuser> (def d (agent 4))\n#'user/d\n\n;; Try sending it\nuser> (send d agent-action)\n#\n\n;; Same thing, there are no threads to process the agents\nuser> @d\n4","created-at":1349607696000,"updated-at":1349607696000,"_id":"542692d5c026201cdc327084"},{"author":{"login":"taylor.sando","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/c127297f5548f7275ded1428aa5518bb?r=PG&default=identicon"},"editors":[],"body":";; Create the agent that we will be using\nuser=> (def a (agent 0))\n#'user/a\n\n;; Dereference the agent to show the value is 0\nuser=> @a\n0\n\n;; Create a function that can increment the agent\n;; This will continually update the value of the agent\nuser=> (defn agent-inc [a]\n (send-off *agent* agent-inc)\n (inc a))\n#'user/agent-inc\n\n;; Send the agent to the agent-inc function\n;; The value is 188 because by the time the repl has sent off the\n;; agent to the function, the function has already been called recursively\nuser=> (send a agent-inc)\n#\n\n;; Dereference of the value a second or so later\nuser=> @a\n716889\n\n;; Another dereference in another couple of seconds\nuser=> @a\n1455264\n\n;; Shutdown the threads for the agents\nuser=> (shutdown-agents)\nnil\n\n;; Dereference the agent to see what value it is\nuser=> @a\n3522353\n\n;; Dereference the agent again in a few seconds\n;; It's the same value, because the agent pool of threads are no longer\n;; active\nuser=> @a\n3522353\n","created-at":1349608162000,"updated-at":1349608162000,"_id":"542692d5c026201cdc327085"}],"notes":null,"arglists":[""],"doc":"Initiates a shutdown of the thread pools that back the agent\n system. Running actions will complete, but no new actions will be\n accepted","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/shutdown-agents"},{"added":"1.0","ns":"clojure.core","name":"conj","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1297212938000,"author":{"login":"TimMc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5d532e51427ef2f4ded31aaca16c8baf?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"cons","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d76"},{"created-at":1398537407000,"author":{"login":"ryo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3f7913b563c72083c74030d928ba407e?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"into","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d77"},{"created-at":1400493822000,"author":{"login":"ryo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3f7913b563c72083c74030d928ba407e?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"peek","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d78"},{"created-at":1400493828000,"author":{"login":"ryo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3f7913b563c72083c74030d928ba407e?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"pop","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d79"},{"created-at":1430745236745,"author":{"login":"jw-00000","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2936?v=3"},"to-var":{"ns":"clojure.core","name":"concat","library-url":"https://github.com/clojure/clojure"},"_id":"55477094e4b01bb732af0a91"},{"created-at":1528231331314,"author":{"login":"miner","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/25400?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"conj!","ns":"clojure.core"},"_id":"5b16f5a3e4b00ac801ed9e0c"},{"created-at":1544351725441,"author":{"login":"l3nz","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/1101849?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"assoc","ns":"clojure.core"},"_id":"5c0cefede4b0ca44402ef5e8"},{"created-at":1561679674033,"author":{"login":"huahaiy","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/889685?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"disj","ns":"clojure.core"},"_id":"5d15573ae4b0ca44402ef778"}],"line":75,"examples":[{"author":{"login":"MrHus","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/22608?v=4"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"Steve","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/454ce0be068cbbf25ee685af20dc7cd6?r=PG&default=identicon"},{"login":"TimMc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5d532e51427ef2f4ded31aaca16c8baf?r=PG&default=identicon"},{"login":"Wilfred","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1f86c0bc40235a9edf351a16b859aabd?r=PG&default=identicon"},{"login":"ElieLabeca","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/724e1112a2be4d5af767c0cf152d087e?r=PG&default=identicon"},{"login":"ElieLabeca","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/724e1112a2be4d5af767c0cf152d087e?r=PG&default=identicon"},{"login":"s_prakash_joy","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/7704115a8be45640094d5d9fc6f4e22a?r=PG&default=identicon"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"},{"login":"alidcastano","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/11031952?v=4"}],"body":";; notice that conjoining to a vector is done at the end\n(conj [1 2 3] 4)\n;;=> [1 2 3 4]\n\n;; notice conjoining to a list is done at the beginning\n(conj '(1 2 3) 4)\n;;=> (4 1 2 3)\n\n(conj [\"a\" \"b\" \"c\"] \"d\")\n;;=> [\"a\" \"b\" \"c\" \"d\"]\n\n;; conjoining multiple items is done in order\n(conj [1 2] 3 4) \n;;=> [1 2 3 4]\n\n(conj '(1 2) 3 4) \n;;=> (4 3 1 2)\n\n(conj [[1 2] [3 4]] [5 6]) \n;;=> [[1 2] [3 4] [5 6]]\n\n;; conjoining to maps only take items as vectors of length exactly 2\n(conj {1 2, 3 4} [5 6])\n;;=> {5 6, 1 2, 3 4}\n\n(conj {:firstname \"John\" :lastname \"Doe\"} {:age 25 :nationality \"Chinese\"})\n;;=> {:firstname \"John\", :lastname \"Doe\", :age 25, :nationality \"Chinese\"}\n\n;; conj on a set\n(conj #{1 3 4} 2)\n;;=> #{1 2 3 4}\n\n","created-at":1279417029000,"updated-at":1582210748471,"_id":"542692c9c026201cdc326abc"},{"author":{"login":"john.r.woodward","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/22b6fbc4a386291e45b1cb4449377086?r=PG&default=identicon"},"editors":[{"login":"john.r.woodward","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/22b6fbc4a386291e45b1cb4449377086?r=PG&default=identicon"},{"login":"Thumbnail","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/db68e51797a2382e185b42ce6534b7a4?r=PG&default=identicon"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":";; conjoin shows similar behaviour to cons\n;; The main difference being that conj works on collections\n;; but cons works with seqs. \n(conj [\"a\" \"b\" \"c\"] [\"a\" \"b\" \"c\"] )\n;;=> [\"a\" \"b\" \"c\" [\"a\" \"b\" \"c\"]]","created-at":1342724544000,"updated-at":1420652159670,"_id":"542692d2c026201cdc326f6d"},{"author":{"login":"jamesqiu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bc1268deaa7f2e78fe2b5ea76e6481d8?r=PG&default=identicon"},"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":";; conjoin nil with x or xs\n(conj nil 3)\n;;=> (3)\n\n(conj nil 3 4)\n;;=> (4 3)","created-at":1349714643000,"updated-at":1420652257330,"_id":"542692d2c026201cdc326f70"},{"author":{"login":"Alan Thompson","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5b677647e3c6fb2bc89fa2f481461b11?r=PG&default=identicon"},"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":";; maps and sets are treated differently\n(conj {1 2} {3 4})\n;;=> {3 4, 1 2} ; the contents of {3 4} are added to {1 2}\n\n(conj #{1 2} #{3})\n;;=> #{1 2 #{3}} ; the whole set #{3} is added to #{1 2}\n\n(clojure.set/union #{1 2} #{3})\n;;=> #{1 2 3} ; must use (clojure.set/union) to merge sets, not conj\n","created-at":1392346414000,"updated-at":1420652309845,"_id":"542692d2c026201cdc326f71"},{"body":";; When conjoining into a map, vector pairs may be provided:\n(conj {:a 1} [:b 2] [:c 3])\n;;=> {:c 3, :b 2, :a 1}\n\n;; Or maps may be provided, with multiple pairings:\n(conj {:a 1} {:b 2 :c 3} {:d 4 :e 5 :f 6})\n;;=> {:f 6, :d 4, :e 5, :b 2, :c 3, :a 1}\n\n;; But multiple pairings cannot appear in vectors:\n(conj {:a 1} [:b 2 :c 3])\n;;=> IllegalArgumentException Vector arg to map conj must be a pair...\n\n;; And pairs may not be provided in lists:\n(conj {:a 1} '(:b 2))\n;;=> ClassCastException ...Keyword cannot be cast to ...Map$Entry...\n","author":{"login":"fordsfords","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7671908?v=3"},"created-at":1417527012413,"updated-at":1417527012413,"_id":"547dbee4e4b03d20a10242bb"},{"updated-at":1453750686379,"created-at":1453750686379,"author":{"login":"bsima","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/200617?v=3"},"body":";; Useful snippet: \"merge\" two or more vectors with `(comp vec flatten conj)`\n(let [a [{:a \"hi\"} {:b \"hey\"}]\n b [{:c \"yo\"} {:d \"hiya\"}]\n c [{:e \"bonjour\"}]]\n ((comp vec flatten conj) a b c))\n;;=> [{:a \"hi\"} {:b \"hey\"} {:c \"yo\"} {:d \"hiya\"} {:e \"bonjour\"}]","_id":"56a6799ee4b060004fc217b0"},{"updated-at":1456128447651,"created-at":1456128447651,"author":{"login":"yinwuzhe","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/5061317?v=3"},"body":"(conj nil 1)\n;=>(1)\n(conj nil [1 2])\n;=>([1 2])\n","_id":"56cac1bfe4b060004fc217cb"},{"editors":[{"login":"edcaceres","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/782909?v=3"},{"avatar-url":"https://avatars.githubusercontent.com/u/1191123?v=3","account-source":"github","login":"TheCodingGent"}],"body":";; Conj new-element into nested structures \"conj-in\"\n\n(def db {:users [{:name \"Eduardo\"}]})\n(def new-element {:name \"Eva\"})\n\n(assoc db :users (conj (:users db) new-element))\n;; => {:users [{:name \"Eduardo\"} {:name \"Eva\"}]}","author":{"avatar-url":"https://avatars.githubusercontent.com/u/782909?v=3","account-source":"github","login":"edcaceres"},"created-at":1479821999279,"updated-at":1483975466743,"_id":"58344aafe4b0782b632278c2"},{"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"}],"body":";; implement stack semantics with conj, peek and pop.\n\n;; we start with a list\n(def stack '(2 1 0))\n\n(peek stack)\n;; => 2\n(pop stack)\n;; => (1 0)\n(type (pop stack))\n;; => cljs.core/List\n;; push = conj\n(conj stack 3)\n;; => (3 2 1 0)\n(type (conj stack 3))\n;; => cljs.core/List\n\n;; now let us try a vector\n(def stack [0 1 2])\n\n(peek stack)\n;; => 2\n(pop stack)\n;; => [0 1]\n(type (pop stack))\n;; => clojure.lang.PersistentVector\n;; push = conj\n(conj stack 3)\n;; => [0 1 2 3]\n(type (conj stack 3))\n;; => clojure.lang.PersistentVector\n","author":{"avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4","account-source":"github","login":"phreed"},"created-at":1510596733632,"updated-at":1510597245457,"_id":"5a09e07de4b0a08026c48cb7"},{"editors":[{"login":"asifm","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/3958387?v=4"}],"body":";; Based on examples from the great book CLOJURE for the BRAVE and TRUE\n;; https://www.braveclojure.com/core-functions-in-depth/\n\n(defn add-first-vec\n\t[target addition]\n\t(apply conj (if (vector? addition) addition [addition]) target))\n\n(add-first-vec [3 4 5 6] 1)\n;; [1 3 4 5 6]\n\n(add-first-vec [3 4 5 6] [1 2])\n;; [1 2 3 4 5 6]","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/1321842?v=4","account-source":"github","login":"berczeck"},"created-at":1598229602892,"updated-at":1665916664510,"_id":"5f430c62e4b0b1e3652d73aa"},{"editors":[{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"}],"body":";; conj also has other arities:\n\n(conj)\n;; => []\n\n(conj [1 2 3])\n;; => [1 2 3]\n\n;; Which are particularly useful when transducing, as the nullary form can be\n;; used to produce init, and the unary form for completion","author":{"avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4","account-source":"github","login":"tomdl89"},"created-at":1678381486402,"updated-at":1699795052780,"_id":"640a11aee4b08cf8563f4b7b"}],"notes":[{"author":{"login":"me7","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10399270?v=3"},"updated-at":1456199923502,"created-at":1456199923502,"body":"list prepend\nvector append","_id":"56cbd8f3e4b02a6769b5a4b1"}],"arglists":["","coll","coll x","coll x & xs"],"doc":"conj[oin]. Returns a new collection with the xs\n 'added'. (conj nil item) returns (item).\n (conj coll) returns coll. (conj) returns [].\n The 'addition' may happen at different 'places' depending\n on the concrete type.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/conj"},{"added":"1.2","ns":"clojure.core","name":"bound?","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1328397785000,"author":{"login":"steveminer","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d28543d134185d12d4006a74738d233e?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"thread-bound?","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521af8"}],"line":5565,"examples":[{"author":{"login":"dpritchett","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/147981?v=3"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"steveminer","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d28543d134185d12d4006a74738d233e?r=PG&default=identicon"}],"body":"user=> (def foobar)\n#'user/foobar\nuser=> (bound? #'foobar)\nfalse\nuser=> (def boing 10)\n#'user/boing\nuser=> (bound? #'boing)\ntrue\nuser=> (defn plus3 [n] (+ 3 n))\n#'user/plus3\nuser=> (bound? #'plus3)\ntrue\n","created-at":1279073551000,"updated-at":1318467872000,"_id":"542692cdc026201cdc326ce1"}],"notes":null,"arglists":["& vars"],"doc":"Returns true if all of the vars provided as arguments have any bound value, root or thread-local.\n Implies that deref'ing the provided vars will succeed. Returns true if no vars are provided.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/bound_q"},{"added":"1.7","ns":"clojure.core","name":"transduce","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1459164080889,"author":{"login":"optevo","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1281179?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"completing","ns":"clojure.core"},"_id":"56f913b0e4b09295d75dbf41"}],"line":7012,"examples":[{"editors":[{"login":"bsvingen","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1647562?v=3"}],"body":";; First, define a transducer for producing the first ten odd numbers:\n(def xf (comp (filter odd?) (take 10)))\n\n;; We can then apply this transducer in different ways using transduce.\n\n;; Get the numbers as a sequence:\n\n(transduce xf conj (range))\n;;=> [1 3 5 7 9 11 13 15 17 19]\n\n;; Or sum them:\n\n(transduce xf + (range))\n;; => 100\n\n;; ... with an initializer:\n\n(transduce xf + 17 (range))\n;; => 117\n\n;; Or concatenate them to a string:\n\n(transduce xf str (range))\n;; => \"135791113151719\"\n\n;; .. with an initializer:\n\n(transduce xf str \"...\" (range))\n;; => \"...135791113151719\"\n","author":{"avatar-url":"https://avatars.githubusercontent.com/u/1647562?v=3","account-source":"github","login":"bsvingen"},"created-at":1435874975857,"updated-at":1435878735757,"_id":"5595b69fe4b00f9508fd66f1"},{"updated-at":1473877511741,"created-at":1473871425560,"author":{"login":"upgradingdave","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/939229?v=3"},"body":";; When studying Korean, I had notes with mixture of Korean and\n;; English and I wanted to filter out any English. \n\n(def example (str \"I will write an autobiography(자서전) later\\n\"\n \"(저는) 나중에 자서전을 쓸 거에요\"))\n\n;; Here's a transducer to filter out english characters\n\n(defn filter-out-english \n \"filter out english characters in a string\"\n []\n (filter (fn [c] \n (let [i (int c)] \n (not (or (and (>= i 65) (<= i 90)) \n (and (>= i 97) (<= i 122))))))))\n\n;; Here's a transducer to help deal with extra spaces and newlines.\n;; Notice the mapcat ensures that the output will always be the same\n;; shape as the input\n\n(defn trim-chars [c n]\n \"Ensure exactly n characters c in a row. For example, squash\n multiple spaces into single space or expand newlines into 2\n newlines\"\n (comp (partition-by #{c})\n (mapcat #(if (= c (first %)) (repeat n c) %))))\n\n\n;; put it all together, we filter out english characters, replace\n;; multiple spaces with single space, and ensure each line is double\n;; spaced (two line breaks between each line)\n(def xf (comp (filter-out-english) \n (trim-chars \\space 1)\n (trim-chars \\newline 2)))\n\n(apply str (transduce xf conj example))\n;; => \" (자서전) \\n\\n(저는) 나중에 자서전을 쓸 거에요\"\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/939229?v=3","account-source":"github","login":"upgradingdave"}],"_id":"57d97e41e4b0709b524f04f7"},{"updated-at":1483049703082,"created-at":1483049703082,"author":{"login":"jvanderhyde","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/6516608?v=3"},"body":";; transduce with the identity transform is equivalent to reduce,\n;; in the following way:\n(transduce identity f sample)\n(f (reduce f (f) sample))\n\n;; For example, we can define a reducing function and then use it:\n(defn conj-second\n ([]\n [])\n ([result]\n result)\n ([result [x y]]\n (conj result y)))\n\n(def sample [[1 :a] [2 :b] [3 :c]])\n\n(transduce identity conj-second sample)\n;;=>[:a :b :c]\n(conj-second (reduce conj-second (conj-second) sample))\n;;=>[:a :b :c]\n\n;; Let's prove the point with printing:\n(defn conj-second\n ([]\n (println \"0\") [])\n ([result]\n (println \"1\") result)\n ([result [x y]]\n (println \"2\") (conj result y)))\n\n;; Then the following both print 0 2 2 2 1\n(transduce identity conj-second sample)\n(conj-second (reduce conj-second (conj-second) sample))\n","_id":"58658ae7e4b0fd5fb1cc964d"},{"editors":[{"login":"vspinu","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/1363467?v=3"}],"body":";;; BUILD A STATEFULL TRANSDUCER\n\n;; Make a transducer that accumulates a sequence when pred is truthy and\n;; returns individual values when pred is falsy.\n;;\n;; For example when pred is odd?, partition\n;;\n;; [1 1 1 2 2 3 3 3]\n;; \n;; into\n;; \n;; [[1 1 1] [2] [2] [3 3 3]]\n;;\n\n(defn accumulate-when [pred]\n ;; A transducer takes a reducer function and returns a reducer function.\n (fn [rf]\n ;; State (an accumulator) which is closed over by the reducer function.\n (let [acc (java.util.ArrayList.)]\n (fn\n ;; Arity 0 (state initializer). In this step we can initialize `acc`\n ;; based on the returned valued of (rf), but here, as it is usually the\n ;; case, this is not needed.\n ([] (rf))\n \n ;; Arity 1 (completer). Called after the reducing process has ended (if\n ;; ever). In this step local state must be cleaned and residual reducing\n ;; step may be performed. `result` is an unreduced value (see reduced\n ;; and unreduced).\n ([result]\n (let [result (if (.isEmpty acc)\n ;; No residual state. Simply return the result.\n result\n ;; Need to clear the residual state and perform one last\n ;; reducing step on the so far accumulated values.\n (let [v (vec (.toArray acc))]\n (.clear acc)\n ;; This step might return a completed value (i.g. on\n ;; which reduced? gives true). We need to deref it\n ;; with `unreduced` in order to supply it to rf.\n (unreduced (rf result v))))]\n ;; Nested rf call. Must happen once!\n (rf result)))\n \n ;; Arity 2 (reducer). This is where the main work happens.\n ([result input]\n (if (pred input)\n ;; When pred is truthy, accumulate and don't call the nested reducer.\n (do\n (.add acc input)\n result)\n ;; When pred is falsy, call nested reducer (possibly twice).\n (if (.isEmpty acc)\n ;; When accumulator is empty, reduce with a singleton.\n (rf result [input])\n (let [v (vec (.toArray acc))]\n (.clear acc)\n ;; First reduce on the accumulated sequence.\n (let [ret (rf result v)]\n (if (reduced? ret)\n ;; If sequence is completed, no more reductions\n ret\n ;; else, reduce once more with the current (falsy) input.\n (rf ret [input])))))))))))\n\n(def x [1 1 1 2 2 3 3 3])\n\n;; Step through with the debugger in order to gain a better understanding of the\n;; involved steps.\n\n(transduce (accumulate-when odd?) conj x)\n;; user> [[1 1 1] [2] [2] [3 3 3]]\n\n(transduce (comp (take 4) (accumulate-when odd?)) conj x)\n;; user> [[1 1 1] [2]]\n\n(transduce (comp (accumulate-when odd?) (take 3)) conj x)\n;; user> [[1 1 1] [2] [2]]\n\n(transduce (comp (accumulate-when odd?) (take 4)) conj x)\n;; user> [[1 1 1] [2] [2] [3 3 3]]\n\n;; Clojure core statefull transducers are partition-by, partition-all, take,\n;; drop, drop-while, take-nth, distinct, interpose, map-indexed and\n;; keep-indexed.\n","author":{"avatar-url":"https://avatars0.githubusercontent.com/u/1363467?v=3","account-source":"github","login":"vspinu"},"created-at":1498561912432,"updated-at":1498561969340,"_id":"59523d78e4b06e730307db43"},{"updated-at":1586130966542,"created-at":1586130966542,"author":{"login":"didibus","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/601540?v=4"},"body":"(transduce\n (partition-by identity)\n (fn\n ;; init - returns initial value for accumulator, called when no init is given to transduce\n ([] [])\n ;; completion - returns the final result, take the final accumulated value, called once there are no more elements to process\n ([acc] acc)\n ;; step - do whatever you want on each element, returns accumulated state and takes accumulated state from before and new element\n ([acc e] (conj acc e)))\n '()\n [1 1 1 2 2 3 3 4 4 5 6 7 7])\n\n;; => ([7 7] [6] [5] [4 4] [3 3] [2 2] [1 1 1])","_id":"5e8a7016e4b087629b5a18cb"},{"editors":[{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"}],"body":";; These two forms are equivalent:\n\n(reduce ((map inc) conj) [] '(1 2 3 4 5))\n;; => [2 3 4 5 6]\n\n(transduce (map inc) conj [] '(1 2 3 4 5))\n;; => [2 3 4 5 6]\n\n;; Which shows how transduce works: it applies the transducer to the reducing\n;; function, and reduces the collection with that\n\n;; But n.b. this example masks the fact that transduce does call f an extra\n;; time for \"completion\", because arity-1 conj = identity.","author":{"avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4","account-source":"github","login":"tomdl89"},"created-at":1678020807238,"updated-at":1678381890546,"_id":"640490c7e4b08cf8563f4b78"},{"editors":[{"login":"cstml","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/29694576?v=4"}],"body":"\n;; transduce and reduce are not equivalent in their reduction strategy and have\n;; slightly different behaviours that you should be aware of. For example, the\n;; next function is a tranduce where we have a no-op xf.\n(transduce identity\n (fn\n ([] (println :no-args))\n ([ret] (println [:one-arg ret]) ret)\n ([next ret] (println [:two-args ret next]) ret))\n (range 10))\n;; this will print:\n\n;; :no-args <- observe that the f is called first with no arguments\n;; [:two-args 0 nil] <- then it is called with the return from the no argument function\n;; [:two-args 1 0]\n;; [:two-args 2 1]\n;; [:two-args 3 2]\n;; [:two-args 4 3]\n;; [:two-args 5 4]\n;; [:two-args 6 5]\n;; [:two-args 7 6]\n;; [:two-args 8 7]\n;; [:two-args 9 8]\n;; [:one-arg 9] <- lastly it is called with the return of the last call, in the 1 arrity\n\n;; the \"equivalent\" reduce function\n(reduce\n (fn\n ([] (println :no-args))\n ([ret] (println [:one-arg ret]) ret)\n ([next ret] (println [:two-args ret next]) ret))\n (range 10))\n;; this will print:\n\n;; [:two-args 1 0]\n;; [:two-args 2 1]\n;; [:two-args 3 2]\n;; [:two-args 4 3]\n;; [:two-args 5 4]\n;; [:two-args 6 5]\n;; [:two-args 7 6]\n;; [:two-args 8 7]\n;; [:two-args 9 8]\n\n;; only the 2 arrity function version is called in this case\n","author":{"avatar-url":"https://avatars.githubusercontent.com/u/29694576?v=4","account-source":"github","login":"cstml"},"created-at":1757103001400,"updated-at":1757103353527,"_id":"68bb4399cd84df5de54e208f"}],"notes":[{"author":{"login":"jvanderhyde","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/6516608?v=3"},"updated-at":1483050000710,"created-at":1483050000710,"body":"Usually you use existing functions to create the transformation, using map, filter, paritition-all, etc. But you can also define your own transformations. A transformation (or transducer) is a function that takes a reducing function and returns a reducing function. See the source for [take](https://github.com/clojure/clojure/blob/clojure-1.8.0/src/clj/clojure/core.clj#L2752) and [filter](https://github.com/clojure/clojure/blob/clojure-1.8.0/src/clj/clojure/core.clj#L2684) for examples.","_id":"58658c10e4b0fd5fb1cc964e"}],"arglists":["xform f coll","xform f init coll"],"doc":"reduce with a transformation of f (xf). If init is not\n supplied, (f) will be called to produce it. f should be a reducing\n step function that accepts both 1 and 2 arguments, if it accepts\n only 2 you can add the arity-1 with 'completing'. Returns the result\n of applying (the transformed) xf to init and the first item in coll,\n then applying xf to that result and the 2nd item, etc. If coll\n contains no items, returns init and f is not called. Note that\n certain transforms may inject or skip items.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/transduce"},{"added":"1.0","ns":"clojure.core","name":"lazy-seq","file":"clojure/core.clj","type":"macro","column":1,"see-alsos":[{"created-at":1318395998000,"author":{"login":"haplo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/890d46f8c0e24dd6fb8546095b1144e?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"lazy-cat","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ed7"},{"created-at":1322679999000,"author":{"login":"mmwaikar","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/29d36f4c9f39c9f8ff61c07033b13118?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"realized?","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ed8"},{"created-at":1322680082000,"author":{"login":"mmwaikar","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/29d36f4c9f39c9f8ff61c07033b13118?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"doall","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ed9"},{"created-at":1370143899000,"author":{"login":"Mark Addleman","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/768de71b6c873394290733acf422b4d5?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"iterate","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521eda"}],"line":685,"examples":[{"updated-at":1448773249031,"created-at":1281346189000,"body":";; The following defines a lazy-seq of all positive numbers. Note that \n;; the lazy-seq allows us to make a recursive call in a safe way because\n;; the call does not happen immediately but instead creates a closure.\n\nuser=> (defn positive-numbers \n\t([] (positive-numbers 1))\n\t([n] (lazy-seq (cons n (positive-numbers (inc n))))))\n#'user/positive-numbers\n\nuser=> (take 5 (positive-numbers))\n(1 2 3 4 5)\n\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"avatar-url":"https://www.gravatar.com/avatar/299a3fab7a1a2d6644455dedae9fce0a?r=PG&default=identicon","account-source":"clojuredocs","login":"Stathis Sideris"},{"login":"hgijeon","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7885562?v=3"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon","account-source":"clojuredocs","login":"gstamp"},"_id":"542692cec026201cdc326ddd"},{"author":{"login":"jakubholynet","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/32b26dbbf1f84656393a57a292c73728?r=PG&default=identicon"},"editors":[{"login":"jakubholynet","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/32b26dbbf1f84656393a57a292c73728?r=PG&default=identicon"},{"login":"jakubholynet","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/32b26dbbf1f84656393a57a292c73728?r=PG&default=identicon"},{"login":"redraiment","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/33087654dbc710e81f51fda5f8241f28?r=PG&default=identicon"},{"login":"Stathis Sideris","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/299a3fab7a1a2d6644455dedae9fce0a?r=PG&default=identicon"},{"avatar-url":"https://avatars.githubusercontent.com/u/7885562?v=3","account-source":"github","login":"hgijeon"},{"login":"olfal1","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7503672?v=3"},{"avatar-url":"https://avatars.githubusercontent.com/u/15624487?v=4","account-source":"github","login":"pluieciel"}],"body":";; A lazy-seq of Fibonacci numbers (fn = fn-1 + fn-2)\n;; The producer function takes exactly two parameters\n;; (because we need the last 2 elements to produce a new one)\nuser=> (defn fib \n ([]\n (fib 1 1))\n ([a b]\n (lazy-seq (cons a (fib b (+ a b))))))\n\nuser=> (take 5 (fib))\n(1 1 2 3 5)\n\n;; Another realization\n;; 1 2 3 5 8 ... Fibonacci numbers start from the 2nd position\n;; + 1 1 2 3 5 ... Fibonacci numbers start from the 1st position\n;; = 2 3 5 8 13 ... Fibonacci numbers start from the 3rd position\nuser=> (def fib\n (cons 1\n (lazy-seq (cons 1 (map + (rest fib) fib)))))\n\nuser=> (take 5 fib)\n(1 1 2 3 5)","created-at":1322121310000,"updated-at":1661333181759,"_id":"542692d3c026201cdc326feb"},{"author":{"login":"jakubholynet","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/32b26dbbf1f84656393a57a292c73728?r=PG&default=identicon"},"editors":[],"body":";; It might be easier to think about the producer function as a function\n;; that, given element n, produces element n+1 via a recursive call to \n;; itself, wrapped with lazy-seq to delay its execution\n;; We might also provide no-argument version of the function that calls \n;; itself for the first element(s) of the sequence being generated.\n;; => variant of fibonaci with a no-arg version and using cons first:\n(defn sum-last-2 \n ([] (sum-last-2 1 2)) \n ([n m] (cons n (lazy-seq (sum-last-2 m (+ n m))))))\n\nuser=> (take 6 (sum-last-2))\n(1 2 3 5 8 13)","created-at":1330300424000,"updated-at":1330300424000,"_id":"542692d3c026201cdc326ff0"},{"updated-at":1436122605747,"created-at":1354916731000,"body":";; An example combining lazy sequences with higher order functions\n;; Generate prime numbers using trial division.\n;; Note that the starting set of sieved numbers should be\n;; the set of integers starting with 2 i.e., (iterate inc 2) \n(defn sieve [s]\n (cons (first s)\n (lazy-seq (sieve (filter #(not= 0 (mod % (first s)))\n (rest s))))))\n\nuser=> (take 20 (sieve (iterate inc 2)))\n(2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71)\n\n\nSadly (nth (sieve (iterate inc 2)) 10000) results in StackOverflowError ;(","editors":[{"avatar-url":"https://www.gravatar.com/avatar/b60d7f482b9f88cb3a673f370ea15c9c?r=PG&default=identicon","account-source":"clojuredocs","login":"emdeesee"},{"login":"lambder","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/95941?v=3"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/d3df4ff6342ed6fba898021bf2d19a6d?r=PG&default=identicon","account-source":"clojuredocs","login":"esumitra"},"_id":"542692d3c026201cdc326ff1"},{"body":";; Other examples on this page are little too eager to produce the head of collection\n;; right away. lazy-seq was introduced to make it possible to postpone any computation\n;; until data is needed.\n;; While it is not relevant for these simple examples, it could be important\n;; for real apps where producing each element is expensive.\n\n;; Here is a demonstration.\n;; Let's define a function that prints mysqr when it's called\n(defn mysqr [n]\n (println \"mysqr\")\n (* n n))\n;; => #'user/mysqr\n\n;; Now function squares that is adopted from positive-numbers example above\n;; Note that lazy-seq is inside of cons\n(defn squares\n ([n] (cons (mysqr n) (lazy-seq (squares (inc n))))))\n;; => #'user/squares\n\n(def sqrs (squares 1))\n;; => mysqr <-- NOTE THAT mysqr WAS CALLED WHEN WE SIMPLY REQUESTED COLLECTION\n;; => #'user/sqrs\n\n(take 1 sqrs)\n;; => (1) <-- HERE WE ARE GETTING FIRST ELEMENT THAT WAS CALCULATED BEFORE\n\n;; Now let's redefine 'squares' by wrapping its entire body in lazy-seq:\n(defn squares\n ([n] (lazy-seq (cons (mysqr n) (squares (inc n))))))\n;; => #'user/squares\n\n;; And when we request the collection:\n(def sqrs (squares 1))\n;; => #'user/sqrs\n;; NOTE THAT mysqr WAS NOT CALLED HERE\n\n(take 1 sqrs)\n;; => mysqr <- AND HERE mysqr IS CALLED WHEN FIRST ELEMENT IS ACTUALLY REQUESTED\n;; => (1)","author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"created-at":1423004375232,"updated-at":1423010785906,"editors":[{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"}],"_id":"54d152d7e4b0e2ac61831cfc"},{"updated-at":1542427316403,"created-at":1449368696760,"author":{"login":"esumitra","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/98965?v=3"},"body":";; Compare recursive functions and lazy sequences\n;; generate (some) valid parenthesis combinations.\n;; (Side note: Everything this generates are valid combinations, but this\n;; doesn't generate all possible valid combinations.) \n;; valid paren combinations for 1 paren - ()\n;; valid paren combinations for 2 paren - ()(),(())\n;; valid paren combinations for 3 paren - ()()(),()(()),(())(),(()()),((()))\n\n;; given ith item, generate (i+1)th item\n(defn next-parens\n [xs]\n (set (mapcat (juxt\n #(str \"()\" %)\n #(str % \"()\")\n #(str \"(\" % \")\"))\n xs)))\n\n;; recursive function to get n paren combinations\n;; combinations are recursively calculated on the stack\n(defn parens-nth-item\n [n]\n (if (= 0 n)\n #{\"\"}\n (next-parens (parens-nth-item (dec n)))))\nuser=> (parens-nth-item 3)\n#{\"(()())\" \"((()))\" \"()()()\" \"()(())\" \"(())()\"}\n\n;; lazy function to get sequence of paren combinations\n;; combinations are lazily calculated on the heap\n(defn parens-sequence\n [xs]\n (lazy-seq (cons xs (parens-sequence (next-parens xs)))))\n\nuser=> (take 3 (parens-sequence #{\"\"}))\n(#{\"()\"} #{\"(())\" \"()()\"} #{\"(()())\" \"((()))\" \"()()()\" \"()(())\" \"(())()\"})","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/98965?v=3","account-source":"github","login":"esumitra"},{"login":"peter-kehl","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/4270240?v=4"}],"_id":"56639c78e4b0f47c7ec61144"},{"updated-at":1464067214072,"created-at":1464067214072,"author":{"login":"cloojure","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7083783?v=3"},"body":"; Create a finite-length lazy seq\n(defn finite-lazy-builder [values]\n (lazy-seq\n ; We need the when-let so the lazy-seq will terminate\n (when-let [ss (seq values)]\n (cons (first values)\n (finite-lazy-builder (next values))))))\n\n(println (finite-lazy-builder [1 2 3 4 5] ))\n;=> (1 2 3 4 5)\n\n","_id":"5743e48ee4b0a1a06bdee49a"},{"updated-at":1661336397540,"created-at":1518199374837,"author":{"login":"ibercode","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/31028993?v=4"},"body":";;generate a seq by multiplying the first n numbers starting from 1\n;;1*1\n;;1*2\n;;2*3\n;;6*4 .....\n\n(defn multiplen\n ([]\n (multiplen 1 1))\n ([total x]\n (let [new-total (* total x)]\n (lazy-seq\n (cons new-total (multiplen new-total (inc x)))))))\n\n;;take the first 5 elements \n(take 5 (multiplen))\n;;(1 2 6 24 120)\n\n;;Another realization of factorials\n(def factorials\n (lazy-seq\n (cons 1 (map * (iterate inc 2) factorials))))\n\n(take 5 factorials)\n;;(1 2 6 24 120)","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/15624487?v=4","account-source":"github","login":"pluieciel"}],"_id":"5a7de24ee4b0316c0f44f8b2"},{"updated-at":1684792382708,"created-at":1684792382708,"author":{"login":"bdevel","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/65951?v=4"},"body":";; From the \"Making Clojure Lazier\" docs,\n;; here's an example using a step function.\n\n(defn filter\n \"Returns a lazy sequence of the items in coll for which\n (pred item) returns true. pred must be free of side-effects.\"\n [pred coll]\n (let [step (fn [p c]\n (when-let [s (seq c)]\n (if (p (first s))\n (cons (first s) (filter p (rest s)))\n (recur p (rest s)))))]\n (lazy-seq (step pred coll))))\n","_id":"646be43ee4b08cf8563f4bbd"}],"macro":true,"notes":[{"body":"I think every form of (cons a (lazy-seq (f b))) in examples should be changed to (lazy-seq (cons a (f b))) to be fully lazy.
\n\nThink about
\n(def one-over ((fn helper [n] (cons (/ 1 n) (lazy-seq (helper (inc n))))) 0))
\nand
\n(def one-over ((fn helper [n] (lazy-seq (cons (/ 1 n) (helper (inc n))))) 0))
\n\nFirst one throws an exception right after hitting enter key, while second code postpones the calculation(and that's the point of lazyness!).
\nTherefore, cons should be inside of lazy-seq.\n","created-at":1448772755640,"updated-at":1448772839454,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/7885562?v=3","account-source":"github","login":"hgijeon"},"_id":"565a8493e4b0be225c0c47a1"}],"arglists":["& body"],"doc":"Takes a body of expressions that returns an ISeq or nil, and yields\n a Seqable object that will invoke the body only the first time seq\n is called, and will cache the result and return it on all subsequent\n seq calls. See also - realized?","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/lazy-seq"},{"added":"1.0","ns":"clojure.core","name":"*print-length*","file":"clojure/core_print.clj","type":"var","column":1,"see-alsos":[{"created-at":1767373745216,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"*print-level*","ns":"clojure.core"},"_id":"6957fbb1b7956e24e4cb4ecb"}],"dynamic":true,"line":16,"examples":[{"author":{"login":"nipra","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/142529?v=3"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"Crowbrammer","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/19522656?v=4"}],"body":";; Oops! Don't do this!!!\nuser=> (iterate inc 0)\n;; Frantically doing C-c C-c :-P\n; Evaluation aborted.\n\nuser=> (set! *print-length* 10)\n10\n\n;; Now it's perfectly fine. Yay!\nuser=> (iterate inc 0)\n(0 1 2 3 4 5 6 7 8 9 ...)\n\n","created-at":1279053974000,"updated-at":1610535308126,"_id":"542692cac026201cdc326b12"}],"notes":[{"body":"```(set! *print-length* nil)``` to revert as it also affects pr-sr which breaks the edn output","created-at":1641496128326,"updated-at":1641496156661,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/132936?v=4","account-source":"github","login":"gzmask"},"_id":"61d73e40e4b0b1e3652d759c"}],"arglists":[],"doc":"*print-length* controls how many items of each collection the\n printer will print. If it is bound to logical false, there is no\n limit. Otherwise, it must be bound to an integer indicating the maximum\n number of items of each collection to print. If a collection contains\n more items, the printer will print items up to the limit followed by\n '...' to represent the remaining items. The root binding is nil\n indicating no limit.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/*print-length*"},{"added":"1.0","ns":"clojure.core","name":"*file*","type":"var","see-alsos":null,"examples":[{"updated-at":1615735028888,"created-at":1615735028888,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/20086?v=4"},"body":";; Given a file named \"example.clj\" is available in the current folder\n;; with content:\n\n(ns example)\n(when *compile-files* (println \"Compiling:\" *file*))\n\n;; If we start a REPL adding \".\" as part of the classpath,\n;; then we can see the following:\n\n(binding [*compile-path* \".\"]\n (compile 'example))\n;; Compiling: example.clj\n;; example\n","_id":"604e28f4e4b0b1e3652d7490"}],"notes":[{"updated-at":1324600617000,"body":"Does this actually work? I couldn't get it to print anything but NO_SOURCE_PATH. (And no, this wasn't in the REPL.)","created-at":1324600599000,"author":{"login":"TimMc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5d532e51427ef2f4ded31aaca16c8baf?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fd3"},{"updated-at":1349216667000,"body":"If you're having trouble getting this feature to work as advertised, check out [this StackOverflow Question](http://stackoverflow.com/questions/12692698/file-variable-not-working/12693068).","created-at":1349216667000,"author":{"login":"Jeff Terrell","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/658b2643cf2a8192286b5bb1ecb62cf8?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fe8"}],"arglists":[],"doc":"The path of the file being evaluated, as a String.\n\n When there is no file, e.g. in the REPL, the value is not defined.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/*file*"},{"added":"1.0","ns":"clojure.core","name":"compare-and-set!","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1350642558000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"atom","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b1e"},{"created-at":1360265895000,"author":{"login":"AtKaaZ","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e10dfa345f44b0fe72bbe081fd51b83?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"reset!","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b1f"},{"created-at":1360265902000,"author":{"login":"AtKaaZ","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e10dfa345f44b0fe72bbe081fd51b83?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"swap!","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b20"},{"created-at":1527705104286,"author":{"login":"agarman","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/138454?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"swap-vals!","ns":"clojure.core"},"_id":"5b0eee10e4b045c27b7fac7f"}],"line":2385,"examples":[{"author":{"login":"yasuto","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cacfb7ecf08cb6461767e514c93b7bf9?r=PG&default=identicon"},"editors":[{"login":"franks42","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/b3ee701dd6c481e5d310467ddfe62c48?r=PG&default=identicon"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":";; first we make a demonstration atom\n(def a (atom 0))\n;; #'user/a \n\n;; failing to set the demonstration atom because the old-value does not match. \n(compare-and-set! a 10 20)\n;;=> false\n\n;; as you can see there was no change to the atom\n@a\n;;=> 0\n\n;; but when the old-value matches the atom is set to the new-value.\n(compare-and-set! a 0 10)\n;;=> true\n\n@a\n;;=> 10\n","created-at":1308629522000,"updated-at":1420734640517,"_id":"542692cfc026201cdc326e27"},{"editors":[{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"}],"body":";; Use compare-and-set! to implement a version of swap!\n;; that stops retrying after some number of attempts, for example\n;; because of a slow update fn and high concurrency on the atom:\n\n(defn swap-or-bail! [a f & [attempts]]\n (loop [i (or attempts 3)]\n (if (zero? i)\n (println \"Could not update. Bailing out.\")\n (let [old (deref a)\n success? (compare-and-set! a old (f old))]\n (when-not success?)\n (println \"Update failed. Retry\" i)\n (recur (dec i)))))))\n\n(defn slow-inc [x]\n (Thread/sleep 5000) \n (inc x))\n\n(def a (atom 0))\n(def f (future (swap-or-bail! a slow-inc)))\n(reset! a 1)\n;; \"Update failed. Retry 3\"\n(reset! a 2)\n;; \"Update failed. Retry 2\"\n(reset! a 3)\n;; Could not update. Bailing out.","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"},"created-at":1553605079299,"updated-at":1584291384572,"_id":"5c9a21d7e4b0ca44402ef6cb"}],"notes":[{"author":{"login":"chbrown","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/360279?v=3"},"updated-at":1471197839931,"created-at":1471197839931,"body":"`compare-and-set!` actually runs an equality comparison, not an identity comparison. The documentation should read:\n\n> Atomically sets the value of atom to newval if and only if the current value of the atom is identical equal to oldval.\n\n (def my-sym (atom 'a))\n (identical? @my-sym 'a)\n ;;=> false\n (= @my-sym 'a)\n ;;=> true\n (compare-and-set! my-sym 'a 'z)\n ;;=> true\n @my-sym\n ;;=> z","_id":"57b0b28fe4b02d8da95c2700"},{"author":{"login":"favila","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/1603620?v=3"},"updated-at":1492977098400,"created-at":1492977098400,"body":"The note that `compare-and-set!` uses equality comparison is wrong, `compare-and-set!` really _does_ use *identity comparison* (Java `==`). Internally, Clojure uses the `AtomicReference.compareAndSet(old, new)` method.\n\nThe reason his example works is due to interning of the `a` symbol: in his example, each `a` is the same (identical) object.\n\nBut as you can see from the example below, even numeric autoboxing can lead to surprising results:\n\n (def a (atom 0))\n ;=> #'user/a\n (compare-and-set! a 0 100)\n ;=> true\n ;(compare-and-set! a 100 200)\n ;=> true\n ;; Fails?! (on Oracle JVM 8 with default settings)\n (compare-and-set! a 200 300)\n ;=> false\n @a\n ;=> 200 ; WAT?\n\nClojure almost always uses boxed numbers (via Java autoboxing) unless you take special steps to avoid it. compare-and-set! only accepts Objects, so numbers are autoboxed to Longs.\n\nJava JVMs will usually intern small integers; by default Oracle/OpenJDK will intern -127 to 128 (the `byte` range) so that all such boxed numbers are identical. This can be altered with the `-XX:AutoBoxCacheMax=` command line flag. This may vary by JVM implementation, too.\n\n(In fact, on ClojureCLR, `compare-and-set!` of longs always fails because the CLR does not intern small numbers, see [this bug report](https://dev.clojure.org/jira/browse/CLJCLR-28).)\n\nSo in the example above, `compare-and-set!` on 0 and 100 work fine due to this auto-interning, but the compare with 200 fails because: `(identical? 200 200)` is false due to autoboxing: two distinct invisible `Long` objects are created for each \"200\" value.\n\nYou don't have to worry about this with `swap!` because the \"old\" value it compares against for the compare-and-set operation is always from the atom itself, so identity comparison works as long as no one else put a different object in the atom in the meantime. However, it is easy to imagine a pathological case with a highly-contented atom where everyone keeps putting the same \"equal\" value into it over and over, and yet swappers have to retry over and over.","_id":"58fd05cae4b01f4add58fe9a"}],"arglists":["atom oldval newval"],"doc":"Atomically sets the value of atom to newval if and only if the\n current value of the atom is identical to oldval. Returns true if\n set happened, else false","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/compare-and-set!"},{"ns":"clojure.core","name":"*use-context-classloader*","type":"var","see-alsos":null,"examples":[{"editors":[{"login":"reborg","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/20086?v=4"}],"body":";; *use-context-classloader* is always bound to true regarldess of any \n;; outer binding setting and thus ignored.\n;; The initial idea was to have a way to tell Clojure to ignore\n;; the context classloader (supposedly set by external libs or frameworks)\n;; in some pretty specific OSGi scenarios. Original context can be found at:\n;; https://groups.google.com/g/clojure/c/aXsFBdowdsA/m/1Ez894XuT30J and\n;; additional use cases https://clojure.atlassian.net/browse/CLJ-2593\n\n(import '[clojure.lang DynamicClassLoader])\n(def custom-classloader (DynamicClassLoader.))\n(.setContextClassLoader (Thread/currentThread) custom-classloader)\n\n(identical?\n (.. (fn []) getClass getClassLoader getParent)\n custom-classloader)\n;; true\n\n;; This should return false and use some other class loader\n(binding [*use-context-classloader* false]\n (identical?\n (.. (fn []) getClass getClassLoader getParent)\n custom-classloader))\n;; true\n\n;; WARNING: If the examples above don't seem to return the expected results, \n;; be aware that tools like Leiningen[https://leiningen.org/] or\n;; nRepl[https://github.com/nrepl/nrepl] alter the context class loader. \n;; Please use a vanilla REPL like \n;; clojure.deps[https://clojure.org/guides/getting_started] instead.","author":{"avatar-url":"https://avatars.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"},"created-at":1617620930283,"updated-at":1655802050958,"_id":"606aefc2e4b0b1e3652d74b1"},{"updated-at":1655794528435,"created-at":1655794528435,"author":{"login":"KingMob","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/946421?v=4"},"body":";; The above example has one minor caveat to be aware of for those who need \n;; to work with classloaders. *use-context-classloader* is not technically\n;; ignored, because RT/baseLoader will use it. But it's usually overridden \n;; by RT/makeClassLoader, which pushes a binding that sets it to true every \n;; time it's called. And RT/makeClassLoader is called every time eval or \n;; compile1 is called and in some versions of load(), so it happens a lot.","_id":"62b16b60e4b0b1e3652d7609"}],"notes":null,"arglists":[],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core/*use-context-classloader*"},{"ns":"clojure.core","name":"await1","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1610778845682,"author":{"login":"Crowbrammer","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/19522656?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"await","ns":"clojure.core"},"_id":"600288dde4b0b1e3652d7434"},{"created-at":1610778852896,"author":{"login":"Crowbrammer","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/19522656?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"await-for","ns":"clojure.core"},"_id":"600288e4e4b0b1e3652d7435"}],"line":3309,"examples":null,"notes":[{"body":"Looking at the source, it seems to take an agent, wait until it's queue is empty, then return the agent. When the agent has a positive queue count, it implements the standard `(await a)` and then returns `a`, the agent.\n\nUse: `(await1 a)`","created-at":1610778678000,"updated-at":1610778828434,"author":{"avatar-url":"https://avatars0.githubusercontent.com/u/19522656?v=4","account-source":"github","login":"Crowbrammer"},"_id":"60028836e4b0b1e3652d7433"}],"arglists":["a"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core/await1"},{"added":"1.0","ns":"clojure.core","name":"let","special-form":true,"file":"clojure/core.clj","type":"macro","column":1,"see-alsos":[{"created-at":1290671337000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"letfn","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b09"},{"created-at":1399434293000,"author":{"login":"Chort409","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/73da2cf9145cfb9c900b31436ee435a6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"if-let","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521ba0"},{"created-at":1412886358634,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"},"to-var":{"ns":"clojure.core","name":"fn","library-url":"https://github.com/clojure/clojure"},"_id":"5436ef56e4b0ae795603157d"},{"created-at":1602614306958,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"for","ns":"clojure.core"},"_id":"5f85f422e4b0b1e3652d73de"}],"line":4523,"examples":[{"author":{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"avatar-url":"https://avatars2.githubusercontent.com/u/12958644?v=4","account-source":"github","login":"funkrider"},{"login":"dijonkitchen","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/11434205?v=4"}],"body":";; let is a Clojure special form, a fundamental building block of the language.\n;;\n;; In addition to parameters passed to functions, let provides a way to create\n;; lexical bindings of data structures to symbols. The binding, and therefore \n;; the ability to resolve the binding, is available only within the lexical \n;; context of the let. \n;; \n;; let uses pairs in a vector for each binding you'd like to make and the value \n;; of the let is the value of the last expression to be evaluated. let also \n;; allows for destructuring which is a way to bind symbols to only part of a \n;; collection.\n\n;; A basic use for a let:\nuser=> (let [x 1] \n x)\n1\n\n;; Note that the binding for the symbol y won't exist outside of the let:\nuser=> (let [y 1] \n y)\n1\nuser=> (prn y)\njava.lang.Exception: Unable to resolve symbol: y in this context (NO_SOURCE_FILE:7)\n\n;; Note that if you use def inside a let block, your interned variable is within \n;; the current namespace and will appear OUTSIDE of the let block. \nuser=> (let [y 1] \n (def z y) \n y)\n1\nuser=> z\n1\n\n;; Another valid use of let:\nuser=> (let [a 1 b 2] \n (+ a b))\n3\n\n;; The forms in the vector can be more complex (this example also uses\n;; the thread macro):\nuser=> (let [c (+ 1 2)\n [d e] [5 6]] \n (-> (+ d e) (- c)))\n8\n\n;; The bindings for let need not match up (note the result is a numeric\n;; type called a ratio):\nuser=> (let [[g h] [1 2 3]] \n (/ g h))\n1/2\n\n;; From http://clojure-examples.appspot.com/clojure.core/let with permission.","created-at":1278720629000,"updated-at":1556647963303,"_id":"542692c7c026201cdc3269bb"},{"updated-at":1285500534000,"created-at":1279162869000,"body":"user=> (let [a (take 5 (range))\n {:keys [b c d] :or {d 10 b 20 c 30}} {:c 50 :d 100}\n [e f g & h] [\"a\" \"b\" \"c\" \"d\" \"e\"]\n _ (println \"I was here!\")\n foo 12\n bar (+ foo 100)]\n [a b c d e f g h foo bar])\nI was here!\n[(0 1 2 3 4) 20 50 100 \"a\" \"b\" \"c\" (\"d\" \"e\") 12 112]\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/142529?v=3","account-source":"github","login":"nipra"},"_id":"542692c7c026201cdc3269c2"},{"author":{"login":"johnfn","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/ffffd204ecbbae82a04f5b574d76746b?r=PG&default=identicon"},"editors":[],"body":"; :as example \n\nuser=> (let [[x y :as my-point] [5 3]]\n (println x y)\n (println my-point))\n\n5 3\n[5 3]\n\n; :as names the group you just destructured.\n\n; equivalent to (and better than)\n\nuser=> (let [[x y] [5 3]\n my-point [x y]]\n ;...","created-at":1312965326000,"updated-at":1312965326000,"_id":"542692c7c026201cdc3269c4"},{"author":{"login":"leifp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d2f37720f063404ef83b987d2824353d?r=PG&default=identicon"},"editors":[],"body":";;; map destructuring, all features\nuser=>\n(let [\n ;;Binding Map\n {:keys [k1 k2] ;; bind vals with keyword keys\n :strs [s1 s2] ;; bind vals with string keys\n :syms [sym1 sym2] ;; bind vals with symbol keys\n :or {k2 :default-kw, ;; default values\n s2 :default-s, \n sym2 :default-sym} \n :as m} ;; bind the entire map to `m`\n ;;Data\n {:k1 :keyword1, :k2 :keyword2, ;; keyword keys\n \"s1\" :string1, \"s2\" :string2, ;; string keys\n 'sym1 :symbol1, ;; symbol keys\n ;; 'sym2 :symbol2 ;; `sym2` will get default value\n }] \n [k1 k2 s1 s2 sym1 sym2 m]) ;; return value\n\n[:keyword1, :keyword2, \n :string1, :string2,\n :symbol1, :default-sym, ;; key didn't exist, so got the default\n {'sym1 :symbol1, :k1 :keyword1, :k2 :keyword2, \n \"s1\" :string1, \"s2\" :string2}]\n\n;; remember that vector and map destructuring can also be used with \n;; other macros that bind variables, e.g. `for` and `doseq`","created-at":1335261849000,"updated-at":1335261849000,"_id":"542692d3c026201cdc326ff3"},{"author":{"login":"ryo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3f7913b563c72083c74030d928ba407e?r=PG&default=identicon"},"editors":[],"body":";;; no value of a key\nuser> (let [{:keys [a b] :as m} (:x {})]\n [a b m])\n[nil nil nil]\n\n;;; same as above\nuser> (let [{:keys [a b] :as m} nil]\n [a b m])\n[nil nil nil]\n\n;;; similar case on Vector\nuser> (let [[a b :as v] nil]\n [a b v])\n[nil nil nil]\n","created-at":1399634796000,"updated-at":1399634796000,"_id":"542692d3c026201cdc326ff4"},{"body":";; lexical clojure (or let-over-fn) is an idiom for doing, in functional languages,\n;; something very similar to object based programming.\n;; Using combinations of 'let' and 'fn' can produce many interesting results.\n\n;; note the use of the ! on the functions to indicate the side effect\n(defn counter []\n (let [cnt (atom 0)]\n {:inc! (fn [] (swap! cnt inc))\n :dec! (fn [] (swap! cnt dec)) \n :get (fn [] @cnt)} ))\n\n;; we can now make and use the object\n(let [cnt (counter)]\n ((:inc! cnt))\n ((:inc! cnt)) \n ((:get cnt)))\n;;=> 2","author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"},"created-at":1412885156677,"updated-at":1412886345817,"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"}],"_id":"5436eaa4e4b0ae795603157c"},{"updated-at":1464664767084,"created-at":1464664767084,"author":{"login":"freezhan","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/5796449?v=3"},"body":"(let [[a b & c :as d] [1 2 3 4 5]]\n (println a) ; 1\n (println b) ; 2\n (println c) ; (3 4 5)\n d) ;[1 2 3 4 5]","_id":"574d02bfe4b0bafd3e2a046b"},{"editors":[{"login":"dijonkitchen","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/11434205?v=4"}],"body":";;define F1Car record\n(defrecord F1Car [team engine tyre oil])\n\n;;build the constructor distructing a single map with options\n(defn make-f1team [f1-team f1-engine {:keys [f1-tyre f1-oil] :as opts}]\n (let [{:keys [tyre oil]} opts]\n (map->F1Car {:team f1-team\n :engine f1-engine\n :tyre f1-tyre\n :oil f1-oil})))\n\n;;create a record\n(def mclaren (make-f1team \"RedBull\" \"Renault\" {:f1-tyre\"Pirelli\" :f1-oil \"Castrol\"}))\n\n;;retrieve values\n(keys mclaren)\n(vals mclaren)\n(:team mclaren)\n(:oil mclaren)","author":{"avatar-url":"https://avatars0.githubusercontent.com/u/31028993?v=4","account-source":"github","login":"ibercode"},"created-at":1510307566093,"updated-at":1556648054942,"_id":"5a0576eee4b0a08026c48caa"},{"updated-at":1556559048678,"created-at":1556559048678,"author":{"login":"funkrider","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/12958644?v=4"},"body":";;It is possible to enumerate the symbols created within a let using a macro.\n(defmacro local-context []\n (let [symbols (keys &env)]\n (zipmap (map (fn [sym] `(quote ~sym)) symbols) symbols)))\n\n(let [a :b lc (local-context)] lc)\n;; => {a :b}","_id":"5cc734c8e4b0ca44402ef713"},{"updated-at":1651606596047,"created-at":1651606596047,"author":{"login":"rgkirch","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/6143833?v=4"},"body":";; the destructuring key, k in this example, doesn't have to be a literal keyword\n(let [k (keyword \"name\")\n {person-name k} {:name \"john\"}]\n person-name)\n;; => \"john\"","_id":"62718444e4b0b1e3652d75e5"},{"updated-at":1692349135324,"created-at":1692179180792,"author":{"login":"jimka2001","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/6414129?v=4"},"body":";; There is some confusion in various lisps about the scope of variables in the\n;; bindings of let variables. It works as follows in Clojure.\n(let [y 'OUTER]\n (let [y 'INNER\n x y] ;; binds x to 'INNER, not to 'OUTER\n x))\n;; => inner\n\n;; Note that both Common Lisp and emacs lisp would bind x to 'OUTER not 'INNER\n;; in the corresponding code.\n\n;; But this is because `let` in Common Lisp and emacs lisp does not bind sequentially.\n;; The correct analogue of Clojure's `let` is in fact `let*` in these other lisps,\n;; in which case the behaviour does match.","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/6414129?v=4","account-source":"github","login":"jimka2001"},{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"}],"_id":"64dc9aece4b08cf8563f4be2"}],"macro":true,"notes":[{"updated-at":1297072373000,"body":"Nota Bene: `let` in Clojure is like `let*` in Scheme -- each init-expr has access to the preceding binding forms. (There is also a `let*`, but it is more or less `let` without destructuring, and in fact is the underlying implementation.)","created-at":1297072373000,"author":{"login":"TimMc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5d532e51427ef2f4ded31aaca16c8baf?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fb2"},{"body":"Be aware that `let`’s `:or` always evaluates the default value, unlike the `or` macro:\n\n user=> (let [{:keys [a]\n :or {a (do (println \"toto\") 1)}} {}]\n a)\n toto\n 1\n\n user=> (let [{:keys [a]\n :or {a (do (println \"toto\") 1)}} {:a 2}]\n a)\n toto\n 2 ","created-at":1554372403311,"updated-at":1554372446160,"author":{"avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4","account-source":"github","login":"bfontaine"},"_id":"5ca5d733e4b0ca44402ef6fd"}],"arglists":["bindings & body"],"doc":"binding => binding-form init-expr\n binding-form => name, or destructuring-form\n destructuring-form => map-destructure-form, or seq-destructure-form\n\n Evaluates the exprs in a lexical context in which the symbols in\n the binding-forms are bound to their respective init-exprs or parts\n therein.\n\n See https://clojure.org/reference/special_forms#binding-forms for\n more information about destructuring.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/let","forms":["(let [bindings*] exprs*)"]},{"added":"1.0","ns":"clojure.core","name":"ref-set","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1284616929000,"author":{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},"to-var":{"ns":"clojure.core","name":"ref","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d91"},{"created-at":1498153558604,"author":{"login":"devn","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/10421?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"alter","ns":"clojure.core"},"_id":"594c0256e4b06e730307db40"},{"created-at":1498153567222,"author":{"login":"devn","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/10421?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"commute","ns":"clojure.core"},"_id":"594c025fe4b06e730307db41"},{"created-at":1498153571630,"author":{"login":"devn","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/10421?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"dosync","ns":"clojure.core"},"_id":"594c0263e4b06e730307db42"}],"line":2472,"examples":[{"updated-at":1285495563000,"created-at":1280777271000,"body":"user=> (def foo (ref {}))\n#'user/foo\n\nuser=> (dosync\n (ref-set foo {:foo \"bar\"}))\n{:foo \"bar\"}\n\nuser=> @foo\n{:foo \"bar\"}\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3","account-source":"github","login":"devn"},"_id":"542692c9c026201cdc326acb"}],"notes":null,"arglists":["ref val"],"doc":"Must be called in a transaction. Sets the value of ref.\n Returns val.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/ref-set"},{"added":"1.1","ns":"clojure.core","name":"pop-thread-bindings","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1374313672000,"author":{"login":"alilee","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2fb0196dc5a7cd3a5cc73f1b9941c209?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"push-thread-bindings","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521eff"},{"created-at":1374313678000,"author":{"login":"alilee","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2fb0196dc5a7cd3a5cc73f1b9941c209?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"binding","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f00"}],"line":1948,"examples":null,"notes":null,"arglists":[""],"doc":"Pop one set of bindings pushed with push-binding before. It is an error to\n pop bindings without pushing before.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/pop-thread-bindings"},{"added":"1.0","ns":"clojure.core","name":"interleave","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1293096421000,"author":{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},"to-var":{"ns":"clojure.core","name":"interpose","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ed3"},{"created-at":1325197345000,"author":{"login":"mmwaikar","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/29d36f4c9f39c9f8ff61c07033b13118?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"zipmap","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ed4"}],"line":4335,"examples":[{"author":{"login":"cdorrat","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5dedcb7069d39421760f6d255def10c3?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":";; This example takes a list of keys and a separate list of values and \n;; inserts them into a map.\n(apply assoc {} \n (interleave [:fruit :color :temp] \n [\"grape\" \"red\" \"hot\"]))\n\n;;=> {:temp \"hot\", :color \"red\", :fruit \"grape\"}\n","created-at":1278756097000,"updated-at":1421097481582,"_id":"542692ccc026201cdc326c48"},{"author":{"login":"kotarak","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5db30f607f0b5fa70d690311aa3bfd3b?r=PG&default=identicon"},"editors":[{"login":"kotarak","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5db30f607f0b5fa70d690311aa3bfd3b?r=PG&default=identicon"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":";; Simple example:\n(interleave [:a :b :c] [1 2 3])\n;;=> (:a 1 :b 2 :c 3)","created-at":1279026371000,"updated-at":1421097499209,"_id":"542692ccc026201cdc326c4c"},{"author":{"login":"kotarak","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5db30f607f0b5fa70d690311aa3bfd3b?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"},{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"}],"body":";; The shortest input stops interleave:\n\n(interleave [:a :b :c] [1 2])\n;;=> (:a 1 :b 2)\n\n(interleave [:a :b] [1 2 3])\n;;=> (:a 1 :b 2)","created-at":1279026486000,"updated-at":1422937238232,"_id":"542692ccc026201cdc326c4f"},{"author":{"login":"octopusgrabbus","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/fd31b8bcea99fa7b0711fbc424587774?r=PG&default=identicon"},"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":"(def s1 [[:000-00-0000 \"TYPE 1\" \"JACKSON\" \"FRED\"]\n [:000-00-0001 \"TYPE 2\" \"SIMPSON\" \"HOMER\"]\n [:000-00-0002 \"TYPE 4\" \"SMITH\" \"SUSAN\"]])\n\n(interleave (map #(nth % 0 nil) s1) (map #(nth % 1 nil) s1))\n;;=> (:000-00-0000 \"TYPE 1\" \n;; :000-00-0001 \"TYPE 2\"\n;; :000-00-0002 \"TYPE 4\")","created-at":1334887108000,"updated-at":1421097410949,"_id":"542692d3c026201cdc326fd1"},{"author":{"login":"octopusgrabbus","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/fd31b8bcea99fa7b0711fbc424587774?r=PG&default=identicon"},"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":"(def s1 [[:000-00-0000 \"TYPE 1\" \"JACKSON\" \"FRED\"]\n [:000-00-0001 \"TYPE 2\" \"SIMPSON\" \"HOMER\"]\n [:000-00-0002 \"TYPE 4\" \"SMITH\" \"SUSAN\"]])\n\n(def cols [0 2 3])\n\n(defn f1 \n [s1 col] \n (map #(get-in s1 [% col] nil) (range (count s1))))\n\n(apply interleave (map (partial f1 s1) cols))\n;;=> (:000-00-0000 \"JACKSON\" \"FRED\" \n;; :000-00-0001 \"SIMPSON\" \"HOMER\" \n;; :000-00-0002 \"SMITH\" \"SUSAN\")","created-at":1334887172000,"updated-at":1421097441002,"_id":"542692d3c026201cdc326fd2"},{"body":"(interleave (repeat \"a\") [1 2 3])\n;;=>(\"a\" 1 \"a\" 2 \"a\" 3)\n","author":{"login":"ttkk1024","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/145719?v=3"},"created-at":1431650103962,"updated-at":1431650103962,"_id":"55553f37e4b01ad59b65f4d1"},{"updated-at":1553297861379,"created-at":1553290561134,"author":{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"},"body":";; interleave can be used as an opposite of zipmap\n(let [m {:a 1, :b 2, :c 3}]\n (split-at (count m) (apply interleave m)))\n;; => [(:a :b :c) (1 2 3)]\n;; (but really, a simpler solution would be [(keys m) (vals m)].)","editors":[{"avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4","account-source":"github","login":"bfontaine"}],"_id":"5c955541e4b0ca44402ef6bc"}],"notes":[{"body":"Behaviour of
(interleave [4 5 6])
\napparently depends on which Clojure version you're using. In 1.10.0 the result is:\n
[4 5 6]
","created-at":1567536152090,"updated-at":1567536173810,"author":{"avatar-url":"https://avatars2.githubusercontent.com/u/179958?v=4","account-source":"github","login":"holtzermann17"},"_id":"5d6eb418e4b0ca44402ef7ab"}],"arglists":["","c1","c1 c2","c1 c2 & colls"],"doc":"Returns a lazy seq of the first item in each coll, then the second etc.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/interleave"},{"added":"1.0","ns":"clojure.core","name":"printf","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1329894578000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.core","name":"format","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e35"},{"created-at":1330170804000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.pprint","name":"cl-format","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e36"},{"created-at":1417278644991,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.core","name":"println","library-url":"https://github.com/clojure/clojure"},"_id":"5479f4b4e4b03d20a10242b9"}],"line":5799,"examples":[{"author":{"login":"lambder","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1c0c20072f52de3a6335cae183b865f6?r=PG&default=identicon"},"editors":[{"login":"jeffi","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1195619?v=3"}],"body":"(printf \"1 + 2 is %s%n\" 3)","created-at":1299610618000,"updated-at":1433459544222,"_id":"542692ccc026201cdc326cad"},{"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":";; Click the link to clojure.core/format under See also for\n;; more extensive examples. printf and format take the same\n;; arguments -- the difference is that format returns a formatted\n;; string, whereas printf sends the formatted string to *out*.\n\n;; Also note that printf output is buffered, and does not automatically\n;; flush at any time, not even when printing newlines. Thus the last few lines\n;; of output may never appear if your program exits before the buffer is\n;; flushed. Use (flush) or a (println ...) call to force flushing of the buffer.","created-at":1331440764000,"updated-at":1417278553807,"_id":"542692d4c026201cdc327038"}],"notes":null,"arglists":["fmt & args"],"doc":"Prints formatted output, as per format","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/printf"},{"added":"1.0","ns":"clojure.core","name":"map?","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1411815243526,"author":{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},"to-var":{"ns":"clojure.core","name":"hash-map","library-url":"https://github.com/clojure/clojure"},"_id":"5426974be4b0d1509f919f73"},{"created-at":1414508257391,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"},"to-var":{"ns":"clojure.core","name":"set?","library-url":"https://github.com/clojure/clojure"},"_id":"544faee1e4b0dc573b892fa9"},{"created-at":1414508398671,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"},"to-var":{"ns":"clojure.core","name":"vector?","library-url":"https://github.com/clojure/clojure"},"_id":"544faf6ee4b03d20a1024283"},{"created-at":1550854368361,"author":{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/94482?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"associative?","ns":"clojure.core"},"_id":"5c7028e0e4b0ca44402ef6a0"}],"line":169,"examples":[{"author":{"login":"dpritchett","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/147981?v=3"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"},{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"}],"body":"(map? {:a 1 :b 2 :c 3})\n;;=> true\n\n(map? (hash-map :a 1 :b 2))\n;;=> true\n\n(map? (sorted-map :a 1 :b 2))\n;;=> true\n\n(map? (array-map :a 1 :b 2))\n;;=> true\n\n(map? '(1 2 3))\n;;=> false\n\n(map? #{:a :b :c})\n;;=> false","created-at":1279074290000,"updated-at":1423276232206,"_id":"542692cbc026201cdc326bdf"},{"updated-at":1443731276562,"created-at":1443731276562,"author":{"login":"hura","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/671872?v=3"},"body":"\"Note that Records also implement `clojure.lang.IPersistentMap`:\"\n\n(defrecord XRec [])\n(map? (->XRec))\n;; => true","_id":"560d974ce4b08e404b6c1c8c"}],"notes":null,"arglists":["x"],"doc":"Return true if x implements IPersistentMap","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/map_q"},{"added":"1.0","ns":"clojure.core","name":"->","file":"clojure/core.clj","type":"macro","column":1,"see-alsos":[{"created-at":1289746069000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"->>","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c48"},{"created-at":1412262619860,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"},"to-var":{"ns":"clojure.core","name":"as->","library-url":"https://github.com/clojure/clojure"},"_id":"542d6adbe4b05f4d257a298a"},{"created-at":1412882642031,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"},"to-var":{"ns":"clojure.core","name":"get-in","library-url":"https://github.com/clojure/clojure"},"_id":"5436e0d2e4b06dbffbbb00c5"},{"created-at":1431612379634,"author":{"login":"pladdy","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/11509380?v=3"},"to-var":{"ns":"clojure.core","name":"some->","library-url":"https://github.com/clojure/clojure"},"_id":"5554abdbe4b03e2132e7d162"},{"created-at":1436359125547,"author":{"login":"jw-00000","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2936?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"doto","ns":"clojure.core"},"_id":"559d19d5e4b00f9508fd66fd"},{"created-at":1471532173241,"author":{"login":"mars0i","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1836941?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"..","ns":"clojure.core"},"_id":"57b5cc8de4b0b5e6d7a4fa59"}],"line":1694,"examples":[{"updated-at":1447300863348,"created-at":1278953347000,"body":";; Use of `->` (the \"thread-first\" macro) can help make code\n;; more readable by removing nesting. It can be especially\n;; useful when using host methods:\n\n;; Arguably a bit cumbersome to read:\nuser=> (first (.split (.replace (.toUpperCase \"a b c d\") \"A\" \"X\") \" \"))\n\"X\"\n\n;; Perhaps easier to read:\nuser=> (-> \"a b c d\" \n .toUpperCase \n (.replace \"A\" \"X\") \n (.split \" \") \n first)\n\"X\"\n\n;; It can also be useful for pulling values out of deeply-nested\n;; data structures:\nuser=> (def person \n {:name \"Mark Volkmann\"\n :address {:street \"644 Glen Summit\"\n :city \"St. Charles\"\n :state \"Missouri\"\n :zip 63304}\n :employer {:name \"Object Computing, Inc.\"\n :address {:street \"12140 Woodcrest Dr.\"\n :city \"Creve Coeur\"\n :state \"Missouri\"\n :zip 63141}}})\n \nuser=> (-> person :employer :address :city)\n\"Creve Coeur\"\n\n;; same as above, but with more nesting\nuser=> (:city (:address (:employer person)))\n\"Creve Coeur\"\n\n;; Note that this operator (along with ->>) has at times been\n;; referred to as a 'thrush' operator.\n\n;; http://blog.fogus.me/2010/09/28/thrush-in-clojure-redux/\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"avatar-url":"https://www.gravatar.com/avatar/34f159f89cbd1d9beac0276f5a7af552?r=PG&default=identicon","account-source":"clojuredocs","login":"uvtc"},{"avatar-url":"https://www.gravatar.com/avatar/34f159f89cbd1d9beac0276f5a7af552?r=PG&default=identicon","account-source":"clojuredocs","login":"uvtc"},{"avatar-url":"https://www.gravatar.com/avatar/34f159f89cbd1d9beac0276f5a7af552?r=PG&default=identicon","account-source":"clojuredocs","login":"uvtc"},{"avatar-url":"https://www.gravatar.com/avatar/1fabe200e8b19ec248fa8285cd6b493b?r=PG&default=identicon","account-source":"clojuredocs","login":"amithgeorge"},{"avatar-url":"https://avatars.githubusercontent.com/u/333974?v=3","account-source":"github","login":"eneroth"},{"login":"yang-wei","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/5494874?v=3"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},"_id":"542692ccc026201cdc326c53"},{"author":{"login":"na_ka_na","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/38aaeb9ed42ddefd5aa63f8b9c4b84a4?r=PG&default=identicon"},"editors":[],"body":";; Your own REPL! (Read Eval Print Loop)\n\n;; We would need a little helper macro for that\n;; It does what its name says - loops forever\nuser=> (defmacro loop-forever [& body] `(loop [] ~@body (recur)))\n\n;; Your own REPL\nuser=> (loop-forever (println (eval (read)))) \n(+ 1 2)\n3\n\n;; If you read the above code left to right (outside in) it reads LPER.\n;; Inside out it reads REPL alright.\n\n;; Sometimes it might be easier to read code outside in, just like a sequence of steps:\n;; 1. Read, 2. Eval, 3. Print, 4. Loop\n;; Here's how -> helps you:\n\nuser=> (-> (read) (eval) (println) (loop-forever)) \n(+ 1 2)\n3\n\n;; Does that read easier for you? If it does, -> is your friend!\n\n;; To see what Clojure did behind the scenes with your -> expression:\nuser=> (require 'clojure.walk)\nnil\nuser=> (clojure.walk/macroexpand-all '(-> (read) (eval) (println) (loop-forever)))\n(loop* [] (println (eval (read))) (recur))\n\n;; You can even use ->'s cousin ->> to setup your own REPL:\nuser=> (->> (read) (eval) (println) (while true))\n(+ 1 2)\n3\n\n;; Can you see why we can't use -> to write the above?\n\n","created-at":1294071196000,"updated-at":1294071196000,"_id":"542692ccc026201cdc326c5a"},{"author":{"login":"BertrandDechoux","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3"},"editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"}],"body":"user=> (def c 5)\nuser=> (-> c (+ 3) (/ 2) (- 1)) \n3\n\n;; and if you are curious why\nuser=> (use 'clojure.walk)\nuser=> (macroexpand-all '(-> c (+ 3) (/ 2) (- 1)))\n(- (/ (+ c 3) 2) 1)\n","created-at":1339249204000,"updated-at":1339250710000,"_id":"542692d1c026201cdc326f3c"},{"body":";; simplest usage example, fill as second item in the first and second form\n\nuser=> (-> \"foo\"\n (str \"bar\")\n (str \"zoo\"))\n\"foobarzoo\"\nuser=> (str \"foo\" \"bar\")\n\"foobar\"\nuser=> (str (str \"foo\" \"bar\") \"zoo\")\n\"foobarzoo\"","author":{"login":"arathunku","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/749393?v=3"},"created-at":1429647887382,"updated-at":1429647887382,"_id":"5536b20fe4b01bb732af0a85"},{"editors":[{"login":"alvarogarcia7","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/4199136?v=3"}],"body":"(-> 3 (- 2)) ; It means (- 3 2)\n=> 1\n\n(->> 3 (- 2)) ; It means (- 2 3)\n=> -1\n\n(doto 3 (- 2)) ; It means (- 3 2) but return the first object 3\n=> 3","author":{"avatar-url":"https://avatars.githubusercontent.com/u/4446025?v=3","account-source":"github","login":"expert0226"},"created-at":1452151863527,"updated-at":1454886061151,"_id":"568e1437e4b0e0706e05bd9e"},{"updated-at":1462650593323,"created-at":1462650593323,"author":{"login":"eggsyntax","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1233514?v=3"},"body":";; Be cautious with anonymous functions; they must be wrapped in an outer\n;; pair of parens.\n(-> 10\n #(/ % 2))\n;; will throw an exception, but\n(-> 10\n (#(/ % 2)))\n;; will work fine. Similarly,\n(-> 10\n (fn [n] (/ n 2)))\n;; will throw an exception, but\n(-> 10\n ((fn [n] (/ n 2))))\n;; works as intended.\n","_id":"572e46e1e4b039e78aadabfc"},{"editors":[{"login":"rafmagana","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/92894?v=3"}],"body":";; How to thread functions that expect more than one argument\n\n;; Say you want to thread this.\nuser=> (inc (/ 10 2))\n=> 6\n\n;; This obviously won't work\nuser=> (-> 2 10 / inc)\n=> ClassCastException java.lang.Long cannot be cast to clojure.lang.IFn\n\n;; Since Clojure is expecting a function instead of `10` in `(10 2)`\nuser=> (clojure.walk/macroexpand-all '(-> 2 10 + inc))\n=> (inc (+ (10 2)))\n\n;; Instead you have two options, either just\nuser=> (-> (/ 10 2) inc)\n=> 6\n\n;; or\nuser=> (-> 10 (/ 2) inc)\n=> 6","author":{"avatar-url":"https://avatars.githubusercontent.com/u/92894?v=3","account-source":"github","login":"rafmagana"},"created-at":1464759684437,"updated-at":1464761625892,"_id":"574e7584e4b0bafd3e2a046d"},{"editors":[{"login":"rafmagana","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/92894?v=3"}],"body":";; For large threads you can use commas (interpreted as whitespaces) \n;; to visualize where the items are going to be inserted.\n\nuser=> (-> + (reduce 10 [6 4]) (* 5) (/ 100))\n=> 1\n\n;; with two commas (you can use one if you prefer)\nuser=> (-> + (reduce ,, 10 [6 4]) (* ,, 5) (/ ,, 100))\n=> 1\n\n;; For instance:\n;; (reduce ,, 10 [6 4])\n;; means\n;; (reduce + 10 [6 4])","author":{"avatar-url":"https://avatars.githubusercontent.com/u/92894?v=3","account-source":"github","login":"rafmagana"},"created-at":1464761041214,"updated-at":1464761604810,"_id":"574e7ad1e4b0bafd3e2a046e"},{"updated-at":1503919516240,"created-at":1503919516240,"author":{"login":"MokkeMeguru","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/30849444?v=4"},"body":";; 4Clojure Question 38\n\n(= (#(-> %& \n sort \n reverse \n first) 1 8 3 4) 8)","_id":"59a3fd9ce4b09f63b945ac57"}],"macro":true,"notes":[{"updated-at":1280208863000,"body":"See also ->> which is similar but threads the first expr as the last argument of the forms.","created-at":1280208863000,"author":{"login":"steveminer","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d28543d134185d12d4006a74738d233e?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521f8e"},{"updated-at":1374299741000,"body":"I have a [short blog](http://wangjinquan.me/show/Clojure%20线性(箭头)�作符) on this, in case you are still confused on it and understand Chinese.","created-at":1374299714000,"author":{"login":"John Wang","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d66c259a1fa85832e41fb9b90c7e613c?r=PG&default=identicon"},"_id":"542692edf6e94c6970522008"},{"body":"Can be used as an alternative to get-in.","created-at":1412882630144,"updated-at":1412882630144,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"},"_id":"5436e0c6e4b0ae795603157a"}],"arglists":["x & forms"],"doc":"Threads the expr through the forms. Inserts x as the\n second item in the first form, making a list of it if it is not a\n list already. If there are more forms, inserts the first form as the\n second item in second form, etc.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/->"},{"added":"1.0","ns":"clojure.core","name":"defstruct","file":"clojure/core.clj","static":true,"type":"macro","column":1,"see-alsos":[{"created-at":1312838555000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"struct","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521a87"},{"created-at":1312849643000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"create-struct","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521a88"},{"created-at":1335411176000,"author":{"login":"steveminer","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d28543d134185d12d4006a74738d233e?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"defrecord","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521a89"},{"created-at":1446587127297,"author":{"login":"delonnewman","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10404?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"deftype","ns":"clojure.core"},"_id":"56392af7e4b04b157a6648e3"},{"created-at":1446587141438,"author":{"login":"delonnewman","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10404?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"defprotocol","ns":"clojure.core"},"_id":"56392b05e4b04b157a6648e4"}],"line":4071,"examples":[{"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":"user=> (defstruct person :name :age :height)\n#'user/person\n\nuser=> (struct person \"george\" 22 115)\n{:name \"george\", :age 22, :height 115}","created-at":1280748955000,"updated-at":1285495885000,"_id":"542692c7c026201cdc3269d6"}],"macro":true,"notes":[{"updated-at":1335411165000,"body":"Structs are obsolete. Use records instead. See `defrecord`.","created-at":1335411165000,"author":{"login":"steveminer","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d28543d134185d12d4006a74738d233e?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fe0"},{"updated-at":1391537723000,"body":"Are structs obsolete ? Or will become obsolete ? The docs for 'defrecord' have 'Alpha - Subject To Change' ?","created-at":1391537723000,"author":{"login":"monojohnny","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/79d11fd92782ff24d9ae806b72b73d2f?r=PG&default=identicon"},"_id":"542692edf6e94c697052201c"},{"updated-at":1392247001000,"body":"The doc string for defrecord has been changed in Clojure 1.6 to remove the 'alpha' designation, along with many other Clojure functions: https://github.com/clojure/clojure/commit/93d13d0c0671130b329863570080c72799563ac7","created-at":1392247001000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"_id":"542692edf6e94c697052201d"},{"author":{"login":"jhigdon","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/45405?v=4"},"updated-at":1550940905930,"created-at":1550940905930,"body":"Adding to why people are saying it's obsolete:\n\nhttps://clojure.org/reference/datatypes#_deftype_and_defrecord\n\nexplains how where defstruct/deftype/defrecord differ\n\nand https://clojure.org/reference/data_structures#StructMaps is where they suggest a record might better serve your needs","_id":"5c717ae9e4b0ca44402ef6a1"},{"author":{"login":"metasoarous","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/88556?v=4"},"updated-at":1605646244437,"created-at":1605646169773,"body":"In _general_, records should be preferred over structs. However, structs aren't _entirely_ obsolete.\n\nThey can still be useful when you need/want to create record-like objects dynamically; That is, when you don't know the field names at compile time. A typical example of this might be loading rows from a CSV (as [semantic-csv](https://github.com/metasoarous/semantic-csv) does). The advantage in this case over using regular maps is significantly improved performance creating and using these objects.\n\nHowever, note that to use structs dynamically, you have to use `create-struct`, rather than `defstruct`, as above. So if anything, one could argue that `defstruct` is obsolete, but not necessary `create-struct` & `struct`.","_id":"5fb43759e4b0b1e3652d740d"}],"arglists":["name & keys"],"doc":"Same as (def name (create-struct keys...))","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/defstruct"},{"added":"1.0","ns":"clojure.core","name":"*err*","type":"var","see-alsos":null,"examples":[{"updated-at":1705869820104,"created-at":1705869734840,"author":{"login":"teodorlu","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/5285452?v=4"},"body":";; All functions that normally write to *out* can write to *err* by binding\n;; *out* to *err*:\n\nuser> (binding [*out* *err*]\n (prn \"prn can be used\")\n (println \"println can also be used\"))\n\"prn can be used\"\nprintln can also be used\n;; => nil","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/5285452?v=4","account-source":"github","login":"teodorlu"}],"_id":"65ad81a669fbcc0c22617484"}],"notes":null,"arglists":[],"doc":"A java.io.Writer object representing standard error for print operations.\n\n Defaults to System/err, wrapped in a PrintWriter","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/*err*"},{"added":"1.0","ns":"clojure.core","name":"get","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1324306493000,"author":{"login":"mmwaikar","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/29d36f4c9f39c9f8ff61c07033b13118?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"map-indexed","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bb1"},{"created-at":1359887523000,"author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"to-var":{"ns":"clojure.core","name":"get-in","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bb2"},{"created-at":1360286957000,"author":{"login":"AtKaaZ","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e10dfa345f44b0fe72bbe081fd51b83?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"find","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bb3"},{"created-at":1416824761214,"author":{"login":"alilee","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/16739?v=3"},"to-var":{"ns":"clojure.core","name":"select-keys","library-url":"https://github.com/clojure/clojure"},"_id":"547307b9e4b03d20a10242b2"},{"created-at":1416824821178,"author":{"login":"alilee","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/16739?v=3"},"to-var":{"ns":"clojure.core","name":"nth","library-url":"https://github.com/clojure/clojure"},"_id":"547307f5e4b03d20a10242b3"}],"line":1508,"examples":[{"updated-at":1545395916321,"created-at":1280321427000,"body":"(get [1 2 3] 1)\n;;=> 2\n\n(get [1 2 3] 5)\n;;=> nil\n\n(get [1 2 3] 5 100)\n;;=> 100\n\n(get {:a 1 :b 2} :b)\n;;=> 2\n\n(get {:a 1 :b 2} :z \"missing\")\n;;=> \"missing\"\n\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3","account-source":"github","login":"phreed"},{"login":"sanel","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/213914?v=4"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon","account-source":"clojuredocs","login":"gstamp"},"_id":"542692cdc026201cdc326cd7"},{"author":{"login":"mmwaikar","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/29d36f4c9f39c9f8ff61c07033b13118?r=PG&default=identicon"},"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":";; to get an index of the element of a vector, use .indexOf\n(def v [\"one\" \"two\" \"three\" \"two\"])\n;; #'user/v\n\n(.indexOf v \"two\")\n;;=> 1\n\n(.indexOf v \"foo\")\n;;=> -1\n","created-at":1324306658000,"updated-at":1421261046680,"_id":"542692d3c026201cdc326fbd"},{"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":";; the system environment has a hash-map semantic\n(get (System/getenv) \"SHELL\")\n;;=> \"/bin/bash\"\n\n(get (System/getenv) \"PATH\")\n;;=> \"/usr/local/bin:/sbin:/usr/sbin:/usr/bin:/bin\"","created-at":1324314703000,"updated-at":1421261106767,"_id":"542692d3c026201cdc326fbe"},{"updated-at":1421261190882,"created-at":1340441156000,"body":";; 'get' is not the only option\n(def my-map {:a 1 :b 2 :c 3})\n\n;; maps act like functions taking keys \n(my-map :a)\n;;=> 1\n\n;; even keys (if they are keywords) act like functions\n(:b my-map)\n;;=> 2","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3","account-source":"github","login":"phreed"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/92894?v=3","account-source":"github","login":"rafmagana"},"_id":"542692d3c026201cdc326fbf"},{"author":{"login":"cympfh","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/7ad064788bb989f0c9ae552257355d6?r=PG&default=identicon"},"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":";; it is tempting to try an index on a list\n(get '(a b c) 1)\n;;=> nil\n\n;; but you should use nth\n(nth '(a b c) 1)\n;;=> b","created-at":1394404668000,"updated-at":1421261345010,"_id":"542692d3c026201cdc326fc0"},{"updated-at":1461265877674,"created-at":1461265877674,"author":{"login":"mars0i","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1836941?v=3"},"body":";; Get also works with strings:\n(get \"abc\" 1)\n;;=> \\b","_id":"571925d5e4b0fc95a97eab50"},{"updated-at":1496171084580,"created-at":1492450542481,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/20086?v=3"},"body":";; For sorted stuff, \"key\" must be of the same type of the existing keys. \n;; This allows descending the sorted tree in log(N) average.\n\n(get (hash-map :a 1 :b 2) \"a\" \"not found\")\n;; \"not found\"\n\n(get (sorted-map :a 1 :b 2) \"a\" \"not found\")\n;; ClassCastException\n\n;; get works on transient maps, but silently fails on transient sets.\n;; A similar issue affects contains?.\n\n(get (transient #{0 1 2}) 1)\n;; nil\n\n;; get uses int cast with precision loss, with (.intValue x).\n;; The example below is explained because 4294967296 equal 2^32, thus\n;; (.intValue 4294967296) returns 0.\n;; Be careful with sufficiently large keys:\n\n(get [\"a\" \"b\" \"c\"] 4294967296)\n;; \"a\"","editors":[{"avatar-url":"https://avatars2.githubusercontent.com/u/20086?v=3","account-source":"github","login":"reborg"},{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/109629?v=3"}],"_id":"58f4fceee4b01f4add58fe94"},{"editors":[{"login":"puppe","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1393865?v=4"}],"body":";; Specifying 'not-found' does NOT guarantee that the return value is\n;; not 'nil'.\n\n(get {} :a 42)\n;;=> 42\n\n(get {:a nil} :a 42)\n;;=> nil\n\n;; This may be especially relevant if you use records, as all pre-defined keys\n;; will usually be present.\n\n(defrecord R [a b])\n(def r (map->R {}))\n\nr\n;;=> #user.R{:a nil :b nil}\n\n(get r :a 42)\n;;=> nil\n\n;; Consider using 'or' instead, as 'nil' is \"falsy\".\n\n(or (get {:a nil} :a) 42)\n;;=> 42","author":{"avatar-url":"https://avatars2.githubusercontent.com/u/1393865?v=4","account-source":"github","login":"puppe"},"created-at":1576172735814,"updated-at":1576172805891,"_id":"5df27cbfe4b0ca44402ef7f8"},{"editors":[{"login":"loeschzwerg","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/24317401?v=4"}],"body":";; Specifying not-found doesn't mean that the expression won't be evaluated.\n;; This can be a problem if you intend to materialize the not-found value \n;; only if key is not set.\n\n(get {:a 1} :a (#(println \"else\")))\n;; else\n;;=> 1\n\n;; using an `or` can solve your problem here\n(or (get {:a 1} :a)\n (println \"not found\"))\n;;=> 1","author":{"avatar-url":"https://avatars2.githubusercontent.com/u/633523?v=4","account-source":"github","login":"timofeytt"},"created-at":1595920651962,"updated-at":1666965797097,"_id":"5f1fd10be4b0b1e3652d7326"},{"updated-at":1690985032681,"created-at":1690985032681,"author":{"login":"usametov","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/5256128?v=4"},"body":";; how to deal with nil map, defensive coding example:\n;; try to get :a key from nil map \n(get nil :a :a1)\n;;=> :a1\n","_id":"64ca6248e4b08cf8563f4bd7"}],"notes":[{"body":"Why is this character/string?","created-at":1420334049781,"updated-at":1420334049781,"author":{"login":"Pierre-Thibault","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10163425?v=3"},"_id":"54a893e1e4b09260f767ca86"},{"author":{"login":"hgijeon","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7885562?v=3"},"updated-at":1449649145088,"created-at":1449649145088,"body":"(:mykey my-hash-map :none) means the same as (get my-hash-map :mykey :none) and
\n('mysym my-hash-map :none) means the same as (get my-hash-map 'mysym :none).
\nSo, you can use (:a {:a 1 :b 2} :not-inserted) as (get {:a 1 :b 2} :a :not-inserted).
\nSee \nhttp://clojure.org/data_structures#Data Structures-Keywords and\nhttp://clojure.org/data_structures#Data Structures-Symbols","_id":"5667e3f9e4b0f47c7ec61147"},{"author":{"login":"navigaid","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/10371727?v=4"},"updated-at":1545127452738,"created-at":1545127452738,"body":"`(get get get get)` is equivalent to `get`\n\nas in:\n\n```\n((get get get get) {:a 1} :a)\n```","_id":"5c18c61ce4b0ca44402ef5ec"}],"arglists":["map key","map key not-found"],"doc":"Returns the value mapped to key, not-found or nil if key not present\n in associative collection, set, string, array, or ILookup instance.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/get"},{"added":"1.0","ns":"clojure.core","name":"doto","file":"clojure/core.clj","type":"macro","column":1,"see-alsos":[{"created-at":1436359076539,"author":{"login":"jw-00000","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2936?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"->","ns":"clojure.core"},"_id":"559d19a4e4b00f9508fd66fb"},{"created-at":1436359083907,"author":{"login":"jw-00000","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2936?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"->>","ns":"clojure.core"},"_id":"559d19abe4b00f9508fd66fc"},{"created-at":1557781859408,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"..","ns":"clojure.core"},"_id":"5cd9dd63e4b0ca44402ef722"}],"line":3878,"examples":[{"author":{"login":"dakrone","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bcacd00a7f05c4772329cf9f446c7987?r=PG&default=identicon"},"editors":[{"login":"ozzloy","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/c546d3f104228c483309c760926e6e3?r=PG&default=identicon"},{"avatar-url":"https://avatars.githubusercontent.com/u/37649?v=3","account-source":"github","login":"fasiha"},{"login":"dominem","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/11671382?v=4"}],"body":";; Note that even though println returns nil, doto still returns the HashMap object\n(doto (java.util.HashMap.)\n (.put \"a\" 1)\n (.put \"b\" 2)\n (println))\n;;=> #\n;;=> {\"b\" 2, \"a\" 1}\n\n;; Equivalent to\n(def m (java.util.HashMap.))\n(.put m \"a\" 1)\n(.put m \"b\" 2)\nm\n;;=> {\"a\" 1, \"b\" 2}\n(println m)\n;;=> #object[java.util.HashMap 0x727fcc37 {a=1, b=2}]","created-at":1293673034000,"updated-at":1565336332524,"_id":"542692c9c026201cdc326ae6"},{"author":{"login":"shockbob","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon"},"editors":[{"login":"shockbob","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon"},{"login":"jakebasile","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/766907?v=2"}],"body":";; quick demonstration of using a Collections function on the resulting ArrayList\n\nuser=> (def al (doto (java.util.ArrayList.) (.add 11) (.add 3) (.add 7)))\n#'user/al\nuser=> al\n#\nuser=> (java.util.Collections/sort al)\nnil\nuser=> al\n#\nuser=>","created-at":1313965605000,"updated-at":1412632698246,"_id":"542692c9c026201cdc326ae8"},{"author":{"login":"jimpil","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/c3cf214ed0c5f0bca153b1c1177575d6?r=PG&default=identicon"},"editors":[{"login":"Ljos","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/45b996a79abca465acaf6c0f10b0437?r=PG&default=identicon"},{"login":"schmee","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/3405586?v=3"}],"body":";; careful when calling 'dotimes' from within a 'doto' statement\nuser=> (doto (java.util.ArrayList.)\n (.add -2)\n (.add -1)\n (dotimes [i 3] (.add i)))\njava.lang.IllegalArgumentException: dotimes requires a vector for its binding (NO_SOURCE_FILE:1)\n\n; what has happened is that (java.util.ArrayList.) has secretly\n; become the first argument to 'dotimes' and thus the exception\n; informs us that it can't find the binding vector required for\n; 'dotimes' to expand. You can cure this behaviour by simply using\n; 'do' instead of 'doto' or by wrapping the call to 'dotimes' in\n; a function. e.g:\n\n;using 'let' with implicit 'do' instead of 'doto'\nuser=> (let [al (java.util.ArrayList.)]\n (.add al -2)\n (.add al -1)\n (dotimes [i 3] (.add al i))\n al);return the ArrayList\n# ;exactly what we intended\n\n;wrapping 'dotimes' in a function literal\nuser=>(doto (java.util.ArrayList.)\n (.add -2)\n (.add -1)\n (#(dotimes [i 3] (.add % i))))\n# ;exactly what we intended again\n","created-at":1339783113000,"updated-at":1421092637298,"_id":"542692d2c026201cdc326f98"},{"updated-at":1650763751893,"created-at":1633711183120,"author":{"login":"benjamin-asdf","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/38900087?v=4"},"body":"; useful during development when you want to log something\n; without changing the structure of your code\n\n(+\n (doto 42 println)\n 10)\n\n=> 52\n\n; similarly wrapping tap> in a threading macro for intermediate results\n\n(-> :hello\n {:hello \"Hello\"}\n (doto tap>) ; tap> \"Hello\"\n (str \" World!\"))\n\n=> \"Hello World!\"","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/38900087?v=4","account-source":"github","login":"benjamin-asdf"},{"login":"dgb23","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10947371?v=4"}],"_id":"6160744fe4b0b1e3652d7554"}],"macro":true,"notes":null,"arglists":["x & forms"],"doc":"Evaluates x then calls all of the methods and functions with the\n value of x supplied at the front of the given arguments. The forms\n are evaluated in order. Returns x.\n\n (doto (new java.util.HashMap) (.put \"a\" 1) (.put \"b\" 2))","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/doto"},{"added":"1.0","ns":"clojure.core","name":"identity","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1365638085000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"nil?","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e76"},{"created-at":1493319344537,"author":{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/94482?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"some?","ns":"clojure.core"},"_id":"59023eb0e4b01f4add58fe9e"},{"created-at":1544362967323,"author":{"login":"Ramblurr","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/14830?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"constantly","ns":"clojure.core"},"_id":"5c0d1bd7e4b0ca44402ef5e9"}],"line":1465,"examples":[{"author":{"login":"dpritchett","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/147981?v=3"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":"user=> (identity 4)\n4","created-at":1279071803000,"updated-at":1332950516000,"_id":"542692ccc026201cdc326c9a"},{"author":{"login":"cschreiner","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/93bff5e102f3d5bcc426e28e06c3c503?r=PG&default=identicon"},"editors":[{"login":"cschreiner","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/93bff5e102f3d5bcc426e28e06c3c503?r=PG&default=identicon"},{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":"user=> (filter identity [1 2 3 nil 4 false true 1234])\n(1 2 3 4 true 1234)","created-at":1279209894000,"updated-at":1332950531000,"_id":"542692ccc026201cdc326c9c"},{"author":{"login":"cschreiner","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/93bff5e102f3d5bcc426e28e06c3c503?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":"user=> (map #(%1 %2) (cycle [inc identity]) [1 2 3 4 5 6 7 8 9 10])\n(2 2 4 4 6 6 8 8 10 10)\n","created-at":1279209982000,"updated-at":1285500217000,"_id":"542692ccc026201cdc326c9f"},{"author":{"login":"cschreiner","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/93bff5e102f3d5bcc426e28e06c3c503?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":"user=> (partition-by identity (sort \"abcdaabccc\"))\n((\\a \\a \\a) (\\b \\b) (\\c \\c \\c \\c) (\\d))\n","created-at":1280212301000,"updated-at":1285501489000,"_id":"542692ccc026201cdc326ca1"},{"author":{"login":"shockbob","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon"},"editors":[],"body":"user=> (map first (partition-by identity [1 1 2 3 3 1 1 5 5]))\n(1 2 3 1 5)","created-at":1310849421000,"updated-at":1310849421000,"_id":"542692ccc026201cdc326ca3"},{"author":{"login":"OnesimusUnbound","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2fa4c391db0d2d1744cc2cd0d787dd3d?r=PG&default=identicon"},"editors":[],"body":"user=> (group-by identity \"abracadabra\")\n{\\a [\\a \\a \\a \\a \\a], \\b [\\b \\b], \\r [\\r \\r], \\c [\\c], \\d [\\d]}","created-at":1312216209000,"updated-at":1312216209000,"_id":"542692ccc026201cdc326ca4"},{"body":"user=> (map #(identity %) [1 2 3 4]) ; ~ (map (fn [x] x) [1 2 3 4])\n(1 2 3 4)","author":{"login":"protsenkovi","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/431393?v=3"},"created-at":1417761372684,"updated-at":1417761372684,"_id":"5481525ce4b03d20a10242c3"},{"updated-at":1539899393566,"created-at":1539899393566,"author":{"login":"peter-kehl","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/4270240?v=4"},"body":"; `identity` can serve in workarounds, because you can't pass a macro\n; to a function. For example, you can't pass `and` as a parameter to `apply`:\n(apply and '(true 1 \"yes\"))\n; \\=> CompilerException... Can't take value of a macro...\n\n; Instead:\n(every? identity '(true 1 \"yes\"))\n","_id":"5bc90001e4b00ac801ed9ee7"}],"notes":[{"updated-at":1280212784000,"body":"I don't quite see the usefulness of this :P","created-at":1280212784000,"author":{"login":"Jacolyte","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1703a0c3ed358b787f4b1bf3b2799472?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521f91"},{"updated-at":1313418353000,"body":"It's useful for example with -> macro when we eventually want to return its argument (in this case: state)\r\n\r\n\r\n\r\n(defn example[state]\r\n (-> state\r\n update-function-1\r\n update-function-2\r\n identity))","created-at":1313418233000,"author":{"login":"dturczanski","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/22c58e86fe0fa676e1fcbe71c1dba1bf?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fc5"},{"updated-at":1316077178000,"body":"Here is another good example:\r\n
(some identity ((juxt :foo :bar) {:bar :b}))
\r\nequivalent to \r\n
 (let [map {:bar b}] (or (:foo map) (:bar map)))","created-at":1316077178000,"author":{"login":"lancepantz","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9fbd3eb69f978b77c1bd66436971cdb2?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fcb"},{"body":"user=> (mapcat identity [[[0 1] [1 2]] [[11 12]]])\n([0 1] [1 2] [11 12])\n","created-at":1424195865165,"updated-at":1424195865165,"author":{"login":"tlightsky","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/429211?v=3"},"_id":"54e38119e4b0b716de7a652c"}],"arglists":["x"],"doc":"Returns its argument.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/identity"},{"added":"1.0","ns":"clojure.core","name":"into","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1399644560000,"author":{"login":"ryo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3f7913b563c72083c74030d928ba407e?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"conj","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c52"},{"created-at":1539774381439,"author":{"login":"witek","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/209520?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"concat","ns":"clojure.core"},"_id":"5bc717ade4b00ac801ed9edb"},{"created-at":1714062792131,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"assoc","ns":"clojure.core"},"_id":"662a85c869fbcc0c226174c1"}],"line":7029,"examples":[{"author":{"login":"Miki","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/52338b3d753f00bb7724f2d2ca060a4?r=PG&default=identicon"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"login":"cloojure","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1ad3de25d00d953de6e8c82f554cdbf5?r=PG&default=identicon"}],"body":"; Maps can be constructed from a sequence of 2-vectors or a sequence \n; of maps\nuser=> (into (sorted-map) [ [:a 1] [:c 3] [:b 2] ] )\n{:a 1, :b 2, :c 3}\nuser=> (into (sorted-map) [ {:a 1} {:c 3} {:b 2} ] )\n{:a 1, :b 2, :c 3}\n\n; When maps are the input source, they convert into an unordered sequence \n; of key-value pairs, encoded as 2-vectors\nuser=> (into [] {1 2, 3 4})\n[[1 2] [3 4]]\n","created-at":1278846273000,"updated-at":1404822264000,"_id":"542692cbc026201cdc326bac"},{"author":{"login":"cran1988","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/6261b9b7e6263f013dfb1330a43a501?r=PG&default=identicon"},"editors":[{"login":"cloojure","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1ad3de25d00d953de6e8c82f554cdbf5?r=PG&default=identicon"},{"avatar-url":"https://avatars.githubusercontent.com/u/4881607?v=3","account-source":"github","login":"sa2812"}],"body":"; Items are conj'ed one at a time, which puts them at the head of \n; the destination list\nuser=> (into () '(1 2 3))\n(3 2 1)\n\n; This does not happen for a vector, however, due to the behavior of conj:\nuser=> (into [1 2 3] '(4 5 6))\n[1 2 3 4 5 6]\n","created-at":1310276614000,"updated-at":1436264587298,"_id":"542692cbc026201cdc326baf"},{"updated-at":1514491228692,"created-at":1334632023000,"body":"(defn test-key-inclusion-cols\n  \"return all values in column1 that aren't in column2\"\n  [column1 column2]\n  (filter (complement (into #{} column2)) column1))\n","editors":[{"login":"jcburley","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/430319?v=4"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/fd31b8bcea99fa7b0711fbc424587774?r=PG&default=identicon","account-source":"clojuredocs","login":"octopusgrabbus"},"_id":"542692d3c026201cdc326fd8"},{"author":{"login":"cloojure","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1ad3de25d00d953de6e8c82f554cdbf5?r=PG&default=identicon"},"editors":[],"body":"; Change from one type of map to another\nuser=> (into (sorted-map) {:b 2 :c 3 :a 1})\n{:a 1, :b 2, :c 3}","created-at":1399534625000,"updated-at":1399534625000,"_id":"542692d3c026201cdc326fd9"},{"updated-at":1448739135641,"created-at":1448739135641,"author":{"login":"dxlr8r","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1648056?v=3"},"body":"; Convert a nested ordering map to hash-map (or another)\nuser=> (use 'flatland.ordered.map)\nuser=> (def ord-map (ordered-map :a \"a\" :b \"b\" :c {:d \"d\" :e \"e\"}))\nuser=> ord-map\n#ordered/map ([:a \"a\"] [:b \"b\"] [:c {:d \"d\", :e \"e\"}]) \n\nuser=> (use 'clojure.walk)\nuser=> (defn disorder [ordering-map map-fn] \n  (postwalk #(if (map? %) (into map-fn %) %) ordering-map))\n\nuser=> (disorder ord-map {})\n{:a \"a\", :b \"b\", :c {:d \"d\", :e \"e\"}}","_id":"565a013fe4b0be225c0c47a0"},{"updated-at":1458739828450,"created-at":1458739828450,"author":{"login":"ha0ck","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/3716736?v=3"},"body":";impl apply merge\nuser=> (into {:x 4} [{:a 1} {:b 2} {:c 3}])\n\n{:x 4, :a 1, :b 2, :c 3}","_id":"56f29a74e4b07ac9eeceed15"},{"updated-at":1462324693090,"created-at":1462324000684,"author":{"login":"fasiha","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/37649?v=3"},"body":";; How do we use a transducer?\n\n; Define the transducer with `comp` but in `->` order:\n(def xform (comp (map #(+ 2 %))\n                 (filter odd?)))\n; adds 2, then omits if result is even.\n\n(into [-1 -2] xform (range 10))\n; => [-1 -2 3 5 7 9 11]\n\n\n; Alternatively, using `transduce` directly:\n(transduce xform conj [-1 -2] (range 10))\n; => [-1 -2 3 5 7 9 11]\n\n; Alternatively, using reduce and explicitly calling `map` and `filter`:\n(reduce conj [-1 -2] (->> (range 10)\n                          (map #(+ 2 %))\n                          (filter odd?)))\n; => [-1 -2 3 5 7 9 11]\n\n\n;; Let's benchmark, using Criterium (https://github.com/hugoduncan/criterium)\n(require '[criterium.core :refer [quick-bench]])\n(quick-bench (into [-1 -2] xform (range 1000000)))\n;   Execution time lower quantile : 54.368948 ms ( 2.5%)\n;   Execution time upper quantile : 55.976303 ms (97.5%)\n\n(quick-bench (transduce xform conj [-1 -2] (range 1000000)))\n;   Execution time lower quantile : 77.738505 ms ( 2.5%)\n;   Execution time upper quantile : 87.088016 ms (97.5%): 1.5x slower than into\n\n(quick-bench (reduce conj [-1 -2] (->> (range 1000000) \n                                       (map #(+ 2 %))\n                                       (filter odd?))))\n;   Execution time lower quantile : 92.607522 ms ( 2.5%)\n;   Execution time upper quantile : 100.426780 ms (97.5%): 1.8x slower than into","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/37649?v=3","account-source":"github","login":"fasiha"}],"_id":"57294b20e4b050526f331420"},{"updated-at":1482220266209,"created-at":1482220266209,"author":{"login":"aksenov","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1590180?v=3"},"body":";; Interesting case you can't directly convert list or sequence into map (due performance reasons). One should use vector instead.\n\n;; This is ok:\n(into {} [[:a \"a\"] [:b \"b\"]])\n;;=> {:a \"a\", :b \"b\"}\n\n;; But this isn't:\n(into {} ['(:a \"a\") '(:b \"b\")])\n;;=> ClassCastException clojure.lang.Keyword cannot be cast to java.util.Map$Entry clojure.lang.ATransientMap.conj (ATransientMap.java:44)","_id":"5858e2eae4b004d3a355e2c8"},{"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"}],"body":";; merging two arrays using the transducer `cat`\n(into [] cat [[1 2 3 ] [4 5 6 ]])\n;=> [1 2 3 4 5 6]\n\n(into '() cat [[1 2 3 ] [4 5 6 ]])\n;=> (6 5 4 3 2 1)\n\n(into '() [1 2 3 4 5 6])\n;=> (6 5 4 3 2 1)","author":{"avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4","account-source":"github","login":"phreed"},"created-at":1517940935300,"updated-at":1519691300149,"_id":"5a79f0c7e4b0e2d9c35f741e"},{"editors":[{"login":"lsevero","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/3440467?v=4"}],"body":";Into is useful to concatenate vectors of maps\n(def a [{:a 1 :b 2} {:a 3 :b 4}])\n(def b [{:c \"c\" :d \"d\"} {:c \"cc\" :d \"dd\"}])\n\n(into a b)\n;=> [{:a 1, :b 2} {:a 3, :b 4} {:c \"c\", :d \"d\"} {:c \"cc\", :d \"dd\"}]\n\n;concat will return a similar result, but will be a lazy-seq instead of a vector","author":{"avatar-url":"https://avatars2.githubusercontent.com/u/3440467?v=4","account-source":"github","login":"lsevero"},"created-at":1582056539595,"updated-at":1582056838335,"_id":"5e4c445be4b0ca44402ef83d"},{"editors":[{"login":"littleli","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/544082?v=4"}],"body":";; Java 9 introduced immutable collections constructed with static 'of' methods\n;; These collections have specific implementation details and are used usually along with Java streams\n;; They cannot be used as operators like this (a-map :key)\n;; Use 'into' to convert them to Clojure collections with improved utility\n\n(into [] (java.util.List/of :a :b :c))\n;=> [:a :b :c]\n\n(into #{} (java.util.Set/of :a :b :c))\n;=> #{:c :b :a}\n\n(into {} (java.util.Map/of :a \"aa\" :b \"bb\" :c \"cc\"))\n;=> {:c \"cc\", :b \"bb\", :a \"aa\"}\n","author":{"avatar-url":"https://avatars0.githubusercontent.com/u/544082?v=4","account-source":"github","login":"littleli"},"created-at":1588591562483,"updated-at":1596476819086,"_id":"5eaffbcae4b087629b5a18fd"},{"updated-at":1600132004721,"created-at":1600132004721,"author":{"login":"luiszambon","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/41161270?v=4"},"body":"; into will return the coll type of the first parameter\n\n(def list-example '(1 2 3 4))\n;=> #'list-example\n(def vector-example [1 2 3 4])\n;=> #'vector-example\n(def set-example #{1 2 3 4})\n;=> #'set-example\n\n(class (into list-example vector-example))\n;=> clojure.lang.PersistentList\n(class (into vector-example list-example))\n;=> clojure.lang.PersistentVector\n(class (into set-example list-example))\n;=> clojure.lang.PersistentHashSet","_id":"5f6013a4e4b0b1e3652d73bd"},{"updated-at":1733862000838,"created-at":1733862000838,"author":{"login":"jacoobes","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/76754747?v=4"},"body":"; I like adding commas to encourage readability\n(def nums #{ 1 2 3 4 5})\n(into nums,  [5 6 7]) ;=> #{1 2 3 4 5 6 7}\n; commas are treated as whitespace\n(into nums   [5 6 7]) ;=> #{1 2 3 4 5 6 7}\n","_id":"6758a27069fbcc0c22617523"}],"notes":null,"arglists":["","to","to from","to xform from"],"doc":"Returns a new coll consisting of to with all of the items of\n  from conjoined. A transducer may be supplied.\n  (into x) returns x. (into) returns [].","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/into"},{"added":"1.0","ns":"clojure.core","name":"areduce","file":"clojure/core.clj","type":"macro","column":1,"see-alsos":[{"to-var":{"library-url":"https://github.com/clojure/clojure","name":"amap","ns":"clojure.core"},"author":{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},"created-at":1342853655000,"_id":"542692ebf6e94c6970521ec7"}],"line":5318,"examples":[{"updated-at":1446748965601,"created-at":1281617241000,"body":";; This should be about as quick as summing up a array of floats in java.\n\nuser=> (defn asum [^floats xs]\n         (areduce xs i ret (float 0)\n                  (+ ret (aget xs i))))\n\nuser=> (asum (float-array [1 2 3]))\n6.0\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"login":"cloojure","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7083783?v=3"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon","account-source":"clojuredocs","login":"gstamp"},"_id":"542692cec026201cdc326df8"}],"macro":true,"notes":[{"author":{"login":"KingMob","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/946421?v=4"},"updated-at":1698778125243,"created-at":1698778125243,"body":"Unlike `reduce`, `areduce` cannot be short-circuited with `(reduced)`. It's essentially a little macro that constructs a loop over all elements of an array. ","_id":"65414c0d69fbcc0c2261741e"}],"arglists":["a idx ret init expr"],"doc":"Reduces an expression across an array a, using an index named idx,\n  and return value named ret, initialized to init, setting ret to the \n  evaluation of expr at each step, returning ret.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/areduce"},{"added":"1.0","ns":"clojure.core","name":"long","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"to-var":{"library-url":"https://github.com/clojure/clojure","name":"int","ns":"clojure.core"},"author":{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},"created-at":1342917169000,"_id":"542692eaf6e94c6970521b73"},{"to-var":{"library-url":"https://github.com/clojure/clojure","name":"longs","ns":"clojure.core"},"author":{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},"created-at":1342917368000,"_id":"542692eaf6e94c6970521b74"},{"to-var":{"library-url":"https://github.com/clojure/clojure","name":"long-array","ns":"clojure.core"},"author":{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},"created-at":1342917373000,"_id":"542692eaf6e94c6970521b75"},{"created-at":1496088186511,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"unchecked-long","ns":"clojure.core"},"_id":"592c7e7ae4b093ada4d4d79c"},{"created-at":1734339241198,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"parse-long","ns":"clojure.core"},"_id":"675feaa969fbcc0c22617525"}],"line":3506,"examples":[{"author":{"login":"zmila","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/68dd6f50915854aa04fefcf4d6fa5c8e?r=PG&default=identicon"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"login":"rand0m86","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/aa88f28de4d9335e744f8d10d5ebf8a6?r=PG&default=identicon"},{"login":"rand0m86","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/aa88f28de4d9335e744f8d10d5ebf8a6?r=PG&default=identicon"}],"body":"v.1.3.0\nuser=> (let [num (* 1234567890 21)] [num (int num) (long num)])\n[25925925690 156121914 25925925690]\n\nv.1.6.0\nuser=> (let [num (* 1234567890 21)] [num (int num) (long num)])\nIllegalArgumentException Value out of range for int: 25925925690","created-at":1281031682000,"updated-at":1406257844000,"_id":"542692c7c026201cdc326992"},{"author":{"login":"zmila","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/68dd6f50915854aa04fefcf4d6fa5c8e?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"rand0m86","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/aa88f28de4d9335e744f8d10d5ebf8a6?r=PG&default=identicon"},{"login":"rand0m86","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/aa88f28de4d9335e744f8d10d5ebf8a6?r=PG&default=identicon"}],"body":"v.1.3.0\nuser=> (= 21 (long 21))\ntrue \n\n;; but\nuser=> (.equals 21 (long 21))\nfalse \n\n;; and thus\nuser=> (get {21 :twenty-one} (long 21))\nnil \n\nv.1.6.0\nuser=> (= 21 (long 21))\ntrue \n\nuser=> (.equals 21 (long 21))\ntrue\n\nuser=> (.equals 21.0 (long 21))\nfalse\n\nuser=> (.equals (long 21.0) (long 21)) \ntrue","created-at":1281031694000,"updated-at":1406257882000,"_id":"542692c7c026201cdc326996"},{"editors":[{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"}],"body":"(long 123)\n;;=> 123\n\n(long 1.23)\n;;=> 1\n\n(long 1.2345678901234567890)\n;;=> 1\n\n(long -1)\n;;=> -1\n\n;; Casting a string does not work\n(long \"123\")\n;;=> Execution error (ClassCastException) at user/eval187 (REPL:1).\n;;java.lang.String cannot be cast to java.lang.Number\n\n;; Use parse-long instead\n(parse-long \"123\")\n;;=> 123\n\n;; Content originally posted by u/didibus on https://clojuredocs.org/clojure.core/num","author":{"avatar-url":"https://avatars0.githubusercontent.com/u/4631165?v=4","account-source":"github","login":"wdhowe"},"created-at":1596590278008,"updated-at":1734339282707,"_id":"5f2a08c6e4b0b1e3652d7361"}],"notes":[{"updated-at":1394070050000,"body":"the second example is no longer true.","created-at":1394070050000,"author":{"login":"clojureking","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/92625b8a6be91bb8c688d0d07b4e2a32?r=PG&default=identicon"},"_id":"542692edf6e94c6970522020"}],"arglists":["x"],"doc":"Coerce to long","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/long"},{"added":"1.0","ns":"clojure.core","name":"double","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1579780040730,"author":{"login":"Hindol","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/705227?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"float","ns":"clojure.core"},"_id":"5e2987c8e4b0ca44402ef81c"},{"created-at":1579780063873,"author":{"login":"Hindol","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/705227?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"bigdec","ns":"clojure.core"},"_id":"5e2987dfe4b0ca44402ef81d"},{"created-at":1734339323390,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"parse-double","ns":"clojure.core"},"_id":"675feafb69fbcc0c22617527"}],"line":3518,"examples":[{"author":{"login":"Miles","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bbb26d2a5e856c4fba0f72c3f7250f3f?r=PG&default=identicon"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":"user=> (double 1)\n1.0","created-at":1283814485000,"updated-at":1332952958000,"_id":"542692cec026201cdc326ddb"},{"updated-at":1522204835943,"created-at":1522204835943,"author":{"login":"yuxuan813","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/22159831?v=4"},"body":";; Ratios can be explicitly coerced to a floating-point representation:\nuser=> (double 1/3)\n;= 0.3333333333333333","_id":"5abb00a3e4b045c27b7fac28"},{"editors":[{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"}],"body":";; Casting a string does not work\n(double \"123.456\")\n;;=> Execution error (ClassCastException) at user/eval197 (REPL:1).\n;;java.lang.String cannot be cast to java.lang.Number\n\n;; Use parse-double instead\n(parse-double \"123.456\")\n;;=> 123.456\n\n;; Content originally posted by u/didibus on https://clojuredocs.org/clojure.core/num","author":{"avatar-url":"https://avatars0.githubusercontent.com/u/4631165?v=4","account-source":"github","login":"wdhowe"},"created-at":1596590762065,"updated-at":1734339339867,"_id":"5f2a0aaae4b0b1e3652d7366"}],"notes":null,"arglists":["x"],"doc":"Coerce to double","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/double"},{"added":"1.7","ns":"clojure.core","name":"volatile?","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1437146147516,"author":{"login":"claj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/353113?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"volatile!","ns":"clojure.core"},"_id":"55a91c23e4b0080a1b79cda6"},{"created-at":1492395420814,"author":{"login":"didibus","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/601540?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"vswap!","ns":"clojure.core"},"_id":"58f4259ce4b01f4add58fe8e"},{"created-at":1492395448747,"author":{"login":"didibus","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/601540?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"vreset!","ns":"clojure.core"},"_id":"58f425b8e4b01f4add58fe8f"}],"line":2565,"examples":[{"editors":[{"login":"ertugrulcetin","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8271291?v=3"}],"body":"(def a (volatile! 0))\n\nuser=> (volatile? a)\n;;=> true\n\n(def b 0)\n\nuser=> (volatile? b)\n;;=> false","author":{"avatar-url":"https://avatars.githubusercontent.com/u/8271291?v=3","account-source":"github","login":"ertugrulcetin"},"created-at":1460034117197,"updated-at":1460034139185,"_id":"57065a45e4b075f5b2c864cf"}],"notes":null,"arglists":["x"],"doc":"Returns true if x is a volatile.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/volatile_q"},{"added":"1.11","ns":"clojure.core","name":"update-vals","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1698251679030,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"update-keys","ns":"clojure.core"},"_id":"6539439f69fbcc0c226173d0"}],"line":8132,"examples":[{"updated-at":1698251589460,"created-at":1698251589460,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":"(update-vals {:a 1, :b 2} inc)\n;; => {:a 2, :b 3}\n\n;; To replace each map with its value for a specific key…\n(update-vals {:a {:x 7, :y 100}, :b {:x 8, :y 150}, :c {:x 9, :y 200}} :x)\n;; => {:a 7, :b 8, :c 9}\n\n;; To dissoc a kv pair from each map…\n(update-vals {:a {:x 7, :y 100}, :b {:x 8, :y 150}, :c {:x 9, :y 200}}\n             #(dissoc % :x))\n;; => {:a {:y 100}, :b {:y 150}, :c {:y 200}}\n\n;; To update a value for a key in each map…\n(update-vals {:a {:x 7, :y 100}, :b {:x 8, :y 150}, :c {:x 9, :y 200}}\n             #(update % :x inc))\n;; => {:a {:x 8, :y 100}, :b {:x 9, :y 150}, :c {:x 10, :y 200}}\n","_id":"6539434569fbcc0c226173cf"}],"notes":null,"arglists":["m f"],"doc":"m f => {k (f v) ...}\n\n  Given a map m and a function f of 1-argument, returns a new map where the keys of m\n  are mapped to result of applying f to the corresponding values of m.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/update-vals"},{"added":"1.0","ns":"clojure.core","name":"definline","file":"clojure/core.clj","type":"macro","column":1,"see-alsos":[{"created-at":1612735270827,"author":{"login":"KingMob","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/946421?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"defmacro","ns":"clojure.core"},"_id":"60206326e4b0b1e3652d744b"}],"line":5282,"examples":null,"macro":true,"notes":[{"updated-at":1354753534000,"body":"Note that, as for macros, the arguments to definline are potentially subject to double evaluation if they are used more than once in the body. For example:\r\n\r\n
\r\nuser=> (definline bad-sqr [x] `(* ~x ~x))\r\n#'user/bad-sqr\r\nuser=> (bad-sqr (do (println \"x\") 5))\r\nx\r\nx\r\n25\r\n
\r\n\r\n","created-at":1354753534000,"author":{"login":"glchapman","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a5176d5d971ba68c15f4afe376aeaf18?r=PG&default=identicon"},"_id":"542692edf6e94c6970521ff8"},{"updated-at":1385846788000,"body":"Any non-like-a-function behaviour should be avoided, because otherwise function will behave differently depending on whether it's inlined or not:\r\n\r\n user=> (definline bad-if [cond then] `(if ~cond ~then))\r\n #'user/bad-if\r\n user=> (bad-if nil (do (prn :side-effect) :not-returned))\r\n nil\r\n user=> (let [bad-if bad-if] (bad-if nil (do (prn :side-effect) :not-returned)))\r\n :side-effect\r\n nil\r\n","created-at":1385846788000,"author":{"login":"Alexey Tarasevich","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/43e0398b89022d32b43de4c968069312?r=PG&default=identicon"},"_id":"542692edf6e94c6970522013"}],"arglists":["name & decl"],"doc":"Experimental - like defmacro, except defines a named function whose\n body is the expansion, calls to which may be expanded inline as if\n it were a macro. Cannot be used with variadic (&) args.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/definline"},{"added":"1.0","ns":"clojure.core","name":"nfirst","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1343067247000,"author":{"login":"john.r.woodward","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/22b6fbc4a386291e45b1cb4449377086?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"next","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521eb5"},{"created-at":1482184108272,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"first","ns":"clojure.core"},"_id":"585855ace4b004d3a355e2c3"},{"created-at":1482184112724,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"ffirst","ns":"clojure.core"},"_id":"585855b0e4b004d3a355e2c4"},{"created-at":1482184132251,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"fnext","ns":"clojure.core"},"_id":"585855c4e4b004d3a355e2c5"},{"created-at":1482184136369,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"nnext","ns":"clojure.core"},"_id":"585855c8e4b004d3a355e2c6"}],"line":107,"examples":[{"author":{"login":"zmila","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/68dd6f50915854aa04fefcf4d6fa5c8e?r=PG&default=identicon"},"editors":[{"login":"zmila","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/68dd6f50915854aa04fefcf4d6fa5c8e?r=PG&default=identicon"},{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":"user=> (nfirst [])\nnil \n\nuser=> (nfirst ['(a b c) '(b a c) '(c b a) '(a c b)])\n(b c)\n\nuser=> (nfirst {:a 1, :b 2, :c 3, :d 4})\n(1)\n\nuser=> (nfirst #{1 2 3})\njava.lang.IllegalArgumentException: Don't know how to create ISeq from: java.lang.Integer (NO_SOURCE_FILE:0)","created-at":1281033567000,"updated-at":1332950990000,"_id":"542692cec026201cdc326d83"}],"notes":null,"arglists":["x"],"doc":"Same as (next (first x))","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/nfirst"},{"added":"1.0","ns":"clojure.core","name":"meta","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1302719092000,"author":{"login":"dnaumov","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/361cb3cfa29928ddff4c49cbb5ad0cbd?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"with-meta","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ec0"},{"created-at":1302719254000,"author":{"login":"dnaumov","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/361cb3cfa29928ddff4c49cbb5ad0cbd?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"*print-meta*","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ec1"},{"created-at":1489661787389,"author":{"login":"delonnewman","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/10404?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"vary-meta","ns":"clojure.core"},"_id":"58ca6f5be4b01f4add58fe75"}],"line":204,"examples":[{"author":{"login":"devn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3"},"editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3","account-source":"github","login":"devn"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":"(use 'clojure.pprint)\n(pprint (meta #'first))\n;;=> prints the following...\n{:ns #,\n :name first,\n :added \"1.0\",\n :file \"clojure/core.clj\",\n :static true,\n :column 1,\n :line 49,\n :arglists ([coll]),\n :doc\n \"Returns the first item in the collection. Calls seq on its\\n \n argument. If coll is nil, returns nil.\"}","created-at":1280777073000,"updated-at":1434396446014,"_id":"542692cfc026201cdc326e8f"},{"updated-at":1519676797874,"created-at":1519670280917,"author":{"login":"finalfantasia","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/2316604?v=4"},"body":";; attach metadata to s.\n;; ^:private is a shorthand notation for ^{:private true} and\n;; ^String is a shorthand notation for ^{:tag java.lang.String}.\n(def ^:private ^String s \"Hello, world!\")\n\n;; inspect the metadata attached to s.\n;; note, you need to use the var #'s, instead of the symbol s, as the argument.\n(clojure.pprint/pprint (meta #'s))\n;; =>\n{:private true,\n :tag java.lang.String,\n :line 3,\n :column 1,\n :file \"/tmp/form-init5430922801479403331.clj\",\n :name s,\n :ns #object[clojure.lang.Namespace 0x13fca031 \"user\"]}\n","editors":[{"avatar-url":"https://avatars3.githubusercontent.com/u/2316604?v=4","account-source":"github","login":"finalfantasia"}],"_id":"5a945408e4b0316c0f44f8f0"},{"editors":[{"login":"randomizedthinking","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/5283430?v=4"}],"body":";; attach metadata to var x\n(def ^{:version 1} x [1 2 3])\n\n;; retrieve metadata of var x: note the notation\n(meta #'x)\n;; =>\n{:version 1,\n :line 3,\n :column 1,\n :file \"...\",\n :name x,\n :ns ...}\n\n;; attach metadata to an obj\n(def y ^{:version 1} [1 2 3])\n\n(meta y) ;=> {:version 1}\n","author":{"avatar-url":"https://avatars.githubusercontent.com/u/5283430?v=4","account-source":"github","login":"randomizedthinking"},"created-at":1670874928008,"updated-at":1670875211552,"_id":"63978730e4b0b1e3652d7699"}],"notes":null,"arglists":["obj"],"doc":"Returns the metadata of obj, returns nil if there is no metadata.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/meta"},{"ns":"clojure.core","name":"find-protocol-impl","file":"clojure/core_deftype.clj","type":"function","column":1,"see-alsos":null,"line":537,"examples":null,"notes":null,"arglists":["protocol x"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core/find-protocol-impl"},{"added":"1.0","ns":"clojure.core","name":"bit-and-not","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":null,"line":1334,"examples":[{"author":{"login":"zmila","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/68dd6f50915854aa04fefcf4d6fa5c8e?r=PG&default=identicon"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":"user=> (bit-and-not 2r1100 2r1001) ; (and X (not Y))\n4\n;; 4 = 2r0100","created-at":1280339735000,"updated-at":1332952979000,"_id":"542692cfc026201cdc326e25"},{"body":";; here is the truth table for AND-NOT (which is not the same as NAND) \n(Integer/toBinaryString (bit-and-not 2r1100 2r1010) )\n;;=> \"100\"\n;; or 2r0100\n\n;; NAND would be...\n(Integer/toBinaryString (bit-not (bit-and 2r1100 2r1010)) )\n;;=> \"11111111111111111111111111110111\"\n;; which is clearly not the same\n\n;; this operation is material non-implication\n(= (bit-and-not 2r1100 2r1010) (bit-and 2r1100 (bit-not 2r1010)) )\n;;=> true\n","author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"},"created-at":1414515398672,"updated-at":1414515782150,"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"}],"_id":"544fcac6e4b03d20a1024296"},{"updated-at":1666990058605,"created-at":1666990058605,"author":{"login":"bhlieberman","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/60364696?v=4"},"body":";;flip the bits of a seq\n(map (fn [n] (bit-and-not 0xff n)) (range 1 10)) ; ~n & 0xff\n;;=> (254 253 252 251 250 249 248 247 246)\n","_id":"635c3feae4b0b1e3652d767d"}],"notes":null,"arglists":["x y","x y & more"],"doc":"Bitwise and with complement","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/bit-and-not"},{"added":"1.5","ns":"clojure.core","name":"*default-data-reader-fn*","file":"clojure/core.clj","type":"var","column":1,"see-alsos":[{"created-at":1529611952524,"author":{"login":"puredanger","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/171129?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"*data-readers*","ns":"clojure.core"},"_id":"5b2c06b0e4b00ac801ed9e1a"},{"created-at":1529611964217,"author":{"login":"puredanger","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/171129?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"tagged-literal","ns":"clojure.core"},"_id":"5b2c06bce4b00ac801ed9e1b"}],"dynamic":true,"line":8025,"examples":[{"editors":[{"login":"puredanger","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/171129?v=4"}],"body":";; Clojure includes a generic tagged-literal type, able to read any\n;; tagged literal. This makes a great default-data-reader-fn.\n\n;; Clojure can't read tagged literals without a registered reader:\nuser=> #object[clojure.lang.Namespace 0x23bff419 \"user\"]\nRuntimeException No reader function for tag object clojure.lang.LispReader$CtorReader.readTagged (LispReader.java:1430)\n\n;; Set tagged-literal to be the default tagged value reader:\nuser=> (set! *default-data-reader-fn* tagged-literal)\n\n;; Try again\nuser=> #object[clojure.lang.Namespace 0x23bff419 \"user\"]\n#object [clojure.lang.Namespace 599782425 \"user\"]\n\n;; Now it works, and reads to a TaggedLiteral object, which\n;; supports ILookup on :tag and :form keys\nuser=> [(:tag *1) (:form *1)]\n[object [clojure.lang.Namespace 599782425 \"user\"]]\n","author":{"avatar-url":"https://avatars0.githubusercontent.com/u/171129?v=4","account-source":"github","login":"puredanger"},"created-at":1529611907877,"updated-at":1529636650211,"_id":"5b2c0683e4b00ac801ed9e19"}],"notes":null,"arglists":[],"doc":"When no data reader is found for a tag and *default-data-reader-fn*\n is non-nil, it will be called with two arguments,\n the tag and the value. If *default-data-reader-fn* is nil (the\n default), an exception will be thrown for the unknown tag.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/*default-data-reader-fn*"},{"added":"1.0","ns":"clojure.core","name":"var?","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1289214474000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"def","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521dc9"},{"created-at":1289214479000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"var","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521dca"},{"created-at":1362015178000,"author":{"login":"AtKaaZ","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e10dfa345f44b0fe72bbe081fd51b83?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"var-get","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521dcc"},{"created-at":1362015184000,"author":{"login":"AtKaaZ","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e10dfa345f44b0fe72bbe081fd51b83?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"var-set","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521dcd"},{"created-at":1362015190000,"author":{"login":"AtKaaZ","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e10dfa345f44b0fe72bbe081fd51b83?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"with-local-vars","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521dce"}],"line":5028,"examples":[{"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"editors":[],"body":"(def my-symbol)\n(var? #'my-symbol)\n=> true\n\n(var? (var my-symbol))\n=> true\n\n(var? (def my-symbol2))\n=> true","created-at":1289214469000,"updated-at":1289214469000,"_id":"542692cac026201cdc326b63"},{"author":{"login":"AtKaaZ","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e10dfa345f44b0fe72bbe081fd51b83?r=PG&default=identicon"},"editors":[],"body":"=> *clojure-version*\n{:major 1, :minor 5, :incremental 0, :qualifier \"RC17\"}\n=> var?\n#\n=> (var?)\n;ArityException Wrong number of args (0) passed to: core$var-QMARK- clojure.lang.AFn.throwArity (AFn.java:437)\n=> (var? 1)\nfalse\n=> (var? defn)\n;CompilerException java.lang.RuntimeException: Can't take value of a macro: #'clojure.core/defn, compiling:(NO_SOURCE_PATH:1:1) \n=> (var? #'defn)\ntrue\n=> (var? #'defn 1 2 3 4)\n;ArityException Wrong number of args (5) passed to: core$var-QMARK- clojure.lang.AFn.throwArity (AFn.java:437)\n=> (var? (var defn))\ntrue\n=> (var? apply)\nfalse\n=> (var? #'apply)\ntrue\n","created-at":1362015139000,"updated-at":1362015139000,"_id":"542692d5c026201cdc3270b2"}],"notes":null,"arglists":["v"],"doc":"Returns true if v is of type clojure.lang.Var","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/var_q"},{"ns":"clojure.core","name":"method-sig","file":"clojure/core_proxy.clj","type":"function","column":1,"see-alsos":null,"line":20,"examples":[{"updated-at":1682607087713,"created-at":1496052873728,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"body":";;;; (method-sig) turns java.lang.reflect.Method into a vector \n;;;; of the form [name (param-types) return-type]\n\n(->> String .getMethods (filter #(= (.getName %) \"indexOf\")))\n;;=> (#object[java.lang.reflect.Method 0x4a499a6c \"public int java.lang.String.indexOf(java.lang.String,int)\"]\n;; #object[java.lang.reflect.Method 0x29b045b3 \"public int java.lang.String.indexOf(int)\"]\n;; #object[java.lang.reflect.Method 0x55ce8ae4 \"public int java.lang.String.indexOf(java.lang.String)\"]\n;; #object[java.lang.reflect.Method 0x33a58323 \"public int java.lang.String.indexOf(int,int)\"])\n\n(->> String .getMethods (filter #(= (.getName %) \"indexOf\")) (map method-sig))\n;;=> ([\"indexOf\" (java.lang.String int) int]\n;; [\"indexOf\" (int) int]\n;; [\"indexOf\" (java.lang.String) int]\n;; [\"indexOf\" (int int) int])","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4","account-source":"github","login":"tomdl89"}],"_id":"592bf489e4b093ada4d4d791"}],"notes":null,"arglists":["meth"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core/method-sig"},{"added":"1.0","ns":"clojure.core","name":"unchecked-add-int","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1423522083291,"author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"to-var":{"ns":"clojure.core","name":"+","library-url":"https://github.com/clojure/clojure"},"_id":"54d93923e4b0e2ac61831d2d"},{"created-at":1423522088305,"author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"to-var":{"ns":"clojure.core","name":"+'","library-url":"https://github.com/clojure/clojure"},"_id":"54d93928e4b081e022073c73"},{"created-at":1488034480881,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"unchecked-subtract-int","ns":"clojure.core"},"_id":"58b19ab0e4b01f4add58fe63"}],"line":1205,"examples":[{"updated-at":1488034461415,"created-at":1488034461415,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10583730?v=3"},"body":";; Adding two int-range Longs works\n(unchecked-add-int 1 1)\n;;=> 2\n\n;; Adding two int-range BigInts works\n(unchecked-add-int 1N 1N)\n;;=> 2\n\n;; Doubles are truncated\n(unchecked-add-int 1 1.9)\n;;=> 2\n\n;; BigDecimals are truncated\n(unchecked-add-int 1 1.9M)\n;;=> 2\n\n;; Uncaught integer overflow\n(unchecked-add-int Integer/MAX_VALUE 1)\n;;=> -2147483648\n\n;; Uncaught integer underflow\n(unchecked-add-int Integer/MIN_VALUE -1)\n;;=> 2147483647\n\n;; Fails for Longs outside of int range\n(unchecked-add-int 2147483648 0)\n;;=> IllegalArgumentException Value out of range for int: 2147483648 clojure.lang.RT.intCast (RT.java:1205)\n\n;; Fails for BigInts outside of int range\n(unchecked-add-int 2147483648N 0)\n;;=> IllegalArgumentException Value out of range for int: 2147483648 clojure.lang.RT.intCast (RT.java:1205)\n\n;; Fails for Doubles outside of int range\n(unchecked-add-int 2147483648.0 0)\n;;=> IllegalArgumentException Value out of range for int: 2147483648 clojure.lang.RT.intCast (RT.java:1205)\n\n;; Fails for BigDecimals outside of int range\n(unchecked-add-int 2147483648.0M 0)\n;;=> IllegalArgumentException Value out of range for int: 2147483648 clojure.lang.RT.intCast (RT.java:1205)","_id":"58b19a9de4b01f4add58fe62"}],"notes":null,"arglists":["x y"],"doc":"Returns the sum of x and y, both int.\n Note - uses a primitive operator subject to overflow.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/unchecked-add-int"},{"ns":"clojure.core","name":"unquote-splicing","file":"clojure/core.clj","type":"var","column":1,"see-alsos":[{"created-at":1319195960000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"unquote","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d37"}],"line":14,"examples":[{"author":{"login":"huahaiy","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/889685?v=2"},"editors":[],"body":"user=> (let [x `(2 3)] \n `(1 ~x))\n(1 (2 3))\n\nuser=> (let [x `(2 3)] \n `(1 ~@x)) \n(1 2 3)\n","created-at":1305077817000,"updated-at":1305077817000,"_id":"542692c8c026201cdc326a73"},{"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"editors":[],"body":"user=> `(1 2 ~(list 3 4))\n\n(1 2 (3 4))\n\nuser=> `(1 2 ~@(list 3 4))\n\n(1 2 3 4)\n\n; borrowed from StackOverflow: \n; http://stackoverflow.com/questions/4571042/can-someone-explain-clojures-unquote-splice-in-simple-terms","created-at":1319196585000,"updated-at":1319196585000,"_id":"542692d5c026201cdc3270b0"},{"editors":[{"login":"green-coder","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/598193?v=4"}],"body":";; The splicing works at any location in the enclosing structure.\n`(1 ~@(list 2 3) 4 ~@(list 5 6) 7)\n=> (1 2 3 4 5 6 7)\n\n;; The enclosing structure can be a list, a vector or a set.\n`[1 ~@(list 2 3) 4 ~@(list 5 6) 7]\n=> [1 2 3 4 5 6 7]\n\n`#{1 ~@(list 2 3) 4 ~@(list 5 6) 7}\n=> #{7 1 4 6 3 2 5}\n\n;; The splicing produces a sequence from any `sequential?` value.\n`(1 ~@'(2 3) 4 ~@[5 6] 7 ~@(range 8 10))\n=> (1 2 3 4 5 6 7 8 9)\n\n`(1 ~@{2 3 4 5} 6)\n=> (1 [2 3] [4 5] 6)\n\n;; It currently does not work well inside maps.\n;; https://dev.clojure.org/jira/browse/CLJ-1425\n`{1 2 ~@[3 4]}\nSyntax error reading source at (REPL:1:15).\nMap literal must contain an even number of forms\n\n`{1 ~@[2 3] 4 ~@[5 6]}\n=> {1 2, 3 4, 5 6}\n\n;; Workaround: don't use the map literals\n`(hash-map 1 2 ~@[3 4])\n=> (clojure.core/hash-map 1 2 3 4)","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/598193?v=4","account-source":"github","login":"green-coder"},"created-at":1547668738996,"updated-at":1547671826780,"_id":"5c3f8d02e4b0ca44402ef61c"}],"notes":null,"arglists":[],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core/unquote-splicing"},{"added":"1.6","ns":"clojure.core","name":"hash-ordered-coll","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1495656275875,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"hash-unordered-coll","ns":"clojure.core"},"_id":"5925e753e4b093ada4d4d744"},{"created-at":1495656285147,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"hash","ns":"clojure.core"},"_id":"5925e75de4b093ada4d4d745"}],"line":5239,"examples":[{"updated-at":1495656268428,"created-at":1495656268428,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"body":";;;; Clojure's (hash-ordered-coll) produces the same hash code regardless\n;;;; of collection type when both of the following two conditions are met:\n;;;; (1) collections contain the same elements\n;;;; (2) collection elements are ordered the same when returned by .iterator()\n\n(hash-ordered-coll [1 2])\n;;=> 156247261\n(hash-ordered-coll '(1 2))\n;;=> 156247261\n(hash-ordered-coll (sorted-set 1 2))\n;;=> 156247261\n(hash-ordered-coll (doto (new java.util.ArrayList) (.add 1) (.add 2)))\n;;=> 156247261\n(hash-ordered-coll (doto (new java.util.TreeSet) (.add 1) (.add 2)))\n;;=> 156247261\n\n(hash-ordered-coll [2 1])\n;;=> -1994590503\n(hash-ordered-coll '(2 1))\n;;=> -1994590503\n(hash-ordered-coll (sorted-set-by > 2 1))\n;;=> -1994590503\n(hash-ordered-coll (doto (new java.util.ArrayList) (.add 2) (.add 1)))\n;;=> -1994590503\n(hash-ordered-coll (doto (new java.util.TreeSet >) (.add 2) (.add 1)))\n;;=> -1994590503\n\n;;;; Notice that this differs from (hash) which \n;;;; (1) doesn't rely on element order as returned by .iterator()\n;;;; (2) falls back on Java's .hashCode() for non-Clojure collections\n\n(hash [1 2])\n;;=> 156247261\n(hash '(1 2))\n;;=> 156247261\n(hash (sorted-set 1 2))\n;;=> 460223544\n(hash (sorted-set-by > 2 1))\n;;=> 460223544\n(hash (doto (new java.util.ArrayList) (.add 1) (.add 2)))\n;;=> 994\n(hash (doto (new java.util.TreeSet) (.add 1) (.add 2)))\n;;=> 3\n","_id":"5925e74ce4b093ada4d4d743"},{"updated-at":1495657079980,"created-at":1495657079980,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"body":";;;;\n;;;; Only accepts implementations of java.lang.Iterable\n;;;;\n\n(hash-ordered-coll true)\n;;=> ClassCastException java.lang.Boolean cannot be cast to java.lang.Iterable\n(hash-ordered-coll 1)\n;;=> ClassCastException java.lang.Long cannot be cast to java.lang.Iterable\n(hash-ordered-coll \\c)\n;;=> ClassCastException java.lang.Character cannot be cast to java.lang.Iterable\n\n;;;;\n;;;; Being seqable is not sufficient!\n;;;;\n\n(hash-ordered-coll \"12\")\n;;=> ClassCastException java.lang.String cannot be cast to java.lang.Iterable\n(hash-ordered-coll (int-array [1 2]))\n;;=> ClassCastException [I cannot be cast to java.lang.Iterable\n(hash-ordered-coll nil)\n;;=> NullPointerException","_id":"5925ea77e4b093ada4d4d747"}],"notes":null,"arglists":["coll"],"doc":"Returns the hash code, consistent with =, for an external ordered\n collection implementing Iterable.\n See http://clojure.org/data_structures#hash for full algorithms.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/hash-ordered-coll"},{"added":"1.1","ns":"clojure.core","name":"future","file":"clojure/core.clj","type":"macro","column":1,"see-alsos":[{"created-at":1332389737000,"author":{"login":"abrooks","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/69976?v=2"},"to-var":{"ns":"clojure.core","name":"future-cancel","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c95"},{"created-at":1336536261000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.core","name":"shutdown-agents","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c96"},{"created-at":1349259124000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"promise","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c97"},{"created-at":1349558136000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"realized?","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c98"},{"created-at":1291441344000,"author":{"login":"pauldoo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5cb916d3c8abc9f45a093209e72489fb?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"delay","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e73"},{"created-at":1291473035000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"future?","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e74"},{"created-at":1300437104000,"author":{"login":"ninjudd","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/7ced25585a7556e9b9b975c1f9e136e3?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"future-call","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e75"},{"created-at":1413483298913,"author":{"login":"Chort409","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1062637?v=2"},"to-var":{"ns":"clojure.core","name":"future-done?","library-url":"https://github.com/clojure/clojure"},"_id":"54400b22e4b05802a3cc25dc"},{"created-at":1537551889359,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"locking","ns":"clojure.core"},"_id":"5ba52e11e4b00ac801ed9ea3"}],"line":7137,"examples":[{"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"azkesz","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/467196a4f2498080c9740a81fcbde855?r=PG&default=identicon"},{"login":"azkesz","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/467196a4f2498080c9740a81fcbde855?r=PG&default=identicon"},{"login":"azkesz","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/467196a4f2498080c9740a81fcbde855?r=PG&default=identicon"},{"login":"yayitswei","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/179c73a6ff978b738c014abeb1ead0f9?r=PG&default=identicon"},{"login":"luke","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/ac463e1534de6c3a7bbe42365286cd?r=PG&default=identicon"}],"body":";; A future's calculation is started here and it runs in another thread\nuser=> (def f (future (Thread/sleep 10000) (println \"done\") 100))\n#'user/f\n;;if you wait 10 seconds before dereferencing it you'll see \"done\"\n\n;; When you dereference it you will block until the result is available.\nuser=> @f\ndone\n100\n\n;; Dereferencing again will return the already calculated value.\n=> @f\n100\n","created-at":1281077331000,"updated-at":1346904770000,"_id":"542692c9c026201cdc326a74"},{"author":{"login":"OnesimusUnbound","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2fa4c391db0d2d1744cc2cd0d787dd3d?r=PG&default=identicon"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"login":"yayitswei","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/179c73a6ff978b738c014abeb1ead0f9?r=PG&default=identicon"},{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"avatar-url":"https://avatars.githubusercontent.com/u/2139?v=3","account-source":"github","login":"jamieorc"},{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"}],"body":";; save the example in a script (e.g. test-future.clj) then run it in the console\n;;\n;; > clojure test-future.clj\n\n(println \"[Main] calculate the answer to life the universe and everything\")\n\n;; Used Thread/sleep to simulate long running process\n(def what-is-the-answer-to-life\n (future \n (println \"[Future] started computation\")\n (Thread/sleep 3000) ;; running for 3 seconds\n (println \"[Future] completed computation\")\n 42))\n \n(println \"[Main] created future\")\n\n(Thread/sleep 1000)\n(println \"[Main] do other things while waiting for the answer\")\n(println \"[Main] get the answer\")\n(println \"[Main] the result\" @what-is-the-answer-to-life)\n(shutdown-agents)\n\n\n;; You may get something like this\n;;\n;; [Main] calculate the answer to life, the universe and everything\n;; [Future] started computation\n;; [Main] created future\n;; [Main] do other things while waiting for the answer\n;; [Main] get the answer\n;; [Future] completed computation\n;; [Main] the result 42\n\n\n;; Note: If you leave out the call to (shutdown-agents), the program\n;; will on most (all?) OS/JVM combinations \"hang\" for 1 minute before\n;; the process exits. It is waiting for a thread created by the\n;; future call to be shut down. shutdown-agents will shut them down\n;; immediately, or (System/exit ) will exit immediately\n;; without waiting for them to shut down.\n\n;; This wait occurs even if you use futures indirectly through some other Clojure\n;; functions that use them internally, such as pmap or clojure.java.shell/sh\n\n;; http://dev.clojure.org/jira/browse/CLJ-124 is a ticket opened against Clojure,\n;; as this 1-minute wait is not considered desirable behavior.","created-at":1312375403000,"updated-at":1518117159450,"_id":"542692c9c026201cdc326a7b"},{"editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/367789?v=3","account-source":"github","login":"mattvvhat"},{"login":"bkovitz","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/4142015?v=3"}],"updated-at":1462724896381,"created-at":1428550055119,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/367789?v=3","account-source":"github","login":"mattvvhat"},"body":";; Futures will not raise their exceptions...\n=> (def my-future (future (/ 1 0))\n\n;; ...until dereferenced!\n=> @my-future\nArithmeticException Divide by zero clojure.lang.Numbers.divide","_id":"5525f1a7e4b033f34014b768"},{"editors":[{"login":"siddharthjain-in","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/6537820?v=4"}],"body":";; Given two URLs, create two futures to slurp their HTML, and return \n;; the page that returns first.\n;; This works because promises can only be delivered once.\n(let [p (promise)]\n (let [angieslist \"https://angieslist.com\" \n homeadvisor \"https://homeadvisor.com\"]\n (doseq [url [angieslist homeadvisor]]\n (future (let [response (slurp url)]\n (deliver p response)))))\n @p)\n","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/1291508?v=4","account-source":"github","login":"tomgeorge"},"created-at":1590118285193,"updated-at":1627314798087,"_id":"5ec7478de4b087629b5a190e"},{"editors":[{"login":"loeschzwerg","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/24317401?v=4"}],"body":";; You may want to do some cleanup whenever you cancel your `future`\n;; InterruptedException is the catch!\n\n;; lets say we want to feed our doge, but only a limited time...\n(defn connect! [conn] (println (reset! conn \"[doge] very yum\")))\n(defn response [conn] (println (reset! conn \"[doge] so full\")))\n(defn clean [conn] (println (reset! conn \"[doge] so hungry\")))\n\n(let [feed-time (rand-int 2000)\n connection (atom \"[doge] such ready\")\n doge-ops (future\n (try\n (println @connection)\n (connect! connection)\n (Thread/sleep 1000)\n (response connection)\n (catch InterruptedException ie\n (clean connection))\n (finally (println \"[doge] wow\"))))]\n (printf \"[Main] granting many feeding time: %dms\\n\" feed-time)\n (if (= :too-late (deref doge-ops feed-time :too-late))\n (do (println \"[Main] stop!\")\n (future-cancel doge-ops))\n @doge-ops))\n\n;; if he's lucky:\n[Main] granting many feeding time: 1582ms\n[doge] such ready\n[doge] very yum\n[doge] so full\n[doge] wow\n=> nil\n\n;; if he's unlucky:\n[Main] granting many feeding time: 569ms\n[doge] such ready\n[doge] very yum\n[Main] stop!\n=> true\n[doge] so hungry\n[doge] wow\n","author":{"avatar-url":"https://avatars.githubusercontent.com/u/24317401?v=4","account-source":"github","login":"loeschzwerg"},"created-at":1651240015047,"updated-at":1651241054178,"_id":"626bec4fe4b0b1e3652d75d8"},{"updated-at":1734308198026,"created-at":1734308198026,"author":{"login":"huahaiy","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/889685?v=4"},"body":";; Notice that future takes a body of expressions. That means it is possible\n;; to add a callback for an async computation in the future definition itself.\n;; There are two cases:\n;; 1. If the callback does not need to take the result of the computation \n;; as input, just do this:\n(future (computation) (callback))\n;; 2. If the callback needs to take the result, do this:\n(future (callback (computation)))","_id":"675f716669fbcc0c22617524"}],"macro":true,"notes":null,"arglists":["& body"],"doc":"Takes a body of expressions and yields a future object that will\n invoke the body in another thread, and will cache the result and\n return it on all subsequent calls to deref/@. If the computation has\n not yet finished, calls to deref/@ will block, unless the variant of\n deref with timeout is used. See also - realized?.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/future"},{"added":"1.0","ns":"clojure.core","name":"reset-meta!","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1458508963890,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"meta","ns":"clojure.core"},"_id":"56ef14a3e4b09295d75dbf31"},{"created-at":1458508972022,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"vary-meta","ns":"clojure.core"},"_id":"56ef14ace4b09295d75dbf32"},{"created-at":1458508987478,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"alter-meta!","ns":"clojure.core"},"_id":"56ef14bbe4b09295d75dbf33"},{"created-at":1458509000330,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"with-meta","ns":"clojure.core"},"_id":"56ef14c8e4b09295d75dbf34"}],"line":2433,"examples":[{"updated-at":1458508861290,"created-at":1458508861290,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10583730?v=3"},"body":"(def ^{:key \"val\"} my-var \"\")\n;;=> #'user/my-var\n\n(meta #'my-var)\n;;=> {:key \"val\", :ns #, :name my-var, :file \"NO_SOURCE_PATH\", :column 1, :line 1}\n\n(reset-meta! #'my-var {:new-key \"new-val\"}) ; replace all metadata\n;;=> {:new-key \"new-val\"}\n\n(meta #'my-var)\n;;=> {:new-key \"new-val\"}\n\n","_id":"56ef143de4b0b41f39d96ceb"}],"notes":null,"arglists":["iref metadata-map"],"doc":"Atomically resets the metadata for a namespace/var/ref/agent/atom","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/reset-meta!"},{"added":"1.0","ns":"clojure.core","name":"cycle","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1360759662000,"author":{"login":"rahulpilani","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3c3585fc1c6bf074ed5f268c9ebcb2f?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"lazy-seq","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ea1"},{"created-at":1434128252248,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"},"to-var":{"ns":"clojure.core","name":"map","library-url":"https://github.com/clojure/clojure"},"_id":"557b0f7ce4b03e2132e7d18d"},{"created-at":1553543700422,"author":{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/94482?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"repeat","ns":"clojure.core"},"_id":"5c993214e4b0ca44402ef6c9"}],"line":3002,"examples":[{"author":{"login":"nipra","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/142529?v=3"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"avatar-url":"https://avatars2.githubusercontent.com/u/22608?v=4","account-source":"github","login":"MrHus"}],"body":"user=> (take 5 (cycle [\"a\" \"b\"]))\n(\"a\" \"b\" \"a\" \"b\" \"a\")\n\nuser=> (take 10 (cycle (range 0 3)))\n(0 1 2 0 1 2 0 1 2 0)\n\n","created-at":1279160241000,"updated-at":1305843374000,"_id":"542692ccc026201cdc326c30"},{"body":";; Typically map works through its set of collections\n;; until any one of the collections is consumed.\n;; 'cycle' can be used to repeat the shorter collections\n;; until the longest collection is consumed.\n(mapv #(vector %2 %1) (cycle [1 2 3 4]) [:a :b :c :d :e :f :g :h :i :j :k :l])\n;;=> [[:a 1] [:b 2] [:c 3] [:d 4] [:e 1] [:f 2] [:g 3] [:h 4] [:i 1] [:j 2] [:k 3] [:l 4]]","author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"},"created-at":1434128630375,"updated-at":1434128842939,"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"_id":"557b10f6e4b01ad59b65f4f2"}],"notes":null,"arglists":["coll"],"doc":"Returns a lazy (infinite!) sequence of repetitions of the items in coll.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/cycle"},{"added":"1.0","ns":"clojure.core","name":"fn","special-form":true,"file":"clojure/core.clj","type":"macro","column":1,"see-alsos":[{"created-at":1360339005000,"author":{"login":"ViljamiPeltola","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1535c08820796d57a212a46a6bdd4cca?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"defn","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c77"}],"line":4560,"examples":[{"author":{"login":"zmila","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/68dd6f50915854aa04fefcf4d6fa5c8e?r=PG&default=identicon"},"editors":[{"login":"zmila","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/68dd6f50915854aa04fefcf4d6fa5c8e?r=PG&default=identicon"},{"login":"belun","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8d3c423e74750fa42c0386833e4b8209?r=PG&default=identicon"},{"login":"belun","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8d3c423e74750fa42c0386833e4b8209?r=PG&default=identicon"},{"login":"belun","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8d3c423e74750fa42c0386833e4b8209?r=PG&default=identicon"},{"login":"belun","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8d3c423e74750fa42c0386833e4b8209?r=PG&default=identicon"},{"login":"belun","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8d3c423e74750fa42c0386833e4b8209?r=PG&default=identicon"},{"login":"belun","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8d3c423e74750fa42c0386833e4b8209?r=PG&default=identicon"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},{"login":"jumblerg","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3f9e06cdf33ea6f2958a8b6430d9fe22?r=PG&default=identicon"},{"login":"jumblerg","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3f9e06cdf33ea6f2958a8b6430d9fe22?r=PG&default=identicon"}],"body":";; simple anonymous function passed to (map )\nuser=> (map (fn [x] (* x x)) (range 1 10))\n(1 4 9 16 25 36 49 64 81) \n\n;; anonymous function with a name. not so anonymous now is it?\n;; this is useful in stack traces\n(fn add [a b] (+ a b))\n\n;; anonymous function with two params, the second is destructured\nuser=> (reduce (fn [m [k v]] (assoc m v k)) {} {:b 2 :a 1 :c 3})\n{2 :b, 1 :a, 3 :c} \n\n;; define and instantly call an anonymous function\nuser=> ((fn [a b c] (+ a b c)) 2 4 6)\n12\n\n;; define and instantly call an anonymous variadic function \n;; \"nums\" is a list here\nuser=> ((fn [& nums] (/ (apply + nums) (count nums))) 1 2 3 4)\n5/2 \n\n;; define and instantly call an anonymous mixed function\n;; \"nums\" is a list, while \"int\" is a number\nuser=> ((fn [int & nums] (+ int (/ (apply + nums) (count nums)))) 10 1 2 3 4)\n25/2 \n\n;; define and instantly call an anonymous overloaded function \n;; even though it is quite pointless\nuser=> ((fn ([a] (inc a)) ([a b] (+ a b))) 3)\n4\n\n","created-at":1280346731000,"updated-at":1410072276000,"_id":"542692c7c026201cdc326977"},{"author":{"login":"belun","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8d3c423e74750fa42c0386833e4b8209?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":";; the shortcut form for (fn ) is #( )\n;; where parameters are referred by their index with the prefix %\n\n;; the equivalent of \nuser=> ((fn [a b c] (+ a b c)) 2 4 6)\n12\n\n;; is\nuser=> (#(+ %1 %2 %3) 2 4 6)\n12\n","created-at":1284093085000,"updated-at":1285487263000,"_id":"542692c7c026201cdc326983"},{"editors":[{"login":"enc7","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/12020265?v=3"}],"body":";; shortcut form #() cannot be used for maps etc.\n\nuser=> ((fn [] {:a 1}))\n{:a 1}\n\nuser=> (#({:a 1}))\nArityException Wrong number of args (0) passed to: PersistentArrayMap\n\nuser=> (#([1]))\nArityException Wrong number of args (0) passed to: PersistentVector\n\n;; explanation for the\tfirst error:\n;; #(f) is a shortcut for (fn [] (f))\n;; that means (#({:a 1})) is shortcut for ((fn [] ({:a 1})))\n;; which leads to the error above because you cannot apply a map to an empty\n;; argument list.\n\n;; i.e. you can only use #() shortcut if the fn body is a list.\n;; As ((fn [] {:a 1})) has the same result \n;; as ((fn [] (identity {:a 1}))), you can write:\n\nuser=> (#(identity {:a 1}))\n{:a 1}","author":{"avatar-url":"https://avatars.githubusercontent.com/u/5733420?v=3","account-source":"github","login":"trimtab613"},"created-at":1442862274788,"updated-at":1448575959557,"_id":"560054c2e4b08e404b6c1c80"},{"updated-at":1515615145069,"created-at":1515615145069,"author":{"login":"ibercode","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/31028993?v=4"},"body":";;map and anonymous function\n;;apply a function to a collection using an anonymous function\n\n(defn byten\n [nums]\n (map #(* 10 %) nums))\n\n(byten [1 2 3 4 5])\n;;(10 20 30 40 50)","_id":"5a5673a9e4b0a08026c48ceb"},{"updated-at":1565772877274,"created-at":1565772877274,"author":{"login":"terjedahl","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/11754710?v=4"},"body":";; shortcut form #() expands to an args-list-count as per \n;; the highest N in %N references within it, \n;; irrespective of whether a lower %N is referenced or not:\n\n(macroexpand-1 '#(prn))\n;;=> (fn* [] (prn))\n\n(macroexpand-1 '#(prn %))\n;;=> (fn* [p1__13122#] (prn p1__13122#))\n\n(macroexpand-1 '#(prn %1))\n;;=> (fn* [p1__13127#] (prn p1__13127#))\n\n(macroexpand-1 '#(prn %2))\n;;=> (fn* [p1__13133# p2__13132#] (prn p2__13132#))\n\n\n;; This will not work because the shortcut expands to a 0-arg fn:\n(let [a (atom :val0)] \n (add-watch a :key #(prn 'CHANGED))\n (reset! a :val1))\n;; Execution error (ArityException) at user/eval13174 (form-init5982058823921663207.clj:3).\n;; Wrong number of args (4) passed to: user/eval13174/fn--13175\n\n;; But this will work because simply referring to %4 expands it to a 4-arg fn:\n(let [a (atom :val0)] \n (add-watch a :key #(do %4 (prn 'CHANGED)))\n (reset! a :val1))\n;;CHANGED\n;;=> :val1 \n\n;; See the 4th bullet-point under \"dispatch macro\":\n;; https://clojure.org/reference/reader#_dispatch","_id":"5d53cc4de4b0ca44402ef7a3"}],"macro":true,"notes":[{"updated-at":1396626727000,"body":"The signature is wrong. It should be (quoting from [clojure.org][1])\r\n\r\n`(fn name? [params* ] exprs*)`\r\n\r\n`(fn name? ([params* ] exprs*)+)`\r\n\r\n\r\n [1]: http://clojure.org/special_forms#fn","created-at":1396626504000,"author":{"login":"Thumbnail","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/db68e51797a2382e185b42ce6534b7a4?r=PG&default=identicon"},"_id":"542692edf6e94c6970522023"},{"author":{"login":"terjedahl","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/11754710?v=3"},"updated-at":1461052793332,"created-at":1461052793332,"body":"What is the purpose of `name?` ?","_id":"5715e579e4b0fc95a97eab4d"},{"author":{"login":"vvvvalvalval","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/5859120?v=3"},"updated-at":1463756441418,"created-at":1463756441418,"body":"@terjedahl `name?` allows for self-recursion, as well as generating more human-friendly class names; it can also make the code clearer.","_id":"573f2699e4b0a1a06bdee494"},{"author":{"login":"battlmonstr","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/11477595?v=3"},"updated-at":1471784633567,"created-at":1471784633567,"body":"This leaves more questions. What is the performance cost? Why (fn name...) is repeated twice? What is a \"binding-form\"?\n\nThe syntax looks good compared to [lambda function](http://dobegin.com/lambda-functions-everywhere/) syntax in other programming languages.","_id":"57b9a6b9e4b0709b524f04d2"},{"author":{"login":"bfabry","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/29587?v=3"},"updated-at":1475793669553,"created-at":1475793669553,"body":"`fn` also supports the prepost map, the same as `defn`\n```\nboot.user=> (def adder (fn [x] {:post [(pos? %)]} (inc x)))\n#'boot.user/adder\nboot.user=> (adder -2)\n\njava.lang.AssertionError: Assert failed: (pos? %)\n```","_id":"57f6d305e4b0709b524f052a"},{"body":"A function can be defined taking specified keyword arguments:\n\n```clojure\n(defn foo [req-1 req-2 & {:keys [key-1 key-2]}\n (list req-1 req-2 key-1 key-2))\n\n(foo a b)\n(foo a b :key-1 100)\n(foo a b :key-2 200)\n(foo a b :key-2 100 :key-1 200)\n```","created-at":1602578421430,"updated-at":1602578490558,"author":{"avatar-url":"https://avatars1.githubusercontent.com/u/6414129?v=4","account-source":"github","login":"jimka2001"},"_id":"5f8567f5e4b0b1e3652d73d9"}],"arglists":["& sigs"],"doc":"params => positional-params*, or positional-params* & rest-param\n positional-param => binding-form\n rest-param => binding-form\n binding-form => name, or destructuring-form\n\n Defines a function.\n\n See https://clojure.org/reference/special_forms#fn for more information","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/fn","forms":["(fn name? [params*] exprs*)","(fn name? ([params*] exprs*) +)"]},{"added":"1.0","ns":"clojure.core","name":"seque","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":null,"line":5450,"examples":[{"author":{"login":"Chouser","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/7a0192050ed6488670acfd3f59405c10?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":"user=> (let [start (System/nanoTime)\n q (seque\n (iterate\n #(do (Thread/sleep 400) (inc %))\n 0))]\n (println \"sleep five seconds...\")\n (Thread/sleep 5000)\n (doseq [i (take 20 q)]\n (println (int (/ (- (System/nanoTime) start) 1e7))\n \":\" i)))\n\n\n;; The iterate form returns a lazy seq that delays nearly a half-second \n;; before returning each subsequent item. Here seque starts a thread \n;; generating the lazy seq.\n\n;; The body of the let allows the seque thread to get ahead by five seconds\n;; before it begins consuming the seq using doseq. The doseq prints a \n;; timestamp and the value from the seq when it becomes available. The\n;; first 11 or so are available almost instantly, until the consuming \n;; doseq catches up with the producing iterate, at which point the consumer\n;; blocks for 400ms before each item can be printed.\n\n;;sleep five seconds...\n500 : 0\n500 : 1\n500 : 2\n500 : 3\n500 : 4\n500 : 5\n500 : 6\n500 : 7\n500 : 8\n500 : 9\n500 : 10\n500 : 11\n520 : 12\n560 : 13\n600 : 14\n640 : 15\n680 : 16\n720 : 17\n760 : 18\n800 : 19\n\n","created-at":1283038869000,"updated-at":1285494350000,"_id":"542692c9c026201cdc326ad1"},{"updated-at":1519066526582,"created-at":1519066439016,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"body":";; A relatively fast producer (a file filter) and a variable speed consumer\n;; (because of pagination) are piped together. Use seque to enable search ahead \n;; of \"n\" items assuming consumer will soon paginate.\n\n(defn search-files [q root n]\n (->> (java.io.File. root)\n file-seq\n (map (memfn getPath))\n (filter #(re-find q %))\n (seque n)))\n\n(defn paginate [n]\n (let [root (System/getProperty \"user.home\")\n search (search-files #\"\\.clj$\" root 1000)]\n (loop [results (partition n search)]\n (println (with-out-str (clojure.pprint/write (first results))))\n (println \"more?\")\n (when (= \"y\" (read-line))\n (recur (rest results))))))\n\n(paginate 3)\n;; (\"/Users/reborg/.atom/fixtures/bad.clj\"\n;; \"/Users/reborg/.atom/fixtures/empty.clj\"\n;; \"/Users/reborg/.atom/fixtures/good.clj\")\n;; more?\n\n;; Note: seque is now producing 997 items ahead.","editors":[{"avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"}],"_id":"5a8b1d47e4b0316c0f44f8cd"},{"updated-at":1745853425602,"created-at":1745853425602,"author":{"login":"sanel","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/213914?v=4"},"body":";; seque can be used to force sequential processing of lazy seqs, especially\n;; if you are dealing with chunking\n\n;; Example without seque. It will always realize 32 elements, even if\n;; we use only 10 elements down the pipeline.\n(->> (range 1 100)\n (map #(do (println \"Loading\" % \"...\") %))\n (map #(do (println \"Processing\" % \"...\") %))\n (take 10)\n (doall))\n\n;; Loading 1 ...\n;; Loading 2 ...\n;; Loading 3 ...\n;; Loading 4 ...\n;; Loading 5 ...\n;; Loading 6 ...\n;; Loading 7 ...\n;; Loading 8 ...\n;; Loading 9 ...\n;; Loading 10 ...\n;; Loading 11 ...\n;; Loading 12 ...\n;; Loading 13 ...\n;; Loading 14 ...\n;; Loading 15 ...\n;; Loading 16 ...\n;; Loading 17 ...\n;; Loading 18 ...\n;; Loading 19 ...\n;; Loading 20 ...\n;; Loading 21 ...\n;; Loading 22 ...\n;; Loading 23 ...\n;; Loading 24 ...\n;; Loading 25 ...\n;; Loading 26 ...\n;; Loading 27 ...\n;; Loading 28 ...\n;; Loading 29 ...\n;; Loading 30 ...\n;; Loading 31 ...\n;; Loading 32 ...\n;; Processing 1 ...\n;; Processing 2 ...\n;; Processing 3 ...\n;; Processing 4 ...\n;; Processing 5 ...\n;; Processing 6 ...\n;; Processing 7 ...\n;; Processing 8 ...\n;; Processing 9 ...\n;; Processing 10 ...\n;; Processing 11 ...\n;; Processing 12 ...\n;; Processing 13 ...\n;; Processing 14 ...\n;; Processing 15 ...\n;; Processing 16 ...\n;; Processing 17 ...\n;; Processing 18 ...\n;; Processing 19 ...\n;; Processing 20 ...\n;; Processing 21 ...\n;; Processing 22 ...\n;; Processing 23 ...\n;; Processing 24 ...\n;; Processing 25 ...\n;; Processing 26 ...\n;; Processing 27 ...\n;; Processing 28 ...\n;; Processing 29 ...\n;; Processing 30 ...\n;; Processing 31 ...\n;; Processing 32 ...\n;; (1 2 3 4 5 6 7 8 9 10)\n\n;; Example with seque. It will correctly realize only 10\n;; elements and process them sequentially.\n(->> (range 1 100)\n (seque 10) ; n elements in queue, can be less\n (map #(do (println \"Loading\" % \"...\") %))\n (map #(do (println \"Processing\" % \"...\") %))\n (take 10)\n (doall))\n\n;; Loading 1 ...\n;; Processing 1 ...\n;; Loading 2 ...\n;; Processing 2 ...\n;; Loading 3 ...\n;; Processing 3 ...\n;; Loading 4 ...\n;; Processing 4 ...\n;; Loading 5 ...\n;; Processing 5 ...\n;; Loading 6 ...\n;; Processing 6 ...\n;; Loading 7 ...\n;; Processing 7 ...\n;; Loading 8 ...\n;; Processing 8 ...\n;; Loading 9 ...\n;; Processing 9 ...\n;; Loading 10 ...\n;; Processing 10 ...\n;; (1 2 3 4 5 6 7 8 9 10)","_id":"680f9bf1cd84df5de54e2088"}],"notes":null,"arglists":["s","n-or-q s"],"doc":"Creates a queued seq on another (presumably lazy) seq s. The queued\n seq will produce a concrete seq in the background, and can get up to\n n items ahead of the consumer. n-or-q can be an integer n buffer\n size, or an instance of java.util.concurrent BlockingQueue. Note\n that reading from a seque can block if the reader gets ahead of the\n producer.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/seque"},{"added":"1.0","ns":"clojure.core","name":"empty?","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1350338539000,"author":{"login":"dansalmo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e33ee460f5f61bc5ba9b598934766215?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"seq","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521ba1"},{"created-at":1435246118250,"author":{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/94482?v=3"},"to-var":{"ns":"clojure.core","name":"empty","library-url":"https://github.com/clojure/clojure"},"_id":"558c1e26e4b0fad27b85f926"},{"created-at":1448373938039,"author":{"login":"BernhardBln","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/4759839?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"not-empty","ns":"clojure.core"},"_id":"56546eb2e4b0538444398279"}],"line":6324,"examples":[{"updated-at":1441306150425,"created-at":1279073789000,"body":"user=> (empty? ())\ntrue\nuser=> (empty? '(1))\nfalse","editors":[{"login":"Ortuna","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/221008?v=3"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/147981?v=3","account-source":"github","login":"dpritchett"},"_id":"542692cac026201cdc326b85"},{"updated-at":1350271972000,"created-at":1279386965000,"body":"user=> (every? empty? [\"\" [] () '() {} #{} nil])\ntrue\n\n;example of recommended idiom for testing if not empty\nuser=> (every? seq [\"1\" [1] '(1) {:1 1} #{1}])\ntrue","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"avatar-url":"https://www.gravatar.com/avatar/e33ee460f5f61bc5ba9b598934766215?r=PG&default=identicon","account-source":"clojuredocs","login":"dansalmo"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/142529?v=3","account-source":"github","login":"nipra"},"_id":"542692cac026201cdc326b86"},{"updated-at":1441306161007,"created-at":1280205236000,"body":"user=> (drop-while empty? [\"\" [] \"foobar\"])\n(\"foobar\")","editors":[{"login":"Ortuna","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/221008?v=3"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/1703a0c3ed358b787f4b1bf3b2799472?r=PG&default=identicon","account-source":"clojuredocs","login":"Jacolyte"},"_id":"542692cac026201cdc326b89"},{"author":{"login":"ryo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3f7913b563c72083c74030d928ba407e?r=PG&default=identicon"},"editors":[],"body":"user=> (empty? nil)\ntrue","created-at":1401128995000,"updated-at":1401128995000,"_id":"542692d2c026201cdc326f9c"},{"editors":[{"login":"nodename","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/48810?v=4"}],"body":";; A collection with a \"nothing\" in it is not empty.\n(= true\n (every? false? [(empty? [nil])\n (empty? #{nil})\n (empty? '(nil))]))\n\n;; But a collection of nothing is empty.\n(= true\n (every? true? [(empty? [])\n (empty? #{})\n (empty? '())]))","author":{"avatar-url":"https://avatars.githubusercontent.com/u/7597818?v=3","account-source":"github","login":"Jjunior130"},"created-at":1482301932387,"updated-at":1664300394921,"_id":"585a21ece4b004d3a355e2d4"}],"notes":[{"updated-at":1402523411000,"body":"Some explanation of why (seq x) is preferable over (not (empty? x)) would be good. Because it's far less readable. When I come across (not (empty? x)) in some code, I immediately understand the author's intention. Not so much with (seq x).","created-at":1402523411000,"author":{"login":"cap10morgan","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/ccd26ba29b49316b38a46f0aa0e96893?r=PG&default=identicon"},"_id":"542692edf6e94c6970522029"},{"updated-at":1405724559000,"body":"I think this is an efficiency thing. If you expand the source you can see that empty? is equivalent to (not (seq coll)) so (not (empty? coll)) would macroexpand to (not (not (seq coll)) ","created-at":1405724559000,"author":{"login":"phreed","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3a0c739cf289be18be932dc3022e6fd3?r=PG&default=identicon"},"_id":"542692edf6e94c697052202d"},{"body":"Avoiding `(not (empty? s))` because it macroexpands into `(not (not ...))`, on the grounds of efficiency, is ridiculous. \n\nI'm a fan of:\n\n```clojure\n(when (not-empty s)\n ...)\n```","created-at":1421094984999,"updated-at":1421094984999,"author":{"login":"moea","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1453611?v=3"},"_id":"54b43048e4b081e022073c01"},{"author":{"login":"cmal","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1773318?v=3"},"updated-at":1478343485388,"created-at":1478343485388,"body":"If I just want to return false when empty, true when not empty, then what can I use if I am going to avoid (not (empty? ...))?","_id":"581dbb3de4b024b73ca35a22"},{"author":{"login":"yogsototh","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/93899?v=3"},"updated-at":1481783695983,"created-at":1481783695983,"body":"Just note `(not (empty? x))` is not perfectly equivalent to `seq`:\n\n~~~\nuser=> (seq '(1 2))\n(1 2)\nuser=> (not (empty? '(1 2)))\ntrue\n~~~","_id":"5852398fe4b004d3a355e2ba"},{"body":"```\nuser> (let [r (and (not (empty? [])))] r)\n;; => false\nuser> (let [r (and (seq []))] r)\n;; => nil\n```\n","created-at":1605311878358,"updated-at":1605311895281,"author":{"avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4","account-source":"github","login":"MicahElliott"},"_id":"5faf1d86e4b0b1e3652d7405"},{"author":{"login":"mars0i","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1836941?v=4"},"updated-at":1685380825029,"created-at":1685380764695,"body":"`(seq x)` is considered idiomatic, so in theory it should be understood by experienced Clojurians. `(not (empty? x))` might be better when you expect your code to be read by those who don't fit that description. (However, there are a number of Clojure idioms that could be confusing to those without much experience; avoiding them all might not be desirable.)","_id":"6474de9ce4b08cf8563f4bc3"}],"arglists":["coll"],"doc":"Returns true if coll has no items. To check the emptiness of a seq,\n please use the idiom (seq x) rather than (not (empty? x))","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/empty_q"},{"added":"1.0","ns":"clojure.core","name":"short","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"to-var":{"library-url":"https://github.com/clojure/clojure","name":"int","ns":"clojure.core"},"author":{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},"created-at":1342917689000,"_id":"542692ebf6e94c6970521f21"},{"to-var":{"library-url":"https://github.com/clojure/clojure","name":"byte","ns":"clojure.core"},"author":{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},"created-at":1342917692000,"_id":"542692ebf6e94c6970521f22"},{"to-var":{"library-url":"https://github.com/clojure/clojure","name":"shorts","ns":"clojure.core"},"author":{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},"created-at":1342917699000,"_id":"542692ebf6e94c6970521f23"},{"to-var":{"library-url":"https://github.com/clojure/clojure","name":"short-array","ns":"clojure.core"},"author":{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},"created-at":1342917703000,"_id":"542692ebf6e94c6970521f24"},{"created-at":1496261330759,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"unchecked-short","ns":"clojure.core"},"_id":"592f22d2e4b06e730307db1a"}],"line":3524,"examples":[{"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":"user=> (class (short 1))\njava.lang.Short","created-at":1281948540000,"updated-at":1332952892000,"_id":"542692c7c026201cdc3269a1"},{"editors":[{"login":"wdhowe","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/4631165?v=4"}],"body":"(short 123)\n;;=> 123\n\n(short 1.23)\n;;=> 1\n\n(short 1.2345678901234567890)\n;;=> 1\n\n(short -1.23)\n;;=> -1\n\n;; Casting a string does not work\n(short \"123\")\n;;=> Execution error (ClassCastException) at user/eval169 (REPL:1).\n;;java.lang.String cannot be cast to java.lang.Number\n\n;; Use Java interop instead\n(Short/parseShort \"123\")\n;;=> 123\n\n;; Content originally posted by u/didibus on https://clojuredocs.org/clojure.core/num","author":{"avatar-url":"https://avatars0.githubusercontent.com/u/4631165?v=4","account-source":"github","login":"wdhowe"},"created-at":1596573268703,"updated-at":1596590353567,"_id":"5f29c654e4b0b1e3652d735f"}],"notes":null,"arglists":["x"],"doc":"Coerce to short","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/short"},{"added":"1.2","ns":"clojure.core","name":"definterface","file":"clojure/core_deftype.clj","type":"macro","column":1,"see-alsos":[{"created-at":1432923318577,"author":{"login":"mars0i","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1836941?v=3"},"to-var":{"ns":"clojure.core","name":"defprotocol","library-url":"https://github.com/clojure/clojure"},"_id":"5568acb6e4b03e2132e7d17b"},{"created-at":1432923344729,"author":{"login":"mars0i","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1836941?v=3"},"to-var":{"ns":"clojure.core","name":"gen-interface","library-url":"https://github.com/clojure/clojure"},"_id":"5568acd0e4b01ad59b65f4e9"},{"created-at":1432923416186,"author":{"login":"mars0i","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1836941?v=3"},"to-var":{"ns":"clojure.core","name":"defrecord","library-url":"https://github.com/clojure/clojure"},"_id":"5568ad18e4b01ad59b65f4ea"},{"created-at":1432923425325,"author":{"login":"mars0i","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1836941?v=3"},"to-var":{"ns":"clojure.core","name":"deftype","library-url":"https://github.com/clojure/clojure"},"_id":"5568ad21e4b03e2132e7d17d"}],"line":20,"examples":[{"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":";; Part of a definterface from a Clojure program for the n-body problem\n;; at the Computer Language Benchmarks Game web site.\n;; For the rest of the program using it, see:\n;; http://github.com/jafingerhut/clojure-benchmarks/blob/master/nbody/nbody.clj-14.clj\n\n;; Currently Clojure does not permit type hints of arrays, e.g. ^ints as\n;; argument types or return types in a definterface. This may be enhanced\n;; later.\n\n(definterface IBody\n (^String name []) ;; return type String, no arguments\n (^double mass []) ;; return type double\n (^double x [])\n (clone [] \"returns copy of self\") ; return type defaults to ^Object\n ;; 3 arguments of type double. A deftype that implements this interface\n ;; must implement the method p! The definterface must use:\n ;; _BANG_ for ! in Clojure method name\n ;; _PLUS_ for +\n ;; _ for -\n (p_BANG_ [^double x ^double y ^double z] \"set pos.\")\n ;; After name demangling, this must be implemented by Clojure method named v+!\n (v_PLUS__BANG_ [^double vx ^double vy ^double vz] \"add to velocity\"))\n","created-at":1298555484000,"updated-at":1298556086000,"_id":"542692cdc026201cdc326d3c"},{"body":";; Note these differences between defprotocol and definterface:\n\n;; defprotocol requires that methods specify a first parameter, which \n;; will be the record object, while definterface requires that this\n;; parameter be left out:\n(definterface I (fooey []))\n;=> user.I\n(defprotocol P (fooey []))\n;=> IllegalArgumentException Definition of function fooey in protocol P must take at least one arg. clojure.core/emit-protocol/fn--5964 (core_deftype.clj:612)\n(defprotocol P (fooey [this]))\n;=> P\n\n;; However, defrecord requires that a parameter for the record object\n;; be used, even with interfaces. (A similar point applies to deftype.)\n(defrecord Irec [stuff] I (fooey [] \"foo\"))\n;=> CompilerException java.lang.IllegalArgumentException: Must supply at least one argument for 'this' in: fooey, compiling:(NO_SOURCE_PATH:1:1) \n(defrecord Irec [stuff] I (fooey [this] \"foo\"))\n;=> user.Irec\n(defrecord Prec [stuff] P (fooey [this] \"foo\"))\n;=> user.Prec\n\n;; Using an interface, only the dot form of the method is available with \n;; defrecord, while the protocol also allows use of normal Clojure function\n;; syntax. (Similar points apply to deftype.)\n(.fooey (Irec. 42))\n;=> \"foo\"\n(fooey (Irec. 42))\n;=> IllegalArgumentException No implementation of method: :fooey of protocol: #'user/P found for class: user.Irec clojure.core/-cache-protocol-fn (core_deftype.clj:544)\n(.fooey (Prec. 42))\n;=> \"foo\"\n(fooey (Prec. 42))\n;=> \"foo\"\n","author":{"login":"mars0i","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1836941?v=3"},"created-at":1432922847490,"updated-at":1432923131996,"editors":[{"login":"mars0i","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1836941?v=3"}],"_id":"5568aadfe4b03e2132e7d175"}],"macro":true,"notes":null,"arglists":["name & sigs"],"doc":"Creates a new Java interface with the given name and method sigs.\n The method return types and parameter types may be specified with type hints,\n defaulting to Object if omitted.\n\n (definterface MyInterface\n (^int method1 [x])\n (^Bar method2 [^Baz b ^Quux q]))","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/definterface"},{"added":"1.10","ns":"clojure.core","name":"add-tap","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1590688364048,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/109629?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"tap>","ns":"clojure.core"},"_id":"5ecffa6ce4b087629b5a1919"},{"created-at":1590688390865,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/109629?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"remove-tap","ns":"clojure.core"},"_id":"5ecffa86e4b087629b5a191c"},{"created-at":1661551771193,"author":{"login":"djblue","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1986211?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"datafy","ns":"clojure.datafy"},"_id":"6309449be4b0b1e3652d765a"}],"line":8106,"examples":[{"editors":[{"login":"harrigan","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/140753?v=4"}],"body":";; log to a file\n(defn log [x] \n (spit \"event.log\" (str x \\newline) :append true))\n\n;; add log function to tap\n(add-tap log) ;;_=> returns nil\n\n(add-tap println)\n\n\n(tap> \"hello\") \n;; prints hello\n;; returns true if successful\n;; event.log:\n;; hello\\n\n(tap> \"clojure\")\n;; prints clojure\n;; returns true\n;; event.log:\n;; hello\\n\n;; clojure\\n\n\n;; the tap set is a hash-set so adding the same function twice has no effect \n(add-tap println) \n(tap> \"<3\")\n;; prints <3\n;; returns true\n;; event.log:\n;; hello\\n\n;; clojure\\n\n;; <3\\n","author":{"avatar-url":"https://avatars.githubusercontent.com/u/21296448?v=4","account-source":"github","login":"earthfail"},"created-at":1660914021711,"updated-at":1696954177287,"_id":"62ff8965e4b0b1e3652d763e"},{"editors":[{"login":"djblue","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1986211?v=4"}],"body":";; Your tap target function can do interesting things when it receives a value\n;; before printing it\n(require '[clojure.datafy :refer [datafy]])\n(add-tap (comp prn datafy))\n","author":{"avatar-url":"https://avatars.githubusercontent.com/u/1986211?v=4","account-source":"github","login":"djblue"},"created-at":1661551901572,"updated-at":1662581217249,"_id":"6309451de4b0b1e3652d765b"}],"notes":null,"arglists":["f"],"doc":"adds f, a fn of one argument, to the tap set. This function will be called with anything sent via tap>.\n This function may (briefly) block (e.g. for streams), and will never impede calls to tap>,\n but blocking indefinitely may cause tap values to be dropped.\n Remember f in order to remove-tap","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/add-tap"},{"added":"1.4","ns":"clojure.core","name":"filterv","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1413317009497,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"},"to-var":{"ns":"clojure.core","name":"filter","library-url":"https://github.com/clojure/clojure"},"_id":"543d8191e4b02688d208b1b7"},{"created-at":1534449404739,"author":{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/94482?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"mapv","ns":"clojure.core"},"_id":"5b75d6fce4b00ac801ed9e61"}],"line":7068,"examples":[{"editors":[{"login":"dijonkitchen","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/11434205?v=4"}],"updated-at":1550019407140,"created-at":1413316994942,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2","account-source":"github","login":"phreed"},"body":";; very similar to filter but returns a vector\n(filterv even? (range 10))\n;;=> [0 2 4 6 8]\n\n(filterv (fn [x]\n (= (count x) 1))\n [\"a\" \"aa\" \"b\" \"n\" \"f\" \"lisp\" \"clojure\" \"q\" \"\"])\n;;=> [\"a\" \"b\" \"n\" \"f\" \"q\"]\n\n(filterv #(= (count %) 1)\n [\"a\" \"aa\" \"b\" \"n\" \"f\" \"lisp\" \"clojure\" \"q\" \"\"])\n;;=> [\"a\" \"b\" \"n\" \"f\" \"q\"]\n","_id":"543d8182e4b0a3cf052fe477"}],"notes":null,"arglists":["pred coll"],"doc":"Returns a vector of the items in coll for which\n (pred item) returns logical true. pred must be free of side-effects.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/filterv"},{"added":"1.0","ns":"clojure.core","name":"hash","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1369891154000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"get","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521aa5"},{"created-at":1495647939893,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"hash-ordered-coll","ns":"clojure.core"},"_id":"5925c6c3e4b093ada4d4d737"},{"created-at":1495647979480,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"hash-unordered-coll","ns":"clojure.core"},"_id":"5925c6ebe4b093ada4d4d738"}],"line":5218,"examples":[{"updated-at":1456675282601,"created-at":1280319931000,"body":"user=> (hash \"a\")\n1455541201\nuser=> (.hashCode \"a\") ; notice that this is different than (hash \"a\")\n97\nuser=> (hash 1)\n1392991556\nuser=> (.hashCode 1) ; notice that this is different than (hash 1)\n1\nuser=> (hash nil)\n0\nuser=> (hash [1 2 3])\n30817\nuser=> (hash [1 2 3 4])\n955331","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3","account-source":"github","login":"jafingerhut"},{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10583730?v=3"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon","account-source":"clojuredocs","login":"gstamp"},"_id":"542692cbc026201cdc326bc4"},{"updated-at":1548542144072,"created-at":1548542144072,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/109629?v=4"},"body":";; In most cases, hash is _consistent_ with =, meaning that for two values x, y,\n;; if (= x y), then (= (hash x) (hash y)). This is a property of hash that\n;; is relied upon for hash-based lookup of keys in maps and\n;; elements in sets to work correctly.\n\n;; There are some pairs of Java objects x, y where even though (= x y) is true,\n;; (= (hash x) (hash y)) is _not_ true.\n\n;; Search for the word \"consistent\" in this article for some categories of such\n;; objects: https://clojure.org/guides/equality\n\n;; In particular, the section titled \"Equality and hash\":\n;; https://clojure.org/guides/equality#equality_and_hash","_id":"5c4ce0c0e4b0ca44402ef640"},{"editors":[{"login":"loeschzwerg","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/24317401?v=4"}],"body":";; Equality is measured by the content\n;; Hashes of lists AND vectors are equal by content\n=> (= (hash '(1 2 3)) (hash [1 2 3]))\ntrue\n\n;; Also works with clojure-\"Objects\" like LazySeq\n=> (= (hash [1 2 3]) (hash (map identity [1 2 3])))\ntrue\n\n;; but not with sets\n=> (= (hash [1 2 3]) (hash (set [1 2 3])))\nfalse","author":{"avatar-url":"https://avatars.githubusercontent.com/u/24317401?v=4","account-source":"github","login":"loeschzwerg"},"created-at":1647338501091,"updated-at":1647339498450,"_id":"62306405e4b0b1e3652d75bb"}],"notes":[{"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10583730?v=3"},"updated-at":1456676195346,"created-at":1456676195346,"body":"Despite what the doc-string says values returned by `(hash)` are different from `(.hashCode)` for more than just `Integer`, `Short`, `Byte` and Clojure collections.\n\nThe list also includes: Keywords, Symbols, Functions, Sequences, `String`, `Long` and `BigInteger` (as of Clojure 1.7.0).","_id":"56d31d63e4b0b41f39d96cd5"}],"arglists":["x"],"doc":"Returns the hash code of its argument. Note this is the hash code\n consistent with =, and thus is different than .hashCode for Integer,\n Short, Byte and Clojure collections.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/hash"},{"added":"1.0","ns":"clojure.core","name":"quot","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1305751242000,"author":{"login":"Kototama","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a54a4dc204925d397ca010b9a332e74d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"rem","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b7e"},{"created-at":1305751245000,"author":{"login":"Kototama","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a54a4dc204925d397ca010b9a332e74d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"mod","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b7f"},{"created-at":1435174860426,"author":{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/94482?v=3"},"to-var":{"ns":"clojure.core","name":"unchecked-divide-int","library-url":"https://github.com/clojure/clojure"},"_id":"558b07cce4b0fad27b85f923"},{"created-at":1468958158412,"author":{"login":"chrismurrph","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10278575?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"/","ns":"clojure.core"},"_id":"578e85cee4b0bafd3e2a04b2"},{"created-at":1698706207105,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"floor-div","ns":"clojure.math"},"_id":"6540331f69fbcc0c2261740e"}],"line":1275,"examples":[{"updated-at":1632985121009,"created-at":1279992131000,"body":";; (quot m n) is the value of m/n, rounded towards 0 to the nearest integer.\n;; m, n need not be integers.\n\nuser=> (quot 10 3)\n3\n\nuser=> (quot 11 3)\n3\n\nuser=> (quot 12 3)\n4\n\nuser=> (quot -5.9 3)\n-1.0\n\nuser=> (quot 10 -3)\n-3\n\nuser=> (quot 15 0)\nArithmeticException / by zero clojure.lang.Numbers.quotient (Numbers.java:1764)\n\n\n;; For ClojureScript (at least v1.10.597), `num`, `div` should be integer.\n;; Otherwise, it does not work correctly due to its implementation:\nhttp://cljs.github.io/api/cljs.core/quot\n\n;; in clojure,\nuser=> (quot 286.3 21.2)\n13.0\n\n;; in clojurescript\ncljs.user=> (quot 286.3 21.2)\n12","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3","account-source":"github","login":"jafingerhut"},{"avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3","account-source":"github","login":"jafingerhut"},{"login":"jngbng","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/552977?v=4"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},"_id":"542692cbc026201cdc326bec"},{"author":{"login":"shockbob","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon"},"editors":[{"login":"shockbob","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon"}],"body":";; note that the \"/\" function and the quot function are not equivalent\n\nuser=> (= (/ 4 2) (quot 4 2))\ntrue\n\nuser=> (= (/ 3 2) (quot 3 2))\nfalse\n","created-at":1316301245000,"updated-at":1316301327000,"_id":"542692cbc026201cdc326bf0"}],"notes":null,"arglists":["num div"],"doc":"quot[ient] of dividing numerator by denominator.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/quot"},{"added":"1.0","ns":"clojure.core","name":"ns-aliases","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1374148394000,"author":{"login":"alilee","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2fb0196dc5a7cd3a5cc73f1b9941c209?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"alias","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b61"},{"created-at":1512036368133,"author":{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"ns-unalias","ns":"clojure.core"},"_id":"5a1fd810e4b0a08026c48cc7"}],"line":4300,"examples":[{"editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3","account-source":"github","login":"phreed"},{"login":"domokato","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2388832?v=4"}],"updated-at":1646765005254,"created-at":1416004195771,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3","account-source":"github","login":"phreed"},"body":";; clojure.core contains an alias\n(ns-aliases 'clojure.core)\n;;=> {jio #}\n\n;; To start with there are no namespace aliases in the user namespace.\n(ns-aliases 'user)\n;;=> {}\n\n;; ...but we can add an alias to the user namespace.\n(alias 'string 'clojure.string) \n(ns-aliases 'user)\n;;=> {string #{Namespace clojure.string>}\n\n","_id":"54668263e4b0dc573b892fc9"},{"body":";; Suppose you want to pass a namespace as an argument...\n(ns wip (:require [clojure.string :as string]\n [clojure.pprint :as pp]))\n(defn foo [nspace] nspace)\n\n;; ...pretty easy to do if you use the namespace symbol.\n(foo (the-ns 'clojure.string))\n;;=> #\n\n;; but, a bit of a problem if you want to pass the alias.\n(foo (the-ns 'string))\n;; java.lang.Exception: No namespace: string found...\n\n;; We can make a function that will serve using ns-aliases.\n(defn the-alias [name] (get (ns-aliases *ns*) name))\n(the-alias 'string)\n;;=> #\n\n(foo (the-alias 'string))\n;;=> #\n\n;; A more direct function can be written.\n;; but this uses an undocumented function.\n(defn the-alias [alias-name] (.lookupAlias *ns* (symbol alias-name)))\n(the-alias \"pp\")\n;;=> #\n\n\n\n\n","author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"},"created-at":1416006101219,"updated-at":1416243613962,"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"_id":"546689d5e4b0dc573b892fcc"}],"notes":null,"arglists":["ns"],"doc":"Returns a map of the aliases for the namespace.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/ns-aliases"},{"added":"1.0","ns":"clojure.core","name":"read","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1313054766000,"author":{"login":"TimMc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5d532e51427ef2f4ded31aaca16c8baf?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"read-string","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f56"},{"created-at":1352963657000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.core","name":"*read-eval*","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f57"}],"line":3767,"examples":[{"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"editors":[],"body":"user=> (read)\n( + 1 1 ) ; <= User types this\n(+ 1 1)\nuser=> (eval (read))\n(+ 1 1) ; <= User types this\n2\n","created-at":1286263972000,"updated-at":1286263972000,"_id":"542692c8c026201cdc326a15"},{"author":{"login":"Chris Riddoch","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/c908fbef70e8540f700a6b362cf57e9e?r=PG&default=identicon"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":";; WARNING: You SHOULD NOT use clojure.core/read or\n;; clojure.core/read-string to read data from untrusted sources. They\n;; were designed only for reading Clojure code and data from trusted\n;; sources (e.g. files that you know you wrote yourself, and no one\n;; else has permission to modify them).\n\n;; Instead, either:\n\n;; (1) Use another data serialization format such as JSON, XML,\n;; etc. and a library for reading them that you trust not to have\n;; vulnerabilities, or\n\n;; (2) if you want a serialization format that can be read safely and\n;; looks like Clojure data structures, use edn\n;; (https://github.com/edn-format/edn). For Clojure 1.3 and later,\n;; the tools.reader contrib library provides an edn reader\n;; (http://github.com/clojure/tools.reader). There is also\n;; clojure.edn/read and clojure.edn/read-string provided in Clojure\n;; 1.5.\n\n;; You definitely should not use clojure.core/read or read-string if\n;; *read-eval* has its default value of true, because an attacker\n;; could cause your application to execute arbitrary code while it is\n;; reading. Example:\n\nuser=> (read-string \"#=(clojure.java.shell/sh \\\"echo\\\" \\\"hi\\\")\")\n{:exit 0, :out \"hi\\n\", :err \"\"}\n\n;; It is straightforward to modify the example above into more\n;; destructive ones that remove all of your files, copy them to\n;; someone else's computer over the Internet, install Trojans, etc.\n\n;; Even if you do bind *read-eval* to false first, like so:\n\n(defn read-string-unsafely [s]\n (binding [*read-eval* false]\n (read-string s)))\n\n;; you may hope you are safe reading untrusted data that way, but in\n;; Clojure 1.4 and earlier, an attacker can send data that causes your\n;; system to execute arbitrary Java constructors. Most of these are\n;; benign, but it only takes one to ruin your application's day.\n;; Examples that should scare you:\n\n;; This causes a socket to be opened, as long as the JVM sandboxing\n;; allows it.\n(read-string-unsafely \"#java.net.Socket[\\\"www.google.com\\\" 80]\")\n\n;; This causes precious-file.txt to be created if it doesn't exist, or\n;; if it does exist, its contents will be erased (given appropriate\n;; JVM sandboxing permissions, and underlying OS file permissions).\n(read-string-unsafely \"#java.io.FileWriter[\\\"precious-file.txt\\\"]\")\n\n;; The particular issue of executing arbitrary Java constructors used\n;; in the examples above no longer works in Clojure 1.5 when\n;; *read-eval* is false. Even so, you SHOULD NEVER USE\n;; clojure.core/read or clojure.core/read-string for reading untrusted\n;; data. Use an edn reader or a different data serialization format.\n\n;; Why should I do this, you may ask, if Clojure 1.5 closes the Java\n;; constructor hole? Because clojure.core/read and read-string are\n;; designed to be able to do dangerous things, and they are not\n;; documented nor promised to be safe from unwanted side effects. If\n;; you use them for reading untrusted data, and a dangerous side\n;; effect is found in the future, you will be told that you are using\n;; the wrong tool for the job. clojure.edn/read and read-string, and\n;; the tools.reader.edn library, are documented to be safe from\n;; unwanted side effects, and if any bug is found in this area it\n;; should get quick attention and corrected.\n\n;; If you understand all of the above, and want to use read or\n;; read-string to read data from a _trusted_ source, continue on\n;; below.\n\n;; read wants its reader arg (or *in*) to be a java.io.PushbackReader.\n;; with-open closes r after the with-open body is done. *read-eval*\n;; specifies whether to allow #=() forms when reading, and evaluate\n;; them as a side effect while reading.\n\n(defn read-from-file-with-trusted-contents [filename]\n (with-open [r (java.io.PushbackReader.\n (clojure.java.io/reader filename))]\n (binding [*read-eval* false]\n (read r))))\n\nuser=> (spit \"testfile.txt\" \"{:a 1 :b 2 :c 3}\")\nnil\nuser=> (read-from-file-with-trusted-contents \"testfile.txt\")\n{:a 1, :b 2, :c 3}\n","created-at":1325831086000,"updated-at":1364783739000,"_id":"542692d5c026201cdc327056"}],"notes":[{"updated-at":1286264042000,"body":"This function is for reading clojure objects not a general input function.","created-at":1286264042000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521f98"}],"arglists":["","stream","stream eof-error? eof-value","stream eof-error? eof-value recursive?","opts stream"],"doc":"Reads the next object from stream, which must be an instance of\n java.io.PushbackReader or some derivee. stream defaults to the\n current value of *in*.\n\n Opts is a persistent map with valid keys:\n :read-cond - :allow to process reader conditionals, or\n :preserve to keep all branches\n :features - persistent set of feature keywords for reader conditionals\n :eof - on eof, return value unless :eofthrow, then throw.\n if not specified, will throw\n\n Note that read can execute code (controlled by *read-eval*),\n and as such should be used only with trusted sources.\n\n For data structure interop use clojure.edn/read","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/read"},{"added":"1.3","ns":"clojure.core","name":"unchecked-double","file":"clojure/core.clj","type":"function","column":1,"see-alsos":null,"line":3578,"examples":[{"updated-at":1507300542297,"created-at":1507300542297,"author":{"login":"PhillRoyle","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/7779270?v=4"},"body":"\n;; the function taking a BigDecimal with limited decimal places\n(unchecked-double 1.77M)\n=> 1.77\n\n;; the function taking a double with limited decimal places\n(unchecked-double 1.22)\n=> 1.22\n\n;; the function taking '0'\n(unchecked-double 0)\n=> 0.0\n\n;; the function does (eventually) round up...:\n(unchecked-double 1.000000000123456789)\n=> 1.0000000001234568\n;;...or down:\n(unchecked-double 1.000000000123456489)\n=> 1.0000000001234566","_id":"59d794bee4b03026fe14ea51"}],"notes":null,"arglists":["x"],"doc":"Coerce to double. Subject to rounding.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/unchecked-double"},{"added":"1.0","ns":"clojure.core","name":"key","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1318592856000,"author":{"login":"mmwaikar","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/29d36f4c9f39c9f8ff61c07033b13118?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"keys","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f60"},{"created-at":1434396249722,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"},"to-var":{"ns":"clojure.core","name":"val","library-url":"https://github.com/clojure/clojure"},"_id":"557f2659e4b01ad59b65f4f4"},{"created-at":1517622978859,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"map","ns":"clojure.core"},"_id":"5a7516c2e4b0e2d9c35f7411"},{"created-at":1517622990497,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"hash-map","ns":"clojure.core"},"_id":"5a7516cee4b0e2d9c35f7412"}],"line":1582,"examples":[{"updated-at":1434395508050,"created-at":1280777907000,"body":";; the following emulates 'keys'\n(map key {:a 1 :b 2})\n;;=> (:a :b)\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3","account-source":"github","login":"phreed"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3","account-source":"github","login":"devn"},"_id":"542692cac026201cdc326b66"},{"body":";; extracts the key of a map entry\n(key (clojure.lang.MapEntry. :a :b))\n;;=> :a\n","author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"},"created-at":1434396125134,"updated-at":1434396125134,"_id":"557f25dde4b03e2132e7d191"}],"notes":null,"arglists":["e"],"doc":"Returns the key of the map entry.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/key"},{"added":"1.0","ns":"clojure.core","name":"longs","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"to-var":{"library-url":"https://github.com/clojure/clojure","name":"long-array","ns":"clojure.core"},"author":{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},"created-at":1342917385000,"_id":"542692ebf6e94c6970521f53"}],"line":5436,"examples":[{"updated-at":1656673080931,"created-at":1656673080931,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":"(def my-floats (float-array [1.1 2.2 3.3]));; => #'user/my-floats\n\n;; long-array will convert where possible\n(long-array my-floats);; => [1, 2, 3]\n\n;; longs will not\n(try (longs my-floats)\n (catch ClassCastException e (ex-message e)));; => \"[F cannot be cast to [J\"","_id":"62bed338e4b0b1e3652d7614"},{"editors":[{"login":"randomizedthinking","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/5283430?v=4"}],"body":";; longs does cast but not convert arrays\n;; it is used as a type-hinting device to avoid reflections\n;; very important for computation intensive codes\n(binding [*print-meta* true]\n (def ^longs x (long-array [1 2 4]))\n (clojure.pprint/pprint #'x)) ;; ^{:tag #function[clojure.core/longs], ...}","author":{"avatar-url":"https://avatars.githubusercontent.com/u/5283430?v=4","account-source":"github","login":"randomizedthinking"},"created-at":1679352950506,"updated-at":1679353150365,"_id":"6418e476e4b08cf8563f4b80"},{"updated-at":1682270999390,"created-at":1682270999390,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":";; Casting avoids expensive reflection, so to see the benefit, enable warning:\n(set! *warn-on-reflection* true)\n\n;; We'll def a long-array but won't type-hint the var:\n(def my-array (long-array [10 20 30 40 50 60]))\n\n;; and try to amap over it without using `longs` or type hinting amap's args:\n(amap my-array i _ (unchecked-inc ^long (aget my-array i)))\n;; Reflection warning… call to static method alength on clojure.lang.RT can't be resolved (argument types: unknown).\n;; Reflection warning… call to static method aclone on clojure.lang.RT can't be resolved (argument types: unknown).\n;; Reflection warning… call to static method aget on clojure.lang.RT can't be resolved (argument types: unknown, int).\n;; Reflection warning… call to static method aset on clojure.lang.RT can't be resolved (argument types: unknown, int, long).\n;; => [11, 21, 31, 41, 51, 61]\n\n;; We can use `longs` to avoid reflection:\n(amap (longs my-array) i _ (unchecked-inc ^long (aget (longs my-array) i)))\n;; => [11, 21, 31, 41, 51, 61]\n\n;; Just as we can type hint in place:\n(amap ^longs my-array i _ (unchecked-inc ^long (aget ^longs my-array i)))\n;; => [11, 21, 31, 41, 51, 61]\n\n;; Or type hint the var:\n(def ^\"[J\" my-array (long-array [10 20 30 40 50 60]))\n(amap my-array i _ (unchecked-inc ^long (aget my-array i)))\n;; => [11, 21, 31, 41, 51, 61]\n","_id":"64456b17e4b08cf8563f4b90"}],"notes":null,"arglists":["xs"],"doc":"Casts to long[]","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/longs"},{"added":"1.0","ns":"clojure.core","name":"not=","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1412341716329,"author":{"login":"verma","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/242524?v=2"},"to-var":{"ns":"clojure.core","name":"=","library-url":"https://github.com/clojure/clojure"},"_id":"542e9fd4e4b05f4d257a29a0"},{"created-at":1412341728824,"author":{"login":"verma","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/242524?v=2"},"to-var":{"ns":"clojure.core","name":"not","library-url":"https://github.com/clojure/clojure"},"_id":"542e9fe0e4b05f4d257a29a1"}],"line":821,"examples":[{"author":{"login":"devn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3"},"editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3","account-source":"github","login":"devn"},{"avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3","account-source":"github","login":"devn"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":"user=> (not= 1 1)\nfalse\n\nuser=> (not= 1 2)\ntrue\n\nuser=> (not= true true)\nfalse\n\nuser=> (not= true false)\ntrue\n\nuser=> (not= true true true true)\nfalse\n\nuser=> (not= true true false true)\ntrue\n","created-at":1280778104000,"updated-at":1285495471000,"_id":"542692c6c026201cdc32690f"},{"updated-at":1565641574887,"created-at":1565641574887,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/109629?v=4"},"body":";; See the Clojure Equality guide for more details:\n;; https://clojure.org/guides/equality","_id":"5d51cb66e4b0ca44402ef7a1"},{"editors":[{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"}],"body":";; An exception to the docstring:\n\n(not= ##NaN ##NaN)\n;; => false\n\n(not (= ##NaN ##NaN))\n;; => true\n\n;; This is because of various shortcuts for checking identity when checking equality.\n;; As a rule of thumb, don't rely on either for testing against the ##NaN literal.\n;; Decide on which logic you want, and explicitly test. E.g.\n\n(defn != [x y]\n (or (not= x y)\n (NaN? x)\n (NaN? y)))\n\n(!= ##NaN ##NaN)\n;; => true","author":{"avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4","account-source":"github","login":"tomdl89"},"created-at":1677513608119,"updated-at":1699794987896,"_id":"63fcd388e4b08cf8563f4b73"}],"notes":null,"tag":"java.lang.Boolean","arglists":["x","x y","x y & more"],"doc":"Same as (not (= obj1 obj2))","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/not="},{"added":"1.0","ns":"clojure.core","name":"string?","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1596596389180,"author":{"login":"wdhowe","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/4631165?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"str","ns":"clojure.core"},"_id":"5f2a20a5e4b0b1e3652d7371"}],"line":162,"examples":[{"author":{"login":"dakrone","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bcacd00a7f05c4772329cf9f446c7987?r=PG&default=identicon"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"}],"body":"user=> (string? \"abc\")\ntrue\n\nuser=> (string? \"\")\ntrue\n\nuser=> (string? \\a)\nfalse\n\nuser=> (string? 1)\nfalse\n\nuser=> (string? [\"a\" \"b\" \"c\"])\nfalse\n\nuser=> (string? nil)\nfalse","created-at":1280546643000,"updated-at":1423277887409,"_id":"542692c7c026201cdc326945"}],"notes":null,"arglists":["x"],"doc":"Return true if x is a String","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/string_q"},{"added":"1.9","ns":"clojure.core","name":"uri?","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1627821463966,"author":{"login":"Okwori","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/16775439?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"instance?","ns":"clojure.core"},"_id":"61069597e4b0b1e3652d7525"}],"line":8083,"examples":[{"updated-at":1495999488091,"created-at":1495999488091,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"body":"(uri? (new java.net.URI \"http://clojuredocs.org/\"))\n;;=> true\n\n(uri? (new java.net.URL \"http://clojuredocs.org/\"))\n;;=> false\n(uri? \"http://clojuredocs.org/\")\n;;=> false\n","_id":"592b2400e4b093ada4d4d781"},{"updated-at":1627822753593,"created-at":1627822683340,"author":{"login":"Okwori","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/16775439?v=4"},"body":";; When fetching URI db.type\n\n;;(uri? #object[com.cognitect.transit.impl.URIImpl 0x3ec31528 \"https://www.datomic.com/details.html\")\n(uri? (com.cognitect.transit.impl.URIImpl. \"https://www.datomic.com/details.html\"))\n;;=> false\n\n(instance? com.cognitect.transit.impl.URIImpl \n (com.cognitect.transit.impl.URIImpl. \"https://www.datomic.com/details.html\")) \n;;=> true\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/16775439?v=4","account-source":"github","login":"Okwori"}],"_id":"61069a5be4b0b1e3652d7526"}],"notes":null,"arglists":["x"],"doc":"Return true if x is a java.net.URI","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/uri_q"},{"added":"1.0","ns":"clojure.core","name":"aset-double","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1349125867000,"author":{"login":"Ljos","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/45b996a79abca465acaf6c0f10b0437?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"double-array","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521abb"}],"line":3992,"examples":[{"author":{"login":"shockbob","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon"},"editors":[],"body":";; create an array of 10 doubles and set one of the elements to 3.1415\n\nuser=> (def ds (double-array 10))\n#'user/ds\nuser=> (vec ds)\n[0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0]\nuser=> (aset-double ds 3 3.1415)\n3.1415\nuser=> (vec ds)\n[0.0 0.0 0.0 3.1415 0.0 0.0 0.0 0.0 0.0 0.0]\nuser=>","created-at":1313914664000,"updated-at":1313914664000,"_id":"542692ccc026201cdc326c88"}],"notes":[{"body":"See [aset](http://clojuredocs.org/clojure.core/aset) for illustrations of multi-dimensional syntax.","created-at":1432829167201,"updated-at":1432829167201,"author":{"login":"mars0i","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1836941?v=3"},"_id":"55673cefe4b01ad59b65f4e1"}],"arglists":["array idx val","array idx idx2 & idxv"],"doc":"Sets the value at the index/indices. Works on arrays of double. Returns val.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/aset-double"},{"added":"1.0","ns":"clojure.core","name":"unchecked-multiply-int","file":"clojure/core.clj","type":"function","column":1,"see-alsos":null,"line":1233,"examples":null,"notes":null,"arglists":["x y"],"doc":"Returns the product of x and y, both int.\n Note - uses a primitive operator subject to overflow.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/unchecked-multiply-int"},{"ns":"clojure.core","name":"chunk-rest","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1443934917158,"author":{"login":"devn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"chunk-first","ns":"clojure.core"},"_id":"5610b2c5e4b08e404b6c1c95"},{"created-at":1443934931280,"author":{"login":"devn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"chunk-next","ns":"clojure.core"},"_id":"5610b2d3e4b0686557fcbd45"}],"line":706,"examples":[{"updated-at":1443935100136,"created-at":1443935100136,"author":{"login":"devn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3"},"body":"(let [chunked-cons (seq (range 1 42))\n rest-chunk (chunk-rest chunked-cons)]\n\n (class rest-chunk)\n ;; => clojure.lang.LazySeq\n\n (first rest-chunk)\n ;; => 33\n\n (last rest-chunk)\n ;; => 41\n)","_id":"5610b37ce4b08e404b6c1c96"}],"notes":null,"tag":"clojure.lang.ISeq","arglists":["s"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core/chunk-rest"},{"added":"1.0","ns":"clojure.core","name":"pcalls","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1299212798000,"author":{"login":"weakreference","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/86146f8bd5207b97701c0f16f0017334?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"pvalues","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521be6"},{"created-at":1336537809000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.core","name":"future","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521be7"},{"created-at":1518042729804,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"pmap","ns":"clojure.core"},"_id":"5a7b7e69e4b0316c0f44f8aa"}],"line":7184,"examples":[{"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":"user=> (pcalls function-1 function-2 ...)\n\n(result1 result2 ...)","created-at":1281093054000,"updated-at":1332951378000,"_id":"542692cdc026201cdc326ccf"},{"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"editors":[],"body":";; pcalls is implemented using Clojure futures. See examples for 'future'\n;; for discussion of an undesirable 1-minute wait that can occur before\n;; your standalone Clojure program exits if you do not use shutdown-agents.","created-at":1336537804000,"updated-at":1336537804000,"_id":"542692d4c026201cdc32702e"}],"notes":null,"arglists":["& fns"],"doc":"Executes the no-arg fns in parallel, returning a lazy sequence of\n their values","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/pcalls"},{"ns":"clojure.core","name":"*allow-unresolved-vars*","type":"var","see-alsos":null,"examples":[{"updated-at":1596399672161,"created-at":1596398748332,"author":{"login":"eltonlaw","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/14999531?v=4"},"body":";; Symbols are resolved during analysis phase, throws error\n;; because a is not defined anywhere reachable\nuser=> (clojure.lang.Compiler/analyze clojure.lang.Compiler$C/EXPRESSION '(+ 1 a))\n\nSyntax error compiling at (REPL:1:68).\nUnable to resolve symbol: a in this context\n\n;; Don't throw an exception on unresolvable symbol, assumption that\n;; there's somewhere else vars are defined not visible to analyzer\n;; (Ex. some external javascript library)\nuser=> (binding [*allow-unresolved-vars* true]\n #_=> (clojure.lang.Compiler/analyze clojure.lang.Compiler$C/EXPRESSION '(+ 1 a)))\n\n#object[clojure.lang.Compiler$StaticMethodExpr 0x1441fb4f \"clojure.lang.Compiler$StaticMethodExpr@1441fb4f\"]\n","editors":[{"avatar-url":"https://avatars2.githubusercontent.com/u/14999531?v=4","account-source":"github","login":"eltonlaw"}],"_id":"5f271c9ce4b0b1e3652d732e"}],"notes":[{"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/20086?v=4"},"updated-at":1617633337145,"created-at":1617633337145,"body":"Originally added to support specific ClojureScript use of the analyzer in the preliminary version of ClojureScript by C.Houser, see https://github.com/richhickey/clojure-contrib/blob/master/clojurescript/src/clojure/contrib/clojurescript.clj#L307-L310.","_id":"606b2039e4b0b1e3652d74b3"}],"arglists":[],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core/*allow-unresolved-vars*"},{"added":"1.2","ns":"clojure.core","name":"remove-all-methods","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1337585106000,"author":{"login":"abrooks","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/69976?v=2"},"to-var":{"ns":"clojure.core","name":"remove-method","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c88"},{"created-at":1341270438000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"prefers","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c89"},{"created-at":1341270443000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"methods","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c8a"},{"created-at":1341270446000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"get-method","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c8b"},{"created-at":1341270452000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"defmulti","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c8c"},{"created-at":1341270455000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"defmethod","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c8d"}],"line":1806,"examples":[{"author":{"login":"shockbob","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon"},"editors":[],"body":";; example showing use of multi-methods before and after remove-all-methods\n;; after removing all the methods, both circle and line tos functions throw\n;; exceptions\n\nuser=> (defmulti tos :Ob)\nnil\nuser=> (defn line [p1 p2] {:Ob :line :p1 p1 :p2 p2})\n#'user/line\nuser=> (defn circle [cent rad] {:Ob :circle :cent cent :rad rad})\n#'user/circle\nuser=> (defmethod tos :line [l] (str \"Line:\" (l :p1) (l :p2)))\n#\nuser=> (defmethod tos :circle [c] (str \"Circle:\" (c :cent) (c :rad)))\n#\nuser=> (println (tos (circle [2 3] 3.3)))\nCircle:[2 3]3.3\nnil\nuser=> (println (tos (line [1 1][0 0])))\nLine:[1 1][0 0]\nnil\nuser=> (remove-all-methods tos)\n#\nuser=> (println (tos (circle [2 3] 3.3)))\njava.lang.IllegalArgumentException: No method in multimethod 'tos' for dispatch\nvalue: :circle (NO_SOURCE_FILE:0)\nuser=> (println (tos (line [1 1][0 0])))\njava.lang.IllegalArgumentException: No method in multimethod 'tos' for dispatch\nvalue: :line (NO_SOURCE_FILE:0)\nuser=>","created-at":1313920017000,"updated-at":1313920017000,"_id":"542692ccc026201cdc326c6b"}],"notes":null,"arglists":["multifn"],"doc":"Removes all of the methods of multimethod.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/remove-all-methods"},{"added":"1.0","ns":"clojure.core","name":"ns-resolve","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1289661007000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"resolve","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b3d"}],"line":4385,"examples":[{"author":{"login":"jamesqiu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bc1268deaa7f2e78fe2b5ea76e6481d8?r=PG&default=identicon"},"editors":[],"body":"user=> (defn f [n] (* n n n))\n#'user/f\nuser=> ((ns-resolve *ns* (symbol \"f\")) 10)\n1000","created-at":1328007015000,"updated-at":1328007015000,"_id":"542692d4c026201cdc32701e"},{"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"editors":[],"body":";; See also http://clojure.org/namespaces for information on namespaces in Clojure and how to inspect and manipulate them","created-at":1348479408000,"updated-at":1348479408000,"_id":"542692d4c026201cdc32701f"},{"updated-at":1601821751716,"created-at":1601821751716,"author":{"login":"jimka2001","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/6414129?v=4"},"body":";; In the binary form of `ns-resolve`, if a fully qualified symbol is given as second argument of `ns-resolve`, then the namespace (given as first argument) is ignored\n(ns-resolve (find-ns 'clojure.core) 'clojure-rte.core/xyzzy)\n;; => #'clojure-rte.core/xyzzy","_id":"5f79dc37e4b0b1e3652d73c8"}],"notes":[{"updated-at":1332557686000,"body":"The appropriate value for the env arg is what you get from the implicit &env arg available to a macro.","created-at":1332557686000,"author":{"login":"steveminer","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d28543d134185d12d4006a74738d233e?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fdb"}],"arglists":["ns sym","ns env sym"],"doc":"Returns the var or Class to which a symbol will be resolved in the\n namespace (unless found in the environment), else nil. Note that\n if the symbol is fully qualified, the var/Class to which it resolves\n need not be present in the namespace.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/ns-resolve"},{"added":"1.5","ns":"clojure.core","name":"as->","file":"clojure/core.clj","type":"macro","column":1,"see-alsos":[{"created-at":1411997691800,"author":{"login":"abrooks","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/69976?v=2"},"to-var":{"ns":"clojure.core","name":"->","library-url":"https://github.com/clojure/clojure"},"_id":"54295ffbe4b09282a148f1ed"},{"created-at":1411997716841,"author":{"login":"abrooks","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/69976?v=2"},"to-var":{"ns":"clojure.core","name":"->>","library-url":"https://github.com/clojure/clojure"},"_id":"54296014e4b09282a148f1ee"},{"created-at":1411997732554,"author":{"login":"abrooks","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/69976?v=2"},"to-var":{"ns":"clojure.core","name":"cond->","library-url":"https://github.com/clojure/clojure"},"_id":"54296024e4b09282a148f1ef"},{"created-at":1411997750265,"author":{"login":"abrooks","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/69976?v=2"},"to-var":{"ns":"clojure.core","name":"cond->>","library-url":"https://github.com/clojure/clojure"},"_id":"54296036e4b09282a148f1f1"},{"created-at":1411997759234,"author":{"login":"abrooks","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/69976?v=2"},"to-var":{"ns":"clojure.core","name":"some->","library-url":"https://github.com/clojure/clojure"},"_id":"5429603fe4b09282a148f1f2"},{"created-at":1411997771032,"author":{"login":"abrooks","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/69976?v=2"},"to-var":{"ns":"clojure.core","name":"some->>","library-url":"https://github.com/clojure/clojure"},"_id":"5429604be4b09282a148f1f3"}],"line":7764,"examples":[{"body":"(def owners [{:owner \"Jimmy\"\n :pets (ref [{:name \"Rex\"\n :type :dog}\n {:name \"Sniffles\"\n :type :hamster}])} \n {:owner \"Jacky\" \n :pets (ref [{:name \"Spot\" \n :type :mink}\n {:name \"Puff\" \n :type :magic-dragon}])}])\n\n;; This example is contrived as there are other more \n;; terse ways of expressing the idea. It demonstrates\n;; several of the ways to extract items from a collection.\n;; Notice how the collection can be used in function or \n;; parameter position.\n(as-> owners $ (nth $ 0) (:pets $) (deref $) ($ 1) ($ :type))\n;;=> :hamster","author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"},"created-at":1412263021928,"updated-at":1412263021928,"_id":"542d6c6de4b05f4d257a298b"},{"body":"(as-> 0 n\n (inc n) ; n is 0 here passed from first parameter to as->\n (inc n)) ; n is 1 here passed from result of previous inc expression\n;;=> 2","author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"created-at":1422928871993,"updated-at":1422928871993,"_id":"54d02be7e4b0e2ac61831cf2"},{"editors":[{"login":"jamesmacaulay","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/340?v=3"}],"body":"; use it in the middle of a -> pipeline to sprinkle in some flexibility\n(-> [10 11]\n (conj 12)\n (as-> xs (map - xs [3 2 1]))\n (reverse))\n; (11 9 7)","author":{"avatar-url":"https://avatars.githubusercontent.com/u/340?v=3","account-source":"github","login":"jamesmacaulay"},"created-at":1452207578399,"updated-at":1452207828195,"_id":"568eeddae4b0f37b65a3c280"},{"updated-at":1456947738297,"created-at":1456947738297,"author":{"login":"x","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/693546?v=3"},"body":";; when you want to use arbitrary positioning of your argument in a thread macro\n(as-> {:a 1 :b 2} m\n (update m :a + 10)\n (reduce (fn [s [_ v]] (+ s v)) 0 m))\n\n;; when you'd like an if statement in your thread\n(as-> {:a 1 :b 2} m\n (update m :a + 10)\n (if update-b\n (update m :b + 10)\n m))","_id":"56d7421ae4b0b41f39d96cdb"},{"editors":[{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},{"login":"greydrizzle","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/5403136?v=4"}],"body":";; as-> with destructured binding\n\n(let [req {:host \"//mysite.com\" :path \"/a/123\" :x \"15.1\" :y \"84.2\"}]\n (as-> req {:keys [host path x y] :as m}\n (assoc m :url (str host path))\n (assoc m :coord [(Double/valueOf x) (Double/valueOf y)])))\n\n;; {:host \"//mysite.com\" :path \"/a/123\" :x \"15.1\" :y \"84.2\" :url \"//mysite.com/a/123\" :coord [15.1 84.2]}","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"},"created-at":1532889321412,"updated-at":1554166083397,"_id":"5b5e08e9e4b00ac801ed9e3a"}],"macro":true,"notes":null,"arglists":["expr name & forms"],"doc":"Binds name to expr, evaluates the first form in the lexical context\n of that binding, then binds name to that result, repeating for each\n successive form, returning the result of the last form.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/as->"},{"added":"1.0","ns":"clojure.core","name":"aset-boolean","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1493752979563,"author":{"login":"barak-haviv","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/2076998?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"boolean-array","ns":"clojure.core"},"_id":"5908dc93e4b01f4add58fea1"}],"line":3982,"examples":[{"author":{"login":"shockbob","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon"},"editors":[],"body":";; create an array of 10 booleans and set one value to true\n;; using aset-boolean\n\nuser=> (def bs (boolean-array 10))\n#'user/bs\nuser=> (vec bs)\n[false false false false false false false false false false]\nuser=> (aset-boolean bs 2 true)\ntrue\nuser=> (vec bs)\n[false false true false false false false false false false]\nuser=>","created-at":1313914167000,"updated-at":1313914167000,"_id":"542692ccc026201cdc326c67"}],"notes":[{"body":"See [aset](http://clojuredocs.org/clojure.core/aset) for illustrations of multi-dimensional syntax.","created-at":1432829103674,"updated-at":1432829103674,"author":{"login":"mars0i","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1836941?v=3"},"_id":"55673cafe4b03e2132e7d171"}],"arglists":["array idx val","array idx idx2 & idxv"],"doc":"Sets the value at the index/indices. Works on arrays of boolean. Returns val.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/aset-boolean"},{"added":"1.0","ns":"clojure.core","name":"trampoline","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1289618007000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"loop","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521df6"},{"created-at":1289618015000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"recur","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521df7"},{"created-at":1422376146394,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"},"to-var":{"ns":"clojure.core","name":"letfn","library-url":"https://github.com/clojure/clojure"},"_id":"54c7bcd2e4b081e022073c35"}],"line":6370,"examples":[{"author":{"login":"dakrone","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bcacd00a7f05c4772329cf9f446c7987?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":"(defn foo [x]\n (if (< x 0)\n (println \"done\")\n #(foo (do (println :x x) (dec x)))))\n;; #'user/foo\n\n;; `trampoline` will keep calling the function \n;; for as long as \"foo\" returns a function.\n\n(trampoline foo 10)\n;; :x 10\n;; :x 9\n;; :x 8\n;; :x 7\n;; :x 6\n;; :x 5\n;; :x 4\n;; :x 3\n;; :x 2\n;; :x 1\n;; :x 0\n;; done\n;;=> nil","created-at":1293675043000,"updated-at":1422375388791,"_id":"542692cfc026201cdc326e3b"},{"body":";; Short tutorial-style article with example of using trampoline at this link:\n;; http://jakemccrary.com/blog/2010/12/06/trampolining-through-mutual-recursion/","author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"created-at":1421338043181,"updated-at":1421338043181,"_id":"54b7e5bbe4b0e2ac61831cb5"},{"body":";; Using mutually recursive functions to implement a finite state machine (FSM)\n;; This machine has three states {a b c} and \n;; seven transitions {:a-b :a-c :b-a :b-c :c-a :c-b :final}.\n\n(defn foo [cmds]\n(letfn\n [(a-> [[_ & rs]]\n #(case _ \n :a-b (b-> rs)\n :a-c (c-> rs)\n false))\n (b-> [[_ & rs]]\n #(case _ \n :b-a (a-> rs)\n :b-c (c-> rs)\n false))\n (c-> [[_ & rs]]\n #(case _ \n :c-a (a-> rs)\n :c-b (c-> rs)\n :final true\n false))]\n (trampoline a-> cmds)))\n \n(foo [:a-b :b-c :c-a :a-c :final])\n;;=> true","author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"},"created-at":1422376023904,"updated-at":1422376335709,"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"_id":"54c7bc57e4b081e022073c33"},{"body":";; from \n;; Mutually recursive functions are nice for implementing \n;; finite state machines (FSAs)\n\n(defn elevator [commands]\n (letfn\n [(ff-open [[_ & r]]\n \"When the elevator is open on the 1st floor\n it can either close or be done.\"\n #(case _\n :close (ff-closed r)\n :done true\n false))\n (ff-closed [[_ & r]]\n \"When the elevator is closed on the 1st floor\n it can either open or go up.\"\n #(case _\n :open (ff-open r)\n :up (sf-closed r)\n false))\n (sf-closed [[_ & r]]\n \"When the elevator is closed on the 2nd floor\n it can either go down or open.\"\n #(case _\n :down (ff-closed r)\n :open (sf-open r)\n false))\n (sf-open [[_ & r]]\n \"When the elevator is open on the 2nd floor\n it can either close or be done\"\n #(case _\n :close (sf-closed r)\n :done true\n false))]\n\n (trampoline ff-open commands)))\n\n(elevator [:close :open :close :up :open :open :done])\n ;=> false\n(elevator [:close :up :open :close :down :open :done])\n ;=> true\n;; run at your own risk!\n(elevator (cycle [:close :open])) \n ; ... runs forever","author":{"login":"foxlog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/150418?v=3"},"created-at":1431484190885,"updated-at":1592576350068,"editors":[{"login":"foxlog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/150418?v=3"},{"avatar-url":"https://avatars0.githubusercontent.com/u/1719584?v=4","account-source":"github","login":"eihli"}],"_id":"5552b71ee4b01ad59b65f4cf"},{"updated-at":1482914635322,"created-at":1482914635322,"author":{"login":"mhmdsalem1993","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10787314?v=3"},"body":";; without trampoline\n(declare hatt)\n(defn catt [n]\n (when-not (zero? n)\n (when (zero? (rem n 100))\n (println \"catt:\" n))\n (hatt (dec n))))\n(defn hatt [n]\n (when-not (zero? n)\n (if (zero? (rem n 100))\n (println \"hatt:\" n))\n (catt (dec n))))\n\n;; std=> catt: 100000000\n;; std=> catt: 99999900\n;; std=> catt: 99999800\n;; std=> catt: 99999700\n;; std=> catt: 99999600\n;; std=> catt: 99999500\n;; std=> catt: 99999400\n;; .\n;; .\n;; .\n;; std => CompilerException java.lang.StackOverflowError\n\n;; with trampoline\n\n(declare hattr)\n\n(defn cattr [n]\n (when-not (zero? n)\n (when (zero? (rem n 100))\n (println \"cattr:\" n))\n (fn [] (hattr (dec n)))))\n(defn hattr [n]\n (when-not (zero? n)\n (if (zero? (rem n 100))\n (println \"hatttr:\" n))\n (fn [] (cattr (dec n)))))\n\n(trampoline cattr 10000000)\n\n;; std=> catt: 100000000\n;; std=> catt: 99999900\n;; std=> catt: 99999800\n;; std=> catt: 99999700\n;; std=> catt: 99999600\n;; std=> catt: 99999500\n;; std=> catt: 99999400\n;; .\n;; .\n;; .\n;; std=> catt: 100\n","_id":"58637b4be4b0fd5fb1cc9645"}],"notes":[{"updated-at":1291742621000,"body":"A tutorial on how to use trampoline is available here: \r\n\r\nhttp://pramode.net/clojure/2010/05/08/clojure-trampoline/\r\n\r\nand here:\r\n\r\nhttp://jakemccrary.com/blog/2010/12/06/trampolining-through-mutual-recursion.html","created-at":1286956413000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521f9a"},{"author":{"login":"dvingo","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/467827?v=4"},"updated-at":1588175434827,"created-at":1588175434827,"body":"The links above are dead. Here are the archived versions:\n\nhttps://web.archive.org/web/20190626232715/http://pramode.net:80/clojure/2010/05/08/clojure-trampoline/\n\nhttps://web.archive.org/web/20110111121137/http://jakemccrary.com:80/blog/2010/12/06/trampolining-through-mutual-recursion.html","_id":"5ea9a24ae4b087629b5a18eb"}],"arglists":["f","f & args"],"doc":"trampoline can be used to convert algorithms requiring mutual\n recursion without stack consumption. Calls f with supplied args, if\n any. If f returns a fn, calls that fn with no arguments, and\n continues to repeat, until the return value is not a fn, then\n returns that non-fn value. Note that if you want to return a fn as a\n final value, you must wrap it in some data structure and unpack it\n after trampoline returns.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/trampoline"},{"added":"1.9","ns":"clojure.core","name":"double?","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1496005756299,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"float?","ns":"clojure.core"},"_id":"592b3c7ce4b093ada4d4d784"},{"created-at":1496005947631,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"decimal?","ns":"clojure.core"},"_id":"592b3d3be4b093ada4d4d785"},{"created-at":1496005954103,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"bigdec?","ns":"clojure.core"},"_id":"592b3d42e4b093ada4d4d786"}],"line":1440,"examples":[{"updated-at":1496005747580,"created-at":1496005747580,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"body":";;;; true for instances of java.lang.Double\n\n(double? 1.0)\n;;=> true\n(double? (new Double \"1\"))\n;;=> true\n\n;;;; false for instances of java.lang.Float, java.lang.BigDecimal\n\n(double? (new Float \"1\"))\n;;=> false\n(double? 1.0M)\n;;=> false\n(double? (new BigDecimal \"1\"))\n;;=> false\n","_id":"592b3c73e4b093ada4d4d783"}],"notes":null,"arglists":["x"],"doc":"Return true if x is a Double","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/double_q"},{"added":"1.0","ns":"clojure.core","name":"when-not","file":"clojure/core.clj","type":"macro","column":1,"see-alsos":[{"created-at":1302596050000,"author":{"login":"Havvy","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e799a79441c7543be48562403411cd13?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"when","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d1b"},{"created-at":1323280013000,"author":{"login":"mmwaikar","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/29d36f4c9f39c9f8ff61c07033b13118?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"when-let","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d1c"},{"created-at":1334293346000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.core","name":"if","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d1d"}],"line":501,"examples":[{"updated-at":1423066223241,"created-at":1280776138000,"body":";; build tuples over sets with the same cardinality \n(map\n #(when-not (= %2 %3) [%1 %2 %3])\n (iterate inc 0) ; a lazy list of indecies\n [:a :b :c]\n [:a :a :a])\n;;=> (nil [1 :b :a] [2 :c :a])\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3","account-source":"github","login":"phreed"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3","account-source":"github","login":"devn"},"_id":"542692c8c026201cdc326a4a"},{"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"editors":[],"body":";; See examples for \"if\" explaining Clojure's idea of logical true\n;; and logical false.","created-at":1334293370000,"updated-at":1334293370000,"_id":"542692d6c026201cdc3270b7"},{"body":";; when-not is similar to unless (in other languages).\n;; An alias can be provided with a macro\n(defmacro unless [& args] `(when-not ~@args))\n\n(map #(unless (= %2 %3) [%1 %2 %3])\n (iterate inc 0) ; a lazy list for indecies\n [:a :b :c]\n [:a :a :a]) \n;;=> (nil [1 :b :a] [2 :c :a])","author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"},"created-at":1423066081989,"updated-at":1423066244981,"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"_id":"54d243e1e4b081e022073c5c"},{"updated-at":1546901293467,"created-at":1546901293467,"author":{"login":"dijonkitchen","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/11434205?v=4"},"body":"(when-not false 2)\n;; 2\n","_id":"5c33d72de4b0ca44402ef614"},{"updated-at":1546901306925,"created-at":1546901306925,"author":{"login":"dijonkitchen","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/11434205?v=4"},"body":"(when-not true 2)\n;; nil\n","_id":"5c33d73ae4b0ca44402ef615"}],"macro":true,"notes":null,"arglists":["test & body"],"doc":"Evaluates test. If logical false, evaluates body in an implicit do.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/when-not"},{"added":"1.0","ns":"clojure.core","name":"*1","file":"clojure/core.clj","type":"var","column":1,"see-alsos":[{"created-at":1302912238000,"author":{"login":"hoornet","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5834f829a9def19620d4014c46642172?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"*2","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b4a"},{"created-at":1302912243000,"author":{"login":"hoornet","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5834f829a9def19620d4014c46642172?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"*3","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b4b"}],"dynamic":true,"line":6345,"examples":[{"updated-at":1412880834853,"created-at":1279047952000,"body":"\"Hello!\"\n;;=> \"Hello!\"\n\n*1\n;;=> \"Hello!\"\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2","account-source":"github","login":"phreed"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/142529?v=3","account-source":"github","login":"nipra"},"_id":"542692cac026201cdc326b1a"}],"notes":null,"arglists":[],"doc":"bound in a repl thread to the most recent value printed","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/*1"},{"added":"1.0","ns":"clojure.core","name":"vec","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1291951288000,"author":{"login":"alimoeeny","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e8dd06976ead4082d2181f3807117e1?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"vector","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521adb"},{"created-at":1291951295000,"author":{"login":"alimoeeny","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e8dd06976ead4082d2181f3807117e1?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"vector?","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521adc"},{"created-at":1291951303000,"author":{"login":"alimoeeny","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e8dd06976ead4082d2181f3807117e1?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"vector-of","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521add"}],"line":369,"examples":[{"author":{"login":"dpritchett","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/147981?v=3"},"editors":[{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},{"avatar-url":"https://avatars3.githubusercontent.com/u/11434205?v=4","account-source":"github","login":"dijonkitchen"},{"login":"whiteknees","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/67022623?v=4"}],"body":"user=> (vec '(1 2 3))\n[1 2 3]\n\nuser=> (vec [1 2 3])\n[1 2 3]\n\nuser=> (vec #{1 2 3})\n[1 2 3]\n\nuser=> (vec {:a 1 :b 2 :c 3})\n[[:a 1] [:b 2] [:c 3]]\n\nuser=> (vector {:a 1 :b 2 :c 3})\n[{:a 1, :b 2, :c 3}]\n\nuser=> (vec '())\n[]\n\nuser=> (vec nil)\n[]","created-at":1279075384000,"updated-at":1663872522168,"_id":"542692c9c026201cdc326a97"},{"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"editors":[],"body":";; Warning. If the arg is a Java array, then the returned vector will alias it,\n;; and modifying the array will thus modify the vector. To avoid this, do\n;; not modify the array after the vec call. One way to guarantee this is to\n;; make a copy of the array, call vec on the new array, and then lose all\n;; references to the copy so it cannot be accessed in any way.\n\nuser=> (def a (to-array (repeat 4 0)))\n#'user/a\nuser=> (seq a)\n(0 0 0 0)\nuser=> (def v (vec a))\n#'user/v\nuser=> v\n[0 0 0 0]\n\n;; Now change a, and v changes, too, since they share state.\nuser=> (aset a 2 -5)\n-5\nuser=> v\n[0 0 -5 0]\n\n;; One way to avoid this\nuser=> (def v (vec (aclone a)))\n#'user/v\nuser=> v\n[0 0 -5 0]\nuser=> (aset a 2 -20)\n-20\nuser=> v\n[0 0 -5 0]\n","created-at":1334463665000,"updated-at":1334463665000,"_id":"542692d5c026201cdc3270b4"}],"notes":null,"arglists":["coll"],"doc":"Creates a new vector containing the contents of coll. Java arrays\n will be aliased and should not be modified.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/vec"},{"added":"1.0","ns":"clojure.core","name":"*print-meta*","type":"var","see-alsos":[{"created-at":1351128584000,"author":{"login":"AtKaaZ","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e10dfa345f44b0fe72bbe081fd51b83?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"pr","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e5d"},{"created-at":1623879909739,"author":{"login":"squiter","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/238017?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"pprint","ns":"clojure.pprint"},"_id":"60ca70e5e4b0b1e3652d750d"}],"examples":[{"author":{"login":"AtKaaZ","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e10dfa345f44b0fe72bbe081fd51b83?r=PG&default=identicon"},"editors":[{"login":"AtKaaZ","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e10dfa345f44b0fe72bbe081fd51b83?r=PG&default=identicon"},{"login":"AtKaaZ","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e10dfa345f44b0fe72bbe081fd51b83?r=PG&default=identicon"}],"body":"user=> (binding [*print-meta* true] \n (pr (var defmacro)) )\n;;^{:macro true, :ns #, :name defmacro, :arglists ^{:line 424, :column 15} ([name doc-string? attr-map? [params*] body] [name doc-string? attr-map? ^{:line 425, :column 46} ([params*] body) + attr-map?]), :column 1, :added \"1.0\", :doc \"Like defn, but the resulting function name is declared as a\\n macro and will be used as a macro by the compiler when it is\\n called.\", :line 419, :file \"clojure/core.clj\"} #'clojure.core/defmacro\nnil\n","created-at":1351126556000,"updated-at":1351126806000,"_id":"542692d1c026201cdc326f37"},{"updated-at":1623879875905,"created-at":1623879875905,"author":{"login":"squiter","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/238017?v=4"},"body":"user=> (binding [*print-meta* true]\n (-> \"{:a ^{:b :c} {}}\"\n clojure.edn/read-string\n clojure.pprint/pprint))\n{:a ^{:b :c} {}}\nnil","_id":"60ca70c3e4b0b1e3652d750c"}],"notes":[{"updated-at":1351128651000,"body":"\"printing an object\" means via **pr** not print or println","created-at":1351128651000,"author":{"login":"AtKaaZ","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e10dfa345f44b0fe72bbe081fd51b83?r=PG&default=identicon"},"_id":"542692edf6e94c6970521ff1"},{"author":{"login":"squiter","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/238017?v=4"},"updated-at":1623879652487,"created-at":1623879652487,"body":"The `*print-meta*` works for `print` and `pprint` after Clojure 1.10.2. Source: https://clojure.atlassian.net/browse/CLJ-1445","_id":"60ca6fe4e4b0b1e3652d750b"}],"arglists":[],"doc":"If set to logical true, when printing an object, its metadata will also\n be printed in a form that can be read back by the reader.\n\n Defaults to false.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/*print-meta*"},{"added":"1.0","ns":"clojure.core","name":"when","file":"clojure/core.clj","type":"macro","column":1,"see-alsos":[{"created-at":1323279976000,"author":{"login":"mmwaikar","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/29d36f4c9f39c9f8ff61c07033b13118?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"when-not","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521aed"},{"created-at":1323279997000,"author":{"login":"mmwaikar","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/29d36f4c9f39c9f8ff61c07033b13118?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"when-let","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521aee"},{"created-at":1334293253000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.core","name":"if","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521aef"},{"created-at":1602793798332,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"boolean","ns":"clojure.core"},"_id":"5f88b146e4b0b1e3652d73e5"},{"created-at":1713009797181,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"when-some","ns":"clojure.core"},"_id":"661a748569fbcc0c226174bc"}],"line":495,"examples":[{"author":{"login":"dpritchett","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/147981?v=3"},"editors":[{"login":"philos99","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1de5617efb013ca7c9cf8e5646818ffa?r=PG&default=identicon"},{"login":"frangio","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/646001f0ba2b7df47a16c0a1d5b62225?r=PG&default=identicon"}],"body":"user=> (when (= 1 1) true)\ntrue\n\nuser=> (when (not= 1 1) true)\nnil","created-at":1279071998000,"updated-at":1325845615000,"_id":"542692cec026201cdc326df2"},{"author":{"login":"OnesimusUnbound","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2fa4c391db0d2d1744cc2cd0d787dd3d?r=PG&default=identicon"},"editors":[{"login":"philos99","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1de5617efb013ca7c9cf8e5646818ffa?r=PG&default=identicon"},{"login":"ElieLabeca","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/724e1112a2be4d5af767c0cf152d087e?r=PG&default=identicon"}],"body":"user=> (def has-value (when true\n (println \"Hello World\")\n \"Returned Value\"))\nHello World\n#'user/has-value\n\nuser=> has-value\n\"Returned Value\"\n\n","created-at":1311798084000,"updated-at":1331756178000,"_id":"542692cec026201cdc326df5"},{"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"editors":[],"body":";; See examples for \"if\" explaining Clojure's idea of logical true\n;; and logical false.","created-at":1334293296000,"updated-at":1334293296000,"_id":"542692d6c026201cdc3270b5"},{"body":";; When is a macro of (if .. do ..)\n\nuser=> (macroexpand '(when 1 2 3 4))\n(if 1 (do 2 3 4))\n\n;; if 1 is true, do will evaluate 2 3 4, but return values of 2 and 3 would be \n;; ignored. Value of 4 (last value) would always be returned. \n;; See https://clojuredocs.org/clojure.core/do for details\n\nuser=> (if 1 (do 2 3 4))\n4\n\n","author":{"login":"nickzam","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/89377?v=3"},"created-at":1421838215231,"updated-at":1421838215231,"_id":"54bf8787e4b0e2ac61831cbe"}],"macro":true,"notes":null,"arglists":["test & body"],"doc":"Evaluates test. If logical true, evaluates body in an implicit do.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/when"},{"added":"1.0","ns":"clojure.core","name":"int","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1333595304000,"author":{"login":"Ljos","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/45b996a79abca465acaf6c0f10b0437?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"char","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d49"},{"to-var":{"library-url":"https://github.com/clojure/clojure","name":"long","ns":"clojure.core"},"author":{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},"created-at":1342917185000,"_id":"542692ebf6e94c6970521d4a"},{"to-var":{"library-url":"https://github.com/clojure/clojure","name":"integer?","ns":"clojure.core"},"author":{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},"created-at":1342917243000,"_id":"542692ebf6e94c6970521d4b"},{"to-var":{"library-url":"https://github.com/clojure/clojure","name":"ints","ns":"clojure.core"},"author":{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},"created-at":1342917294000,"_id":"542692ebf6e94c6970521d4c"},{"to-var":{"library-url":"https://github.com/clojure/clojure","name":"int-array","ns":"clojure.core"},"author":{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},"created-at":1342917326000,"_id":"542692ebf6e94c6970521d4d"},{"to-var":{"library-url":"https://github.com/clojure/clojure","name":"short","ns":"clojure.core"},"author":{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},"created-at":1342917681000,"_id":"542692ebf6e94c6970521d4e"}],"line":884,"examples":[{"updated-at":1661231771832,"created-at":1280208450000,"body":"user=> (int 1)\n1\n\nuser=> (int 1M)\n1\n\nuser=> (int 1.2)\n1\n\nuser=> (int \\1)\n49\n\nuser=> (int \\a)\n97\n\n;; Strings cannot be cast to an int.\nuser=> (int \"1\")\nExecution error (ClassCastException) at user/eval175 (REPL:1).\njava.lang.String cannot be cast to java.lang.Character\n\n;; Use Java interop instead\n(Integer/parseInt \"1\")\n;;=> 1\n\n;; Using JavaScript interop for ClojureScript\n(js/parseInt \"5\")\n;;=> 5\n\n(js/parseInt \"5.22\")\n;;=> 5","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3","account-source":"github","login":"Dimagog"},{"avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3","account-source":"github","login":"Dimagog"},{"avatar-url":"https://www.gravatar.com/avatar/45b996a79abca465acaf6c0f10b0437?r=PG&default=identicon","account-source":"clojuredocs","login":"Ljos"},{"login":"wdhowe","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/4631165?v=4"},{"avatar-url":"https://avatars.githubusercontent.com/u/747125?v=4","account-source":"github","login":"metehan"},{"login":"mathisto","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8226466?v=4"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/1703a0c3ed358b787f4b1bf3b2799472?r=PG&default=identicon","account-source":"clojuredocs","login":"Jacolyte"},"_id":"542692cec026201cdc326d78"}],"notes":[{"author":{"login":"jw-00000","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/2936?v=4"},"updated-at":1529869571125,"created-at":1529869571125,"body":"To convert a string containing a number to an integer, use Java's Integer/parseInt, e.g. `(Integer/parseInt \"-10\")`.","_id":"5b2ff503e4b00ac801ed9e1e"},{"body":"The `int` function fails to convert a float to a `clojure.lang.BigInt`. For example `(int (* 1.0 111111111111111111))` fails with an `IllegalArgumentException` exception.\n\nHere is a suggestion to work around this limitation.\n\n```\n(letfn [(-int [x]\n (try (int x)\n (catch IllegalArgumentException _\n (bigint x))\n (catch ArithmeticException _\n (bigint x))))]\n (-int (ceil (sqrt 22056254169643100399065378))))\n```\nwhich evaluates to the `BitInt` 4696408645939N.\n","created-at":1701245370509,"updated-at":1701246637088,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/6414129?v=4","account-source":"github","login":"jimka2001"},"_id":"6566f1ba69fbcc0c22617461"},{"author":{"login":"ClemRz","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1130946?v=4"},"updated-at":1721779607348,"created-at":1721779607348,"body":"Beware, the `int` function truncates and does not round:\n\n```\n=> (int 15538.999999999998)\n15538\n```","_id":"66a0459769fbcc0c226174de"}],"arglists":["x"],"doc":"Coerce to int","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/int"},{"added":"1.8","ns":"clojure.core","name":"map-entry?","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1602615292813,"author":{"login":"victoraldecoa","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/2746668?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"key","ns":"clojure.core"},"_id":"5f85f7fce4b0b1e3652d73e3"},{"created-at":1602615302919,"author":{"login":"victoraldecoa","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/2746668?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"val","ns":"clojure.core"},"_id":"5f85f806e4b0b1e3652d73e4"}],"line":1492,"examples":[{"updated-at":1476873674402,"created-at":1476873674402,"author":{"login":"G1enY0ung","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/15034155?v=3"},"body":"user=> (class {:a 1 :b 2})\nclojure.lang.PersistentArrayMap\n\nuser=> (class (first {:a 1 :b 2}))\nclojure.lang.MapEntry\n;; A map entry is treated as an ordered collection of key and value.\n;; https://github.com/clojure/clojure/blob/master/src/jvm/clojure/lang/MapEntry.java\n\nuser=> (map-entry? (first {:a 1 :b 2}))\ntrue","_id":"58074dcae4b001179b66bdce"}],"notes":null,"arglists":["x"],"doc":"Return true if x is a map entry","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/map-entry_q"},{"added":"1.0","ns":"clojure.core","name":"ns-refers","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1288055172000,"author":{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},"to-var":{"ns":"clojure.core","name":"ns-map","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521a82"}],"line":4280,"examples":[{"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"editors":[],"body":"user> (ns-refers 'clojure.main)\n{sorted-map #'clojure.core/sorted-map, read-line #'clojure.core/read-line, re-pattern #'clojure.core/re-pattern, keyword? #'clojure.core/keyword?, val #'clojure.core/val, chunked-seq? #'clojure.core/chunked-seq?, *compile-path* #'clojure.core/*compile-path*, ...chop...}","created-at":1288075058000,"updated-at":1288075058000,"_id":"542692c9c026201cdc326af9"}],"notes":null,"arglists":["ns"],"doc":"Returns a map of the refer mappings for the namespace.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/ns-refers"},{"added":"1.0","ns":"clojure.core","name":"rand","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1292321223000,"author":{"login":"alimoeeny","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e8dd06976ead4082d2181f3807117e1?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"rand-int","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f6a"},{"created-at":1311342603000,"author":{"login":"Havvy","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e799a79441c7543be48562403411cd13?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"rand-nth","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f6b"},{"created-at":1434034912362,"author":{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/94482?v=3"},"to-var":{"ns":"clojure.core","name":"shuffle","library-url":"https://github.com/clojure/clojure"},"_id":"5579a2e0e4b03e2132e7d18c"}],"line":4964,"examples":[{"author":{"login":"devijvers","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/81018e4231ac1ce8b7a9e6d377092656?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":";; Test `rand` never returns `n`:\nuser=> (some (partial <= 10) (take 100000 (repeatedly (fn [] (int (rand 10))))))\nnil\n","created-at":1279658909000,"updated-at":1285497610000,"_id":"542692c8c026201cdc326a0f"},{"author":{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},"editors":[],"body":"user=> (rand)\n0.17469201779243182\n\nuser=> (rand 100)\n49.542391492950834","created-at":1286329327000,"updated-at":1286329327000,"_id":"542692c8c026201cdc326a11"}],"notes":null,"arglists":["","n"],"doc":"Returns a random floating point number between 0 (inclusive) and\n n (default 1) (exclusive).","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/rand"},{"added":"1.0","ns":"clojure.core","name":"second","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1295238626000,"author":{"login":"TimMc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5d532e51427ef2f4ded31aaca16c8baf?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"first","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b2a"},{"created-at":1303125643000,"author":{"login":"Havvy","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e799a79441c7543be48562403411cd13?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"nth","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b2b"},{"created-at":1374512098000,"author":{"login":"alilee","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2fb0196dc5a7cd3a5cc73f1b9941c209?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"fnext","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b2c"},{"created-at":1374512133000,"author":{"login":"alilee","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2fb0196dc5a7cd3a5cc73f1b9941c209?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"next","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b2d"}],"line":93,"examples":[{"updated-at":1423275208669,"created-at":1279071308000,"body":"user=> (second '(:alpha :bravo :charlie))\n:bravo\n\nuser=> (second [1 2 3])\n2\n\nuser=> (second {:a 1 :b 2 :c 3})\n[:b 2]\n\nuser=> (second #{1 2 3})\n2\n\nuser=> (second [1 2])\n2\n\nuser=> (second [1])\nnil\n\nuser=> (second [])\nnil\n\nuser=> (second nil)\nnil","editors":[{"avatar-url":"https://avatars2.githubusercontent.com/u/22608?v=4","account-source":"github","login":"MrHus"},{"avatar-url":"https://avatars2.githubusercontent.com/u/22608?v=4","account-source":"github","login":"MrHus"},{"avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3","account-source":"github","login":"Dimagog"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/147981?v=3","account-source":"github","login":"dpritchett"},"_id":"542692c7c026201cdc326949"}],"notes":[{"author":{"login":"glts","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/1483271?v=4"},"updated-at":1520169736267,"created-at":1520169736267,"body":"Synonym of `fnext`.","_id":"5a9bf308e4b0316c0f44f90b"}],"arglists":["x"],"doc":"Same as (first (next x))","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/second"},{"added":"1.2","ns":"clojure.core","name":"vector-of","file":"clojure/gvec.clj","type":"function","column":1,"see-alsos":[{"created-at":1291951396000,"author":{"login":"alimoeeny","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e8dd06976ead4082d2181f3807117e1?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"vec","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c44"},{"created-at":1291951401000,"author":{"login":"alimoeeny","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e8dd06976ead4082d2181f3807117e1?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"vector","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c45"},{"created-at":1291951406000,"author":{"login":"alimoeeny","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e8dd06976ead4082d2181f3807117e1?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"vector?","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c46"}],"line":523,"examples":[{"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"editors":[{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"}],"body":"user=> (conj (vector-of :int) 1 2 3)\n[1 2 3] ; <-- note, these are unboxed internally\n\nuser=> (vector-of :int 1 2 3)\n[1 2 3] ; same here\n\nuser=> (type (conj (vector-of :int) 1 2 3))\nclojure.core.Vec\n","created-at":1284711309000,"updated-at":1423523824042,"_id":"542692c6c026201cdc3268d1"}],"notes":[{"author":{"login":"Hindol","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/705227?v=4"},"updated-at":1581663088148,"created-at":1581663088148,"body":"The primary use of `vector-of` is to be space efficient. As most of Clojure deals with boxed types, boxing/unboxing will happen everytime an element is taken out/inserted.","_id":"5e464370e4b0ca44402ef838"}],"arglists":["t","t & elements"],"doc":"Creates a new vector of a single primitive type t, where t is one\n of :int :long :float :double :byte :short :char or :boolean. The\n resulting vector complies with the interface of vectors in general,\n but stores the values unboxed internally.\n\n Optionally takes one or more elements to populate the vector.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/vector-of"},{"ns":"clojure.core","name":"hash-combine","file":"clojure/core_deftype.clj","type":"function","column":1,"see-alsos":null,"line":128,"examples":[{"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":";; Calculates the hashes for x and y and produces a new hash that represents\n;; the combination of the two.\n\nuser=> (hash-combine 100 \"a\")\n-1640524969\n","created-at":1280320404000,"updated-at":1285496804000,"_id":"542692cdc026201cdc326d1e"}],"notes":null,"arglists":["x y"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core/hash-combine"},{"added":"1.0","ns":"clojure.core","name":">","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1291975136000,"author":{"login":"alimoeeny","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e8dd06976ead4082d2181f3807117e1?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"=","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c4f"},{"created-at":1291975141000,"author":{"login":"alimoeeny","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e8dd06976ead4082d2181f3807117e1?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"not=","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c50"},{"created-at":1291975147000,"author":{"login":"alimoeeny","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e8dd06976ead4082d2181f3807117e1?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"<","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c51"}],"line":1072,"examples":[{"author":{"login":"mattdw","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/ee24aacb65359196b0a1bad050f9a62f?r=PG&default=identicon"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"login":"Iceland_jack","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/c889e0a95a3bb07f90ab28ad442f1127?r=PG&default=identicon"}],"body":"user=> (> 1 2)\nfalse\nuser=> (> 2 1)\ntrue\nuser=> (> 2 2)\nfalse\nuser=> (> 6 5 4 3 2)\ntrue\nuser=> (sort > (vals {:foo 5, :bar 2, :baz 10}))\n(10 5 2)","created-at":1280322039000,"updated-at":1340813399000,"_id":"542692ccc026201cdc326c96"}],"notes":null,"arglists":["x","x y","x y & more"],"doc":"Returns non-nil if nums are in monotonically decreasing order,\n otherwise false.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/>"},{"added":"1.0","ns":"clojure.core","name":"replace","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1281451180000,"author":{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},"to-var":{"ns":"clojure.walk","name":"prewalk-replace","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521dc2"},{"created-at":1281451198000,"author":{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},"to-var":{"ns":"clojure.walk","name":"postwalk-replace","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521dc3"},{"created-at":1385849073000,"author":{"login":"Alexey Tarasevich","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/43e0398b89022d32b43de4c968069312?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"map","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521dc4"},{"created-at":1439523160945,"author":{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/94482?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"replace","ns":"clojure.string"},"_id":"55cd6158e4b072d7f27980e7"}],"line":5111,"examples":[{"updated-at":1670326100220,"created-at":1280289240000,"body":";; Vectors in the first argument are implicitly treated like maps\n;; from zero-based indexes to values so this is equivalent to\n;;\n;; (replace {0 :zeroth, 1 :first, 2 :second, 3 :third, 4 :fourth} [0 2 4 0])\nuser=> (replace [:zeroth :first :second :third :fourth] [0 2 4 0])\n[:zeroth :second :fourth :zeroth]\n\nuser=> (replace [10 9 8 7 6] [0 2 4])\n[10 8 6]","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"avatar-url":"https://www.gravatar.com/avatar/c889e0a95a3bb07f90ab28ad442f1127?r=PG&default=identicon","account-source":"clojuredocs","login":"Iceland_jack"},{"avatar-url":"https://www.gravatar.com/avatar/c889e0a95a3bb07f90ab28ad442f1127?r=PG&default=identicon","account-source":"clojuredocs","login":"Iceland_jack"},{"login":"agnul","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7526067?v=4"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/2c8ecc24181d171df85a26458b9cd5f?r=PG&default=identicon","account-source":"clojuredocs","login":"jneira"},"_id":"542692cbc026201cdc326bca"},{"author":{"login":"huahaiy","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/889685?v=2"},"editors":[{"login":"Iceland_jack","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/c889e0a95a3bb07f90ab28ad442f1127?r=PG&default=identicon"},{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"}],"body":"user=> (replace {2 :two, 4 :four} [4 2 3 4 5 6 2])\n[:four :two 3 :four 5 6 :two]\n\nuser=> (replace '{0 ZERO, 1 ONE, 2 TWO} '(This is the code 0 1 2 0))\n(This is the code ZERO ONE TWO ZERO)","created-at":1305078367000,"updated-at":1423093999544,"_id":"542692cbc026201cdc326bce"},{"author":{"login":"Alexey Tarasevich","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/43e0398b89022d32b43de4c968069312?r=PG&default=identicon"},"editors":[],"body":"; Behaves somewhat similar to map, but notice the differences\nuser=> (map [:zeroth :first :second :third :fourth] [0 2 4 0])\n(:zeroth :second :fourth :zeroth)\n\n; 1. replace returns a vector, while map returns a seq\n; 2. replace keeps unmatched values, while map replace with nil\nuser=> (map {} [0])\n(nil)\nuser=> (map [] [0])\nIndexOutOfBoundsException clojure.lang.PersistentVector.arrayFor (PersistentVector.java:107)\n","created-at":1385849488000,"updated-at":1385849488000,"_id":"542692d5c026201cdc327071"},{"updated-at":1472236519899,"created-at":1472236519899,"author":{"login":"ertugrulcetin","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8271291?v=3"},"body":"user=> (replace {2 :a, 4 :b} [1 2 3 4])\n;;=> [1 :a 3 :b]","_id":"57c08be7e4b0709b524f04d5"},{"updated-at":1517940922527,"created-at":1517935073686,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"body":";; On hash-maps:\n\n(def user {:name \"jack\" :city \"London\" :id 123})\n(defn entry [k v] (clojure.lang.MapEntry/create k v))\n(def sub {(entry :city \"London\") [:postcode \"WD12\"]})\n\n(into {} (replace sub user))\n;; {:name \"jack\", :postcode \"WD12\", :id 123}","editors":[{"avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"}],"_id":"5a79d9e1e4b0e2d9c35f741b"}],"notes":[{"updated-at":1280289719000,"body":"The behaviour for vectors was a little strange for me. I'd say replace \"selects\" from \"smap\" the indexes which are in \"coll\"","created-at":1280289719000,"author":{"login":"jneira","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2c8ecc24181d171df85a26458b9cd5f?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521f92"}],"arglists":["smap","smap coll"],"doc":"Given a map of replacement pairs and a vector/collection, returns a\n vector/seq with any elements = a key in smap replaced with the\n corresponding val in smap. Returns a transducer when no collection\n is provided.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/replace"},{"added":"1.9","ns":"clojure.core","name":"int?","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1495654441434,"author":{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/94482?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"integer?","ns":"clojure.core"},"_id":"5925e029e4b093ada4d4d73c"},{"created-at":1495654448767,"author":{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/94482?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"number?","ns":"clojure.core"},"_id":"5925e030e4b093ada4d4d73d"},{"created-at":1495654503504,"author":{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/94482?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"pos-int?","ns":"clojure.core"},"_id":"5925e067e4b093ada4d4d73e"},{"created-at":1495654510856,"author":{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/94482?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"neg-int?","ns":"clojure.core"},"_id":"5925e06ee4b093ada4d4d73f"},{"created-at":1495654522385,"author":{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/94482?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"nat-int?","ns":"clojure.core"},"_id":"5925e07ae4b093ada4d4d740"}],"line":1414,"examples":[{"editors":[{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/94482?v=3"}],"body":";; Note that this will return true for things which aren't strictly Java ints:\n(int? 42) \n;; => true\n\n(int? (java.lang.Integer. 42)) \n;; => true\n\n(int? (java.lang.Long. 42)) \n;; => true\n\n(int? 42.0)\n;; => false\n\n(int? (bigdec 42))\n;; => false\n\n;; The distinction between int? and integer? is that integer? will return true \n;; for BigInts:\n\n(int? (bigint 42)) \n;; => false\n\n(integer? (bigint 42)) \n;; => true\n\n(int? java.math.BigInteger/ONE)\n;; => false\n\n(integer? java.math.BigInteger/ONE)\n;; => true\n","author":{"avatar-url":"https://avatars.githubusercontent.com/u/94482?v=3","account-source":"github","login":"timgilbert"},"created-at":1495654364949,"updated-at":1495655962185,"_id":"5925dfdce4b093ada4d4d73a"},{"editors":[{"login":"liuchong","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/236058?v=4"}],"body":";; Here is the definition, it's simple (and 呵呵哒):\n;;\n;; (defn int?\n;; \"Return true if x is a fixed precision integer\"\n;; {:added \"1.9\"}\n;; [x] (or (instance? Long x)\n;; (instance? Integer x)\n;; (instance? Short x)\n;; (instance? Byte x)))\n;;\n\n(int? (Long/MAX_VALUE))\n;; => true\n\n(int? (Long/MIN_VALUE))\n;; => true\n\n(int? 0.0)\n;; => false","author":{"avatar-url":"https://avatars2.githubusercontent.com/u/236058?v=4","account-source":"github","login":"liuchong"},"created-at":1572414469669,"updated-at":1572414534344,"_id":"5db92405e4b0ca44402ef7d5"}],"notes":null,"arglists":["x"],"doc":"Return true if x is a fixed precision integer","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/int_q"},{"added":"1.0","ns":"clojure.core","name":"associative?","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1570520657017,"author":{"login":"xmo-odoo","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/7571158?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"assoc","ns":"clojure.core"},"_id":"5d9c3e51e4b0ca44402ef7c5"},{"created-at":1570520665970,"author":{"login":"xmo-odoo","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/7571158?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"assoc-in","ns":"clojure.core"},"_id":"5d9c3e59e4b0ca44402ef7c6"},{"created-at":1570520672069,"author":{"login":"xmo-odoo","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/7571158?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"update","ns":"clojure.core"},"_id":"5d9c3e60e4b0ca44402ef7c7"},{"created-at":1570520678789,"author":{"login":"xmo-odoo","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/7571158?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"update-in","ns":"clojure.core"},"_id":"5d9c3e66e4b0ca44402ef7c8"},{"created-at":1772182819420,"author":{"login":"daveliepmann","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/974443?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"sequential?","ns":"clojure.core"},"_id":"69a15d2380b64033abf8ed1c"}],"line":6300,"examples":[{"author":{"login":"Clinton","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e460563f35b0b25d8671d6ef83f54ce?r=PG&default=identicon"},"editors":[],"body":"user=> (associative? [1 2 3]) ; vector\ntrue\nuser=> (associative? '(1 2 3)) ; list\nfalse\nuser=> (associative? {:a 1 :b 2}) ; map\ntrue\nuser=> (associative? #{:a :b :c}) ; set\nfalse\nuser=> (associative? \"fred\") ; string\nfalse\n","created-at":1327061297000,"updated-at":1327061297000,"_id":"542692d2c026201cdc326f4d"}],"notes":null,"arglists":["coll"],"doc":"Returns true if coll implements Associative","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/associative_q"},{"added":"1.3","ns":"clojure.core","name":"unchecked-int","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1496090254478,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"int","ns":"clojure.core"},"_id":"592c868ee4b093ada4d4d79f"}],"line":3560,"examples":[{"updated-at":1496090244589,"created-at":1496090244589,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"body":"(unchecked-int 1)\n;;=> 1\n(unchecked-int 1N)\n;;=> 1\n(unchecked-int 1.1)\n;;=> 1\n(unchecked-int 1.9)\n;;=> 1\n(unchecked-int 5/3)\n;;=> 1\n\n(unchecked-int -1)\n;;=> -1\n(unchecked-int -1N)\n;;=> -1\n(unchecked-int -1.1)\n;;=> -1\n(unchecked-int -1.9)\n;;=> -1\n(unchecked-int -5/3)\n;;=> -1\n\n;;;; Note that (unchecked-int) does not range check its argument\n;;;; so integer overflow or rounding may occur. \n;;;; Use (int) if you want to throw an exception in such cases.\n\n(unchecked-int 2147483648)\n;;=> -2147483648\n(unchecked-int -2147483649)\n;;=> 2147483647\n\n(int 2147483648)\n;;=> IllegalArgumentException Value out of range for int: 2147483648\n(long -2147483649)\n;;=> IllegalArgumentException Value out of range for int: -2147483649\n\n(unchecked-int 1.0E9)\n;;=> 1000000000\n(unchecked-int 1.0E10)\n;;=> 2147483647\n(unchecked-int 1.0E11)\n;;=> 2147483647\n\n(int 1.0E9)\n;;=> 1000000000\n(int 1.0E10)\n;;=> IllegalArgumentException Value out of range for int: 1.0E10\n(int 1.0E11)\n;;=> IllegalArgumentException Value out of range for int: 1.0E11","_id":"592c8684e4b093ada4d4d79e"}],"notes":null,"arglists":["x"],"doc":"Coerce to int. Subject to rounding or truncation.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/unchecked-int"},{"added":"1.2","ns":"clojure.core","name":"set-error-handler!","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1287220602000,"author":{"login":"hugoduncan","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/80fa2a15219b987664e4d6f5c78b4c27?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"agent","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c1e"},{"created-at":1287220615000,"author":{"login":"hugoduncan","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/80fa2a15219b987664e4d6f5c78b4c27?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"agent-error","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c1f"},{"created-at":1329375224000,"author":{"login":"Claj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5fd658a8d2ef549071cb5286b1b874aa?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"restart-agent","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c20"}],"line":2211,"examples":[{"author":{"login":"Claj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5fd658a8d2ef549071cb5286b1b874aa?r=PG&default=identicon"},"editors":[{"login":"Claj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5fd658a8d2ef549071cb5286b1b874aa?r=PG&default=identicon"},{"login":"Claj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5fd658a8d2ef549071cb5286b1b874aa?r=PG&default=identicon"},{"login":"Claj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5fd658a8d2ef549071cb5286b1b874aa?r=PG&default=identicon"}],"body":"(def bond (agent 7))\n\n(defn err-handler-fn [ag ex]\n (println \"evil error occured: \" ex \" and we still have value \" @ag))\n\n(set-error-handler! bond err-handler-fn)\n\n;;division by zero:\n\n(send bond (fn [x] (/ x 0)))\n=>evil error occured: #Divide by zero> and we still have value 7\n\n(send bond inc)\n=>FAILURE ;;Agent is failed, needs restart, but keeps the last OK value\n\n@bond\n=>7\n\n(restart-agent bond 7) ;; or replace 7 with @ag\n\n(send bond inc)\n=># ;;because of async update\n\n@bond\n=>8\n","created-at":1329375108000,"updated-at":1329375308000,"_id":"542692d5c026201cdc32707d"},{"updated-at":1497900465897,"created-at":1497900465897,"author":{"login":"cloojure","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/7083783?v=3"},"body":"(deftest t-rstart\n (future (println \"running in a thread...\"))\n (let [agt (agent 0)\n\n ; This doesn't work\n h01 (fn [a e]\n (println :10 \"agent error found:\" )\n (println :11 \"restarting agent...\")\n (restart-agent a 100)\n (Thread/sleep 100)\n (println :12 \"agent restarted, state=\" @a))\n\n ; This works. Need to call restart-agent in a separate thread\n h02 (fn [a e]\n (println :20 \"agent error found:\" )\n (future\n (println :21 \"restarting agent...\")\n (restart-agent a 200)\n (println :22 \"agent restarted, state=\" @a))) ;=> 200\n ]\n (set-error-handler! agt h02)\n (send agt inc)\n (Thread/sleep 100) (println :01 @agt) ;=> 1\n (Thread/sleep 100) (send agt #(/ % 0))\n (Thread/sleep 100) (println :02 @agt) ;=> 200\n (Thread/sleep 100) (send agt inc)\n (Thread/sleep 100) (println :03 @agt) ;=> 201\n))\n\n; Output\n; running in a thread...\n; :01 1\n; :20 agent error found:\n; :21 restarting agent...\n; :22 agent restarted, state= 200\n; :02 200\n; :03 201","_id":"594825b1e4b06e730307db3c"}],"notes":null,"arglists":["a handler-fn"],"doc":"Sets the error-handler of agent a to handler-fn. If an action\n being run by the agent throws an exception or doesn't pass the\n validator fn, handler-fn will be called with two arguments: the\n agent and the exception.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/set-error-handler!"},{"ns":"clojure.core","name":"inst-ms*","type":"function","see-alsos":null,"examples":null,"notes":null,"tag":null,"arglists":["inst"],"doc":null,"library-url":"https://github.com/clojure/clojure","href":"/clojure.core/inst-ms*"},{"added":"1.0","ns":"clojure.core","name":"keyword?","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1495715288280,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"simple-keyword?","ns":"clojure.core"},"_id":"5926cdd8e4b093ada4d4d761"},{"created-at":1495715310898,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"qualified-keyword?","ns":"clojure.core"},"_id":"5926cdeee4b093ada4d4d763"},{"created-at":1548518287990,"author":{"login":"cljlc","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/36645452?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"keyword","ns":"clojure.core"},"_id":"5c4c838fe4b0ca44402ef637"}],"line":570,"examples":[{"author":{"login":"dpritchett","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/147981?v=3"},"editors":[{"avatar-url":"https://avatars0.githubusercontent.com/u/36645452?v=4","account-source":"github","login":"cljlc"},{"login":"borkdude","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/284934?v=4"}],"body":"(keyword? 'x)\n;;=> false\n\n(keyword? :x)\n;;=> true\n\n(keyword? true)\n;;=> false\n\n;; Note: some of the keywords below are non-conformant and will not work\n;; with destructuring. For more info see 'keyword'.\n\n(keyword? :-)\n;;=> true\n\n(keyword? :+)\n;;=> true\n\n(keyword? :-o)\n;;=> true\n\n(keyword? :')\n;;=> true\n\n(keyword? :#)\n;;=> true\n\n(keyword? :)\n;;=> true\n\n(keyword? :'/-)\n;;=> true\n\n(keyword? :'//-)\n;;=> true\n\n(keyword? :////)\n;;=> true\n\n(keyword? :'//-,)\n;;=> true\n\n(keyword? :'//,-)\n;;=> ArityException Wrong number of args (2) passed to: core/keyword? clojure.lang.AFn.throwArity (AFn.java:429)\n;; Note: the comma is taken as space, so the code above is equivalent to\n(keyword? :'// -)\n\n(keyword? :-:)\n;;=> RuntimeException Invalid token: :-: clojure.lang.Util.runtimeException (Util.java:221)\n;;=> RuntimeException Unmatched delimiter: ) clojure.lang.Util.runtimeException (Util.java:221)\n;; https://clojure.org/reference/reader states:\n;; \"Symbols beginning or ending with ':' are reserved by Clojure.\"\n\n(keyword? :-:-)\n;;=> true\n;; https://clojure.org/reference/reader states:\n;; \"A symbol can contain one or more non-repeating ':'s\" and:\n;; \"Keywords are like symbols, [...]\"\n\n(keyword? :....)\n;;=> true\n\n(keyword? :,,,,)\n;;=> RuntimeException Invalid token: : clojure.lang.Util.runtimeException (Util.java:221)\n;;=> RuntimeException Unmatched delimiter: ) clojure.lang.Util.runtimeException (Util.java:221)\n;; Note: the comma is taken as space, so the code above is equivalent to\n(keyword? : )\n\n(keyword? :a:b:c)\n;;=> true\n\n(keyword? :a.b.c)\n;;=> true\n\n(keyword? :73)\n;;=> true\n\n","created-at":1279074168000,"updated-at":1551304081227,"_id":"542692c6c026201cdc3268cc"}],"notes":null,"arglists":["x"],"doc":"Return true if x is a Keyword","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/keyword_q"},{"added":"1.0","ns":"clojure.core","name":"force","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1342465196000,"author":{"login":"sergey","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/fbf950615302e00a14bceec914af32ca?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"delay","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d92"}],"line":763,"examples":[{"author":{"login":"yasuto","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cacfb7ecf08cb6461767e514c93b7bf9?r=PG&default=identicon"},"editors":[{"login":"yasuto","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cacfb7ecf08cb6461767e514c93b7bf9?r=PG&default=identicon"},{"login":"yasuto","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cacfb7ecf08cb6461767e514c93b7bf9?r=PG&default=identicon"}],"body":";; an example for delay using an event-queue\nuser> (import [java.util.concurrent PriorityBlockingQueue])\njava.util.concurrent.PriorityBlockingQueue\nuser> (defn create-event-element [delayed-event tme]\n (struct event delayed-event tme))\n#'user/create-event-element\nuser> (defn comp-queue [e1 e2]\n (if (< (:time e1) (:time e2))\n true false))\n#'user/comp-queue\nuser> (defn update [n]\n\t(reset! c n))\n#'user/update\nuser> (defn create-event-queue [comp-queue size]\n (new PriorityBlockingQueue size (comp comp-queue)))\n#'user/create-event-queue\nuser> (def queue (create-event-queue comp-queue 10))\n#'user/queue\nuser> (def elements (take 10 (repeatedly \n\t\t\t (fn[](create-event-element \n\t\t\t\t (delay (update (rand-int 20)))\n\t\t\t\t (rand))))))\n#'user/elements\nuser> (def c (atom 0))\n#'user/c\nuser> @c\n0\nuser> (doseq [e elements]\n\t (.add queue e))\nnil\nuser> (dotimes [_ 10]\n\t (let [e (.poll queue)]\n\t\t (println \"c=\" @c)\n\t\t (print \"time=\" (:time e) \":\")\n\t\t (println (force (:object e)))))\nc= 0\ntime= 0.07805244345581108 :19\nc= 19\ntime= 0.24297414417455565 :6\nc= 6\ntime= 0.24427040715816817 :0\nc= 0\ntime= 0.24938478920862384 :17\nc= 17\ntime= 0.33612588239752494 :6\nc= 6\ntime= 0.5148481493716295 :5\nc= 5\ntime= 0.5823642080700586 :7\nc= 7\ntime= 0.7674970100941858 :4\nc= 4\ntime= 0.9206272921555505 :14\nc= 14\ntime= 0.9958255204018474 :4\nnil\nuser> @c\n4\nuser> (def elements (take 10 (repeatedly \n\t\t\t (fn[](create-event-element \n\t\t\t\t (delay (update (rand-int 20)))\n\t\t\t\t (rand))))))\n#'user/elements\n;; if we check 'element', delay objects will be evaluated. The below is\n;; this example. Please compare the above with the below.\nuser> elements \n({:object #, :time 0.48566816399656854} {:object #, :time 0.9374202154797486} {:object #, :time 0.3271116626875401} {:object #, :time 0.8843712542267577} {:object #, :time 0.86383171974926} {:object #, :time 0.2120086056700251} {:object #, :time 0.9406336968276247} {:object #, :time 0.2150071400135528} {:object #, :time 0.7520042839572664} {:object #, :time 0.6264819751284463})\n;; The object of the last elements is #. Therefore,\n;; This indicates the atom 'c' has already updated.\nuser> @c \n1 \nuser> (doseq [e elements]\n\t (.add queue e))\nnil\n;; 'atom c' has never been updated because it has already\n;; been evaluated.\nuser> (dotimes [_ 10]\n\t (let [e (.poll queue)]\n\t\t (println \"c=\" @c)\n\t\t (print \"time=\" (:time e) \":\")\n\t\t (println (force (:object e)))))\nc= 1\ntime= 0.2120086056700251 :14\nc= 1\ntime= 0.2150071400135528 :0\nc= 1\ntime= 0.3271116626875401 :17\nc= 1\ntime= 0.48566816399656854 :16\nc= 1\ntime= 0.6264819751284463 :1\nc= 1\ntime= 0.7520042839572664 :7\nc= 1\ntime= 0.86383171974926 :10\nc= 1\ntime= 0.8843712542267577 :15\nc= 1\ntime= 0.9374202154797486 :19\nc= 1\ntime= 0.9406336968276247 :5\nnil\nuser> ","created-at":1308852117000,"updated-at":1308852376000,"_id":"542692cdc026201cdc326ce6"},{"author":{"login":"yasuto","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cacfb7ecf08cb6461767e514c93b7bf9?r=PG&default=identicon"},"editors":[{"login":"yasuto","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cacfb7ecf08cb6461767e514c93b7bf9?r=PG&default=identicon"}],"body":";; the tarai benchmark comparing non-lazy version with lazy-version\n(defn tarai [x y z]\n (if (<= (x) (y))\n (y)\n (recur (fn [] (tarai (fn [] (- (x) 1)) y z))\n (fn [] (tarai (fn [] (- (y) 1)) z x))\n (fn [] (tarai (fn [] (- (z) 1)) x y)))))\n\n(defn tarai-d [x y z]\n (if (<= (force x) (force y))\n (force y)\n (recur (delay (tarai-d (- (force x) 1) y z))\n (delay (tarai-d (- (force y) 1) z x))\n (delay (tarai-d (- (force z) 1) x y)))))\n\nuser> (dotimes [_ 10] (time (tarai (fn [] 192) (fn [] 96) (fn [] 0))))\n\"Elapsed time: 139.660729 msecs\"\n\"Elapsed time: 132.493587 msecs\"\n\"Elapsed time: 135.867772 msecs\"\n\"Elapsed time: 132.924774 msecs\"\n\"Elapsed time: 137.491084 msecs\"\n\"Elapsed time: 134.72752 msecs\"\n\"Elapsed time: 132.969652 msecs\"\n\"Elapsed time: 135.795754 msecs\"\n\"Elapsed time: 134.261724 msecs\"\n\"Elapsed time: 138.059968 msecs\"\n\nnil\nuser> (dotimes [_ 10 ] (time (tarai-d 192 96 0)))\n\"Elapsed time: 3.181795 msecs\"\n\"Elapsed time: 2.960096 msecs\"\n\"Elapsed time: 3.000855 msecs\"\n\"Elapsed time: 3.140536 msecs\"\n\"Elapsed time: 3.658821 msecs\"\n\"Elapsed time: 3.319659 msecs\"\n\"Elapsed time: 2.9182 msecs\"\n\"Elapsed time: 3.125442 msecs\"\n\"Elapsed time: 2.944342 msecs\"\n\"Elapsed time: 2.951613 msecs\"\nnil","created-at":1308905934000,"updated-at":1308906319000,"_id":"542692cdc026201cdc326ce9"},{"updated-at":1564512316203,"created-at":1564511910921,"author":{"login":"jordangedney","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/5439697?v=4"},"body":";; Similarly to deref/@ you can evaluate a delay using force\n\nuser> (def new-delay (delay (println \"I only print once\") 5))\n#'user/new-delay\n\nuser> (force new-delay)\nI only print once\n5\n\nuser> (force new-delay)\n5\n\n;; force works with expressions other than delays: \n\nuser> (force (println \"\\\\O\"))\n\\O\nnil\n\nuser> (force :field)\n:field","editors":[{"avatar-url":"https://avatars3.githubusercontent.com/u/5439697?v=4","account-source":"github","login":"jordangedney"}],"_id":"5d408ea6e4b0ca44402ef78d"}],"notes":null,"arglists":["x"],"doc":"If x is a Delay, returns the (possibly cached) value of its expression, else returns x","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/force"},{"added":"1.1","ns":"clojure.core","name":"bound-fn*","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1350609405000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"bound-fn","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e82"}],"line":2011,"examples":[{"author":{"login":"metajack","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/194d8437f5baed192c90be27369c4922?r=PG&default=identicon"},"editors":[],"body":"(def ^:dynamic *some-var* nil)\n\n(defn f [] (println *some-var*))\n\n;; run f without a new binding\nuser=> (f)\nnil\nnil\n\n;; run f with a new binding\nuser=> (binding [*some-var* \"hello\"]\n (f))\nhello\nnil\n\n;; run f in a thread with a new binding\nuser=> (binding [*some-var* \"goodbye\"]\n (.start (Thread. f)))\nnil\nnil\n\n;; run a bound f in a thread with a new binding\nuser=> (binding [*some-var* \"goodbye\"]\n (.start (Thread. (bound-fn* f))))\ngoodbye\nnil\n","created-at":1331769960000,"updated-at":1331769960000,"_id":"542692d2c026201cdc326f5d"},{"updated-at":1613596413856,"created-at":1613596413856,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/20086?v=4"},"body":";; Capture thread local bindings so the lazy sequence can realize outside\n;; the binding block\n\n(def ^:dynamic *a* nil)\n\n(binding [*a* 1] (map #(+ % *a*) (range 10)))\n;; NullPointerException clojure.lang.Numbers.ops (Numbers.java:1013)\n\n(binding [*a* 1] (map (bound-fn* #(+ % *a*)) (range 10)))\n;; (1 2 3 4 5 6 7 8 9 10)\n","_id":"602d86fde4b0b1e3652d7456"}],"notes":null,"arglists":["f"],"doc":"Returns a function, which will install the same bindings in effect as in\n the thread at the time bound-fn* was called and then call f with any given\n arguments. This may be used to define a helper function which runs on a\n different thread, but needs the same bindings in place.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/bound-fn*"},{"added":"1.2","ns":"clojure.core","name":"namespace-munge","file":"clojure/core_deftype.clj","type":"function","column":1,"see-alsos":[{"created-at":1559582586002,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"munge","ns":"clojure.core"},"_id":"5cf5577ae4b0ca44402ef747"}],"line":13,"examples":[{"editors":[{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"}],"body":";;; replace \"-\" to \"_\" (this is the only conversion this fn does)\nuser=> (namespace-munge \"hello-world\")\n\"hello_world\"","author":{"avatar-url":"https://avatars.githubusercontent.com/u/932074?v=3","account-source":"github","login":"redraiment"},"created-at":1487211126912,"updated-at":1683030639215,"_id":"58a50a76e4b01f4add58fe58"}],"notes":null,"arglists":["ns"],"doc":"Convert a Clojure namespace name to a legal Java package name.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/namespace-munge"},{"added":"1.2","ns":"clojure.core","name":"group-by","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1318588913000,"author":{"login":"mmwaikar","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/29d36f4c9f39c9f8ff61c07033b13118?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"partition-by","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bf8"},{"created-at":1332443915000,"author":{"login":"Cosmi","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/10f2eae92de67116fa98d06ec55fcf29?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"frequencies","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bf9"}],"line":7294,"examples":[{"author":{"login":"mvonrohr","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/59714f4428e8ef53b809ee923203531?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":";; group strings by their length\n(group-by count [\"a\" \"as\" \"asd\" \"aa\" \"asdf\" \"qwer\"])\n;;=> {1 [\"a\"], 2 [\"as\" \"aa\"], 3 [\"asd\"], 4 [\"asdf\" \"qwer\"]}\n\n;; group integers by a predicate\n(group-by odd? (range 10))\n;;=> {false [0 2 4 6 8], true [1 3 5 7 9]}\n","created-at":1279083015000,"updated-at":1420742429526,"_id":"542692cdc026201cdc326cd2"},{"author":{"login":"Brool","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/781c0e32be2a2f7117dabd76a3fb7c3?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"uvtc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/34f159f89cbd1d9beac0276f5a7af552?r=PG&default=identicon"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":";; group by a primary key\n(group-by :user-id [{:user-id 1 :uri \"/\"} \n {:user-id 2 :uri \"/foo\"} \n {:user-id 1 :uri \"/account\"}])\n\n;;=> {1 [{:user-id 1, :uri \"/\"} \n;; {:user-id 1, :uri \"/account\"}],\n;; 2 [{:user-id 2, :uri \"/foo\"}]}\n","created-at":1285069474000,"updated-at":1420742470832,"_id":"542692cdc026201cdc326cd4"},{"editors":[{"login":"Canna71","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/5303303?v=3"}],"body":";; group by multiple criteria\n(def words [\"Air\" \"Bud\" \"Cup\" \"Awake\" \"Break\" \"Chunk\" \"Ant\" \"Big\" \"Check\"])\n(group-by (juxt first count) words)\n\n;;{[\\A 3] [\"Air\" \"Ant\"], \n;;[\\B 3] [\"Bud\" \"Big\"], \n;;[\\C 3] [\"Cup\"], \n;;[\\A 5] [\"Awake\"], \n;;[\\B 5] [\"Break\"], \n;;[\\C 5] [\"Chunk\" \"Check\"]}","author":{"avatar-url":"https://avatars.githubusercontent.com/u/5303303?v=3","account-source":"github","login":"Canna71"},"created-at":1471771939875,"updated-at":1471772272493,"_id":"57b97523e4b0709b524f04cf"},{"updated-at":1486507759173,"created-at":1486507759173,"author":{"login":"pavanred","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/60858?v=3"},"body":"user=> (group-by :category [{:category \"a\" :id 1}\n {:category \"a\" :id 2}\n {:category \"b\" :id 3}])\n;;{\"a\" [{:category \"a\", :id 1} {:category \"a\", :id 2}], \n;; \"b\" [{:category \"b\", :id 3}]}\n\nuser=> (group-by #(get % :category) [{:category \"a\" :id 1}\n {:category \"a\" :id 2}\n {:category \"b\" :id 3}])\n;;{\"a\" [{:category \"a\", :id 1} {:category \"a\", :id 2}], \n;; \"b\" [{:category \"b\", :id 3}]}\n\nuser=> (defn my-category [item] (get item :category))\n;;#'user/my-category\n\nuser=> (group-by my-category [{:category \"a\" :id 1}\n {:category \"a\" :id 2}\n {:category \"b\" :id 3}])\n;;{\"a\" [{:category \"a\", :id 1} {:category \"a\", :id 2}], \n;; \"b\" [{:category \"b\", :id 3}]}\n","_id":"589a4eefe4b01f4add58fe3f"},{"updated-at":1528069898970,"created-at":1528069898970,"author":{"login":"statcompute","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/4590938?v=4"},"body":"(require '[ultra-csv.core :refer [read-csv]])\n \n(def ds (read-csv \"/home/liuwensui/Downloads/nycflights.csv\"))\n \n(map\n (fn [x] {:year (first (key x))\n :month (last (key x))\n :flights (count (val x))})\n (group-by (juxt :year :month) ds))","_id":"5b147f0ae4b00ac801ed9e0b"},{"editors":[{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"}],"body":";; Find anagrams\n(def words [\"meat\" \"mat\" \"team\" \"mate\" \"eat\" \"tea\"])\n\n(group-by set words)\n;;=> {#{\\a \\e \\m \\t} [\"meat\" \"team\" \"mate\"],\n;; #{\\a \\m \\t} [\"mat\"], \n;; #{\\a \\e \\t} [\"eat\" \"tea\"]}\n","author":{"avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4","account-source":"github","login":"MicahElliott"},"created-at":1581460975386,"updated-at":1581461174115,"_id":"5e432defe4b0ca44402ef830"},{"updated-at":1706781302064,"created-at":1706781302064,"author":{"login":"jimka2001","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/6414129?v=4"},"body":";; one way to iterate across return value of group-by\n(for [[k v] (group-by (fn [n] (mod n 3)) (range 20))]\n (list k v))\n;; -> ((0 [0 3 6 9 12 15 18]) \n;; (1 [1 4 7 10 13 16 19]) \n;; (2 [2 5 8 11 14 17]))","_id":"65bb6a7669fbcc0c22617497"},{"updated-at":1776855273747,"created-at":1776855273747,"author":{"login":"pikariop","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1998952?v=4"},"body":"(let [items [{:id 1 :name \"primary\"}\n {:id 2 :name \"secondary\" :parent {:id 1}}\n {:id 3 :name \"secondary\" :parent {:id 1}}\n {:id 4 :name \"also primary\"}]]\n (group-by #(:id (or (:parent %) %))\n items))\n;=> {1 [{:id 1, :name \"primary\"}\n; {:id 2, :name \"secondary\", :parent {:id 1}}\n; {:id 3, :name \"secondary\", :parent {:id 1}}],\n; 4 [{:id 4, :name \"also primary\"}]}\n\n","_id":"69e8a8e9737c00011c0a9671"}],"notes":null,"arglists":["f coll"],"doc":"Returns a map of the elements of coll keyed by the result of\n f on each element. The value at each key will be a vector of the\n corresponding elements, in the order they appeared in coll.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/group-by"},{"added":"1.0","ns":"clojure.core","name":"prn","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1290672937000,"author":{"login":"dale","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a7a1eca257c6cea943fea41e5cc3e9a3?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"println","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cc3"},{"created-at":1291028040000,"author":{"login":"dale","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a7a1eca257c6cea943fea41e5cc3e9a3?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"pr","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cc4"}],"line":3740,"examples":[{"updated-at":1402400103000,"created-at":1335592532000,"body":"user=> (prn \"fred\" 1)\n\"fred\" 1\nnil\n\nuser=> (def items [ \"hello\" :a 1 (list :b 2) \\c {:d 4} #{5 6 7} ])\n#'user/items\n\n; prn outputs items in a machine-readable format, such as in a source\n; file. Note the double-quotes around the string \"hello\" and the escaped letter \"c\".\nuser=> (prn items)\n[\"hello\" :a 1 (:b 2) \\c {:d 4} #{5 6 7}]\nnil\n\n; println is for human-readable output, like a report. Note the lack of quotes around the string \"hello\", and the unescaped letter \"c\". \nuser=> (println items)\n[hello :a 1 (:b 2) c {:d 4} #{5 6 7}]\nnil\n\n; pr-str produces a string with escaped punctuation, so that println yields the same result as the original prn call.\nuser=> (println (pr-str items))\n[\"hello\" :a 1 (:b 2) \\c {:d 4} #{5 6 7}]\nnil\n\n","editors":[{"avatar-url":"https://www.gravatar.com/avatar/1ad3de25d00d953de6e8c82f554cdbf5?r=PG&default=identicon","account-source":"clojuredocs","login":"cloojure"},{"avatar-url":"https://www.gravatar.com/avatar/1ad3de25d00d953de6e8c82f554cdbf5?r=PG&default=identicon","account-source":"clojuredocs","login":"cloojure"},{"avatar-url":"https://www.gravatar.com/avatar/1ad3de25d00d953de6e8c82f554cdbf5?r=PG&default=identicon","account-source":"clojuredocs","login":"cloojure"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3","account-source":"github","login":"devn"},"_id":"542692d4c026201cdc32703b"}],"notes":null,"arglists":["& more"],"doc":"Same as pr followed by (newline). Observes *flush-on-newline*","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/prn"},{"added":"1.2","ns":"clojure.core","name":"extend","file":"clojure/core_deftype.clj","type":"function","column":1,"see-alsos":[{"created-at":1326611307000,"author":{"login":"Claj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5fd658a8d2ef549071cb5286b1b874aa?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"satisfies?","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e53"},{"created-at":1326611311000,"author":{"login":"Claj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5fd658a8d2ef549071cb5286b1b874aa?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"extends?","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e54"},{"created-at":1326611316000,"author":{"login":"Claj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5fd658a8d2ef549071cb5286b1b874aa?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"extenders","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e55"},{"created-at":1394618470000,"author":{"login":"Chort409","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/73da2cf9145cfb9c900b31436ee435a6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"extend-type","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e56"},{"created-at":1394618476000,"author":{"login":"Chort409","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/73da2cf9145cfb9c900b31436ee435a6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"extend-protocol","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e57"}],"line":780,"examples":[{"author":{"login":"semperos","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/edeae8e7534b3d554e4ec2c35ffc68d?r=PG&default=identicon"},"editors":[{"login":"semperos","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/edeae8e7534b3d554e4ec2c35ffc68d?r=PG&default=identicon"}],"body":"; From Sean Devlin's talk on protocols at Clojure Conj\n(defprotocol Dateable\n (to-ms [t]))\n\n(extend java.lang.Number\n Dateable\n {:to-ms identity})\n\n(extend java.util.Date\n Dateable\n {:to-ms #(.getTime %)})\n\n(extend java.util.Calendar\n Dateable\n {:to-ms #(to-ms (.getTime %))})","created-at":1296704103000,"updated-at":1296705296000,"_id":"542692c7c026201cdc3269d3"},{"updated-at":1542060365406,"created-at":1542060009207,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"body":";; \"extend\" enables the definition of concrete implementations\n;; after declaration time. This provides \n;; a lightweight version of abstract methods/classes.\n\n(defprotocol IBaz\n (foo [_])\n (bar [_])\n (baz [_]))\n\n;; DefaultBaz contains some default implementations.\n(def DefaultBaz\n {:foo (fn [_] (str \"DefaultBaz::foo\"))\n :bar (fn [_] (str \"DefaultBaz::bar\"))})\n\n(defrecord MyBaz [])\n\n;; MyBaz accepts \"bar\" as default from the \"super-class\"\n;; but overrides \"foo\". \"baz\" is provided without override.\n(extend MyBaz\n IBaz\n (assoc DefaultBaz \n :foo (fn [this] (str \"MyBaz::foo\"))\n :baz (fn [this] (str \"MyBaz::baz\"))))\n\n(def my-baz (->MyBaz))\n(foo my-baz)\n;; \"MyBaz::foo\"\n\n;; Note: additional \"extend-*\" calls will change all instances\n;; created so far.\n\n(extend-type MyBaz\n IBaz\n (foo [this] (str \"NEW\")))\n\n(foo my-baz)\n;; \"NEW\"","editors":[{"avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"}],"_id":"5be9f7e9e4b00ac801ed9ef3"}],"notes":[{"author":{"login":"nethopper","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1613187?v=4"},"updated-at":1725531590596,"created-at":1725531590596,"body":"The type being extended must be `import`ed even if it is a Clojure type (e.g. a record). So the following works:\n```\n(ns com.example-ns.a\n (:import (com.example_ns.b Foo))) ;; <-- import\n\n(defprotocol IBar\n (bar [_]))\n\n(extend Foo\n IBar\n {:bar identity})\n```\n\nBut this fails to compile:\n```\n(ns com.example-ns.a\n (:require [com.example-ns.b :refer [Foo]])) ;; <-- require\n\n(defprotocol IBar\n (bar [_]))\n\n(extend Foo\n IBar\n {:bar identity})\n```\n \nSee [defrecord example](https://clojuredocs.org/clojure.core/defrecord#example-542692d2c026201cdc326f87).","_id":"66d985c669fbcc0c226174f1"}],"arglists":["atype & proto+mmaps"],"doc":"Implementations of protocol methods can be provided using the extend construct:\n\n (extend AType\n AProtocol\n {:foo an-existing-fn\n :bar (fn [a b] ...)\n :baz (fn ([a]...) ([a b] ...)...)}\n BProtocol \n {...} \n ...)\n \n extend takes a type/class (or interface, see below), and one or more\n protocol + method map pairs. It will extend the polymorphism of the\n protocol's methods to call the supplied methods when an AType is\n provided as the first argument. \n\n Method maps are maps of the keyword-ized method names to ordinary\n fns. This facilitates easy reuse of existing fns and fn maps, for\n code reuse/mixins without derivation or composition. You can extend\n an interface to a protocol. This is primarily to facilitate interop\n with the host (e.g. Java) but opens the door to incidental multiple\n inheritance of implementation since a class can inherit from more\n than one interface, both of which extend the protocol. It is TBD how\n to specify which impl to use. You can extend a protocol on nil.\n\n If you are supplying the definitions explicitly (i.e. not reusing\n exsting functions or mixin maps), you may find it more convenient to\n use the extend-type or extend-protocol macros.\n\n Note that multiple independent extend clauses can exist for the same\n type, not all protocols need be defined in a single extend call.\n\n See also:\n extends?, satisfies?, extenders","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/extend"},{"added":"1.0","ns":"clojure.core","name":"unchecked-multiply","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1423522441619,"author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"to-var":{"ns":"clojure.core","name":"*","library-url":"https://github.com/clojure/clojure"},"_id":"54d93a89e4b081e022073c76"},{"created-at":1423522447793,"author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"to-var":{"ns":"clojure.core","name":"*'","library-url":"https://github.com/clojure/clojure"},"_id":"54d93a8fe4b0e2ac61831d31"}],"line":1240,"examples":[{"author":{"login":"shockbob","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon"},"editors":[{"login":"kentros","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/765acc548dfd021fd854d75f9da3d0a9?r=PG&default=identicon"}],"body":";; the unchecked-multiply function silently overflows\n\nuser=> (* 1000000000000 10)\n10000000000000\nuser=> (unchecked-multiply 1000000000000 10)\n10000000000000\n\nuser=> (* 3037000500 3037000500)\nArithmeticException integer overflow clojure.lang.Numbers.throwIntOverflow (Numbers.java:1424)\nuser=> (unchecked-multiply 3037000500 3037000500)\n-9223372036709301616\n\n","created-at":1313910992000,"updated-at":1407321150000,"_id":"542692c6c026201cdc326917"}],"notes":null,"arglists":["x y"],"doc":"Returns the product of x and y, both long.\n Note - uses a primitive operator subject to overflow.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/unchecked-multiply"},{"added":"1.5","ns":"clojure.core","name":"some->>","file":"clojure/core.clj","type":"macro","column":1,"see-alsos":[{"created-at":1412083996468,"author":{"login":"jw-00000","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2936?v=2"},"to-var":{"ns":"clojure.core","name":"->>","library-url":"https://github.com/clojure/clojure"},"_id":"542ab11ce4b0df9bb778a59d"},{"created-at":1412084003950,"author":{"login":"jw-00000","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2936?v=2"},"to-var":{"ns":"clojure.core","name":"some->","library-url":"https://github.com/clojure/clojure"},"_id":"542ab123e4b0df9bb778a59e"}],"line":7790,"examples":[{"editors":[{"login":"pzeldin","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/12401420?v=3"}],"body":";; an example of looking up a value from a\n;; map and performing an operation(addition)\n;; on it if it exists\nuser=> (some->> {:y 3 :x 5}\n (:y)\n (- 2))\n\n-1\n\n\n;; if we were to look up a value which\n;; doesn't exist, it will safely short-circuit\nuser=> (some->> {:y 3 :x 5}\n (:z)\n (- 2))\n\nnil\n","author":{"avatar-url":"https://avatars.githubusercontent.com/u/1583002?v=3","account-source":"github","login":"superfunc"},"created-at":1446217046027,"updated-at":1457975262515,"_id":"56338556e4b04b157a6648dc"}],"macro":true,"notes":null,"arglists":["expr & forms"],"doc":"When expr is not nil, threads it into the first form (via ->>),\n and when that result is not nil, through the next etc","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/some->>"},{"added":"1.4","ns":"clojure.core","name":"default-data-readers","file":"clojure/core.clj","type":"var","column":1,"see-alsos":null,"line":7988,"examples":[{"updated-at":1546539310208,"created-at":1546539310208,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"body":";; As of Clojure 1.10 the content is:\ndefault-data-readers\n;; {uuid #'clojure.uuid/default-uuid-reader, \n;; inst #'clojure.instant/read-instant-date}\n\n;; Which allows reading of UUIDs and Instants:\n(type (read-string \"#inst \\\"2017-08-23T10:22:22.000-00:00\\\"\"))\n;; java.util.Date\n(type (read-string \"#uuid \\\"374c8c4-fd89-4f1b-a11f-42e334ccf5ce\\\"\"))\n;; java.util.UUID\n\n;; And is overridable with \"*data-readers*\"\n(binding [*data-readers* {'uuid identity}]\n (read-string \"#uuid \\\"374c8c4-fd89-4f1b-a11f-42e334ccf5ce\\\"\"))\n;; \"374c8c4-fd89-4f1b-a11f-42e334ccf5ce\"\n\n;; Or options from edn/read-string\n(require '[clojure.edn :as edn])\n(edn/read-string {:readers {'inst (constantly :nope)}} \n \"#inst \\\"2017-08-23T10:22:22.000-00:00\\\"\")\n;; :nope","_id":"5c2e512ee4b0ca44402ef60d"}],"notes":null,"arglists":[],"doc":"Default map of data reader functions provided by Clojure. May be\n overridden by binding *data-readers*.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/default-data-readers"},{"ns":"clojure.core","name":"->VecSeq","file":"clojure/gvec.clj","type":"function","column":1,"see-alsos":null,"line":59,"examples":null,"notes":null,"arglists":["am vec anode i offset _meta"],"doc":"Positional factory function for class clojure.core.VecSeq.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/->VecSeq"},{"added":"1.0","ns":"clojure.core","name":"even?","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"to-var":{"library-url":"https://github.com/clojure/clojure","name":"odd?","ns":"clojure.core"},"author":{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},"created-at":1354423235000,"_id":"542692ebf6e94c6970521dd1"}],"line":1400,"examples":[{"updated-at":1406097631000,"created-at":1279073824000,"body":"user=> (even? 2)\ntrue\n\nuser=> (even? 1)\nfalse","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3","account-source":"github","login":"jafingerhut"},{"avatar-url":"https://avatars.githubusercontent.com/u/92894?v=3","account-source":"github","login":"rafmagana"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/147981?v=3","account-source":"github","login":"dpritchett"},"_id":"542692ccc026201cdc326cb5"},{"author":{"login":"replore","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e7869fe1a48cb1814c657eaca6bea3eb?r=PG&default=identicon"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":"user=> (filter even? (range 10))\n(0 2 4 6 8)","created-at":1321356072000,"updated-at":1332949375000,"_id":"542692d2c026201cdc326f9e"}],"notes":null,"arglists":["n"],"doc":"Returns true if n is even, throws an exception if n is not an integer","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/even_q"},{"added":"1.0","ns":"clojure.core","name":"unchecked-dec","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1289217146000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"unchecked-add","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c37"},{"created-at":1289217151000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"unchecked-dec","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c38"},{"created-at":1289217154000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"unchecked-inc","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c39"},{"created-at":1289217159000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"unchecked-negate","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c3a"},{"created-at":1289217163000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"unchecked-divide","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c3b"},{"created-at":1289217168000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"unchecked-subtract","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c3c"},{"created-at":1289217172000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"unchecked-multiply","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c3d"},{"created-at":1289217176000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"unchecked-remainder","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c3e"},{"created-at":1423522315984,"author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"to-var":{"ns":"clojure.core","name":"dec","library-url":"https://github.com/clojure/clojure"},"_id":"54d93a0be4b0e2ac61831d2e"},{"created-at":1423522329856,"author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"to-var":{"ns":"clojure.core","name":"dec'","library-url":"https://github.com/clojure/clojure"},"_id":"54d93a19e4b081e022073c75"}],"line":1184,"examples":[{"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":"user=> (unchecked-dec 4)\n3\n\nuser=> (unchecked-dec Integer/MIN_VALUE)\n2147483647\n\n","created-at":1289217142000,"updated-at":1289267924000,"_id":"542692c6c026201cdc326939"},{"updated-at":1488018651069,"created-at":1488018651069,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10583730?v=3"},"body":";; Illustrates the difference between (dec), (dec') and (unchecked-dec)\n\n;; The \"N\" suffix denotes a BigInt instance\n;; https://github.com/clojure/clojure/blob/master/src/jvm/clojure/lang/BigInt.java\n\nLong/MIN_VALUE\n;;=> -9223372036854775808\n\n(dec Long/MIN_VALUE)\n;;=> ArithmeticException integer overflow clojure.lang.Numbers.throwIntOverflow (Numbers.java:1501)\n\n(dec' Long/MIN_VALUE)\n;;=> -9223372036854775809N \n\n;; Notice how the resulting number becomes POSITIVE:\n(unchecked-dec Long/MIN_VALUE)\n;;=> 9223372036854775807 \n\n\n","_id":"58b15cdbe4b01f4add58fe5e"}],"notes":null,"arglists":["x"],"doc":"Returns a number one less than x, a long.\n Note - uses a primitive operator subject to overflow.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/unchecked-dec"},{"ns":"clojure.core","name":"Inst","file":"clojure/core.clj","type":"var","column":1,"see-alsos":null,"line":6909,"examples":null,"notes":null,"arglists":[],"doc":null,"library-url":"https://github.com/clojure/clojure","href":"/clojure.core/Inst"},{"added":"1.7","ns":"clojure.core","name":"tagged-literal?","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1757184340552,"author":{"login":"daveliepmann","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/974443?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"tagged-literal","ns":"clojure.core"},"_id":"68bc8154cd84df5de54e2093"}],"line":7957,"examples":null,"notes":null,"arglists":["value"],"doc":"Return true if the value is the data representation of a tagged literal","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/tagged-literal_q"},{"added":"1.0","ns":"clojure.core","name":"double-array","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1349125799000,"author":{"login":"Ljos","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/45b996a79abca465acaf6c0f10b0437?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"doubles","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521ac2"},{"created-at":1349125811000,"author":{"login":"Ljos","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/45b996a79abca465acaf6c0f10b0437?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"aget","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521ac3"},{"created-at":1349125816000,"author":{"login":"Ljos","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/45b996a79abca465acaf6c0f10b0437?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"aset","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521ac4"},{"created-at":1349125826000,"author":{"login":"Ljos","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/45b996a79abca465acaf6c0f10b0437?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"aset-double","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521ac5"}],"line":5370,"examples":[{"author":{"login":"shockbob","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon"},"editors":[],"body":";; create a double array using double-array\n;; and show it can be used with the standard Java functions\n;; binarySearch and fill\n\nuser=> (def ds (double-array (range 3 20)))\n#'user/ds\nuser=> (type ds)\n[D\nuser=> (vec ds)\n[3.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0 11.0 12.0 13.0 14.0 15.0 16.0 17.0 18.0 19.0]\nuser=> (java.util.Arrays/binarySearch ds 10.0)\n7\nuser=> (java.util.Arrays/fill ds 3 8 99.0)\nnil\nuser=> (vec ds)\n[3.0 4.0 5.0 99.0 99.0 99.0 99.0 99.0 11.0 12.0 13.0 14.0 15.0 16.0 17.0 18.0 19\n.0]\nuser=>","created-at":1313906832000,"updated-at":1313906832000,"_id":"542692cac026201cdc326b10"},{"updated-at":1661427039227,"created-at":1661427039227,"author":{"login":"ertugrulcetin","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8271291?v=4"},"body":"(double-array [1 2.2 3.5])\n;;=> #object[\"[D\" 0x249e3e74 \"[D@249e3e74\"]\n\n(vec (double-array [1 2.2 3.5]))\n;;=> [1.0 2.2 3.5]","_id":"63075d5fe4b0b1e3652d7651"}],"notes":null,"arglists":["size-or-seq","size init-val-or-seq"],"doc":"Creates an array of doubles","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/double-array"},{"added":"1.0","ns":"clojure.core","name":"in-ns","type":"function","see-alsos":[{"created-at":1331258262000,"author":{"login":"frangio","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/646001f0ba2b7df47a16c0a1d5b62225?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"ns","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c41"}],"examples":[{"updated-at":1497795624520,"created-at":1285103646000,"body":";; Let's create new namespace, create new variable in it, then access it from\n;; another namespace\n\n;; create the namespace and switch to it\n(in-ns 'first-namespace)\n;;=> #\n\n;; create a variable and check it\n;; first-namespace=> \n(def my-var \"some value\")\n;;=> #'first-namespace/my-var\n\n;; first-namespace=> \nmy-var\n;;=> \"some value\"\n\n;; create another namespace and switch to this one\n;; first-namespace=> \n(in-ns 'second-namespace)\n;;=> #\n\n;; use variable from the other namespace here\n;; second-namespace=> \nfirst-namespace/my-var\n;;=> \"some value\"\n\n;; in-ns works within top-level forms (e.g. the compiler or the REPL)\n;; It may fail when called within a function at runtime because *ns* is a Var\n;; and unless there are thread-local bindings for *ns*, it cannot be set!\nsecond.namespace=> (defn swap-ns! [ns-name] (clojure.core/in-ns ns-name))\n;; #'second.namespace/swap-ns!\n\nsecond.namespace=> (swap-ns! 'other.ns)\n;; #namespace[other.ns]\n\n;; Later, at runtime...\n;; Throws IllegalStateException(\"Can't change/establish root binding of: *ns* with set\")\n;; Remember, *ns* is a root var and in-ns calls set!, which only works after\n;; someone somewhere calls the binding macro (or Java equivalent)\n(defn -main\n [& args]\n (println *ns*)\n (second.namespace/swap-ns! 'arbitrary-namespace))\n;; prints #namespace[clojure.core] and then will crash","editors":[{"avatar-url":"https://www.gravatar.com/avatar/8d3c423e74750fa42c0386833e4b8209?r=PG&default=identicon","account-source":"clojuredocs","login":"belun"},{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3","account-source":"github","login":"phreed"},{"login":"Artiavis","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/1834136?v=3"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/8d3c423e74750fa42c0386833e4b8209?r=PG&default=identicon","account-source":"clojuredocs","login":"belun"},"_id":"542692cdc026201cdc326d10"},{"author":{"login":"belun","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8d3c423e74750fa42c0386833e4b8209?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":";; The \"in-ns\" function works almost the same as \"ns\", but does not load\n;; clojure.core \n\n;; user=>\n(in-ns 'my-namespace)\n;;=> #\n\n;; the function clojure.core/inc won't just work\n;; my-namespace=> \n(inc 1)\n;; java.lang.Exception: Unable to resolve symbol: inc in this context\n;; (NO_SOURCE_FILE:15)\n\n;; my-namespace=>\n(clojure.core/inc 1)\n;;=> 2\n","created-at":1285105578000,"updated-at":1423811341705,"_id":"542692cdc026201cdc326d13"}],"notes":null,"arglists":["name"],"doc":"Sets *ns* to the namespace named by the symbol, creating it if needed.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/in-ns"},{"added":"1.0","ns":"clojure.core","name":"create-ns","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1284970193000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"remove-ns","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cb1"},{"created-at":1284970227000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"find-ns","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cb2"},{"created-at":1502465564365,"author":{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"intern","ns":"clojure.core"},"_id":"598dce1ce4b0d19c2ce9d712"}],"line":4158,"examples":[{"author":{"login":"belun","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8d3c423e74750fa42c0386833e4b8209?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"avatar-url":"https://avatars.githubusercontent.com/u/412966?v=3","account-source":"github","login":"nasser"}],"body":";; This won't work because the symbol my-new-namespace isn't defined yet\nuser=> (create-ns my-new-namespace)\njava.lang.Exception: Unable to resolve symbol: my-new-namespace in this context (NO_SOURCE_FILE:2)\n\n\n;; This won't work because create-ns expects a symbol, not a string \nuser=> (create-ns \"my-new-namespace\")\njava.lang.ClassCastException: java.lang.String cannot be cast to clojure.lang.Symbol (NO_SOURCE_FILE:0)\n\n\n;; Here my-new-namespace is quoted and passed literally to create-ns\n;; without being looked up. It works as documented.\nuser=> (create-ns 'my-new-namespace)\n#\n","created-at":1284947276000,"updated-at":1457302200380,"_id":"542692cac026201cdc326b8f"},{"author":{"login":"belun","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8d3c423e74750fa42c0386833e4b8209?r=PG&default=identicon"},"editors":[{"login":"belun","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8d3c423e74750fa42c0386833e4b8209?r=PG&default=identicon"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"avatar-url":"https://avatars.githubusercontent.com/u/340?v=3","account-source":"github","login":"jamesmacaulay"},{"login":"siddharthjain-in","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/6537820?v=4"}],"body":";; Let's create a namespace and check for our result\n;; the new namespace will be \"my-new-namespace\"\n\n;; it does not exist yet, so looking for it, finds nothing\nuser=> (find-ns 'my-new-namespace) \nnil\n\n;; let's create it\nuser=> (create-ns 'my-new-namespace)\n#\n\n;; now searching for it again will have a result\nuser=> (find-ns 'my-new-namespace)\n#\n","created-at":1284947982000,"updated-at":1651887290877,"_id":"542692cac026201cdc326b91"},{"author":{"login":"belun","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8d3c423e74750fa42c0386833e4b8209?r=PG&default=identicon"},"editors":[{"login":"belun","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8d3c423e74750fa42c0386833e4b8209?r=PG&default=identicon"},{"login":"belun","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8d3c423e74750fa42c0386833e4b8209?r=PG&default=identicon"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":";; You can create a namespace, not switch to it and still work in, by storing it\n\n;; create the namespace\nuser=> (def for-later-use (create-ns 'my-namespace))\n#'user/for-later-use\n\n;; assign a value for a variable\nuser=> (intern for-later-use 'my-var \"some value\")\n#'my-namespace/my-var\n;; notice how the \"for-later-use\" symbol has been evaluated to the namespace it represents\n\n;; check the new variable\nuser=> my-namespace/my-var\n\"some value\"\n\n;; you can also work on a namespace by using the its name\n;; (but quoting it) instead of the return of \"create-ns\"\nuser=> (intern 'my-namespace 'my-var \"some other value\")\n#'my-namespace/my-var\n\n;; check the new assignment and see what's changed\nuser=> my-namespace/my-var\n\"some other value\"\n","created-at":1285113908000,"updated-at":1285485928000,"_id":"542692cbc026201cdc326b96"},{"editors":[{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"}],"body":";; create-ns may be used to override *ns* at macroexpansion\n(in-ns 'user)\n\n(defmacro uses-*ns* [kw]\n (let [spaced (keyword (str (ns-name *ns*)) (name kw))]\n `(println ~spaced)))\n\n(macroexpand '(user/uses-*ns* :kw))\n;;=> (clojure.core/println :user/kw)\n;; 'user' namespace reflects current namespace\n\n(binding [*ns* (create-ns 'foo.bar)]\n (macroexpand '(user/uses-*ns* :kw)))\n;; => (clojure.core/println :foo.bar/kw)\n;; 'user' namespace has been overriden\n","author":{"avatar-url":"https://avatars.githubusercontent.com/u/389119?v=4","account-source":"github","login":"vladkotu"},"created-at":1701085700005,"updated-at":1701171712856,"_id":"6564820469fbcc0c2261745f"}],"notes":null,"arglists":["sym"],"doc":"Create a new namespace named by the symbol if one doesn't already\n exist, returns it or the already-existing namespace of the same\n name.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/create-ns"},{"added":"1.0","ns":"clojure.core","name":"re-matcher","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1282039999000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"re-find","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b2e"}],"line":4902,"examples":[{"author":{"login":"dakrone","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bcacd00a7f05c4772329cf9f446c7987?r=PG&default=identicon"},"editors":[{"login":"philos99","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1de5617efb013ca7c9cf8e5646818ffa?r=PG&default=identicon"}],"body":"user=> (def *matcher* (re-matcher #\"\\d+\" \"abc12345def\"))\n#'user/*matcher*\n\nuser=> (re-find *matcher*)\n\"12345\"","created-at":1280546885000,"updated-at":1317219277000,"_id":"542692c8c026201cdc326a0d"},{"updated-at":1622895302889,"created-at":1622895302889,"author":{"login":"cloojure","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7083783?v=4"},"body":";\n; Java supports named capture groups\n;\n; Define a phone number pattern with some named groups\n(let [patt (re-pattern \"(?\\\\d{3})-(?\\\\d{3})-(?\\\\d{4})\")]\n ; `re-matches` will find the capturing groups and stick them in a vector\n ; after the full match The capture groups are numbered starting with 1.\n ; The full match is like group zero.\n (is= [\"619-239-5464\" \"619\" \"239\" \"5464\"] (re-matches patt \"619-239-5464\"))\n\n ; Construct a java.util.regex.Matcher. Keep in mind that it is a mutable object!\n (let [matcher (re-matcher patt \"619-239-5464\")]\n ; Execute the Matcher via `re-find`. It returns all 4 groups and caches them\n (is= [\"619-239-5464\" \"619\" \"239\" \"5464\"] (re-find matcher))\n\n ; `re-groups` simply returns the cached result from the Matcher\n (is= [\"619-239-5464\" \"619\" \"239\" \"5464\"] (re-groups matcher))\n\n ; We need the instance function Matcher.group( ) to\n ; extract the named group\n (is= \"619\" (.group matcher \"area\"))\n (is= \"239\" (.group matcher \"prefix\"))\n (is= \"5464\" (.group matcher \"tail\"))))\n","_id":"60bb6ac6e4b0b1e3652d7507"}],"notes":[{"body":"17:44 < mearnsh> tsdh: re-matcher should be avoided because the Matcher object it returns mutates in a non-thread-safe way","created-at":1417436686825,"updated-at":1417436686825,"author":{"login":"r4um","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/629631?v=3"},"_id":"547c5e0ee4b0dc573b892fe8"},{"author":{"login":"timmc","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/78608?v=3"},"updated-at":1461677086067,"created-at":1461677086067,"body":"It's fine to use from a controlled context. For instance, if you have a let that creates a Matcher, pulls out groups, and returns the data, you're working in a single-threaded context and the mutable object never even escapes.\n","_id":"571f6c1ee4b0fc95a97eab57"}],"tag":"java.util.regex.Matcher","arglists":["re s"],"doc":"Returns an instance of java.util.regex.Matcher, for use, e.g. in\n re-find.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/re-matcher"},{"added":"1.0","ns":"clojure.core","name":"defn","file":"clojure/core.clj","type":"macro","column":1,"see-alsos":[{"created-at":1334710750000,"author":{"login":"Ljos","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/45b996a79abca465acaf6c0f10b0437?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"def","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521edb"},{"created-at":1334710756000,"author":{"login":"Ljos","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/45b996a79abca465acaf6c0f10b0437?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"defn-","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521edc"},{"created-at":1361269869000,"author":{"login":"AtKaaZ","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e10dfa345f44b0fe72bbe081fd51b83?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"defmacro","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521edd"},{"created-at":1399636777000,"author":{"login":"ryo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3f7913b563c72083c74030d928ba407e?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"fn","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ede"},{"created-at":1460434537177,"author":{"login":"ivanpierre","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/625541?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"declare","ns":"clojure.core"},"_id":"570c7669e4b075f5b2c864e7"}],"line":285,"examples":[{"updated-at":1361268155000,"created-at":1279161740000,"body":"user=> (defn foo [a b c]\n\t (* a b c))\n#'user/foo\nuser=> (foo 1 2 3)\n6\n\nuser=> (defn bar [a b & [c]]\n (if c\n (* a b c)\n (* a b 100)))\n#'user/bar\nuser=> (bar 5 6)\n3000\nuser=> (bar 5 6 2)\n60\n\nuser=> (defn baz [a b & {:keys [c d] :or {c 10 d 20}}]\n (* a b c d))\n#'user/baz\nuser=> (baz 2 3)\n1200\nuser=> (baz 2 3 :c 5)\n600\nuser=> (baz 2 3 :c 5 :d 6)\n180\n\nuser=> (defn boo [a b & {:keys [c d] :or {c 10 d 20} :as all-specified}]\n (println all-specified)\n (* a b c d))\n#'user/boo\nuser=> (boo 2 3)\nnil\n1200\nuser=> (boo 2 3 :c 5)\n{:c 5}\n600\nuser=> (boo 1 2 :d 3 :c 4)\n{:c 4, :d 3}\n24\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"avatar-url":"https://www.gravatar.com/avatar/9e10dfa345f44b0fe72bbe081fd51b83?r=PG&default=identicon","account-source":"clojuredocs","login":"AtKaaZ"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/142529?v=3","account-source":"github","login":"nipra"},"_id":"542692cbc026201cdc326bd1"},{"author":{"login":"kotarak","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5db30f607f0b5fa70d690311aa3bfd3b?r=PG&default=identicon"},"editors":[{"login":"kotarak","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5db30f607f0b5fa70d690311aa3bfd3b?r=PG&default=identicon"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":"user=> (defn bar\n ([a b] (bar a b 100))\n ([a b c] (* a b c)))\n#'user/bar\nuser=> (bar 5 6)\n3000\nuser=> (bar 5 6 2)\n60\n","created-at":1279213901000,"updated-at":1285496324000,"_id":"542692cbc026201cdc326bd6"},{"author":{"login":"pkolloch","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/10b2fd3c0a4cc46dc241a48468dc551?r=PG&default=identicon"},"editors":[{"login":"pkolloch","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/10b2fd3c0a4cc46dc241a48468dc551?r=PG&default=identicon"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"philos99","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1de5617efb013ca7c9cf8e5646818ffa?r=PG&default=identicon"}],"body":";; You can use destructuring to have keyword arguments. This would be a\n;; pretty verbose version of map (in an example a bit more verbose than\n;; the first above):\n\n(defn keyworded-map [& {function :function sequence :sequence}]\n (map function sequence))\n\n;; You can call it like this:\n\nuser=> (keyworded-map :sequence [1 2 3] :function #(+ % 2))\n(3 4 5)\n\n\n;; The declaration can be shortened with \":keys\" if your local variables \n;; should be named in the same way as your keys in the map:\n\n(defn keyworded-map [& {:keys [function sequence]}]\n (map function sequence))\n","created-at":1280457897000,"updated-at":1317454000000,"_id":"542692cbc026201cdc326bd9"},{"author":{"login":"AtKaaZ","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e10dfa345f44b0fe72bbe081fd51b83?r=PG&default=identicon"},"editors":[{"login":"AtKaaZ","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e10dfa345f44b0fe72bbe081fd51b83?r=PG&default=identicon"},{"login":"AtKaaZ","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e10dfa345f44b0fe72bbe081fd51b83?r=PG&default=identicon"},{"login":"AtKaaZ","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e10dfa345f44b0fe72bbe081fd51b83?r=PG&default=identicon"}],"body":"(defn somefn\n [req1 req2 ;required params\n & {:keys [a b c d e] ;optional params\n :or {a 1 ;optional params with preset default values other than the nil default\n ; b takes nil if not specified on call\n c 3 ; c is 3 when not specified on call\n d 0 ; d is 0 --//--\n ; e takes nil if not specified on call\n }\n :as mapOfParamsSpecifiedOnCall ;takes nil if no extra params(other than the required ones) are specified on call\n }]\n (println req1 req2 mapOfParamsSpecifiedOnCall a b c d e)\n )\n\n=> (somefn 9 10 :b 2 :d 4)\n;9 10 {:b 2, :d 4} 1 2 3 4 nil\nnil\n=> (somefn)\n;ArityException Wrong number of args (0) passed to: funxions$somefn ;clojure.lang.AFn.throwArity (AFn.java:437)\n=> (somefn 9 10)\n;9 10 nil 1 nil 3 0 nil\nnil\n=> (somefn 9 10 :x 123)\n;9 10 {:x 123} 1 nil 3 0 nil\nnil\n=> (somefn 9 10 123)\n;IllegalArgumentException No value supplied for key: 123 ;clojure.lang.PersistentHashMap.create (PersistentHashMap.java:77)\n=> (somefn 9 10 123 45)\n;9 10 {123 45} 1 nil 3 0 nil\nnil\n=> (try \n (somefn 9 10 123)\n (catch IllegalArgumentException e (println \"caught:\" e)))\n;caught: #\nnil","created-at":1361269606000,"updated-at":1361269847000,"_id":"542692d2c026201cdc326f7c"},{"updated-at":1442603127799,"created-at":1442603127799,"author":{"login":"dxlr8r","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1648056?v=3"},"body":";; :as only include parameters provided, not the default (:or) ones.\n;; This is some boilerplate code to get around this. \n;; Hopefully not needed in the future revisions of Clojure.\n\n(defn bar [f g h & {:keys [override]}]\n (let [default {:a 1 :b 2 :c 3}\n args (merge default override)]\n (conj '() f g h args)))\n\n(bar 1 2 3 :override {:a 9 :z 5}) ; returns -> ({:z 5, :a 9, :b 2, :c 3} 3 2 1)\n","_id":"55fc6077e4b06a9ffaad4fc1"},{"updated-at":1516276416080,"created-at":1516276416080,"author":{"login":"ibercode","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/31028993?v=4"},"body":";;defn basic examples\n(defn say-hi [name]\n (str \"Hi \" name))\n\n(say-hi \"Jack\")\n;;\"Hi Jack\"\n\n;;the same result using def\n(def say-hello (fn [name]\n (str \"Hello \" name)))\n\n(say-hello \"Bob\")\n;;\"Hello Bob\"\n\n;;the same result using def and an anonymous function\n(def say-bye #(str \"Bye Bye \" %))\n\n(say-bye \"Mark\")\n;;\"Bye Bye Mark\"","_id":"5a608ac0e4b0a08026c48cff"},{"updated-at":1516725425484,"created-at":1516725425484,"author":{"login":"jakubholynet","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/624958?v=4"},"body":";;define a function with metadata\n(defn hello {:awesome true} [] nil)\n\n(meta #'hello)\n=>\n{:arglists ([]),\n :awesome true,\n ...\n}\n\n;; define a function with a return value type hint\n(defn hinted ^long [] 42)\n\n(-> #'hinted meta :arglists first meta :tag)\n=> long\n\n;; both metadata on the fn and return type hint (on the argument vector)\n(defn hinted+meta {:awesome true} ^long [] 42)","_id":"5a6764b1e4b09621d9f53a76"},{"updated-at":1547395275348,"created-at":1547395275348,"author":{"login":"victorb","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/459764?v=4"},"body":";; Documentation can also be added with `defn`\n=> (defn add \"Adds two numbers\" [x y] (+ x y))\n#'user/add\n\n;; This documentation can be read with the `doc` function\n=> (doc add) \n-------------------------\nuser/add\n([x y])\n Adds two numbers\n\n;; It can also be used when searching for functions with `find-doc`\n=> (find-doc \"two numbers\")\n-------------------------\nuser/add\n([x y])\n Adds two numbers","_id":"5c3b60cbe4b0ca44402ef61a"},{"updated-at":1550694890901,"created-at":1550694890901,"author":{"login":"cljlc","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/36645452?v=4"},"body":";; prepost-map examples\n\n;; check that exactly one of :a or :b are in the argument map: \n(defn example\n [{:keys [a b]}]\n {:pre [(not (and a b))\n (or a b)]}\n (println a b))\n;; #'user/example\n\n(example {:a 1 :b 2})\n;; Execution error (AssertionError) at user/example (REPL:1).\n;; Assert failed: (not (and a b))\n\n(example {:c 1 :d 2})\n;; Execution error (AssertionError) at user/example (REPL:1).\n;; Assert failed: (or a b)\n\n(example {:a 1 :c 2})\n;; 1 nil\n;; nil\n\n;; check that the error-free average is between the max and min of the arguments:\n(defn avg\n [error & nums]\n {:post [(<= (apply min nums) % (apply max nums))]}\n (/ (apply + error nums)\n (count nums)))\n;; #'user/avg\n\n(avg 0 1 2 3 4 5)\n;; 3\n\n(avg 100 1 2 3 4 5)\n;; Execution error (AssertionError) at user/avg (REPL:1).\n;; Assert failed: (<= (apply min nums) % (apply max nums))\n","_id":"5c6db9eae4b0ca44402ef69c"},{"updated-at":1578771116812,"created-at":1578770937032,"author":{"login":"boraseoksoon","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/6975179?v=4"},"body":";; To inverse boolean\n\n(defn ! [bool]\n (if (= bool true)\n false true))\n\n(! true)\n;; => false\n\n(! false)\n;; => true","editors":[{"avatar-url":"https://avatars2.githubusercontent.com/u/6975179?v=4","account-source":"github","login":"boraseoksoon"}],"_id":"5e1a21f9e4b0ca44402ef813"},{"updated-at":1590107719852,"created-at":1590107719852,"author":{"login":"mdave16","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/15642321?v=4"},"body":"; You can also destructure inside the method\n(defn foo\n \"Will be passed a hash\"\n [{x :bar y :baz}]\n (+ x y))\n\n(foo 1 2)\n; Wrong number of args (2) passed\n\n(foo {:bar 1 :baz 2})\n; 3\n\n(defn potentially-confusing-fn\n \"Will be passed a hash with one key\"\n [{x :match}]\n (* x x))\n\n(potentially-confusing-fn 1)\n; NullPointerException and nil return\n\n(potentially-confusing-fn {:match 2})\n; 4","_id":"5ec71e47e4b087629b5a190d"}],"macro":true,"notes":null,"arglists":["name doc-string? attr-map? [params*] prepost-map? body","name doc-string? attr-map? ([params*] prepost-map? body) + attr-map?"],"doc":"Same as (def name (fn [params* ] exprs*)) or (def\n name (fn ([params* ] exprs*)+)) with any doc-string or attrs added\n to the var metadata. prepost-map defines a map with optional keys\n :pre and :post that contain collections of pre or post conditions.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/defn"},{"added":"1.0","ns":"clojure.core","name":"ref","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1284616785000,"author":{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},"to-var":{"ns":"clojure.core","name":"alter","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d3e"},{"created-at":1284616936000,"author":{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},"to-var":{"ns":"clojure.core","name":"ref-set","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d3f"},{"created-at":1323973222000,"author":{"login":"Claj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5fd658a8d2ef549071cb5286b1b874aa?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"add-watch","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d40"},{"created-at":1326521654000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"dosync","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d41"},{"created-at":1349393302000,"author":{"login":"eric","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2b0c9ae6f1da9716451e7c86bc87230b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"commute","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d42"},{"created-at":1349397556000,"author":{"login":"eric","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2b0c9ae6f1da9716451e7c86bc87230b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"ensure","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d43"},{"created-at":1364770237000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"ref-history-count","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d44"},{"created-at":1364770253000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"ref-min-history","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d45"},{"created-at":1364770260000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"ref-max-history","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d46"},{"created-at":1364873716000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"set-validator!","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d47"}],"line":2279,"examples":[{"author":{"login":"devn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3"},"editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3","account-source":"github","login":"devn"},{"avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3","account-source":"github","login":"devn"},{"avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3","account-source":"github","login":"devn"},{"avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3","account-source":"github","login":"devn"},{"avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3","account-source":"github","login":"devn"},{"avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3","account-source":"github","login":"devn"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"AtKaaZ","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e10dfa345f44b0fe72bbe081fd51b83?r=PG&default=identicon"}],"body":"user=> (ref [])\n#\n\nuser=> (ref 1 :validator pos?)\n#\n\n=> (ref 0 :validator pos?)\nIllegalStateException Invalid reference state clojure.lang.ARef.validate (ARef.java:33)\n\n=> (dosync (ref-set (ref 1 :validator pos?) 0))\nIllegalStateException Invalid reference state clojure.lang.ARef.validate (ARef.java:33)\n\n=> (dosync (ref-set (ref 1 :validator pos?) 2))\n2","created-at":1280779137000,"updated-at":1360387666000,"_id":"542692cac026201cdc326b3a"},{"updated-at":1470997853281,"created-at":1470997853281,"author":{"login":"Lacty","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7412474?v=3"},"body":"; create(ref)\n(def a (ref '(1 2 3)))\n\n; read(deref)\n(deref a) ; -> (1 2 3)\n\n; rewrite(ref-set)\n; (ref-set a '(3 2 1)) err!\n(dosync (ref-set a '(3 2 1)))\n\n(deref a) ; -> (3 2 1)","_id":"57ada55de4b0bafd3e2a04e7"},{"updated-at":1548668131418,"created-at":1548668131418,"author":{"login":"Activeghost","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10783037?v=4"},"body":";; EXAMPLE: Storing an object in a state map to control it's lifecycle\n(def state (ref {}))\n\n(defn start->streams\n []\n (log/info \"[start->streams] enter\")\n\n;; deref state and do something with it (in this case, check if we have created it)\n (when (not (instance? KafkaStreams (:streams @state)))\n (let [config-file (s/conform ::configs/configuration-file (configs/config CONFIG_PATH))\n kafka-config (s/conform ::configs/kafka-configuration (:processor.config/kafka-configuration config-file))\n stream-processing-props {StreamsConfig/APPLICATION_ID_CONFIG (:applicationid kafka-config)\n StreamsConfig/COMMIT_INTERVAL_MS_CONFIG (:auto.commit.interval.ms kafka-config)\n StreamsConfig/BOOTSTRAP_SERVERS_CONFIG (:bootstrap-servers kafka-config)\n StreamsConfig/DEFAULT_KEY_SERDE_CLASS_CONFIG (.getName (.getClass (Serdes/String)))\n StreamsConfig/DEFAULT_VALUE_SERDE_CLASS_CONFIG (.getName (.getClass (Serdes/String)))\n StreamsConfig/PROCESSING_GUARANTEE_CONFIG StreamsConfig/EXACTLY_ONCE}]\n (try \n (log/infof \"[start->streams] creating kafka stream with config: %s\" stream-processing-props)\n\n (dosync \n\n;; update the ref and store an object in the state map\n (alter state conj (-> { :streams (KafkaStreams. (topology) (StreamsConfig. stream-processing-props))})))\n (log/info \"[start->streams] stream created\")\n\n (catch Exception e (log/error e)))))\n\n;; deref the state and call an fn on the contained object\n (.start (:streams @state)))\n","_id":"5c4ecce3e4b0ca44402ef655"},{"updated-at":1553601306531,"created-at":1553601306531,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"body":";; Refs automatically deref their content when used as a function:\n(def m (ref {:a 1 :b 2}))\n\n(m :a)\n;; 1\n\n;; Refs natural ordering is by creation time (oldest first), not their content:\n(def z (ref 10))\n(def y (ref 12))\n(def x (ref 1))\n\n(map deref (sort [x y z]))\n;; (10 12 1)","_id":"5c9a131ae4b0ca44402ef6ca"}],"notes":null,"arglists":["x","x & options"],"doc":"Creates and returns a Ref with an initial value of x and zero or\n more options (in any order):\n\n :meta metadata-map\n\n :validator validate-fn\n\n :min-history (default 0)\n :max-history (default 10)\n\n If metadata-map is supplied, it will become the metadata on the\n ref. validate-fn must be nil or a side-effect-free fn of one\n argument, which will be passed the intended new state on any state\n change. If the new state is unacceptable, the validate-fn should\n return false or throw an exception. validate-fn will be called on\n transaction commit, when all refs have their final values.\n\n Normally refs accumulate history dynamically as needed to deal with\n read demands. If you know in advance you will need history you can\n set :min-history to ensure it will be available when first needed (instead\n of after a read fault). History is limited, and the limit can be set\n with :max-history.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/ref"},{"added":"1.3","ns":"clojure.core","name":"bigint","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1509577775565,"author":{"login":"chrm","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/448995?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"biginteger","ns":"clojure.core"},"_id":"59fa542fe4b0a08026c48c90"},{"created-at":1567418361421,"author":{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"bigdec","ns":"clojure.core"},"_id":"5d6ce7f9e4b0ca44402ef7aa"}],"line":3645,"examples":[{"author":{"login":"Miles","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bbb26d2a5e856c4fba0f72c3f7250f3f?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"Miles","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bbb26d2a5e856c4fba0f72c3f7250f3f?r=PG&default=identicon"},{"login":"rebcabin","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/880b0bb3a4be9237326dd69565444dee?r=PG&default=identicon"}],"body":"user=> (bigint 30)\n30\n\n\n;; Actually do something BigInteger-ish... (http://download.oracle.com/javase/6/docs/api/)\n\nuser=> (def x (bigint 97))\n#'user/x\n\nuser=> (.isProbablePrime (.toBigInteger x) 100)\ntrue\n","created-at":1283817133000,"updated-at":1375568824000,"_id":"542692cec026201cdc326d94"},{"author":{"login":"rebcabin","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/880b0bb3a4be9237326dd69565444dee?r=PG&default=identicon"},"editors":[{"login":"rebcabin","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/880b0bb3a4be9237326dd69565444dee?r=PG&default=identicon"},{"avatar-url":"https://avatars2.githubusercontent.com/u/31996?v=4","account-source":"github","login":"avelino"}],"body":"user> (= (bigint 42) (clojure.lang.BigInt/fromBigInteger (BigInteger. \"42\")))\ntrue\nuser> (= 42N (bigint 42))\ntrue\nuser> (= 42 (bigint 42))\ntrue\nuser> (= 42 (clojure.lang.BigInt/fromBigInteger (BigInteger. \"42\")))\ntrue\n","created-at":1375568690000,"updated-at":1528931565159,"_id":"542692d2c026201cdc326f4f"},{"author":{"login":"rebcabin","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/880b0bb3a4be9237326dd69565444dee?r=PG&default=identicon"},"editors":[{"login":"rebcabin","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/880b0bb3a4be9237326dd69565444dee?r=PG&default=identicon"}],"body":"user> (reduce * (repeat 20 1000))\nArithmeticException integer overflow clojure.lang.Numbers.throwIntOverflow (Numbers.java:1388)\n\nuser> (reduce * (repeat 20 (bigint 1000)))\n1000000000000000000000000000000000000000000000000000000000000N\n","created-at":1375569614000,"updated-at":1375569672000,"_id":"542692d2c026201cdc326f51"},{"updated-at":1509577762158,"created-at":1509577762158,"author":{"login":"chrm","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/448995?v=4"},"body":";; There is a difference between `BigInt` and `BigInteger`. The first is from\n;; Clojure and should be better for performace, because less unboxing is\n;; necessary. The second is from Java and has more functionality.\n;; https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html\n\n(type 123N)\n;; => clojure.lang.BigInt\n\n(type (bigint 123))\n;; => clojure.lang.BigInt\n\n(type (biginteger 123))\n;; => java.math.BigInteger\n\n(.modInverse (bigint 123) (bigint 4))\n;; IllegalArgumentException No matching method found: modInverse for class\n;; clojure.lang.BigInt\n\n(.modInverse (biginteger 123) (biginteger 4))\n;; => 3","_id":"59fa5422e4b0a08026c48c8f"},{"updated-at":1535909892844,"created-at":1535909892844,"author":{"login":"cloojure","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/7083783?v=4"},"body":"; It also works for strings\n(bigint \"12345\") => 12345N\n","_id":"5b8c2004e4b00ac801ed9e7e"},{"updated-at":1598220963933,"created-at":1598220963933,"author":{"login":"berczeck","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/1321842?v=4"},"body":";; Take care with ratios the decimal part is removed not rounded\nuser=> (bigint 5/4) ; 1.25\n;; 1N\n\nuser=> (bigint 5/2) ; 2.5\n;; 2N","_id":"5f42eaa3e4b0b1e3652d73a7"}],"notes":[{"updated-at":1375486531000,"body":"The last example does not seem to work; there seems to be a missing coercion from Clojure BigInt to Java BigInteger. I get
\r\nIllegalArgumentException No matching method found: isProbablePrime for class clojure.lang.BigInt  clojure.lang.Reflector.invokeMatchingMethod (Reflector.java:53)
","created-at":1375486531000,"author":{"login":"rebcabin","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/880b0bb3a4be9237326dd69565444dee?r=PG&default=identicon"},"_id":"542692edf6e94c697052200a"}],"tag":"clojure.lang.BigInt","arglists":["x"],"doc":"Coerce to BigInt","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/bigint"},{"added":"1.2","ns":"clojure.core","name":"extends?","file":"clojure/core_deftype.clj","type":"function","column":1,"see-alsos":[{"created-at":1302036433000,"author":{"login":"TimMc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5d532e51427ef2f4ded31aaca16c8baf?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"defprotocol","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cb6"},{"created-at":1491526670270,"author":{"login":"delonnewman","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/10404?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"defrecord","ns":"clojure.core"},"_id":"58e6e40ee4b01f4add58fe84"},{"created-at":1491526677033,"author":{"login":"delonnewman","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/10404?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"deftype","ns":"clojure.core"},"_id":"58e6e415e4b01f4add58fe85"},{"created-at":1501651292857,"author":{"login":"chbrown","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/360279?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"satisfies?","ns":"clojure.core"},"_id":"5981615ce4b0d19c2ce9d705"}],"line":558,"examples":[{"author":{"login":"mstoeckli","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/271f1fe6c39e19db5714ce29b64d3ad5?r=PG&default=identicon"},"editors":[],"body":"user=> (defprotocol Area (get-area [this]))\nArea\n\nuser=> (defrecord Rectangle [width height]\n Area\n (get-area [this]\n (* width height)))\nuser.Rectangle\n\n(extends? Area Rectangle)\ntrue\n","created-at":1337146392000,"updated-at":1337146392000,"_id":"542692d3c026201cdc326fa4"}],"notes":null,"arglists":["protocol atype"],"doc":"Returns true if atype extends protocol","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/extends_q"},{"added":"1.1","ns":"clojure.core","name":"promise","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1343782692000,"author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"to-var":{"ns":"clojure.core","name":"realized?","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ed2"},{"created-at":1291473023000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"future","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f35"},{"created-at":1301868450000,"author":{"login":"TimMc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5d532e51427ef2f4ded31aaca16c8baf?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"deliver","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f36"}],"line":7244,"examples":[{"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"editors":[{"login":"neveu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/197e0539bc06e120eea534aa2a7d3ec0?r=PG&default=identicon"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":"user=> (def x (promise))\n#'user/x\n;; Trying to deref at this point will make your repl wait forever\n\n\nuser=> (deliver x 100)\n#<core$promise$reify__5534@4369a50b: 100>\n\n;; the promise has been delivered, deref x will return immediately\nuser=> @x\n100\n\n","created-at":1280748732000,"updated-at":1285488731000,"_id":"542692c7c026201cdc3269c8"},{"author":{"login":"neotyk","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/366ff985977b3aab09510bc335cd44a4?r=PG&default=identicon"},"editors":[],"body":";; Create a promise\nuser> (def p (promise))\n#'user/p ; p is our promise\n\n;; Check if was delivered/realized\nuser> (realized? p)\nfalse ; No yet\n\n;; Delivering the promise\nuser> (deliver p 42)\n#\n\n;; Check again if it was delivered\nuser> (realized? p)\ntrue ; Yes!\n\n;; Deref to see what has been delivered\nuser> @p\n42\n\n;; Note that @ is shorthand for deref\nuser> (deref p)\n42\n","created-at":1324962605000,"updated-at":1324962605000,"_id":"542692d4c026201cdc32703f"},{"updated-at":1481568139131,"created-at":1474382276273,"author":{"login":"JoshAaronJones","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/19951591?v=3"},"body":";; Illustrates how threads can work together via promises\n;; First, an example to show a future that delivers\n\nuser=> (def p (promise))\n#'user/p\n\n;; future that will deliver the promise from another thread after 10 sec delay\nuser=> (future\n (Thread/sleep 10000)\n (deliver p 123))\n#future[{:status :pending, :val nil} 0x9a51df1]\n\n;; within 10 seconds dereference p, and wait for delivery of the value\nuser=> @p\n123\n\n\n;; Now, an example to show a future that blocks while waiting for a promise\n;; to be delivered -- this is used to achieve callback-style functionality\n\n;; redefine p\nuser=> (def p (promise))\n#'user/p\n\n;; create a new callback thread that will wait for a promise to be delivered\nuser=> (future\n (println \"About to block while waiting for 'p'\")\n (println \"Now I can do some work with the value \" @p))\nAbout to block while waiting for 'p'\n#future[{:status :pending, :val nil} 0x1737df29]\n\n;; deliver the promise, triggering the blocking callback thread\nuser=> (deliver p 123)\nNow I can do some work with the value 123\n#promise[{:status :ready, :val 123} 0x674a4c4a]","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/19951591?v=3","account-source":"github","login":"JoshAaronJones"},{"login":"jamieorc","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2139?v=3"}],"_id":"57e149c4e4b0709b524f0502"}],"notes":null,"arglists":[""],"doc":"Returns a promise object that can be read with deref/@, and set,\n once only, with deliver. Calls to deref/@ prior to delivery will\n block, unless the variant of deref with timeout is used. All\n subsequent derefs will return the same delivered value without\n blocking. See also - realized?.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/promise"},{"added":"1.0","ns":"clojure.core","name":"aset-char","file":"clojure/core.clj","type":"function","column":1,"see-alsos":null,"line":4007,"examples":[{"author":{"login":"shockbob","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon"},"editors":[],"body":";; create an array of 10 characters (initially set to blank by default)\n;; and set one of the elements to the character \"a\"\n\nuser=> (def cs (char-array 10))\n#'user/cs\nuser=> (vec cs)\n[\\ \\ \\ \\ \\ \\ \\ \\ \\ \\ ]\nuser=> (aset-char cs 3 \\a)\n\\a\nuser=> (vec cs)\n[\\ \\ \\ \\a \\ \\ \\ \\ \\ \\ ]\nuser=>","created-at":1313914505000,"updated-at":1313914505000,"_id":"542692c9c026201cdc326ad3"}],"notes":[{"body":"See [aset](http://clojuredocs.org/clojure.core/aset) for illustrations of multi-dimensional syntax.","created-at":1432829137215,"updated-at":1432829137215,"author":{"login":"mars0i","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1836941?v=3"},"_id":"55673cd1e4b01ad59b65f4de"}],"arglists":["array idx val","array idx idx2 & idxv"],"doc":"Sets the value at the index/indices. Works on arrays of char. Returns val.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/aset-char"},{"added":"1.0","ns":"clojure.core","name":"rseq","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1293103256000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"reverse","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c2e"}],"line":1596,"examples":[{"author":{"login":"pkolloch","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/10b2fd3c0a4cc46dc241a48468dc551?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":"user=> (vec (range 10))\n[0 1 2 3 4 5 6 7 8 9]\n\nuser=> (rseq (vec (range 10)))\n(9 8 7 6 5 4 3 2 1 0)\n","created-at":1282324324000,"updated-at":1285494434000,"_id":"542692c8c026201cdc326a58"},{"author":{"login":"clojureking","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/92625b8a6be91bb8c688d0d07b4e2a32?r=PG&default=identicon"},"editors":[{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"}],"body":"(rseq (into (sorted-map) {:a 1 :b 2}))\n;; => ([:b 2] [:a 1])","created-at":1409352627000,"updated-at":1423095124718,"_id":"542692d5c026201cdc327078"},{"updated-at":1613699307202,"created-at":1613698736253,"author":{"login":"Crowbrammer","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/19522656?v=4"},"body":";; Huge performance boost for vectors and sorted maps over `reverse`.\n\n(def nums (vec (range 1000000)))\n(time (reverse nums))\n;; \"Elapsed time: 30.1222 msecs\"\n(time (rseq nums))\n;; \"Elapsed time: 0.0664 msecs\"","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/19522656?v=4","account-source":"github","login":"Crowbrammer"}],"_id":"602f16b0e4b0b1e3652d7457"},{"updated-at":1680191517830,"created-at":1680191517830,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":";; The docstring doesn't mention sorted-sets directly\n;; Arguably they are implied by mention of sorted-maps\n\n(def ss (into (sorted-set) (range 1e6)))\n\n;; So this is a constant time way of getting the last element:\n\n(time (first (rseq ss)))\n\"Elapsed time: 0.04606 msecs\"\n;; => 999999\n\n;; vs the linear approach:\n\n(time (last ss))\n\"Elapsed time: 164.557625 msecs\"\n;; => 999999\n\n","_id":"6425b01de4b08cf8563f4b88"}],"notes":null,"arglists":["rev"],"doc":"Returns, in constant time, a seq of the items in rev (which\n can be a vector or sorted-map), in reverse order. If rev is empty returns nil","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/rseq"},{"added":"1.10","ns":"clojure.core","name":"ex-cause","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1636723273402,"author":{"login":"loeschzwerg","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/24317401?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"ex-info","ns":"clojure.core"},"_id":"618e6a49e4b0b1e3652d756f"},{"created-at":1636723280306,"author":{"login":"loeschzwerg","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/24317401?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"ex-data","ns":"clojure.core"},"_id":"618e6a50e4b0b1e3652d7570"},{"created-at":1636723289915,"author":{"login":"loeschzwerg","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/24317401?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"ex-message","ns":"clojure.core"},"_id":"618e6a59e4b0b1e3652d7571"}],"line":4857,"examples":[{"updated-at":1636723247465,"created-at":1636723247465,"author":{"login":"loeschzwerg","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/24317401?v=4"},"body":";; (ex-cause e) gives you the next linked exception in an Exception-chain\n;; Use \n(def a 1) ;;=> #'user/a\n(def b 0) ;;=> #'user/b\n\n(def chain \n (try \n (/ a b)\n (catch ArithmeticException ae\n (ex-info ;; contextualize ae with ExceptionInfo\n \"Send help, please\"\n {:divisor a\n :divident b}\n ae)))) \n;;=> #'user/chain\n\nchain\n;;=>\n;#error{:cause \"Divide by zero\",\n; :via [{:type clojure.lang.ExceptionInfo,\n; :message \"Send help, please\",\n; :data {:divisor 1, :divident 0},\n; :at [...]}\n; {:type java.lang.ArithmeticException,\n; :message \"Divide by zero\",\n; :at [clojure.lang.Numbers divide \"Numbers.java\" 188]}],\n; :trace [[clojure.lang.Numbers divide \"Numbers.java\" 188]\n; [...]\n; [java.lang.Thread run \"Thread.java\" 829]]}\n\n(ex-cause chain)\n;;=>\n;#error{:cause \"Divide by zero\",\n; :via [{:type java.lang.ArithmeticException, ;; <-- ae is first.\n; :message \"Divide by zero\",\n; :at [clojure.lang.Numbers divide \"Numbers.java\" 188]}],\n; :trace [[clojure.lang.Numbers divide \"Numbers.java\" 188]\n; [...]","_id":"618e6a2fe4b0b1e3652d756e"},{"updated-at":1636972033983,"created-at":1636972033983,"author":{"login":"loeschzwerg","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/24317401?v=4"},"body":";; You can use ex-cause to extract the messages of a chain:\n(defn ex-msg-chain [ex delimiter]\n (->> ex\n (iterate ex-cause)\n (take-while some?)\n (mapv ex-message)\n (interpose delimiter)\n (apply str))\n;;=> #'user/ex-msg-chain\n\n;; Let's try this on a simple chained Exception\n(def chained-ex\n (ex-info \"top-level\"\n {:level 1}\n (ex-info \"sec-level\"\n {:level 2}\n (ex-info \"low-level\"\n {:level 3}))))\n;;=> #'user/chained-ex\n\n(ex-msg-chain chained-ex \" -> \")\n;;=> \"top-level -> sec-level -> low-level\"","_id":"61923601e4b0b1e3652d7578"}],"notes":null,"tag":"java.lang.Throwable","arglists":["ex"],"doc":"Returns the cause of ex if ex is a Throwable.\n Otherwise returns nil.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/ex-cause"},{"added":"1.0","ns":"clojure.core","name":"construct-proxy","file":"clojure/core_proxy.clj","type":"function","column":1,"see-alsos":[{"created-at":1539823552877,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"get-proxy-class","ns":"clojure.core"},"_id":"5bc7d7c0e4b00ac801ed9edf"},{"created-at":1539823559598,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"proxy","ns":"clojure.core"},"_id":"5bc7d7c7e4b00ac801ed9ee0"}],"line":295,"examples":[{"updated-at":1539823495958,"created-at":1539823495958,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"body":";; Compared to \"proxy\" you have the option to pick different \n;; constructors on the same proxy class.\n\n(def MyThread (get-proxy-class Thread))\n\n(defn t\n ([clazz f] (construct-proxy clazz f))\n ([clazz id f] (construct-proxy clazz f id)))\n\n(str (t MyThread #()))\n;; \"Thread[Thread-2,5,main]\"\n\n(str (t MyThread \"***MYTHREAD***\" #()))\n;; \"Thread[***MYTHREAD***,5,main]\"\n","_id":"5bc7d787e4b00ac801ed9ede"}],"notes":null,"arglists":["c & ctor-args"],"doc":"Takes a proxy class and any arguments for its superclass ctor and\n creates and returns an instance of the proxy.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/construct-proxy"},{"added":"1.0","ns":"clojure.core","name":"agent-errors","file":"clojure/core.clj","type":"function","column":1,"see-alsos":null,"line":2253,"examples":null,"deprecated":"1.2","notes":null,"arglists":["a"],"doc":"DEPRECATED: Use 'agent-error' instead.\n Returns a sequence of the exceptions thrown during asynchronous\n actions of the agent.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/agent-errors"},{"added":"1.0","ns":"clojure.core","name":"*compile-files*","type":"var","see-alsos":null,"examples":[{"updated-at":1584381840421,"created-at":1584381840421,"author":{"login":"devn","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/10421?v=4"},"body":";; Ensure that the `require` doesn't result in AOT'd class files\n(binding [*compile-files* false]\n (require 'foo.bar))","_id":"5e6fbf90e4b087629b5a18bf"},{"editors":[{"login":"reborg","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/20086?v=4"}],"body":";; The \"defruntime\" macro below prevents initialization of a definition \n;; during AOT compilation but allows it (once only) at runtime. Can be used to\n;; load configuration files or other runtime only data.\n\n(defmacro defruntime [sym & body]\n `(defonce ~sym\n (when-not *compile-files* ~@body)))\n\n(defruntime config\n (println \"This won't happen during AOT compile\"))\n","author":{"avatar-url":"https://avatars.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"},"created-at":1613847596666,"updated-at":1614012007913,"_id":"60315c2ce4b0b1e3652d745f"}],"notes":null,"arglists":[],"doc":"Set to true when compiling files, false otherwise.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/*compile-files*"},{"added":"1.10","ns":"clojure.core","name":"ex-message","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1602605078561,"author":{"login":"m0smith","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/398808?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"ex-data","ns":"clojure.core"},"_id":"5f85d016e4b0b1e3652d73db"},{"created-at":1602605096620,"author":{"login":"m0smith","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/398808?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"ex-info","ns":"clojure.core"},"_id":"5f85d028e4b0b1e3652d73dc"}],"line":4849,"examples":[{"updated-at":1587607327636,"created-at":1587603158684,"author":{"login":"thiagorfaria","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/5934045?v=4"},"body":"(try\n (let [error-message \"Something went wrong!\"\n error-data {:error 404}]\n (throw (ex-info error-message error-data)))\n (catch Exception e\n (prn (str \"Oops! \" (ex-message e)))\n (prn (str \"Because! \" (ex-data e)))))\n\n;; => \"Oops! Something went wrong!\"\n;; \"Because! {:error 404}\"","editors":[{"avatar-url":"https://avatars2.githubusercontent.com/u/5934045?v=4","account-source":"github","login":"thiagorfaria"}],"_id":"5ea0e6d6e4b087629b5a18dc"}],"notes":null,"arglists":["ex"],"doc":"Returns the message attached to ex if ex is a Throwable.\n Otherwise returns nil.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/ex-message"},{"ns":"clojure.core","name":"*math-context*","type":"var","see-alsos":[{"created-at":1635281435762,"author":{"login":"Chouser","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/36110?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"with-precision","ns":"clojure.core"},"_id":"61786a1be4b0b1e3652d755c"}],"examples":null,"notes":null,"tag":"java.math.MathContext","arglists":[],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core/*math-context*"},{"added":"1.0","ns":"clojure.core","name":"float","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1496073295794,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"unchecked-float","ns":"clojure.core"},"_id":"592c444fe4b093ada4d4d796"},{"created-at":1593104025671,"author":{"login":"mars0i","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/1836941?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"bigdec","ns":"clojure.core"},"_id":"5ef4d699e4b0b1e3652d730f"}],"line":3512,"examples":[{"updated-at":1496073286628,"created-at":1283814444000,"body":"(float 1)\n;;=> 1.0\n(float 1.11)\n;;=> 1.11\n(float 1.111111111111111111111111111M)\n;;=> 1.1111112\n\n;;;; Note that (float) range checks its argument and throws an exception\n;;;; if the value is out of range.\n;;;; Use (unchecked-float) instead if you want to skip the range checks.\n\n(float Double/MAX_VALUE)\n;;=> IllegalArgumentException Value out of range for float: 1.7976931348623157E308\n(unchecked-float Double/MAX_VALUE)\n;;=> Infinity\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3","account-source":"github","login":"jafingerhut"},{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/bbb26d2a5e856c4fba0f72c3f7250f3f?r=PG&default=identicon","account-source":"clojuredocs","login":"Miles"},"_id":"542692c9c026201cdc326afd"},{"editors":[{"login":"wdhowe","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/4631165?v=4"}],"body":";; Casting a string does not work\n(float \"123.456\")\n;;=> Execution error (ClassCastException) at user/eval193 (REPL:1).\n;;java.lang.String cannot be cast to java.lang.Number\n\n;; Use Java interop instead\n(Float/parseFloat \"123.456\")\n;;=> 123.456\n\n;; Content originally posted by u/didibus on https://clojuredocs.org/clojure.core/num","author":{"avatar-url":"https://avatars0.githubusercontent.com/u/4631165?v=4","account-source":"github","login":"wdhowe"},"created-at":1596590631704,"updated-at":1596590780119,"_id":"5f2a0a27e4b0b1e3652d7365"}],"notes":null,"arglists":["x"],"doc":"Coerce to float","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/float"},{"added":"1.0","ns":"clojure.core","name":"pr-str","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1299623857000,"author":{"login":"TimMc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5d532e51427ef2f4ded31aaca16c8baf?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"pr","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b27"},{"created-at":1313054793000,"author":{"login":"TimMc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5d532e51427ef2f4ded31aaca16c8baf?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"read-string","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b28"},{"created-at":1360241771000,"author":{"login":"mmwaikar","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/29d36f4c9f39c9f8ff61c07033b13118?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"prn-str","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b29"},{"created-at":1517964034880,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"str","ns":"clojure.core"},"_id":"5a7a4b02e4b0e2d9c35f7420"}],"line":4785,"examples":[{"author":{"login":"Miles","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bbb26d2a5e856c4fba0f72c3f7250f3f?r=PG&default=identicon"},"editors":[{"login":"Miles","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bbb26d2a5e856c4fba0f72c3f7250f3f?r=PG&default=identicon"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"Kototama","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a54a4dc204925d397ca010b9a332e74d?r=PG&default=identicon"},{"login":"Miles","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bbb26d2a5e856c4fba0f72c3f7250f3f?r=PG&default=identicon"}],"body":"user=> (def x [1 2 3 4 5])\n#'user/x\nuser=> x\n[1 2 3 4 5]\n\n\n;; Turn that data into a string...\nuser=> (pr-str x)\n\"[1 2 3 4 5]\"\n\n\n;; ...and turn that string back into data!\nuser=> (read-string (pr-str x))\n[1 2 3 4 5]\n","created-at":1284257614000,"updated-at":1287792086000,"_id":"542692cbc026201cdc326c20"},{"author":{"login":"dansalmo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e33ee460f5f61bc5ba9b598934766215?r=PG&default=identicon"},"editors":[],"body":";; you can think of pr-str as the inverse of read-string\n;; turn string into symbols\nuser=> (read-string \"(a b foo :bar)\")\n(a b foo :bar)\n\n;;turn symbols into a string\nuser=> (pr-str '(a b foo :bar))\n\"(a b foo :bar)\"","created-at":1346843924000,"updated-at":1346843924000,"_id":"542692d4c026201cdc327032"},{"author":{"login":"GyrosOfWar","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8abc292bf5d9e88cfcbcfbe492774a38?r=PG&default=identicon"},"editors":[{"login":"GyrosOfWar","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8abc292bf5d9e88cfcbcfbe492774a38?r=PG&default=identicon"},{"login":"GyrosOfWar","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8abc292bf5d9e88cfcbcfbe492774a38?r=PG&default=identicon"},{"login":"GyrosOfWar","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8abc292bf5d9e88cfcbcfbe492774a38?r=PG&default=identicon"}],"body":"(defn write-object\n \"Serializes an object to disk so it can be opened again later.\n Careful: It will overwrite an existing file at file-path.\"\n [obj file-path]\n (with-open [wr (writer file-path)]\n (.write wr (pr-str obj)))))","created-at":1391924453000,"updated-at":1391924601000,"_id":"542692d4c026201cdc327033"},{"updated-at":1516110350763,"created-at":1516110350763,"author":{"login":"martinklepsch","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/97496?v=4"},"body":";; Be careful with side-effects that are part of lazy sequences.\n;; Especially printing can yield unexpected results.\nuser=> (->> (range 10)\n (map #(do (println %) %))\n (pr-str))\n\n\"(0\\n1\\n2\\n3\\n4\\n5\\n6\\n7\\n8\\n9\\n0 1 2 3 4 5 6 7 8 9)\"\n","_id":"5a5e020ee4b0a08026c48cf7"},{"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"}],"body":";; sometimes when printing lazy sequences you do not get what you want.\n(str (take 5 (range 10)))\n;=> \"clojure.lang.LazySeq@1b554e1\"\n\n;; in those cases `pr-str` to the rescue.\n(pr-str (take 5 (range 10)))\n;=> \"(0 1 2 3 4)\"","author":{"avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4","account-source":"github","login":"phreed"},"created-at":1517963998229,"updated-at":1517964057656,"_id":"5a7a4adee4b0e2d9c35f741f"},{"editors":[{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"}],"body":";; Be aware that pr-str and friends are influenced by a couple global variables\n;; such as *print-length*:\n\n(set! *print-length* 10)\n(pr-str (range 15))\n;=> \"(0 1 2 3 4 5 6 7 8 9 ...)\"\n\n(set! *print-length* -1)\n(pr-str (range 15))\n;=> \"(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14)\"","author":{"avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4","account-source":"github","login":"bfontaine"},"created-at":1522748816082,"updated-at":1522748961361,"_id":"5ac34d90e4b045c27b7fac30"}],"notes":null,"tag":"java.lang.String","arglists":["& xs"],"doc":"pr to a string, returning it","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/pr-str"},{"added":"1.0","ns":"clojure.core","name":"concat","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1332796328000,"author":{"login":"Olivenmann","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d5b1703fb08dd81e4cb2f653a3aaf10b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"conj","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521da6"},{"created-at":1343083284000,"author":{"login":"john.r.woodward","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/22b6fbc4a386291e45b1cb4449377086?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"into","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521da7"},{"created-at":1520441797302,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"lazy-cat","ns":"clojure.core"},"_id":"5aa019c5e4b0316c0f44f90f"},{"created-at":1590171359727,"author":{"login":"themustafabasit","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/24441401?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"quote","ns":"clojure.core"},"_id":"5ec816dfe4b087629b5a190f"},{"created-at":1597428941227,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"mapcat","ns":"clojure.core"},"_id":"5f36d4cde4b0b1e3652d7377"},{"created-at":1597429044495,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"zipmap","ns":"clojure.core"},"_id":"5f36d534e4b0b1e3652d7378"},{"created-at":1685378146800,"author":{"login":"mars0i","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1836941?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"cat","ns":"clojure.core"},"_id":"6474d462e4b08cf8563f4bbf"},{"created-at":1685378175177,"author":{"login":"mars0i","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1836941?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"cat","ns":"clojure.core.reducers"},"_id":"6474d47fe4b08cf8563f4bc0"}],"line":720,"examples":[{"updated-at":1473090562851,"created-at":1279026744000,"body":"\nuser=> (concat [1 2] [3 4])\n(1 2 3 4)\n\nuser=> (into [] (concat [1 2] [3 4]))\n[1 2 3 4]\n\nuser=> (concat [:a :b] nil [1 [2 3] 4])\n(:a :b 1 [2 3] 4)\n\n=> (concat [1] [2] '(3 4) [5 6 7] #{9 10 8})\n(1 2 3 4 5 6 7 8 9 10)\n;; The last three elements might appear in a different order.\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"avatar-url":"https://www.gravatar.com/avatar/22b6fbc4a386291e45b1cb4449377086?r=PG&default=identicon","account-source":"clojuredocs","login":"john.r.woodward"},{"avatar-url":"https://www.gravatar.com/avatar/22b6fbc4a386291e45b1cb4449377086?r=PG&default=identicon","account-source":"clojuredocs","login":"john.r.woodward"},{"avatar-url":"https://www.gravatar.com/avatar/9e10dfa345f44b0fe72bbe081fd51b83?r=PG&default=identicon","account-source":"clojuredocs","login":"AtKaaZ"},{"login":"mars0i","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1836941?v=3"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/5db30f607f0b5fa70d690311aa3bfd3b?r=PG&default=identicon","account-source":"clojuredocs","login":"kotarak"},"_id":"542692c9c026201cdc326a99"},{"author":{"login":"Bob Jarvis","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5ba4bce40c00d30a3b924cbaaf94c17a?r=PG&default=identicon"},"editors":[],"body":"user=> (concat \"abc\" \"def\")\n(\\a \\b \\c \\d \\e \\f)\n","created-at":1392247889000,"updated-at":1392247889000,"_id":"542692d2c026201cdc326f66"},{"body":"user=> (apply concat '(([1 2]) ([3 4] [5 6]) ([7 8])))\n([1 2] [3 4] [5 6] [7 8])\n","author":{"login":"prabhathk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/11288784?v=3"},"created-at":1430731339291,"updated-at":1430731382642,"editors":[{"login":"prabhathk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/11288784?v=3"}],"_id":"55473a4be4b06eaacc9cda88"},{"updated-at":1501863107172,"created-at":1501863107172,"author":{"login":"RobinNagpal","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/745748?v=4"},"body":"user=> (concat '(1 2 3) '(4 5 6))\n;; (1 2 3 4 5 6)","_id":"59849cc3e4b0d19c2ce9d707"},{"updated-at":1501863170406,"created-at":1501863170406,"author":{"login":"RobinNagpal","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/745748?v=4"},"body":"user=> (concat [1 2 3] [4 5 6])\n;; (1 2 3 4 5 6)","_id":"59849d02e4b0d19c2ce9d708"},{"editors":[{"login":"RobinNagpal","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/745748?v=4"}],"body":"(concat {:a \"A\" :b \"B\" :c \"C\"} {:d \"D\" :e \"E\"})\n;; ([:a \"A\"] [:b \"B\"] [:c \"C\"] [:d \"D\"] [:e \"E\"])","author":{"avatar-url":"https://avatars3.githubusercontent.com/u/745748?v=4","account-source":"github","login":"RobinNagpal"},"created-at":1501863260134,"updated-at":1501863287333,"_id":"59849d5ce4b0d19c2ce9d709"},{"updated-at":1520436404730,"created-at":1520436404730,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"body":"(defn padding-right [s width pad] \n (apply str (take width (concat s (repeat pad)))))\n\n(padding-right \"Clojure\" 10 \" \")\n;; \"Clojure \"","_id":"5aa004b4e4b0316c0f44f90e"},{"editors":[{"login":"manojarya","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/2968153?v=4"}],"body":";; beware! concat returns a lazy 'sequence'. \n\n(conj (concat [1 2] [3 4]) 5) ; doesn't return (1 2 3 4 5)\n;;=>(5 1 2 3 4)","author":{"avatar-url":"https://avatars0.githubusercontent.com/u/2968153?v=4","account-source":"github","login":"manojarya"},"created-at":1569483435769,"updated-at":1569512850496,"_id":"5d8c6aabe4b0ca44402ef7c1"},{"editors":[{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"}],"body":";; Here is a good article by Stuart Sierra in his \"Clojure Dont's\" series\n;; on concat, and how using it in certain ways can lead to surprisingly large\n;; stack usage:\n;; https://stuartsierra.com/2015/04/26/clojure-donts-concat\n\n(first (reduce concat (map next-results (range 1 4000))))\n;; StackOverflowError clojure.core/seq (core.clj:133)\n\n(nth (iterate #(concat % [1 2 3]) [1 2 3]) 4000)\n;; StackOverflowError clojure.core/seq (core.clj:133)","author":{"avatar-url":"https://avatars2.githubusercontent.com/u/109629?v=4","account-source":"github","login":"jafingerhut"},"created-at":1577571723261,"updated-at":1611951560722,"_id":"5e07d58be4b0ca44402ef801"},{"updated-at":1590171425117,"created-at":1588243083702,"author":{"login":"themustafabasit","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/24441401?v=4"},"body":";; list 1\n(def list1 (list 'let ['x 10]))\n;; => #'user/list1\nlist1\n;; => (let [x 10])\n\n;; list 2\n(def list2 (list '(println \"x:\" x) '(println \"Bye!\")))\n;; => #'user/list2\nlist2\n;; => ((println \"x:\" x) (println \"Bye!\"))\n\n;; ***\n;; concat all the elements of list1 & list2, and return a new list \n;; In this case - let + [x 10] + (println \"x:\" x) + (println \"Bye!\")\n\n(concat list1 list2)\n;; => (let [x 10] (println \"x:\" x) (println \"Bye!\"))\n\n(eval (concat list1 list2))\n;; => x: 10\n;; Bye!\n;; nil\n\n\n;; see also - quote","editors":[{"avatar-url":"https://avatars2.githubusercontent.com/u/24441401?v=4","account-source":"github","login":"themustafabasit"}],"_id":"5eaaaa8be4b087629b5a18ec"},{"editors":[{"login":"wactbprot","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/113518?v=4"}],"body":"(concat [1 2 3] nil)\n;; => (1 2 3)\n\n(concat [1 2 3] [nil])\n;; => (1 2 3 nil)","author":{"avatar-url":"https://avatars.githubusercontent.com/u/113518?v=4","account-source":"github","login":"wactbprot"},"created-at":1612534560315,"updated-at":1612534622108,"_id":"601d5320e4b0b1e3652d7449"},{"editors":[{"login":"sofiiahitlan","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/48576209?v=4"}],"body":"(concat [1 2 3] 4 5)\n;; => (1Error printing return value (IllegalArgumentException) at clojure.lang.RT/seqFrom (RT.java:577).\n;; Don't know how to create ISeq from: java.lang.Long\n\n(concat [1 2 3] [4 5])\n;; => (1 2 3 4 5)","author":{"avatar-url":"https://avatars.githubusercontent.com/u/48576209?v=4","account-source":"github","login":"sofiiahitlan"},"created-at":1740065891331,"updated-at":1740065932829,"_id":"67b74c63cd84df5de54e207e"}],"notes":null,"arglists":["","x","x y","x y & zs"],"doc":"Returns a lazy seq representing the concatenation of the elements in the supplied colls.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/concat"},{"added":"1.0","ns":"clojure.core","name":"aset-short","file":"clojure/core.clj","type":"function","column":1,"see-alsos":null,"line":3997,"examples":[{"author":{"login":"shockbob","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon"},"editors":[],"body":";; create an array of 10 shorts and set one of the values to 31415\n\nuser=> (def ss (short-array 10))\n#'user/ss\nuser=> (vec ss)\n[0 0 0 0 0 0 0 0 0 0]\nuser=> (aset-short ss 3 31415)\n31415\nuser=> (vec ss)\n[0 0 0 31415 0 0 0 0 0 0]\nuser=>","created-at":1313915280000,"updated-at":1313915280000,"_id":"542692cac026201cdc326b1c"}],"notes":[{"body":"See [aset](http://clojuredocs.org/clojure.core/aset) for illustrations of multi-dimensional syntax.","created-at":1432829129279,"updated-at":1432829129279,"author":{"login":"mars0i","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1836941?v=3"},"_id":"55673cc9e4b01ad59b65f4dd"}],"arglists":["array idx val","array idx idx2 & idxv"],"doc":"Sets the value at the index/indices. Works on arrays of short. Returns val.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/aset-short"},{"added":"1.5","ns":"clojure.core","name":"set-agent-send-off-executor!","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1553631504676,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"set-agent-send-executor!","ns":"clojure.core"},"_id":"5c9a8910e4b0ca44402ef6d9"},{"created-at":1553631511505,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"send-via","ns":"clojure.core"},"_id":"5c9a8917e4b0ca44402ef6da"},{"created-at":1559240493574,"author":{"login":"pdbrown","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/1607096?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"shutdown-agents","ns":"clojure.core"},"_id":"5cf01f2de4b0ca44402ef73a"}],"line":2112,"examples":[{"updated-at":1553631658338,"created-at":1553631497381,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"body":";; This permanently change the thread pool used by agents receiving \n;; tasks with \"send-off\". Use this to control thread pools of applications\n;; you don't own.\n\n(import '[java.util.concurrent Executors])\n(def fj-pool (Executors/newWorkStealingPool 20))\n(set-agent-send-off-executor! fj-pool)","editors":[{"avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"}],"_id":"5c9a8909e4b0ca44402ef6d8"}],"notes":null,"arglists":["executor"],"doc":"Sets the ExecutorService to be used by send-off","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/set-agent-send-off-executor!"},{"added":"1.0","ns":"clojure.core","name":"ns","file":"clojure/core.clj","type":"macro","column":1,"see-alsos":[{"created-at":1289000801000,"author":{"login":"remleduff","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/f14b40211cdc07185c43edf8f4bd7a5b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"use","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f07"},{"created-at":1289000808000,"author":{"login":"remleduff","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/f14b40211cdc07185c43edf8f4bd7a5b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"require","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f08"},{"created-at":1289000818000,"author":{"login":"remleduff","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/f14b40211cdc07185c43edf8f4bd7a5b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"refer","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f09"},{"created-at":1291628676000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"import","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f0a"},{"created-at":1312583994000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"ns-publics","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f0b"},{"created-at":1340999276000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"in-ns","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f0c"},{"created-at":1355453198000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"remove-ns","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f0d"},{"created-at":1366844150000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"ns-map","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f0e"},{"created-at":1398960898000,"author":{"login":"ryo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3f7913b563c72083c74030d928ba407e?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"*ns*","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f0f"},{"created-at":1686507880947,"author":{"login":"mars0i","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1836941?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"alias","ns":"clojure.core"},"_id":"64861168e4b08cf8563f4bc9"}],"line":5817,"examples":[{"updated-at":1514387836686,"created-at":1279069109000,"body":";; Generate a Java class\n(ns org.clojuredocs.test\n (:gen-class))\n\n(defn -main [] (println \"Hello, World!\"))\n\n\n;; After compilation:\nsh$ java -cp classes org.clojuredocs.test\nHello, World!\n","editors":[{"avatar-url":"https://www.gravatar.com/avatar/81018e4231ac1ce8b7a9e6d377092656?r=PG&default=identicon","account-source":"clojuredocs","login":"devijvers"},{"avatar-url":"https://www.gravatar.com/avatar/81018e4231ac1ce8b7a9e6d377092656?r=PG&default=identicon","account-source":"clojuredocs","login":"devijvers"},{"avatar-url":"https://www.gravatar.com/avatar/81018e4231ac1ce8b7a9e6d377092656?r=PG&default=identicon","account-source":"clojuredocs","login":"devijvers"},{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"login":"jcburley","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/430319?v=4"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/81018e4231ac1ce8b7a9e6d377092656?r=PG&default=identicon","account-source":"clojuredocs","login":"devijvers"},"_id":"542692cac026201cdc326b6e"},{"updated-at":1541261966025,"created-at":1284948992000,"body":";; Let's create a namespace and then assign it as the current namespace\nuser=> (create-ns 'my-new-namespace)\n#namespace[my-new-namespace]\n\nuser=> (ns 'my-new-namespace)\njava.lang.ClassCastException: clojure.lang.PersistentList cannot be cast to\n clojure.lang.Symbol (NO_SOURCE_FILE:26)\n;; oops, this is not the way to do it; if create-ns needs a symbol, ns does not\n\nuser=> (ns my-new-namespace)\nnil\n\nmy-new-namespace=>\n;; it worked as the current namespace is our newly created one\n\n","editors":[{"avatar-url":"https://www.gravatar.com/avatar/8d3c423e74750fa42c0386833e4b8209?r=PG&default=identicon","account-source":"clojuredocs","login":"belun"},{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"login":"enocom","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/1175430?v=4"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/8d3c423e74750fa42c0386833e4b8209?r=PG&default=identicon","account-source":"clojuredocs","login":"belun"},"_id":"542692cac026201cdc326b73"},{"author":{"login":"belun","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8d3c423e74750fa42c0386833e4b8209?r=PG&default=identicon"},"editors":[{"login":"belun","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8d3c423e74750fa42c0386833e4b8209?r=PG&default=identicon"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":";; Generating a class so we can call Clojure from Java \n(ns com.domain.tiny\n (:gen-class\n :name com.domain.tiny\n :methods [#^{:static true} [binomial [int int] double]]))\n\n(defn binomial\n \"Calculate the binomial coefficient.\"\n [n k]\n (let [a (inc n)]\n (loop [b 1\n c 1]\n (if (> b k)\n c\n (recur (inc b) (* (/ (- a b) b) c))))))\n\n(defn -binomial\n \"A Java-callable wrapper around the 'binomial' function.\"\n [n k]\n (binomial n k))\n\n(defn -main []\n (println (str \"(binomial 5 3): \" (binomial 5 3)))\n (println (str \"(binomial 10042 111): \" (binomial 10042 111))))\n\n\n;; Calling from Java\nimport com.domain.tiny;\n\npublic class Main {\n\n public static void main(String[] args) {\n System.out.println(\"(binomial 5 3): \" + tiny.binomial(5, 3));\n System.out.println(\"(binomial 10042, 111): \" + tiny.binomial(10042, 111));\n }\n}\n\n\n;; The result was:\n(binomial 5 3): 10.0\n(binomial 10042, 111): 4.9068389575068143E263\n\n\n;; Example was borrowed from clartaq @ Stack Overflow","created-at":1285031740000,"updated-at":1285486378000,"_id":"542692cac026201cdc326b76"},{"author":{"login":"remleduff","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/f14b40211cdc07185c43edf8f4bd7a5b?r=PG&default=identicon"},"editors":[{"login":"remleduff","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/f14b40211cdc07185c43edf8f4bd7a5b?r=PG&default=identicon"},{"login":"remleduff","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/f14b40211cdc07185c43edf8f4bd7a5b?r=PG&default=identicon"},{"login":"remleduff","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/f14b40211cdc07185c43edf8f4bd7a5b?r=PG&default=identicon"},{"login":"remleduff","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/f14b40211cdc07185c43edf8f4bd7a5b?r=PG&default=identicon"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=3"}],"body":";; Create a namespace named demo.namespace.\n(ns demo.namespace)\n\n;; Clojure recommends namespaces be at least \"two segments\" (ie, they should\n;; have at least one '.') otherwise it will create a class in the \"default\n;; package\", which is discouraged.\n\n;; If this declaration appears in a file named \"demo/namespace.clj\" present\n;; in your classpath, it is known as a \"lib\", \"demo/namespace.clj\" is the lib's\n;; \"root resource\". See http://clojure.org/libs\n\n;; From a clean repl you can load the lib using\nuser=>(require 'demo.namespace) \n; or\nuser=>(use 'demo.namespace)","created-at":1288999353000,"updated-at":1423811574430,"_id":"542692cac026201cdc326b79"},{"author":{"login":"remleduff","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/f14b40211cdc07185c43edf8f4bd7a5b?r=PG&default=identicon"},"editors":[{"login":"remleduff","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/f14b40211cdc07185c43edf8f4bd7a5b?r=PG&default=identicon"},{"login":"remleduff","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/f14b40211cdc07185c43edf8f4bd7a5b?r=PG&default=identicon"},{"login":"remleduff","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/f14b40211cdc07185c43edf8f4bd7a5b?r=PG&default=identicon"},{"login":"remleduff","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/f14b40211cdc07185c43edf8f4bd7a5b?r=PG&default=identicon"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=3"}],"body":";; This example will illustrate changing between namespaces at the repl\n\n;; At the repl, the ns macro can be used to create a namespace, but it is\n;; used to change the current namespace (be careful of typos)\nuser=>(ns demo.namespace)\nnil\ndemo.namespace=> ; The prompt at the repl is now \"demo.namespace\" reflecting\n ; that the current namespace is no longer \"user\".\n\n;; Add a new function to demo.namespace\ndemo.namespace=>(defn foo [] (prn \"Hello from demo.namespace\"))\n#'demo.namespace/foo\n\n;; From within \"demo.namespace\" we can use foo without qualifying it\ndemo.namespace=>(foo)\n\"Hello from demo.namespace\"\nnil\n\n;; Switch back to the \"user\" namespace\ndemo.namespace=>(ns user)\nnil\n\n;; We can no longer use \"foo\" without qualification\nuser=> (foo)\njava.lang.Exception: Unable to resolve symbol: foo in this context\n (NO_SOURCE_FILE:4)\n\nuser=> (demo.namespace/foo)\n\"Hello from demo.namespace\"\nnil\n\n;; The public symbols of \"demo.namespace\" can be \"referred into\" the \"user\"\n;; namespace if desired\nuser=> (refer 'demo.namespace)\nnil\n\n;; foo is now an alias in the \"user\" namespace which refers to the\n;; \"demo.namespace/foo\" symbol\nuser=> (foo)\n\"Hello from demo.namespace\"\nnil","created-at":1289000535000,"updated-at":1423811666025,"_id":"542692cac026201cdc326b7e"},{"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"editors":[],"body":"(ns rosettacode.24game\n (:require [clojure.string :as str])\n (:use clojure.test))\n\n(deftest test\n (is (= \"ABC\" (str/capitalize \"abc\")))","created-at":1289383303000,"updated-at":1289383303000,"_id":"542692cac026201cdc326b83"},{"author":{"login":"scode","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/87b4fd6e7ac86cbf1f1b683f7856057?r=PG&default=identicon"},"editors":[],"body":";; Multiple required namespaces with aliases\n(ns demo.namespace\n (:require [com.example.httplib :as httplib]\n [com.example.otherlib :as otherlib]))\n","created-at":1297670267000,"updated-at":1297670267000,"_id":"542692cac026201cdc326b84"},{"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"editors":[{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"}],"body":";; In clojure 1.4 and higher you can use the refer function from within\n;; a require which is equivalent to (:use foo only [...]) but still \n;; allows you to reference the required namespace:\n(ns my.ns.example\n (:require [my.lib :refer [function1 function2]]))\n\n;; And :refer :all is equivalent to :use :\n(ns my.ns.example\n (:require [my.lib :refer :all]))\n","created-at":1340687963000,"updated-at":1357904913000,"_id":"542692d4c026201cdc327014"},{"updated-at":1358656144000,"created-at":1358656144000,"body":"(ns foo.bar\n (:refer-clojure :exclude [ancestors printf])\n (:require [clojure.contrib sql sql.tests])\n (:use [my.lib this that])\n (:import [java.util Date Timer Random]\n (java.sql Connection Statement)))","editors":[],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3","account-source":"github","login":"devn"},"_id":"542692d4c026201cdc327017"},{"editors":[{"login":"PetrGlad","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/124476?v=3"}],"body":"; Gotchas\n(ns newns1 [:require clojure.string])\n; newns1=> nil ; Success\n; Note use of vector instead of list - ns macro successfuly processes it \n; but some tools that read this code might not recognize this dependency.\n; Always write ns as per documentation.\n\n(in-ns 'newns2)\n; newns2=> #object[clojure.lang.Namespace 0x29a8c1fb \"newns2\"]\n; New namespace was successfully created\n(first [])\n; newns2=> CompilerException java.lang.RuntimeException: \n; Unable to resolve symbol: first in this context, \n; compiling:(NO_SOURCE_PATH:7:1) \n; Although \"first\" is in core library, it's name is not available here. \n; To fix this do\n(clojure.core/refer-clojure)\n; newns2=> nil\n(first [])\n; newns2=> nil ; Success\n\n; \"ns\" macro both switches to a namespace and refers default library, \n; \"in-ns\" just switches to given namespace\n(ns newns3)\n; newns3=> nil\n(first [])\n; newns3=> nil\n","author":{"avatar-url":"https://avatars.githubusercontent.com/u/124476?v=3","account-source":"github","login":"PetrGlad"},"created-at":1473163926788,"updated-at":1473164242037,"_id":"57ceb296e4b0709b524f04e4"},{"updated-at":1508739714948,"created-at":1508739714948,"author":{"login":"thescalaguy","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/24409454?v=4"},"body":";; Shows how to use an attr-map\n;; These are arbitrary key-value pairs\n(ns cljdocs.example.core\n \"This is a doc string, FYI :D\"\n {:author \"John Doe\"\n :last-update-date \"23-10-2017\"})\n=> nil\n\n;; The keys in the attr-map are merged with the compiler-generated attr-map\n(meta *ns*)\n=> {:doc \"This is a doc string, FYI :D\", :author \"John Doe\", :last-update-date \"23-10-2017\"}\n","_id":"59ed8a82e4b03026fe14ea93"},{"updated-at":1549690956926,"created-at":1549690956926,"author":{"login":"mars0i","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/1836941?v=4"},"body":";; If you import a Java class with an unqualified name (perhaps from local\n;; source file), use the bare class name without placing it in a vector or list:\n(ns foo.bar\n (:import MyClass))","_id":"5c5e684ce4b0ca44402ef674"},{"updated-at":1627881643879,"created-at":1604651002536,"author":{"login":"green-coder","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/598193?v=4"},"body":";; References to things in a given namespace can be locally renamed.\n(ns foo.bar\n (:require [clojure.string :refer [blank?]\n :rename {blank? contains-only-spaces-likes?}]))\n\n(contains-only-spaces-likes? \" \")\n; => true\n","editors":[{"avatar-url":"https://avatars1.githubusercontent.com/u/598193?v=4","account-source":"github","login":"green-coder"}],"_id":"5fa507fae4b0b1e3652d73ff"}],"macro":true,"notes":[{"updated-at":1291628686000,"body":"Good description of use/require/import here:\r\n\r\nhttp://blog.8thlight.com/articles/2010/12/6/clojure-libs-and-namespaces-require-use-import-and-ns","created-at":1291628686000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fac"},{"body":"[How to `ns` — Stuart Sierra’s Opinionated Style Guide for Clojure Namespace Declarations]( https://stuartsierra.com/2016/clojure-how-to-ns.html)\n> Make it look like this:\n>
(ns com.example.my-application.server\n  \"Example application HTTP server and routing.\"\n  (:refer-clojure :exclude [send])\n  (:require\n   [clojure.core.async :as async :refer [! >!!]]\n   [com.example.my-application.base]\n   [com.example.my-application.server.sse :as server.sse]\n   [io.pedestal.http :as http]\n   [io.pedestal.http.sse :as http.sse]\n   [ring.util.response :as response])\n  (:import\n   (java.nio.file Files LinkOption)\n   (org.apache.commons.io FileUtils)))
","created-at":1597543297488,"updated-at":1597552862469,"author":{"avatar-url":"https://avatars3.githubusercontent.com/u/2316604?v=4","account-source":"github","login":"finalfantasia"},"_id":"5f389381e4b0b1e3652d7379"},{"author":{"login":"matasaru","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1546100?v=4"},"updated-at":1668983174412,"created-at":1668983174412,"body":"The post referred in the first note has moved to:\n\nhttps://8thlight.com/insights/clojure-libs-and-namespaces-require-use-import-and-ns","_id":"637aa986e4b0b1e3652d768c"}],"arglists":["name docstring? attr-map? references*"],"doc":"Sets *ns* to the namespace named by name (unevaluated), creating it\n if needed. references can be zero or more of: (:refer-clojure ...)\n (:require ...) (:use ...) (:import ...) (:load ...) (:gen-class)\n with the syntax of refer-clojure/require/use/import/load/gen-class\n respectively, except the arguments are unevaluated and need not be\n quoted. (:gen-class ...), when supplied, defaults to :name\n corresponding to the ns name, :main true, :impl-ns same as ns, and\n :init-impl-ns true. All options of gen-class are\n supported. The :gen-class directive is ignored when not\n compiling. If :gen-class is not supplied, when compiled only an\n nsname__init.class will be generated. If :refer-clojure is not used, a\n default (refer 'clojure.core) is used. Use of ns is preferred to\n individual calls to in-ns/require/use/import:\n\n (ns foo.bar\n (:refer-clojure :exclude [ancestors printf])\n (:require (clojure.contrib sql combinatorics))\n (:use (my.lib this that))\n (:import (java.util Date Timer Random)\n (java.sql Connection Statement)))","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/ns"},{"added":"1.0","ns":"clojure.core","name":"symbol","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1289212889000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"var","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d00"},{"created-at":1289212892000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"var?","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d01"},{"created-at":1331269623000,"author":{"login":"franks42","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/b3ee701dd6c481e5d310467ddfe62c48?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"symbol?","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d02"},{"created-at":1331269707000,"author":{"login":"franks42","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/b3ee701dd6c481e5d310467ddfe62c48?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"name","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d03"},{"created-at":1331269713000,"author":{"login":"franks42","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/b3ee701dd6c481e5d310467ddfe62c48?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"namespace","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d04"},{"created-at":1350410406000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"keyword","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d05"},{"created-at":1450416041205,"author":{"login":"blx","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/887504?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"resolve","ns":"clojure.core"},"_id":"567397a9e4b09a2675a0ba79"},{"created-at":1571179415471,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"deref","ns":"clojure.core"},"_id":"5da64b97e4b0ca44402ef7cd"}],"line":591,"examples":[{"author":{"login":"dakrone","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bcacd00a7f05c4772329cf9f446c7987?r=PG&default=identicon"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":";; Returns a symbol with the given namespace and name.\n;;\n;; (symbol name): name can be a string or a symbol.\n;;\n;; (symbol ns name): ns and name must both be strings.\n;;\n;; A symbol string begins with a non-numeric character and can contain\n;; alphanumeric characters and *, +, !, -, _, and ?. (see\n;; http://clojure.org/reader for details).\n;;\n;; symbol does not validate input strings for ns and name, and may return\n;; improper symbols with undefined behavior for non-conformant ns and\n;; name.\n\nuser=> (symbol 'foo)\nfoo\n\nuser=> (symbol \"foo\")\nfoo\n\nuser=> (symbol \"clojure.core\" \"foo\")\nclojure.core/foo\n","created-at":1280546541000,"updated-at":1331646095000,"_id":"542692c8c026201cdc326a06"},{"updated-at":1406075648000,"created-at":1331680187000,"body":";; some gotchas to be aware of:\n\nuser=> (symbol \"user\" 'abc)\nClassCastException clojure.lang.Symbol cannot be cast to java.lang.String clojure.core/symbol (core.clj:523)\n\nuser=> (symbol *ns* \"abc\")\nClassCastException clojure.lang.Namespace cannot be cast to java.lang.String clojure.core/symbol (core.clj:523)\n\nuser=> (symbol 'user \"abc\")\nClassCastException clojure.lang.Symbol cannot be cast to java.lang.String clojure.core/symbol (core.clj:523)\n\n\n;; Warning - the following generated symbols are non-conformant and may wreak\n;; serious havoc in the near/far future when least expected...\n\nuser=> (symbol \"abc def\")\nabc def\n\nuser=> (symbol \"123def\")\n123def\n\nuser=> (symbol \"/123/def/ghi\")\n/123/def/ghi\n\nuser=> (symbol \"/abc/def/ghi\")\n/abc/def/ghi","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/92894?v=3","account-source":"github","login":"rafmagana"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/b3ee701dd6c481e5d310467ddfe62c48?r=PG&default=identicon","account-source":"clojuredocs","login":"franks42"},"_id":"542692d5c026201cdc3270a0"},{"body":";; but keywords and numbers are not names\n(symbol 3)\n;; Long cannot be cast to String\n\n;; ... and so they cannot be converted to symbols\n(symbol :dog) \n;; Keyword cannot be cast to String","author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"},"created-at":1412434976752,"updated-at":1412435184005,"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"}],"_id":"54300c20e4b05f4d257a29a3"}],"notes":null,"tag":"clojure.lang.Symbol","arglists":["name","ns name"],"doc":"Returns a Symbol with the given namespace and name. Arity-1 works\n on strings, keywords, and vars.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/symbol"},{"added":"1.0","ns":"clojure.core","name":"to-array-2d","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1375613655000,"author":{"login":"alilee","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2fb0196dc5a7cd3a5cc73f1b9941c209?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"to-array","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521eac"}],"line":4029,"examples":[{"author":{"login":"yasuto","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cacfb7ecf08cb6461767e514c93b7bf9?r=PG&default=identicon"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":"user> (def a (to-array-2d [[1 2 3][4 5 6]]))\n#'user/a\nuser> (alength a)\n2\nuser> (alength (aget a 0))\n3\nuser> (aget a 0 0)\n1\nuser> (aget a 0 1)\n2\nuser> (aget a 0 2)\n3\nuser> (aget a 1 0)\n4\nuser> (aget a 2 0)\n→ ERROR\nnil\n\nuser> ","created-at":1307740341000,"updated-at":1325519043000,"_id":"542692cac026201cdc326b5b"},{"updated-at":1486711509639,"created-at":1313976771000,"body":";; quick example of a ragged array where the length of each element of the \n;; 2d array is unique\n\nuser=> (def a (to-array-2d [[0][1 2][3 4 5][6 7 8 9]]))\n#'user/a\nuser=> (map alength [(aget a 0)(aget a 1)(aget a 2)])\n(1 2 3)\nuser=>\nuser=> (aget a 0 2)\nArrayIndexOutOfBoundsException java.lang.reflect.Array.get (Array.java:-2)","editors":[{"login":"zezhenyan","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8064559?v=3"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon","account-source":"clojuredocs","login":"shockbob"},"_id":"542692cac026201cdc326b5d"}],"notes":null,"tag":"[[Ljava.lang.Object;","arglists":["coll"],"doc":"Returns a (potentially-ragged) 2-dimensional array of Objects\n containing the contents of coll, which can be any Collection of any\n Collection.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/to-array-2d"},{"added":"1.0","ns":"clojure.core","name":"mod","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1305751254000,"author":{"login":"Kototama","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a54a4dc204925d397ca010b9a332e74d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"rem","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e34"},{"created-at":1414324069552,"author":{"login":"alilee","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/16739?v=2"},"to-var":{"ns":"clojure.core","name":"quot","library-url":"https://github.com/clojure/clojure"},"_id":"544cdf65e4b03d20a102427c"},{"created-at":1468958800877,"author":{"login":"chrismurrph","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10278575?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"/","ns":"clojure.core"},"_id":"578e8850e4b0bafd3e2a04b3"}],"line":3592,"examples":[{"author":{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},"editors":[{"login":"jeffmad","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/c526ef2dcf52b0cf18875fcb5616cee0?r=PG&default=identicon"},{"login":"jeffmad","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/c526ef2dcf52b0cf18875fcb5616cee0?r=PG&default=identicon"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"rvlieshout","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/139665?v=2"}],"body":"user=> (mod 10 5)\n0\n\nuser=> (mod 10 6)\n4\n\nuser=> (mod 10 10)\n0\n\nuser=> (mod 10 -1)\n0\n\n;; The mod function is defined as the amount by which a number exceeds the\n;; largest integer multiple of the divisor that is not greater than that number.\n;; The largest integer multiple of 5 not greater than -2 is 5 * -1 = -5.\n;; The amount by which -2 exceeds -5 is 3. \n;;\nuser=> (mod -2 5) \n3","created-at":1279992236000,"updated-at":1415184216966,"_id":"542692cec026201cdc326d7d"},{"updated-at":1558287692250,"created-at":1466434631179,"author":{"login":"dijonkitchen","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/11434205?v=3"},"body":";; rem and mod are commonly used to get the remainder.\n;; mod means Knuth's mod, Don't confuse it with ANSI C's %\n;; operator, which despite being pronounced\n;; 'mod' actually implements rem, i.e. -10 % 3 = -1.\n;; mod has sign of divisor.\n;; Absolute value depends on dividend and divisor having \n;; same sign or not.\n\nuser=> (mod -10 3)\n2\n\nuser=> (rem -10 3)\n-1\n\nuser=> (mod 10 -3)\n-2\nuser=> (mod -10 -3)\n-1\nuser=> (mod 10 3)\n1","editors":[{"avatar-url":"https://avatars3.githubusercontent.com/u/7660326?v=4","account-source":"github","login":"Shinkenjoe"},{"login":"vaer-k","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/4069456?v=4"}],"_id":"57680447e4b0bafd3e2a048a"},{"updated-at":1486561191724,"created-at":1486561191724,"author":{"login":"betegelse","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/6758479?v=3"},"body":";; It works for float / double numbers, too, where it is defined as\n;; (- n (* (Math/floor (/ n d)) d))\n\nuser=> (mod 1.5 1)\n;;=> 0.5\n\nuser=> (mod 475.095 7)\n;;=> 6.095000000000027\n\nuser=> (mod 1024.8402 5.12)\n;;=> 0.8402000000000953\n\nuser=> (mod -1024.8402 5.12)\n;;=> 4.279799999999905\n\nuser=> (let [n 1024.8402\n d 5.12\n q (Math/floor (/ n d))\n r (mod n d)]\n (->> (* q d) (+ r) (- n)))\n;;=> 0.0\n","_id":"589b1fa7e4b01f4add58fe40"}],"notes":[{"updated-at":1314955596000,"body":"The difference between **rem** and **mod** can be remembered by noting that **mod** always returns a value between 0 and div.","created-at":1314955596000,"author":{"login":"wdkrnls","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/6d08a2f792f289b95fe1d982d4133d71?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fc8"},{"updated-at":1350500565000,"body":"I am confused by the comment about the definition on lines 13+ of the example - which is not accurate when invoking mod when 'num' is positive and 'div' negative. Applying the definition to
(mod 10 -3)
we have \r\n
  • the largest multiple of -3 not exceeding 10 is 9, from using -3 as a multiplier
  • \r\n
  • however (mod 10 -3) yields -2, meaning that 10 exceeds the largest multiple not greater than 10 by -2 i.e. 10 - -2 = 12 is the largest multiple <= 10, a contradiction.
  • \r\n
  • therefore (mod 10 -3) should yield 1, not -2
  • \r\n\r\nSo unless I misunderstood, the definition should be changed to something like:
    \r\n

    \"The mod function is defined as the amount by which a number exceeds the largest integer multiple of the divisor that is not greater than that number, except when the number is positive and the divisor negative, in which case the result is the amount by which the number exceeds the smallest multiple that is not smaller than the number.\"

    \r\n\r\nOr, change the implementation to something similar to:\r\n\r\n
    (defn mod-2\r\n\t  [num div]\r\n\t  (let [m (rem num div)]\r\n\t    (if (or (zero? m) (= (pos? num) (pos? div)))\r\n\t     \tm\r\n\t     \t(if (pos? div) (+ m div) m)))) \r\n
    \r\n\t \t\r\nto fit the current definition.","created-at":1350430293000,"author":{"login":"kingcode","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3d7dd4232cb043d2a3efd99e08ff0983?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fef"}],"arglists":["num div"],"doc":"Modulus of num and div. Truncates toward negative infinity.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/mod"},{"added":"1.0","ns":"clojure.core","name":"amap","file":"clojure/core.clj","type":"macro","column":1,"see-alsos":[{"to-var":{"library-url":"https://github.com/clojure/clojure","name":"areduce","ns":"clojure.core"},"author":{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},"created-at":1342853671000,"_id":"542692ebf6e94c6970521d8d"},{"created-at":1346930905000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"map","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d8e"}],"line":5302,"examples":[{"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":"(def an-array (int-array 25000 (int 0)))\n\nuser=> (time (amap ^ints an-array \n idx \n ret \n (+ (int 1) \n (aget ^ints an-array idx))))\n\n\"Elapsed time: 14.708653 msecs\"\n\n;; Note: without type hinting the performance of would not be good.","created-at":1281078010000,"updated-at":1285495171000,"_id":"542692ccc026201cdc326c51"}],"macro":true,"notes":null,"arglists":["a idx ret expr"],"doc":"Maps an expression across an array a, using an index named idx, and\n return value named ret, initialized to a clone of a, then setting \n each element of ret to the evaluation of expr, returning the new \n array ret.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/amap"},{"added":"1.0","ns":"clojure.core","name":"pop","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1366675885000,"author":{"login":"jjcomer","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/ef581bba2f97adb539c67a35465b3e1b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"peek","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e4d"},{"created-at":1399433581000,"author":{"login":"Yun","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/f18708f979ad613ab134cb5002558965?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"rest","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e4e"},{"created-at":1400493789000,"author":{"login":"ryo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3f7913b563c72083c74030d928ba407e?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"conj","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e4f"},{"created-at":1580395434633,"author":{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"butlast","ns":"clojure.core"},"_id":"5e32ebaae4b0ca44402ef829"},{"created-at":1699735252549,"author":{"login":"mars0i","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1836941?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"pop!","ns":"clojure.core"},"_id":"654fe6d469fbcc0c2261744b"}],"line":1481,"examples":[{"author":{"login":"pkolloch","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/10b2fd3c0a4cc46dc241a48468dc551?r=PG&default=identicon"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":"user=> (peek [1 2 3])\n3\nuser=> (pop [1 2 3])\n[1 2]\nuser=> (peek '(1 2 3))\n1\nuser=> (pop '(1 2 3))\n(2 3)","created-at":1282321157000,"updated-at":1332951332000,"_id":"542692cec026201cdc326db5"},{"updated-at":1523918116720,"created-at":1486084396464,"author":{"login":"HomoEfficio","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/17228983?v=3"},"body":"user=> (peek ())\nnil\nuser=> (pop ())\nIllegalStateException Can't pop empty list\n\nuser=> (peek [])\nnil\nuser=> (pop [])\nIllegalStateException Can't pop empty vector\n\nuser=> (peek (clojure.lang.PersistentQueue/EMPTY))\nnil\nuser=> (into [] (pop (clojure.lang.PersistentQueue/EMPTY)))\n[] ;; Can pop empty Queue","editors":[{"avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"}],"_id":"5893d92ce4b01f4add58fe39"},{"updated-at":1518213815646,"created-at":1518213815646,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"body":";; Use a vector as a LIFO stack to check for balanced brackets\n\n(require '[clojure.set :refer [map-invert]])\n\n(defn balance [form]\n (let [brackets {\\[ \\] \\( \\) \\{ \\}}\n scan (fn [q x]\n (cond\n (brackets x) (conj q x)\n ((map-invert brackets) x)\n (if (= (brackets (peek q)) x)\n (pop q)\n (throw\n (ex-info\n (str \"Unmatched delimiter \" x) {})))\n :else q))]\n (reduce scan [] form)))\n\n(balance \"(let [a (inc 1]) (+ a 2))\")\n;; ExceptionInfo Unmatched delimiter ]\n\n(balance \"(let [a (inc 1)] (+ a 2))\")\n;; []\n","_id":"5a7e1ab7e4b0316c0f44f8b4"},{"updated-at":1518707324327,"created-at":1518707324327,"author":{"login":"ibercode","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/31028993?v=4"},"body":";;basic example on vector and list\n\n;;pop on vector returns a new vector removing the last element\n(pop [1 2 3])\n;; [1 2]\n\n;;pop on list returns a new list removing the first element\n(pop '(1 2 3)) ;; (2 3)","_id":"5a85a27ce4b0316c0f44f8be"}],"notes":[{"updated-at":1349888752000,"body":"Small reminder:\r\n\r\n
    \r\nDo not work for arbitrary seq but just for persistent types implementing clojure.lang.IPersistentStack (like clojure.lang.Persistent*).\r\n\r\n
    \r\nExample:\r\n
    user> (pop (cons 1 '()))\r\n; Evaluation aborted.\r\n
    \r\ndo not work because type is clojure.lang.Cons but\r\n\r\n
    user> (pop (conj '() 1))\r\n()\r\n
    \r\nworks because type is clojure.lang.PersistentList.","created-at":1349885055000,"author":{"login":"tomby42","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/305033855efb82d6041586b874b5bb24?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521feb"}],"arglists":["coll"],"doc":"For a list or queue, returns a new list/queue without the first\n item, for a vector, returns a new vector without the last item. If\n the collection is empty, throws an exception. Note - not the same\n as next/butlast.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/pop"},{"added":"1.0","ns":"clojure.core","name":"use","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1284770251000,"author":{"login":"rbolkey","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d537f88b794c220d6ce447add22c12a7?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"refer","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521dd2"},{"created-at":1284770260000,"author":{"login":"rbolkey","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d537f88b794c220d6ce447add22c12a7?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"require","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521dd3"},{"created-at":1289380610000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"ns","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521dd4"},{"created-at":1291628646000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"import","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521dd5"}],"line":6156,"examples":[{"author":{"login":"scode","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/87b4fd6e7ac86cbf1f1b683f7856057?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":";; Use the namespace clojure.java.io:\nuser=> (use '(clojure.java io))\n\n","created-at":1279160083000,"updated-at":1285497782000,"_id":"542692cfc026201cdc326e03"},{"author":{"login":"dpritchett","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/147981?v=3"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"clizzin","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/555813697e5dc358bb27d5efd3ffa23?r=PG&default=identicon"}],"body":";; Imports only the split function from clojure.string.\nuser=> (use '[clojure.string :only (split)])\nnil\n\n;; split is now available without a namespace qualification.\nuser=> (split \"hello world\" #\" \")\n[\"hello\" \"world\"]\n\n;; You can also add the :as keyword to import the rest of clojure.string\n;; with a namespace qualification.\nuser=> (use '[clojure.string :as s :only (split)])\nnil\n\n;; Now we can access any function in clojure.string using s.\nuser=> (s/replace \"foobar\" \"foo\" \"squirrel\")\n\"squirrelbar\"\n\n;; And we can still call split with or without the s qualification.\nuser=> (split \"hello world\" #\" \")\n[\"hello\" \"world\"]\nuser=> (s/split \"hello world\" #\" \")\n[\"hello\" \"world\"]","created-at":1279596076000,"updated-at":1294233809000,"_id":"542692cfc026201cdc326e05"},{"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"editors":[{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"}],"body":"(ns some.namespace\n (:require [clojure.contrib.json :as json])\n (:use [clojure.string :only [trim lower-case split]]\n [clojure.contrib.shell-out]\n [clojure.pprint]\n [clojure.test]))\n","created-at":1291021620000,"updated-at":1338424818000,"_id":"542692cfc026201cdc326e08"},{"updated-at":1474049969039,"created-at":1474049969039,"author":{"login":"mars0i","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1836941?v=3"},"body":";; use accepts other keywords from require that aren't listed in the docstring.\n\n;; If you try to load a namespace, and it fails to load due to an error in\n;; the source code, when you load it again after fixing the problem, you\n;; can get a \"namespace not found\" exception. Use :reload to avoid this:\n(use '[my.namespace] :reload)\n\n;; However, if the error was in source for a namespace required or used\n;; from my.namespace, you'll get the \"namespace not found\" exception\n;; after fixing the problem, even using :reload. Use :reload-all to avoid this:\n(use '[my.namespace] :reload-all)\n\n;; You can also use :verbose, which does what you would think it would do:\n(use '[my.namespace] :verbose)","_id":"57dc37b1e4b0709b524f04fb"},{"updated-at":1648959694945,"created-at":1648959694945,"author":{"login":"mars0i","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1836941?v=4"},"body":";; As the docstring says,\n;;\n;; The arguments and semantics for :exclude, :only, and :rename are the same\n;; as those documented for clojure.core/refer\n;;\n;; but the syntax for these options is derived from require, not refer.\n;; Here is an example using Clojure 1.11, in which the abs function was\n;; introduced into clojure.core.\n\n;; First let's try it with require and refer separately:\nuser=> (require 'clojure.math.numeric-tower)\nnil\nuser=> (refer 'clojure.math.numeric-tower :exclude '[abs])\nnil\nuser=> abs\n#object[clojure.core$abs 0x36fdf831 \"clojure.core$abs@36fdf831\"]\n;; The last line shows that we've correctly excluded the version of\n;; abs that numeric-tower defines, and instead are using the version of abs\n;; that's now in clojure.core.\n\n;; Now let's try it with use. The refer-style syntax doesn't work:\nuser=> (use 'clojure.math.numeric-tower :exclude '[abs])\nSyntax error compiling at (/private/var/folders/68/d0l7z7p906l07fj6s7j5_ygm0000gq/T/form-init6849217183418449171.clj:1:1).\nUnsupported option(s) supplied: :exclude\n;; Instead :exclude must be wrapped up with the namespace in a sequence,\n;; as with options for require:\nuser=> (use '[clojure.math.numeric-tower :exclude [abs]])\nnil\nuser=> abs\n#object[clojure.core$abs 0x13abd924 \"clojure.core$abs@13abd924\"]\n","_id":"624920cee4b0b1e3652d75ca"}],"notes":[{"updated-at":1291628658000,"body":"Good description of use/require/import here:\r\n\r\nhttp://blog.8thlight.com/articles/2010/12/6/clojure-libs-and-namespaces-require-use-import-and-ns","created-at":1291628658000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fab"},{"updated-at":1318868130000,"body":"http://blog.8thlight.com/colin-jones/2010/12/05/clojure-libs-and-namespaces-require-use-import-and-ns.html","created-at":1318868130000,"author":{"login":"vikbehal","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/b773242b82712096e51f5f6aed5f9abd?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fd0"},{"author":{"login":"rafaroca","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/609454?v=4"},"updated-at":1667422305527,"created-at":1667422305527,"body":"The blog post from 8thlight is not available under the above URL anymore. The Wayback Machine has a snapshot of it.\n\nhttps://web.archive.org/web/20220323035057/https://8thlight.com/blog/colin-jones/2010/12/05/clojure-libs-and-namespaces-require-use-import-and-ns.html","_id":"6362d861e4b0b1e3652d7680"}],"arglists":["& args"],"doc":"Like 'require, but also refers to each lib's namespace using\n clojure.core/refer. Use :use in the ns macro in preference to calling\n this directly.\n\n 'use accepts additional options in libspecs: :exclude, :only, :rename.\n The arguments and semantics for :exclude, :only, and :rename are the same\n as those documented for clojure.core/refer.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/use"},{"ns":"clojure.core","name":"unquote","file":"clojure/core.clj","type":"var","column":1,"see-alsos":[{"created-at":1319196053000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"unquote-splicing","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d5d"},{"created-at":1537911869941,"author":{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/94482?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"quote","ns":"clojure.core"},"_id":"5baaac3de4b00ac801ed9ea6"}],"line":13,"examples":[{"author":{"login":"huahaiy","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/889685?v=2"},"editors":[{"login":"huahaiy","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/889685?v=2"}],"body":"user=> (let [x 2]\n `(1 x 3))\n(1 user/x 3)\n\nuser=> (let [x 2]\n `(1 ~x 3))\n(1 2 3)\n","created-at":1305077398000,"updated-at":1305077465000,"_id":"542692cec026201cdc326d76"},{"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"editors":[],"body":"user=> `(1 (dec 3) 3)\n\n(1 (clojure.core/dec 3) 3)\n\nuser => `(1 ~(dec 3) 3)\n\n(1 2 3)","created-at":1319196729000,"updated-at":1319196729000,"_id":"542692d5c026201cdc3270af"}],"notes":null,"arglists":[],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core/unquote"},{"added":"1.0","ns":"clojure.core","name":"declare","file":"clojure/core.clj","type":"macro","column":1,"see-alsos":[{"created-at":1336168390000,"author":{"login":"gavilancomun","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/f4b1f93f88e052f9eb412a8791b6ddf1?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"def","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c7e"},{"created-at":1763765247119,"author":{"login":"claj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/353113?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"letfn","ns":"clojure.core"},"_id":"6920ebff848d032713abce4a"}],"line":2793,"examples":[{"updated-at":1285500741000,"created-at":1279161281000,"body":"user=> (defn foo []\n (undefined-func))\n; Evaluation aborted. Unable to resolve symbol: undefined-func in this context\nnil\n\nuser=> (declare undefined-func)\n#'user/undefined-func\n\nuser=> (defn foo []\n (undefined-func))\n#'user/foo\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/142529?v=3","account-source":"github","login":"nipra"},"_id":"542692cdc026201cdc326d18"},{"author":{"login":"lu4nx","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4acdafde2cbf672ee0389cf8016378?r=PG&default=identicon"},"editors":[{"login":"lu4nx","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4acdafde2cbf672ee0389cf8016378?r=PG&default=identicon"}],"body":"user=> (declare show)\n#'user/show\nuser=> (defn welcome [user-name] (prn (show) user-name))\n#'user/welcome\nuser=> (defn show [] (prn \"welcome \"))\n#'user/show\nuser=> (welcome \"lu4nx\")\n\"welcome \"\nnil \"lu4nx\"\nnil\nuser=> ","created-at":1385992546000,"updated-at":1385992606000,"_id":"542692d2c026201cdc326f78"},{"body":"; def will do too.\nuser=> (def show)\n#'user/show\nuser=> (defn welcome [user-name] (prn (show) user-name))\n#'user/welcome\nuser=> (defn show [] (prn \"welcome\"))\n#'user/show\nuser=> (welcome \"lu4nx\")\n\"welcome\"\nnil \"lu4nx\"\nnil","author":{"login":"kimtg","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7685905?v=3"},"created-at":1425741679616,"updated-at":1425741679616,"_id":"54fb176fe4b0b716de7a6533"},{"editors":[{"login":"owenRiddy","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/8080718?v=4"}],"body":";;Declare (like \"def\") has a natural partner in \"var\".\n;;Consider trying to embed a to-be-defined function in a data structure:\n\n(declare foo)\n(def bar {:handy-fn foo})\n(defn foo [] 42)\n((:handy-fn bar))\n;;IllegalStateException Attempting to call unbound fn: #'user/foo clojure.lang.Var$Unbound.throwArity (Var.java:43)\n\n;;:handy-fn in bar is now permanently linked to the unbound var\n;; present when the def was evaluated. This can be avoided\n;; by not evaluating foo when creating bar.\n\n(declare foo)\n;;(def bar {:handy-fn (var foo)})\n(def bar {:handy-fn #'foo})\n(defn foo [] 42)\n((:handy-fn bar))\n;; 42","author":{"avatar-url":"https://avatars0.githubusercontent.com/u/8080718?v=4","account-source":"github","login":"owenRiddy"},"created-at":1502501725640,"updated-at":1502501762521,"_id":"598e5b5de4b0d19c2ce9d714"}],"macro":true,"notes":null,"arglists":["& names"],"doc":"defs the supplied var names with no bindings, useful for making forward declarations.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/declare"},{"added":"1.1","ns":"clojure.core","name":"dissoc!","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1329969087000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.core","name":"assoc!","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ea9"},{"created-at":1577916166729,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/109629?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"conj!","ns":"clojure.core"},"_id":"5e0d1706e4b0ca44402ef80b"}],"line":3407,"examples":[{"author":{"avatar-url":"https://avatars.githubusercontent.com/u/1453?v=4","account-source":"github","login":"ghoseb"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":";; dissoc! works on a transient map\n\n;; WARNING: Below is an example of what is called \"bashing in place\" of\n;; a transient, and is _NOT_ the correct way to use transients. See assoc!\n;; examples for some discussion of the reason.\n;; Also see one example for conj! that contains a detailed example\n;; of a wrong result that can occur if you do not use its return value.\n\n(let [my-map (transient {:x 1 :y 2 :z 3})]\n (dissoc! my-map :x) ; mistake is to use my-map below, not dissoc! return val\n (persistent! my-map)) ; returns persistent map {:y 2 :z 3}\n\n\n;; Here is a correct way to do the operation described above:\n\n(let [my-map (transient {:x 1 :y 2 :z 3})\n x (dissoc! my-map :x)] ; after this, don't use my-map again, only x\n (persistent! x)) ; returns persistent map {:y 2 :z 3}","created-at":1293728413000,"updated-at":1577916082525,"_id":"542692cbc026201cdc326c15"}],"notes":null,"arglists":["map key","map key & ks"],"doc":"Returns a transient map that doesn't contain a mapping for key(s).","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/dissoc!"},{"added":"1.2","ns":"clojure.core","name":"reductions","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1289800579000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"reduce","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b07"},{"created-at":1423043837477,"author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"to-var":{"ns":"clojure.core","name":"reduced","library-url":"https://github.com/clojure/clojure"},"_id":"54d1ecfde4b081e022073c59"}],"line":7362,"examples":[{"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":"user=> (reductions + [1 1 1 1])\n(1 2 3 4)\nuser=> (reductions + [1 2 3])\n(1 3 6)\n\n;; This is just like reduce except that the calculation is collected during the reduce.\nuser=> (assert (= (reduce + [1 2 3]) \n (last (reductions + [1 2 3]))))\nnil\n","created-at":1281363432000,"updated-at":1285494988000,"_id":"542692cbc026201cdc326baa"},{"body":"user=> (reductions conj [] '(1 2 3))\n([] [1] [1 2] [1 2 3])","author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"created-at":1423043905622,"updated-at":1423043905622,"_id":"54d1ed41e4b081e022073c5a"},{"body":"user=> (reductions + [1 2 3 4 5])\n(1 3 6 10 15)\n\n;;defining the function to perform the same reductions\nuser=> (reductions (fn [sum num] (+ sum num)) [1 2 3 4 5])\n;;(1 3 6 10 15)\n\n;;reductions using a init value 100\nuser=> (reductions (fn [sum num] (+ sum num)) 100 [1 2 3 4 5])\n;;(100 101 103 106 110 115)\n\n;;defining a function for the same reductions\nuser=>(defn add [sum num] \n #_=>(+ sum num))\n;;#'user/add\n\nuser=>(reductions add [1 2 3 4 5])\n;;(1 3 6 10 15)","author":{"login":"pavanred","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/60858?v=3"},"created-at":1427434749175,"updated-at":1427476229157,"editors":[{"login":"pavanred","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/60858?v=3"}],"_id":"5514ecfde4b08eb9aa0a8d3a"},{"updated-at":1488836230529,"created-at":1488836230529,"author":{"login":"matrix10657","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/1264071?v=3"},"body":";; useful for performing lazy calculations which rely on \n;; previous calculations\n\n;; e.g. Taking an infinite list of posts with some height and \n;; adding an offset to each, which is the sum of all previous \n;; heights\n\nuser=> (def posts (repeat {:height 50}))\n#'user/posts\n\nuser=> (take 3 posts)\n({:height 50} {:height 50} {:height 50})\n\nuser=> (def posts-with-offsets\n #_=> (map #(assoc %1 :offset %2)\n #_=> posts\n #_=> (reductions + 0 (map :height posts))))\n#'user/posts-with-offsets\n\nuser=> (take 3 posts-with-offsets)\n({:height 50, :offset 0} {:height 50, :offset 50} {:height 50, :offset 100})\n\n","_id":"58bdd686e4b01f4add58fe6b"}],"notes":[{"author":{"login":"betegelse","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/6758479?v=3"},"updated-at":1486825461877,"created-at":1486825461877,"body":"I think the description above would be clearer if it stated that the result of reductions is equivalent to the sequence of results of applying reduce to `(take n coll)`, with `n` starting with 1, that is, equivalent to\n```clojure\n(defn my-reduce [op coll] (for [n (range (count coll))] (reduce op (take (inc n) coll)))\n```\n","_id":"589f27f5e4b01f4add58fe4a"},{"author":{"login":"jayzawrotny","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/590297?v=4"},"updated-at":1523454828509,"created-at":1523454828509,"body":"In other libraries and languages this function may be referred to as \"scan\". ","_id":"5ace136ce4b045c27b7fac3c"}],"arglists":["f coll","f init coll"],"doc":"Returns a lazy seq of the intermediate values of the reduction (as\n per reduce) of coll by f, starting with init.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/reductions"},{"added":"1.0","ns":"clojure.core","name":"aset-byte","file":"clojure/core.clj","type":"function","column":1,"see-alsos":null,"line":4002,"examples":[{"author":{"login":"shockbob","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon"},"editors":[],"body":";; create an array of 10 bytes and set one of the values to 127\n\nuser=> (def bs (byte-array 10))\n#'user/bs\nuser=> (vec bs)\n[0 0 0 0 0 0 0 0 0 0]\nuser=> (aset-byte bs 2 127)\n127\nuser=> (vec bs)\n[0 0 127 0 0 0 0 0 0 0]\nuser=>","created-at":1313914294000,"updated-at":1313914294000,"_id":"542692c6c026201cdc32692c"}],"notes":[{"body":"See [aset](http://clojuredocs.org/clojure.core/aset) for illustrations of multi-dimensional syntax.","created-at":1432829120788,"updated-at":1432829120788,"author":{"login":"mars0i","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1836941?v=3"},"_id":"55673cc0e4b03e2132e7d172"}],"arglists":["array idx val","array idx idx2 & idxv"],"doc":"Sets the value at the index/indices. Works on arrays of byte. Returns val.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/aset-byte"},{"added":"1.9","ns":"clojure.core","name":"indexed?","file":"clojure/core.clj","type":"function","column":1,"see-alsos":null,"line":6340,"examples":[{"updated-at":1611630046254,"created-at":1611630046254,"author":{"login":"Crowbrammer","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/19522656?v=4"},"body":"(indexed? '(1 2 3)) ;;=> false\n\n(indexed? [1 2 3]) ;;=> true\n\n(indexed? {:a \"Hi\" :hello \"Why\"}) ;;=> false\n\n(indexed? (sorted-set 1 2 3)) ;;=> false\n\n(indexed? #{1 2 3}) ;;=> false","_id":"600f85dee4b0b1e3652d743d"}],"notes":null,"arglists":["coll"],"doc":"Return true if coll implements Indexed, indicating efficient lookup by index","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/indexed_q"},{"added":"1.1","ns":"clojure.core","name":"ref-history-count","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1329984882000,"author":{"login":"Claj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5fd658a8d2ef549071cb5286b1b874aa?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"ref-min-history","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521eb6"},{"created-at":1329984893000,"author":{"login":"Claj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5fd658a8d2ef549071cb5286b1b874aa?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"ref-max-history","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521eb7"},{"created-at":1364770223000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"ref","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521eb8"}],"line":2480,"examples":[{"author":{"login":"Claj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5fd658a8d2ef549071cb5286b1b874aa?r=PG&default=identicon"},"editors":[],"body":"user=> (def store (ref {}))\n#'user/store\nuser=> (ref-history-count store)\n0\nuser=> (ref-max-history store)\n10\nuser=> (ref-min-history store)\n0","created-at":1329984988000,"updated-at":1329984988000,"_id":"542692d5c026201cdc327069"},{"updated-at":1656667547237,"created-at":1656667547237,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":";; ref must have a :min-history of >0 to use the history queue\n\n(def r (ref 42 :min-history 2));; => #'user/r\n(ref-history-count r);; => 0\n(dosync (alter r inc));; => 43\n(ref-history-count r);; => 1\n(dosync (alter r inc));; => 44\n(ref-history-count r);; => 2","_id":"62bebd9be4b0b1e3652d7611"}],"notes":null,"arglists":["ref"],"doc":"Returns the history count of a ref","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/ref-history-count"},{"added":"1.2","ns":"clojure.core","name":"-","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1351919398000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.core","name":"-'","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d20"},{"created-at":1423527267534,"author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"to-var":{"ns":"clojure.core","name":"unchecked-negate","library-url":"https://github.com/clojure/clojure"},"_id":"54d94d63e4b0e2ac61831d44"},{"created-at":1423527580571,"author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"to-var":{"ns":"clojure.core","name":"unchecked-subtract","library-url":"https://github.com/clojure/clojure"},"_id":"54d94e9ce4b081e022073c85"},{"created-at":1525302779122,"author":{"login":"NealEhardt","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/1338977?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"dec","ns":"clojure.core"},"_id":"5aea45fbe4b045c27b7fac5c"}],"line":1045,"examples":[{"author":{"login":"MrHus","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/22608?v=4"},"editors":[{"avatar-url":"https://avatars2.githubusercontent.com/u/22608?v=4","account-source":"github","login":"MrHus"},{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":"user=> (- 1)\n-1 \nuser=> (- 6 3) \n3\nuser=> (- 10 3 2) \n5","created-at":1279418306000,"updated-at":1332950680000,"_id":"542692c8c026201cdc326a4f"},{"body":"\n(- 0 9000000000000000000 1000000000000000000)\n;; ArithmeticException: integer overflow\n\n(-' 0 9000000000000000000 1000000000000000000)\n;;=> 10000000000000000000N \n\n\n","author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"},"created-at":1412882447241,"updated-at":1412882447241,"_id":"5436e00fe4b0ae7956031579"}],"notes":null,"arglists":["x","x y","x y & more"],"doc":"If no ys are supplied, returns the negation of x, else subtracts\n the ys from x and returns the result. Does not auto-promote\n longs, will throw on overflow. See also: -'","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/-"},{"added":"1.1","ns":"clojure.core","name":"assoc!","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1324959540000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"dissoc!","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521a8d"},{"created-at":1324959556000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"transient","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521a8e"},{"to-var":{"library-url":"https://github.com/clojure/clojure","name":"conj!","ns":"clojure.core"},"author":{"avatar-url":"https://avatars.githubusercontent.com/u/1453?v=4","account-source":"github","login":"ghoseb"},"created-at":1327875049000,"_id":"542692eaf6e94c6970521a8f"},{"created-at":1417201150839,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.core","name":"pop!","library-url":"https://github.com/clojure/clojure"},"_id":"5478c5fee4b03d20a10242b6"},{"created-at":1417201158048,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.core","name":"disj!","library-url":"https://github.com/clojure/clojure"},"_id":"5478c606e4b03d20a10242b7"},{"created-at":1417201185853,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.core","name":"persistent!","library-url":"https://github.com/clojure/clojure"},"_id":"5478c621e4b0dc573b892fe2"}],"line":3394,"examples":[{"author":{"login":"yasuto","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cacfb7ecf08cb6461767e514c93b7bf9?r=PG&default=identicon"},"editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/1453?v=4","account-source":"github","login":"ghoseb"},{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":";; The key concept to understand here is that transients are \n;; not meant to be `bashed in place`; always use the value \n;; returned by either assoc! or other functions that operate\n;; on transients.\n\n(defn merge2\n \"An example implementation of `merge` using transients.\"\n [x y]\n (persistent! (reduce\n (fn [res [k v]] (assoc! res k v))\n (transient x)\n y)))\n\n;; Why always use the return value, and not the original? Because the return\n;; value might be a different object than the original. The implementation\n;; of Clojure transients in some cases changes the internal representation\n;; of a transient collection (e.g. when it reaches a certain size). In such\n;; cases, if you continue to try modifying the original object, the results\n;; will be incorrect. See one example for conj! that contains a detailed\n;; example of a wrong result that can occur if you do not use its return value.\n\n;; Think of transients like persistent collections in how you write code to\n;; update them, except unlike persistent collections, the original collection\n;; you passed in should be treated as having an undefined value. Only the return\n;; value is predictable.","created-at":1307739385000,"updated-at":1577916047949,"_id":"542692c8c026201cdc326a21"},{"updated-at":1482997682425,"created-at":1482997682425,"author":{"login":"dalzony","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/562341?v=3"},"body":"(def m (assoc! (transient {}) :x 1 :y 2))\n\n(:x m)\n;; 1\n\n(:y m)\n;; 2\n\n(count m)\n;; 2","_id":"5864bfb2e4b0fd5fb1cc9649"}],"notes":null,"arglists":["coll key val","coll key val & kvs"],"doc":"When applied to a transient map, adds mapping of key(s) to\n val(s). When applied to a transient vector, sets the val at index.\n Note - index must be <= (count vector). Returns coll.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/assoc!"},{"added":"1.0","ns":"clojure.core","name":"hash-set","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1471555426806,"author":{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/94482?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"sorted-set","ns":"clojure.core"},"_id":"57b62762e4b0b5e6d7a4fa5a"},{"created-at":1532623831801,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"set","ns":"clojure.core"},"_id":"5b59fbd7e4b00ac801ed9e2d"}],"line":391,"examples":[{"author":{"login":"zmila","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/68dd6f50915854aa04fefcf4d6fa5c8e?r=PG&default=identicon"},"editors":[{"login":"rafael","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/7adbf4434f63cedd463196b652fa7a44?r=PG&default=identicon"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"clojureking","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/92625b8a6be91bb8c688d0d07b4e2a32?r=PG&default=identicon"},{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"},{"avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"}],"body":";; Any duplicates are squashed (no error)\n(hash-set 1 2 1 3 1 4 1 5)\n;;=> #{1 4 3 2 5}\n\n;; There is an equivalent reader macro '#{...}'\n(= (hash-set :c :a :b) #{:b :a :c})\n;;=> true \n\n;; A string can be treated as a sequence to produce\n;; a set of the characters found in the string.\n(apply hash-set (seq \"Lorem ipsum dolor sit amet\"))\n;;=> #{\\space \\a \\d \\e \\i \\L \\l \\m \\o \\p \\r \\s \\t \\u}\n\n;; or simply (see \"set\")\n(set \"Lorem ipsum dolor sit amet\")\n;;=> #{\\space \\a \\d \\e \\i \\L \\l \\m \\o \\p \\r \\s \\t \\u}","created-at":1280503618000,"updated-at":1532623811799,"_id":"542692c6c026201cdc326931"},{"updated-at":1643941642045,"created-at":1643941642045,"author":{"login":"jlb0170","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/4674635?v=4"},"body":";; The \"equivalent\" reader macro throws an error when receiving duplicates, however:\n#{ 1 2 1 }\n;;=> Duplicate key: 1","_id":"61fc8f0ae4b0b1e3652d75a7"}],"notes":null,"arglists":["","& keys"],"doc":"Returns a new hash set with supplied keys. Any equal keys are\n handled as if by repeated uses of conj.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/hash-set"},{"added":"1.4","ns":"clojure.core","name":"reduce-kv","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1413271598814,"author":{"login":"viksit","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/198669?v=2"},"to-var":{"ns":"clojure.core","name":"reduce","library-url":"https://github.com/clojure/clojure"},"_id":"543cd02ee4b0a3cf052fe475"},{"created-at":1423043757434,"author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"to-var":{"ns":"clojure.core","name":"reduced","library-url":"https://github.com/clojure/clojure"},"_id":"54d1ecade4b081e022073c58"}],"line":6989,"examples":[{"body":"Let's assume you want to apply a function to a vector of maps,\n\nInput: [{:a 1 :b 2} {:a 3 :b 4}]\n\nsuch that all vals are incremented by 1.\n\nResult: [{:a 2 :b 3} {:a 4 :b 5}]\n\nAn easy way to do so is using reduce-kv,\n\n(def vector-of-maps [{:a 1 :b 2} {:a 3 :b 4}])\n\n(defn update-map [m f] \n (reduce-kv (fn [m k v] \n (assoc m k (f v))) {} m))\n\n(map #(update-map % inc) vector-of-maps)\n\n=> ({:b 3, :a 2} {:b 5, :a 4})","author":{"login":"viksit","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/198669?v=2"},"created-at":1413271555020,"updated-at":1413271555020,"_id":"543cd003e4b02688d208b1b4"},{"body":";; Swap keys and values in a map\nuser=> (reduce-kv #(assoc %1 %3 %2) {} {:a 1 :b 2 :c 3})\n{1 :a, 2 :b, 3 :c}","author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"created-at":1423043718645,"updated-at":1423043718645,"_id":"54d1ec86e4b0e2ac61831d0f"},{"updated-at":1445117098242,"created-at":1445117098242,"author":{"login":"Luckvery","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1178168?v=3"},"body":";; Swap keys with values, only if values are not empty,\n;; while turning values into proper keys\n\n(def someMap { :foo \"food\", :bar \"barista\", :baz \"bazaar\"})\n\n(defn swap [someMap]\n (reduce-kv (fn [m k v]\n (if (empty? v) m (assoc m (keyword v) (name k)))) {} someMap))\n\n(swap someMap)\n\n=> {:food \"foo\", :barista \"bar\", :bazaar \"baz\"}\n","_id":"5622bcaae4b04b157a6648d6"},{"editors":[{"login":"bpetri","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8858685?v=3"}],"body":";; Calculate total wins and winning streaks\n(def all-games \n [{:game 1 :won true} \n {:game 2 :won false} \n {:game 3 :won true} \n {:game 4 :won true}])\n\n(reduce-kv\n (fn [result index game]\n (let [last-game (last result)\n wins (if (:won game) \n (inc (:total last-game 0)) \n (:total last-game))\n streak (if (:won game) \n (inc (:streak last-game 0)) \n 0)]\n (println (assoc game :total wins :streak streak))\n (conj result (assoc game :total wins :streak streak))))\n []\n all-games)\n\n;; Output\n;; {:game 1, :won true, :total 1, :streak 1}\n;; {:game 2, :won false, :total 1, :streak 0}\n;; {:game 3, :won true, :total 2, :streak 1}\n;; {:game 4, :won true, :total 3, :streak 2}\n\n;; [{:game 1, :won true, :total 1, :streak 1} {:game 2, :won false, :total 1, :streak 0} {:game 3, :won true, :total 2, :streak 1} {:game 4, :won true, :total 3, :streak 2}]","author":{"avatar-url":"https://avatars.githubusercontent.com/u/140163?v=3","account-source":"github","login":"puppybits"},"created-at":1446938119194,"updated-at":1461160135892,"_id":"563e8607e4b0290a56055d1f"},{"editors":[{"login":"jvanderhyde","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/6516608?v=3"}],"body":";; You can define map-kv using reduce-kv, \n;; to do something to every value in a map.\n\n(defn map-kv [f coll]\n (reduce-kv (fn [m k v] (assoc m k (f v))) (empty coll) coll))\n\n(map-kv inc {:a 12, :b 19, :c 2})\n;;=> {:c 3, :b 20, :a 13}\n\n;; It works on vectors, too.\n(map-kv inc [1 1 2 3 5])\n;;=> [2 2 3 4 6]","author":{"avatar-url":"https://avatars.githubusercontent.com/u/6516608?v=3","account-source":"github","login":"jvanderhyde"},"created-at":1473374682272,"updated-at":1473374856199,"_id":"57d1e9dae4b0709b524f04eb"},{"updated-at":1486417959138,"created-at":1486417959138,"author":{"login":"overset","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/34342?v=3"},"body":";; It works with indexes on vectors as well\n\n(reduce-kv (fn [res idx itm] (assoc res idx itm)) {} [\"one\" \"two\" \"three\"])\n\n;;=> {2 \"three\", 1 \"two\", 0 \"one\"}","_id":"5898f027e4b01f4add58fe3c"},{"updated-at":1486833406498,"created-at":1486833406498,"author":{"login":"bsifou","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8908139?v=3"},"body":"\n(defn update-map-entries[m e]\n (reduce-kv (fn [r k v] (assoc r k v)) m e))\n\n;;user=> (update-map-entries {:a 1 :b 2 :c 3} {:a 5 :b 9})\n;;{:a 5, :b 9, :c 3}\n;;user=> (update-map-entries {:a 1 :b 2 :c 3} {:a 5 :b 9 :d 8})\n;;{:a 5, :b 9, :c 3, :d 8}\n\n\n","_id":"589f46fee4b01f4add58fe4b"},{"updated-at":1596611537211,"created-at":1596611537211,"author":{"login":"themustafabasit","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/24441401?v=4"},"body":";; increment map values \n(def abc-map {:a 1\n :b 2\n :c 3})\n(seq abc-map)\n;; => ([:a 1] [:b 2] [:c 3])\n\n;; via reduce \n(reduce (fn [new-map [k v]]\n (assoc new-map k (inc v)))\n {}\n abc-map)\n;; => {:a 2, :b 3, :c 4}\n\n\n;; via reduce-kv\n(reduce-kv (fn [new-map k v]\n (assoc new-map k (inc v)))\n {}\n abc-map)\n;; => {:a 2, :b 3, :c 4}\n","_id":"5f2a5bd1e4b0b1e3652d7372"},{"updated-at":1602494138585,"created-at":1602494138585,"author":{"login":"cdol","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/47477903?v=4"},"body":";; filter a coll of maps with arbitrary # of preds\n\n;; setup coll\n(def people '(\t{:gender \"male\", :age-group \"child\", :origin \"Germany\", :prename \"Hans\"}\n\t\t{:gender \"male\", :age-group \"adult\", :origin \"France\", :prename \"Jacques\"}\n\t\t{:gender \"male\", :age-group \"senior\", :origin \"Estonia\", :prename \"Rasmus\"}\n\t\t{:gender \"male\", :age-group \"adult\", :origin \"Poland\", :prename \"Jakub\"}\n\t\t{:gender \"male\", :age-group \"senior\", :origin \"Germany\", :prename \"Uwe\"}\n\t\t{:gender \"female\", :age-group \"adult\", :origin \"France\", :prename \"Amélie\"}\n\t\t{:gender \"female\", :age-group \"child\", :origin \"Estonia\", :prename \"Sofia\"}\n\t\t{:gender \"female\", :age-group \"child\", :origin \"Germany\", :prename \"Emma\"}\n\t\t{:gender \"female\", :age-group \"child\", :origin \"Estonia\", :prename \"Alisa\"}\n\t\t{:gender \"female\", :age-group \"senior\", :origin \"Poland\", :prename \"Anna\"}))\n\n;; select elements using reduce-kv & filter\n(defn multi-pred [coll m] \n (reduce-kv \n (fn [erg k v] (filter #(= v (k %)) erg)) coll m) )\n\n;; two \"preds\"\n(multi-pred people {:gender \"male\", :age-group \"senior\"})\n;; => ({:gender \"male\", :age-group \"senior\", :origin \"Estonia\", :prename \"Rasmus\"} {:gender \"male\", :age-group \"senior\", :origin \"Germany\", :prename \"Uwe\"})\n\n;; three \"preds\"\n(multi-pred people {:gender \"female\", :age-group \"child\", :origin \"Estonia\"})\n;; => ({:gender \"female\", :age-group \"child\", :origin \"Estonia\", :prename \"Sofia\"} {:gender \"female\", :age-group \"child\", :origin \"Estonia\", :prename \"Alisa\"})","_id":"5f841ebae4b0b1e3652d73d6"},{"updated-at":1639378520202,"created-at":1639378520202,"author":{"login":"cloudbuck3t","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/90472507?v=4"},"body":";; an example to show how to add a new key to nested maps.\n\n;; consider a map with submaps\n{:a {:b 1} :c {:d 2} :e {:f 3}}\n\n\n;; reduce-kv keeps an accumulator that \n;; starts with the value provided in init, \n;; in this case an empty map.\n\n\n;; you can return the original collection via reduce-kv this way\n(reduce-kv\n (fn [acc k v]\n (assoc acc k v))\n {}\n {:a {:b 1} :c {:d 2} :e {:f 3}}))\n\n;; the output is identical to the input.\n=> {:a {:b 1} :c {:d 2} :e {:f 3}}\n\n;; you can insert a new key-value pair into each submap \n;; by using this instead, generalized as a function\n;; that takes a map and a new-key and its new-key-value as inputs:\n\n(defn add-submap [m new-key new-keys-value]\n (reduce-kv\n (fn [acc k v]\n (assoc acc k (assoc v new-key new-keys-value)))\n {}\n m))\n\n;; notice how the value \"v\" of the key \"k\" is actually the submap on each key,\n;; when we visit :a we are looking at the first k-v pair,\n;; the key is :a, \n;; and the value is {:b 1}\n;; \n;; so we assoc a new key into that submap (the value) \n;; for each key-and-submap pairing.\n\n;; so when you run this function \n=> (add-submap {:a {:b 1} \n :c {:d 2} \n :e {:f 3}} :email-verified nil)\n\n;; the result is the original data with the new key and its val in each submap.\n=> {:a {:b 1, :email-verified nil}, \n :c {:d 2, :email-verified nil}, \n :e {:f 3, :email-verified nil}}","_id":"61b6ee58e4b0b1e3652d7588"}],"notes":[{"author":{"login":"KingMob","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/946421?v=4"},"updated-at":1610241088036,"created-at":1610241088036,"body":"Currently broken for subvectors: [CLJ-2065](https://clojure.atlassian.net/browse/CLJ-2065)","_id":"5ffa5440e4b0b1e3652d7428"},{"author":{"login":"diegonayalazo","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/11781279?v=4"},"updated-at":1649396094971,"created-at":1649396032294,"body":"Seems to be fixed for subvectors as of release 1.11. https://clojure.atlassian.net/browse/CLJ-2065","_id":"624fc940e4b0b1e3652d75cd"}],"arglists":["f init coll"],"doc":"Reduces an associative collection. f should be a function of 3\n arguments. Returns the result of applying f to init, the first key\n and the first value in coll, then applying f to that result and the\n 2nd key and value, etc. If coll contains no entries, returns init\n and f is not called. Note that reduce-kv is supported on vectors,\n where the keys will be the ordinals.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/reduce-kv"},{"added":"1.0","ns":"clojure.core","name":"or","file":"clojure/core.clj","type":"macro","column":1,"see-alsos":[{"created-at":1300530940000,"author":{"login":"j1n3l0","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/6db7c6ecdbe97a1e844c88ecf587f61f?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"and","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c42"},{"created-at":1334293978000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.core","name":"if","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c43"},{"created-at":1582756022836,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"some-fn","ns":"clojure.core"},"_id":"5e56f0b6e4b087629b5a18ad"}],"line":856,"examples":[{"author":{"login":"dakrone","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bcacd00a7f05c4772329cf9f446c7987?r=PG&default=identicon"},"editors":[{"login":"purplejacket","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/214093?v=3"}],"body":"user> (or true false false)\ntrue\n\nuser> (or true true true)\ntrue\n\nuser> (or false false false)\nfalse\n\nuser> (or nil nil)\nnil\n\nuser> (or false nil)\nnil\n\nuser> (or true nil)\ntrue\n\n;; or doesn't evaluate if the first value is true\nuser> (or true (println \"foo\"))\ntrue\n\n;; order matters\nuser> (or (println \"foo\") true)\nfoo\ntrue\n\n;; does not coerce a given value to a boolean true, returns the value\nuser> (or false 42)\n42\n\nuser> (or false 42 9999)\n42\n\nuser> (or 42 9999)\n42","created-at":1293673853000,"updated-at":1429754329073,"_id":"542692cbc026201cdc326bc3"},{"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"editors":[],"body":";; See examples for \"if\" explaining Clojure's idea of logical true\n;; and logical false.","created-at":1334293981000,"updated-at":1334293981000,"_id":"542692d4c026201cdc327022"},{"updated-at":1454687827177,"created-at":1454687827177,"author":{"login":"ertugrulcetin","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8271291?v=3"},"body":";;evaluates last expression for this case\nuser> (or nil false)\nfalse\n\nuser> (or false nil)\nnil","_id":"56b4c653e4b060004fc217bc"},{"updated-at":1581256939913,"created-at":1581256939913,"author":{"login":"caumond","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/11491686?v=4"},"body":";; Defaulted value\nuser> (or nil \"crazy default value\")\ncrazy default value\n\nuser> (or \"value\" \"not useful default value\")\nvalue","_id":"5e4010ebe4b0ca44402ef82d"},{"updated-at":1596145782717,"created-at":1596145383310,"author":{"login":"luiszambon","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/41161270?v=4"},"body":";; It cares about function's return. Example:\n;; println returns 'nil', so the next param will be evaluated.\n(or (println \"Clojure\") true \"Code\" false)\nClojure\n;;=>true\n","editors":[{"avatar-url":"https://avatars0.githubusercontent.com/u/41161270?v=4","account-source":"github","login":"luiszambon"}],"_id":"5f233ee7e4b0b1e3652d732b"},{"editors":[{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"}],"body":";; `or` is a macro, so can't be given where a fn is expected\n(map or [true false] [false false])\n;; => Syntax error compiling at…\n;; => Can't take value of a macro: #'clojure.core/or\n\n;; wrap in a fn instead\n(map #(or %1 %2) [true false] [false false])\n;; => (true false)","author":{"avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4","account-source":"github","login":"tomdl89"},"created-at":1658141645967,"updated-at":1682634667591,"_id":"62d53bcde4b0b1e3652d7627"}],"macro":true,"notes":null,"arglists":["","x","x & next"],"doc":"Evaluates exprs one at a time, from left to right. If a form\n returns a logical true value, or returns that value and doesn't\n evaluate any of the other expressions, otherwise it returns the\n value of the last expression. (or) returns nil.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/or"},{"added":"1.0","ns":"clojure.core","name":"cast","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1434488356659,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"},"to-var":{"ns":"clojure.core","name":"type","library-url":"https://github.com/clojure/clojure"},"_id":"55808e24e4b01ad59b65f4fe"}],"line":348,"examples":[{"updated-at":1463934422291,"created-at":1289541716000,"body":";; Cast doesn't change the type of the input - it just throws an exception if it's the wrong type\n;; Since Long is a subclass of Number\nuser=> (cast Number 1) \n1\nuser=> (type (cast Number 1))\njava.lang.Long\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3","account-source":"github","login":"phreed"},{"login":"tirkarthi","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/3972343?v=3"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/bc41ebab54cc0e0fbe99d753876d45ce?r=PG&default=identicon","account-source":"clojuredocs","login":"Victor"},"_id":"542692cdc026201cdc326ccd"}],"notes":null,"arglists":["c x"],"doc":"Throws a ClassCastException if x is not a c, else returns x.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/cast"},{"added":"1.0","ns":"clojure.core","name":"reset!","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1324098243000,"author":{"login":"TimMc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5d532e51427ef2f4ded31aaca16c8baf?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"swap!","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ee4"},{"created-at":1360265917000,"author":{"login":"AtKaaZ","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e10dfa345f44b0fe72bbe081fd51b83?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"compare-and-set!","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ee5"},{"created-at":1360265926000,"author":{"login":"AtKaaZ","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e10dfa345f44b0fe72bbe081fd51b83?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"atom","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ee6"},{"created-at":1527705044232,"author":{"login":"agarman","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/138454?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"swap-vals!","ns":"clojure.core"},"_id":"5b0eedd4e4b045c27b7fac7e"},{"created-at":1527705380123,"author":{"login":"agarman","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/138454?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"reset-vals!","ns":"clojure.core"},"_id":"5b0eef24e4b045c27b7fac85"}],"line":2393,"examples":[{"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"editors":[{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":"user=> (def x (atom 10))\n#'user/x\n\nuser=> @x\n10\n\nuser=> (reset! x 20)\n20\n\nuser=> @x\n20","created-at":1281850260000,"updated-at":1416077324639,"_id":"542692ccc026201cdc326cb0"}],"notes":null,"arglists":["atom newval"],"doc":"Sets the value of atom to newval without regard for the\n current value. Returns newval.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/reset!"},{"added":"1.0","ns":"clojure.core","name":"name","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1385200415000,"author":{"login":"abrooks","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/69976?v=2"},"to-var":{"ns":"clojure.core","name":"namespace","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ca3"}],"line":1604,"examples":[{"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"login":"rafmagana","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/92894?v=3"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"},{"login":"egracer","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/4086884?v=3"}],"body":";; the name of the keyword is without the ':'\n;; \"str\" will retain the ':'.\n(name :x)\n;;=> \"x\"\n\n(name \"x\")\n;;=> \"x\"\n\n;; returns the symbol name as a string without the namespace.\n(name 'x)\n;;=> \"x\"\n\n(name 'user/x)\n;;=> \"x\"\n\n;; throws an error for invalid types, no nil punning\n(name nil)\n;;=> Error: Doesn't support name:\n\n(name 2)\n;;=> Error: Doesn't support name: 2","created-at":1280319438000,"updated-at":1455058375466,"_id":"542692cbc026201cdc326b9a"},{"updated-at":1548517573974,"created-at":1467226948210,"author":{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/94482?v=3"},"body":";; Note that for namespaced keywords, `name` only returns the name part.\n(name :my-ns/my-name)\n;;=> \"my-name\"\n\n(name :ns/deep/key)\n;;=> \"deep/key\"\n;; For more info see: `keyword` and `keyword?`...\n(name :'//-,)\n;;=> \"/-\"\n(name :/)\n;;=> \"/\"\n(name ://)\n;;=> RuntimeException Invalid token: :// clojure.lang.Util.runtimeException (Util.java:221)\n;;=> RuntimeException Unmatched delimiter: ) clojure.lang.Util.runtimeException (Util.java:221)\n(name :///)\n;;=> \"//\"\n(namespace :///)\n;;=> \"\"\n\n;; If you want the namespace part, you can use (namespace):\n(namespace :my-ns/my-key)\n;;=> \"my-ns\"\n\n;; Using (str) will give you both parts, but also includes the leading colon.\n(str :my-ns/my-key)\n;;=> \":my-ns/my-key\"","editors":[{"avatar-url":"https://avatars0.githubusercontent.com/u/36645452?v=4","account-source":"github","login":"cljlc"}],"_id":"57741b44e4b0bafd3e2a0499"},{"updated-at":1548513828805,"created-at":1478905733257,"author":{"login":"souenzzo","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/3241703?v=3"},"body":";; To get full key\n(defn keyname [key] (str (namespace key) \"/\" (name key)))\n\n(keyname :ns/key)\n=> \"ns/key\"\n\n(keyname :ns/deep/key)\n=> \"ns/deep/key\"\n\n;; Just for fun\n(string/replace :key/val #\"^:\" \"\")\n=> \"key/val\"","editors":[{"avatar-url":"https://avatars0.githubusercontent.com/u/36645452?v=4","account-source":"github","login":"cljlc"}],"_id":"58264f85e4b0782b632278bf"},{"updated-at":1548517913344,"created-at":1548517913344,"author":{"login":"cljlc","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/36645452?v=4"},"body":";; `name` (and `namespace`) \"knows\" how a keyword was built:\n\n(name (keyword \"a/b\" \"c\"))\n;;=> \"c\"\n\n(name (keyword \"a\" \"b/c\"))\n;;=> \"b/c\"\n","_id":"5c4c8219e4b0ca44402ef636"},{"editors":[{"login":"green-coder","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/598193?v=4"}],"body":";; To get the fully qualified name of the keyword, we can use symbol.\n\n(str (symbol :a/b))\n;;=> \"a/b\"\n","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/598193?v=4","account-source":"github","login":"green-coder"},"created-at":1577551007249,"updated-at":1577551119811,"_id":"5e07849fe4b0ca44402ef7ff"},{"updated-at":1635440614807,"created-at":1635440614807,"author":{"login":"naxels","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/3195443?v=4"},"body":"; Preserves capitals\n\n(name :pageQuery)\n; => \"pageQuery\"","_id":"617ad7e6e4b0b1e3652d7560"}],"notes":null,"tag":"java.lang.String","arglists":["x"],"doc":"Returns the name String of a string, symbol or keyword.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/name"},{"added":"1.0","ns":"clojure.core","name":"ffirst","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1343067219000,"author":{"login":"john.r.woodward","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/22b6fbc4a386291e45b1cb4449377086?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"first","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521a7f"},{"created-at":1348637462000,"author":{"login":"dansalmo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e33ee460f5f61bc5ba9b598934766215?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"fnext","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521a80"},{"created-at":1348637521000,"author":{"login":"dansalmo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e33ee460f5f61bc5ba9b598934766215?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"nfirst","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521a81"},{"created-at":1482183756311,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"nnext","ns":"clojure.core"},"_id":"5858544ce4b004d3a355e2bf"},{"created-at":1482183947394,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"next","ns":"clojure.core"},"_id":"5858550be4b004d3a355e2c2"}],"line":100,"examples":[{"author":{"login":"zmila","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/68dd6f50915854aa04fefcf4d6fa5c8e?r=PG&default=identicon"},"editors":[{"login":"zmila","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/68dd6f50915854aa04fefcf4d6fa5c8e?r=PG&default=identicon"},{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":"user=> (ffirst '([]))\nnil \n\nuser=> (ffirst ['(a b c) '(b a c)])\na \n\nuser=> (ffirst '([a b c] [b a c]))\na","created-at":1280345631000,"updated-at":1332951869000,"_id":"542692cbc026201cdc326bba"},{"author":{"login":"zmila","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/68dd6f50915854aa04fefcf4d6fa5c8e?r=PG&default=identicon"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":"user=> (first {:b 2 :a 1 :c 3})\n[:b 2] \n\nuser=> (ffirst {:b 2 :a 1 :c 3})\n:b","created-at":1280345657000,"updated-at":1332951883000,"_id":"542692cbc026201cdc326bbd"},{"body":"user=> (first [1])\n1\n\nuser=> (ffirst [[1]])\n1","author":{"login":"divyashravanthi","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/6253335?v=3"},"created-at":1432113125180,"updated-at":1432113125180,"_id":"555c4fe5e4b03e2132e7d163"}],"notes":null,"arglists":["x"],"doc":"Same as (first (first x))","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/ffirst"},{"added":"1.0","ns":"clojure.core","name":"sorted-set","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1317095643000,"author":{"login":"pauldoo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5cb916d3c8abc9f45a093209e72489fb?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"sorted-set-by","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c6b"},{"created-at":1330671694000,"author":{"login":"Chouser","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/7a0192050ed6488670acfd3f59405c10?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"subseq","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c6c"},{"created-at":1330671698000,"author":{"login":"Chouser","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/7a0192050ed6488670acfd3f59405c10?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"rsubseq","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c6d"},{"created-at":1330671734000,"author":{"login":"Chouser","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/7a0192050ed6488670acfd3f59405c10?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"sorted-map","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c6e"},{"created-at":1419807368932,"author":{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=3"},"to-var":{"ns":"clojure.core","name":"into","library-url":"https://github.com/clojure/clojure"},"_id":"54a08a88e4b09260f767ca80"},{"created-at":1423277153400,"author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"to-var":{"ns":"clojure.core","name":"hash-set","library-url":"https://github.com/clojure/clojure"},"_id":"54d57c61e4b0e2ac61831d1f"},{"created-at":1548553242467,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/109629?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"compare","ns":"clojure.core"},"_id":"5c4d0c1ae4b0ca44402ef646"}],"line":419,"examples":[{"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=3"},{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"}],"body":"user=> (sorted-set 3 2 1)\n#{1 2 3}\n\nuser=> (sorted-set 3 2 1 1)\n#{1 2 3}\n\nuser=> #{2 1 3}\n#{1 3 2}\n\nuser=> (apply sorted-set #{2 1 3})\n#{1 2 3}","created-at":1280319522000,"updated-at":1423277124415,"_id":"542692cfc026201cdc326e6f"},{"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/109629?v=4"}],"body":"(sorted-set :a \"A\" 1)\n\n;;Exception\n;;unable to implement java.lang.String.compareTo\n\n;; This exception occurs because the default comparator, a Clojure function\n;; named `compare`, throws an exception when asked to compare two values of\n;; very dissimilar tpyes, like a keyword and a string, or a keyword and a number.\n;; If you really want a sorted set containing such dissimilar types, you will\n;; need to create your own custom comparator and use sorted-set-by.\n;; See this article for advice on creating custom comparators:\n;; https://clojure.org/guides/comparators","author":{"avatar-url":"https://avatars0.githubusercontent.com/u/31028993?v=4","account-source":"github","login":"ibercode"},"created-at":1518777459431,"updated-at":1548624108584,"_id":"5a86b473e4b0316c0f44f8c5"},{"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/109629?v=4"}],"body":";; (sorted-set ...) is equivalent in behavior to (sorted-set-by compare ...)\n;; where compare is Clojure's default comparator function clojure.core/compare\n;; See the documentation of compare for more details on its behavior.\n\n;; For a set sorted by the order that elements were added,\n;; see ordered-set: https://github.com/clj-commons/ordered\n\n;; If you deal with many large sets of integers, and want a more memory-efficient\n;; data structure for those, see int-set and dense-int-set:\n;; https://github.com/clojure/data.int-map","author":{"avatar-url":"https://avatars2.githubusercontent.com/u/109629?v=4","account-source":"github","login":"jafingerhut"},"created-at":1548553235377,"updated-at":1548618903382,"_id":"5c4d0c13e4b0ca44402ef645"}],"notes":null,"arglists":["& keys"],"doc":"Returns a new sorted set with supplied keys. Any equal keys are\n handled as if by repeated uses of conj.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/sorted-set"},{"added":"1.0","ns":"clojure.core","name":"counted?","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1495640676349,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"bounded-count","ns":"clojure.core"},"_id":"5925aa64e4b093ada4d4d72c"}],"line":6318,"examples":[{"author":{"login":"dakrone","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bcacd00a7f05c4772329cf9f446c7987?r=PG&default=identicon"},"editors":[],"body":"user=> (counted? [:a :b :c])\ntrue\n\nuser=> (counted? '(:a :b :c))\ntrue\n\nuser=> (counted? {:a 1 :b 2 :c 3})\ntrue\n\nuser=> (counted? #{:a :b :c})\ntrue\n\nuser=> (counted? \"asdf\")\nfalse\n\nuser=> (counted? (into-array Integer/TYPE [1 2 3]))\nfalse","created-at":1286508818000,"updated-at":1286508818000,"_id":"542692cac026201cdc326b0c"},{"updated-at":1467307667667,"created-at":1467307667667,"author":{"login":"miner","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/25400?v=3"},"body":";; Lazy sequences are not counted?\n(counted? (map inc (range 5)))\n;;=> false","_id":"57755693e4b0bafd3e2a049c"}],"notes":null,"arglists":["coll"],"doc":"Returns true if coll implements count in constant time","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/counted_q"},{"added":"1.1","ns":"clojure.core","name":"byte-array","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1451898302123,"author":{"login":"muhuk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/40178?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"bytes","ns":"clojure.core"},"_id":"568a35bee4b0f37b65a3c27d"},{"created-at":1455883026411,"author":{"login":"guruma","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/534540?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"byte","ns":"clojure.core"},"_id":"56c70312e4b0b41f39d96ccc"}],"line":5346,"examples":[{"author":{"login":"shockbob","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon"},"editors":[{"login":"shockbob","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon"}],"body":";; create an array of bytes\n;; and demonstrate that you can use it in the standard Java fill function\n;; note the needed byte coercion in the fill function call\n\nuser=> (def bees (byte-array 10))\n#'user/bees\n\nuser=> (for [i (range 10)](aset-byte bees i (* i i)))\n(0 1 4 9 16 25 36 49 64 81)\n\nuser=> (vec bees)\n[0 1 4 9 16 25 36 49 64 81]\n\nuser=> (java.util.Arrays/fill bees (byte 122))\nnil\nuser=> (vec bees)\n[122 122 122 122 122 122 122 122 122 122]\nuser=>","created-at":1313959908000,"updated-at":1313962959000,"_id":"542692cec026201cdc326d67"},{"editors":[{"login":"guruma","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/534540?v=3"}],"body":";; copied from the example in clojure.core/byte\nuser=> (def x (byte-array [(byte 0x43) \n (byte 0x6c)\n (byte 0x6f)\n (byte 0x6a)\n (byte 0x75)\n (byte 0x72)\n (byte 0x65)\n (byte 0x21)]))\n#'user/x\n\nuser=> (String. x)\n\"Clojure!\"","author":{"avatar-url":"https://avatars.githubusercontent.com/u/534540?v=3","account-source":"github","login":"guruma"},"created-at":1455883152605,"updated-at":1455883201637,"_id":"56c70390e4b0b41f39d96ccd"},{"editors":[{"login":"nivekuil","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/4633048?v=4"}],"body":";; NOTE: equality uses identity, not value semantics.\nuser=> (= (byte-array 10) (byte-array 10))\nfalse\nuser=> (java.util.Arrays/equals (byte-array 10) (byte-array 10))\ntrue\n\nuser=> (def a (byte-array [(byte 0x43)]))\n#'user/a\nuser=> (def b (byte-array [(byte 0x43)]))\n#'user/b\nuser=> (= a b)\nfalse\nuser=> (java.util.Arrays/equals a b)\ntrue","author":{"avatar-url":"https://avatars3.githubusercontent.com/u/4633048?v=4","account-source":"github","login":"nivekuil"},"created-at":1606705309670,"updated-at":1606705382806,"_id":"5fc4609de4b0b1e3652d7412"}],"notes":[{"body":"The maximum size of a byte-array is Integer/MAX_VALUE, as arrays are int-indexed in Java. However, it is possible to pass a value that is larger than this, resulting in a cast that will wrap around. This incorrect usage will not give any indication of error.","created-at":1625076336154,"updated-at":1625076620437,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/1780598?v=4","account-source":"github","login":"dspearson"},"_id":"60dcb270e4b0b1e3652d7510"},{"author":{"login":"luposlip","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/763627?v=4"},"updated-at":1631709838369,"created-at":1631709678505,"body":"To type hint a byte array, use this non-obvious syntax:\n\n
    (.write ^OutputStream output-stream ^\"[B\" bytearray)
    ","_id":"6141e9eee4b0b1e3652d753b"},{"author":{"login":"brunchboy","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2228869?v=4"},"updated-at":1731011533745,"created-at":1731011533745,"body":"You can also use `^bytes` to type hint a byte array, and as of Clojure 1.12, `^byte/1` for a one-dimensional byte array, `^byte/2` for two dimensions, etc.","_id":"672d23cd69fbcc0c2261750e"}],"arglists":["size-or-seq","size init-val-or-seq"],"doc":"Creates an array of bytes","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/byte-array"},{"added":"1.11","ns":"clojure.core","name":"parse-double","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1775529746545,"author":{"login":"wlkr","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/5406568?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"parse-long","ns":"clojure.core"},"_id":"69d46f127955605a202df2a1"}],"line":8179,"examples":[{"updated-at":1698255818548,"created-at":1698255818548,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":"(parse-double \"4.2\")\n;; => 4.2\n\n(parse-double \"-4.2e4\")\n;; => -42000.0\n\n(parse-double \"4\")\n;; => 4.0\n\n(parse-double \"NaN\")\n;; => ##NaN\n\n(parse-double \"Infinity\")\n;; => ##Inf\n\n(parse-double \"four\")\n;; => nil\n(parse-double \"\")\n;; => nil","_id":"653953ca69fbcc0c226173db"}],"notes":null,"arglists":["s"],"doc":"Parse string with floating point components and return a Double value,\n or nil if parse fails.\n\n Grammar: https://docs.oracle.com/javase/8/docs/api/java/lang/Double.html#valueOf-java.lang.String-","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/parse-double"},{"added":"1.7","ns":"clojure.core","name":"tagged-literal","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1661550936046,"author":{"login":"djblue","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1986211?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"read-string","ns":"clojure.edn"},"_id":"63094158e4b0b1e3652d7656"},{"created-at":1757184352247,"author":{"login":"daveliepmann","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/974443?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"tagged-literal?","ns":"clojure.core"},"_id":"68bc8160cd84df5de54e2094"}],"line":7963,"examples":[{"updated-at":1661545330654,"created-at":1661545330654,"author":{"login":"Quezion","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1403153?v=4"},"body":"(def x (tagged-literal 'user {:name \"Foo\"}))\n\n(:form x) ;; Get the actual codeform\n;; => {:name \"Foo\"}\n\n(:tag x) ;; Get the tagged symbol\n;; => user","_id":"63092b72e4b0b1e3652d7654"},{"updated-at":1661546360936,"created-at":1661546360936,"author":{"login":"djblue","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1986211?v=4"},"body":"(require '[clojure.edn :as edn])\n(edn/read-string {:default tagged-literal} \"#js [1 2 3]\")\n;; => #js [1 2 3]\n","_id":"63092f78e4b0b1e3652d7655"}],"notes":[{"author":{"login":"miner","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/25400?v=4"},"updated-at":1610656712993,"created-at":1610656712993,"body":"`tagged-literal` is useful as a value fo `clojure.core/*default-data-reader-fn*`","_id":"6000abc8e4b0b1e3652d7431"}],"arglists":["tag form"],"doc":"Construct a data representation of a tagged literal from a\n tag symbol and a form.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/tagged-literal"},{"added":"1.0","ns":"clojure.core","name":"println","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1290672953000,"author":{"login":"dale","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a7a1eca257c6cea943fea41e5cc3e9a3?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"prn","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521ae2"},{"created-at":1302236980000,"author":{"login":"TimMc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5d532e51427ef2f4ded31aaca16c8baf?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"print","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521ae3"},{"created-at":1374264342000,"author":{"login":"lbeschastny","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/416170465e4045f810f09a9300dda4dd?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"println-str","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521ae4"},{"created-at":1518042813319,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"pprint","ns":"clojure.pprint"},"_id":"5a7b7ebde4b0316c0f44f8ac"}],"line":3759,"examples":[{"author":{"login":"devn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3"},"editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3","account-source":"github","login":"devn"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"cloojure","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1ad3de25d00d953de6e8c82f554cdbf5?r=PG&default=identicon"},{"login":"cloojure","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1ad3de25d00d953de6e8c82f554cdbf5?r=PG&default=identicon"},{"login":"cloojure","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1ad3de25d00d953de6e8c82f554cdbf5?r=PG&default=identicon"}],"body":"user=> (println \"Hello world.\")\nHello world.\nnil\n\nuser=> (def items [ \"hello\" :a 1 (list :b 2) \\c {:d 4} #{5 6 7} ])\n#'user/items\n\n; println is for human-readable output, like a report. Note the lack of quotes around the string \"hello\" and the unescaped letter \"c\". \nuser=> (println items)\n[hello :a 1 (:b 2) c {:d 4} #{5 6 7}]\nnil\n\n; prn outputs items in a machine-readable format, such as in a source\n; file. Note the double-quotes around the string \"hello\" and the escaped letter \"c\".\nuser=> (prn items)\n[\"hello\" :a 1 (:b 2) \\c {:d 4} #{5 6 7}]\nnil\n\n; pr-str produces a string with escaped punctuation, so that println yields the same result as the original prn call.\nuser=> (println (pr-str items))\n[\"hello\" :a 1 (:b 2) \\c {:d 4} #{5 6 7}]\nnil\n\n; Calling println w/o args outputs a newline and nothing else.\nuser=> (println)\n\nnil\n; The newline function does the same.\nuser=> (newline)\n\nnil\nuser=>","created-at":1280776981000,"updated-at":1402400141000,"_id":"542692cec026201cdc326d9a"},{"body":"; be careful when using println in functions like map\n; println has nil as its return value\n\nuser=> (map #(println %) (range 1 4))\n\n(1 2 3 nil nil nil)\n\n","author":{"login":"rsachdeva","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/232903?v=2"},"created-at":1413839939176,"updated-at":1413839939176,"_id":"54457c43e4b0dc573b892fa1"}],"notes":null,"arglists":["& more"],"doc":"Same as print followed by (newline)","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/println"},{"added":"1.2","ns":"clojure.core","name":"extend-type","file":"clojure/core_deftype.clj","type":"macro","column":1,"see-alsos":[{"created-at":1336757561000,"author":{"login":"Cosmi","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/10f2eae92de67116fa98d06ec55fcf29?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"extend","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521be8"},{"created-at":1351471424000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"extend-protocol","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521be9"},{"created-at":1351471431000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"defprotocol","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bea"}],"line":848,"examples":[{"author":{"login":"yasuto","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cacfb7ecf08cb6461767e514c93b7bf9?r=PG&default=identicon"},"editors":[],"body":";;; This is a library for the shopping result.\n\n(defrecord Banana [qty])\n\n;;; 'subtotal' differ from each fruit.\n\n(defprotocol Fruit\n (subtotal [item]))\n\n(extend-type Banana\n Fruit\n (subtotal [item]\n (* 158 (:qty item))))\n\n;;; Please see the term of 'reify'.","created-at":1315674061000,"updated-at":1315674061000,"_id":"542692cbc026201cdc326bc2"}],"macro":true,"notes":null,"arglists":["t & specs"],"doc":"A macro that expands into an extend call. Useful when you are\n supplying the definitions explicitly inline, extend-type\n automatically creates the maps required by extend. Propagates the\n class as a type hint on the first argument of all fns.\n\n (extend-type MyType \n Countable\n (cnt [c] ...)\n Foo\n (bar [x y] ...)\n (baz ([x] ...) ([x y & zs] ...)))\n\n expands into:\n\n (extend MyType\n Countable\n {:cnt (fn [c] ...)}\n Foo\n {:baz (fn ([x] ...) ([x y & zs] ...))\n :bar (fn [x y] ...)})","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/extend-type"},{"added":"1.0","ns":"clojure.core","name":"macroexpand-1","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1284957759000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"macroexpand","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b13"},{"created-at":1289586228000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.walk","name":"macroexpand-all","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b14"}],"line":4044,"examples":[{"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"editors":[],"body":"user=> (macroexpand-1 '(defstruct mystruct[a b]))\n(def mystruct (clojure.core/create-struct [a b]))\n","created-at":1286272779000,"updated-at":1286272779000,"_id":"542692cbc026201cdc326ba7"},{"updated-at":1339248839000,"created-at":1339248839000,"body":"user=> (macroexpand-1 '(-> c (+ 3) (* 2)))\n(clojure.core/-> (clojure.core/-> c (+ 3)) (* 2))","editors":[],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},"_id":"542692d4c026201cdc326ffa"},{"editors":[{"login":"lourkeur","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/15657735?v=4"}],"body":"; When testing macro expansion in a file instead of at the REPL, \n; please note that it may be necessary to use a backquote\n; instead of a straight quote.\n\n(defmacro iiinc [x]\n `(+ 3 ~x))\n\n(deftest t-stuff\n ; This doesn't work.\n (println (macroexpand-1 '(iiinc 2))) ;=> (iiinc 2)\n\n ; Oddly, we can use the macro itself fine in our tests...\n (println (iiinc 2)) ;=> 5\n (is (= 5 (iiinc 2))) ;=> unit test passes\n\n ; This fixes it by resolving the symbol iiinc at compile-time.\n (println (macroexpand-1 `(iiinc 2)))) ;=> (+ 3 2)\n\n; Also, as the previous examples show, please remember that \n; you must quote the form you are providing to `macroexpand-1`.\n","author":{"avatar-url":"https://avatars3.githubusercontent.com/u/7083783?v=3","account-source":"github","login":"cloojure"},"created-at":1494031935843,"updated-at":1522520280321,"_id":"590d1e3fe4b01f4add58feaf"}],"notes":null,"arglists":["form"],"doc":"If form represents a macro form, returns its expansion,\n else returns form.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/macroexpand-1"},{"added":"1.0","ns":"clojure.core","name":"assoc-in","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1291975376000,"author":{"login":"alimoeeny","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e8dd06976ead4082d2181f3807117e1?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"assoc","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521ac6"},{"created-at":1302248543000,"author":{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},"to-var":{"ns":"clojure.core","name":"update-in","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521ac7"},{"created-at":1318010528000,"author":{"login":"jks","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/de50bee3396570d25f900873303c98f1?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"get-in","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521ac9"},{"created-at":1570520711353,"author":{"login":"xmo-odoo","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/7571158?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"associative?","ns":"clojure.core"},"_id":"5d9c3e87e4b0ca44402ef7ca"}],"line":6224,"examples":[{"author":{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":"(def users [{:name \"James\" :age 26} {:name \"John\" :age 43}])\n\n;; update the age of the second (index 1) user \n(assoc-in users [1 :age] 44)\n;;=> [{:name \"James\", :age 26} {:name \"John\", :age 44}]\n\n;; insert the password of the second (index 1) user\n(assoc-in users [1 :password] \"nhoJ\")\n;;=> [{:name \"James\", :age 26} {:password \"nhoJ\", :name \"John\", :age 43}]\n\n;; create a third (index 2) user\n;; Also (assoc m 2 {...}) or (conj m {...})\n(assoc-in users [2] {:name \"Jack\" :age 19}) \n;;=> [{:name \"James\", :age 26} {:name \"John\", :age 43} {:name \"Jack\", :age 19}]\n\n;; From http://clojure-examples.appspot.com/clojure.core/assoc-in","created-at":1278953901000,"updated-at":1422565766316,"_id":"542692cac026201cdc326b38"},{"author":{"login":"devth","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/70c7535cbb9fea0353250a4edda155be?r=PG&default=identicon"},"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"},{"avatar-url":"https://avatars.githubusercontent.com/u/200617?v=3","account-source":"github","login":"bsima"},{"login":"elias94","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8095533?v=4"}],"body":";; can be used to update a mutable item.\n(def ppl (atom {\"persons\" {\"joe\" {:age 1}}}))\n(swap! ppl assoc-in [\"persons\" \"bob\"] {:age 2})\n\n@ppl\n;;=> {\"persons\" {\"joe\" {:age 1}, \"bob\" {:age 2}}}","created-at":1378880124000,"updated-at":1625799501437,"_id":"542692d2c026201cdc326f4c"},{"editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3","account-source":"github","login":"phreed"},{"login":"clojureman","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/1793303?v=3"}],"updated-at":1495693228091,"created-at":1412006606316,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/453580?v=2","account-source":"github","login":"pmbauer"},"body":";; be careful with that empty path sequence, it's seldom what you want\n(assoc-in {} [] {:k :v})\n;;=> {nil {:k :v}}\n\n;; In general, you find that for a non-empty path\n;; (get-in (assoc-in m path v) path) \n;; is equal to v.\n;; Surprisingly this does not hold true in case of an empty path.","_id":"542982cee4b09282a148f203"},{"body":";; another example of updating a mutable item.\n;; this time the first key is to a map and the second to a vector.\n(def foo (atom {:users [{:a \"a\"} {:b \"b\"}]}))\n(swap! foo assoc-in [:users 2] {:c \"c\"})\n;;=> {:users [{:a \"a\"} {:b \"b\"} {:c \"c\"}]}\n\n","author":{"login":"saiberz","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1022999?v=3"},"created-at":1418344457312,"updated-at":1422566109388,"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"_id":"548a3809e4b04e93c519ffa4"},{"editors":[{"login":"coffeefire","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/14366530?v=3"}],"updated-at":1448358381451,"created-at":1433960090535,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/571777?v=3","account-source":"github","login":"cthulhu-bot"},"body":";; assoc-in into a nested map structure\n(def foo {:user {:bar \"baz\"}})\n(assoc-in foo [:user :id] \"some-id\")\n;;=> {:user {:bar \"baz\", :id \"some-id\"}}\n","_id":"55787e9ae4b01ad59b65f4ef"},{"editors":[{"login":"prudentbot","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/3210379?v=3"}],"body":"(assoc-in {} [:cookie :monster :vocals] \"Finntroll\")\n; => {:cookie {:monster {:vocals \"Finntroll\"}}}\n\n(get-in {:cookie {:monster {:vocals \"Finntroll\"}}} [:cookie :monster])\n; => {:vocals \"Finntroll\"}\n\n(assoc-in {} [1 :connections 4] 2)\n; => {1 {:connections {4 2}}}\n\n;; from http://www.braveclojure.com/functional-programming/","author":{"avatar-url":"https://avatars.githubusercontent.com/u/3210379?v=3","account-source":"github","login":"prudentbot"},"created-at":1438058284679,"updated-at":1438100741796,"_id":"55b7072ce4b06a85937088b7"},{"editors":[{"login":"amirrajan","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/517055?v=3"}],"body":";; assoc-in can be used on vectors too\n\n(def row 0)\n(def col 0)\n\n(assoc-in [[1 1 1]\n [1 1 1]\n [1 1 1]] [row col] 0)\n; => [[0 1 1][1 1 1][1 1 1]]\n\n(get-in [[0 1 1]\n [1 1 1]\n [1 1 1]] [row col])\n; => 0","author":{"avatar-url":"https://avatars.githubusercontent.com/u/517055?v=3","account-source":"github","login":"amirrajan"},"created-at":1445568749511,"updated-at":1445568838675,"_id":"5629a0ede4b04b157a6648d8"},{"editors":[{"login":"gosukiwi","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/161972?v=3"}],"body":"; Playing around with assoc-in\n\n(assoc-in {:person {:name \"Mike\"}} [:person :name] \"Violet\")\n; => {:person {:name \"Violet\"}}\n\n(assoc-in {:person {:name \"Mike\"}} [:person] \"Violet\")\n; => {:person \"Violet\"}\n\n(assoc-in [{:person {:name \"Mike\"}}] [0 :person :name] \"Violet\")\n; => [{:person {:name \"Violet\"}}]\n\n(assoc-in [{:person {:name [\"Mike\"]}}] [0 :person :name 1] \"Smith\")\n; => [{:person {:name [\"Mike\" \"Smith\"]}}]\n\n(assoc-in [{:person {:name [\"Mike\"]}}] [0 :person :name 2] \"Smith\")\n; => IndexOutOfBoundsException","author":{"avatar-url":"https://avatars.githubusercontent.com/u/161972?v=3","account-source":"github","login":"gosukiwi"},"created-at":1470551622806,"updated-at":1470551660418,"_id":"57a6d646e4b0bafd3e2a04cc"},{"editors":[{"login":"loeschzwerg","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/24317401?v=4"}],"body":";; Note that, unlike `assoc`, `assoc-in` cannot be used with multiple values.\n\n(def my-map {})\n\n;; This works\n(assoc my-map :a 1\n :b 2\n :c 3)\n; => {:a 1, :b 2, :c 3}\n\n;; This doesn’t\n(assoc-in my-map [:a :aa] 1\n [:b :bb] 2\n [:c :cc] 3)\n; ArityException Wrong number of args (7) passed to: core/assoc-in\n\n;; This works\n(-> my-map\n (assoc-in [:a :aa] 1)\n (assoc-in [:b :bb] 2)\n (assoc-in [:c :cc] 3))","author":{"avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4","account-source":"github","login":"bfontaine"},"created-at":1524054770336,"updated-at":1631275246821,"_id":"5ad73af2e4b045c27b7fac3f"}],"notes":[{"body":"Unlike `assoc`, you can only do one kv at a time:\n\n```\n;; Allowed\n(assoc {} :a \"a\" :b \"b\" :c \"c\")\n;; Not allowed:\n(assoc-in {} [:a :b] \"cya\" [:a :d :e] \"f\" [:b :g] \"wow\")\n```","created-at":1648401233813,"updated-at":1648401332618,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/19522656?v=4","account-source":"github","login":"Crowbrammer"},"_id":"62409b51e4b0b1e3652d75c2"}],"arglists":["m [k & ks] v"],"doc":"Associates a value in a nested associative structure, where ks is a\n sequence of keys and v is the new value and returns a new nested structure.\n If any levels do not exist, hash-maps will be created.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/assoc-in"},{"added":"1.0","ns":"clojure.core","name":"char-name-string","file":"clojure/core_print.clj","type":"var","column":1,"see-alsos":[{"created-at":1375209941000,"author":{"login":"alilee","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2fb0196dc5a7cd3a5cc73f1b9941c209?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"char-escape-string","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b76"}],"line":342,"examples":[{"author":{"login":"alilee","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2fb0196dc5a7cd3a5cc73f1b9941c209?r=PG&default=identicon"},"editors":[],"body":"user=> (char-name-string \\newline)\n\"newline\"","created-at":1375209966000,"updated-at":1375209966000,"_id":"542692d2c026201cdc326f5f"},{"updated-at":1592040564496,"created-at":1592040564496,"author":{"login":"ertugrulcetin","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/8271291?v=4"},"body":"(map char-name-string [\\backspace \\tab \\newline \\formfeed \\return \\space])\n;;=> (\"backspace\" \"tab\" \"newline\" \"formfeed\" \"return\" \"space\")","_id":"5ee49c74e4b0b1e3652d7303"}],"notes":null,"tag":"java.lang.String","arglists":[],"doc":"Returns name string for char or nil if none","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/char-name-string"},{"added":"1.0","ns":"clojure.core","name":"bit-test","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1405720487000,"author":{"login":"phreed","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3a0c739cf289be18be932dc3022e6fd3?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"bit-set","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cac"},{"created-at":1405720498000,"author":{"login":"phreed","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3a0c739cf289be18be932dc3022e6fd3?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"bit-shift-left","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cad"},{"created-at":1405720509000,"author":{"login":"phreed","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3a0c739cf289be18be932dc3022e6fd3?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"bit-xor","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cae"}],"line":1363,"examples":[{"author":{"login":"zmila","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/68dd6f50915854aa04fefcf4d6fa5c8e?r=PG&default=identicon"},"editors":[{"login":"zmila","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/68dd6f50915854aa04fefcf4d6fa5c8e?r=PG&default=identicon"},{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":"(bit-test 2r1001 0) ;;=> true \n(bit-test 2r1001 1) ;;=> false \n(bit-test 2r1001 7) ;;=> false","created-at":1280338595000,"updated-at":1421943187268,"_id":"542692cfc026201cdc326e7c"},{"updated-at":1550024741651,"created-at":1550024741651,"author":{"login":"pauloaug","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/804447?v=4"},"body":";; Note that the index starts from the least significant bit (right to left).\n\n(map #(bit-test 2r10011 %) [0 1 2 3 4])\n;;=> (true true false false true) ","_id":"5c638025e4b0ca44402ef682"},{"editors":[{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"}],"body":";; bit-wise powerset (set of all subsets)\n\n(defn powerset [coll]\n (let [cnt (count coll)\n bits (Math/pow 2 cnt)]\n (for [i (range bits)]\n (for [j (range i)\n :while (< j cnt)\n :when (bit-test i j)]\n (nth coll j)))))\n\n(powerset [1 2 3])\n;; (() (1) (2) (1 2) (3) (1 3) (2 3) (1 2 3))","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"},"created-at":1564483500939,"updated-at":1564483573152,"_id":"5d401face4b0ca44402ef78b"}],"notes":null,"arglists":["x n"],"doc":"Test bit at index n","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/bit-test"},{"added":"1.0","ns":"clojure.core","name":"defmethod","file":"clojure/core.clj","type":"macro","column":1,"see-alsos":[{"created-at":1285162546000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"defmulti","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b40"},{"created-at":1341270386000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"remove-method","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b41"},{"created-at":1341270389000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"remove-all-methods","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b42"},{"created-at":1341270393000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"prefers","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b43"},{"created-at":1341270396000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"methods","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b44"},{"created-at":1341270398000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"get-method","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b45"}],"line":1800,"examples":[{"author":{"login":"Victor","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bc41ebab54cc0e0fbe99d753876d45ce?r=PG&default=identicon"},"editors":[],"body":"(defmulti service-charge (fn [acct] [(account-level acct) (:tag acct)]))\n(defmethod service-charge [::acc/Basic ::acc/Checking] [_] 25)\n(defmethod service-charge [::acc/Basic ::acc/Savings] [_] 10)\n(defmethod service-charge [::acc/Premium ::acc/Account] [_] 0)","created-at":1290489730000,"updated-at":1290489730000,"_id":"542692c7c026201cdc3269cb"},{"author":{"login":"Victor","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bc41ebab54cc0e0fbe99d753876d45ce?r=PG&default=identicon"},"editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/104014?v=3","account-source":"github","login":"slester"},{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"}],"body":";this example illustrates that the dispatch type\n;does not have to be a symbol, but can be anything (in this case, it's a string)\n\n(defmulti greeting\n (fn [x] (get x \"language\")))\n\n;params is not used, so we could have used [_]\n(defmethod greeting \"English\" [params]\n \"Hello!\")\n\n(defmethod greeting \"French\" [params]\n \"Bonjour!\")\n\n;then can use this like this:\n(def english-map {\"id\" \"1\", \"language\" \"English\"})\n(def french-map {\"id\" \"2\", \"language\" \"French\"})\n\n=>(greeting english-map)\n\"Hello!\"\n=>(greeting french-map)\n\"Bonjour!\"\n","created-at":1290492873000,"updated-at":1572016935512,"_id":"542692c7c026201cdc3269cc"},{"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"editors":[],"body":";; Methods can be given a name. Very useful in stack traces.\n(defmethod foo \"a\" name-of-method [params] \"was a\")\n","created-at":1308205150000,"updated-at":1308205150000,"_id":"542692c7c026201cdc3269cd"},{"editors":[{"login":"gariepyalex","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/6105461?v=4"}],"body":"(defmulti ticket-price :customer-status)\n\n(defmethod ticket-price :student\n ;; Everything after the dispatch value is passed to fn.\n student-price\n [customer]\n 10.0)\n\n(defmethod ticket-price :professional\n professional-price\n [customer]\n 650.0)","author":{"avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4","account-source":"github","login":"bfontaine"},"created-at":1572017355964,"updated-at":1596053774142,"_id":"5db314cbe4b0ca44402ef7d4"}],"macro":true,"notes":null,"arglists":["multifn dispatch-val & fn-tail"],"doc":"Creates and installs a new method of multimethod associated with dispatch-value. ","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/defmethod"},{"added":"1.10","ns":"clojure.core","name":"requiring-resolve","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1611863381575,"author":{"login":"nbaumanGR","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/76698379?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"resolve","ns":"clojure.core"},"_id":"60131555e4b0b1e3652d7441"}],"line":6145,"examples":[{"editors":[{"login":"daemianmack","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/24476?v=4"}],"body":";; Resolve a qualified symbol\n(requiring-resolve 'clojure.java.shell/sh)\n\n;; Resolve and evaluate\n((requiring-resolve 'some-ns/some-fn))\n\n;; In deps.edn, replace all spaces with the \"Corfield\" comma, ;)\n((requiring-resolve,'clojure.java.shell/sh))","author":{"avatar-url":"https://avatars0.githubusercontent.com/u/705227?v=4","account-source":"github","login":"Hindol"},"created-at":1583391908395,"updated-at":1605911520381,"_id":"5e60a4a4e4b087629b5a18b7"},{"editors":[{"login":"Folcon","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/123055?v=4"}],"body":"(defn debug? [] (= (env :debug?) \"true\"))\n\n;; If you need to do conditional requires such as the one below:\n(if (debug?)\n (do\n (require '[nrepl.cmdline :refer [-main] :rename {-main -nrepl-main}])\n (resolve 'nrepl.cmdline))\n (declare -nrepl-main))\n\n(defn -main [& args]\n (when (debug?)\n (future (apply -nrepl-main args))))\n\n;; This is strictly better!\n(defn -main [& args]\n (when (debug?)\n ;; Swap to require and resolve in one step!\n (future (apply (requiring-resolve 'nrepl.cmdline/-main) args))))","author":{"avatar-url":"https://avatars.githubusercontent.com/u/123055?v=4","account-source":"github","login":"Folcon"},"created-at":1643638396360,"updated-at":1643638468576,"_id":"61f7ee7ce4b0b1e3652d75a4"}],"notes":null,"arglists":["sym"],"doc":"Resolves namespace-qualified sym per 'resolve'. If initial resolve\nfails, attempts to require sym's namespace and retries.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/requiring-resolve"},{"ns":"clojure.core","name":"EMPTY-NODE","file":"clojure/gvec.clj","type":"var","column":1,"see-alsos":null,"line":20,"examples":null,"notes":null,"arglists":[],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core/EMPTY-NODE"},{"added":"1.0","ns":"clojure.core","name":"time","file":"clojure/core.clj","type":"macro","column":1,"see-alsos":null,"line":3910,"examples":[{"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"editors":[],"body":"user> (time (Thread/sleep 100))\n\"Elapsed time: 100.284772 msecs\"\nnil","created-at":1286871374000,"updated-at":1286871374000,"_id":"542692c6c026201cdc326908"},{"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"editors":[],"body":";when working with lazy seqs\n(time (doall (...)))","created-at":1289011003000,"updated-at":1289011003000,"_id":"542692c6c026201cdc326909"},{"author":{"login":"Omer","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/dae0f434afde5246ccb030cdec81fb71?r=PG&default=identicon"},"editors":[{"login":"Omer","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/dae0f434afde5246ccb030cdec81fb71?r=PG&default=identicon"}],"body":";; Time how long it takes to write a string to a file 100 times\n(defn time-test []\n (with-open [w (writer \"test.txt\" :append false)]\n (dotimes [_ 100]\n (.write w \"I am being written to a file.\"))))\n\n\nuser=> (time (time-test))\n\"Elapsed time: 19.596371 msecs\"","created-at":1338273583000,"updated-at":1338273812000,"_id":"542692d5c026201cdc3270a6"},{"author":{"login":"micrub","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/c649274329369f1a7a4869e29655e058?r=PG&default=identicon"},"editors":[],"body":"user=> (time (Thread/sleep 1000))\n\"Elapsed time: 1000.267483 msecs\"\nnil\nuser=> (with-out-str (time (Thread/sleep 1000)))\n\"\\\"Elapsed time: 1010.12942 msecs\\\"\\n\"\n\n","created-at":1400389644000,"updated-at":1400389644000,"_id":"542692d5c026201cdc3270a8"},{"updated-at":1619013512243,"created-at":1619013512243,"author":{"login":"sFritsch09","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/58191603?v=4"},"body":";;get elapsed time in seconds:\n\n(defmacro sectime\n [expr]\n `(let [start# (. System (currentTimeMillis))\n ret# ~expr]\n (prn (str \"Elapsed time: \" (/ (double (- (. System (currentTimeMillis)) start#)) 1000.0) \" secs\"))\n ret#))","_id":"60802f88e4b0b1e3652d74cc"}],"macro":true,"notes":[{"author":{"login":"mars0i","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1836941?v=4"},"updated-at":1646109474809,"created-at":1646109474809,"body":"Because the Java JIT compiler compiles code differently after the code has been running for a bit of time, if you want to use `time` for benchmarking, you should at least \"warm up\" your code by running it several times, using the later `time` outputs as the ones that count. A better strategy is to use a benchmarking library such as [Criterium](https://github.com/hugoduncan/criterium), which will do the warmup for you, and much more.","_id":"621da322e4b0b1e3652d75ae"}],"arglists":["expr"],"doc":"Evaluates expr and prints the time it took. Returns the value of\n expr.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/time"},{"added":"1.0","ns":"clojure.core","name":"memoize","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1358780692000,"author":{"login":"AtKaaZ","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e10dfa345f44b0fe72bbe081fd51b83?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"delay","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d2a"}],"line":6414,"examples":[{"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":";; First we define a function that presumably have some expensive computation.\nuser=> (defn myfunc[a] (println \"doing some work\") (+ a 10))\n#'user/myfunc\n\n;; Next we create a memoized version of the function.\nuser=> (def myfunc-memo (memoize myfunc))\n#'user/myfunc-memo\n\n\n;; The first time we call the function with a particular argument the\n;; original function is invoked and the value is returned. The next\n;; time the function is called with the same argument the cached result\n;; is returned and the original function is NOT called.\n\nuser=> (myfunc-memo 1)\ndoing some work\n11\nuser=> (myfunc-memo 1)\n11\nuser=> (myfunc-memo 20)\ndoing some work\n30\nuser=> (myfunc-memo 20)\n30\n","created-at":1280909609000,"updated-at":1285495306000,"_id":"542692ccc026201cdc326c75"},{"body":"\n;; Fibonacci number with recursion.\n(defn fib [n]\n (condp = n\n 0 1\n 1 1\n (+ (fib (dec n)) (fib (- n 2)))))\n\n(time (fib 30))\n;; \"Elapsed time: 8179.04028 msecs\"\n\n;; Fibonacci number with recursion and memoize.\n(def m-fib\n (memoize (fn [n]\n (condp = n\n 0 1\n 1 1\n (+ (m-fib (dec n)) (m-fib (- n 2)))))))\n\n(time (m-fib 30))\n;; \"Elapsed time: 1.282557 msecs\"\n ","author":{"login":"discoverfly","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1535428?v=3"},"created-at":1429269742396,"updated-at":1429269742396,"_id":"5530eceee4b01bb732af0a83"},{"updated-at":1497303795210,"created-at":1497303795210,"author":{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/94482?v=3"},"body":";; It's possible to memoize a function with multiple arguments:\n(def times (memoize (fn [x y] (* x y))))\n\n(times 1 2) ; => 2\n\n(times 2 0) ; => 0","_id":"593f0af3e4b06e730307db31"},{"updated-at":1532276203982,"created-at":1532276203982,"author":{"login":"comnik","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/1313051?v=4"},"body":";; Memoize is a simple way to make a mapping deterministic.\n(def attribute->id (memoize (fn [attr] (clojure.lang.RT/nextID))))\n\n(attribute->id :name) ; => 16305\n\n(attribute->id :age) ; => 16306\n\n(attribute->id :name) ; => 16305","_id":"5b54adebe4b00ac801ed9e2a"},{"updated-at":1555579882226,"created-at":1555579882226,"author":{"login":"harununal","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/36730353?v=4"},"body":"; We can take a rand and use it repeatly \n; (Just with same parameter)\n\n(defn only-first-one-rand\n [n]\n (rand n))\n\n(def ofor-memo (memoize only-first-one-rand))\n\n(ofor-memo 10) ;=> 3.683571228686361 \n\n(ofor-memo 10) ;=> 3.683571228686361\n\n;And we can assign a random value to an integer\n\n(ofor-memo 6) ;=> 2.8058589761445867\n\n(ofor-memo 10) ;=> 3.683571228686361","_id":"5cb843eae4b0ca44402ef70d"},{"updated-at":1555580792896,"created-at":1555580792896,"author":{"login":"harununal","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/36730353?v=4"},"body":"; When we use memoize, we say to Clojure :\n; \" x function returned with y parameters as z value. \n; No need to repeat this process everytimes. \n; Because you has pure functions. \n; Just keep \"z value\" on your mind. \n; Thank you.\" ","_id":"5cb84778e4b0ca44402ef70e"}],"notes":[{"author":{"login":"rquinlivan","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/485844?v=3"},"updated-at":1480901638909,"created-at":1480901638909,"body":"What is the definition of \"often\" for the purposes of caching? Is there a util like this that allows for different cache eviction strategies?","_id":"5844c406e4b0782b632278d2"},{"author":{"login":"PetrGlad","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/124476?v=3"},"updated-at":1483028454253,"created-at":1483028454253,"body":"@rquinlivan The implementation of clojure.core/memoize is plain straightforward. It should be obvious that computation_cost times number_of_calls should determine whether to use it or not. If you need more control over caching have a look at [clojure.core.cache](https://github.com/clojure/core.cache)","_id":"586537e6e4b0fd5fb1cc964b"},{"author":{"login":"l3nz","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/1101849?v=4"},"updated-at":1591252941044,"created-at":1591252896617,"body":"`memoize` is nice but it may be tricky to use in production, because it just caches everything. Also, the key under which the value is stored are all the parametres you have as input. \n\nIf you need something more flexible, with user-definable keys (eg because you are passing in a database connection) or a flexible eviction policy, see `clojure.core.memoize` that is a wrapper around `clojure.core.cache`.","_id":"5ed897a0e4b087629b5a1922"}],"arglists":["f"],"doc":"Returns a memoized version of a referentially transparent function. The\n memoized version of the function keeps a cache of the mapping from arguments\n to results and, when calls with the same arguments are repeated often, has\n higher performance at the expense of higher memory use.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/memoize"},{"added":"1.0","ns":"clojure.core","name":"alter-meta!","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1375212992000,"author":{"login":"alilee","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2fb0196dc5a7cd3a5cc73f1b9941c209?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"vary-meta","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bd0"},{"created-at":1375213001000,"author":{"login":"alilee","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2fb0196dc5a7cd3a5cc73f1b9941c209?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"with-meta","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bd1"},{"created-at":1456685895947,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"meta","ns":"clojure.core"},"_id":"56d34347e4b02a6769b5a4bc"},{"created-at":1458508939384,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"reset-meta!","ns":"clojure.core"},"_id":"56ef148be4b09295d75dbf30"}],"line":2423,"examples":[{"updated-at":1456685878779,"created-at":1456685878779,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10583730?v=3"},"body":"(def ^{:version 1} document \"This is text\")\n;;=> #'user/document\n\n(meta #'document)\n;;=> {:version 1}\n\n(alter-meta! #'document #(update-in % [:version] inc)) ;increase version\n;;=> {:version 2}\n\n(meta #'document) ;metadata of var was changed\n;;=> {:version 2}\n\n(alter-meta! #'document update-in [:version] inc) ;same as above but shorter\n;;=> {:version 3}\n\n(meta #'document) ;metadata of var was changed again\n;;=> {:version 3}\n","_id":"56d34336e4b0b41f39d96cda"}],"notes":null,"arglists":["iref f & args"],"doc":"Atomically sets the metadata for a namespace/var/ref/agent/atom to be:\n\n (apply f its-current-meta args)\n\n f must be free of side-effects","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/alter-meta!"},{"added":"1.1","ns":"clojure.core","name":"future?","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"to-var":{"library-url":"https://github.com/clojure/clojure","name":"future","ns":"clojure.core"},"author":{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},"created-at":1339251269000,"_id":"542692ebf6e94c6970521ef5"}],"line":6609,"examples":[{"author":{"login":"BertrandDechoux","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3"},"editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"}],"body":"user=> (def f (future (inc 0)))\n#'user/f\n\nuser=> (future? f)\ntrue\n\nuser=> (future? 1)\nfalse\n","created-at":1339251424000,"updated-at":1339251441000,"_id":"542692d3c026201cdc326fb9"}],"notes":null,"arglists":["x"],"doc":"Returns true if x is a future","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/future_q"},{"added":"1.0","ns":"clojure.core","name":"zero?","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1400618891000,"author":{"login":"ryo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3f7913b563c72083c74030d928ba407e?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"pos?","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521dde"},{"created-at":1400618896000,"author":{"login":"ryo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3f7913b563c72083c74030d928ba407e?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"neg?","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ddf"},{"created-at":1605573252870,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"=","ns":"clojure.core"},"_id":"5fb31a84e4b0b1e3652d7406"}],"line":869,"examples":[{"updated-at":1423525588057,"created-at":1279075455000,"body":"(zero? 0) ;;=> true\n(zero? 0.0) ;;=> true\n(zero? 2r000) ;;=> true\n(zero? 0x0) ;;=> true\n\n(zero? 1) ;;=> false\n(zero? 3.14159265358M) ;;=> false\n(zero? (/ 1 2)) ;;=> false\n\n(zero? nil) ;;=> NullPointerException","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3","account-source":"github","login":"jafingerhut"},{"avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3","account-source":"github","login":"devn"},{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3","account-source":"github","login":"phreed"},{"avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3","account-source":"github","login":"Dimagog"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/147981?v=3","account-source":"github","login":"dpritchett"},"_id":"542692c8c026201cdc326a6d"}],"notes":[{"author":{"login":"chbrown","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/360279?v=3"},"updated-at":1499457802441,"created-at":1499457802441,"body":"`(zero? x)` calls `(clojure.lang.Numbers/isZero x)`, which will throw a `ClassCastException ... cannot be cast to java.lang.Number` or `NullPointerException` if `x` is anything but a number.","_id":"595fe90ae4b06e730307db50"}],"arglists":["num"],"doc":"Returns true if num is zero, else false","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/zero_q"},{"added":"1.9","ns":"clojure.core","name":"simple-keyword?","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1495715327644,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"keyword?","ns":"clojure.core"},"_id":"5926cdffe4b093ada4d4d764"},{"created-at":1495715337823,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"qualified-keyword?","ns":"clojure.core"},"_id":"5926ce09e4b093ada4d4d765"}],"line":1652,"examples":[{"updated-at":1495722311941,"created-at":1495722311941,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"body":"(simple-keyword? :keyword)\n;;=> true\n\n(simple-keyword? :user/:keyword)\n;;=> false\n(simple-keyword? ::keyword)\n;;=> false\n\n(simple-keyword? \"string\")\n;;=> false\n(simple-keyword? 42)\n;;=> false\n(simple-keyword? nil)\n;;=> false","_id":"5926e947e4b093ada4d4d769"}],"notes":null,"arglists":["x"],"doc":"Return true if x is a keyword without a namespace","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/simple-keyword_q"},{"added":"1.0","ns":"clojure.core","name":"require","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1281451664000,"author":{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},"to-var":{"ns":"clojure.core","name":"remove-ns","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bf3"},{"created-at":1291628612000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"import","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bf4"},{"created-at":1291628619000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"use","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bf5"},{"to-var":{"library-url":"https://github.com/clojure/clojure","name":"ns","ns":"clojure.core"},"author":{"avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3","account-source":"github","login":"devn"},"created-at":1358655983000,"_id":"542692eaf6e94c6970521bf6"},{"created-at":1423094191542,"author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"to-var":{"ns":"clojure.core","name":"refer","library-url":"https://github.com/clojure/clojure"},"_id":"54d2b1afe4b081e022073c60"},{"created-at":1654081012452,"author":{"login":"PEZ","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/30010?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"requiring-resolve","ns":"clojure.core"},"_id":"629745f4e4b0b1e3652d75f4"},{"created-at":1654081063935,"author":{"login":"PEZ","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/30010?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"resolve","ns":"clojure.core"},"_id":"62974627e4b0b1e3652d75f6"}],"line":6066,"examples":[{"author":{"login":"scode","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/87b4fd6e7ac86cbf1f1b683f7856057?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"avatar-url":"https://avatars.githubusercontent.com/u/8088318?v=3","account-source":"github","login":"jackyfkc"},{"avatar-url":"https://avatars.githubusercontent.com/u/10583730?v=3","account-source":"github","login":"svenschoenung"},{"login":"jkxyz","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10171367?v=4"}],"body":";; Require clojure.set and call its union function:\n\nuser=> (require 'clojure.set)\nnil\nuser=> (clojure.set/union #{1} #{2})\n#{1 2}\n","created-at":1279160245000,"updated-at":1667391689806,"_id":"542692ccc026201cdc326cb8"},{"updated-at":1461731642529,"created-at":1283923768000,"body":";; alias clojure.java.io as io\nuser=> (require '[clojure.java.io :as io])\nnil\n\nuser=> (io/file \"Filename\")\n#\n\n;; alias clojure.java.io as io using prefixes\nuser=> (require '(clojure.java [io :as io2]))\nnil\n\nuser=> (io2/file \"Filename\")\n#","editors":[{"avatar-url":"https://www.gravatar.com/avatar/bd6e62afb4881ab0f617611b8b65d003?r=PG&default=identicon","account-source":"clojuredocs","login":"teyc"},{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"avatar-url":"https://www.gravatar.com/avatar/bc41ebab54cc0e0fbe99d753876d45ce?r=PG&default=identicon","account-source":"clojuredocs","login":"Victor"},{"avatar-url":"https://www.gravatar.com/avatar/bc41ebab54cc0e0fbe99d753876d45ce?r=PG&default=identicon","account-source":"clojuredocs","login":"Victor"},{"login":"jackyfkc","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8088318?v=3"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/bd6e62afb4881ab0f617611b8b65d003?r=PG&default=identicon","account-source":"clojuredocs","login":"teyc"},"_id":"542692ccc026201cdc326cbb"},{"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"editors":[],"body":"(ns rosettacode.24game\n (:require [clojure.string :as str]))\n\n(defn parse-infix-data\n \"input '1+2+3+4'\n output (1 + 2 + 3 + 4)\n where the numbers are clojure numbers, and the symbols are clojure operators\"\n [string] (map read-string (next (str/split string #\"\"))))","created-at":1289382235000,"updated-at":1289382235000,"_id":"542692ccc026201cdc326cc0"},{"author":{"login":"lambder","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1c0c20072f52de3a6335cae183b865f6?r=PG&default=identicon"},"editors":[],"body":"(require '(clojure.contrib [sql :as sql]))","created-at":1314991093000,"updated-at":1314991093000,"_id":"542692ccc026201cdc326cc1"},{"author":{"login":"devn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3"},"editors":[{"login":"nickgieschen","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cbfa20635c9269675d54547c080c9b64?r=PG&default=identicon"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"}],"body":"(ns myproject.core\n (:use [clojure.core] :reload)\n (:require [clojure.string :as str :refer [replace]] :reload-all))\n\n(str/replace \"foo\" #\"o\" \"e\")\n\"fee\"\n\n; similar but using a prefix.\n(ns myproject.core\n (:require (clojure [core]\n [string :as str :refer [replace]] ))) \n\n","created-at":1358655968000,"updated-at":1507304199209,"_id":"542692d5c026201cdc327072"},{"updated-at":1482287160163,"created-at":1482284632050,"author":{"login":"ichisemasashi","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/679549?v=3"},"body":"; rename a function name (thanks for @noisesmith)\n; rename 'clojure.repl/doc' to 'd'\nuser=> (require '[clojure.repl :as r :refer [doc] :rename {doc d}])\nnil\nuser=> (d doc)\n-------------------------\nclojure.repl/doc\n([name])\nMacro\n Prints documentation for a var or special form given its name\nnil\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/679549?v=3","account-source":"github","login":"ichisemasashi"}],"_id":"5859de58e4b004d3a355e2cd"},{"editors":[{"login":"eval","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/290596?v=4"}],"body":";; Note that require is known _not_ to be thread safe in Clojure 1.11.x and\n;; earlier, so avoid calling it concurrently from multiple threads.\n\n;; See https://ask.clojure.org/index.php/9893/require-is-not-thread-safe\n;; for some thoughts on approaches to using require from multiple threads\n;; safely, which today boils down to \"use locks to make all calls to require\n;; guaranteed to execute one at a time\".","author":{"avatar-url":"https://avatars2.githubusercontent.com/u/109629?v=4","account-source":"github","login":"jafingerhut"},"created-at":1608133142354,"updated-at":1698411289229,"_id":"5fda2a16e4b0b1e3652d7419"},{"updated-at":1654081970684,"created-at":1654081970684,"author":{"login":"PEZ","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/30010?v=4"},"body":";; Watch out for the Gilardi scenario: https://technomancy.us/143\n;; If you need to refer to the required symbols in the same block\n;; of code as it is being defined, that will only work at top level\n;; and in top-level `do`:\n\n(do\n (require '[clojure.set :as c-set])\n (c-set/union #{1} #{2})) ; => #{\"1\" \"2\"}\n\n;; It won't work here, because the compiler does not know about\n;; `c-set` when it tries to compile the form:\n\n(->> [\"1\" \"2\"]\n (reduce (fn [acc v]\n (require '[clojure.set :as c-set])\n (c-set/union acc #{v}))\n #{})) ; => Syntax error compiling at ...\n ; No such namespace: c-set\n\n;; A solution is to move the use of the required symbol to run-time.\n;; E.g. with `resolve`:\n\n(->> [\"1\" \"2\"]\n (reduce (fn [acc v]\n (require '[clojure.set :as c-set])\n ((resolve 'c-set/union) acc #{v}))\n #{})) ; => #{\"1\" \"2\"}\n\n;; At which point `requiring-resolve` might be clearer:\n\n(->> [\"1\" \"2\"]\n (reduce (fn [acc v]\n ((requiring-resolve 'clojure.set/union) acc #{v}))\n #{})) ; => #{\"1\" \"2\"}","_id":"629749b2e4b0b1e3652d75f7"},{"updated-at":1654162737681,"created-at":1654162737681,"author":{"login":"imrekoszo","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1116295?v=4"},"body":";; As a follow-up to previous examples, one more reason to prefer using\n;; `requiring-resolve` from within runtime functions when possible, is that it\n;; wraps `require` in a thread-safe way (require itself is not thread-safe as of\n;; 1.11.1 as mentioned in an earlier example).\n;; This is done via the private function `clojure.core/serialized-require`\n;; Some more info can be found in the comment at\n;; https://ask.clojure.org/index.php/9893/require-is-not-thread-safe?show=9902#c9902","_id":"62988531e4b0b1e3652d75f8"},{"updated-at":1698413996926,"created-at":1698413765537,"author":{"login":"eval","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/290596?v=4"},"body":";; :as-alias (introduced in v1.11) allows you to create an alias without loading\n;; the namespace. Typically, when using :as-alias, the namespace is just used as a\n;; qualifier and is not a loadable namespace.\nuser=> (require '[company.some-widget.some-entity :as-alias some-entity])\n\n;; As with regular aliases it's now more convenient to create maps\nuser=> {::some-entity/id \"some-id\"}\n{:company.some-widget.some-entity/id \"some-id\"}\n\n;; ...to destructure\nuser=> (defn find-some-entity-by-id [{::some-entity/keys [id]}]\n ,,,)\n\n;; ...or to register specs\nuser=> (s/def ::some-entity/id string?)\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/290596?v=4","account-source":"github","login":"eval"}],"_id":"653bbcc569fbcc0c226173f6"}],"notes":[{"updated-at":1291628629000,"body":"Good description of use/require/import here:\r\n\r\nhttp://blog.8thlight.com/articles/2010/12/6/clojure-libs-and-namespaces-require-use-import-and-ns","created-at":1291628629000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521faa"}],"arglists":["& args"],"doc":"Loads libs, skipping any that are already loaded. Each argument is\n either a libspec that identifies a lib, a prefix list that identifies\n multiple libs whose names share a common prefix, or a flag that modifies\n how all the identified libs are loaded. Use :require in the ns macro\n in preference to calling this directly.\n\n Libs\n\n A 'lib' is a named set of resources in classpath whose contents define a\n library of Clojure code. Lib names are symbols and each lib is associated\n with a Clojure namespace and a Java package that share its name. A lib's\n name also locates its root directory within classpath using Java's\n package name to classpath-relative path mapping. All resources in a lib\n should be contained in the directory structure under its root directory.\n All definitions a lib makes should be in its associated namespace.\n\n 'require loads a lib by loading its root resource. The root resource path\n is derived from the lib name in the following manner:\n Consider a lib named by the symbol 'x.y.z; it has the root directory\n /x/y/, and its root resource is /x/y/z.clj, or\n /x/y/z.cljc if /x/y/z.clj does not exist. The\n root resource should contain code to create the lib's\n namespace (usually by using the ns macro) and load any additional\n lib resources.\n\n Libspecs\n\n A libspec is a lib name or a vector containing a lib name followed by\n options expressed as sequential keywords and arguments.\n\n Recognized options:\n :as takes a symbol as its argument and makes that symbol an alias to the\n lib's namespace in the current namespace.\n :as-alias takes a symbol as its argument and aliases like :as, however\n the lib will not be loaded. If the lib has not been loaded, a new\n empty namespace will be created (as with create-ns).\n :refer takes a list of symbols to refer from the namespace or the :all\n keyword to bring in all public vars.\n\n Prefix Lists\n\n It's common for Clojure code to depend on several libs whose names have\n the same prefix. When specifying libs, prefix lists can be used to reduce\n repetition. A prefix list contains the shared prefix followed by libspecs\n with the shared prefix removed from the lib names. After removing the\n prefix, the names that remain must not contain any periods.\n\n Flags\n\n A flag is a keyword.\n Recognized flags: :reload, :reload-all, :verbose\n :reload forces loading of all the identified libs even if they are\n already loaded (has no effect on libspecs using :as-alias)\n :reload-all implies :reload and also forces loading of all libs that the\n identified libs directly or indirectly load via require or use\n (has no effect on libspecs using :as-alias)\n :verbose triggers printing information about each load, alias, and refer\n\n Example:\n\n The following would load the libraries clojure.zip and clojure.set\n abbreviated as 's'.\n\n (require '(clojure zip [set :as s]))","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/require"},{"added":"1.0","ns":"clojure.core","name":"unchecked-dec-int","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1678034697354,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"unchecked-inc-int","ns":"clojure.core"},"_id":"6404c709e4b08cf8563f4b7a"}],"line":1177,"examples":[{"updated-at":1658482155693,"created-at":1658482155693,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":"(unchecked-dec-int 42);; => 41\n(unchecked-dec-int 42.2);; => 41\n(unchecked-dec-int Integer/MIN_VALUE);; => 2147483647","_id":"62da6debe4b0b1e3652d762e"}],"notes":null,"arglists":["x"],"doc":"Returns a number one less than x, an int.\n Note - uses a primitive operator subject to overflow.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/unchecked-dec-int"},{"added":"1.1","ns":"clojure.core","name":"persistent!","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1286870194000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"transient","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521a86"}],"line":3375,"examples":[{"author":{"login":"yasuto","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cacfb7ecf08cb6461767e514c93b7bf9?r=PG&default=identicon"},"editors":[],"body":"user> (def foo (transient [1 2 3]))\n#'user/foo\nuser> foo\n#\nuser> (persistent! foo)\n[1 2 3]\nuser> foo\n#\nuser> (conj! foo 4)\n→ ERROR:Transient used after persistent! call\nuser> (persistent! foo)\n→ ERROR: Transient used after persistent! call","created-at":1307739912000,"updated-at":1307739912000,"_id":"542692cdc026201cdc326d20"},{"body":";; Use persistent! to evaluate your object,\n;; once the computation is complete\n\n(loop [large-set (transient #{})\n i 0]\n (if (< i 100000)\n (recur (conj! large-set i) (inc i))\n (persistent! large-set)))\n\n;; Returns a large set *much* faster than its\n;; persistent version. While keeping the same\n;; code structure\n","author":{"login":"mattvvhat","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/367789?v=3"},"created-at":1428551188131,"updated-at":1428551188131,"_id":"5525f614e4b01bb732af0a7c"}],"notes":null,"arglists":["coll"],"doc":"Returns a new, persistent version of the transient collection, in\n constant time. The transient collection cannot be used after this\n call, any such use will throw an exception.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/persistent!"},{"added":"1.0","ns":"clojure.core","name":"nnext","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1482183664107,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"next","ns":"clojure.core"},"_id":"585853f0e4b004d3a355e2bb"},{"created-at":1482183673811,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"fnext","ns":"clojure.core"},"_id":"585853f9e4b004d3a355e2bc"},{"created-at":1482183802054,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"ffirst","ns":"clojure.core"},"_id":"5858547ae4b004d3a355e2c0"},{"created-at":1482183808882,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"nfirst","ns":"clojure.core"},"_id":"58585480e4b004d3a355e2c1"}],"line":121,"examples":[{"updated-at":1672789836612,"created-at":1281033362000,"body":"user=> (nnext '(1 2 3))\n(3)\n\nuser=> (nnext [])\nnil \n\nuser=> (nnext ['(a b c) '(b a c) '(c b a) '(a c b)])\n((c b a) (a c b)) \n\nuser=> (nnext {:a 1, :b 2, :c 3, :d 4})\n([:c 3] [:d 4]) \n\nuser=> (nnext #{:a :b :c})\n(:c)","editors":[{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/68dd6f50915854aa04fefcf4d6fa5c8e?r=PG&default=identicon","account-source":"clojuredocs","login":"zmila"},"_id":"542692cbc026201cdc326ba1"}],"notes":null,"arglists":["x"],"doc":"Same as (next (next x))","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/nnext"},{"added":"1.0","ns":"clojure.core","name":"add-watch","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1331138866000,"author":{"login":"pjlegato","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/4ce55cfd8b3ae2f63f5ecbc8fc1c05d4?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"remove-watch","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e04"}],"line":2161,"examples":[{"author":{"login":"devijvers","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/81018e4231ac1ce8b7a9e6d377092656?r=PG&default=identicon"},"editors":[{"login":"devijvers","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/81018e4231ac1ce8b7a9e6d377092656?r=PG&default=identicon"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"Daniel Brotsky","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/afb394be4b0eb5fc369a2fdbfea0a236?r=PG&default=identicon"}],"body":";; Add useful context to watcher function:\n(defn watch-agent [_agent context]\n (let [watch-fn (fn [_context _key _ref old-value new-value] ;...\n )] \n (add-watch _agent nil (partial watch-fn context))))\n","created-at":1279390260000,"updated-at":1356749167000,"_id":"542692c6c026201cdc326935"},{"updated-at":1507629557002,"created-at":1356749543000,"body":"Notice that it is nondeterministic that return happens first\nor the `print` call happens first. (because they are happening in different threads)\n \nuser> (def a (agent 0))\n=> #'user/a\nuser> a\n=> #agent[{:status :ready, :val 0} 0x591e4e8e]\nuser> (add-watch a :key (fn [k r os ns] (print k r os ns)))\n=> #agent[{:status :ready, :val 0} 0x591e4e8e]\nuser> (send a inc)\n=> #agent[{:status :ready, :val 1} 0x591e4e8e]\n:key #agent[{:status :ready, :val 1} 0x591e4e8e] 0 1\nuser> (send a inc)\n:key #agent[{:status :ready, :val 2} 0x591e4e8e] 1 2\n=> #agent[{:status :ready, :val 2} 0x591e4e8e]\n","editors":[{"avatar-url":"https://www.gravatar.com/avatar/afb394be4b0eb5fc369a2fdbfea0a236?r=PG&default=identicon","account-source":"clojuredocs","login":"Daniel Brotsky"},{"avatar-url":"https://avatars.githubusercontent.com/u/154699?v=3","account-source":"github","login":"avasenin"},{"login":"wontheone1","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/11784756?v=4"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/afb394be4b0eb5fc369a2fdbfea0a236?r=PG&default=identicon","account-source":"clojuredocs","login":"Daniel Brotsky"},"_id":"542692d1c026201cdc326f45"},{"body":"(def a (atom {}))\n\n(add-watch a :watcher\n (fn [key atom old-state new-state]\n (prn \"-- Atom Changed --\")\n (prn \"key\" key)\n (prn \"atom\" atom)\n (prn \"old-state\" old-state)\n (prn \"new-state\" new-state)))\n\n(reset! a {:foo \"bar\"})\n\n;; \"-- Atom Changed --\"\n;; \"key\" :watcher\n;; \"atom\" #\n;; \"old-state\" {}\n;; \"new-state\" {:foo \"bar\"}\n;; {:foo \"bar\"}","author":{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=3"},"created-at":1419712448016,"updated-at":1419712448016,"_id":"549f17c0e4b09260f767ca7f"},{"body":";; The name of my account can change, and I want to update another atom accordingly.\n;; I just take the fourth argument that contains the new state and I ignore the other arguments.\n\n(let [account (atom {:name \"pending\" \n :funds 100.50 \n :profit-loss 23.45})\n label-account-name (atom \"no-name-yet\")]\n (add-watch account :listener-one #(reset! label-account-name (:name %4)))\n (println \"Before swap:\" @label-account-name)\n (swap! account assoc :name \"CFD\")\n (println \"After swap:\" @label-account-name))\n\n;; Before swap: no-name-yet\n;; After swap: CFD","author":{"login":"EfrainBergillos","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/9882960?v=3"},"created-at":1421365692915,"updated-at":1421365692915,"_id":"54b851bce4b081e022073c17"},{"body":";; ClojureScript: Log the new value of the ref to console whenever it changes\n\n(def a (atom nil))\n\n(add-watch a :logger #(-> %4 clj->js js/console.log))\n\n(reset! a (my-app/initial-state))","author":{"login":"jkxyz","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10171367?v=3"},"created-at":1434457905527,"updated-at":1434458524720,"editors":[{"login":"jkxyz","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10171367?v=3"}],"_id":"55801731e4b01ad59b65f4f7"}],"notes":[{"author":{"login":"hura","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/671872?v=3"},"updated-at":1438348899904,"created-at":1438348899904,"body":"One \"gotcha\" is that atoms `add-watch`es do not always guarantee order semantics. So if you have a watch put `[old-val new-val]` on a channel, and your atom operation is something like `(swap! a inc)`, you may see values in your channel like this:\n\n```\n[0 1]\n[2 3]\n[1 2]\n[3 4]\n[6 7]\n[4 5]\n```\n\nThis is because the watches are dispatched in different threads.\n\n[Source](https://groups.google.com/d/msg/clojure/RI1Pq3E3188/YyqyGq36f1oJ)","_id":"55bb7663e4b03580923b00db"}],"arglists":["reference key fn"],"doc":"Adds a watch function to an agent/atom/var/ref reference. The watch\n fn must be a fn of 4 args: a key, the reference, its old-state, its\n new-state. Whenever the reference's state might have been changed,\n any registered watches will have their functions called. The watch fn\n will be called synchronously, on the agent's thread if an agent,\n before any pending sends if agent or ref. Note that an atom's or\n ref's state may have changed again prior to the fn call, so use\n old/new-state rather than derefing the reference. Note also that watch\n fns may be called from multiple threads simultaneously. Var watchers\n are triggered only by root binding changes, not thread-local\n set!s. Keys must be unique per reference, and can be used to remove\n the watch with remove-watch, but are otherwise considered opaque by\n the watch mechanism.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/add-watch"},{"added":"1.0","ns":"clojure.core","name":"not-every?","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1315793146000,"author":{"login":"wdkrnls","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/6d08a2f792f289b95fe1d982d4133d71?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"every?","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b10"},{"created-at":1315793156000,"author":{"login":"wdkrnls","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/6d08a2f792f289b95fe1d982d4133d71?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"not-any?","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b11"},{"created-at":1315793166000,"author":{"login":"wdkrnls","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/6d08a2f792f289b95fe1d982d4133d71?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"some","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b12"}],"line":2701,"examples":[{"author":{"login":"dpritchett","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/147981?v=3"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":"user=> (not-every? odd? '(1 2 3))\ntrue\nuser=> (not-every? odd? '(1 3))\nfalse","created-at":1279074566000,"updated-at":1332950344000,"_id":"542692ccc026201cdc326c92"}],"notes":null,"tag":"java.lang.Boolean","arglists":["pred coll"],"doc":"Returns false if (pred x) is logical true for every x in\n coll, else true.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/not-every_q"},{"added":"1.0","ns":"clojure.core","name":"class?","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1357883124000,"author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"to-var":{"ns":"clojure.core","name":"class","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f40"}],"line":5496,"examples":[{"author":{"login":"dakrone","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bcacd00a7f05c4772329cf9f446c7987?r=PG&default=identicon"},"editors":[],"body":"user=> (class? 1)\nfalse\n\nuser=> (class? java.lang.String)\ntrue\n\nuser=> (class? [])\nfalse","created-at":1286508711000,"updated-at":1286508711000,"_id":"542692cac026201cdc326b16"}],"notes":null,"arglists":["x"],"doc":"Returns true if x is an instance of Class","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/class_q"},{"added":"1.0","ns":"clojure.core","name":"rem","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1305751179000,"author":{"login":"Kototama","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a54a4dc204925d397ca010b9a332e74d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"quot","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521de4"},{"created-at":1305751201000,"author":{"login":"Kototama","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a54a4dc204925d397ca010b9a332e74d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"mod","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521de5"}],"line":1283,"examples":[{"author":{"login":"dpritchett","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/147981?v=3"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":"user=> (rem 10 9)\n1\nuser=> (rem 2 2)\n0","created-at":1279071638000,"updated-at":1332952568000,"_id":"542692c8c026201cdc3269df"},{"updated-at":1705708321782,"created-at":1314221509000,"body":";; rem and mod are commonly used to get the remainder.\n;; mod means Knuth's mod (truncating towards negativity). \n;; rem implements ANSI C's % operator\n;; Absolute value stays the same, always the distance\n;; towards zero.\n;; sign depends on dividend. \n\n\nuser=> (rem -10 3)\n-1\nuser=> (rem 10 -3)\n1\nuser=> (rem -10 -3)\n-1\nuser=> (rem 10 3)\n1\n\nuser=> (mod -10 3)\n2\nuser=> (mod 10 -3)\n-2\nuser=> (mod -10 -3)\n-1","editors":[{"avatar-url":"https://www.gravatar.com/avatar/f764e6667c2664b9979227fc40be024e?r=PG&default=identicon","account-source":"clojuredocs","login":"popopome"},{"avatar-url":"https://www.gravatar.com/avatar/f764e6667c2664b9979227fc40be024e?r=PG&default=identicon","account-source":"clojuredocs","login":"popopome"},{"avatar-url":"https://avatars.githubusercontent.com/u/263299?v=2","account-source":"github","login":"zw"},{"avatar-url":"https://avatars.githubusercontent.com/u/466333?v=3","account-source":"github","login":"num1"},{"login":"Shinkenjoe","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/7660326?v=4"},{"avatar-url":"https://avatars2.githubusercontent.com/u/2888536?v=4","account-source":"github","login":"xiechao06"},{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/2fa4c391db0d2d1744cc2cd0d787dd3d?r=PG&default=identicon","account-source":"clojuredocs","login":"OnesimusUnbound"},"_id":"542692c8c026201cdc3269e1"}],"notes":null,"arglists":["num div"],"doc":"remainder of dividing numerator by denominator.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/rem"},{"added":"1.2","ns":"clojure.core","name":"agent-error","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1329375490000,"author":{"login":"Claj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5fd658a8d2ef549071cb5286b1b874aa?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"agent","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e79"},{"created-at":1329375495000,"author":{"login":"Claj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5fd658a8d2ef549071cb5286b1b874aa?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"restart-agent","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e7a"},{"created-at":1329375504000,"author":{"login":"Claj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5fd658a8d2ef549071cb5286b1b874aa?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"set-error-handler!","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e7b"}],"line":2186,"examples":[{"author":{"login":"Claj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5fd658a8d2ef549071cb5286b1b874aa?r=PG&default=identicon"},"editors":[],"body":"(def tdate (agent (java.util.Date.)))\n\n@tdate\n=> #\n\n(send tdate inc) ;;this has no meaning, rendering a (silent) error\n\n(agent-error tdate)\n=> #","created-at":1329375525000,"updated-at":1329375525000,"_id":"542692d1c026201cdc326f48"}],"notes":null,"arglists":["a"],"doc":"Returns the exception thrown during an asynchronous action of the\n agent if the agent is failed. Returns nil if the agent is not\n failed.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/agent-error"},{"added":"1.0","ns":"clojure.core","name":"some","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1302013833000,"author":{"login":"pauldoo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5cb916d3c8abc9f45a093209e72489fb?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"every?","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b19"},{"created-at":1314584649000,"author":{"login":"shockbob","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"not-any?","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b1a"},{"created-at":1333669222000,"author":{"login":"Radford Smith","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/7db5c7bf2289ca4da17da34aef761283?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"keep","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b1b"},{"created-at":1333669233000,"author":{"login":"Radford Smith","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/7db5c7bf2289ca4da17da34aef761283?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"keep-indexed","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b1c"},{"created-at":1374512423000,"author":{"login":"alilee","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2fb0196dc5a7cd3a5cc73f1b9941c209?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"some-fn","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b1d"},{"created-at":1436882896023,"author":{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/94482?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"some->","ns":"clojure.core"},"_id":"55a517d0e4b020189d740552"},{"created-at":1550596421868,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"contains?","ns":"clojure.core"},"_id":"5c6c3945e4b0ca44402ef697"},{"created-at":1550597894678,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"some?","ns":"clojure.core"},"_id":"5c6c3f06e4b0ca44402ef698"},{"created-at":1550597965635,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"if-some","ns":"clojure.core"},"_id":"5c6c3f4de4b0ca44402ef699"},{"created-at":1550597978829,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"when-some","ns":"clojure.core"},"_id":"5c6c3f5ae4b0ca44402ef69a"}],"line":2709,"examples":[{"author":{"login":"dpritchett","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/147981?v=3"},"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"},{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"}],"body":";; 2 is even, so `some` stops there, 3 and 4 are never tested\n(some even? '(1 2 3 4))\n;;=> true\n\n;; they are all odd, so not true, i.e. nil\n(some even? '(1 3 5 7))\n;;=> nil","created-at":1279071879000,"updated-at":1423276722153,"_id":"542692c6c026201cdc32693b"},{"author":{"login":"devijvers","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/81018e4231ac1ce8b7a9e6d377092656?r=PG&default=identicon"},"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"}],"body":"(some true? [false false false])\n;;=> nil\n\n(some true? [false true false])\n;;=> true\n\n(some true? [true true true])\n;;=> true\n","created-at":1279402782000,"updated-at":1412977043756,"_id":"542692c6c026201cdc32693c"},{"author":{"login":"MrHus","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/22608?v=4"},"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"},{"login":"Okwori","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/16775439?v=4"}],"body":"(some #(= 5 %) [1 2 3 4 5])\n;;=> true\n\n(some #(= 5 %) [6 7 8 9 10])\n;;=> nil\n\n(some #(not= 5 %) [1 2 3 4 5])\n;;=> true\n\n(some #(not= 5 %) [6 7 8 9 10])\n;;=> true","created-at":1279415908000,"updated-at":1628796580693,"_id":"542692c6c026201cdc32693d"},{"author":{"login":"jamesqiu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bc1268deaa7f2e78fe2b5ea76e6481d8?r=PG&default=identicon"},"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":";; the first logical true value is returned, i.e. anything but nil and false\n;; when return nil if its predicate is logical false.\n(some #(when (even? %) %) '(1 2 3 4))\n;;=> 2","created-at":1297541384000,"updated-at":1421346805315,"_id":"542692c6c026201cdc32693e"},{"author":{"login":"shockbob","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon"},"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"},{"avatar-url":"https://avatars1.githubusercontent.com/u/636991?v=4","account-source":"github","login":"edgardini"}],"body":";; a hash acts as a function returning nil when the\n;; key is not present and the key value otherwise.\n(some {2 \"two\" 3 \"three\"} [nil 3 2])\n;;=> \"three\"\n\n;; there is nothing special about the 'nil' in the collection,\n;; it is still being used as a key to find its corresponding value in the hash.\n(some {nil \"nothing\" 2 \"two\" 3 \"three\"} [nil 3 2])\n;;=> \"nothing\"\n\n;; the hash (as function) returns a nil for the key of '3',\n;; therefore 'some' keeps inspecting the collection,\n;; returning the next logical true value.\n(some {2 \"two\" 3 nil} [nil 3 2])\n;;=> \"two\"","created-at":1310849563000,"updated-at":1587274820037,"_id":"542692c6c026201cdc32693f"},{"updated-at":1688285065877,"created-at":1314584832000,"body":";; `some` can be used in place of `(first (filter ...))` in most cases.\n(first (filter even? [1 2 3 4]))\n;;=> 2\n\n;; `some` returns exactly one item or `nil` if nothing is found.\n(some #(when (even? %) %) [1 2 3 4])\n;;=> 2\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3","account-source":"github","login":"phreed"},{"login":"finalfantasia","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2316604?v=4"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon","account-source":"clojuredocs","login":"shockbob"},"_id":"542692c6c026201cdc326940"},{"updated-at":1617899114358,"created-at":1314782258000,"body":";; find whether a word is in a list of words.\n(def word \"foo\")\n(def words [\"bar\" \"baz\" \"foo\" \"\"])\n(some (partial = word) words)\n;;=> true","editors":[{"avatar-url":"https://www.gravatar.com/avatar/34f159f89cbd1d9beac0276f5a7af552?r=PG&default=identicon","account-source":"clojuredocs","login":"uvtc"},{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2","account-source":"github","login":"phreed"},{"login":"rsangar1","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10330856?v=4"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon","account-source":"clojuredocs","login":"gstamp"},"_id":"542692c6c026201cdc326941"},{"author":{"login":"devn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3"},"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"},{"login":"rsangar1","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10330856?v=4"}],"body":";; here we see sets being used as a predicate\n;; the first member of the collection that appears in the set is returned\n\n(some #{2} (range 0 10)) ;;=> 2\n(some #{6 2 4} (range 0 10)) ;;=> 2\n(some #{2 4 6} (range 3 10)) ;;=> 4\n(some #{200} (range 0 10)) ;;=> nil\n\n","created-at":1362705803000,"updated-at":1617899235932,"_id":"542692d5c026201cdc32708a"},{"editors":[{"login":"adamdavislee","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8780347?v=4"}],"updated-at":1711067153402,"created-at":1421347932889,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3","account-source":"github","login":"phreed"},"body":";; Be careful—`nil` or `false` can occasionally be returned on success\n(some #{nil} [1 nil 2 false 3])\n;;=> nil\n\n;; If you are testing for the presence of `nil` in a collection\n(some nil? [1 nil 2 false 3])\n;;=> true\n\n;; If you are testing for the presence of `false` in a collection\n(some false? [1 nil 2 false 3])\n;;=> true\n\n;; If you are testing for the presence of \"falsey\" in a collection\n(some not [1 nil 2 false 3])\n;;=> true\n","_id":"54b80c5ce4b0e2ac61831cb9"},{"body":";; if you have a case where the predicate arguments are fixed/known, \n;; but the predicate function isn't:\n;; coll can supply the predicate function instead of the predicate arguments\n\n;; define the function 'not equal' (ne)\n(defn ne [n1 n2] (not= n1 n2))\n;;=> #'user/ne\n\n(some #(% 3 7) (list ne))\n;;=>true\n\n(some #(% 3 3) (list ne))\n;;=>nil\n\n\n","author":{"login":"qsys","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2430465?v=3"},"created-at":1428947077779,"updated-at":1428947719382,"editors":[{"login":"qsys","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2430465?v=3"}],"_id":"552c0085e4b01bb732af0a7d"},{"body":";; extending the previous example: supplying multiple functions.\n(defn ne [n1 n2] (not= n1 n2)) \n;;=> #'user/ne\n\n;; function to check if the sum is less than 'limit'\n(defn sumlt [limit n1 n2] (> limit (+ n1 n2))) \n;;=>'user/sumlt\n\n(some #(% 3 7) (list ne #(sumlt 10 %1 %2))) \n;;=>true\n\n(some #(% 3 3) (list ne #(sumlt 10 %1 %2))) \n;;=>true\n\n(some #(% 7 7) (list ne #(sumlt 10 %1 %2))) \n;;=>nil\n\n;; same, but one of the functions returns a value instead a boolean.\n(some #(% 3 7) (list ne (fn [n1 n2] (+ n1 n2)))) \n;;=>true\n\n(some #(% 7 7) (list ne (fn [n1 n2] (+ n1 n2)))) \n;;=>14\n\n;; the importance of order of the function list.\n(some #(% 7 7) (list ne #(sumlt 10 %1 %2) (fn [n1 n2] (+ n1 n2)))) \n;;=>14\n\n(some #(% 7 7) (list ne (fn [n1 n2] (+ n1 n2)) #(sumlt 10 %1 %2))) \n;;=>14\n\n(some #(% 3 3) (list ne #(sumlt 10 %1 %2) (fn [n1 n2] (+ n1 n2)))) \n;;=>true\n\n(some #(% 3 3) (list ne (fn [n1 n2] (+ n1 n2)) #(sumlt 10 %1 %2))) \n;;=>6\n","author":{"login":"qsys","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2430465?v=3"},"created-at":1428947310117,"updated-at":1428948227036,"editors":[{"login":"qsys","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2430465?v=3"}],"_id":"552c016ee4b033f34014b76d"},{"updated-at":1446612111804,"created-at":1446612111804,"author":{"login":"Art-B","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1143795?v=3"},"body":";;if you want to return the element the caused the predicate to return true\n;;use the \"and\" function on the predicate and the argument:\n\n(some #(and (even? %) %) [1 3 5 7 8 2])\n;;=> 8","_id":"56398c8fe4b0290a56055d1b"},{"updated-at":1543509450658,"created-at":1543509450658,"author":{"login":"aviflax","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/141844?v=4"},"body":";; As an alternative to the above usage of `and`, I prefer to use `if`\n;; in such cases; I think it’s slightly clearer:\n\n(some #(if (even? %) %) [1 3 5 7 8 2])\n;;=> 8","_id":"5c0015cae4b0ca44402ef5d1"},{"updated-at":1626283719651,"created-at":1626283719651,"author":{"login":"humorless","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/3061798?v=4"},"body":";; `some` can be an alternative for `apply or`\n(def v [nil false 5 nil 7])\n\n;; (apply or v)\n;; java runtime exception because or is macro\n\n(some identity v)\n;;=> 5\n\n;; Source - lamdaisland episode\n;; https://lambdaisland.com/episodes/clojure-core-some","_id":"60ef1ec7e4b0b1e3652d7517"},{"updated-at":1738861481173,"created-at":1738861481173,"author":{"login":"JpOnline","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2047803?v=4"},"body":"(defn get-pred\n \"Returns the first element of coll that satisfies the predicate f. \n A behavior you'd expect from a typical 'find' function.\"\n [f coll]\n (some #(when (f %) %) coll))\n\nuser=> (get-pred #(> (count %) 5)\n [\"a\" \"b\" \"the answer\" \"wrong\"])\n;;=> \"the answer\"","_id":"67a4eba9cd84df5de54e2078"}],"notes":[{"updated-at":1351243602000,"body":"Be careful about using sets as predicates if you don't know what is in the set.\r\nIn particular,
    (#{nil} nil)
    is
    nil
    and
    (#{false} false)
    is
    false
    Consider using
    contains?
    instead.","created-at":1351243602000,"author":{"login":"Sgeo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bf4e0e4e4f0b1f703b1372a8dd7b0735?r=PG&default=identicon"},"_id":"542692edf6e94c6970521ff3"}],"arglists":["pred coll"],"doc":"Returns the first logical true value of (pred x) for any x in coll,\n else nil. One common idiom is to use a set as pred, for example\n this will return :fred if :fred is in the sequence, otherwise nil:\n (some #{:fred} coll)","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/some"},{"added":"1.1","ns":"clojure.core","name":"future-cancelled?","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"to-var":{"library-url":"https://github.com/clojure/clojure","name":"future","ns":"clojure.core"},"author":{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},"created-at":1339251909000,"_id":"542692eaf6e94c6970521aa0"},{"to-var":{"library-url":"https://github.com/clojure/clojure","name":"future?","ns":"clojure.core"},"author":{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},"created-at":1339251915000,"_id":"542692eaf6e94c6970521aa1"},{"to-var":{"library-url":"https://github.com/clojure/clojure","name":"future-cancel","ns":"clojure.core"},"author":{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},"created-at":1339251923000,"_id":"542692eaf6e94c6970521aa2"},{"to-var":{"library-url":"https://github.com/clojure/clojure","name":"future-done?","ns":"clojure.core"},"author":{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},"created-at":1339251931000,"_id":"542692eaf6e94c6970521aa3"}],"line":7153,"examples":[{"updated-at":1339251900000,"created-at":1339251900000,"body":"user=> (def f (future (inc 0))) \n#'user/f\n\nuser=> (future-cancel f) \nfalse\n\nuser=> (future-cancelled? f)\nfalse\n\nuser=> (future-done? f) \ntrue\n\nuser=> @f \n1\n","editors":[],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},"_id":"542692d3c026201cdc326fb5"},{"updated-at":1339252110000,"created-at":1339252110000,"body":"user=> (def f (future (Thread/sleep 5000) (inc 0)))\n#'user/f\n\nuser=> (future-cancel f) \ntrue\n\nuser=> (future-cancelled? f) \ntrue\n\nuser=> (future-done? f) \ntrue\n\nuser=> @f \njava.util.concurrent.CancellationException (NO_SOURCE_FILE:0)","editors":[],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},"_id":"542692d3c026201cdc326fb6"}],"notes":null,"arglists":["f"],"doc":"Returns true if future f is cancelled","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/future-cancelled_q"},{"added":"1.0","ns":"clojure.core","name":"memfn","file":"clojure/core.clj","type":"macro","column":1,"see-alsos":null,"line":3897,"examples":[{"author":{"login":"nipra","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/142529?v=3"},"editors":[{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"vmfhrmfoaj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7251822?v=4"}],"body":"user=> (def *files* (file-seq (java.io.File. \"/tmp/\")))\n#'user/*files*\nuser=> (count (filter (memfn isDirectory) *files*))\n68\nuser=> (count (filter #(.isDirectory %) *files*))\n68\nuser=> (count (filter java.io.File/.isDirectory *files*)) ; Clojure 1.12 or higher\n68\n","created-at":1279241437000,"updated-at":1778890371251,"_id":"542692cac026201cdc326b0d"},{"editors":[{"login":"bsima","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/200617?v=3"}],"updated-at":1447790514365,"created-at":1434489283413,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/519370?v=3","account-source":"github","login":"emidln"},"body":"user=> ;; you must pass arguments to your method to add up to the expected arity\n\nuser=> (def starts-with (memfn startsWith prefix))\n#'user/starts-with\nuser=> (starts-with \"pikachu\" \"pika\")\ntrue\nuser=> (starts-with \"pikachu\" \"bulba\")\nfalse","_id":"558091c3e4b03e2132e7d199"},{"updated-at":1532986210979,"created-at":1532986210979,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"body":"(set! *warn-on-reflection* true)\n\n;; memfn is inherently subject to reflective calls\n\n(time (dotimes [n 100000] (mapv (memfn toLowerCase) [\"A\" \"B\" \"C\"])))\n;; Reflection warning, call to toLowerCase can't be resolved\n;; \"Elapsed time: 794.081758 msecs\"\n\n;; But accepts and propagate type hints to avoid it\n\n(time (dotimes [n 100000] (mapv (memfn ^String toLowerCase) [\"A\" \"B\" \"C\"])))\n;; \"Elapsed time: 33.708462 msecs\"","_id":"5b5f8362e4b00ac801ed9e3d"}],"macro":true,"notes":null,"arglists":["name & args"],"doc":"Expands into code that creates a fn that expects to be passed an\n object and any args and calls the named instance method on the\n object passing the args. Use when you want to treat a Java method as\n a first-class fn. name may be type-hinted with the method receiver's\n type in order to avoid reflective calls.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/memfn"},{"added":"1.9","ns":"clojure.core","name":"neg-int?","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1495640945095,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"pos-int?","ns":"clojure.core"},"_id":"5925ab71e4b093ada4d4d732"},{"created-at":1495640949709,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"nat-int?","ns":"clojure.core"},"_id":"5925ab75e4b093ada4d4d733"},{"created-at":1495705357040,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"int?","ns":"clojure.core"},"_id":"5926a70de4b093ada4d4d74f"}],"line":1428,"examples":[{"updated-at":1495703597089,"created-at":1495703597089,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"body":"(neg-int? -1)\n;;=> true\n(neg-int? -9223372036854775808)\n;;=> true\n\n;;;; false for non-negative values\n\n(neg-int? 0)\n;;=> false\n(neg-int? 1)\n;;=> false\n\n;;;; false for decimal values\n\n(neg-int? -1.0)\n;;=> false\n(neg-int? -1/2)\n;;=> false\n\n;;;; false for BigInt values\n\n(neg-int? -1N)\n;;=> false\n(neg-int? -9223372036854775809)\n;;=> false","_id":"5926a02de4b093ada4d4d74a"}],"notes":null,"arglists":["x"],"doc":"Return true if x is a negative fixed precision integer","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/neg-int_q"},{"added":"1.0","ns":"clojure.core","name":"struct-map","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1283400432000,"author":{"login":"james","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/4b163432c99a124feee4be046a3f9d66?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"struct","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c56"}],"line":4078,"examples":[{"author":{"login":"james","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/4b163432c99a124feee4be046a3f9d66?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":";; create a new struct type\n(defstruct s :1 :2)\n#'user/s\n\nuser=> (type s)\nclojure.lang.PersistentStructMap$Def\n\n;; create an instance of this new struct type\n(def s1 (struct s \"one\" \"two\"))\n#'user/s1\n\nuser=> (println s1)\n{:1 \"one\", :2 \"two\"}\n\nuser=> (type s1)\nclojure.lang.PersistentStructMap\n\n;; create a new struct instance that is based on the previous struct type\n;; with the option of supplying a new key/value pairs\n(def s2 (struct-map s :3 \"three\"))\n#'user/s2\n\nuser=> (println s2)\n{:1 nil, :2 nil, :3 \"three\"}\n\nuser=> (type s2)\nclojure.lang.PersistentStructMap\n","created-at":1283401838000,"updated-at":1285488890000,"_id":"542692ccc026201cdc326c94"},{"updated-at":1473936902003,"created-at":1473936902003,"author":{"login":"PetrGlad","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/124476?v=3"},"body":";; Map -> struct\n(defstruct S :db)\n(into (struct-map S) {:db \"db\" :name \"Grut\"})","_id":"57da7e06e4b0709b524f04fa"}],"notes":null,"arglists":["s & inits"],"doc":"Returns a new structmap instance with the keys of the\n structure-basis. keyvals may contain all, some or none of the basis\n keys - where values are not supplied they will default to nil.\n keyvals can also contain keys not in the basis.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/struct-map"},{"added":"1.0","ns":"clojure.core","name":"drop","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1288872301000,"author":{"login":"jartur","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8eae7b45fd8d383bc1a49e24bee51c9b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"take","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521c99"},{"created-at":1288872352000,"author":{"login":"jartur","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8eae7b45fd8d383bc1a49e24bee51c9b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"drop-last","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521c9a"},{"created-at":1288872358000,"author":{"login":"jartur","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8eae7b45fd8d383bc1a49e24bee51c9b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"drop-while","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521c9b"},{"created-at":1306331554000,"author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"to-var":{"ns":"clojure.core","name":"nthnext","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521c9c"},{"created-at":1356088859000,"author":{"login":"TimMc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5d532e51427ef2f4ded31aaca16c8baf?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"nthrest","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521c9d"}],"line":2926,"examples":[{"author":{"login":"zmila","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/68dd6f50915854aa04fefcf4d6fa5c8e?r=PG&default=identicon"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":";; although negative (or zero) drop-item-counts are accepted they do nothing\n(drop -1 [1 2 3 4])\n;;=> (1 2 3 4) \n\n(drop 0 [1 2 3 4])\n;;=> (1 2 3 4) \n\n(drop 2 [1 2 3 4])\n;;=> (3 4) \n\n;; dropping more items than are present is allowed, and all items are dropped.\n(drop 5 [1 2 3 4])\n;;=> ()","created-at":1280344844000,"updated-at":1420736258191,"_id":"542692cec026201cdc326da3"},{"body":";; similar to subvec but lazy and with seqs\n(take 3 (drop 5 (range 1 11)))\n;;=> (6 7 8)","author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"},"created-at":1420736116932,"updated-at":1420736116932,"_id":"54aeb674e4b081e022073bf2"}],"notes":null,"arglists":["n","n coll"],"doc":"Returns a laziness-preserving sequence of all but the first n items in coll.\n Returns a stateful transducer when no collection is provided.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/drop"},{"added":"1.4","ns":"clojure.core","name":"*data-readers*","file":"clojure/core.clj","type":"var","column":1,"see-alsos":[{"created-at":1618154998966,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/20086?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"print-method","ns":"clojure.core"},"_id":"607315f6e4b0b1e3652d74c2"}],"dynamic":true,"line":7996,"examples":[{"updated-at":1618154693914,"created-at":1618154693914,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/20086?v=4"},"body":"(import '[java.net URL])\n\n;; Teaching Clojure how to read URL objects from a string\n\n(binding [*data-readers* {'url #(URL. %)}] \n (read-string \"#url \\\"file:/etc/hosts\\\"\"))\n\n;; #object[java.net.URL 0x64a8c844 \"file:/etc/hosts\"]","_id":"607314c5e4b0b1e3652d74c1"}],"notes":[{"author":{"login":"rmoehn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/311879?v=3"},"updated-at":1436316512612,"created-at":1436316512612,"body":"`clojure.edn/read` and `clojure.edn/read-string` don't look into\n`*data-readers*` in order to find the reader functions for a reader tag.\nThat's why they won't get the mappings from `data_readers.clj` either.\nSee the [note on `clojure.edn/read`](https://clojuredocs.org/clojure.edn/read)\nfor more information and a warning.","_id":"559c7360e4b00f9508fd66fa"},{"author":{"login":"raxod502","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/6559064?v=3"},"updated-at":1483727344008,"created-at":1483727344008,"body":"Note that if you're using `clojure.reader/read` instead of `clojure.core/read`, you have to bind `clojure.reader/*data-readers*` rather than `clojure.core/*data-readers*`.","_id":"586fe1f0e4b09108c8545a4a"}],"arglists":[],"doc":"Map from reader tag symbols to data reader Vars.\n\n When Clojure starts, it searches for files named 'data_readers.clj'\n and 'data_readers.cljc' at the root of the classpath. Each such file\n must contain a literal map of symbols, like this:\n\n {foo/bar my.project.foo/bar\n foo/baz my.project/baz}\n\n The first symbol in each pair is a tag that will be recognized by\n the Clojure reader. The second symbol in the pair is the\n fully-qualified name of a Var which will be invoked by the reader to\n parse the form following the tag. For example, given the\n data_readers.clj file above, the Clojure reader would parse this\n form:\n\n #foo/bar [1 2 3]\n\n by invoking the Var #'my.project.foo/bar on the vector [1 2 3]. The\n data reader function is invoked on the form AFTER it has been read\n as a normal Clojure data structure by the reader.\n\n Reader tags without namespace qualifiers are reserved for\n Clojure. Default reader tags are defined in\n clojure.core/default-data-readers but may be overridden in\n data_readers.clj, data_readers.cljc, or by rebinding this Var.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/*data-readers*"},{"added":"1.0","ns":"clojure.core","name":"nth","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1303125578000,"author":{"login":"Havvy","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e799a79441c7543be48562403411cd13?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"first","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d83"},{"created-at":1303125582000,"author":{"login":"Havvy","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e799a79441c7543be48562403411cd13?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"second","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d84"},{"created-at":1303125660000,"author":{"login":"Havvy","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e799a79441c7543be48562403411cd13?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"nthnext","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d85"},{"created-at":1389744320000,"author":{"login":"jw0","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/ca45063da41a9f3aa9028295d8b66d89?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"get","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d86"},{"created-at":1544035070645,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"take-nth","ns":"clojure.core"},"_id":"5c081afee4b0ca44402ef5dd"},{"created-at":1544035081114,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"nthrest","ns":"clojure.core"},"_id":"5c081b09e4b0ca44402ef5de"},{"created-at":1544035090445,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"rand-nth","ns":"clojure.core"},"_id":"5c081b12e4b0ca44402ef5df"}],"line":891,"examples":[{"updated-at":1433457696443,"created-at":1279417427000,"body":"; Note that nth uses zero-based indexing, so that\n; (first my-seq) <=> (nth my-seq 0)\n(def my-seq [\"a\" \"b\" \"c\" \"d\"])\n(nth my-seq 0)\n; => \"a\"\n(nth my-seq 1)\n; => \"b\"\n(nth [] 0)\n; => IndexOutOfBoundsException ...\n(nth [] 0 \"nothing found\")\n; => \"nothing found\"\n(nth [0 1 2] 77 1337)\n; => 1337","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/3272?v=3","account-source":"github","login":"morty"},{"avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3","account-source":"github","login":"Dimagog"},{"avatar-url":"https://avatars.githubusercontent.com/u/7083783?v=3","account-source":"github","login":"cloojure"}],"author":{"avatar-url":"https://avatars2.githubusercontent.com/u/22608?v=4","account-source":"github","login":"MrHus"},"_id":"542692cbc026201cdc326c10"},{"updated-at":1473696117507,"created-at":1473696117507,"author":{"login":"st-keller","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/476463?v=3"},"body":"(nth [\"last\"] -1 \"this is not perl\")\n; => \"this is not perl\"","_id":"57d6d175e4b0709b524f04f5"}],"notes":[{"author":{"login":"pesterhazy","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/106328?v=3"},"updated-at":1475067300924,"created-at":1475067300924,"body":"Rather than throwing an exception, `(nth nil n)` returns `nil` for any number `n`.","_id":"57ebbda4e4b0709b524f050f"},{"author":{"login":"beoliver","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1413969?v=4"},"updated-at":1558362123119,"created-at":1558362123119,"body":"Floats are treated as indexes `(nth [0 1] 1.9)` returns the element at index `1`. At first glance it may seem as though they are always rounded down. However due to floating point precision `(nth [0 1] 1.9999999999999999)` will raise an `IndexOutOfBoundsException`.","_id":"5ce2b80be4b0ca44402ef727"}],"arglists":["coll index","coll index not-found"],"doc":"Returns the value at the index. get returns nil if index out of\n bounds, nth throws an exception unless not-found is supplied. nth\n also works for strings, Java arrays, regex Matchers and Lists, and,\n in O(n) time, for sequences.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/nth"},{"added":"1.0","ns":"clojure.core","name":"sorted?","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1281961844000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"sorted-map","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521af9"},{"created-at":1281961850000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"sorted-set","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521afa"}],"line":6312,"examples":[{"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":"user=> (sorted? (sorted-set 5 3 1 2 4))\ntrue\nuser=> (sorted? (sorted-map :a 1 :c 3 :b 2))\ntrue\n\n;; Note you can't just pass in a collection that happens to be sorted.\nuser=> (sorted? [1 2 3 4 5])\nfalse\n","created-at":1281961832000,"updated-at":1285494525000,"_id":"542692c7c026201cdc326985"},{"author":{"login":"Alexey Tarasevich","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/43e0398b89022d32b43de4c968069312?r=PG&default=identicon"},"editors":[{"login":"Alexey Tarasevich","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/43e0398b89022d32b43de4c968069312?r=PG&default=identicon"}],"body":"=> (sorted? (sort [1 2]))\nfalse","created-at":1385847625000,"updated-at":1385847666000,"_id":"542692d5c026201cdc327097"}],"notes":null,"arglists":["coll"],"doc":"Returns true if coll implements Sorted","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/sorted_q"},{"added":"1.0","ns":"clojure.core","name":"nil?","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1365638069000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"identity","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c87"},{"created-at":1431460678381,"author":{"login":"mmavko","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1064539?v=3"},"to-var":{"ns":"clojure.core","name":"some?","library-url":"https://github.com/clojure/clojure"},"_id":"55525b46e4b01ad59b65f4ce"}],"line":438,"examples":[{"author":{"login":"dpritchett","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/147981?v=3"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"}],"body":"user=> (nil? nil)\ntrue\nuser=> (nil? 0)\nfalse\nuser=> (nil? false)\nfalse\nuser=> (nil? '())\nfalse","created-at":1279074467000,"updated-at":1423017086496,"_id":"542692c6c026201cdc326943"},{"updated-at":1514329022413,"created-at":1509054633215,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"},"body":";; as nil? is defined as \"Returns true if x is nil, false otherwise.\"\n;; and some? is defined as \"Returns true if x is not nil, false otherwise.\"\n\n;; (some? x) is just shorthand for (not (nil? x))\n;; this also means that nil? is the same as (not (some? x)) as this\n;; just expands into (not (not (nil? x))).\n\n(def nil?? (complement some?))\n;;#'user/nil??\n\n(for [x [nil 0 false [] '()]]\n (= (nil? x) (nil?? x)))\n;;=> (true true true true true)","editors":[{"avatar-url":"https://avatars2.githubusercontent.com/u/1413969?v=4","account-source":"github","login":"beoliver"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"}],"_id":"59f258a9e4b0a08026c48c78"}],"notes":null,"tag":"java.lang.Boolean","arglists":["x"],"doc":"Returns true if x is nil, false otherwise.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/nil_q"},{"added":"1.2","ns":"clojure.core","name":"extend-protocol","file":"clojure/core_deftype.clj","type":"macro","column":1,"see-alsos":[{"created-at":1336670528000,"author":{"login":"Cosmi","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/10f2eae92de67116fa98d06ec55fcf29?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"extend","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b0a"},{"created-at":1336670535000,"author":{"login":"Cosmi","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/10f2eae92de67116fa98d06ec55fcf29?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"extend-type","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b0b"},{"created-at":1351471414000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"defprotocol","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b0c"}],"line":880,"examples":[{"updated-at":1489086655613,"created-at":1298553541000,"body":"(defprotocol XmlNode\n (as-xml [this]))\n\n(defrecord User [^Integer id ^String name ^java.util.Date dob])\n\n;; Protocols can be extended to existing types and user defined types\n(extend-protocol XmlNode\n Integer\n (as-xml [this] (str this))\n String\n (as-xml [this] (identity this))\n java.util.Date\n (as-xml [this] (-> (java.text.SimpleDateFormat. \"yyyy-MM-dd HH:mm:ss\")\n (.format this)))\n User\n (as-xml [this] (str \"\"\n \"\" (as-xml (:id this)) \"\"\n \"\" (as-xml (:name this)) \"\"\n \"\" (as-xml (:dob this)) \"\"\n \"\")))","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/1837?v=2","account-source":"github","login":"bmabey"},{"login":"Akeboshiwind","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/8889986?v=3"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/696a8f13a7fcf0b4265fe801f18ba7b5?r=PG&default=identicon","account-source":"clojuredocs","login":"kevinjqiu"},"_id":"542692cdc026201cdc326d08"}],"macro":true,"notes":null,"arglists":["p & specs"],"doc":"Useful when you want to provide several implementations of the same\n protocol all at once. Takes a single protocol and the implementation\n of that protocol for one or more types. Expands into calls to\n extend-type:\n\n (extend-protocol Protocol\n AType\n (foo [x] ...)\n (bar [x y] ...)\n BType\n (foo [x] ...)\n (bar [x y] ...)\n AClass\n (foo [x] ...)\n (bar [x y] ...)\n nil\n (foo [x] ...)\n (bar [x y] ...))\n\n expands into:\n\n (do\n (clojure.core/extend-type AType Protocol \n (foo [x] ...) \n (bar [x y] ...))\n (clojure.core/extend-type BType Protocol \n (foo [x] ...) \n (bar [x y] ...))\n (clojure.core/extend-type AClass Protocol \n (foo [x] ...) \n (bar [x y] ...))\n (clojure.core/extend-type nil Protocol \n (foo [x] ...) \n (bar [x y] ...)))","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/extend-protocol"},{"added":"1.0","ns":"clojure.core","name":"split-at","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1314290653000,"author":{"login":"Havvy","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e799a79441c7543be48562403411cd13?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"split-with","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f61"},{"created-at":1314291163000,"author":{"login":"Havvy","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e799a79441c7543be48562403411cd13?r=PG&default=identicon"},"to-var":{"ns":"clojure.string","name":"split","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f62"},{"created-at":1665533548834,"author":{"login":"mdave16","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/15642321?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"subvec","ns":"clojure.core"},"_id":"6346066ce4b0b1e3652d7677"}],"line":3008,"examples":[{"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"}],"body":"user=> (split-at 2 [1 2 3 4 5])\n[(1 2) (3 4 5)]\n\nuser=> (split-at 3 [1 2])\n[(1 2) ()]","created-at":1281512425000,"updated-at":1423277558140,"_id":"542692c9c026201cdc326af7"},{"editors":[{"login":"calebwebster","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/61309806?v=4"}],"body":"user=> (let [[first-half second-half] (split-at 3 [1 2 3 4 5 6])] first-half)\n(1 2 3)","author":{"avatar-url":"https://avatars.githubusercontent.com/u/61309806?v=4","account-source":"github","login":"calebwebster"},"created-at":1682641999924,"updated-at":1682642529546,"_id":"644b144fe4b08cf8563f4ba3"},{"updated-at":1689932824742,"created-at":1689932824742,"author":{"login":"flipsi","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/6862899?v=4"},"body":"user=> (split-at 2 [:a :b :c :d])\n[(:a :b) (:c :d)]\n","_id":"64ba5418e4b08cf8563f4bd5"}],"notes":null,"arglists":["n coll"],"doc":"Returns a vector of [(take n coll) (drop n coll)]","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/split-at"},{"added":"1.0","ns":"clojure.core","name":"*e","file":"clojure/core.clj","type":"var","column":1,"see-alsos":[{"created-at":1334156010000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.repl","name":"pst","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521ad3"}],"dynamic":true,"line":6360,"examples":[{"updated-at":1423525828173,"created-at":1281462019000,"body":"user=> (ns-refers) ;;Oops! we missed a namespace (ns-refers 'user)\n; Evaluation aborted.\n\nuser=> *e\n#","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3","account-source":"github","login":"Dimagog"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3","account-source":"github","login":"devn"},"_id":"542692c9c026201cdc326af2"}],"notes":null,"arglists":[],"doc":"bound in a repl thread to the most recent exception caught by the repl","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/*e"},{"added":"1.0","ns":"clojure.core","name":"load-reader","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1350072969000,"author":{"login":"AtKaaZ","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e10dfa345f44b0fe72bbe081fd51b83?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"load-file","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bb9"}],"line":4108,"examples":[{"author":{"login":"AtKaaZ","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e10dfa345f44b0fe72bbe081fd51b83?r=PG&default=identicon"},"editors":[],"body":"(load-reader (java.io.FileReader. \"filename.clj\"))","created-at":1350072954000,"updated-at":1350072954000,"_id":"542692d4c026201cdc326ff5"}],"notes":null,"arglists":["rdr"],"doc":"Sequentially read and evaluate the set of forms contained in the\n stream/file","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/load-reader"},{"added":"1.7","ns":"clojure.core","name":"random-sample","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1554235214583,"author":{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/94482?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"rand","ns":"clojure.core"},"_id":"5ca3bf4ee4b0ca44402ef6f8"},{"created-at":1554235230102,"author":{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/94482?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"shuffle","ns":"clojure.core"},"_id":"5ca3bf5ee4b0ca44402ef6f9"},{"created-at":1579868288317,"author":{"login":"Hindol","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/705227?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"rand-nth","ns":"clojure.core"},"_id":"5e2ae080e4b0ca44402ef821"},{"created-at":1579868294562,"author":{"login":"Hindol","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/705227?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"rand-int","ns":"clojure.core"},"_id":"5e2ae086e4b0ca44402ef822"}],"line":7865,"examples":[{"updated-at":1452115466344,"created-at":1452115466344,"author":{"login":"DanBurton","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/713692?v=3"},"body":";; The output of random-sample is a sequence.\n;; Each element of the original collection has probability \"prob\"\n;; of being included in the output sequence.\n\n(random-sample 0.5 [1 2 3 4 5])\n;;=> (1 2 4)\n\n\n;; random-sample can operate on an infinite sequence,\n;; producing an infinite sequence.\n\n(take 10 (random-sample 0.1 (repeat :foo)))\n;;=> (:foo :foo :foo :foo :foo :foo :foo :foo :foo :foo)\n\n(take 10 (random-sample 0.01 (range)))\n;;=> (57 113 281 286 352 497 727 768 957 960)","_id":"568d860ae4b0e0706e05bd9d"}],"notes":null,"arglists":["prob","prob coll"],"doc":"Returns items from coll with random probability of prob (0.0 -\n 1.0). Returns a transducer when no collection is provided.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/random-sample"},{"added":"1.5","ns":"clojure.core","name":"cond->","file":"clojure/core.clj","type":"macro","column":1,"see-alsos":[{"created-at":1411998595433,"author":{"login":"abrooks","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/69976?v=2"},"to-var":{"ns":"clojure.core","name":"cond->>","library-url":"https://github.com/clojure/clojure"},"_id":"54296383e4b09282a148f1f5"},{"created-at":1411998602440,"author":{"login":"abrooks","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/69976?v=2"},"to-var":{"ns":"clojure.core","name":"->","library-url":"https://github.com/clojure/clojure"},"_id":"5429638ae4b09282a148f1f6"},{"created-at":1411998615269,"author":{"login":"abrooks","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/69976?v=2"},"to-var":{"ns":"clojure.core","name":"->>","library-url":"https://github.com/clojure/clojure"},"_id":"54296397e4b09282a148f1f8"},{"created-at":1411998624770,"author":{"login":"abrooks","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/69976?v=2"},"to-var":{"ns":"clojure.core","name":"as->","library-url":"https://github.com/clojure/clojure"},"_id":"542963a0e4b09282a148f1f9"},{"created-at":1411998631299,"author":{"login":"abrooks","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/69976?v=2"},"to-var":{"ns":"clojure.core","name":"some->","library-url":"https://github.com/clojure/clojure"},"_id":"542963a7e4b09282a148f1fa"},{"created-at":1411998638842,"author":{"login":"abrooks","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/69976?v=2"},"to-var":{"ns":"clojure.core","name":"some->>","library-url":"https://github.com/clojure/clojure"},"_id":"542963aee4b09282a148f1fb"},{"created-at":1411998676919,"author":{"login":"abrooks","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/69976?v=2"},"to-var":{"ns":"clojure.core","name":"cond","library-url":"https://github.com/clojure/clojure"},"_id":"542963d4e4b09282a148f1fc"},{"created-at":1541446172443,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"if","ns":"clojure.core"},"_id":"5be09a1ce4b00ac801ed9eed"}],"line":7730,"examples":[{"editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2","account-source":"github","login":"phreed"},{"login":"blue0513","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8979468?v=4"}],"updated-at":1614926804893,"created-at":1413201278329,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/154699?v=2","account-source":"github","login":"avasenin"},"body":"\n(cond-> 1 ; we start with 1\n true inc ; the condition is true so (inc 1) => 2\n false (* 42) ; the condition is false so the operation is skipped\n (= 2 2) (* 3)) ; (= 2 2) is true so (* 2 3) => 6 \n;;=> 6\n;; notice that the threaded value gets used in \n;; only the form and not the test part of the clause.","_id":"543bbd7ee4b0e1a656a1ce56"},{"editors":[{"login":"bkovitz","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/4142015?v=3"},{"avatar-url":"https://avatars.githubusercontent.com/u/200617?v=3","account-source":"github","login":"bsima"}],"updated-at":1478639146955,"created-at":1414318380459,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/1724788?v=2","account-source":"github","login":"arichiardi"},"body":";; Useful when you want to conditionally evaluate expressions and thread them \n;; together. For instance, the following returns a vector containing the names \n;; (as symbols) of the implementing classes of obj.\n\n=> (defn instance->types\n [obj]\n (cond-> [] \n (instance? java.util.SortedMap obj) (conj 'SortedMap)\n (instance? java.util.AbstractMap obj) (conj 'AbstractMap)))\n#'user/instance->types\n\n=> (def hm (java.util.HashMap.))\n#'user/hm\n\n=> (instance->types hm)\n[AbstractMap]\n\n=> (def tm (java.util.TreeMap.))\n#'user/tm\n\n=> (instance->types tm)\n[SortedMap AbstractMap]","_id":"544cc92ce4b03d20a102427b"},{"updated-at":1460811298414,"created-at":1460416087314,"author":{"login":"trikitrok","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2502164?v=3"},"body":"=> (defn divisible-by? [divisor number] \n (zero? (mod number divisor)))\n#'user/divisible-by?\n\n=> (defn say [n]\n (cond-> nil\n (divisible-by? 3 n) (str \"Fizz\")\n (divisible-by? 5 n) (str \"Buzz\")\n :always (or (str n))))\n#'user/say\n\n=> (say 1)\n\"1\"\n\n=> (say 3)\n\"Fizz\"\n\n=> (say 5)\n\"Buzz\"\n\n=> (say 15)\n\"FizzBuzz\"","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/5594302?v=3","account-source":"github","login":"jwatki06"}],"_id":"570c2e57e4b0fc95a97eab4a"},{"editors":[{"login":"mhmdsalem1993","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10787314?v=3"}],"body":"(let [x 1 y 2]\n (cond-> []\n (odd? x) (conj \"x is odd\")\n (zero? (rem y 3)) (conj \"y is divisible by 3\")\n (even? y) (conj \"y is even\")))\n;=> [\"x is odd\" \"y is even\"]\n\n;;; IS Equivalent to \n\n(let [x 1 y 2]\n (as-> [] <>\n (if (odd? x)\n (conj <> \"x is odd\")\n <>)\n (if (zero? (rem y 3)) \n (conj <> \"y is divisible by 3\") \n <>)\n (if (even? y)\n (conj <> \"y is even\")\n <>)))\n;=> [\"x is odd\" \"y is even\"] ","author":{"avatar-url":"https://avatars.githubusercontent.com/u/10787314?v=3","account-source":"github","login":"mhmdsalem1993"},"created-at":1482844255361,"updated-at":1482844441856,"_id":"5862685fe4b0123d4c9dfa36"},{"updated-at":1602284044262,"created-at":1542058214210,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"body":"; Consider a code snippet that coerces any string to an integer, else noop:\n(let [x \"123\"] \n (if (string? x) \n (Integer. x) \n x))\n\n; We can reduce the repetition of `x` by using `cond->`\n(let [x \"123\"] \n (cond-> x \n (string? x) (Integer.))) ","editors":[{"avatar-url":"https://avatars0.githubusercontent.com/u/7083783?v=4","account-source":"github","login":"cloojure"}],"_id":"5be9f0e6e4b00ac801ed9ef2"},{"updated-at":1658894505969,"created-at":1658894505969,"author":{"login":"rainbyte","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/749068?v=4"},"body":";; always returns 1\n(defn f [x] 1)\n\n;; cond-> doesn't short circuit on nil\n(cond-> nil\n true f\n false inc\n true inc)\n;=> 2","_id":"62e0b8a9e4b0b1e3652d7630"},{"editors":[{"login":"daveliepmann","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/974443?v=4"}],"body":";; If most of a -> is unconditional but one step is conditional, cond-> is useful:\n\n(-> {}\n (assoc :foo \"foo\")\n (cond-> false\n (assoc :truthy true))\n (assoc :bar \"bar\"))\n;; => {:foo \"foo\", :bar \"bar\"}\n\n\n(-> {}\n (assoc :foo \"foo\")\n (cond-> true ; this is the only change from above\n (assoc :truthy true))\n (assoc :bar \"bar\"))\n;; => {:foo \"foo\", :truthy true, :bar \"bar\"}","author":{"avatar-url":"https://avatars.githubusercontent.com/u/974443?v=4","account-source":"github","login":"daveliepmann"},"created-at":1682519506133,"updated-at":1682519612025,"_id":"644935d2e4b08cf8563f4b9a"}],"macro":true,"notes":null,"arglists":["expr & clauses"],"doc":"Takes an expression and a set of test/form pairs. Threads expr (via ->)\n through each form for which the corresponding test\n expression is true. Note that, unlike cond branching, cond-> threading does\n not short circuit after the first true test expression.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/cond->"},{"added":"1.0","ns":"clojure.core","name":"dotimes","file":"clojure/core.clj","type":"macro","column":1,"see-alsos":[{"created-at":1327501844000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"repeat","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c5f"},{"created-at":1338272081000,"author":{"login":"Omer","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/dae0f434afde5246ccb030cdec81fb71?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"for","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c60"},{"created-at":1340037835000,"author":{"login":"Parijat Mishra","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e3aba44539a78ea92373418456f090e3?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"doseq","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c61"}],"line":3331,"examples":[{"author":{"login":"Brian Marick","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a523012f661f603806ab1c22d855216f?r=PG&default=identicon"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":"user=> (dotimes [n 5] (println \"n is\" n))\nn is 0\nn is 1\nn is 2\nn is 3\nn is 4\nnil","created-at":1278822115000,"updated-at":1332952709000,"_id":"542692c7c026201cdc3269c5"},{"author":{"login":"GyrosOfWar","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8abc292bf5d9e88cfcbcfbe492774a38?r=PG&default=identicon"},"editors":[{"login":"GyrosOfWar","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8abc292bf5d9e88cfcbcfbe492774a38?r=PG&default=identicon"},{"login":"GyrosOfWar","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8abc292bf5d9e88cfcbcfbe492774a38?r=PG&default=identicon"},{"login":"GyrosOfWar","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8abc292bf5d9e88cfcbcfbe492774a38?r=PG&default=identicon"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":"user=> (dotimes [n 10] \n (println (map #(* % (inc n)) (range 1 11))))\n\n(1 2 3 4 5 6 7 8 9 10)\n(2 4 6 8 10 12 14 16 18 20)\n(3 6 9 12 15 18 21 24 27 30)\n(4 8 12 16 20 24 28 32 36 40)\n(5 10 15 20 25 30 35 40 45 50)\n(6 12 18 24 30 36 42 48 54 60)\n(7 14 21 28 35 42 49 56 63 70)\n(8 16 24 32 40 48 56 64 72 80)\n(9 18 27 36 45 54 63 72 81 90)\n(10 20 30 40 50 60 70 80 90 100)\nnil","created-at":1388454361000,"updated-at":1412833684226,"_id":"542692d2c026201cdc326f94"},{"updated-at":1546681637583,"created-at":1546679853153,"author":{"login":"akhuramazda","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/46395055?v=4"},"body":"user=> (dotimes [x 8] (print x) \n (dotimes [y x] (print (get (vec \"Clojure\") y))) \n (newline))\n0\n1C\n2Cl\n3Clo\n4Cloj\n5Cloju\n6Clojur\n7Clojure\nnil\n\n;ranges with dotimes\n\n(dotimes [y 5] \n (println (map #(inc %) (range (inc y)))))\n\n(1)\n(1 2)\n(1 2 3)\n(1 2 3 4)\n(1 2 3 4 5)\nnil\n\n;factorials using ranges by dotimes\n\n(dotimes [y 5] \n (println \"factorial\" (inc y) \" = \" (apply * (map #(inc %) (range (inc y))))))\n\nfactorial 1 = 1\nfactorial 2 = 2\nfactorial 3 = 6\nfactorial 4 = 24\nfactorial 5 = 120\nnil\n","editors":[{"avatar-url":"https://avatars3.githubusercontent.com/u/46395055?v=4","account-source":"github","login":"akhuramazda"}],"_id":"5c30762de4b0ca44402ef60e"}],"macro":true,"notes":[{"author":{"login":"mars0i","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1836941?v=4"},"updated-at":1653798508777,"created-at":1653798508777,"body":"`dotimes` always returns `nil` no matter what is returned by the body the last time through the loop.","_id":"6292f66ce4b0b1e3652d75f3"}],"arglists":["bindings & body"],"doc":"bindings => name n\n\n Repeatedly executes body (presumably for side-effects) with name\n bound to integers from 0 through n-1.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/dotimes"},{"added":"1.12","ns":"clojure.core","name":"stream-seq!","file":"clojure/core.clj","type":"function","column":1,"see-alsos":null,"line":6870,"examples":null,"notes":null,"arglists":["stream"],"doc":"Takes a java.util.stream.BaseStream instance s and returns a seq of its\n contents. This is a terminal operation on the stream.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/stream-seq!"},{"added":"1.0","ns":"clojure.core","name":"select-keys","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1416824728916,"author":{"login":"alilee","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/16739?v=3"},"to-var":{"ns":"clojure.core","name":"get","library-url":"https://github.com/clojure/clojure"},"_id":"54730798e4b0dc573b892fde"},{"created-at":1470768451052,"author":{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/94482?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"keys","ns":"clojure.core"},"_id":"57aa2543e4b0bafd3e2a04d2"},{"created-at":1485972364767,"author":{"login":"yochannah","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/9271438?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"dissoc","ns":"clojure.core"},"_id":"5892238ce4b01f4add58fe36"},{"created-at":1518043231143,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"hash-map","ns":"clojure.core"},"_id":"5a7b805fe4b0316c0f44f8b0"}],"line":1555,"examples":[{"author":{"login":"Brian Marick","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a523012f661f603806ab1c22d855216f?r=PG&default=identicon"},"editors":[{"login":"Brian Marick","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a523012f661f603806ab1c22d855216f?r=PG&default=identicon"},{"login":"devijvers","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/81018e4231ac1ce8b7a9e6d377092656?r=PG&default=identicon"},{"login":"delonnewman","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10404?v=2"},{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},{"avatar-url":"https://avatars3.githubusercontent.com/u/11671382?v=4","account-source":"github","login":"dominem"}],"body":"(select-keys {:a 1 :b 2} [:a])\n;;=> {:a 1}\n\n(select-keys {:a 1 :b 2} [:a :c])\n;;=> {:a 1}\n\n(select-keys {:a 1 :b 2 :c 3} [:a :c])\n;;=> {:c 3, :a 1}","created-at":1278823330000,"updated-at":1565345504857,"_id":"542692c8c026201cdc326a0a"},{"updated-at":1445936137205,"created-at":1445936137205,"author":{"login":"nzl-nott","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/458621?v=3"},"body":"user=> (select-keys [1 2 3] [0 0 2])\n{0 1, 2 3}","_id":"562f3c09e4b04b157a6648db"},{"updated-at":1528821523346,"created-at":1528821523346,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"body":";; Extract letters at even indexes from a word into a map:\n(let [word \"hello\"] \n (select-keys (vec word) (filter even? (range (count word)))))\n;; {0 \\h, 2 \\l, 4 \\o}","_id":"5b1ff713e4b00ac801ed9e11"},{"updated-at":1596746741144,"created-at":1596746741144,"author":{"login":"wdhowe","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/4631165?v=4"},"body":";; select-keys can be useful for grabbing environment variables.\n;; it will not error or set a key to nil if some are missing.\n\n;; in the shell/terminal\nexport HTTP_PORT=8000\nexport HTTP_HOST=localhost\n\n;; in the clojure source code\n(ns myapp.core\n (:require [environ.core :as environ]))\n \n(def config (select-keys environ/env [:http-port\n :http-host\n :http-timeout]))\n\n;; notice http-timeout is omitted from the map\n(println config)\n;;=> {:http-port 8000, :http-host localhost}","_id":"5f2c6bf5e4b0b1e3652d7375"},{"updated-at":1702081256690,"created-at":1702081256690,"author":{"login":"Kaspazza","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/36607370?v=4"},"body":";; When there is no match, it will always return empty map.\n(select-keys {:a 1 :b 2 :c 3} nil)\n;;=> {}\n(select-keys {:a 1 :b 2 :c 3} [])\n;;=> {}\n(select-keys {:a 1 :b 2 :c 3} [:d])\n;;=> {}","_id":"6573b2e869fbcc0c2261747a"},{"updated-at":1717103131021,"created-at":1717103131021,"author":{"login":"E-A-Griffin","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/53583563?v=4"},"body":";; Passing nil as the first argument will return a map\n(select-keys nil [:a])\n;;=> {}\n\n;; some->/some->> is helpful if you want possibly nil arguments to stay nil\n(def x nil)\n(def y {:a 0 :b 1})\n\n(some-> x\n (select-keys [:a]))\n;;=> nil\n\n(some-> y\n (select-keys [:a]))\n;;=> {:a 0}","_id":"6658ea1b69fbcc0c226174cd"}],"notes":[{"body":"Why does `select-keys` return a map with keys in reverse order of the keyseq vector?\n\nJay Fields has a [good blog post](http://blog.jayfields.com/2011/01/clojure-select-keys-select-values-and.html) on `select-keys` with implementations of `select-values` (which is what I was really after).","created-at":1425399933187,"updated-at":1425401550961,"author":{"login":"gknapp","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/143027?v=3"},"_id":"54f5e07de4b01ed96c93c881"},{"author":{"login":"TheSeldonPlan","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/3837766?v=3"},"updated-at":1444496540091,"created-at":1444496500482,"body":"I think @gknapp is correct. `select-keys` returns a map with keys in the order of the keyseq vector. Perhaps this has changed since his comment, and the documentation needs to be updated. \n \n```clojure\nuser=> (select-keys {:a 1 :b 2 :c 3} [:a :c])\n{:a 1, :c 3}\nuser=> (select-keys {:a 1 :b 2 :c 3} [:c :a])\n{:c 3, :a 1}\n```\n\n","_id":"56194474e4b084e61c76ecc2"},{"author":{"login":"mlanza","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/39192?v=3"},"updated-at":1448375423888,"created-at":1448375423888,"body":"Wouldn't the following signature be better for partial application? \n\n (select-keys keyseq map)\n\n (def stooges [{:name \"Larry\" :birthday \"Oct 05\"} \n {:name \"Curly\" :birthday \"Jun 19\"} \n {:name \"Moe\" :birthday \"Oct 22\"}])\n\nTacit style is about consistent order (general to specific), not concision:\n\n (map (partial select-keys [:name]) stooges) ;tacit\n (map #(select-keys % [:name]) stooges)","_id":"5654747fe4b0be225c0c479d"},{"body":"If you are looking for a `select-vals` or `select-values` alternative of this function, you can do the following:\n\n
    \n(map {:a 1 :b 2 :c 3 :d 4} [:a :d])\n;;=> (1 4)\n
    ","created-at":1506607739129,"updated-at":1506607752839,"author":{"avatar-url":"https://avatars2.githubusercontent.com/u/76983?v=4","account-source":"github","login":"raszi"},"_id":"59cd027be4b03026fe14ea4c"},{"author":{"login":"hkjels","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/339547?v=4"},"updated-at":1508228053028,"created-at":1508228053028,"body":"`select-keys` will return in the order provided for `array-maps`. However, `array-maps` turn into `hash-maps` at a certain threshold, which are un-ordered. So generally, when you need certain ordering, use a sequence instead.","_id":"59e5bbd5e4b03026fe14ea92"},{"body":"VERY IMPORTANT!!!\n\n`select-keys` returns a map. Maps DO NOT guarantee ordering of their key/value pairs. If you depend on order, do not rely on `select-keys`.\n\nYou might think the order is preserved, only because maps of 8 elements or less in Clojure are implemented with an `array-map` which preserves insertion order, but maps beyond that will use a `hash-map` which does not guarantee ordering. And this is an implementation details, in future release of Clojure, the threshold or type of implementation for maps could change to any other which could even break the ordering for small maps.","created-at":1571861481277,"updated-at":1571861546570,"author":{"avatar-url":"https://avatars3.githubusercontent.com/u/601540?v=4","account-source":"github","login":"didibus"},"_id":"5db0b3e9e4b0ca44402ef7d2"}],"arglists":["map keyseq"],"doc":"Returns a map containing only those entries in map whose key is in keys","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/select-keys"},{"added":"1.0","ns":"clojure.core","name":"bit-and","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1414514292247,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"},"to-var":{"ns":"clojure.core","name":"bit-or","library-url":"https://github.com/clojure/clojure"},"_id":"544fc674e4b03d20a102428f"}],"line":1307,"examples":[{"author":{"login":"zmila","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/68dd6f50915854aa04fefcf4d6fa5c8e?r=PG&default=identicon"},"editors":[{"login":"zmila","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/68dd6f50915854aa04fefcf4d6fa5c8e?r=PG&default=identicon"},{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"}],"body":";; bits can be entered using radix notation\n;; but they are long integers so by default they\n;; display in decimal.\n(bit-and 2r1100 2r1001)\n;;=> 8\n;; 8 = 2r1000\n\n;; here we see the same bits entered in decimal\n(bit-and 12 9)\n;;=> 8","created-at":1280337486000,"updated-at":1414514260267,"_id":"542692c8c026201cdc326a70"},{"author":{"login":"Pierre","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/dc0590890ca22fee047f8e2598c2568d?r=PG&default=identicon"},"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"}],"body":";; bits can be entered in hexidecimal\n(bit-and 0x08 0xFF)\n;;=> 8\n\n;; bits can be show with Integer/toHexString\n(Integer/toHexString (bit-and 0x0108 0xFFFF))\n;;=> \"108\"","created-at":1332068603000,"updated-at":1414513918522,"_id":"542692d2c026201cdc326f57"},{"author":{"login":"Claj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5fd658a8d2ef549071cb5286b1b874aa?r=PG&default=identicon"},"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"}],"body":";; bits can also be shown with Integer/toBinaryString\n\n(Integer/toBinaryString 235)\n;;=> \"11101011\"\n\n(Integer/toBinaryString 199)\n;;=> \"11000111\"\n\n(bit-and 235 199)\n;;=> 195\n\n(Integer/toBinaryString 195)\n;;=> \"11000011\"\n\n;; 11101011 = 235\n;;& 11000111 = 199\n;;==========\n;; 11000011 = 195","created-at":1345828834000,"updated-at":1414513960925,"_id":"542692d2c026201cdc326f58"},{"body":";; here is the truth table for AND \n(Integer/toBinaryString (bit-and 2r1100 2r1010) )\n;;=> \"1000\"\n;; or 2r1000","author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"},"created-at":1414514718289,"updated-at":1414514718289,"_id":"544fc81ee4b03d20a1024295"}],"notes":null,"arglists":["x y","x y & more"],"doc":"Bitwise and","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/bit-and"},{"added":"1.9","ns":"clojure.core","name":"bounded-count","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1495640661107,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"counted?","ns":"clojure.core"},"_id":"5925aa55e4b093ada4d4d72b"}],"line":7576,"examples":[{"updated-at":1495640638447,"created-at":1495640638447,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"body":";;;; Length of a vector can be determined in constant time\n;;;; so this always returns the actual length of the vector\n\n(bounded-count 5 [1 2 3 4])\n;;=> 4\n(bounded-count 5 [1 2 3 4 5])\n;;=> 5\n(bounded-count 5 [1 2 3 4 5 6])\n;;=> 6\n\n;;;; Length of a lazy seq cannot be determined in constant time\n;;;; so this counts at most the first 5 elements\n\n(bounded-count 5 (map identity [1 2 3 4]))\n;;=> 4\n(bounded-count 5 (map identity [1 2 3 4 5]))\n;;=> 5\n(bounded-count 5 (map identity [1 2 3 4 5 6]))\n;;=> 5","_id":"5925aa3ee4b093ada4d4d72a"},{"updated-at":1495640775383,"created-at":1495640775383,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"body":";;;; This would run forever\n\n(count (range))\n\n;;;; But this doesn't\n\n(bounded-count 10000 (range))\n;;=> 10000\n","_id":"5925aac7e4b093ada4d4d72d"}],"notes":null,"arglists":["n coll"],"doc":"If coll is counted? returns its count, else will count at most the first n\n elements of coll using its seq","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/bounded-count"},{"added":"1.7","ns":"clojure.core","name":"update","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1441163795513,"author":{"login":"brunchboy","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2228869?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"update-in","ns":"clojure.core"},"_id":"55e66a13e4b0efbd681fbb91"},{"created-at":1441163918027,"author":{"login":"brunchboy","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2228869?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"fnil","ns":"clojure.core"},"_id":"55e66a8ee4b072d7f27980f8"},{"created-at":1449608873882,"author":{"login":"Chort409","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1062637?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"assoc","ns":"clojure.core"},"_id":"566746a9e4b0f47c7ec61146"},{"created-at":1570520722969,"author":{"login":"xmo-odoo","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/7571158?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"associative?","ns":"clojure.core"},"_id":"5d9c3e92e4b0ca44402ef7cb"}],"line":6251,"examples":[{"editors":[{"login":"hiteki","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2091138?v=3"},{"avatar-url":"https://avatars3.githubusercontent.com/u/11671382?v=4","account-source":"github","login":"dominem"},{"login":"dijonkitchen","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/11434205?v=4"}],"body":"(def p {:name \"James\" :age 26})\n;;=> #'user/p\n\n(update p :age inc)\n;;=> {:name \"James\", :age 27}\n\n;; remember, the value of p hasn't changed because it is immutable!\np\n;; {:name \"James\", :age 26}\n(update p :age + 10)\n;;=> {:name \"James\", :age 36}\n\n;; Here we see that the keyed object is \n;; the first argument in the function call.\n;; i.e. :age (- 26 10) => 16\n(update p :age - 10)\n;;=> {:name \"James\", :age 16}\n\n","author":{"avatar-url":"https://avatars.githubusercontent.com/u/2091138?v=3","account-source":"github","login":"hiteki"},"created-at":1437170219147,"updated-at":1587790479572,"_id":"55a97a2be4b0080a1b79cda8"},{"updated-at":1448421903787,"created-at":1448421903787,"author":{"login":"egracer","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/4086884?v=3"},"body":";; the map in update can be nil, and f will still be applied to nil and \n;; return a value\n\n(def empty-map nil)\n#'user/empty-map\n\n(update empty-map :some-key #(str \"foo\" %))\n;;=> {:some-key \"foo\"}\n","_id":"56552a0fe4b053844439827b"},{"updated-at":1476877532228,"created-at":1476877532228,"author":{"login":"G1enY0ung","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/15034155?v=3"},"body":";; can also use in []\n\nuser=> (update [1 2 3] 0 inc)\n;;=> [2 2 3]\n\nuser=> (update [] 0 #(str \"foo\" %))\n;;=> [\"foo\"]","_id":"58075cdce4b001179b66bdcf"},{"updated-at":1524433722089,"created-at":1524433722089,"author":{"login":"statcompute","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/4590938?v=4"},"body":"(def ds [{:id 1.0 :name \"name1\"}\n {:id 2.0 :name \"name2\"}\n {:id 3.0 :name \"name3\"}])\n\n(map (fn [x] (update x :name #(if (= \"name2\" %) % \"not 2\"))) ds)\n\n;; ({:id 1.0, :name \"not 2\"} {:id 2.0, :name \"name2\"} {:id 3.0, :name \"not 2\"})","_id":"5add033ae4b045c27b7fac4d"},{"editors":[{"login":"elken","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2872862?v=4"}],"body":";; From string to boolean\n\n(def answer {:answer \"France\" :correct \"true\" :age 11})\n(update answer :correct #(= % \"true\"))\n\n;; {:answer \"France\", :correct true, :age 11}","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/226965?v=4","account-source":"github","login":"aarkerio"},"created-at":1535749324652,"updated-at":1688394857769,"_id":"5b89accce4b00ac801ed9e7c"},{"updated-at":1601184024906,"created-at":1601184024906,"author":{"login":"gloorfindel","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/49351337?v=4"},"body":";; Applying a function to the same key in a sequence of arrays\n\n(def dates [{:date \"20200430\",:time \"08:35\"}\n {:date \"20200430\",:time \"09:15\"}]\n\n;; Takes the current time value in the array, and reduces it to the hour by \n;; calling the reduce-to-hour function (not included here)\n\n(map #(update % :time (constantly (reduce-to-hour (:time %)))) dates)\n=> ({:date \"20200430\", :time \"08\"} {:date \"20200430\", :time \"09\"})","_id":"5f702118e4b0b1e3652d73c2"},{"editors":[{"login":"huahaiy","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/889685?v=4"}],"body":";; Very common, update a vector inside a map\n(def little-schemer {:authors [{:birth-year 1944, :name \"Daniel Friedman\"}\n {:name \"Matthias Felleisen\"}]\n :title \"The Little Schemer\"})\n\n(update little-schemer :authors conj {:name \"Gerald J. Sussman\"})\n;;=> \n{:authors [{:birth-year 1944, :name \"Daniel Friedman\"}\n {:name \"Matthias Felleisen\"}\n {:name \"Gerald J. Sussman\"}]\n :title \"The Little Schemer\"}","author":{"avatar-url":"https://avatars.githubusercontent.com/u/889685?v=4","account-source":"github","login":"huahaiy"},"created-at":1613242096574,"updated-at":1613242234272,"_id":"60281ef0e4b0b1e3652d744f"},{"editors":[{"login":"reborg","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/20086?v=4"}],"body":";; For a simple change of value we can use constantly\n(def hm {:banana 1, :apple 2, :orange 3})\n\n(update hm :banana (constantly 6))\n;;=> {:banana 6 :apple 2 :orange 3}\n\n;; Which is equivalent to using \"assoc\"\n(assoc hm :banana 6)\n;;=> {:banana 6 :apple 2 :orange 3}","author":{"avatar-url":"https://avatars.githubusercontent.com/u/8339935?v=4","account-source":"github","login":"rogefm"},"created-at":1614089059545,"updated-at":1614426803060,"_id":"60350b63e4b0b1e3652d7466"},{"updated-at":1623859525031,"created-at":1623859525031,"author":{"login":"mars0i","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1836941?v=4"},"body":";; A quirk in use with vectors (tested with 1.10.3)\n;; If you throw away the argument to the function, you can add a value to\n;; the end of the vector: \n\n;; Normal, expected behavior:\n(update [1 2 3] 2 (fn [_] 42))\n;;=> [1 2 42]\n\n;; If the index is just past the end, you can append to the vector:\n(update [1 2 3] 3 (fn [_] 42))\n;;=> [1 2 3 42]\n\n;; More than one past end won't work\n(update [1 2 3] 4 (fn [_] 42))\n;;=> Execution error (IndexOutOfBoundsException) at user/eval2049 (form-init3979469036338260438.clj:1).\n\n;; If you don't throw away the argument, and your index is one past\n;; the end of the vector, you'll still get an error:\n\n;; Normal, expected behavior:\n(update [1 2 3] 2 inc)\n;;=> [1 2 4]\n\n;; Here the trick fails:\n(update [1 2 3] 3 inc)\n;;=> Execution error (NullPointerException) at user/eval1985 (form-init8618353961027343980.clj:1).","_id":"60ca2145e4b0b1e3652d750a"},{"updated-at":1731003583209,"created-at":1731003583209,"author":{"login":"lpasz","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/42593470?v=4"},"body":";; Will update the value by incrementing it\n(update {:a 1} :a (fn [value] (inc value)))\n;; => {:a 2}\n\n;; Will raise because there is no key with that value\n(update {} :a (fn [value] (inc value)))\n;; => Execution error (NullPointerException) at user/eval1 (REPL:1).\n;; Cannot invoke \"Object.getClass()\" because \"x\" is null \n\n;; In some languages update would provide a default value if none is found\n;; Map.update(map, key, default_value, function)\n;; Map.update(%{}, :a , 1 , & &1 + 1) => %{a: 1}\n\n;; But in Clojure, if no value is found nil is returned to the update function.\n;; So to fix that function we would need to\n(update {} :a (fn [value] (if value (inc value) 1)))\n;; => {:a 1}\n\n;; Other arguments at update level will just be passed along to your function\n\n(def dollar-rate 5.70)\n\n(defn add-funds-to-account [my-account amount coin]\n (update my-account\n :amount-in-brl\n (fn [curr-amount added-amount coin]\n (case coin\n :brl (+ added-amount curr-amount)\n :usd (+ (* dollar-rate added-amount) curr-amount))) \n amount \n coin))\n\n(add-funds-to-account {:amount-in-brl 10} 10 :brl)\n;; => {:amount-in-brl 20}\n(add-funds-to-account {:amount-in-brl 10} 10 :usd)\n;; => {:amount-in-brl 67.0} ","_id":"672d04bf69fbcc0c2261750d"}],"notes":[{"author":{"login":"alper","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/72429?v=4"},"updated-at":1576842276976,"created-at":1576842276976,"body":"But how do you do a pure update idiomatically? So update one value for another?","_id":"5dfcb424e4b0ca44402ef7fc"},{"author":{"login":"Crowbrammer","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/19522656?v=4"},"updated-at":1633061790090,"created-at":1633061790090,"body":"To the previous note (alper), you are looking for `assoc`. ","_id":"61568b9ee4b0b1e3652d754d"},{"author":{"login":"earthfail","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/21296448?v=4"},"updated-at":1661097969047,"created-at":1661097969047,"body":"in clojure 1.11 there is an [update-vals](https://github.com/clojure/clojure/blob/5ffe3833508495ca7c635d47ad7a1c8b820eab76/src/clj/clojure/core.clj#L8061) and [update-keys](https://github.com/clojure/clojure/blob/5ffe3833508495ca7c635d47ad7a1c8b820eab76/src/clj/clojure/core.clj#L8077) to apply function for all values or all keys respectively","_id":"630257f1e4b0b1e3652d7646"}],"arglists":["m k f","m k f x","m k f x y","m k f x y z","m k f x y z & more"],"doc":"'Updates' a value in an associative structure, where k is a\n key and f is a function that will take the old value\n and any supplied args and return the new value, and returns a new\n structure. If the key does not exist, nil is passed as the old value.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/update"},{"added":"1.0","ns":"clojure.core","name":"list*","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":null,"line":650,"examples":[{"author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"editors":[{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"}],"body":";; `list*` function:\nuser=> (list* 1 [2 3])\n(1 2 3)\nuser=> (list* 1 2 [3 4])\n(1 2 3 4)\n\n;; compared to regular `list` function:\nuser=> (list 1 [2 3])\n(1 [2 3])\nuser=> (list 1 2 [3 4])\n(1 2 [3 4])\n\n;; Corner cases:\nuser=> (list* nil [1 2])\n(nil 1 2)\nuser=> (list* 1 nil)\n(1)\nuser=> (list* () [1 2])\n(() 1 2)\nuser=> (list* 1 ())\n(1)\n","created-at":1280721203000,"updated-at":1306322562000,"_id":"542692c6c026201cdc3268d5"},{"updated-at":1474307619700,"created-at":1474307619700,"author":{"login":"Manishapillai","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/20270279?v=3"},"body":";;Prepend a map to a list\nuser=> (list* {:name \"Anne\"} [{:city \"NJ\"}]) \n({:name \"Anne\"} {:city \"NJ\"})","_id":"57e02623e4b0709b524f0501"},{"updated-at":1541543275442,"created-at":1496358734409,"author":{"login":"smnplk","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/380618?v=3"},"body":";; Useful if you want to get all the arguments of a function into a list (actually a seq, but that is not important)\n(defn args-to-list [a b c & args]\n (list* a b c args))\n\nuser=> (args-to-list 1 2 3 4 5 6)\n(1 2 3 4 5 6)\n\n;; same as list, but it expects the last element to be a sequence which is then unpacked \n\n;; Example usage in the wild\n(defn my-max\n ([a] a)\n ([a b] (if (> a b) a b))\n ([a b & args] (reduce my-max (list* a b args))))\n\n","editors":[{"avatar-url":"https://avatars2.githubusercontent.com/u/380618?v=4","account-source":"github","login":"smnplk"}],"_id":"59309f4ee4b06e730307db20"},{"editors":[{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"}],"body":";; `list*` function:\nuser=> (list* 1 '(2 3))\n(1 2 3)\n\nuser=> (list* 1 2 '(3 4))\n(1 2 3 4)","author":{"avatar-url":"https://avatars3.githubusercontent.com/u/153773?v=4","account-source":"github","login":"arlicle"},"created-at":1536069875312,"updated-at":1656675472111,"_id":"5b8e90f3e4b00ac801ed9e86"},{"updated-at":1673074886220,"created-at":1673074886220,"author":{"login":"Chandrama1","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/78619926?v=4"},"body":";; `list*` function:\n(list* \"Superman\" '(\"Batman\" \"Ironman\"))\n=> (\"Superman\" \"Batman\" \"Ironman\")\n\n(list* '(\"Batman\" \"Ironman\") '(\"Superman\" \"Hulk\"))\n=> ((\"Batman\" \"Ironman\") \"Superman\" \"Hulk\")\n\n(list* '(\"Batman\" \"Ironman\") \"Superman\")\n=> ((\"Batman\" \"Ironman\") \\S \\u \\p \\e \\r \\m \\a \\n)","_id":"63b918c6e4b08cf8563f4b5d"}],"notes":[{"body":"The doc string mentions returning a new list, but it should say a new sequence. Surprisingly, `list*` typically does not return an actual list. Instead, it usually returns a Cons, which works as a seq, but is not strictly a list. \n\n```\n(list? (list* 1 '(2 3)))\n;=> false\n\n(type (list* 1 '(2 3)))\n;=> clojure.lang.Cons\n\n(first (list* 1 '(2 3)))\n;=> 1\n\n(peek (list* 1 '(2 3)))\nClassCastException clojure.lang.Cons cannot be cast to clojure.lang.IPersistentStack\n\n(list? (list* '(2 3)))\n;=> true\n\n(list? (into () (list* 1 '(2 3))))\n;=> true\n```\n\nI think `seq*` would have been a better name for this function.","created-at":1425311436162,"updated-at":1425311436162,"author":{"login":"miner","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/25400?v=3"},"_id":"54f486cce4b0b716de7a652e"}],"arglists":["args","a args","a b args","a b c args","a b c d & more"],"doc":"Creates a new seq containing the items prepended to the rest, the\n last of which will be treated as a sequence.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/list*"},{"added":"1.2","ns":"clojure.core","name":"reify","file":"clojure/core_deftype.clj","type":"macro","column":1,"see-alsos":[{"created-at":1323993523000,"author":{"login":"TimMc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5d532e51427ef2f4ded31aaca16c8baf?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"proxy","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ef4"}],"line":70,"examples":[{"updated-at":1458043116563,"created-at":1315673869000,"body":"(ns foo)\n\n;;; This is a library for the shopping result.\n\n(defrecord Banana [qty])\n(defrecord Grape [qty])\n(defrecord Orange [qty])\n\n;;; 'subtotal' differs from each fruit.\n\n(defprotocol Fruit\n (subtotal [item]))\n\n(extend-type Banana\n Fruit\n (subtotal [item]\n (* 158 (:qty item))))\n\n(extend-type Grape\n Fruit\n (subtotal [item]\n (* 178 (:qty item))))\n\n(extend-type Orange\n Fruit\n (subtotal [item]\n (* 98 (:qty item))))\n\n;;; 'coupon' is the function returing a 'reify' of subtotal. This is\n;;; when someone uses a coupon ticket, the price of some fruits is \n;;; taken off 25%.\n\n(defn coupon [item]\n (reify Fruit\n (subtotal [_]\n (int (* 0.75 (subtotal item))))))\n\n;;; Example: To compute the total when someone bought 10 oranges,\n;;; 15 bananas and 10 grapes, using a coupon for the grapes.\n(apply + (map subtotal [(Orange. 10) (Banana. 15) (coupon (Grape. 10))]))\n;;; 4685 ; (apply + '(980 2370 1335))","editors":[{"avatar-url":"https://www.gravatar.com/avatar/cacfb7ecf08cb6461767e514c93b7bf9?r=PG&default=identicon","account-source":"clojuredocs","login":"yasuto"},{"avatar-url":"https://www.gravatar.com/avatar/cacfb7ecf08cb6461767e514c93b7bf9?r=PG&default=identicon","account-source":"clojuredocs","login":"yasuto"},{"avatar-url":"https://www.gravatar.com/avatar/cacfb7ecf08cb6461767e514c93b7bf9?r=PG&default=identicon","account-source":"clojuredocs","login":"yasuto"},{"avatar-url":"https://www.gravatar.com/avatar/cacfb7ecf08cb6461767e514c93b7bf9?r=PG&default=identicon","account-source":"clojuredocs","login":"yasuto"},{"avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3","account-source":"github","login":"Dimagog"},{"login":"antonaut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/513311?v=3"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/cacfb7ecf08cb6461767e514c93b7bf9?r=PG&default=identicon","account-source":"clojuredocs","login":"yasuto"},"_id":"542692cdc026201cdc326d5d"},{"author":{"login":"number23","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/89e8dc9231de751fd558d5784406cc5e?r=PG&default=identicon"},"editors":[],"body":";; Using a reified FileFilter implementation to obtain only directory files\n(.listFiles (java.io.File. \".\")\n (reify\n java.io.FileFilter\n (accept [this f]\n (.isDirectory f))))\n","created-at":1339172939000,"updated-at":1339172939000,"_id":"542692d5c026201cdc32706f"},{"author":{"login":"puredanger","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/89c8afd032c7b3473f67c9b00d3acd5a?r=PG&default=identicon"},"editors":[],"body":";;;; This example shows how to reify a multi-arity protocol function\n;;;; (note the different style in defprotocol vs reify)\n\n;; define a multi-arity protocol function blah\n(defprotocol Foo\n (blah\n [this x]\n [this x y]))\n\n;; define an anonymous extension via reify\n(def r (reify Foo \n (blah [_ x] x)\n (blah [_ x y] y)))\n\n;; invoke blah via the r instance\n(blah r 1) ;; => 1\n(blah r 1 2) ;; => 2\n\n\n","created-at":1355788930000,"updated-at":1355788930000,"_id":"542692d5c026201cdc327070"},{"body":";; Note that nested class is referred via '$' \n;; and 'this' is always present in parameters (see underscore in parameters list):\n(Thread/setDefaultUncaughtExceptionHandler\n (reify java.lang.Thread$UncaughtExceptionHandler\n (uncaughtException [_ thread throwable]\n (println (str throwable)))))","author":{"login":"PetrGlad","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/124476?v=3"},"created-at":1420462447425,"updated-at":1420462470195,"editors":[{"login":"PetrGlad","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/124476?v=3"}],"_id":"54aa896fe4b04e93c519ffb3"},{"updated-at":1440403056415,"created-at":1440377269300,"author":{"login":"yubrshen","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2638417?v=3"},"body":";;; This example is inspired by the above one and simplified\n;;; to highlight reify's returning a value/\"object\" \n;;; with protocol realization for just this one piece of value/\"object\".\n\n(ns foo)\n\n(defrecord Grape [qty])\n\n(defprotocol Fruit\n (subtotal [item]))\n\n(extend-type Grape\n Fruit\n (subtotal [item]\n (* 178 (:qty item))))\n\n;;; 'discounted' is the function returning a 'reify' instance of fruit with modified \n;;; implementation of subtotal (with discount). That is, \n;;; when someone uses a discounted coupon, the price of the fruits is taken off 25%.\n\n(defn discounted [item]\n (reify Fruit\n (subtotal [_]\n (println \"modifying subtotal with discount:\")\n (int (* 0.75 (subtotal item))))))\n\n;;; Example:\n;;; There is 10 pieces of Grape, and the subtotal before discount is\n;;; (subtotal (Grape. 10))\n;;; => 1780\n\n;;; With discount, then\n;;; (subtotal (discounted (Grape. 10)))\n;;; => modifying subtotal with discount:\n;;; => 1335\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/2638417?v=3","account-source":"github","login":"yubrshen"}],"_id":"55da69b5e4b0831e02cddf1e"},{"editors":[{"login":"Aljendro","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/7899307?v=3"}],"body":"(comment\n \"reify\n\n verb | re·ify | \\\\ˈrā-ə-ˌfī, ˈrē-\\\\\n\n : to regard (something abstract) as a material or concrete thing\")\n\n(defprotocol shape\n \"A geometric shape.\"\n\n (area [this]\n \"Calculates the area of the shape.\n\n The first argument is required and corresponds to the implicit target\n object ('this' in Java parlance).\"))\n\n\n(defn make-circle\n \"Creates a circle (a geometric shape) object.\"\n [radius]\n\n (reify shape\n (area [_]\n (* Math/PI radius radius))))\n\n(. (make-circle 8) area)\n;;=> 201.06192982974676\n\n(def circle (make-circle 8))\n\n(satisfies? shape circle)\n;;=> true\n\n(. circle area)\n;;=> 201.06192982974676\n\n\n(defn make-triangle\n \"Creates a triangle (a geometric shape) object.\"\n [base height]\n\n (reify shape\n (area [_]\n (* 0.5 base height))))\n\n(def triangle (make-triangle 8 8))\n\n(. triangle area)\n;;=> 32.0\n","author":{"avatar-url":"https://avatars.githubusercontent.com/u/19507371?v=3","account-source":"github","login":"clojureling"},"created-at":1463855829138,"updated-at":1493672301532,"_id":"5740aad5e4b00a9b70be566c"},{"updated-at":1613046786005,"created-at":1613046786005,"author":{"login":"RokLenarcic","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/3322433?v=4"},"body":";; Attaching metadata to reify object creates a new instance\n;; Reify call itself attaches metadata of (reify ...) form to the object\n;; so effectively it always creates two objects but return one of them.\n\n;; This matters when you use finalize\n\n(defn create []\n (reify Object\n (finalize [this] (println \"GCing\" this) nil)))\n\n(do (create)\n (System/gc))\n\n;;GCing #object[.$create$reify__7691 0x3b287fd2 .$create$reify__7691@3b287fd2]\n;;GCing #object[.$create$reify__7691 0x38249fdc .$create$reify__7691@38249fdc]\n;;=> nil","_id":"60252402e4b0b1e3652d744c"},{"updated-at":1669428148216,"created-at":1669428148216,"author":{"login":"huahaiy","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/889685?v=4"},"body":"(defprotocol Foo (foo-f [this]))\n(defprotocol Bar (bar-f [this]))\n\n;; It is fine to reify multiple protocol/interfaces\n(def foo-bar\n (reify\n Foo\n (foo-f [_] :foo)\n Bar\n (bar-f [_] :bar)))\n\n(foo-f foo-bar) ;;=>:foo\n(bar-f foo-bar) ;;=>:bar\n","_id":"638173b4e4b0b1e3652d7691"}],"macro":true,"notes":[{"author":{"login":"ieugen","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1050920?v=4"},"updated-at":1680326363601,"created-at":1680326363601,"body":"reify can implement multiple interfaces:\n\n```clojure\n(let [a (reify\n java.lang.AutoCloseable\n (close [_this]\n (println \"aaa\"))\n java.lang.Runnable\n (run [_this]\n (println \"Run\")))]\n (.close a)\n (.run a))\n```\n\nNote that methods in reify DO NOT accept docstrings like clojure defn's , although they look very similar. You will get compilation error with method not found if you use a docstring. \n\nSomething like this\n```\n; Evaluating file: java_map.clj\n; Syntax error (IllegalArgumentException) compiling reify* at (src/java_map.clj:27:5).\n; Can't define method not in interfaces: close\n; Evaluation of file java_map.clj failed: class clojure.lang.Compiler$CompilerException\n```","_id":"6427bedbe4b08cf8563f4b8b"},{"author":{"login":"ieugen","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1050920?v=4"},"updated-at":1684257603676,"created-at":1684257154747,"body":"Sometimes you will need to add type hints.\nThis is mandatory if there are overloaded methods. \n\nOne such case is when implementing `java.util.Collection` `toArray` .\n\nWithout type hints, you will get \n\n```\nMismatched return type: toArray, expected: [Ljava.lang.Object;, had: java.lang.Object\n```\n\nA correct way to handle this is like bellow.\n\nNote: when you add one type hint, you need to add for all methods in reify. \nSee docs above.\n```\n(reify java.util.Collection\n (^boolean containsAll [_this ^java.util.Collection c])\n (^objects toArray [_this]\n (throw (UnsupportedOperationException.)))\n (^objects toArray [_this ^objects objects]\n (throw (UnsupportedOperationException.))))\n```\n\nhttps://github.com/clojure/data.avl/commit/03f32144951ab7b50b8a74ea5e8c22629e7fbde0\n","_id":"6463b982e4b08cf8563f4bbc"}],"arglists":["& opts+specs"],"doc":"reify creates an object implementing a protocol or interface.\n reify is a macro with the following structure:\n\n (reify options* specs*)\n \n Currently there are no options.\n\n Each spec consists of the protocol or interface name followed by zero\n or more method bodies:\n\n protocol-or-interface-or-Object\n (methodName [args+] body)*\n\n Methods should be supplied for all methods of the desired\n protocol(s) and interface(s). You can also define overrides for\n methods of Object. Note that the first parameter must be supplied to\n correspond to the target object ('this' in Java parlance). Thus\n methods for interfaces will take one more argument than do the\n interface declarations. Note also that recur calls to the method\n head should *not* pass the target object, it will be supplied\n automatically and can not be substituted.\n\n The return type can be indicated by a type hint on the method name,\n and arg types can be indicated by a type hint on arg names. If you\n leave out all hints, reify will try to match on same name/arity\n method in the protocol(s)/interface(s) - this is preferred. If you\n supply any hints at all, no inference is done, so all hints (or\n default of Object) must be correct, for both arguments and return\n type. If a method is overloaded in a protocol/interface, multiple\n independent method definitions must be supplied. If overloaded with\n same arity in an interface you must specify complete hints to\n disambiguate - a missing hint implies Object.\n\n Method heads are recursion points for recur, as in a fn. The method\n bodies of reify are lexical closures, and can refer to the surrounding\n local scope:\n \n (str (let [f \"foo\"] \n (reify Object\n (toString [this] f))))\n == \"foo\"\n\n (seq (let [f \"foo\"] \n (reify clojure.lang.Seqable\n (seq [this] (seq f)))))\n == (\\f \\o \\o)\n \n reify always implements clojure.lang.IObj and transfers meta\n data of the form to the created object.\n \n (meta ^{:k :v} (reify Object (toString [this] \"foo\")))\n == {:k :v}","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/reify"},{"added":"1.0","ns":"clojure.core","name":"update-in","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1302248534000,"author":{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},"to-var":{"ns":"clojure.core","name":"assoc-in","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c66"},{"created-at":1318010541000,"author":{"login":"jks","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/de50bee3396570d25f900873303c98f1?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"get-in","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c67"},{"created-at":1348895075000,"author":{"login":"eric","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2b0c9ae6f1da9716451e7c86bc87230b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"fnil","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c68"},{"created-at":1441163870973,"author":{"login":"brunchboy","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2228869?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"update","ns":"clojure.core"},"_id":"55e66a5ee4b072d7f27980f7"},{"created-at":1570520733044,"author":{"login":"xmo-odoo","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/7571158?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"associative?","ns":"clojure.core"},"_id":"5d9c3e9de4b0ca44402ef7cc"}],"line":6235,"examples":[{"updated-at":1565345379991,"created-at":1280322066000,"body":"(def users [{:name \"James\" :age 26} {:name \"John\" :age 43}])\n;;=> #'user/users\n\n;; similar to assoc-in but does not simply replace the item.\n;; the specified function is performed on the matching item.\n;; here the age of the second (index 1) user is incremented.\n(update-in users [1 :age] inc)\n;;=> [{:name \"James\", :age 26} {:name \"John\", :age 44}]\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3","account-source":"github","login":"phreed"},{"login":"dominem","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/11671382?v=4"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon","account-source":"clojuredocs","login":"gstamp"},"_id":"542692c9c026201cdc326a9e"},{"author":{"login":"gregg-williams","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/58610a64fc8638eec8d2239d80d4046f?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"Jeff N","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/7a9dd2ab880632b999aaeff00fc0d8e2?r=PG&default=identicon"},{"login":"Jeff N","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/7a9dd2ab880632b999aaeff00fc0d8e2?r=PG&default=identicon"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"},{"avatar-url":"https://avatars.githubusercontent.com/u/2091138?v=3","account-source":"github","login":"hiteki"},{"login":"dominem","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/11671382?v=4"}],"body":"(def p {:name \"James\" :age 26})\n;;=> #'user/p\n\n(update-in p [:age] inc)\n;;=> {:name \"James\", :age 27}\n\n;; remember, the value of p hasn't changed!\n(update-in p [:age] + 10)\n;;=> {:name \"James\", :age 36}\n\n;; Here we see that the keyed object is \n;; the first argument in the function call.\n;; i.e. :age (- 26 10) => 16\n(update-in p [:age] - 10)\n;;=> {:name \"James\", :age 16}","created-at":1283780561000,"updated-at":1565345395993,"_id":"542692c9c026201cdc326aa0"},{"updated-at":1447712876892,"created-at":1305018966000,"body":"(defn char-cnt [s]\n \"Counts occurence of each character in s\"\n (reduce\n (fn [m k]\n (update-in m [k] (fnil inc 0)))\n {}\n s))\n;; Note use of fnil above \n;; - returns 0 if nil is passed to inc (avoids null pointer exception)\n\n(char-cnt \"foo-bar\")\n;;=> {\\r 1, \\a 1, \\b 1, \\- 1, \\o 2, \\f 1}\n","editors":[{"avatar-url":"https://www.gravatar.com/avatar/d1906fc5df2c8ce5b2d58cc6ea855aab?r=PG&default=identicon","account-source":"clojuredocs","login":"shuaybi"},{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3","account-source":"github","login":"phreed"},{"login":"ghiden","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/17842?v=3"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/d1906fc5df2c8ce5b2d58cc6ea855aab?r=PG&default=identicon","account-source":"clojuredocs","login":"shuaybi"},"_id":"542692c9c026201cdc326aa4"},{"author":{"login":"jamesqiu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bc1268deaa7f2e78fe2b5ea76e6481d8?r=PG&default=identicon"},"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":";; f has args\n;; The keyed value is placed as the first argument\n;; :a (/ 3 4 5) => 3/20 \n(update-in {:a 3} [:a] / 4 5)\n;;=> {:a 3/20}","created-at":1349714558000,"updated-at":1422566857659,"_id":"542692d5c026201cdc3270b1"},{"editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3","account-source":"github","login":"phreed"},{"login":"clojureman","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/1793303?v=3"}],"updated-at":1495693819157,"created-at":1412006537832,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/453580?v=2","account-source":"github","login":"pmbauer"},"body":";; be careful with that empty path sequence, it's seldom what you want\n(update-in {} [] (constantly {:k :v}))\n;;=> {nil {:k :v}}\n\n;; In general, you find that for a non-empty path\n;; (get-in (update-in m path (constantly v)) path) \n;; is equal to v.\n;; Surprisingly this does not hold true in case of an empty path.","_id":"54298289e4b09282a148f202"},{"editors":[{"login":"bkovitz","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/4142015?v=3"}],"body":";;You can use update-in in a nested map too, in order to update more than\n;;one value:\n\n(def m {:1 {:value 0, :active false}, :2 {:value 0, :active false}})\n\n(update-in m [:1] assoc :value 1 :active true)\n;;=>{:1 {:value 1, :active true}, :2 {:value 0, :active false}}","author":{"avatar-url":"https://avatars.githubusercontent.com/u/50778?v=3","account-source":"github","login":"edipofederle"},"created-at":1442182854368,"updated-at":1460718796470,"_id":"55f5f6c6e4b05246bdf20a90"},{"editors":[{"login":"gnperdue","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1294053?v=3"}],"body":";; We may dig into multiple levels with `update-in`:\n(def player1 {:name \"Player 1\" :attribs {:str 10 :int 11 :wis 9}})\n\n(update-in player1 [:attribs :str] inc)\n;; {:name \"Player 1\", :attribs {:str 11, :int 11, :wis 9}}\n\n(update-in player1 [:attribs :str] * 2)\n;; {:name \"Player 1\", :attribs {:str 20, :int 11, :wis 9}}\n\n;; We can see one level via `update`...\n\n(update player1 :attribs #(update % :str inc))\n;; {:name \"Player 1\", :attribs {:str 11, :int 11, :wis 9}}","author":{"avatar-url":"https://avatars.githubusercontent.com/u/1294053?v=3","account-source":"github","login":"gnperdue"},"created-at":1451965282908,"updated-at":1451965612224,"_id":"568b3b62e4b0e0706e05bd9b"},{"updated-at":1459182480723,"created-at":1459182480723,"author":{"login":"ertugrulcetin","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8271291?v=3"},"body":"user=> (update-in {:a {:b 3}} [:a :b] inc)\n\n;;=> {:a {:b 4}}","_id":"56f95b90e4b09295d75dbf42"},{"updated-at":1476877648099,"created-at":1476877648099,"author":{"login":"G1enY0ung","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/15034155?v=3"},"body":";; can also use in []\n\nuser=> (update-in [1 2 [1 2 3]] [2 0] inc)\n;;=> [1 2 [2 2 3]]","_id":"58075d50e4b001179b66bdd0"},{"updated-at":1514472378082,"created-at":1514472169736,"author":{"login":"jcburley","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/430319?v=4"},"body":";; can mix associative types as well\n\nuser=> (update-in [1 {:a 2 :b 3 :c 4}] [1 :c] (fnil inc 5))\n;; => [1 {:a 2, :b 3, :c 5}]\nuser=> (update-in [1 {:a 2 :b 3 :c 4}] [1 :d] (fnil inc 5))\n;; => [1 {:a 2, :b 3, :c 4, :d 6}]\n\n;; but of course vector indices must be appropriate types\n\nuser=> (update-in [1 {:a 2 :b 3 :c 4}] [:b :c] (fnil inc 5))\nIllegalArgumentException Key must be integer clojure.lang.APersistentVector.assoc (APersistentVector.java:345)","editors":[{"avatar-url":"https://avatars1.githubusercontent.com/u/430319?v=4","account-source":"github","login":"jcburley"}],"_id":"5a4502e9e4b0a08026c48ce4"},{"updated-at":1524434442870,"created-at":1524434442870,"author":{"login":"statcompute","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/4590938?v=4"},"body":"(def ds [{:id 1.0 :name \"name1\"}\n {:id 2.0 :name \"name2\"}\n {:id 3.0 :name \"name3\"}])\n\n(map (fn [x] (update-in x [:name] #(if (= \"name2\" %) % \"not 2\"))) ds)\n\n;; | :id | :name |\n;; |-----+-------|\n;; | 1.0 | not 2 |\n;; | 2.0 | name2 |\n;; | 3.0 | not 2 |\n","_id":"5add060ae4b045c27b7fac4e"}],"notes":null,"arglists":["m ks f & args"],"doc":"'Updates' a value in a nested associative structure, where ks is a\n sequence of keys and f is a function that will take the old value\n and any supplied args and return the new value, and returns a new\n nested structure. If any levels do not exist, hash-maps will be\n created.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/update-in"},{"added":"1.0","ns":"clojure.core","name":"prefer-method","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1337584953000,"author":{"login":"abrooks","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/69976?v=2"},"to-var":{"ns":"clojure.core","name":"prefers","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e0f"},{"created-at":1337584964000,"author":{"login":"abrooks","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/69976?v=2"},"to-var":{"ns":"clojure.core","name":"get-method","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e10"},{"created-at":1337584977000,"author":{"login":"abrooks","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/69976?v=2"},"to-var":{"ns":"clojure.core","name":"methods","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e11"}],"line":1820,"examples":[{"editors":[{"login":"ertugrulcetin","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8271291?v=3"}],"body":"(def m {:os ::osx})\n\n(defmulti ex :os)\n\n(defmethod ex ::unix\n [_]\n \"unix\")\n\n(derive ::osx ::unix)\n\n(ex m)\n;;=> \"unix\"\n\n(defmethod ex ::bsd\n [_]\n \"bsd\")\n\n(derive ::osx ::bsd)\n\n;; which one to choose ::unix or ::bsd ?? -> Conflict!!!\n(ex m)\n;;=> IllegalArgumentException Multiple methods in multimethod 'ex' match...\n\n(prefer-method ex ::unix ::bsd)\n\n(ex m)\n;;=> \"unix\"\n\n","author":{"avatar-url":"https://avatars.githubusercontent.com/u/8271291?v=3","account-source":"github","login":"ertugrulcetin"},"created-at":1475488456319,"updated-at":1475488811909,"_id":"57f22ac8e4b0709b524f0514"}],"notes":null,"arglists":["multifn dispatch-val-x dispatch-val-y"],"doc":"Causes the multimethod to prefer matches of dispatch-val-x over dispatch-val-y \n when there is a conflict","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/prefer-method"},{"added":"1.0","ns":"clojure.core","name":"aset-int","file":"clojure/core.clj","type":"function","column":1,"see-alsos":null,"line":3972,"examples":[{"author":{"login":"shockbob","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon"},"editors":[],"body":";; create an array of 10 ints and set one of the values to 31415\n\nuser=> (def is (int-array 10))\n#'user/is\nuser=> (vec is)\n[0 0 0 0 0 0 0 0 0 0]\nuser=> (aset-int is 3 31415)\n31415\nuser=> (vec is)\n[0 0 0 31415 0 0 0 0 0 0]\nuser=>","created-at":1313915065000,"updated-at":1313915065000,"_id":"542692cdc026201cdc326d37"}],"notes":[{"body":"See [aset](http://clojuredocs.org/clojure.core/aset) for illustrations of multi-dimensional syntax.","created-at":1432829144129,"updated-at":1432829144129,"author":{"login":"mars0i","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1836941?v=3"},"_id":"55673cd8e4b03e2132e7d173"}],"arglists":["array idx val","array idx idx2 & idxv"],"doc":"Sets the value at the index/indices. Works on arrays of int. Returns val.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/aset-int"},{"added":"1.0","ns":"clojure.core","name":"*clojure-version*","file":"clojure/core.clj","type":"var","column":3,"see-alsos":[{"created-at":1328398023000,"author":{"login":"steveminer","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d28543d134185d12d4006a74738d233e?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"clojure-version","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521aa6"}],"dynamic":true,"line":7217,"examples":[{"updated-at":1493242329065,"created-at":1280322760000,"body":"user=> *clojure-version*\n{:interim true, :major 1, :minor 2, :incremental 0, :qualifier \"master\"}","editors":[{"login":"chbrown","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/360279?v=3"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/ee24aacb65359196b0a1bad050f9a62f?r=PG&default=identicon","account-source":"clojuredocs","login":"mattdw"},"_id":"542692cac026201cdc326b62"}],"notes":null,"arglists":[],"doc":"The version info for Clojure core, as a map containing :major :minor \n :incremental and :qualifier keys. Feature releases may increment \n :minor and/or :major, bugfix releases will increment :incremental. \n Possible values of :qualifier include \"GA\", \"SNAPSHOT\", \"RC-x\" \"BETA-x\"","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/*clojure-version*"},{"added":"1.7","ns":"clojure.core","name":"ensure-reduced","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1464286337203,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"reduced","ns":"clojure.core"},"_id":"57473c81e4b0af2c9436d1ef"},{"created-at":1464286352101,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"reduced?","ns":"clojure.core"},"_id":"57473c90e4b0bafd3e2a045d"},{"created-at":1464286361977,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"unreduced","ns":"clojure.core"},"_id":"57473c99e4b0af2c9436d1f0"},{"created-at":1464286386482,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"reduce","ns":"clojure.core"},"_id":"57473cb2e4b0af2c9436d1f1"}],"line":2866,"examples":[{"updated-at":1464286295227,"created-at":1464286295227,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10583730?v=3"},"body":"(ensure-reduced :foo)\n;;=> object[clojure.lang.Reduced 0x7dc19a70 {:status :ready, :val :foo}]\n\n(ensure-reduced (reduced :foo))\n;;=> object[clojure.lang.Reduced 0x45385f75 {:status :ready, :val :foo}]","_id":"57473c57e4b0bafd3e2a045c"},{"updated-at":1682279619055,"created-at":1682279619055,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":";; If our reducing function's short-circuit coincides with our transducer's\n;; short-circuit, `reduced` could lead to the reduction returning a Reduced:\n\n(defn conj-till-neg\n ([coll] coll)\n ([coll x] (cond-> (conj coll x) (neg? x) reduced)))\n\n(defn take-till-odd [rf]\n (fn new-rf\n ([result] (rf result))\n ([result x] (cond-> (rf result x) (odd? x) reduced))))\n\n(transduce take-till-odd conj-till-neg [] [6 4 2 -1 -2])\n;; => #\n\n;; So we can change `reduced` to `ensure-reduced` to avoid doubling up:\n(defn take-till-odd [rf]\n (fn new-rf\n ([result] (rf result))\n ([result x] (cond-> (rf result x) (odd? x) ensure-reduced))))\n\n(transduce take-till-odd conj-till-neg [] [6 4 2 -1 -2])\n;; => [6 4 2 -1]\n","_id":"64458cc3e4b08cf8563f4b95"}],"notes":null,"arglists":["x"],"doc":"If x is already reduced?, returns it, else returns (reduced x)","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/ensure-reduced"},{"added":"1.0","ns":"clojure.core","name":"*'","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1412880795489,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"},"to-var":{"ns":"clojure.core","name":"*","library-url":"https://github.com/clojure/clojure"},"_id":"5436d99be4b0ae7956031574"}],"line":998,"examples":[{"body":";; there is an implicit 1\n(*')\n;;=> 1 \n\n;; the implicit 1 comes into play\n(*' 6)\n;;=> 6\n\n(*' 2 3)\n;;=> 6\n\n(*' 2 3 4)\n;;=> 24\n\n(*' 0.5 200)\n;;=> 100.0\n\n;; great so it gives the same results as *.\n;; not quite check this out\n(* 1234567890 9876543210)\n;; ArithmeticException integer overflow\n(*' 1234567890 9876543210)\n;;=> 12193263111263526900N","author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"},"created-at":1412880775853,"updated-at":1412880775853,"_id":"5436d987e4b0ae7956031573"}],"notes":null,"arglists":["","x","x y","x y & more"],"doc":"Returns the product of nums. (*') returns 1. Supports arbitrary precision.\n See also: *","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/*'"},{"added":"1.0","ns":"clojure.core","name":"instance?","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1285513897000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"type","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e9d"},{"created-at":1285513925000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"supers","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e9e"},{"created-at":1341631058000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"doto","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e9f"},{"created-at":1341631065000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"class","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ea0"},{"created-at":1432578737325,"author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"to-var":{"ns":"clojure.core","name":"satisfies?","library-url":"https://github.com/clojure/clojure"},"_id":"55636ab1e4b03e2132e7d16d"},{"created-at":1482897919586,"author":{"login":"mars0i","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1836941?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"isa?","ns":"clojure.core"},"_id":"586339ffe4b0fd5fb1cc9642"}],"line":141,"examples":[{"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"login":"john.r.woodward","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/22b6fbc4a386291e45b1cb4449377086?r=PG&default=identicon"},{"login":"steloflute","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/fc0969cd0910a427052f0f6281967392?r=PG&default=identicon"},{"login":"Phalphalak","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a684c0fd4f27597437de953e92a15d4b?r=PG&default=identicon"},{"login":"Phalphalak","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a684c0fd4f27597437de953e92a15d4b?r=PG&default=identicon"},{"login":"Phalphalak","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a684c0fd4f27597437de953e92a15d4b?r=PG&default=identicon"},{"login":"Phalphalak","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a684c0fd4f27597437de953e92a15d4b?r=PG&default=identicon"},{"login":"Phalphalak","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a684c0fd4f27597437de953e92a15d4b?r=PG&default=identicon"},{"login":"Phalphalak","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a684c0fd4f27597437de953e92a15d4b?r=PG&default=identicon"}],"body":"user=> (instance? Long 1)\ntrue\nuser=> (instance? Integer 1)\nfalse\nuser=> (instance? Number 1)\ntrue\nuser=> (instance? String 1)\nfalse\nuser=> (instance? String \"1\")\ntrue\n","created-at":1282289726000,"updated-at":1358905451000,"_id":"542692c6c026201cdc3268e1"},{"author":{"login":"shockbob","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon"},"editors":[{"login":"Phalphalak","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a684c0fd4f27597437de953e92a15d4b?r=PG&default=identicon"},{"login":"Phalphalak","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a684c0fd4f27597437de953e92a15d4b?r=PG&default=identicon"},{"login":"Phalphalak","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a684c0fd4f27597437de953e92a15d4b?r=PG&default=identicon"}],"body":"user=> (def al (new java.util.ArrayList))\n#'user/al\nuser=> (instance? java.util.Collection al)\ntrue\nuser=> (instance? java.util.RandomAccess al)\ntrue\nuser=> (instance? java.lang.String al)\nfalse","created-at":1313989675000,"updated-at":1358543212000,"_id":"542692c6c026201cdc3268eb"},{"author":{"login":"Phalphalak","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a684c0fd4f27597437de953e92a15d4b?r=PG&default=identicon"},"editors":[{"login":"Phalphalak","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a684c0fd4f27597437de953e92a15d4b?r=PG&default=identicon"}],"body":";; Some things are more than what they seem to be at first glance\nuser=> (instance? clojure.lang.IFn +)\ntrue\nuser=> (instance? clojure.lang.Keyword :a)\ntrue\nuser=> (instance? clojure.lang.IFn :a)\ntrue\nuser=> (instance? clojure.lang.IFn {:a 1})\ntrue\n","created-at":1358905444000,"updated-at":1358905610000,"_id":"542692d3c026201cdc326fcf"},{"editors":[{"login":"mars0i","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1836941?v=3"}],"body":";; If `c` is specified with a literal class name, this is a Java\n;; class name. If any of the namespace components of the class\n;; include dashes, the dashes have to be replaced with underscores:\n\n(ns foo-bar)\n(defrecord Box [x])\n(def box (Box. 42))\n\n(instance? foo-bar.Box box)\n;=> CompilerException java.lang.ClassNotFoundException: foo-bar.Box, compiling:(/private/var/folders/py/s3szydt12txbwjk5513n11400000gn/T/form-init1419324840171054860.clj:1:1)\n(instance? foo_bar.Box box)\n;=> true\n\n;; This rule doesn't apply to the last component of the class name:\n\n(defrecord My-Box [x]) ; not an idiomatic choice\n(def mybox (My-Box. 42))\n\n(instance? foo_bar.My-Box mybox)\n;=> true\n","author":{"avatar-url":"https://avatars.githubusercontent.com/u/1836941?v=3","account-source":"github","login":"mars0i"},"created-at":1482898746157,"updated-at":1482898800493,"_id":"58633d3ae4b0fd5fb1cc9643"}],"notes":null,"arglists":["c x"],"doc":"Evaluates x and tests if it is an instance of the class\n c. Returns true or false","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/instance_q"},{"added":"1.0","ns":"clojure.core","name":"with-open","file":"clojure/core.clj","type":"macro","column":1,"see-alsos":[{"created-at":1496906064866,"author":{"login":"fhur","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/6452323?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"slurp","ns":"clojure.core"},"_id":"5938f950e4b06e730307db30"},{"created-at":1507926365257,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"input-stream","ns":"clojure.java.io"},"_id":"59e1215de4b03026fe14ea7f"}],"line":3857,"examples":[{"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"benmoss","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/239754?v=3"},{"login":"PetrGlad","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/124476?v=3"}],"body":";; Opens the file 'myfile.txt' and prints out the contents. The \n;; 'with-open' ensures that the reader is closed at the end of the \n;; form. \n;; \n;; Please note that reading a file a character at a time is not \n;; very efficient.\n\nuser=> (with-open [r (clojure.java.io/input-stream \"myfile.txt\")] \n (loop [c (.read r)] \n (if (not= c -1)\n (do \n (print (char c)) \n (recur (.read r))))))\n","created-at":1281949367000,"updated-at":1420810336807,"_id":"542692c7c026201cdc32699a"},{"author":{"login":"octopusgrabbus","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/fd31b8bcea99fa7b0711fbc424587774?r=PG&default=identicon"},"editors":[],"body":"(defn write-csv-file\n \"Writes a csv file using a key and an s-o-s (sequence of sequences)\"\n [out-sos out-file]\n\n (spit out-file \"\" :append false)\n (with-open [out-data (io/writer out-file)]\n (csv/write-csv out-data out-sos)))\n\n","created-at":1352321815000,"updated-at":1352321815000,"_id":"542692d6c026201cdc3270bb"},{"updated-at":1522741647810,"created-at":1522741647810,"author":{"login":"jcburley","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/430319?v=4"},"body":";; Try to read 3 lines of text from a test file and return them (to the REPL)\n;; as a list:\n(with-open [r (clojure.java.io/reader \"test-0.txt\")]\n (binding [*in* r] (repeatedly 3 read-line)))\n\n;; The above returns a lazy seq without reading any lines while *in* is bound\n;; to the file, resulting in the original *in* (usually stdin) being read.\n;; To fix, wrap the body within the *in* binding in (doall ...):\n(with-open [r (clojure.java.io/reader \"test-0.txt\")]\n (binding [*in* r] (doall (repeatedly 3 read-line))))\n\n;; That ensures the sequence will be fully realized with the binding of *in*\n;; still in effect, thus reading all 3 lines from the test file.","_id":"5ac3318fe4b045c27b7fac2f"},{"editors":[{"login":"NielsvanKlaveren","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/43436964?v=4"}],"body":";Process multiple files with a transducer as if it's one file\n;Not lazy, but processes a line at a time\n\n(defn process-file\n [t file]\n (with-open [rdr (io/reader file)]\n (into []\n t\n (line-seq rdr))))\n\n(defn process-files\n [t files]\n (into []\n (comp (mapcat (fn [file] (process-file t file))))\n files))\n\n(apply + (process-files (comp (map count))\n [\"test-0.txt\" \"test-1.txt\" \"test-2.txt\"]))","author":{"avatar-url":"https://avatars0.githubusercontent.com/u/43436964?v=4","account-source":"github","login":"NielsvanKlaveren"},"created-at":1544177851915,"updated-at":1544184780984,"_id":"5c0a48bbe4b0ca44402ef5e2"}],"macro":true,"notes":null,"arglists":["bindings & body"],"doc":"bindings => [name init ...]\n\n Evaluates body in a try expression with names bound to the values\n of the inits, and a finally clause that calls (.close name) on each\n name in reverse order.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/with-open"},{"added":"1.6","ns":"clojure.core","name":"mix-collection-hash","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":null,"line":5228,"examples":null,"notes":null,"arglists":["hash-basis count"],"doc":"Mix final collection hash for ordered or unordered collections.\n hash-basis is the combined collection hash, count is the number\n of elements included in the basis. Note this is the hash code\n consistent with =, different from .hashCode.\n See http://clojure.org/data_structures#hash for full algorithms.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/mix-collection-hash"},{"added":"1.0","ns":"clojure.core","name":"re-find","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1282039272000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"re-groups","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bfe"},{"created-at":1282039314000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"re-matcher","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bff"},{"created-at":1282039324000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"re-pattern","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c00"},{"created-at":1282039359000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"re-seq","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c01"},{"created-at":1324028214000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.core","name":"re-matches","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c02"},{"created-at":1379040124000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.core","name":"subs","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c03"},{"created-at":1412843259867,"author":{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},"to-var":{"ns":"clojure.string","name":"replace","library-url":"https://github.com/clojure/clojure"},"_id":"543646fbe4b0ae795603156f"}],"line":4951,"examples":[{"author":{"login":"nipra","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/142529?v=3"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"login":"jwatki06","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/5594302?v=3"}],"body":"user=> (def matcher (re-matcher #\"\\d+\" \"abc12345def\"))\n#'user/matcher\n\nuser=> (re-find matcher)\n\"12345\"\n\n;; If you only want the first match, it is shorter to call re-find with the\n;; pattern and the string to search, rather than explicitly creating a matcher\n;; as above.\nuser=> (re-find #\"\\d+\" \"abc12345def\")\n\"12345\"\n\n;; If you want all matches as a sequence, use re-seq. Creating a matcher\n;; explicitly with re-matcher and passing it to re-find is only the best way\n;; if you want to write a loop that iterates through all matches, and do not\n;; want to use re-seq for some reason.\n","created-at":1279049854000,"updated-at":1465229780990,"_id":"542692cac026201cdc326b4c"},{"author":{"login":"OnesimusUnbound","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2fa4c391db0d2d1744cc2cd0d787dd3d?r=PG&default=identicon"},"editors":[],"body":";; re-find can be used to iterate through re matches in the string\n\nuser=> (def phone-number \"672-345-456-3212\")\n#'user/phone-number\n\nuser=> (def matcher (re-matcher #\"\\d+\" phone-number))\n#'user/matcher\n\nuser=> (re-find matcher)\n\"672\"\n\nuser=> (re-find matcher)\n\"345\"\n\nuser=> (re-find matcher)\n\"456\"\n\nuser=> (re-find matcher)\n\"3212\"\n\n;; when there's no more valid matches, nil is returned\nuser=> (re-find matcher)\nnil","created-at":1312373129000,"updated-at":1312373129000,"_id":"542692cac026201cdc326b4f"},{"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"editors":[],"body":";; When there are parenthesized groups in the pattern and re-find\n;; finds a match, it returns a vector. The first item is the part of\n;; the string that matches the entire pattern, and each successive\n;; item are the parts of the string that matched the 1st, 2nd,\n;; etc. parenthesized groups. Groups are numbered by the order in\n;; which their left parenthesis occurs in the string, from left to\n;; right.\nuser=> (def line \" RX packets:1871074138 errors:5 dropped:48 overruns:9\")\n#'user/line\n\nuser=> (re-find #\"(\\S+):(\\d+)\" line)\n[\"packets:1871074138\" \"packets\" \"1871074138\"]\n\n;; groups can nest\nuser=> (re-find #\"(\\S+:(\\d+)) \\S+:\\d+\" line)\n[\"packets:1871074138 errors:5\" \"packets:1871074138\" \"1871074138\"]\n\n;; If there is no match, re-find always returns nil, whether there are\n;; parenthesized groups or not.\nuser=> (re-find #\"(\\S+):(\\d+)\" \":2 numbers but not 1 word-and-colon: before\")\nnil\n\n;; A parenthesized group can have nil as its result if it is part of\n;; an 'or' (separated by | in the regex), and another alternative is\n;; the one that matches.\nuser=> (re-find #\"(\\D+)|(\\d+)\" \"word then number 57\")\n[\"word then number \" \"word then number \" nil]\n\nuser=> (re-find #\"(\\D+)|(\\d+)\" \"57 number then word\")\n[\"57\" nil \"57\"]\n\n;; It is also possible for a group to match the empty string.\nuser=> (re-find #\"(\\d*)(\\S)\\S+\" \"lots o' digits 123456789\")\n[\"lots\" \"\" \"l\"]\n\n;; If you want to use parentheses to group a part of the regex, but\n;; have no interest in capturing the string it matches, you can follow\n;; the left paren with ?: to prevent capturing.\nuser=> (re-find #\"(?:\\S+):(\\d+)\" line)\n[\"packets:1871074138\" \"1871074138\"]\n\n;; re-matches also behaves this way, and re-seq returns a sequence of\n;; matches, where each one can be a vector like re-find returns.\n","created-at":1324028180000,"updated-at":1324028180000,"_id":"542692d4c026201cdc32704a"},{"author":{"login":"Claj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5fd658a8d2ef549071cb5286b1b874aa?r=PG&default=identicon"},"editors":[],"body":";;It's possible to get variables out of your string with regexp\n\nuser=> (re-find #\"(\\d\\d\\d) (USD)\" \"450 USD\")\n[\"450 USD\" \"450\" \"USD\"]\nuser=> (nth *1 1)\n\"450\"\n\n;;thanks kotarak @ stackoverflow.com for this one","created-at":1326426979000,"updated-at":1326426979000,"_id":"542692d4c026201cdc32704b"},{"author":{"login":"Pete Mancini","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/19c72d50850490b8dea594fe3eb04437?r=PG&default=identicon"},"editors":[{"login":"Pete Mancini","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/19c72d50850490b8dea594fe3eb04437?r=PG&default=identicon"}],"body":";; If your input has line delimiters you can switch on multiline with (?m)\n\nuser=> (def testcase \"Line 1\\nLine 2\\nTarget Line\\nLine 4\\nNot a target line\")\nuser=>(re-find #\"(?im)^target.*$\" testcase)\n\"Target Line\"","created-at":1369872025000,"updated-at":1369872064000,"_id":"542692d4c026201cdc32704c"},{"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"editors":[],"body":";; Note: See clojure.core/subs for discussion of behavior of substrings\n;; holding onto references of the original strings, which can\n;; significantly affect your memory usage in some cases.","created-at":1379040119000,"updated-at":1379040119000,"_id":"542692d4c026201cdc32704e"},{"updated-at":1598128246429,"created-at":1598128036322,"author":{"login":"jgomo3","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/1125678?v=4"},"body":";; Use it as a simple predicate based on regexp,\n;; since it returns nil if `re` and `s` do not match.\n\nuser=> (def text-with-blank-lines [\"En un lugar de la Mancha,\"\n \"\"\n \" \"\n \"de cuyo nombre no quiero acordarme\"\n \" \"])\n\n;; Let's count how many non-blank lines are there:\nuser=> (count (filter #(re-find #\"\\S\" %) text-with-blank-lines))\n2\n\n;; Example inspired in 'Programming Clojure 3rd Ed.' 'Seq-in Stream'.","editors":[{"avatar-url":"https://avatars0.githubusercontent.com/u/1125678?v=4","account-source":"github","login":"jgomo3"}],"_id":"5f417fa4e4b0b1e3652d7386"}],"notes":[{"body":"the regex can't be a var?\n\n```clojure\n(let [regex \"abc\"] (re-find #a \"abc\"))\n```\nthis will get an error!","created-at":1419230605090,"updated-at":1419230605090,"author":{"login":"paomian","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2999156?v=3"},"_id":"5497bd8de4b09260f767ca7d"},{"author":{"login":"blx","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/887504?v=3"},"updated-at":1447600673577,"created-at":1447600673577,"body":"@paomian: The regex *can* be a variable, but the variable needs to be a regex.\n\nThis works fine:\n
    \n(let [regex #\"abc\"] (re-find regex \"abc\"))\n
    \n\nbecause the **#** reader macro for declaring regexes applies to the string right after it -- without doing any kind of substitution.\n\nYou could also do\n
    \n(let [regex \"abc\"] (re-find (re-pattern regex) \"abc\"))\n
    ","_id":"5648a221e4b053844439826f"}],"arglists":["m","re s"],"doc":"Returns the next regex match, if any, of string to pattern, using\n java.util.regex.Matcher.find(). Uses re-groups to return the\n groups.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/re-find"},{"added":"1.7","ns":"clojure.core","name":"run!","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1502125415874,"author":{"login":"mars0i","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/1836941?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"doseq","ns":"clojure.core"},"_id":"59889d67e4b0d19c2ce9d70d"},{"created-at":1502125443214,"author":{"login":"mars0i","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/1836941?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"map","ns":"clojure.core"},"_id":"59889d83e4b0d19c2ce9d70e"},{"created-at":1502125454691,"author":{"login":"mars0i","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/1836941?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"mapv","ns":"clojure.core"},"_id":"59889d8ee4b0d19c2ce9d70f"}],"line":7902,"examples":[{"updated-at":1451663711803,"created-at":1451663490717,"author":{"login":"s-mage","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2388396?v=3"},"body":"(run! prn (range 5))\n; 0\n; 1\n; 2\n; 3\n; 4\n; returns nil\n\n; compared to mapv\n(mapv prn (range 5))\n; 0 \n; 1 \n; 2 \n; 3 \n; 4 \n; returns [nil nil nil nil nil] ","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/2388396?v=3","account-source":"github","login":"s-mage"}],"_id":"5686a082e4b0e0706e05bd96"},{"editors":[{"login":"berczeck","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/1321842?v=4"}],"body":"(run! #(http-out-create-person! %) [{:name \"alex\" :country :peru} \n {:name \"eddu\" :country :peru}])\n\n; (http-out-create-person! {:name \"alex\" :country :peru})\n; (http-out-create-person! {:name \"eddu\" :country :peru})\n; nil","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/1321842?v=4","account-source":"github","login":"berczeck"},"created-at":1598157184683,"updated-at":1598157582001,"_id":"5f41f180e4b0b1e3652d7394"}],"notes":null,"arglists":["proc coll"],"doc":"Runs the supplied procedure (via reduce), for purposes of side\n effects, on successive items in the collection. Returns nil","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/run!"},{"added":"1.0","ns":"clojure.core","name":"val","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1318590007000,"author":{"login":"mmwaikar","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/29d36f4c9f39c9f8ff61c07033b13118?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"vals","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521efb"},{"created-at":1423522665421,"author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"to-var":{"ns":"clojure.core","name":"key","library-url":"https://github.com/clojure/clojure"},"_id":"54d93b69e4b0e2ac61831d35"},{"created-at":1423522670342,"author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"to-var":{"ns":"clojure.core","name":"keys","library-url":"https://github.com/clojure/clojure"},"_id":"54d93b6ee4b0e2ac61831d36"}],"line":1589,"examples":[{"updated-at":1434396569392,"created-at":1280777702000,"body":";; emulate 'vals'\n(map val {:a 1 :b 2})\n;;=> (1 2)\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3","account-source":"github","login":"phreed"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3","account-source":"github","login":"devn"},"_id":"542692c6c026201cdc3268cd"},{"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":"(val (first {:one :two}))\n;;=> :two","created-at":1288970694000,"updated-at":1434396586900,"_id":"542692c6c026201cdc3268cf"},{"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"editors":[],"body":";syntactic sugar for (val)\n(:doc (meta #'meta))","created-at":1288970885000,"updated-at":1288970885000,"_id":"542692c6c026201cdc3268d0"},{"body":";; extracts the key of a map entry\n(val (clojure.lang.MapEntry. :a :b))\n;;=> :b","author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"},"created-at":1434396268230,"updated-at":1434396268230,"_id":"557f266ce4b03e2132e7d193"}],"notes":[{"updated-at":1345454203000,"body":"This is my first attempt at using this site to gain an understanding of a closure function. Two of the examples above seem incorrect. \r\n\r\nExample 3(?) seems to have nothing to do with val \r\n\r\n(notice the lack of example identifiers)\r\n","created-at":1344320583000,"author":{"login":"dansalmo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e33ee460f5f61bc5ba9b598934766215?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fe6"}],"arglists":["e"],"doc":"Returns the value in the map entry.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/val"},{"added":"1.0","ns":"clojure.core","name":"defonce","file":"clojure/core.clj","type":"macro","column":1,"see-alsos":[{"created-at":1421928745226,"author":{"login":"Gitward","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8510849?v=3"},"to-var":{"ns":"clojure.core","name":"def","library-url":"https://github.com/clojure/clojure"},"_id":"54c0e929e4b081e022073c21"}],"line":5881,"examples":[{"author":{"login":"dakrone","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bcacd00a7f05c4772329cf9f446c7987?r=PG&default=identicon"},"editors":[],"body":"user> (defonce foo 5)\n#'user/foo\n\nuser> foo\n5\n\n;; defonce does nothing the second time\nuser> (defonce foo 10)\nnil\n\nuser> foo\n5","created-at":1293672804000,"updated-at":1293672804000,"_id":"542692cec026201cdc326dba"},{"updated-at":1468533299702,"created-at":1468533299702,"author":{"login":"DanBurton","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/713692?v=3"},"body":";; Supports ^:private\nuser=> (defonce ^:private foo 3)\n#'user/foo\nuser=> foo\n3\nuser=> (in-ns 'user2)\nuser2=> user/foo\n java.lang.IllegalStateException: var: user/foo is not public\n","_id":"57880a33e4b0bafd3e2a04a1"},{"updated-at":1599762924778,"created-at":1599762924778,"author":{"login":"luiszambon","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/41161270?v=4"},"body":"user> (def code {:clojure \"Yes\"})\n#'user/code\n\nuser> code\n{:clojure \"Yes\"}\n\n;; defonce will not be evaluated\nuser> (defonce code (+ 10 10))\nnil\n\nuser> code\n{:clojure \"Yes\"}","_id":"5f5a71ece4b0b1e3652d73b7"}],"macro":true,"notes":[{"updated-at":1385014731000,"body":"Note that this isn't thread safe. I.e. EXPR for the same NAME can be evaluated more than once.","created-at":1385014731000,"author":{"login":"lnostdal","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a539e214c9980ff4b53ad5ca9347aa91?r=PG&default=identicon"},"_id":"542692edf6e94c697052200d"}],"arglists":["name expr"],"doc":"defs name to have the root value of the expr iff the named var has no root value,\n else expr is unevaluated","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/defonce"},{"added":"1.0","ns":"clojure.core","name":"unchecked-add","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1289215695000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"unchecked-dec","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b8a"},{"created-at":1289215703000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"unchecked-inc","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b8b"},{"created-at":1289215708000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"unchecked-negate","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b8c"},{"created-at":1289215717000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"unchecked-divide","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b8d"},{"created-at":1289215722000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"unchecked-subtract","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b8e"},{"created-at":1289215736000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"unchecked-multiply","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b8f"},{"created-at":1289215741000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"unchecked-remainder","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b90"},{"created-at":1423522050658,"author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"to-var":{"ns":"clojure.core","name":"+","library-url":"https://github.com/clojure/clojure"},"_id":"54d93902e4b0e2ac61831d2b"},{"created-at":1423522057832,"author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"to-var":{"ns":"clojure.core","name":"+'","library-url":"https://github.com/clojure/clojure"},"_id":"54d93909e4b0e2ac61831d2c"}],"line":1212,"examples":[{"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":";; can't interchange INTs with LONGs, only F(int, int) or F(long, long)\n;; F is a function, not an operator.\n;; overflow very easily as shown below.\n\nuser=> (unchecked-add Integer/MAX_VALUE 0)\n2147483647\n\nuser=> (unchecked-add Integer/MAX_VALUE 1)\n-2147483648\n\nuser=> (unchecked-add Integer/MAX_VALUE Integer/MAX_VALUE)\n-2\n\nuser=> (unchecked-add Integer/MAX_VALUE Long/MAX_VALUE)\njava.lang.IllegalArgumentException: No matching method found: unchecked_add (NO_SOURCE_FILE:0)\n\nuser=> (unchecked-add Integer/MAX_VALUE Long/MAX_VALUE)\njava.lang.IllegalArgumentException: No matching method found: unchecked_add (NO_SOURCE_FILE:0)\n\nuser=> (unchecked-add Long/MAX_VALUE Long/MAX_VALUE)\n-2\n\nuser=> (unchecked-add 5 Long/MAX_VALUE)\njava.lang.IllegalArgumentException: No matching method found: unchecked_add (NO_SOURCE_FILE:0)\n\nuser=> (unchecked-add 5555555555 Long/MAX_VALUE)\n-9223372031299220254","created-at":1289215507000,"updated-at":1289267828000,"_id":"542692c9c026201cdc326ac9"}],"notes":null,"arglists":["x y"],"doc":"Returns the sum of x and y, both long.\n Note - uses a primitive operator subject to overflow.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/unchecked-add"},{"added":"1.0","ns":"clojure.core","name":"loaded-libs","file":"clojure/core.clj","type":"function","column":1,"see-alsos":null,"line":6167,"examples":[{"editors":[{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"}],"body":";; Show the list of loaded libs (files named after the \"ns\"\n;; declaration they contain) and created namespaces (\"ns\" only). \n;; \"ns\" side effects into loaded-libs, \"create-ns\" (or \"in-ns\") does not:\n\n(ns a)\n(ns b) \n(every? (loaded-libs) ['a 'b])\n;; true\n\n(create-ns 'x)\n(create-ns 'y)\n(not-every? (loaded-libs) ['x 'y])\n;; true","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"},"created-at":1546097021308,"updated-at":1546097304134,"_id":"5c27917de4b0ca44402ef604"}],"notes":[{"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"updated-at":1546099777305,"created-at":1546099777305,"body":"Trivia: the concept of \"library\" goes all the way back to Clojure contrib and was initially inspired by other packaging systems (it was even named \"Jewels\" at some point, possibly inspired by Ruby Gems). Check the following:\n\n* https://groups.google.com/d/msg/clojure/fjDJfAsxwRo/-5hE4yDMVTQJ\n* https://github.com/clojure/clojure-contrib/blob/da367723d33b20cb89e4aac7dc4221a0138c2f8f/jewel.clj","_id":"5c279c41e4b0ca44402ef606"}],"arglists":[""],"doc":"Returns a sorted set of symbols naming the currently loaded libs","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/loaded-libs"},{"ns":"clojure.core","name":"->Vec","file":"clojure/gvec.clj","type":"function","column":1,"see-alsos":null,"line":170,"examples":null,"notes":null,"arglists":["am cnt shift root tail _meta"],"doc":"Positional factory function for class clojure.core.Vec.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/->Vec"},{"added":"1.9","ns":"clojure.core","name":"bytes?","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1495728541051,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"byte-array","ns":"clojure.core"},"_id":"5927019de4b093ada4d4d76d"},{"created-at":1495728555435,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"bytes","ns":"clojure.core"},"_id":"592701abe4b093ada4d4d76e"}],"line":5441,"examples":[{"updated-at":1495728500906,"created-at":1495728500906,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"body":";;;; Returns true for byte[] arrays:\n\n(bytes? (.getBytes \"foo\"))\n;;=> true\n(bytes? (byte-array [102 111 111]))\n;;=> true\n\n;;;; Returns false for Byte[] arrays:\n\n(bytes? (to-array (map byte [102 111 111])))\n;;=> false","_id":"59270174e4b093ada4d4d76c"}],"notes":null,"arglists":["x"],"doc":"Return true if x is a byte array","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/bytes_q"},{"added":"1.0","ns":"clojure.core","name":"not","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1301366612000,"author":{"login":"pauldoo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5cb916d3c8abc9f45a093209e72489fb?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"complement","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521dd8"},{"created-at":1375213332000,"author":{"login":"alilee","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2fb0196dc5a7cd3a5cc73f1b9941c209?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"false?","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521dd9"}],"line":526,"examples":[{"author":{"login":"mattdw","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/ee24aacb65359196b0a1bad050f9a62f?r=PG&default=identicon"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"}],"body":"user=> (not true)\nfalse\nuser=> (not false)\ntrue\nuser=> (not nil)\ntrue\n\n;; acts as complement of `boolean`\nuser=> (boolean \"a string\")\ntrue\nuser=> (not \"a string\")\nfalse\nuser=> (boolean 1)\ntrue\nuser=> (not 1)\nfalse","created-at":1280323469000,"updated-at":1422932403041,"_id":"542692cfc026201cdc326e64"},{"updated-at":1475631952638,"created-at":1475631952638,"author":{"login":"aakoch","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/137713?v=3"},"body":"user=> (not (= \"a\" \"b\"))\ntrue","_id":"57f45b50e4b0709b524f0520"}],"notes":null,"tag":"java.lang.Boolean","arglists":["x"],"doc":"Returns true if x is logical false, false otherwise.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/not"},{"added":"1.0","ns":"clojure.core","name":"with-meta","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1301486163000,"author":{"login":"ninjudd","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/7ced25585a7556e9b9b975c1f9e136e3?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"vary-meta","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d5e"},{"created-at":1341551175000,"author":{"login":"jgauthier","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e8668403f9cac4041a106e57e8037dff?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"meta","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d5f"},{"created-at":1374315863000,"author":{"login":"alilee","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2fb0196dc5a7cd3a5cc73f1b9941c209?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"alter-meta!","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d60"}],"line":213,"examples":[{"updated-at":1285495834000,"created-at":1280776037000,"body":"user=> (with-meta [1 2 3] {:my \"meta\"})\n[1 2 3]\n\nuser=> (meta (with-meta [1 2 3] {:my \"meta\"}))\n{:my \"meta\"}\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3","account-source":"github","login":"devn"},"_id":"542692c8c026201cdc326a41"},{"author":{"login":"mmwaikar","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/29d36f4c9f39c9f8ff61c07033b13118?r=PG&default=identicon"},"editors":[],"body":";; the same example above in a simplified way\nuser=> (def wm (with-meta [1 2 3] {:my \"meta\"}))\n#'user/wm\n\nuser=> wm\n[1 2 3]\n\nuser=> (meta wm)\n{:my \"meta\"}","created-at":1359717828000,"updated-at":1359717828000,"_id":"542692d6c026201cdc3270ba"},{"editors":[{"login":"Rovanion","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/632775?v=4"}],"body":";; Trying to attach meta data to nil with throw an exception\n(with-meta nil {:my \"meta\"})\n;; Unhandled java.lang.NullPointerException\n\n;; It also only works for Clojure data types implementing clojure.lang.IObj\n(require '[clojure.java.io :as io])\n(with-meta (io/file \".\") {:my \"meta\"})\n;; Unhandled java.lang.ClassCastException\n;; java.io.File cannot be cast to clojure.lang.IObj\n","author":{"avatar-url":"https://avatars2.githubusercontent.com/u/632775?v=4","account-source":"github","login":"Rovanion"},"created-at":1546960387304,"updated-at":1546960610725,"_id":"5c34be03e4b0ca44402ef616"},{"updated-at":1603447088199,"created-at":1603446774741,"author":{"login":"jimka2001","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/6414129?v=4"},"body":";; The meta data notation `^:dynamic` can be used to force a variable to be dynamic.\n\n(def ^:dynamic *my-dynamic-variable* \"my doc string\" the-initial-value)\n\n;; However, using this notation within a macro does not have the same semantics.\n;; For example the following macro *will not* expand to a definition of a \n;; dynamic variable whose value is a function.\n\n(defmacro dyn-fun [name lambda-list & body] ;; WRONG\n `(def ^:dynamic ~name (fn ~lambda-list ~@body)))\n\n;; The macro should be written something like the following.\n\n(defmacro dyn-fun [name lambda-list & body]\n `(def ~(with-meta name {:dynamic true}) (fn ~lambda-list ~@body)))\n","editors":[{"avatar-url":"https://avatars1.githubusercontent.com/u/6414129?v=4","account-source":"github","login":"jimka2001"}],"_id":"5f92a7f6e4b0b1e3652d73e7"}],"notes":[{"author":{"login":"beoliver","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1413969?v=4"},"updated-at":1558365596405,"created-at":1558365596405,"body":"The Clojure documentation states that \"metadata does not impact equality (or hash codes). Two objects that differ only in metadata are equal.\" One should be aware that while a function can be compared to itself:\n```\n(defn foo [x] (+ x x))\n```\ntesting equality\n```\n> (= foo foo)\ntrue\n> (= (with-meta foo {:hello :world}) foo)\nfalse\n> (= (with-meta foo {}) foo)\nfalse\n```\n","_id":"5ce2c59ce4b0ca44402ef728"}],"arglists":["obj m"],"doc":"Returns an object of the same type and value as obj, with\n map m as its metadata.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/with-meta"},{"added":"1.7","ns":"clojure.core","name":"unreduced","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1456683860012,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"reduced?","ns":"clojure.core"},"_id":"56d33b54e4b02a6769b5a4b7"},{"created-at":1456683872206,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"reduced","ns":"clojure.core"},"_id":"56d33b60e4b02a6769b5a4b8"},{"created-at":1456683877778,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"reduce","ns":"clojure.core"},"_id":"56d33b65e4b02a6769b5a4b9"},{"created-at":1464286441935,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"ensure-reduced","ns":"clojure.core"},"_id":"57473ce9e4b0bafd3e2a045e"}],"line":2872,"examples":[{"updated-at":1456683816266,"created-at":1456683816266,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10583730?v=3"},"body":"(unreduced :foo)\n;;=> :foo\n\n(unreduced (reduced :foo))\n;;=> :foo\n\n(unreduced (clojure.lang.Reduced. :foo))\n;;=> :foo","_id":"56d33b28e4b0b41f39d96cd8"},{"editors":[{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"}],"body":";; Transducers have a \"completing arity\" which is called at the end of the\n;; reduction to finalize the output. This is done outside of the normal\n;; reduction loop, so there is nothing to unwrap a reduced return value, should\n;; the reducing function be called from the completing arity and happen to wrap\n;; the return in a Reduced:\n\n(defn conj-till-odd\n ([coll] coll)\n ([coll x] (cond-> (conj coll x) (odd? x) reduced)))\n\n(defn inc-nums+7 [rf]\n (fn new-rf\n ([result] (rf result 7)) ; A bit contrived, but makes the point\n ([result x] (rf result (inc x)))))\n\n(transduce inc-nums+7 conj-till-odd [] [1 3 5 7 9])\n;; => #\n\n;; So we can wrap the return of the completing arity in `unreduced` to make sure\n;; we don't return a Reduced. After all, it's the end of the reduction anyway:\n\n(defn inc-nums+7 [rf]\n (fn new-rf\n ([result] (unreduced (rf result 7)))\n ([result x] (rf result (inc x)))))\n\n(transduce inc-nums+7 conj-till-odd [] [1 3 5 7 9])\n;; => [2 4 6 8 10 7]","author":{"avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4","account-source":"github","login":"tomdl89"},"created-at":1682279892453,"updated-at":1682326266615,"_id":"64458dd4e4b08cf8563f4b96"}],"notes":null,"arglists":["x"],"doc":"If x is reduced?, returns (deref x), else returns x","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/unreduced"},{"added":"1.0","ns":"clojure.core","name":"the-ns","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1416003694964,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"},"to-var":{"ns":"clojure.core","name":"ns-name","library-url":"https://github.com/clojure/clojure"},"_id":"5466806ee4b03d20a10242a2"},{"created-at":1524168245582,"author":{"login":"delonnewman","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/10404?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"create-ns","ns":"clojure.core"},"_id":"5ad8f635e4b045c27b7fac46"}],"line":4179,"examples":[{"author":{"login":"belun","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8d3c423e74750fa42c0386833e4b8209?r=PG&default=identicon"},"editors":[{"login":"belun","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8d3c423e74750fa42c0386833e4b8209?r=PG&default=identicon"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":";; Let's play with a namespace by its name and by its symbol \n(def for-later-use (create-ns 'my-namespace))\n;;=> #'user/for-later-use\n\n(the-ns for-later-use)\n;;=> #\n\n(the-ns 'my-namespace)\n;;=> #\n\n;; not going to find anything this way because we just asked the repl\n;; not to perform an evaluate on it and there is not such \n;; namespace with the name \"for-later-use\"\n(the-ns 'for-later-use)\n;; java.lang.Exception: No namespace: for-later-use found (NO_SOURCE_FILE:0)\n\n;; not going to work either because \"my-namespace\" is the name of a namespace\n;; and not a symbol that points to something\n(the-ns my-namespace)\n;; java.lang.Exception: Unable to resolve symbol: my-namespace in this context (NO_SOURCE_FILE:12)\n","created-at":1285114597000,"updated-at":1416003645892,"_id":"542692c6c026201cdc3268d9"}],"notes":null,"arglists":["x"],"doc":"If passed a namespace, returns it. Else, when passed a symbol,\n returns the namespace named by it, throwing an exception if not\n found.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/the-ns"},{"added":"1.6","ns":"clojure.core","name":"record?","file":"clojure/core_deftype.clj","static":true,"type":"function","column":1,"see-alsos":null,"line":407,"examples":[{"body":";; Define a record R\nuser=> (defrecord R [x])\nuser.R\n\n;; Create an instance of R called r\nuser=> (def r (->R 1))\n#'user/r\n\n;; Look at r\nuser=> r\n#user.R{:x 1}\n\n;; Is r a record?\nuser=> (record? r)\ntrue\n\n;; Interestingly adding \"fields\" not defined in R keeps it a record\nuser=> (def r2 (assoc r :y 2))\n#'user/r2\n\nuser=> r2\n#user.R{:x 1, :y 2}\n\n;; r2 is still a record\nuser=> (record? r2)\ntrue\n\n;; But regular map is not a record\nuser=> (record? {:x 1})\nfalse","author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"created-at":1423042551694,"updated-at":1423042594636,"editors":[{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"}],"_id":"54d1e7f7e4b0e2ac61831d0d"}],"notes":null,"arglists":["x"],"doc":"Returns true if x is a record","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/record_q"},{"added":"1.0","ns":"clojure.core","name":"type","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1281949423000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"class","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521acb"},{"created-at":1285511147000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"supers","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521acc"},{"created-at":1285513879000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"instance?","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521acd"}],"line":3492,"examples":[{"author":{"login":"belun","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8d3c423e74750fa42c0386833e4b8209?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"ampleyfly","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d1f7428e063b5d881a2366ee5fd526fd?r=PG&default=identicon"},{"login":"categorics","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3de94aa23c7d475ed00b9d32bc35877a?r=PG&default=identicon"},{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},{"avatar-url":"https://avatars2.githubusercontent.com/u/1665744?v=4","account-source":"github","login":"rleppink"},{"login":"seancorfield","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/43875?v=4"}],"body":";; Checking numbers\nuser=> (type 10)\njava.lang.Long\n\nuser=> (type 10.0)\njava.lang.Double\n\nuser=> (type nil)\nnil\n\n;; Checking collections\nuser=> (type [10 20])\nclojure.lang.PersistentVector\n\nuser=> (type '(10 20))\nclojure.lang.PersistentList\n\n\n;; Checking other, but somewhat intuitive, forms\nuser=> (type \"A string\")\njava.lang.String\n\nuser=> (type :a)\nclojure.lang.Keyword\n\nuser=> (type Thread)\njava.lang.Class\n\n\n;; Checking a symbol\nuser=> (type 'whatever)\nclojure.lang.Symbol\n\n;; A surprise attack yields\nuser=> (type clojure.lang.Symbol)\n;; not such a surprising response\njava.lang.Class\n\n\n;; Checking a function\nuser=> (defn foo [] (\"any string\"))\n#'user/foo\nuser=> (type foo)\nuser$foo\n\n\n;; Checking a macro\nuser=> (type clojure.core/fn)\njava.lang.Exception: Can't take value of a macro: #'clojure.core/fn (NO_SOURCE_FILE:94)\n\n","created-at":1284412202000,"updated-at":1537559961680,"_id":"542692cfc026201cdc326e29"},{"updated-at":1551950967539,"created-at":1305510021000,"body":";This example demonstrates how to add type information to regular clojure maps\n(defn purchase-order [id date amount]\n ^{:type ::PurchaseOrder} ;metadata\n {:id id :date date :amount amount})\n\n(def my-order (purchase-order 10 (java.util.Date.) 100.0))\n\nmy-order\n=> {:id 10, :date #, :amount 100.0}\n\n(type my-order)\n=> PurchaseOrder","editors":[{"avatar-url":"https://www.gravatar.com/avatar/d1906fc5df2c8ce5b2d58cc6ea855aab?r=PG&default=identicon","account-source":"clojuredocs","login":"shuaybi"},{"login":"borkdude","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/284934?v=4"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/d1906fc5df2c8ce5b2d58cc6ea855aab?r=PG&default=identicon","account-source":"clojuredocs","login":"shuaybi"},"_id":"542692cfc026201cdc326e2d"}],"notes":null,"arglists":["x"],"doc":"Returns the :type metadata of x, or its Class if none","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/type"},{"added":"1.0","ns":"clojure.core","name":"identical?","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1343319790000,"author":{"login":"john.r.woodward","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/22b6fbc4a386291e45b1cb4449377086?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"=","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cc5"},{"created-at":1343319794000,"author":{"login":"john.r.woodward","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/22b6fbc4a386291e45b1cb4449377086?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"==","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cc6"}],"line":777,"examples":[{"author":{"login":"dpritchett","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/147981?v=3"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"login":"john.r.woodward","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/22b6fbc4a386291e45b1cb4449377086?r=PG&default=identicon"},{"login":"john.r.woodward","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/22b6fbc4a386291e45b1cb4449377086?r=PG&default=identicon"}],"body":"user=> (def x 1)\n#'user/x\nuser=> (identical? x x)\ntrue\nuser=> (identical? x 1)\ntrue\nuser=> (identical? x 2)\nfalse\nuser=> (identical? x ((constantly 1) 8))\ntrue\nuser=> (identical? 'a 'a)\nfalse","created-at":1279074018000,"updated-at":1343322315000,"_id":"542692c8c026201cdc326a61"},{"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"editors":[],"body":"user=> (def x {:foo 1, :bar -3})\n#'user/x\nuser=> (def y {:foo 1, :bar -3})\n#'user/y\n;; Values are equal, but different objects were constructed\nuser=> (= x y)\ntrue\nuser=> (identical? x y)\nfalse\n","created-at":1329874849000,"updated-at":1329874849000,"_id":"542692d3c026201cdc326fca"},{"body":"; Java wrapper class caching\n; details at: https://www.owasp.org/index.php/Java_gotchas#Immutable_Objects_.2F_Wrapper_Class_Caching\nuser=> (identical? 128 128)\nfalse\nuser=> (identical? 127 127)\ntrue\nuser=> (identical? -127 -127)\ntrue\nuser=> (identical? -128 -128)\ntrue\nuser=> (identical? -130 -130)\nfalse","author":{"login":"MPechorin","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/3315568?v=3"},"created-at":1431147344205,"updated-at":1431147344205,"_id":"554d9350e4b03e2132e7d15e"},{"editors":[{"login":"ertugrulcetin","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8271291?v=3"}],"body":"user=> (def a (String. \"abc\"))\n;;=> #'user/a\n\nuser=> (def b (String. \"abc\"))\n;;=> #'user/b\n\n=> (identical? a b)\n;;=> false\n;; initialised 2 new objects\n\nuser=> (def a \"abc\")\n;;=> #'user/a\n\nuser=> (def b \"abc\")\n;;=> #'user/b\n\n=> (identical? a b)\n;;=> true\n;; refers same objects(address), look String pooling\n","author":{"avatar-url":"https://avatars.githubusercontent.com/u/8271291?v=3","account-source":"github","login":"ertugrulcetin"},"created-at":1470912975934,"updated-at":1470913004034,"_id":"57ac59cfe4b0bafd3e2a04e3"},{"editors":[{"login":"wontheone1","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/11784756?v=4"}],"body":";; two keywords with the same value are the same object\n\n(= :abc :abc)\n=> true\n\n(identical? :abc :abc)\n=> true\n\n;; two symbols with the same name are different objects\n(= 'abc 'abc)\n=> true\n\n(identical? 'abc 'abc)\n=> false\n\n;; Strings are interned. see https://en.wikipedia.org/wiki/String_interning\n(= \"abc\" \"abc\")\n=> true\n(identical? \"abc\" \"abc\")\n=> true","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/11784756?v=4","account-source":"github","login":"wontheone1"},"created-at":1556561354455,"updated-at":1556562044316,"_id":"5cc73dcae4b0ca44402ef714"},{"editors":[{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"}],"body":";; When there is no interning (1000 is outside long range\n;; of automatically interned numbers), autoboxing plays\n;; interesting tricks:\n\n(let [x 1000 y x]\n (identical? x y))\n;; false\n\n;; This is practically equivalent to the following, \n;; which explains what is going on during Clojure evaluation:\n(let [x 1000 y x]\n (identical? (Long/valueOf x) (Long/valueOf y)))\n;; false","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"},"created-at":1578397898483,"updated-at":1578426767152,"_id":"5e1470cae4b0ca44402ef80f"},{"updated-at":1603680840719,"created-at":1603680840719,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/109629?v=4"},"body":";; In general, other examples where `identical?` returns true are\n;; often implementation-specific optimizations that can change from one\n;; JDK version to another, or one version of Clojure to another.\n;; You should think _very_ carefully before writing code that relies on\n;; `identical?` returning true.\n\n;; One scenario where it is safe to use `identical?` can be seen in the\n;; implementation of Clojure's function `get-in`, where a sentinel object\n;; is freshly constructed, and thus guaranteed to be not identical? to any\n;; other object that existed before the function was called. This new\n;; object is used as a default value in case a lookup of a key in a map fails\n;; to find a matching key. Regardless of what values the map contains, it is\n;; guaranteed that if the return value is `identical?` to this freshly allocated\n;; sentinel object, it could not have been found in the map.","_id":"5f963a48e4b0b1e3652d73f5"}],"notes":null,"arglists":["x y"],"doc":"Tests if 2 arguments are the same object","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/identical_q"},{"added":"1.0","ns":"clojure.core","name":"unchecked-divide-int","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1435174878967,"author":{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/94482?v=3"},"to-var":{"ns":"clojure.core","name":"quot","library-url":"https://github.com/clojure/clojure"},"_id":"558b07dee4b0fad27b85f924"}],"line":1247,"examples":[{"updated-at":1599829194677,"created-at":1599829194677,"author":{"login":"fhightower","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/3599813?v=4"},"body":";; like http://clojuredocs.org/clojure.core/quot, (unchecked-divide-int m n) is the value of m/n, rounded down to the nearest integer.\n\n(unchecked-divide-int 3 2)\n;; => 1\n\n(unchecked-divide-int 2 4)\n;; => 0\n\n(unchecked-divide-int 4 2)\n;; => 2\n\n(unchecked-divide-int 0 4)\n;; => 0\n\n(unchecked-divide-int 1 0)\n;; => ArithmeticException / by zero clojure.lang.Numbers.unchecked_int_divide (Numbers.java:1698)","_id":"5f5b74cae4b0b1e3652d73bb"}],"notes":null,"arglists":["x y"],"doc":"Returns the division of x by y, both int.\n Note - uses a primitive operator subject to truncation.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/unchecked-divide-int"},{"added":"1.0","ns":"clojure.core","name":"ns-name","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1416003383632,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"},"to-var":{"ns":"clojure.core","name":"the-ns","library-url":"https://github.com/clojure/clojure"},"_id":"54667f37e4b0dc573b892fc7"}],"line":4190,"examples":[{"author":{"login":"sunng","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/4cc03baa6fbb880e246ce5c9c8e247ce?r=PG&default=identicon"},"editors":[{"login":"sunng","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/4cc03baa6fbb880e246ce5c9c8e247ce?r=PG&default=identicon"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":";; get the namespace name as a symbol\n(ns-name (the-ns 'user))\n;;=> user\n\n\n","created-at":1327579554000,"updated-at":1416003810277,"_id":"542692d4c026201cdc32701b"}],"notes":null,"arglists":["ns"],"doc":"Returns the name of the namespace, a symbol.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/ns-name"},{"added":"1.0","ns":"clojure.core","name":"max-key","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1350408889000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"max","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e60"},{"created-at":1371841171000,"author":{"login":"adereth","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5ad11b4e208a6cdb3bd45fe01dea59b7?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"min-key","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e61"},{"created-at":1459931910164,"author":{"login":"mhmdsalem1993","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10787314?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"min","ns":"clojure.core"},"_id":"5704cb06e4b0fc95a97eab2d"}],"line":5042,"examples":[{"author":{"login":"pkolloch","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/10b2fd3c0a4cc46dc241a48468dc551?r=PG&default=identicon"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":"user=> (max-key count \"asd\" \"bsd\" \"dsd\" \"long word\")\n\"long word\"","created-at":1282324042000,"updated-at":1332951974000,"_id":"542692c6c026201cdc3268d3"},{"body":"; find the key that has the highest value in a map\nuser=> (key (apply max-key val {:a 3 :b 7 :c 9}))\n:c","author":{"login":"huahaiy","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/889685?v=3"},"created-at":1418724141005,"updated-at":1418724141005,"_id":"5490032de4b09260f767ca79"},{"updated-at":1590259945797,"created-at":1590259945797,"author":{"login":"garaud","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/98194?v=4"},"body":";; find the index of the highest value. Equivalent to an 'argmax' function\nuser=> (first (apply max-key second (map-indexed vector '(2 1 6 5 4))))\n2","_id":"5ec970e9e4b087629b5a1915"},{"updated-at":1619610212721,"created-at":1617247307182,"author":{"login":"sova","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/451489?v=4"},"body":";; find the max :timestamp in a collection of maps.\nuser=> (def mmm [\n {:timestamp 1 :name \"v\"} \n {:timestamp 2 :name \"q\"} \n {:timestamp 3 :name \"r\"}])\n\nuser=> (apply max-key :timestamp mmm)\n{:timestamp 3, :name \"r\"}\n\nuser=> (:timestamp (apply max-key :timestamp mmm))\n3\n\n;;if the map is indexed by item-id, use an anonymous function where the key goes.\n\nuser=> (def map-with-index {\n \"gary\" {:timestamp 1 :name \"v\"} \n \"carl\" {:timestamp 2 :name \"q\"} \n \"lola\" {:timestamp 3 :name \"r\"}})\n\nuser=> (apply max-key #(:timestamp (val %)) map-with-index)\n[\"lola\" {:timestamp 3, :name \"r\"}]\n\n;notice how we replaced :timestamp with #(:timestamp (val %)) \n;to get the inner value [and not the (key %)] of the indexed version.","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/451489?v=4","account-source":"github","login":"sova"},{"avatar-url":"https://avatars.githubusercontent.com/u/16775439?v=4","account-source":"github","login":"Okwori"}],"_id":"60653c4be4b0b1e3652d74ad"},{"updated-at":1722009635721,"created-at":1722008791497,"author":{"login":"sofiiahitlan","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/48576209?v=4"},"body":";; filter out the the biggest map based on the size\n\nuser=> (def maps [{:a 1 :b 2}\n {:a 1}\n {:a 1 :b 2 :c 3}\n {:a 1 :b 2 :c 3 :d 4}])\n\nuser=> (apply max-key count maps)\n{:a 1 :b 2 :c 3 :d 4}\n\n;; in a case when multiple maps are of the same size, returns the last\n;; biggest map it encounters ","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/48576209?v=4","account-source":"github","login":"sofiiahitlan"}],"_id":"66a3c4d769fbcc0c226174e1"}],"notes":null,"arglists":["k x","k x y","k x y & more"],"doc":"Returns the x for which (k x), a number, is greatest.\n\n If there are multiple such xs, the last one is returned.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/max-key"},{"added":"1.3","ns":"clojure.core","name":"*unchecked-math*","type":"var","see-alsos":[{"created-at":1441815099356,"author":{"login":"miner","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/25400?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"*warn-on-reflection*","ns":"clojure.core"},"_id":"55f05a3be4b05246bdf20a8a"}],"examples":[{"body":"user=> (unchecked-add Long/MAX_VALUE 1)\n-9223372036854775808\n\nuser=> (+ Long/MAX_VALUE 1)\nArithmeticException integer overflow clojure.lang.Numbers.throwIntOverflow\n\nuser=> (set! *unchecked-math* true)\ntrue\n\nuser=> (+ Long/MAX_VALUE 1)\n-9223372036854775808","author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"created-at":1423526557905,"updated-at":1423526557905,"_id":"54d94a9de4b081e022073c80"}],"notes":[{"updated-at":1339147124000,"body":"Note that, even if `*unchecked-math*` is true when compiling, the unchecked operations are used only when both operands are primitive; if either operand is boxed, normal Clojure arithmetic is used (see [this message](http://groups.google.com/group/clojure/msg/532b32950db75f56) from Stuart Sierra on the Clojure Google group). This can be worked around by adding type hints (e.g. `^long`) where necessary.","created-at":1339147124000,"author":{"login":"glchapman","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a5176d5d971ba68c15f4afe376aeaf18?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fe3"}],"arglists":[],"doc":"While bound to true, compilations of +, -, *, inc, dec and the\n coercions will be done without overflow checks. While bound\n to :warn-on-boxed, same behavior as true, and a warning is emitted\n when compilation uses boxed math. Default: false.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/*unchecked-math*"},{"added":"1.0","ns":"clojure.core","name":"defn-","file":"clojure/core.clj","type":"macro","column":1,"see-alsos":[{"created-at":1358128693000,"author":{"login":"juan.facorro","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d6f59d93cc17c698f16e550034a2d1ad?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"defn","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d56"}],"line":4978,"examples":[{"updated-at":1285500672000,"created-at":1279162183000,"body":"\nuser=> (ns test)\nnil\n\ntest=> (defn- foo []\n \"World!\")\n#'test/foo\n\ntest=> (defn bar []\n (str \"Hello \" (foo)))\n#'test/bar\n\ntest=> (foo)\n\"World!\"\ntest=> (bar)\n\"Hello World!\"\ntest=> (ns playground)\nnil\nplayground=> (test/bar)\n\"Hello World!\"\n\n;; Error will be thrown\n;; var: #'test/foo is not public\nplayground=> (test/foo)\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/142529?v=3","account-source":"github","login":"nipra"},"_id":"542692cac026201cdc326b4a"},{"updated-at":1601478908333,"created-at":1601478908333,"author":{"login":"jimka2001","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/6414129?v=4"},"body":";;It is sometimes useful to call a private function from within a test case\n(defn- my-private-fun [x] (+ x 42))\n\n;; in test case file\n(deftest t-testing-my-private-fun\n (testing \"my-private-fun\")\n (is (= 45 (#'my-private-fun 3)) \"didn't get 45 as expected\")))","_id":"5f74a0fce4b0b1e3652d73c7"}],"macro":true,"notes":null,"arglists":["name & decls"],"doc":"same as defn, yielding non-public def","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/defn-"},{"added":"1.0","ns":"clojure.core","name":"*out*","type":"var","see-alsos":[{"created-at":1302912138000,"author":{"login":"hoornet","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5834f829a9def19620d4014c46642172?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"*in*","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c2b"}],"examples":[{"editors":[{"login":"owenRiddy","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8080718?v=4"}],"body":";; One approach to silence printing\n\n(def noop-writer\n ;; *out* needs to be bound to a java.io.writer, so proxy a writer\n ;; https://docs.oracle.com/javase/7/docs/api/java/io/Writer.html\n (proxy [java.io.Writer] []\n (close [] nil)\n (flush [] nil)\n (write\n ;; ... which politely ignores any calls.\n ([cbuf] nil)\n ([cbuf off len] nil))))\n=> #'user/noop-writer\n\n;; Now if we bind *out* to the no-op writer println won't do anything\n(do\n (println \"Hello?\")\n (binding [*out* noop-writer]\n ;; (.write noop-writer) will be used to print this, so nothing will happen.\n (println \"world\")))\n=> Hello?\nnil","author":{"avatar-url":"https://avatars.githubusercontent.com/u/8080718?v=4","account-source":"github","login":"owenRiddy"},"created-at":1645240924505,"updated-at":1645240999533,"_id":"6210625ce4b0b1e3652d75a9"}],"notes":null,"tag":"java.io.Writer","arglists":[],"doc":"A java.io.Writer object representing standard output for print operations.\n\n Defaults to System/out, wrapped in an OutputStreamWriter","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/*out*"},{"added":"1.0","ns":"clojure.core","name":"file-seq","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1329988618000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.java.io","name":"file","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b05"},{"created-at":1329988623000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.java.io","name":"delete-file","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b06"}],"line":5001,"examples":[{"author":{"login":"shockbob","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon"},"editors":[{"login":"shockbob","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon"},{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4","account-source":"github","login":"phreed"},{"login":"KlayKla","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/40676441?v=4"}],"body":";; first create a Java File object using the file function in\n;; the clojure.java.io package and use that object to create a file-seq\n;; then show the first 10 members of that seq\n\n(def f (clojure.java.io/file \"c:\\\\clojure-1.2.0\"))\n;;=> #'user/f\n(def fs (file-seq f))\n;;=> #'user/fs\n(first fs)\n;;=> #\n(clojure.pprint/pprint (take 10 fs))\n;; (#\n;; #\n;; #\n;; #\n;; #\n;; #\n;; #\n;; #\n;; #\n;; #)\n;;=>","created-at":1313961191000,"updated-at":1625184652730,"_id":"542692cbc026201cdc326bf2"},{"updated-at":1509141653447,"created-at":1509135502851,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"},"body":";; Fill an array with the file names in a directory.\n;; Put them in an array.\n(mapv str (filter #(.isFile %) (file-seq (clojure.java.io/file \".\"))))\n\n;; Use the Path utilities to do glob filtering.\n(let [grammar-matcher (.getPathMatcher \n (java.nio.file.FileSystems/getDefault)\n \"glob:*.{g4,md}\")]\n (->> \".\"\n clojure.java.io/file\n file-seq\n (filter #(.isFile %))\n (filter #(.matches grammar-matcher (.getFileName (.toPath %))))\n (mapv #(.getAbsolutePath %))))\n\n;; At that point it may be better to just use the java.nio.file classes.\n;; https://github.com/ajoberstar/ike.cljj has some ideas","editors":[{"avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4","account-source":"github","login":"phreed"}],"_id":"59f3948ee4b0a08026c48c79"}],"notes":[{"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"},"updated-at":1509135556587,"created-at":1509135556587,"body":"The file operations from java are https://docs.oracle.com/javase/8/docs/api/java/io/File.html","_id":"59f394c4e4b0a08026c48c7a"}],"arglists":["dir"],"doc":"A tree seq on java.io.Files","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/file-seq"},{"added":"1.0","ns":"clojure.core","name":"agent","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1287220581000,"author":{"login":"hugoduncan","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/80fa2a15219b987664e4d6f5c78b4c27?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"set-error-handler!","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b66"},{"created-at":1332037921000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"send","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b67"},{"created-at":1332037925000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"send-off","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b68"},{"created-at":1332038024000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"release-pending-sends","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b69"},{"created-at":1332038048000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"agent-error","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b6a"},{"created-at":1332038056000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"restart-agent","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b6b"},{"created-at":1349393706000,"author":{"login":"eric","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2b0c9ae6f1da9716451e7c86bc87230b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"add-watch","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b6c"},{"created-at":1358869462000,"author":{"login":"avasenin","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/154699?v=3"},"to-var":{"ns":"clojure.core","name":"set-error-mode!","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b6d"},{"created-at":1364873755000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"set-validator!","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b6e"},{"created-at":1568811536981,"author":{"login":"witek","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/209520?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"await","ns":"clojure.core"},"_id":"5d822a10e4b0ca44402ef7b7"}],"line":2071,"examples":[{"author":{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},"editors":[{"login":"srid","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bd3a68d670372cd09876c26270a4299a?r=PG&default=identicon"},{"login":"srid","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bd3a68d670372cd09876c26270a4299a?r=PG&default=identicon"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":";; Agents provide shared access to mutable state. \n;; They allow non-blocking (asynchronous as opposed \n;; to synchronous atoms) and independent change of \n;; individual locations (unlike coordinated change \n;; of multiple locations through refs).\n\n;; agent creates one:\n(def counter (agent 0))\n;; #'user/counter\n\n;; send requests a change to its value:\n(send counter inc)\n\n; @ or deref provides a snapshot of the current state:\n@counter\n;;=> 1\n\n;; agents can reference any data structure:\n\n(def pulp-fiction (agent {}))\n;; #'user/pulp-fiction\n\n(send pulp-fiction assoc :act-one \"PROLOGUE\")\n@pulp-fiction\n;;=> {:act-one \"PROLOGUE\"}\n\n(send pulp-fiction assoc :act-two \"VINCENT VEGA & MARSELLUS WALLACE'S WIFE\")\n@pulp-fiction\n;;=> {:act-two \"VINCENT VEGA & MARSELLUS WALLACE'S WIFE\", :act-one \"PROLOGUE\"}\n\n; From http://clojure-examples.appspot.com/clojure.core/agent with permission.","created-at":1278720383000,"updated-at":1434143400277,"_id":"542692cfc026201cdc326e6c"}],"notes":null,"arglists":["state & options"],"doc":"Creates and returns an agent with an initial value of state and\n zero or more options (in any order):\n\n :meta metadata-map\n\n :validator validate-fn\n\n :error-handler handler-fn\n\n :error-mode mode-keyword\n\n If metadata-map is supplied, it will become the metadata on the\n agent. validate-fn must be nil or a side-effect-free fn of one\n argument, which will be passed the intended new state on any state\n change. If the new state is unacceptable, the validate-fn should\n return false or throw an exception. handler-fn is called if an\n action throws an exception or if validate-fn rejects a new state --\n see set-error-handler! for details. The mode-keyword may be either\n :continue (the default if an error-handler is given) or :fail (the\n default if no error-handler is given) -- see set-error-mode! for\n details.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/agent"},{"added":"1.0","ns":"clojure.core","name":"ns-map","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1288055092000,"author":{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},"to-var":{"ns":"clojure.core","name":"ns-interns","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bc2"},{"created-at":1288055096000,"author":{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},"to-var":{"ns":"clojure.core","name":"ns-publics","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bc3"},{"created-at":1288055105000,"author":{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},"to-var":{"ns":"clojure.core","name":"ns-refers","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bc4"},{"created-at":1288055110000,"author":{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},"to-var":{"ns":"clojure.core","name":"ns-imports","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bc5"},{"created-at":1710247968492,"author":{"login":"Kaspazza","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/36607370?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"find-ns","ns":"clojure.core"},"_id":"65f0502069fbcc0c226174b5"}],"line":4197,"examples":[{"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"editors":[],"body":"(ns-map 'clojure.core)\n{sorted-map #'clojure.core/sorted-map, read-line #'clojure.core/read-line, re-pattern #'clojure.core/re-pattern, keyword? #'clojure.core/keyword?, ClassVisitor clojure.asm.ClassVisitor, asm-type #'clojure.core/asm-type, val #'clojure.core/val, ...chop...}","created-at":1288074955000,"updated-at":1288074955000,"_id":"542692cec026201cdc326d75"},{"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"editors":[],"body":";; See also http://clojure.org/namespaces for information on namespaces in Clojure and how to inspect and manipulate them","created-at":1348479374000,"updated-at":1348479374000,"_id":"542692d4c026201cdc327019"},{"author":{"login":"xiepan","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/c278acb4a5a933c93a68f87cbe95e16c?r=PG&default=identicon"},"editors":[],"body":";; ns-map = ns-refers + ns-interns + ns-imports\nuser=> (count (ns-imports *ns*))\n;;=> 96\n\nuser=> (count (ns-interns *ns*))\n;;=> 2\n\nuser=> (count (ns-refers *ns*))\n;;=> 590\n\nuser=> (+ *1 *2 *3)\n;;=> 688\n\nuser=> (count (ns-map *ns*))\n;;=> 688","created-at":1356702864000,"updated-at":1356702864000,"_id":"542692d4c026201cdc32701a"}],"notes":null,"arglists":["ns"],"doc":"Returns a map of all the mappings for the namespace.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/ns-map"},{"added":"1.0","ns":"clojure.core","name":"set-validator!","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1364873765000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"atom","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ea4"},{"created-at":1364873772000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"agent","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ea5"},{"created-at":1364873776000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"ref","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ea6"}],"line":2406,"examples":[{"updated-at":1575082178619,"created-at":1326874022000,"body":"user=> (def atm (atom [2]))\n#'user/atm\n\nuser=> (set-validator! atm #(every? even? %))\nnil\n\nuser=> (swap! atm into [5])\n#\n\nuser=> (set-validator! atm nil)\nnil\n\nuser=> (swap! atm into [5]))\n[2 5]","editors":[{"avatar-url":"https://www.gravatar.com/avatar/4b9f5878e727c1bc92648eef74b99c85?r=PG&default=identicon","account-source":"clojuredocs","login":"nickbauman"},{"avatar-url":"https://avatars.githubusercontent.com/u/69976?v=2","account-source":"github","login":"abrooks"},{"login":"eggsyntax","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1233514?v=4"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/4b9f5878e727c1bc92648eef74b99c85?r=PG&default=identicon","account-source":"clojuredocs","login":"nickbauman"},"_id":"542692d5c026201cdc327081"},{"editors":[{"login":"beoliver","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1413969?v=4"}],"body":"user=> (def a 1)\n#'user/a\n\nuser=> (set-validator! (var a) (fn [update-result] (< update-result 3)))\nnil\n\nuser=> (alter-var-root (var a) inc)\n2\n\nuser=> (alter-var-root (var a) inc)\nIllegalStateException Invalid reference state clojure.lang.ARef.validate (ARef.java:33)\n\nuser=> a\n2","author":{"avatar-url":"https://avatars2.githubusercontent.com/u/1413969?v=4","account-source":"github","login":"beoliver"},"created-at":1509261847201,"updated-at":1509262058025,"_id":"59f58217e4b0a08026c48c7e"}],"notes":[{"updated-at":1330569448000,"body":"If you want your validator to throw an exception with a useful message, make sure it is a RuntimeException (or subclass), otherwise ARef#validate will throw an IllegalStateException with a generic message.","created-at":1330569448000,"author":{"login":"TimMc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5d532e51427ef2f4ded31aaca16c8baf?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fd9"}],"arglists":["iref validator-fn"],"doc":"Sets the validator-fn for a var/ref/agent/atom. validator-fn must be nil or a\n side-effect-free fn of one argument, which will be passed the intended\n new state on any state change. If the new state is unacceptable, the\n validator-fn should return false or throw an exception. If the current state (root\n value if var) is not acceptable to the new validator, an exception\n will be thrown and the validator will not be changed.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/set-validator!"},{"added":"1.9","ns":"clojure.core","name":"ident?","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1495714949645,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"simple-ident?","ns":"clojure.core"},"_id":"5926cc85e4b093ada4d4d757"},{"created-at":1495714961458,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"qualified-ident?","ns":"clojure.core"},"_id":"5926cc91e4b093ada4d4d758"},{"created-at":1596594971704,"author":{"login":"wdhowe","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/4631165?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"keyword?","ns":"clojure.core"},"_id":"5f2a1b1be4b0b1e3652d7369"},{"created-at":1596594982016,"author":{"login":"wdhowe","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/4631165?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"symbol?","ns":"clojure.core"},"_id":"5f2a1b26e4b0b1e3652d736a"}],"line":1627,"examples":[{"updated-at":1596591509304,"created-at":1596591509304,"author":{"login":"wdhowe","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/4631165?v=4"},"body":"(ident? :hello)\n;;=> true\n\n(ident? 'abc)\n;;=> true\n\n(ident? \"hi\")\n;;=> false\n\n(ident? 123)\n;;=> false","_id":"5f2a0d95e4b0b1e3652d7368"}],"notes":null,"arglists":["x"],"doc":"Return true if x is a symbol or keyword","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/ident_q"},{"added":"1.2","ns":"clojure.core","name":"defprotocol","file":"clojure/core_deftype.clj","type":"macro","column":1,"see-alsos":[{"created-at":1289830442000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"reify","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bbd"},{"created-at":1289830461000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"extend-type","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bbe"},{"created-at":1289830466000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"extend-protocol","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bbf"},{"created-at":1302045794000,"author":{"login":"TimMc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5d532e51427ef2f4ded31aaca16c8baf?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"extends?","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bc0"},{"created-at":1345918777000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"satisfies?","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bc1"},{"created-at":1432923297245,"author":{"login":"mars0i","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1836941?v=3"},"to-var":{"ns":"clojure.core","name":"definterface","library-url":"https://github.com/clojure/clojure"},"_id":"5568aca1e4b01ad59b65f4e7"},{"created-at":1432923360775,"author":{"login":"mars0i","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1836941?v=3"},"to-var":{"ns":"clojure.core","name":"gen-interface","library-url":"https://github.com/clojure/clojure"},"_id":"5568ace0e4b03e2132e7d17c"},{"created-at":1432923510740,"author":{"login":"mars0i","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1836941?v=3"},"to-var":{"ns":"clojure.core","name":"defrecord","library-url":"https://github.com/clojure/clojure"},"_id":"5568ad76e4b03e2132e7d17e"},{"created-at":1432923517065,"author":{"login":"mars0i","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1836941?v=3"},"to-var":{"ns":"clojure.core","name":"deftype","library-url":"https://github.com/clojure/clojure"},"_id":"5568ad7de4b03e2132e7d17f"}],"line":716,"examples":[{"author":{"login":"Kototama","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a54a4dc204925d397ca010b9a332e74d?r=PG&default=identicon"},"editors":[{"login":"Kototama","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a54a4dc204925d397ca010b9a332e74d?r=PG&default=identicon"},{"login":"Kototama","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a54a4dc204925d397ca010b9a332e74d?r=PG&default=identicon"},{"login":"Kototama","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a54a4dc204925d397ca010b9a332e74d?r=PG&default=identicon"},{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},{"login":"maacl","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8ff89765136c38707e0f57cf48679a13?r=PG&default=identicon"},{"login":"TimMc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5d532e51427ef2f4ded31aaca16c8baf?r=PG&default=identicon"},{"login":"pjlegato","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/4ce55cfd8b3ae2f63f5ecbc8fc1c05d4?r=PG&default=identicon"}],"body":"(defprotocol Fly\n \"A simple protocol for flying\"\n (fly [this] \"Method to fly\"))\n\n(defrecord Bird [name species]\n Fly\n (fly [this] (str (:name this) \" flies...\")))\n\n(extends? Fly Bird)\n-> true\n\n(def crow (Bird. \"Crow\" \"Corvus corax\"))\n\n(fly crow)\n-> \"Crow flies...\"","created-at":1286490281000,"updated-at":1348996644000,"_id":"542692cfc026201cdc326e14"},{"author":{"login":"Kototama","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a54a4dc204925d397ca010b9a332e74d?r=PG&default=identicon"},"editors":[{"login":"Ljos","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/45b996a79abca465acaf6c0f10b0437?r=PG&default=identicon"}],"body":";; from Stuart Halloway's examples:\n\n(defprotocol Player\n (choose [p])\n (update-strategy [p me you]))\n\n(defrecord Stubborn [choice]\n Player\n (choose [_] choice)\n (update-strategy [this _ _] this))\n\n(defrecord Mean [last-winner]\n Player\n (choose [_]\n (if last-winner\n last-winner\n (random-choice)))\n (update-strategy [_ me you]\n (->Mean (when (iwon? me you) me))))\n","created-at":1286490493000,"updated-at":1358536428000,"_id":"542692cfc026201cdc326e1c"},{"author":{"login":"franks42","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/b3ee701dd6c481e5d310467ddfe62c48?r=PG&default=identicon"},"editors":[{"avatar-url":"https://avatars3.githubusercontent.com/u/889685?v=4","account-source":"github","login":"huahaiy"}],"body":";; defprotocol does NOT support interfaces with variable argument lists, \n;; like [this & args]\n;; (this is not documented anywhere... )\n\n;; The error message encountered will be something like \"No single method: \n;; x_y_z of interface: ns.Foo found for function: x-y-z of protocol: Foo\"\n\n;; The workaround is to define the interface with the variable arg list in a fn\n;; separately outside of the protocol, which then calls the protocol interface\n;; with a slightly different name and an array in place of the variable list,\n;; like:\n\n(defprotocol MyProtocol\n (-my-fn [this args]))\n\n(defn my-fn [this & args] (-my-fn this args))","created-at":1358608093000,"updated-at":1593221853032,"_id":"542692d2c026201cdc326f80"},{"author":{"login":"bmabey","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/b966e0fe46246f9a0641fa2e322fec38?r=PG&default=identicon"},"editors":[],"body":";; Protocols allow you to add new abstractions to existing types in a clean way.\n;; Polymorphic functions are created in namespaces as opposed to\n;; having the polymorphism live on Classes as typically done in OO.\n\n;; example from: \n;; https://speakerdeck.com/bmabey/clojure-plain-and-simple?slide=230\n(ns abstraction-a)\n\n(defprotocol AbstractionA\n (foo [obj]))\n\n(extend-protocol AbstractionA\n nil\n (foo [s] (str \"foo-A!\"))\n String\n (foo [s] (str \"foo-A-\" (.toUpperCase s))))\n\n(ns abstraction-b)\n\n(defprotocol AbstractionB\n (foo [obj]))\n\n(extend-protocol AbstractionB\n nil\n (foo [s] (str \"foo-B!\"))\n String\n (foo [s] (str \"foo-B-\" (.toLowerCase s))))\n\n\nuser=> (require '[abstraction-a :as a])\n\nuser=> (require '[abstraction-b :as b])\n\nuser=> (a/foo \"Bar\")\n\"foo-A-BAR\"\n\nuser=> (b/foo \"Bar\")\n\"foo-B-bar\"\n\nuser=> (a/foo nil)\n\"foo-A!\"\n\nuser=> (b/foo nil)\n\"foo-B!\"\n","created-at":1380075979000,"updated-at":1380075979000,"_id":"542692d2c026201cdc326f81"},{"body":";; Note these differences between defprotocol and definterface:\n\n;; defprotocol requires that methods specify a first parameter, which \n;; will be the record object, while definterface requires that this\n;; parameter be left out:\n(definterface I (fooey []))\n;=> user.I\n(defprotocol P (fooey []))\n;=> IllegalArgumentException Definition of function fooey in protocol P must take at least one arg. clojure.core/emit-protocol/fn--5964 (core_deftype.clj:612)\n(defprotocol P (fooey [this]))\n;=> P\n\n;; However, defrecord requires that a parameter for the record object\n;; be used, even with interfaces. (A similar point applies to deftype.)\n(defrecord Irec [stuff] I (fooey [] \"foo\"))\n;=> CompilerException java.lang.IllegalArgumentException: Must supply at least one argument for 'this' in: fooey, compiling:(NO_SOURCE_PATH:1:1) \n(defrecord Irec [stuff] I (fooey [this] \"foo\"))\n;=> user.Irec\n(defrecord Prec [stuff] P (fooey [this] \"foo\"))\n;=> user.Prec\n\n;; Using an interface, only the dot form of the method is available with \n;; defrecord, while the protocol also allows use of normal Clojure function\n;; syntax. (Similar points apply to deftype.)\n(.fooey (Irec. 42))\n;=> \"foo\"\n(fooey (Irec. 42))\n;=> IllegalArgumentException No implementation of method: :fooey of protocol: #'user/P found for class: user.Irec clojure.core/-cache-protocol-fn (core_deftype.clj:544)\n(.fooey (Prec. 42))\n;=> \"foo\"\n(fooey (Prec. 42))\n;=> \"foo\"\n","author":{"login":"mars0i","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1836941?v=3"},"created-at":1432923158804,"updated-at":1432923158804,"_id":"5568ac16e4b03e2132e7d17a"}],"macro":true,"notes":null,"arglists":["name & opts+sigs"],"doc":"A protocol is a named set of named methods and their signatures:\n (defprotocol AProtocolName\n\n ;optional doc string\n \"A doc string for AProtocol abstraction\"\n\n ;options\n :extend-via-metadata true\n\n ;method signatures\n (bar [this a b] \"bar docs\")\n (baz [this a] [this a b] [this a b c] \"baz docs\"))\n\n No implementations are provided. Docs can be specified for the\n protocol overall and for each method. The above yields a set of\n polymorphic functions and a protocol object. All are\n namespace-qualified by the ns enclosing the definition The resulting\n functions dispatch on the type of their first argument, which is\n required and corresponds to the implicit target object ('this' in \n Java parlance). defprotocol is dynamic, has no special compile-time \n effect, and defines no new types or classes. Implementations of \n the protocol methods can be provided using extend.\n\n When :extend-via-metadata is true, values can extend protocols by\n adding metadata where keys are fully-qualified protocol function\n symbols and values are function implementations. Protocol\n implementations are checked first for direct definitions (defrecord,\n deftype, reify), then metadata definitions, then external\n extensions (extend, extend-type, extend-protocol)\n\n defprotocol will automatically generate a corresponding interface,\n with the same name as the protocol, i.e. given a protocol:\n my.ns/Protocol, an interface: my.ns.Protocol. The interface will\n have methods corresponding to the protocol functions, and the\n protocol will automatically work with instances of the interface.\n\n Note that you should not use this interface with deftype or\n reify, as they support the protocol directly:\n\n (defprotocol P \n (foo [this]) \n (bar-me [this] [this y]))\n\n (deftype Foo [a b c] \n P\n (foo [this] a)\n (bar-me [this] b)\n (bar-me [this y] (+ c y)))\n \n (bar-me (Foo. 1 2 3) 42)\n => 45\n\n (foo \n (let [x 42]\n (reify P \n (foo [this] 17)\n (bar-me [this] x)\n (bar-me [this y] x))))\n => 17","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/defprotocol"},{"added":"1.0","ns":"clojure.core","name":"swap!","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1285759338000,"author":{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},"to-var":{"ns":"clojure.core","name":"atom","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e05"},{"created-at":1289908501000,"author":{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},"to-var":{"ns":"clojure.core","name":"reset!","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e06"},{"created-at":1416850487272,"author":{"login":"kumarshantanu","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109792?v=3"},"to-var":{"ns":"clojure.core","name":"compare-and-set!","library-url":"https://github.com/clojure/clojure"},"_id":"54736c37e4b03d20a10242b4"},{"created-at":1527704983219,"author":{"login":"agarman","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/138454?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"swap-vals!","ns":"clojure.core"},"_id":"5b0eed97e4b045c27b7fac7c"}],"line":2362,"examples":[{"author":{"login":"Kototama","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a54a4dc204925d397ca010b9a332e74d?r=PG&default=identicon"},"editors":[{"login":"jamieorc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/ad647269ea91f1d48b3e76624d89f1d0?r=PG&default=identicon"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":";; make an atomic list\n(def players (atom ()))\n;; #'user/players\n\n;; conjoin a keyword into that list\n(swap! players conj :player1)\n;;=> (:player1)\n\n;; conjoin a second keyword into the list\n(swap! players conj :player2)\n;;=> (:player2 :player1)\n\n;; take a look at what is in the list\n(deref players)\n;;=> (:player2 :player1)","created-at":1286491687000,"updated-at":1420734256040,"_id":"542692cdc026201cdc326d54"},{"author":{"login":"Kototama","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a54a4dc204925d397ca010b9a332e74d?r=PG&default=identicon"},"editors":[{"login":"jamieorc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/ad647269ea91f1d48b3e76624d89f1d0?r=PG&default=identicon"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":";; how to: atomic counter \n(def counter (atom 0))\n;; #'user/counter\n\n(swap! counter inc)\n;;=> 1\n\n(swap! counter inc)\n;;=> 2","created-at":1286491725000,"updated-at":1420734313570,"_id":"542692cdc026201cdc326d56"},{"author":{"login":"esumitra","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d3df4ff6342ed6fba898021bf2d19a6d?r=PG&default=identicon"},"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":";; swap map values\n(def m1 (atom {:a \"A\" :b \"B\"}))\n;; atom\n\n;; dereference the atom\n@m1\n;;=> {:a \"A\", :b \"B\"}\n\n;; notice that the value swapped in, is part of the returned value\n(swap! m1 assoc :a \"Aaay\")\n;;=> {:a \"Aaay\", :b \"B\"}","created-at":1408514586000,"updated-at":1420734414461,"_id":"542692d5c026201cdc32709f"},{"editors":[{"login":"sj4","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8431449?v=3"}],"body":";; increment a map value\n(def m1 (atom {:a \"A\" :b \"B\" :n 0}))\n;; atom\n\n;; dereference the atom\n@m1\n;;=> {:a \"A\", :b \"B\", :n 0}\n\n;; notice that the value swapped in, is part of the returned value\n(swap! m1 update-in [:n] inc)\n;;=> {:a \"A\", :b \"B\", :n 1}","author":{"avatar-url":"https://avatars.githubusercontent.com/u/17842?v=3","account-source":"github","login":"ghiden"},"created-at":1447720194998,"updated-at":1477140034391,"_id":"564a7502e4b0be225c0c4794"},{"updated-at":1518531750651,"created-at":1518531750651,"author":{"login":"ibercode","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/31028993?v=4"},"body":"(def car\n (atom {:make \"Audi\"\n :model \"Q3\"}))\n\n@car\n;;{:make \"Audi\", :model \"Q3\"}\n\n(swap!\n car\n assoc :model \"Q5\")\n;;{:make \"Audi\", :model \"Q5\"}\n\n(swap!\n car\n update-in [:model] str \" Sport\")\n;;{:make \"Audi\", :model \"Q5 Sport\"}","_id":"5a82f4a6e4b0316c0f44f8bb"},{"updated-at":1648892616887,"created-at":1648892539184,"author":{"login":"Kaspazza","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/36607370?v=4"},"body":";; Update vector inside map\n(def data (atom {:name \"hello\" :nums []}))\n\n@data\n;; {:name \"hello\" :nums []}\n\n(swap! data update :nums conj {:first 1 :second 2})\n;; {:name \"hello\" :nums [{:first 1 :second 2}]}\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/36607370?v=4","account-source":"github","login":"Kaspazza"}],"_id":"62481a7be4b0b1e3652d75c7"}],"notes":[{"author":{"login":"amirrajan","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/517055?v=3"},"updated-at":1466249130785,"created-at":1466249130785,"body":"If you want to swap the entire atom, user `reset!`.","_id":"57652faae4b0bafd3e2a0489"},{"author":{"login":"KyleErhabor","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/40676441?v=4"},"updated-at":1655085693891,"created-at":1655085693891,"body":"When using `swap!`, it's important you're *only* taking into consideration the\nvalue of the atom *inside* `f`. See https://ericnormand.me/mini-guide/atom-code-explanation for more information.","_id":"62a69a7de4b0b1e3652d75fe"}],"arglists":["atom f","atom f x","atom f x y","atom f x y & args"],"doc":"Atomically swaps the value of atom to be:\n (apply f current-value-of-atom args). Note that f may be called\n multiple times, and thus should be free of side effects. Returns\n the value that was swapped in.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/swap!"},{"added":"1.0","ns":"clojure.core","name":"vals","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1318590020000,"author":{"login":"mmwaikar","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/29d36f4c9f39c9f8ff61c07033b13118?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"val","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521aa9"},{"created-at":1359517156000,"author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"to-var":{"ns":"clojure.core","name":"keys","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521aaa"},{"created-at":1423522691570,"author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"to-var":{"ns":"clojure.core","name":"key","library-url":"https://github.com/clojure/clojure"},"_id":"54d93b83e4b0e2ac61831d37"},{"created-at":1517623064066,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"hash-map","ns":"clojure.core"},"_id":"5a751718e4b0e2d9c35f7415"}],"line":1576,"examples":[{"updated-at":1431626759785,"created-at":1280776235000,"body":"(vals {:a \"foo\", :b \"bar\"})\n;;=> (\"foo\" \"bar\")\n\n(vals {})\n;;=> nil\n\n(vals nil)\n;;=> nil","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2","account-source":"github","login":"phreed"},{"avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3","account-source":"github","login":"Dimagog"},{"avatar-url":"https://avatars.githubusercontent.com/u/6926?v=3","account-source":"github","login":"aleksandersumowski"},{"avatar-url":"https://avatars.githubusercontent.com/u/1033604?v=3","account-source":"github","login":"fourq"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3","account-source":"github","login":"devn"},"_id":"542692c8c026201cdc326a08"},{"updated-at":1471129931147,"created-at":1471129931147,"author":{"login":"sleyzerzon","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/528932?v=3"},"body":"(defn flatten-a-map [dpdnts-map]\n (apply set/union (vals dpdnts-map)))\n\n(flatten-a-map {:e #{:m :f}, :c #{:f}, :b #{:c :f}, :d #{:m :f}, :a #{:c :f}}\n\n;;=> #{:m :c :f}","_id":"57afa94be4b02d8da95c26f7"}],"notes":[{"updated-at":1385457081000,"body":"Functions keys and vals return sequences such that\r\n
    \r\n(= (zipmap (keys m) (vals m)) m)\r\n
    ","created-at":1385457081000,"author":{"login":"akhudek","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/aaf21f137b69cc5154c8afb29b793e18?r=PG&default=identicon"},"_id":"542692edf6e94c6970522011"}],"arglists":["map"],"doc":"Returns a sequence of the map's values, in the same order as (seq map).","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/vals"},{"added":"1.0","ns":"clojure.core","name":"unchecked-subtract","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1289216526000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"unchecked-add","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b98"},{"created-at":1289216530000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"unchecked-dec","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b99"},{"created-at":1289216535000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"unchecked-inc","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b9a"},{"created-at":1289216540000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"unchecked-negate","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b9b"},{"created-at":1289216544000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"unchecked-divide","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b9c"},{"created-at":1289216549000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"unchecked-subtract","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b9d"},{"created-at":1289216555000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"unchecked-multiply","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b9e"},{"created-at":1289216559000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"unchecked-remainder","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b9f"},{"created-at":1423522496433,"author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"to-var":{"ns":"clojure.core","name":"-","library-url":"https://github.com/clojure/clojure"},"_id":"54d93ac0e4b0e2ac61831d33"},{"created-at":1423522501593,"author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"to-var":{"ns":"clojure.core","name":"-'","library-url":"https://github.com/clojure/clojure"},"_id":"54d93ac5e4b081e022073c77"}],"line":1226,"examples":[{"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"reborg","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/20086?v=3"}],"body":";; can't interchange INTs with LONGs, only F(int, int) or F(long, long)\n;; F is a function, not an\n;; overflow very easily as shown below.\n\n(unchecked-subtract Long/MIN_VALUE 5555555554)\nuser=> 9223372031299220254\n\n;; it promotes to long\n(unchecked-subtract Long/MIN_VALUE (int 1))\nuser=> 9223372036854775807\n\n(unchecked-subtract Integer/MIN_VALUE Long/MIN_VALUE)\nuser=> 9223372034707292160\n\n(unchecked-subtract Long/MIN_VALUE Long/MIN_VALUE)\nuser=> 0\n\n(unchecked-subtract Integer/MIN_VALUE Integer/MIN_VALUE)\nuser=> 0\n\n(unchecked-subtract Integer/MIN_VALUE 0)\nuser=> -2147483648\n\n;; Again, promote to long\n(unchecked-subtract Integer/MIN_VALUE 1)\nuser=> -2147483649\n\n;; To prevent long promotion, see unchecked-subtract-int ","created-at":1289216520000,"updated-at":1418679203559,"_id":"542692cac026201cdc326b46"}],"notes":null,"arglists":["x y"],"doc":"Returns the difference of x and y, both long.\n Note - uses a primitive operator subject to overflow.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/unchecked-subtract"},{"added":"1.10","ns":"clojure.core","name":"tap>","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1590688347515,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/109629?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"add-tap","ns":"clojure.core"},"_id":"5ecffa5be4b087629b5a1917"},{"created-at":1590688354528,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/109629?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"remove-tap","ns":"clojure.core"},"_id":"5ecffa62e4b087629b5a1918"}],"line":8124,"examples":[{"updated-at":1590688330192,"created-at":1590688330192,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/109629?v=4"},"body":";; For a bit more documentation, see Clojure 1.10.0 release notes regarding\n;; tap> here:\n\n;; https://github.com/clojure/clojure/blob/master/changes.md#23-tap","_id":"5ecffa4ae4b087629b5a1916"},{"editors":[{"login":"cloojure","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7083783?v=4"}],"body":";; Register a tap handler\n\n(add-tap (bound-fn* clojure.pprint/pprint))\n\n;; Log using the above handler\n\n(tap> \"Hello world\")","author":{"avatar-url":"https://avatars.githubusercontent.com/u/1250807?v=4","account-source":"github","login":"maxthoursie"},"created-at":1630499566267,"updated-at":1638836325268,"_id":"612f72eee4b0b1e3652d7538"},{"updated-at":1685388563826,"created-at":1685388468155,"author":{"login":"cloped","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/25209410?v=4"},"body":";; Using tap but returning initial content\n(defn major-champs [] [{:team-name \"SK\"}\n {:team-name \"LG\"}])\n\n(doto (major-champs)\n (tap>))\n;;=> [{:team-name \"SK\"} {:team-name \"LG\"}]","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/25209410?v=4","account-source":"github","login":"cloped"}],"_id":"6474fcb4e4b08cf8563f4bc4"}],"notes":[{"author":{"login":"Crowbrammer","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/19522656?v=4"},"updated-at":1651676980432,"created-at":1651676980432,"body":"`tap>` is a primary tool in the [Portal](https://github.com/djblue/portal) library. ","_id":"62729734e4b0b1e3652d75e6"}],"arglists":["x"],"doc":"sends x to any taps. Will not block. Returns true if there was room in the queue,\n false if not (dropped).","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/tap>"},{"added":"1.0","ns":"clojure.core","name":"*warn-on-reflection*","type":"var","see-alsos":[{"created-at":1441815046413,"author":{"login":"miner","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/25400?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"*unchecked-math*","ns":"clojure.core"},"_id":"55f05a06e4b06a9ffaad4fb9"}],"examples":[{"author":{"login":"shockbob","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon"},"editors":[{"login":"shockbob","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon"},{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"}],"body":";; define two variables then set *warn-on-reflection* to true and try to call\n;; one of their Java methods. Warnings are generated in both cases\n;; set *warn-on-reflection* to false and note that you can call both functions\n;; without a warning\n\nuser=> (def i 23)\n#'user/i\nuser=> (def s \"123\")\n#'user/s\nuser=> (set! *warn-on-reflection* true)\ntrue\nuser=> (.toString i)\nReflection warning, NO_SOURCE_PATH:4 - reference to field toString can't be resolved.\n\"23\"\nuser=> (.toString s)\nReflection warning, NO_SOURCE_PATH:5 - reference to field toString can't be resolved.\n\"123\"\n\n;; Reflection (and hence reflection warnings) could be removed by giving type hints:\nuser=> (.toString ^String s)\n\"123\"\n\nuser=> (set! *warn-on-reflection* false)\nfalse\nuser=> (.toString i)\n\"23\"\nuser=> (.toString s)\n\"123\"\nuser=>","created-at":1313969775000,"updated-at":1423526770411,"_id":"542692c9c026201cdc326a80"},{"updated-at":1672450302873,"created-at":1672450302873,"author":{"login":"randomizedthinking","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/5283430?v=4"},"body":"(set! *warn-on-reflection* true) ;; turn on *warn-on-reflection*\n(def s \"abc\") ;; define s\n(.toString s) ;; => \"abc\"; WARN: type of s is unknown\n(.toString ^String s) ;; => \"abc\"; no warn given the type hint\n(let [s \"abc\"] (.toString s)) ;; => \"abc\"; no warn since Clojure can infer\n ;; type for the local binding\n(set! *warn-on-reflection* false) ;; turn off *warn-on-reflection*\n","_id":"63af90fee4b08cf8563f4b57"},{"updated-at":1672450954887,"created-at":1672450954887,"author":{"login":"randomizedthinking","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/5283430?v=4"},"body":";; Important to note *warn-on-reflection* take its effect at compile time,\n;; so binding the option won't work... even with a set! inside.\n;; - binding creates a new env to evaluate subsequent statements\n;; - yet, compiler still lives in the current env, so it won't see the value\n\n(binding [*warn-on-reflection* true]\n (set! *warn-on-reflection* true)\n (def s \"abc\")\n (.toString s)) ;; => \"abc\", no warning\n(println *warn-on-reflection*) ;; => false\n","_id":"63af938ae4b08cf8563f4b58"}],"notes":null,"arglists":[],"doc":"When set to true, the compiler will emit warnings when reflection is\n needed to resolve Java method calls or field accesses.\n\n Defaults to false.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/*warn-on-reflection*"},{"added":"1.1","ns":"clojure.core","name":"sorted-set-by","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1317095652000,"author":{"login":"pauldoo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5cb916d3c8abc9f45a093209e72489fb?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"sorted-set","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e50"},{"created-at":1353458232000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.core","name":"sorted-map-by","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e51"},{"created-at":1353822010000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.core","name":"compare","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e52"}],"line":427,"examples":[{"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"editors":[],"body":"user> (sorted-set-by > 3 5 8 2 1)\n#{8 5 3 2 1}","created-at":1286955847000,"updated-at":1286955847000,"_id":"542692cdc026201cdc326ccc"},{"updated-at":1548548862480,"created-at":1353462397000,"body":";; Be cautious about comparison functions that only compare part of\n;; the objects:\nuser=> (defn second-< [x y]\n (< (second x) (second y)))\nuser=> (sorted-set-by second-< [:a 1] [:b 1] [:c 1])\n#{[:a 1]}\n\n;; Where did the other elements go?\n\n;; Replacing < with <= might look like a fix, but doesn't work,\n;; either:\nuser=> (defn second-<= [x y]\n (<= (second x) (second y)))\nuser=> (def s2 (sorted-set-by second-<= [:a 1] [:b 1] [:c 1]))\n#'user/s2\nuser=> s2\n#{[:c 1] [:b 1] [:a 1]}\n;; So far, so good, but set membership tests can't find the elements.\nuser=> (contains? s2 [:b 1])\nfalse\nuser=> (s2 [:c 1])\nnil\n\n;; Here is one way to write a good comparison function. When the two\n;; objects are equal in the parts we care about, use the tie-breaker\n;; 'compare' on the whole values to give them a consistent order that\n;; is only equal if the entire values are equal.\nuser=> (defn second-<-with-tie-break [x y]\n (let [c (compare (second x) (second y))]\n (if (not= c 0)\n c\n ;; Otherwise we don't care as long as ties are broken\n ;; consistently.\n (compare x y))))\nuser=> (def s3 (sorted-set-by second-<-with-tie-break [:a 1] [:b 1] [:c 1]))\n#'user/s3\nuser=> s3\n#{[:a 1] [:b 1] [:c 1]}\nuser=> (contains? s3 [:b 1])\ntrue\nuser=> (s3 [:c 1])\n[:c 1]\n;; All good now!\n\n;; See this article for more details: https://clojure.org/guides/comparators","editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/109629?v=4"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3","account-source":"github","login":"jafingerhut"},"_id":"542692d5c026201cdc327096"},{"updated-at":1533310624576,"created-at":1533310624576,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"body":";; Another custom comparator example.\n;; sorted-set of colls by size descending, then normal coll equality:\n\n(sorted-set-by \n (fn [x y] (compare [(count y) x] [(count x) y]))\n [3 :a] [:b] [1 :c] [:v] [:a])\n\n;; #{[1 :c] [3 :a] [:a] [:b] [:v]}","_id":"5b6476a0e4b00ac801ed9e47"}],"notes":null,"arglists":["comparator & keys"],"doc":"Returns a new sorted set with supplied keys, using the supplied\n comparator. Any equal keys are handled as if by repeated uses of\n conj.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/sorted-set-by"},{"added":"1.0","ns":"clojure.core","name":"sync","file":"clojure/core.clj","type":"macro","column":1,"see-alsos":[{"created-at":1285922313000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"dosync","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c4a"}],"line":2515,"examples":null,"macro":true,"notes":[{"updated-at":1285922372000,"body":"Same as dosync but allows for extra options (which are not currently supported). Probably best to use dosync instead at the moment.","created-at":1285922372000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521f97"}],"arglists":["flags-ignored-for-now & body"],"doc":"transaction-flags => TBD, pass nil for now\n\n Runs the exprs (in an implicit do) in a transaction that encompasses\n exprs and any nested calls. Starts a transaction if none is already\n running on this thread. Any uncaught exception will abort the\n transaction and flow out of sync. The exprs may be run more than\n once, but any effects on Refs will be atomic.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/sync"},{"added":"1.9","ns":"clojure.core","name":"qualified-ident?","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1495714973950,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"ident?","ns":"clojure.core"},"_id":"5926cc9de4b093ada4d4d759"},{"created-at":1495714979401,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"simple-ident?","ns":"clojure.core"},"_id":"5926cca3e4b093ada4d4d75a"},{"created-at":1596595698804,"author":{"login":"wdhowe","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/4631165?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"qualified-symbol?","ns":"clojure.core"},"_id":"5f2a1df2e4b0b1e3652d736e"},{"created-at":1596595706676,"author":{"login":"wdhowe","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/4631165?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"qualified-keyword?","ns":"clojure.core"},"_id":"5f2a1dfae4b0b1e3652d736f"}],"line":1637,"examples":[{"updated-at":1596596073730,"created-at":1596596073730,"author":{"login":"wdhowe","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/4631165?v=4"},"body":"(qualified-ident? 'clojure.core/asymbol)\n;;=> true\n\n(qualified-ident? ::akeyword)\n;;=> true\n\n(qualified-ident? 'asymbol)\n;;=> false\n\n(qualified-ident? :akeyword)\n;;=> false\n\n(qualified-ident? \"hello\")\n;;=> false\n\n(qualified-ident? 7)\n;;=> false\n\n(qualified-ident? nil)\n;;=> false","_id":"5f2a1f69e4b0b1e3652d7370"}],"notes":null,"arglists":["x"],"doc":"Return true if x is a symbol or keyword with a namespace","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/qualified-ident_q"},{"added":"1.0","ns":"clojure.core","name":"assert","file":"clojure/core.clj","type":"macro","column":1,"see-alsos":[{"created-at":1538056745370,"author":{"login":"witek","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/209520?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"assert","ns":"clojure.spec.alpha"},"_id":"5bace229e4b00ac801ed9eaa"}],"line":4866,"examples":[{"author":{"login":"dakrone","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bcacd00a7f05c4772329cf9f446c7987?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":"user=> (assert true)\nnil\n\nuser=> (assert false)\njava.lang.AssertionError: Assert failed: false (NO_SOURCE_FILE:0)\n\nuser=> (assert nil)\njava.lang.AssertionError: Assert failed: nil (NO_SOURCE_FILE:0)\n\nuser=> (assert 0)\nnil\n\nuser=> (assert [1 2 3])\nnil\n\nuser=> (assert \"foo\")\nnil","created-at":1280547946000,"updated-at":1285496150000,"_id":"542692cac026201cdc326aff"},{"body":";; Messages can help you track down what went wrong.\nuser=> (assert (= 5 (+ 2 2)) \"There are four lights!\")\n\nAssertionError Assert failed: There are four lights!","author":{"login":"jakebasile","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/766907?v=2"},"created-at":1412964928037,"updated-at":1412964928037,"_id":"54382240e4b0ae7956031582"},{"updated-at":1704391970105,"created-at":1704391970105,"author":{"login":"sofiiahitlan","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/48576209?v=4"},"body":";; AssertionError isn't an Exception so it should be caught properly:\nuser=> (try\n (let [some-with-cond? (fn [el]\n {:pre [(some? el)]}\n (some? el))]\n (some-with-cond? nil))\n (catch AssertionError e \"AssertionError caught.\"))\n\nAssertionError caught.\n\n;; catch Exception wouldn't work:\nuser=> (try\n (let [some-with-cond? (fn [el]\n {:pre [(some? el)]}\n (some? el))]\n (some-with-cond? nil))\n (catch Exception e \"AssertionError caught.\"))\n\nExecution error (AssertionError) at loaders.core/eval26824$some-with-cond? (form-init14472288491470508923.clj:5587).\nAssert failed: (some? el)","_id":"6596f52269fbcc0c2261747e"}],"macro":true,"notes":[{"updated-at":1372297439000,"body":"The documentation (\"... and throws an exception if ...\") is incorrect. It throws AssertionError which an Error and not an Exception. They both extend Throwable but Error is not an Exception.","created-at":1372297439000,"author":{"login":"Steve Kuo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/160d6580f280b5e9e5a1188b32c4ef2d?r=PG&default=identicon"},"_id":"542692edf6e94c6970522007"},{"body":"By default, assertions are turned on, since the value of `*assert*` defaults to true in Clojure.","created-at":1571604965857,"updated-at":1571606716980,"author":{"avatar-url":"https://avatars3.githubusercontent.com/u/601540?v=4","account-source":"github","login":"didibus"},"_id":"5dacc9e5e4b0ca44402ef7cf"},{"body":"in [shadow-cljs](https://shadow-cljs.github.io/docs/UsersGuide.html#compiler-options), All assertions are removed in `release` mode by default. In other words, *assert* is false in release mode. (see `:elide-asserts` option) It is applied to schema libraries like malli, `malli.core/assert` is removed on release mode.\n\n","created-at":1757391428304,"updated-at":1757391451899,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/160077355?v=4","account-source":"github","login":"taehee-kim-sherpas"},"_id":"68bfaa44cd84df5de54e2095"}],"arglists":["x","x message"],"doc":"Evaluates expression x and throws an AssertionError with optional\n message if x does not evaluate to logical true.\n\n Assertion checks are omitted from compiled code if '*assert*' is\n false.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/assert"},{"added":"1.0","ns":"clojure.core","name":"*compile-path*","type":"var","see-alsos":null,"examples":[{"updated-at":1615140201244,"created-at":1613936568196,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/20086?v=4"},"body":";; Assuming \"mypath\" exists on disk, the following AOT-compiles any form\n;; inside \"eval\" into the folder specified by \"*compile-path*\".\n\n(binding [*compile-files* true \n *compile-path* \"mypath\"]\n (eval '(+ 1 1)))\n;; 2","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"}],"_id":"6032b7b8e4b0b1e3652d7461"}],"notes":null,"arglists":[],"doc":"Specifies the directory where 'compile' will write out .class\n files. This directory must be in the classpath for 'compile' to\n work.\n\n Defaults to \"classes\"","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/*compile-path*"},{"added":"1.0","ns":"clojure.core","name":"true?","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1303250769000,"author":{"login":"TimMc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5d532e51427ef2f4ded31aaca16c8baf?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"false?","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521da5"},{"created-at":1420558589659,"author":{"login":"kappa","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/47310?v=3"},"to-var":{"ns":"clojure.core","name":"boolean","library-url":"https://github.com/clojure/clojure"},"_id":"54ac00fde4b04e93c519ffb5"}],"line":514,"examples":[{"author":{"login":"dpritchett","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/147981?v=3"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":"user=> (true? true)\ntrue\nuser=> (true? 1)\nfalse\nuser=> (true? (= 1 1))\ntrue","created-at":1279075280000,"updated-at":1332951307000,"_id":"542692c7c026201cdc32699f"},{"updated-at":1651781147567,"created-at":1651781147567,"author":{"login":"starain31","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/6347630?v=4"},"body":"user=> (true? false)\nfalse","_id":"62742e1be4b0b1e3652d75e7"}],"notes":null,"tag":"java.lang.Boolean","arglists":["x"],"doc":"Returns true if x is the value true, false otherwise.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/true_q"},{"added":"1.0","ns":"clojure.core","name":"release-pending-sends","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":null,"line":2150,"examples":[{"updated-at":1553649905128,"created-at":1553649905128,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"body":";; release-pending-sends makes sense when an agent produces\n;; additional actions and there is no need to wait for the update\n;; of the current agent's state.\n\n(require '[clojure.string :refer [split]])\n(def alpha (mapv agent (repeat 26 0))) ; one for each letter of the alphabet\n(def others (agent 0))\n(def words (agent {}))\n\n(def war-and-peace \"http://www.gutenberg.org/files/2600/2600-0.txt\")\n(def book (slurp war-and-peace)) ; a large book\n\n(send-off words\n (fn [state]\n (doseq [letter book\n :let [l (Character/toLowerCase letter)\n idx (- (int l) (int \\a))]] ; get the index of the correct agent\n (send (get alpha idx others) inc)) ; send an increment for each letter\n (release-pending-sends) ; release those sends\n (merge-with + state ; move on to calculate word frequencies\n (frequencies (split book #\"\\s+\")))))\n\n(apply await alpha) ; give it some time\n(map deref alpha) ; see each letter frequency in the book\n;; (202719 34657 61621 118297 313572\n;; 54901 51327 167415 172257 2575 20432\n;; 96530 61648 184185 190083 45533 2331\n;; 148431 162897 226414 64400 27087\n;; 59209 4384 46236 2388)\n","_id":"5c9ad0f1e4b0ca44402ef6e0"}],"notes":null,"arglists":[""],"doc":"Normally, actions sent directly or indirectly during another action\n are held until the action completes (changes the agent's\n state). This function can be used to dispatch any pending sent\n actions immediately. This has no impact on actions sent during a\n transaction, which are still held until commit. If no action is\n occurring, does nothing. Returns the number of actions dispatched.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/release-pending-sends"},{"added":"1.0","ns":"clojure.core","name":"print","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1290672979000,"author":{"login":"dale","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a7a1eca257c6cea943fea41e5cc3e9a3?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"pr","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ca4"},{"created-at":1374264324000,"author":{"login":"lbeschastny","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/416170465e4045f810f09a9300dda4dd?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"println","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ca5"},{"created-at":1374264330000,"author":{"login":"lbeschastny","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/416170465e4045f810f09a9300dda4dd?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"print-str","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ca6"},{"created-at":1518042801277,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"pprint","ns":"clojure.pprint"},"_id":"5a7b7eb1e4b0316c0f44f8ab"},{"created-at":1565163732742,"author":{"login":"bbatsov","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/103882?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"printf","ns":"clojure.core"},"_id":"5d4a80d4e4b0ca44402ef792"},{"created-at":1565163762897,"author":{"login":"bbatsov","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/103882?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"println-str","ns":"clojure.core"},"_id":"5d4a80f2e4b0ca44402ef793"}],"line":3750,"examples":[{"author":{"login":"dakrone","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bcacd00a7f05c4772329cf9f446c7987?r=PG&default=identicon"},"editors":[],"body":";; same as println, but without a newline\nuser> (print \"foo\") (print \"foo\")\nfoofoo","created-at":1293674014000,"updated-at":1293674014000,"_id":"542692c8c026201cdc326a67"},{"updated-at":1638001638376,"created-at":1638001638376,"author":{"login":"owenRiddy","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8080718?v=4"},"body":";; Output only flushes when there is a newline. It is likely that (print)\n;; will be seen in the company of (flush).\n\n;; Buggy case. Wants to print a prompt character, but it doesn't appear.\n(print \"> \") ;; This doesn't work,\n(readline)\n\n;; Working case. The output can be flushed this way.\n(print \"> \")\n(flush)\n(readline)","_id":"61a1ebe6e4b0b1e3652d757b"},{"updated-at":1668538912352,"created-at":1668538912352,"author":{"login":"slk500","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/13615024?v=4"},"body":"(print \"foo\" \"foo\")\n;; => foo foo","_id":"6373e220e4b0b1e3652d7682"}],"notes":[{"author":{"login":"jcburley","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/430319?v=4"},"updated-at":1514410810601,"created-at":1514410810601,"body":"\"Human consumption\" means, for example, that a string is printed as-is -- without surrounding double quotes and without nonprinting characters being escaped.","_id":"5a44133ae4b0a08026c48ce1"}],"arglists":["& more"],"doc":"Prints the object(s) to the output stream that is the current value\n of *out*. print and println produce output for human consumption.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/print"},{"added":"1.0","ns":"clojure.core","name":"empty","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1311798862000,"author":{"login":"OnesimusUnbound","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2fa4c391db0d2d1744cc2cd0d787dd3d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"not-empty","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521caf"},{"created-at":1435246081050,"author":{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/94482?v=3"},"to-var":{"ns":"clojure.core","name":"empty?","library-url":"https://github.com/clojure/clojure"},"_id":"558c1e01e4b0fad27b85f925"}],"line":5294,"examples":[{"updated-at":1422931647361,"created-at":1280319600000,"body":"(empty '(1 2)) ;; => ()\n(empty [1 2]) ;; => []\n(empty {1 2}) ;; => {}\n(empty #{1 2}) ;; => #{}\n\n;; Works for PersistentQueue as well, which is slightly harder to see\n(def q (conj clojure.lang.PersistentQueue/EMPTY 1))\n;; => #'user/q\nq\n;; => #\n(seq q)\n;; => (1)\n\n(def empty-q (empty q))\n;; => #'user/empty-q\nempty-q\n;; => #\n(seq empty-q)\n;; => nil\n\n;; returns nil when input is not supported or not a collection\n(empty (int-array [1 2])) ;; => nil\n(empty 1) ;; => nil\n\n(map empty [[\\a \\b] {1 2} (range 4)])\n;; => ([] {} ())\n\n(swap! (atom (range 10)) empty) \n;; => ()\n","editors":[{"avatar-url":"https://www.gravatar.com/avatar/2fa4c391db0d2d1744cc2cd0d787dd3d?r=PG&default=identicon","account-source":"clojuredocs","login":"OnesimusUnbound"},{"avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3","account-source":"github","login":"jafingerhut"},{"avatar-url":"https://www.gravatar.com/avatar/fc0969cd0910a427052f0f6281967392?r=PG&default=identicon","account-source":"clojuredocs","login":"steloflute"},{"avatar-url":"https://www.gravatar.com/avatar/65f765955a0a25d112d33528ae6f811b?r=PG&default=identicon","account-source":"clojuredocs","login":"pmbauer"},{"avatar-url":"https://avatars.githubusercontent.com/u/92894?v=3","account-source":"github","login":"rafmagana"},{"avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3","account-source":"github","login":"Dimagog"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon","account-source":"clojuredocs","login":"gstamp"},"_id":"542692c6c026201cdc326901"},{"updated-at":1406096618000,"created-at":1349755361000,"body":";; The output will not necessarily be of the same JVM class as the input\nuser=> (class (seq [1]))\nclojure.lang.PersistentVector$ChunkedSeq\n\nuser=> (class (empty (seq [1])))\nclojure.lang.PersistentList$EmptyList\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/92894?v=3","account-source":"github","login":"rafmagana"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/5d532e51427ef2f4ded31aaca16c8baf?r=PG&default=identicon","account-source":"clojuredocs","login":"TimMc"},"_id":"542692d2c026201cdc326f9a"},{"updated-at":1438729355156,"created-at":1438729355156,"author":{"login":"kwladyka","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/3903726?v=3"},"body":";; Create the same data structure with the same metadata, but empty\n(def foo (with-meta #{1 2 3} {:some-meta 1}))\nfoo ;; => #{1 2 3}\n(meta foo) ;; => {:some-meta 1}\n\n(def empty-foo (empty foo))\nempty-foo ;; => #{}\n(meta empty-foo) ;; => {:some-meta 1}","_id":"55c1448be4b0080a1b79cdb6"}],"notes":null,"arglists":["coll"],"doc":"Returns an empty collection of the same category as coll, or nil","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/empty"},{"added":"1.0","ns":"clojure.core","name":"remove-method","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1337585035000,"author":{"login":"abrooks","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/69976?v=2"},"to-var":{"ns":"clojure.core","name":"get-method","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521abc"},{"created-at":1337585038000,"author":{"login":"abrooks","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/69976?v=2"},"to-var":{"ns":"clojure.core","name":"methods","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521abd"},{"created-at":1337585113000,"author":{"login":"abrooks","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/69976?v=2"},"to-var":{"ns":"clojure.core","name":"remove-all-methods","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521abe"},{"created-at":1341270408000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"prefers","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521abf"},{"created-at":1341270413000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"defmulti","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521ac0"},{"created-at":1341270415000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"defmethod","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521ac1"}],"line":1813,"examples":[{"author":{"login":"shockbob","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon"},"editors":[],"body":";; long example showing setting up a multi-method, then removing one of the \n;; methods, showing the multi-method has been removed\n\nuser=> (defmulti tos :Ob)\nnil\nuser=> (defn line [p1 p2] {:Ob :line :p1 p1 :p2 p2})\n#'user/line\nuser=> (defn circle [cent rad] {:Ob :circle :cent cent :rad rad})\n#'user/circle\nuser=> (defmethod tos :line [l] (str \"Line:\" (l :p1) (l :p2)))\n#\nuser=> (defmethod tos :circle [c] (str \"Circle:\" (c :cent) (c :rad)))\n#\nuser=> (def cc (circle [2 3] 3.3))\n#'user/cc\nuser=> (def ll (line [1 1][0 0]))\n#'user/ll\nuser=> (tos cc)\n\"Circle:[2 3]3.3\"\nuser=> (tos ll)\n\"Line:[1 1][0 0]\"\nuser=> (remove-method tos :line)\n#\nuser=> (tos ll)\njava.lang.IllegalArgumentException: No method in multimethod 'tos' for dispatch\nvalue: :line (NO_SOURCE_FILE:0)\nuser=>\n","created-at":1313919038000,"updated-at":1313919038000,"_id":"542692c6c026201cdc32690a"}],"notes":null,"arglists":["multifn dispatch-val"],"doc":"Removes the method of multimethod associated with dispatch-value.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/remove-method"},{"added":"1.0","ns":"clojure.core","name":"*in*","type":"var","see-alsos":[{"created-at":1302912160000,"author":{"login":"hoornet","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5834f829a9def19620d4014c46642172?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"*out*","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f55"}],"examples":null,"notes":null,"arglists":[],"doc":"A java.io.Reader object representing standard input for read operations.\n\n Defaults to System/in, wrapped in a LineNumberingPushbackReader","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/*in*"},{"ns":"clojure.core","name":"print-ctor","file":"clojure/core_print.clj","type":"function","column":1,"see-alsos":[{"created-at":1536529682606,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"print-dup","ns":"clojure.core"},"_id":"5b959512e4b00ac801ed9e91"},{"created-at":1536529703992,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"read-string","ns":"clojure.core"},"_id":"5b959527e4b00ac801ed9e92"}],"line":97,"examples":[{"updated-at":1536529666220,"created-at":1536529666220,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"body":";; print-ctor assembles print-dup suitable constructors.\n;; The construction syntax is later used to initialize the same object type with \n;; read-string. Warning: there are security implications when evaluating untrusted\n;; sources with read-string. Be sure serialized data can't be tampered with.\n\n(defrecord Point [x y])\n;; user.Point\n\n(defmethod print-dup user.Point [o w]\n (print-ctor o (fn [o w] (print-dup (vals o) w)) w))\n;; #object[clojure.lang.MultiFn 0x2409c5d]\n\n(binding [*print-dup* true] (pr-str (Point. 1 2)))\n;; \"#=(user.Point. (1 2))\"\n\n(read-string \"#=(user.Point. (1 2))\")\n;; #user.Point{:x 1, :y 2}","_id":"5b959502e4b00ac801ed9e90"}],"notes":null,"arglists":["o print-args w"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core/print-ctor"},{"added":"1.0","ns":"clojure.core","name":"letfn","special-form":true,"file":"clojure/core.clj","type":"macro","column":1,"see-alsos":[{"created-at":1290671346000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"let","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d4f"},{"created-at":1550262321823,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"fn","ns":"clojure.core"},"_id":"5c672031e4b0ca44402ef685"},{"created-at":1593366479574,"author":{"login":"mars0i","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/1836941?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"loop","ns":"clojure.core"},"_id":"5ef8d7cfe4b0b1e3652d7318"}],"line":6622,"examples":[{"updated-at":1421879657394,"created-at":1279163187000,"body":"(letfn [(twice [x]\n (* x 2))\n (six-times [y]\n (* (twice y) 3))]\n (println \"Twice 15 =\" (twice 15))\n (println \"Six times 15 =\" (six-times 15)))\n;; Twice 15 = 30\n;; Six times 15 = 90\n;;=> nil\n\n;; Unable to resolve symbol: twice in this context\n(twice 4)\n;; Evaluation aborted.\n\n;; Unable to resolve symbol: six-times in this context\n(six-times 100)\n;; Evaluation aborted.\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"avatar-url":"https://www.gravatar.com/avatar/44d451ffa4fe640f2a0f6ec05bf5d962?r=PG&default=identicon","account-source":"clojuredocs","login":"maciek"},{"avatar-url":"https://www.gravatar.com/avatar/44d451ffa4fe640f2a0f6ec05bf5d962?r=PG&default=identicon","account-source":"clojuredocs","login":"maciek"},{"avatar-url":"https://www.gravatar.com/avatar/44d451ffa4fe640f2a0f6ec05bf5d962?r=PG&default=identicon","account-source":"clojuredocs","login":"maciek"},{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3","account-source":"github","login":"phreed"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/142529?v=3","account-source":"github","login":"nipra"},"_id":"542692c7c026201cdc32694c"},{"updated-at":1442001785037,"created-at":1442001785037,"author":{"login":"miner","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/25400?v=3"},"body":";; A contrived example of mutual recursion\n(defn even2? [n]\n (letfn [(neven? [n] (if (zero? n) true (nodd? (dec n))))\n (nodd? [n] (if (zero? n) false (neven? (dec n))))]\n (neven? n)))\n","_id":"55f33379e4b05246bdf20a8b"},{"updated-at":1465311455163,"created-at":1465311354216,"author":{"login":"sleyzerzon","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/528932?v=3"},"body":";;using to create comparator\n\n(defn compartr [s1 s2]\n (letfn [ (inner-author [author] ((juxt :lname :fname) author))] \n (compare (inner-author s1) (inner-author s2))))\n=> #'user/compartr\n\n(sorted-set-by compartr\n {:fname \"Steve\" :lname \"Smith\"}\n {:fname \"David\" :lname \"Smith\"})\n\n=> #{{:fname \"David\", :lname \"Smith\"} {:fname \"Steve\", :lname \"Smith\"}}","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/528932?v=3","account-source":"github","login":"sleyzerzon"}],"_id":"5756e07ae4b0bafd3e2a047c"},{"updated-at":1621331030069,"created-at":1621330967298,"author":{"login":"green-coder","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/598193?v=4"},"body":";; letfn can be replaced with let for recursive functions\n;; which are not mutually recursive.\n\n(letfn [(mul-2 [n]\n (if (zero? n)\n 0\n (+ 2 (mul-2 (dec n)))))]\n (mul-2 5))\n=> 10\n\n(let [mul-2 (fn mul-2 [n]\n (if (zero? n)\n 0\n (+ 2 (mul-2 (dec n)))))]\n (mul-2 5))\n=> 10","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/598193?v=4","account-source":"github","login":"green-coder"}],"_id":"60a38c17e4b0b1e3652d74fe"},{"editors":[{"login":"claj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/353113?v=4"}],"body":"(defn clj->php\n \"Serializes a subset of Clojure data types to the PHP serialization format.\n\n To avoid intermediary allocations of strings, a StringBuilder is sent around\n as an aggregate. The StringBuilder is realized to a string before returned.\"\n [clj-data]\n (letfn\n ;; primitive encoder for string\n [(encode-string*\n [^StringBuilder sb ^String clj-data]\n (let [string-length-in-bytes (count (.getBytes clj-data))]\n (-> sb\n (.append \"s:\")\n (.append string-length-in-bytes)\n (.append \":\\\"\")\n (.append clj-data)\n (.append \"\\\";\"))))\n ;; primitive encoders for numbers\n (encode-float*\n [^StringBuilder sb clj-data]\n (-> sb\n (.append \"d:\")\n (.append clj-data)\n (.append \";\")))\n\n (encode-int*\n [^StringBuilder sb ^Long clj-data]\n (-> sb\n (.append \"i:\")\n (.append clj-data)\n (.append \";\")))\n ;; encoders for collections\n ;; PHP associative collections.\n ;; Arrays/vectors uses only integer keys from 0 to n-1 (ordered).\n ;; Associative maps can have objects of any type as key.\n (encode-map*\n ;; used for both hash-maps and vectors\n [^StringBuilder sb clj-data]\n (let [sb (-> sb\n (.append \"a:\")\n (.append (count clj-data))\n (.append \":{\"))\n sb (reduce-kv (fn [^StringBuilder sb k v]\n (-> sb\n (clj->php* k)\n (clj->php* v)))\n sb\n clj-data)\n sb (.append ^StringBuilder sb \"}\")]\n sb))\n ;; given a seqable but not indexed collection, we serialize\n ;; it with a synthetic index key using map-indexed.\n (encode-collection*\n [^StringBuilder sb clj-data]\n (let [sb (-> sb\n (.append \"a:\")\n (.append (count clj-data))\n (.append \":{\"))\n sb (reduce (fn [sb [syntethic-k v]]\n (-> sb\n ;; in this case k is always an int!.\n (encode-int* syntethic-k)\n (clj->php* v)))\n sb\n (map-indexed (fn [a b] [a b]) clj-data))\n sb (.append ^StringBuilder sb \"}\")]\n sb))\n\n ;; the general dispatch function, used recursively in \n ;; the collection encoders:\n \n (clj->php* [^StringBuilder sb clj-data]\n (cond\n ;; sorted in some decently performant order\n (integer? clj-data) (encode-int* sb clj-data)\n (string? clj-data) (encode-string* sb clj-data)\n (map? clj-data) (encode-map* sb clj-data)\n (vector? clj-data) (encode-map* sb clj-data) \n (coll? clj-data) (encode-collection* sb clj-data)\n (nil? clj-data) (.append sb \"N;\")\n (true? clj-data) (.append sb \"b:1;\")\n (false? clj-data) (.append sb \"b:0;\")\n (float? clj-data) (encode-float* sb clj-data)\n :else (throw (ex-info \"cannot encode\" \n {:val clj-data\n :class (class clj-data)}))))]\n\n ;; str realizes the StringBuilder.\n (str (clj->php* (StringBuilder.) clj-data))))\n\n;;;; example:\n\n(clj->php {\"a-vector\" [42 \"hello\"]\n \"this is a FLOAT:\" 505.3\n \"inner-map\" {\"submap\" 1}\n \"boolean value\" false})\n;; =>\n;;ordered map with four kv pairs, unescaped and line breaked for some readability:\n\na:4:\n{s:8:\"a-vector\";\n a:2:{i:0;i:42;\n i:1;s:5:\"hello\";}\n\n s:16:\"this is a FLOAT:\";d:505.3;\n\n s:9:\"inner-map\";\n a:1:{s:6:\"submap\";i:1;}\n \n s:13:\\\"boolean value\";b:0;\n}","author":{"avatar-url":"https://avatars.githubusercontent.com/u/353113?v=4","account-source":"github","login":"claj"},"created-at":1763763477458,"updated-at":1763769476928,"_id":"6920e515848d032713abce3f"}],"macro":true,"notes":[{"updated-at":1315519060000,"body":"Using `letfn` allows you to create local functions that reference each other whereas `(let myfunc #(...)]...)` wouldn't because it executes its bindings serially.","created-at":1315519060000,"author":{"login":"Justinus","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1d9575e413b2eb108a35552b7cc0b54f?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fca"},{"body":"To be more precise (about the note above), letfn allows ahead-of-definition use of functions. The following is ok:\n
    \n(defn testme [] \n  (let [twice (fn [x] (* x 2))\n        six-times (fn [y] (* (twice y) 3))] \n  (println \"15x6=\" (six-times 15))))\n
    \n\nBut this one for instance doesn't compile (and would be ok with letfn):\n\n
    \n(defn testme [] \n  (let [twelve-times (fn [x] (* (six-times x) 2)) \n        six-times (fn [y] (* y 6))] \n  (println \"2x12=\" (twelve-times 2))))\n
    \n","created-at":1428350072457,"updated-at":1428350719864,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/20086?v=3"},"_id":"5522e478e4b033f34014b766"},{"body":"
    \n(letfn [(six-times [y]\n           (* (twice y) 3))\n        (twice [x]\n           (* x 2))]\n  (println \"Twice 15 =\" (twice 15))\n  (println \"Six times 15 =\" (six-times 15)))\n;; Twice 15 = 30\n;; Six times 15 = 90\n;;=> nil\n
    ","created-at":1434901354547,"updated-at":1434901354547,"author":{"login":"muhuk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/40178?v=3"},"_id":"5586db6ae4b0fad27b85f91b"},{"author":{"login":"mars0i","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/1836941?v=4"},"updated-at":1592847494238,"created-at":1592847494238,"body":"And just to clarify further what is already implicit in other remarks, `letfn` allows a definition to refer to itself recursively: \n```\n(letfn [(my-range [n]\n (when (pos? n)\n (cons n (my-range (dec n)))))]\n (my-range 5))\n;;=> (5 4 3 2 1)\n```\nbut `let` doesn't:\n```\n(let [my-range (fn [n]\n (when (pos? n)\n (cons n (my-range (dec n)))))]\n (my-range 5))\nSyntax error compiling at ...\nUnable to resolve symbol: my-range in this context\n```\n","_id":"5ef0ec86e4b0b1e3652d730c"},{"author":{"login":"miner","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/25400?v=4"},"updated-at":1751048868656,"created-at":1751047008047,"body":"This is a bit of tangent, but the `fn` form optionally takes a name, which allows recursive calls. You still need `leftn` for mutually recursive functions.\n\n```clojure\n(let [my-range (fn my-range [n]\n (when (pos? n)\n (cons n (my-range (dec n)))))]\n (my-range 5))\n;;=> (5 4 3 2 1)\n```","_id":"685edb60cd84df5de54e208a"}],"url":null,"arglists":["fnspecs & body"],"doc":"fnspec ==> (fname [params*] exprs) or (fname ([params*] exprs)+)\n\n Takes a vector of function specs and a body, and generates a set of\n bindings of functions to their names. All of the names are available\n in all of the definitions of the functions, as well as the body.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/letfn","forms":["(letfn [fnspecs*] exprs*)"]},{"added":"1.7","ns":"clojure.core","name":"volatile!","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1437144380666,"author":{"login":"claj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/353113?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"vswap!","ns":"clojure.core"},"_id":"55a9153ce4b0080a1b79cda2"},{"created-at":1437144392165,"author":{"login":"claj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/353113?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"vreset!","ns":"clojure.core"},"_id":"55a91548e4b0080a1b79cda3"},{"created-at":1437144401502,"author":{"login":"claj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/353113?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"volatile?","ns":"clojure.core"},"_id":"55a91551e4b06a85937088ad"},{"created-at":1437146220915,"author":{"login":"claj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/353113?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"atom","ns":"clojure.core"},"_id":"55a91c6ce4b06a85937088af"}],"line":2542,"examples":[{"updated-at":1437146196403,"created-at":1437146196403,"author":{"login":"claj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/353113?v=3"},"body":"(def val (volatile! 0))\n\n@val\n;;=> 0\n\n(vswap! val inc)\n;;=> 1\n\n(vreset! val \"nothing\")\n;;=> \"nothing\"\n\n@val\n;;=> \"nothing\"","_id":"55a91c54e4b06a85937088ae"}],"notes":[{"author":{"login":"claj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/353113?v=3"},"updated-at":1437144350368,"created-at":1437144350368,"body":"An exhaustive StackOverflow question about volatile!\n\nhttp://stackoverflow.com/questions/31288608/what-is-clojure-volatile#comment50623688_31288608","_id":"55a9151ee4b06a85937088ab"},{"author":{"login":"claj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/353113?v=3"},"updated-at":1437145076111,"created-at":1437144891888,"body":"Volatiles are meant to hold state in stateful transducers, since they are more performant (and less capable) than atoms.\n\nVolatiles are just a wrapped Java `volatile Object` reference. The Java `volatile`\nkeyword implies that reading and writing from this variable will not be reordered by JIT or the CPU. It does *not* imply atomicity.\n\nChanges to references made `volatile` are always \"written through\" CPU caches all the way to main memory (which is somewhat expensive), this means changes are guaranteed to propagate to other threads (nescessary in stateful transducers).","_id":"55a9173be4b0080a1b79cda4"}],"tag":"clojure.lang.Volatile","arglists":["val"],"doc":"Creates and returns a Volatile with an initial value of val.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/volatile!"},{"added":"1.0","ns":"clojure.core","name":"/","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1330259296000,"author":{"login":"frangio","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/646001f0ba2b7df47a16c0a1d5b62225?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"quot","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521dc8"},{"created-at":1423528033194,"author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"to-var":{"ns":"clojure.core","name":"unchecked-divide-int","library-url":"https://github.com/clojure/clojure"},"_id":"54d95061e4b0e2ac61831d45"},{"created-at":1691574231088,"author":{"login":"ferdinand-beyer","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/23474334?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"ratio?","ns":"clojure.core"},"_id":"64d35fd7e4b08cf8563f4bdd"}],"line":1022,"examples":[{"updated-at":1467677691841,"created-at":1279992021000,"body":"user=> (/ 6 3)\n2\n\nuser=> (/ 6 3 2)\n1\n\nuser=> (/ 10)\n1/10\n\nuser=> (/ 1 3)\n1/3\n\nuser=> (/)\nArityException Wrong number of args (0) passed to: core$-SLASH-\n\nuser=> (/ 1 0)\njava.lang.ArithmeticException\n\nuser=> (/ 0)\njava.lang.ArithmeticException\n","editors":[{"avatar-url":"https://www.gravatar.com/avatar/e7869fe1a48cb1814c657eaca6bea3eb?r=PG&default=identicon","account-source":"clojuredocs","login":"replore"},{"avatar-url":"https://www.gravatar.com/avatar/e7869fe1a48cb1814c657eaca6bea3eb?r=PG&default=identicon","account-source":"clojuredocs","login":"replore"},{"avatar-url":"https://www.gravatar.com/avatar/67e9a6f766dc4b30bd5e9ff3e77c1777?r=PG&default=identicon","account-source":"clojuredocs","login":"jmglov"},{"login":"bkovitz","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/4142015?v=3"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},"_id":"542692c9c026201cdc326ac5"},{"author":{"login":"rebcabin","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/880b0bb3a4be9237326dd69565444dee?r=PG&default=identicon"},"editors":[],"body":";;; Automatically handles floating point:\n\nuser=> (/ 43.0 2)\n21.5","created-at":1387152003000,"updated-at":1387152003000,"_id":"542692d1c026201cdc326f44"},{"editors":[{"login":"ferdinand-beyer","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/23474334?v=4"}],"body":"user=> (numerator (/ 2 6)) \n1\nuser=> (denominator (/ 2 6)) \n3","author":{"avatar-url":"https://avatars.githubusercontent.com/u/870478?v=4","account-source":"github","login":"idrozd"},"created-at":1639061278628,"updated-at":1691574194163,"_id":"61b2171ee4b0b1e3652d7586"}],"notes":null,"arglists":["x","x y","x y & more"],"doc":"If no denominators are supplied, returns 1/numerator,\n else returns numerator divided by all of the denominators.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/_fs"},{"added":"1.0","ns":"clojure.core","name":"read-line","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1425998580860,"author":{"login":"kimtg","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7685905?v=3"},"to-var":{"ns":"clojure.core","name":"flush","library-url":"https://github.com/clojure/clojure"},"_id":"54ff02f4e4b01ed96c93c888"}],"line":3822,"examples":[{"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":"user=> (read-line)\nline to be read ;Type text into console\n\"line to be read\"\n","created-at":1282634673000,"updated-at":1285494406000,"_id":"542692c6c026201cdc3268c5"},{"body":";; (flush) is needed to display print values.\n;; Otherwise the print value stays buffered until you hit enter.\nuser=> (do (print \"What's your name? \") \n (flush) \n (read-line))\nWhat's your name? Clojure\n\"Clojure\"","author":{"login":"kimtg","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7685905?v=3"},"created-at":1425998545713,"updated-at":1587658953937,"editors":[{"avatar-url":"https://avatars3.githubusercontent.com/u/24317401?v=4","account-source":"github","login":"loeschzwerg"},{"login":"dijonkitchen","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/11434205?v=4"}],"_id":"54ff02d1e4b01ed96c93c887"},{"updated-at":1475631664273,"created-at":1475631664273,"author":{"login":"aakoch","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/137713?v=3"},"body":"(println \"Enter something> \")\n(def x (read-line))\n(println (str \"You typed \\\"\" x \"\\\"\"))","_id":"57f45a30e4b0709b524f051f"},{"editors":[{"login":"stathissideris","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/162007?v=4"}],"body":";; Example of a tiny menu system. Usage:\n\n(menu {:prompt \"Which database\" \n :options [\"Localhost\" \"Remote\" {:id \"o\" :text \"Other\"}]})\n\n;; Implementation\n(require '[clojure.string :as str])\n\n(defn menu [{:keys [prompt options]}]\n (let [options (map (fn [o idx]\n (if (string? o)\n {:id (str (inc idx)) :text o}\n o)) options (range))\n valid-options (set (map :id options))]\n (loop []\n (when prompt\n (println)\n (println prompt)\n (println))\n (doseq [{:keys [id text]} options]\n (println (str \" [\" id \"]\") text))\n (println)\n (println \"or press to cancel\")\n\n (let [in (str/trim (read-line))]\n (cond (= in \"\")\n :cancelled\n\n (not (valid-options in))\n (do\n (println (format \"\\n-- Invalid option '%s'!\" in))\n (recur))\n\n :else\n (first (filter #(= in (:id %)) options)))))))","author":{"avatar-url":"https://avatars2.githubusercontent.com/u/162007?v=4","account-source":"github","login":"stathissideris"},"created-at":1598028614337,"updated-at":1598028647399,"_id":"5f3ffb46e4b0b1e3652d7382"}],"notes":[{"author":{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"},"updated-at":1506413349250,"created-at":1506413349250,"body":"Be aware that `read-line` uses Java’s `BufferedReader`’s `.readLine` method that itself uses an internal buffer of either 4k or 8k. That causes `(read-line)` to return a truncated string if you try to read a large line.","_id":"59ca0b25e4b03026fe14ea4a"}],"arglists":[""],"doc":"Reads the next line from stream that is the current value of *in* .","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/read-line"},{"added":"1.7","ns":"clojure.core","name":"reader-conditional?","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1495964626662,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"reader-conditional","ns":"clojure.core"},"_id":"592a9bd2e4b093ada4d4d77b"},{"created-at":1495964632155,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"read","ns":"clojure.core"},"_id":"592a9bd8e4b093ada4d4d77c"},{"created-at":1495964638029,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"read-string","ns":"clojure.core"},"_id":"592a9bdee4b093ada4d4d77d"}],"line":7970,"examples":[{"updated-at":1495963975752,"created-at":1495963975752,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"body":"(reader-conditional? (read-string {:read-cond :preserve} \"#?(:clj (Math/exp 1))\"))\n;;=> true\n(reader-conditional? (reader-conditional '(:clj (Math/exp 1)) false))\n;;=> true\n\n(reader-conditional? \"#?(:clj (Math/exp 1))\")\n;;=> false\n(reader-conditional? '#?(:clj (Math/exp 1)))\n;;=> false","_id":"592a9947e4b093ada4d4d779"},{"updated-at":1495964618275,"created-at":1495964618275,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"body":";;;; Let's say we have the source code for a Clojure program:\n\n(def source-code\n \"(defn str-to [type s]\n (case type\n :int #?(:clj (Integer/parseInt s) :cljs (js/parseInt s))\n #?@(:clj [:long (Long/parseLong s)])\n :float #?(:clj (Float/parseFloat s) :cljs (js/parseFloat s))\n #?@(:clj [:double (Double/parseDouble s)])))\")\n\n;;;; Here's a function that finds all the reader conditionals\n;;;; in a given source code which contain a specific platform tag:\n\n(defn find-reader-conditionals [code tag]\n (->> code\n (read-string {:read-cond :preserve}) ;; read into Clojure data structures\n (tree-seq seqable? identity) ;; lazy seq of all forms\n (filter reader-conditional?) ;; keep only reader conditionals\n (filter #(some #{tag} (:form %))))) ;; keep only reader conds with tag\n\n(pprint (find-reader-conditionals source-code :clj))\n;;=> (#?(:clj (Integer/parseInt s) :cljs (js/parseInt s))\n;; #?@(:clj [:long (Long/parseLong s)])\n;; #?(:clj (Float/parseFloat s) :cljs (js/parseFloat s))\n;; #?@(:clj [:double (Double/parseDouble s)]))\n\n(pprint (find-reader-conditionals source-code :cljs))\n;;=> (#?(:clj (Integer/parseInt s) :cljs (js/parseInt s))\n;; #?(:clj (Float/parseFloat s) :cljs (js/parseFloat s)))","_id":"592a9bcae4b093ada4d4d77a"}],"notes":null,"arglists":["value"],"doc":"Return true if the value is the data representation of a reader conditional","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/reader-conditional_q"},{"added":"1.0","ns":"clojure.core","name":"bit-or","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1414514313045,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"},"to-var":{"ns":"clojure.core","name":"bit-and","library-url":"https://github.com/clojure/clojure"},"_id":"544fc689e4b03d20a1024290"},{"created-at":1414514340059,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"},"to-var":{"ns":"clojure.core","name":"bit-xor","library-url":"https://github.com/clojure/clojure"},"_id":"544fc6a4e4b03d20a1024291"}],"line":1316,"examples":[{"author":{"login":"zmila","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/68dd6f50915854aa04fefcf4d6fa5c8e?r=PG&default=identicon"},"editors":[{"login":"zmila","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/68dd6f50915854aa04fefcf4d6fa5c8e?r=PG&default=identicon"},{"login":"adeel","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd14b215b86d93682addd69690ece881?r=PG&default=identicon"}],"body":"user=> (bit-or 2r1100 2r1001)\n13\n;; 13 = 2r1101\n\n;; the same in decimal\nuser=> (bit-or 12 9)\n13\n","created-at":1280337691000,"updated-at":1303117577000,"_id":"542692c6c026201cdc326929"},{"body":";; here is the truth table for OR\n(Integer/toBinaryString (bit-or 2r1100 2r1010) )\n;;=> \"1110\"\n;; or 2r1110","author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"},"created-at":1414514761650,"updated-at":1414514761650,"_id":"544fc849e4b0dc573b892fb2"}],"notes":null,"arglists":["x y","x y & more"],"doc":"Bitwise or","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/bit-or"},{"added":"1.0","ns":"clojure.core","name":"clear-agent-errors","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1282643269000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"restart-agent","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f32"}],"line":2263,"examples":null,"deprecated":"1.2","notes":null,"arglists":["a"],"doc":"DEPRECATED: Use 'restart-agent' instead.\n Clears any exceptions thrown during asynchronous actions of the\n agent, allowing subsequent actions to occur.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/clear-agent-errors"},{"added":"1.0","ns":"clojure.core","name":"vector","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1291953313000,"author":{"login":"alimoeeny","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e8dd06976ead4082d2181f3807117e1?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"vec","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d25"},{"created-at":1291953319000,"author":{"login":"alimoeeny","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e8dd06976ead4082d2181f3807117e1?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"vector?","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d26"},{"created-at":1291953324000,"author":{"login":"alimoeeny","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e8dd06976ead4082d2181f3807117e1?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"vector-of","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d27"},{"created-at":1291953354000,"author":{"login":"alimoeeny","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e8dd06976ead4082d2181f3807117e1?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"pop","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d28"},{"created-at":1343081413000,"author":{"login":"john.r.woodward","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/22b6fbc4a386291e45b1cb4449377086?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"into","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d29"}],"line":355,"examples":[{"updated-at":1340285477000,"created-at":1281948660000,"body":";; create an empty vector the long way\nuser=> (vector)\n[]\n\n;; create an empty vector the short way\nuser=> []\n[]\n\n;; you can even create vectors with nil values\nuser=> (vector nil)\n[nil]\n\n;; create a vector the long way\nuser=> (vector 1 2 3)\n[1 2 3]\n\n;; create a vector the short way\nuser=> [1 2 3]\n[1 2 3]\n\n;; checking for the 2 results above\nuser=> (class (vector 1 2 3))\nclojure.lang.PersistentVector\n\nuser=> (class [1 2 3])\nclojure.lang.PersistentVector\n\nuser=> (= (vector 1 2 3) [1 2 3])\ntrue\n\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"avatar-url":"https://www.gravatar.com/avatar/8d3c423e74750fa42c0386833e4b8209?r=PG&default=identicon","account-source":"clojuredocs","login":"belun"},{"avatar-url":"https://avatars.githubusercontent.com/u/92894?v=3","account-source":"github","login":"rafmagana"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon","account-source":"clojuredocs","login":"gstamp"},"_id":"542692c9c026201cdc326aa6"},{"author":{"login":"belun","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8d3c423e74750fa42c0386833e4b8209?r=PG&default=identicon"},"editors":[{"login":"belun","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8d3c423e74750fa42c0386833e4b8209?r=PG&default=identicon"},{"login":"belun","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8d3c423e74750fa42c0386833e4b8209?r=PG&default=identicon"},{"login":"belun","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8d3c423e74750fa42c0386833e4b8209?r=PG&default=identicon"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"belun","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8d3c423e74750fa42c0386833e4b8209?r=PG&default=identicon"},{"login":"belun","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8d3c423e74750fa42c0386833e4b8209?r=PG&default=identicon"},{"login":"belun","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8d3c423e74750fa42c0386833e4b8209?r=PG&default=identicon"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":";; Destructuring with a vector, inside a \"let\" form, a simple case (a symbol\n;; for each element):\n\n;; destructuring with an inline vector\nuser=> (let [[first-element second-element third-element fourth-element] \n [10 20 30 40]] \n (str \"first=\" first-element \" second=\" second-element \n \" third=\" third-element \" fourth=\" fourth-element))\n\"first=10 second=20 third=30 fourth=40\"\n;; notice how 4 symbols were created pointing to the scalars 10, 20, 30 and 40\n\n\n;; destructuring with a symbol to a vector\nuser=> (def my-vector [1 2 3 4])\n#'user/my-vector\n\nuser=> (let [[first-element second-element third-element fourth-element] my-vector] \n (str \"first=\" first-element \" second=\" second-element \n \" third=\" third-element \" fourth=\" fourth-element))\n\"first=1 second=2 third=3 fourth=4\"","created-at":1285529828000,"updated-at":1285725388000,"_id":"542692c9c026201cdc326aaa"},{"author":{"login":"belun","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8d3c423e74750fa42c0386833e4b8209?r=PG&default=identicon"},"editors":[{"login":"belun","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8d3c423e74750fa42c0386833e4b8209?r=PG&default=identicon"},{"login":"belun","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8d3c423e74750fa42c0386833e4b8209?r=PG&default=identicon"},{"login":"belun","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8d3c423e74750fa42c0386833e4b8209?r=PG&default=identicon"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"belun","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8d3c423e74750fa42c0386833e4b8209?r=PG&default=identicon"},{"login":"belun","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8d3c423e74750fa42c0386833e4b8209?r=PG&default=identicon"},{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":";; Destructuring with a vector, inside a \"let\" form, more complex cases:\n\nuser=> (let [[first-element second-element & the-rest] my-vector] \n (str \"first=\" first-element \" second=\" second-element \" \n the-rest=\" the-rest))\n\"first=1 second=2 the-rest=(3 4)\"\n;; notice how \"the-rest\" is a sequence\n\nuser=> (let [[first-element second-element third-element fourth-element \n :as everything] \n my-vector] \n (str \"first=\" first-element \" second=\" second-element \" \n third=\" third-element \" fourth=\" fourth-element \" \n everything=\" everything))\n\"first=1 second=2 third=3 fourth=4 everything=[1 2 3 4]\"\n;; notice how \"everything\" is the whole vector","created-at":1285529834000,"updated-at":1331682689000,"_id":"542692c9c026201cdc326ab3"},{"editors":[{"login":"alvarogarcia7","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/4199136?v=3"}],"body":";; Create pairs from a seq\n;; (1 2 3 4) -> ([1 2] [2 3] [3 4])\n\n\n(def inp (list 1 2 3 4))\n;; (1 2 3 4)\n(map vector inp (drop 1 inp))\n;; ([1 2] [2 3] [3 4])","author":{"avatar-url":"https://avatars.githubusercontent.com/u/4199136?v=3","account-source":"github","login":"alvarogarcia7"},"created-at":1456569943409,"updated-at":1456570207244,"_id":"56d17e57e4b02a6769b5a4b2"},{"updated-at":1546245875727,"created-at":1546245875727,"author":{"login":"abhishekamralkar","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/868407?v=4"},"body":";; Vectors in Clojure are heterogeneous\nuser=> (def my-vector [1 \"a\" :b])\n\nuser=> my-vector\n[1 \"a\" :b]\n","_id":"5c29d6f3e4b0ca44402ef609"},{"updated-at":1587681648212,"created-at":1587681648212,"author":{"login":"dijonkitchen","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/11434205?v=4"},"body":"user=> (vector {:a 1 :b 2 :c 3})\n;; [{:a 1, :b 2, :c 3}]\n\nuser=> (vec {:a 1 :b 2 :c 3})\n;; [[:a 1] [:b 2] [:c 3]]","_id":"5ea21970e4b087629b5a18e2"}],"notes":null,"arglists":["","a","a b","a b c","a b c d","a b c d e","a b c d e f","a b c d e f & args"],"doc":"Creates a new vector containing the args.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/vector"},{"added":"1.0","ns":"clojure.core","name":"proxy-super","file":"clojure/core_proxy.clj","type":"macro","column":1,"see-alsos":[{"created-at":1354011410000,"author":{"login":"juan.facorro","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d6f59d93cc17c698f16e550034a2d1ad?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"proxy","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d30"}],"line":396,"examples":[{"author":{"login":"juan.facorro","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d6f59d93cc17c698f16e550034a2d1ad?r=PG&default=identicon"},"editors":[{"login":"juan.facorro","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d6f59d93cc17c698f16e550034a2d1ad?r=PG&default=identicon"},{"login":"juan.facorro","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d6f59d93cc17c698f16e550034a2d1ad?r=PG&default=identicon"},{"login":"juan.facorro","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d6f59d93cc17c698f16e550034a2d1ad?r=PG&default=identicon"}],"body":";; Create a proxy for java.util.ArrayList that overrides the add() \n;; method and calls the super class implementation using proxy-super.\n(def lst (proxy [java.util.ArrayList] []\n (add [x]\n (println \"Adding some stuff:\" x)\n (proxy-super add x))))\n\nuser=> (.add lst 1)\nAdding some stuff: 1\ntrue\n\nuser=> (.add lst 2)\nAdding some stuff: 2\ntrue\n\nuser=> (.add lst [:this :is :some :other :stuff])\nAdding some stuff: [:this :is :some :other :stuff]\ntrue\n\nuser=> (.size lst)\n3\n\n\n ","created-at":1354011876000,"updated-at":1354012030000,"_id":"542692d4c026201cdc327042"},{"updated-at":1601464064060,"created-at":1601464064060,"author":{"login":"BrunoBonacci","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/1639862?v=4"},"body":";; WARNING ON REFLECTION:\n;; because `proxy-super` expansion captures 'this without type hint,\n;; it generates a reflection warning\nuser=> (set! *warn-on-reflection* true)\ntrue\n\n(def lst (proxy [java.util.ArrayList] []\n (add [x]\n (println \"Adding some stuff:\" x)\n (proxy-super add x))))\nReflection warning, NO_SOURCE_PATH:4:14 - call to method add can't be resolved (target class is unknown).\n#'user/lst\n\nuser=> (.add lst 1)\nReflection warning, NO_SOURCE_PATH:1:1 - call to method add can't be resolved (target class is unknown).\nAdding some stuff: 1\ntrue\n\n;; In order to avoid the reflection add the type hint to 'this\n;; in the following way. Note no reflection warnings.\n;; add type to the proxy, add let binding on 'this with type\n(def ^java.util.ArrayList lst (proxy [java.util.ArrayList] []\n (add [x]\n (println \"Adding some stuff:\" x)\n (let [^java.util.ArrayList this this] ;; add explicit type to 'this\n (proxy-super add x)))))\n#'user/lst\n\nuser> (.add lst 1)\nAdding some stuff: 1\ntrue","_id":"5f746700e4b0b1e3652d73c5"}],"macro":true,"notes":[{"updated-at":1401348603000,"body":"Note that proxy-super calls are not reentrant. If calling the base method results in another call to the virtual method you are overriding (before the proxy-super call has returned), your proxy's code will not be invoked. Instead, the call will go directly to the base class's method.\r\n","created-at":1401348603000,"author":{"login":"glchapman","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a5176d5d971ba68c15f4afe376aeaf18?r=PG&default=identicon"},"_id":"542692edf6e94c6970522027"}],"arglists":["meth & args"],"doc":"Use to call a superclass method in the body of a proxy method. \n Note, expansion captures 'this","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/proxy-super"},{"added":"1.0","ns":"clojure.core","name":">=","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1451249634940,"author":{"login":"justCxx","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/6506296?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"<=","ns":"clojure.core"},"_id":"56804fe2e4b0e0706e05bd8f"},{"created-at":1588958557112,"author":{"login":"alexandreaquiles","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/258331?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":">","ns":"clojure.core"},"_id":"5eb5955de4b087629b5a1905"},{"created-at":1588958562611,"author":{"login":"alexandreaquiles","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/258331?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"=","ns":"clojure.core"},"_id":"5eb59562e4b087629b5a1906"}],"line":1087,"examples":[{"author":{"login":"mattdw","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/ee24aacb65359196b0a1bad050f9a62f?r=PG&default=identicon"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":"user=> (>= 2 1)\ntrue\nuser=> (>= 2 2)\ntrue\nuser=> (>= 1 2)\nfalse\nuser=> (>= 6 5 4 3 2)\ntrue","created-at":1280321990000,"updated-at":1332950567000,"_id":"542692ccc026201cdc326cae"},{"updated-at":1598156842291,"created-at":1598156542824,"author":{"login":"berczeck","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/1321842?v=4"},"body":"user=> (>= 1/2 1/3 1/4)\ntrue\n\nuser=> (<= 1/4 1/3 1/4)\nfalse\n\nuser=> (>= 1/2 0.5)\ntrue","editors":[{"avatar-url":"https://avatars1.githubusercontent.com/u/1321842?v=4","account-source":"github","login":"berczeck"}],"_id":"5f41eefee4b0b1e3652d7390"}],"notes":null,"arglists":["x","x y","x y & more"],"doc":"Returns non-nil if nums are in monotonically non-increasing order,\n otherwise false.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/>="},{"added":"1.0","ns":"clojure.core","name":"drop-last","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1298747615000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"drop","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f41"},{"created-at":1298747622000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"drop-while","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f42"},{"created-at":1524421874890,"author":{"login":"huahaiy","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/889685?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"butlast","ns":"clojure.core"},"_id":"5adcd4f2e4b045c27b7fac4a"},{"created-at":1615942867695,"author":{"login":"Crowbrammer","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/19522656?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"pop","ns":"clojure.core"},"_id":"605154d3e4b0b1e3652d74a0"}],"line":2957,"examples":[{"updated-at":1508194130933,"created-at":1280344984000,"body":"\n(drop-last [1 2 3 4])\n;=> (1 2 3) \n\n(drop-last -1 [1 2 3 4])\n;=> (1 2 3 4) \n\n(drop-last 0 [1 2 3 4])\n;=> (1 2 3 4) \n\n(drop-last 5 [1 2 3 4])\n;=> ()\n\n;; works differently with any seq.\n;; but with some the last items become ambiguous.\n(drop-last 2 (vector 1 2 3 4))\n;=> (1 2)\n(drop-last 2 (list 1 2 3 4 ))\n;=> (1 2)\n(drop-last 2 {:a 1 :b 2 :c 3 :d 4})\n;=> ([:a 1] [:b 2])","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3","account-source":"github","login":"jafingerhut"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/68dd6f50915854aa04fefcf4d6fa5c8e?r=PG&default=identicon","account-source":"clojuredocs","login":"zmila"},"_id":"542692cbc026201cdc326bc8"},{"updated-at":1615942982457,"created-at":1615234915525,"author":{"login":"Crowbrammer","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/19522656?v=4"},"body":";; Using `drop-last` vs. using `butlast`\n\n(def v [1 2 3 4])\n\n(butlast v) ;;=> (1 2 3)\n(drop-last v) ;;=> (1 2 3)\n(drop-last 2 v) ;;=> (1 2) butlast can't do this\n(butlast 2 v) ;;=> ArityException\n(drop-last 0 v) ;;=> (1 2 3 4) \n(drop-last -1 v) ;;=> (1 2 3 4)\n\n;; Performance differences:\n;; - `butlast`, linear time\n;; - `drop-last`, lazy, efficient, more flexible, constant time(?) \n;; - `pop`, constant but requires a vector\n\n(def r (range 10000))\n\n(time (butlast r)) ;;=> \"Elapsed time: 6.379 msecs\"\n(time (drop-last r)) ;;=> \"Elapsed time: 0.0475 msecs\"\n(time (drop-last 2 r)) ;;=> \"Elapsed time: 0.0569 msecs\"\n(time (drop-last 0 r)) ;;=> \"Elapsed time: 0.098 msecs\"\n(time (drop-last -1 r)) ;;=> \"Elapsed time: 0.0615 msecs\"\n\n(def r-vec (vec r)) ;; to work like `butlast` pop needs a vector \n(time (pop r-vec)) ;;=> \"Elapsed time: 0.062 msecs\"","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/19522656?v=4","account-source":"github","login":"Crowbrammer"}],"_id":"60468763e4b0b1e3652d7474"}],"notes":[{"author":{"login":"huahaiy","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/889685?v=4"},"updated-at":1524422027867,"created-at":1524422027867,"body":"`drop-last` is lazy and implemented with `map`, whereas `butlast` is not lazy and implemented with `loop` and `recur`. ","_id":"5adcd58be4b045c27b7fac4b"}],"arglists":["coll","n coll"],"doc":"Return a lazy sequence of all but the last n (default 1) items in coll","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/drop-last"},{"added":"1.0","ns":"clojure.core","name":"not-empty","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1311798738000,"author":{"login":"OnesimusUnbound","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2fa4c391db0d2d1744cc2cd0d787dd3d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"empty","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d87"},{"created-at":1441028012851,"author":{"login":"BernhardBln","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/4759839?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"empty?","ns":"clojure.core"},"_id":"55e457ace4b072d7f27980f4"},{"created-at":1479824393862,"author":{"login":"jswalens","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/12746328?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"seq","ns":"clojure.core"},"_id":"58345409e4b0782b632278c5"}],"line":5590,"examples":[{"updated-at":1484346990250,"created-at":1311798802000,"body":"user=> (not-empty [1])\n[1]\nuser=> (not-empty [1 3 5])\n[1 3 5]\nuser=> (not-empty [])\nnil\nuser=> (not-empty '())\nnil\nuser=> (not-empty {})\nnil\nuser=> (not-empty nil)\nnil","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3","account-source":"github","login":"Dimagog"},{"login":"tkocmathla","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/183459?v=3"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/2fa4c391db0d2d1744cc2cd0d787dd3d?r=PG&default=identicon","account-source":"clojuredocs","login":"OnesimusUnbound"},"_id":"542692cfc026201cdc326e48"},{"updated-at":1480975247792,"created-at":1480975247792,"author":{"login":"joshdegagne","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/3721599?v=3"},"body":";; Same behaviour for strings\n\nuser> (not-empty \"hello\")\n\"hello\"\n\nuser> (not-empty \"\")\nnil","_id":"5845e38fe4b0782b632278d6"},{"editors":[{"login":"kopos","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/655969?v=4"}],"body":";; if-let can now work with colls also, not being limited to scalar values alone\nuser> (if-let [valid (not-empty (filter even? [2 4 6]))] valid)\n(2 4 6)\n\n;; if-let helps avoid another nested if check\nuser> (if-let [valid (not-empty (filter even? [1 3 5]))] valid)\nnil\n\n;; without not-empty we would have to work with another if conditional\nuser> (if-let [valid (filter even? [1 3 5])] valid)\n()","author":{"avatar-url":"https://avatars0.githubusercontent.com/u/655969?v=4","account-source":"github","login":"kopos"},"created-at":1586364994600,"updated-at":1586365117971,"_id":"5e8e0242e4b087629b5a18d0"},{"updated-at":1731920302814,"created-at":1731920302814,"author":{"login":"iGEL","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/36442?v=4"},"body":";; The difference to seq is, that it doesn't change the \n;; type of collection if it's not empty:\n\n(seq #{1 2 3}) ;; -> (1 3 2)\n(seq [1 2 3]) ;; -> (1 2 3)\n\n(not-empty #{1 2 3}) ;; -> #{1 3 2}\n(not-empty [1 2 3]) ;; -> [1 2 3]","_id":"673b01ae69fbcc0c22617516"}],"notes":null,"arglists":["coll"],"doc":"If coll is empty, returns nil, else coll","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/not-empty"},{"added":"1.0","ns":"clojure.core","name":"distinct","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1396938593000,"author":{"login":"ryo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3f7913b563c72083c74030d928ba407e?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"distinct?","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c04"},{"created-at":1440188357188,"author":{"login":"blx","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/887504?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"dedupe","ns":"clojure.core"},"_id":"55d787c5e4b0831e02cddf19"},{"created-at":1440188421908,"author":{"login":"blx","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/887504?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"set","ns":"clojure.core"},"_id":"55d78805e4b072d7f27980eb"}],"line":5082,"examples":[{"author":{"login":"zmila","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/68dd6f50915854aa04fefcf4d6fa5c8e?r=PG&default=identicon"},"editors":[{"login":"zmila","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/68dd6f50915854aa04fefcf4d6fa5c8e?r=PG&default=identicon"},{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":"user=> (distinct [1 2 1 3 1 4 1 5])\n(1 2 3 4 5)","created-at":1280343931000,"updated-at":1332949923000,"_id":"542692c7c026201cdc3269aa"},{"author":{"login":"zmila","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/68dd6f50915854aa04fefcf4d6fa5c8e?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":"user=> (def fractions \n (for [n (range 1 100) d (range (inc n) 100)] \n (let [gcd (clojure.contrib.math/gcd n d)] \n (/ (/ n gcd) (/ d gcd)))))\n;; all irreducible fractions with denominator < 100\n;; (1/2 1/3 ... 1/99 2/3 1/2 2/5 1/3 ...)\n\nuser=> (count fractions)\n4851\n\nuser=> (count (distinct fractions))\n3003\n","created-at":1280343971000,"updated-at":1285496532000,"_id":"542692c7c026201cdc3269ad"},{"updated-at":1607179413496,"created-at":1607179413496,"author":{"login":"siddharthjain-in","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/6537820?v=4"},"body":"user=> (distinct [1/2 2/4])\n(1/2)\n\nuser=> (distinct [1/2 0.5])\n(1/2 0.5)","_id":"5fcb9c95e4b0b1e3652d7415"},{"updated-at":1654971641960,"created-at":1654971641960,"author":{"login":"clojer","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/107184681?v=4"},"body":"user=> (apply str (distinct \"tattoo\"))\n\"tao\"","_id":"62a4dcf9e4b0b1e3652d75fc"}],"notes":[{"updated-at":1285266859000,"body":"If you do not need the lazyness of distinct, set can be faster. Like: (count (set some-coll)).","created-at":1285266859000,"author":{"login":"morphling","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/90ffa70a579c3e0c398b7523ecdc6a87?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521f96"},{"updated-at":1389130101000,"body":"Use this function if you want to remove only consequtive duplicates\r\n\r\n (defn distinct-consequtive [sequence] (map first (partition-by identity sequence)))\r\n\r\n (distinct-consequtive [1 1 2 3 3 2 2 3])\r\n ;=> (1 2 3 2 3)","created-at":1389130101000,"author":{"login":"vshatsky","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/20b6441a990cf524f4ce73f67f3a56d8?r=PG&default=identicon"},"_id":"542692edf6e94c6970522018"},{"author":{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1334295?v=3"},"updated-at":1463670462203,"created-at":1463670462203,"body":"Use [`dedupe`](https://clojuredocs.org/clojure.core/dedupe) if you want to remove consecutive duplicates, available since Clojure 1.7.","_id":"573dd6bee4b05c05173143fd"}],"arglists":["","coll"],"doc":"Returns a lazy sequence of the elements of coll with duplicates removed.\n Returns a stateful transducer when no collection is provided.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/distinct"},{"added":"1.0","ns":"clojure.core","name":"partition","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1297761042000,"author":{"login":"TimMc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5d532e51427ef2f4ded31aaca16c8baf?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"partition-all","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521da0"},{"created-at":1314290633000,"author":{"login":"Havvy","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e799a79441c7543be48562403411cd13?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"split-at","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521da1"},{"created-at":1324097144000,"author":{"login":"rjack","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/7a561494c10e6fd3367f7a0bbc18da27?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"partition-by","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521da2"},{"created-at":1526479435653,"author":{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"cycle","ns":"clojure.core"},"_id":"5afc3a4be4b045c27b7fac68"}],"line":3202,"examples":[{"updated-at":1421743255734,"created-at":1279644356000,"body":";; partition a list of 20 items into 5 (20/4) lists of 4 items\n(partition 4 (range 20))\n;;=> ((0 1 2 3) (4 5 6 7) (8 9 10 11) (12 13 14 15) (16 17 18 19))\n\n;; partition a list of 22 items into 5 (20/4) lists of 4 items \n;; the last two items do not make a complete partition and are dropped.\n(partition 4 (range 22))\n;;=> ((0 1 2 3) (4 5 6 7) (8 9 10 11) (12 13 14 15) (16 17 18 19))\n\n;; uses the step to select the starting point for each partition\n(partition 4 6 (range 20))\n;;=> ((0 1 2 3) (6 7 8 9) (12 13 14 15))\n\n;; if the step is smaller than the partition size, items will be reused\n(partition 4 3 (range 20))\n;;=> ((0 1 2 3) (3 4 5 6) (6 7 8 9) (9 10 11 12) (12 13 14 15) (15 16 17 18))\n\n;; when there are not enough items to fill the last partition, a pad can be supplied.\n(partition 3 6 [\"a\"] (range 20))\n;;=> ((0 1 2) (6 7 8) (12 13 14) (18 19 \"a\"))\n\n;; when a pad is supplied, the last partition may not be of the same size as the rest\n(partition 4 6 [\"a\"] (range 20))\n;;=> ((0 1 2 3) (6 7 8 9) (12 13 14 15) (18 19 \"a\"))\n\n;; but only as many pad elements are used as necessary to fill the final partition.\n(partition 4 6 [\"a\" \"b\" \"c\" \"d\"] (range 20))\n;;=> ((0 1 2 3) (6 7 8 9) (12 13 14 15) (18 19 \"a\" \"b\"))\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3","account-source":"github","login":"phreed"},{"avatar-url":"https://avatars.githubusercontent.com/u/59250?v=3","account-source":"github","login":"jayp"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/142529?v=3","account-source":"github","login":"nipra"},"_id":"542692cdc026201cdc326d23"},{"author":{"login":"uvtc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/34f159f89cbd1d9beac0276f5a7af552?r=PG&default=identicon"},"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":";; a step smaller than the partition-size results in reuse.\n(partition 3 1 [:a :b :c :d :e :f])\n;;=> ((:a :b :c) (:b :c :d) (:c :d :e) (:d :e :f))\n","created-at":1340078697000,"updated-at":1420738171371,"_id":"542692d4c026201cdc327027"},{"author":{"login":"Parijat Mishra","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e3aba44539a78ea92373418456f090e3?r=PG&default=identicon"},"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":";; When there are less than n items in the coll, partition's behaviour\n;; depends on whether there is a pad or not\n\n;; without pad\n(partition 10 [1 2 3 4])\n;;=> ()\n\n;; again, without pad\n(partition 10 10 [1 2 3 4])\n;;=> ()\n\n;; with a pad this time (note: the pad is an empty sequence)\n(partition 10 10 nil [1 2 3 4])\n;;=> ((1 2 3 4))\n\n;; or, explicit empty sequence instead of nil\n(partition 10 10 [] [1 2 3 4])\n;;=> ((1 2 3 4))\n","created-at":1340625444000,"updated-at":1420738216041,"_id":"542692d4c026201cdc327028"},{"updated-at":1470789114426,"created-at":1470789114426,"author":{"login":"porglezomp","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1690225?v=3"},"body":";; Partitioning 0 elements will produce an infinite seq of empty sequences\n(partition 0 [1 2 3])\n;; *hangs*\n\n(take 5 (partition 0 [1 2 3]))\n;; => (() () () () ())","_id":"57aa75fae4b0bafd3e2a04d3"},{"editors":[{"login":"luciancrasovan","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/6660425?v=4"},{"avatar-url":"https://avatars.githubusercontent.com/u/6537820?v=4","account-source":"github","login":"siddharthjain-in"}],"body":";; Using nil as a pad will let the incomplete partition in the result\n;; Here we use it to drop every fourth element in an array\n(partition 3 4 nil [1 2 3 4 5 6 7 8 9])\n;;((1 2 3) (5 6 7) (9))","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/6660425?v=4","account-source":"github","login":"luciancrasovan"},"created-at":1520841935104,"updated-at":1708656172840,"_id":"5aa634cfe4b0316c0f44f91f"},{"updated-at":1526479384489,"created-at":1525990704985,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"},"body":";; Here is a nice little trick to make a ring.\n(def foo [5 6 7 8])\n\n(partition 2 1 foo foo)\n;;=> ((5 6) (6 7) (7 8) (8 5))\n\n;; This will produce a part for each element of foo.\n;; Without the pad stops sooner.\n(partition 2 1 foo)\n;;=> ((5 6) (6 7) (7 8))\n\n;; Just how crazy can this get?\n(partition 4 1 foo foo)\n;;=> ((5 6 7 8) (6 7 8 5))\n;; Not too crazy, this illustrates the \n;; fact that the first use of the pad halts the partitioning.\n;; To my way of thinking this is not what I expected.\n\n;; The following alternative implementation continues \n;; until the coll has been consumed once completely.\n(defn spiral\n ([n step coll]\n (spiral n step coll coll))\n ([n step pad coll]\n (lazy-seq\n (when-let [s (seq coll)]\n (let [p (doall (take n s))\n item (take n (apply concat p (repeat pad)))]\n (if (< 1 (count p))\n (cons item (spiral n step pad (nthrest s step)))\n (list item)))))))\n(spiral 4 1 foo)\n;;=> ((5 6 7 8) (6 7 8 5) (7 8 5 6) (8 5 6 7))\n\n(spiral 4 2 foo)\n;;=> ((5 6 7 8) (7 8 5 6))\n\n(spiral 6 1 foo)\n;;=> ((5 6 7 8 5 6) (6 7 8 5 6 7) (7 8 5 6 7 8) (8 5 6 7 8 5))\n\n(def bar [:a :b :c])\n(spiral 6 2 bar foo)\n;;=> ((5 6 7 8 :a :b) (7 8 :a :b :c :a))\n\n;; Note that if you don’t need the padding, the function above can be\n;; simplified a lot by using cycle:\n(defn spiral\n [n offset coll]\n (take (/ (count coll) offset) (partition n offset (cycle coll))))","editors":[{"avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4","account-source":"github","login":"phreed"},{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"}],"_id":"5af4c530e4b045c27b7fac60"},{"updated-at":1545833930836,"created-at":1533240763986,"author":{"login":"anpr","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/1492772?v=4"},"body":";; In case you want behaviour similar to Ruby's each_slice, \n;; where the last sequence doesn't necessarily have the same \n;; size as the others, you can just provide an empty or nil pad value.\n(partition 3 3 nil (range 11))\n;;=> ((0 1 2) (3 4 5) (6 7 8) (9 10)))\n\n;; This is the default behavior of partition-all\n(partition-all 3 3 (range 11))\n;;=> ((0 1 2) (3 4 5) (6 7 8) (9 10))) \n","editors":[{"avatar-url":"https://avatars1.githubusercontent.com/u/1492772?v=4","account-source":"github","login":"anpr"},{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"}],"_id":"5b6365bbe4b00ac801ed9e44"},{"updated-at":1566230801010,"created-at":1566230801010,"author":{"login":"malloryerik","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10395849?v=4"},"body":"user=> (partition 5 \"superfragilistic\")\n((\\s \\u \\p \\e \\r) (\\f \\r \\a \\g \\i) (\\l \\i \\s \\t \\i))","_id":"5d5ac911e4b0ca44402ef7a7"},{"editors":[{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"}],"body":";; There's no transducer arity for partition, but there is for partition-all\n;; To enforce full partitions only, we can provide our own reducing function…\n(let [rf (completing (fn [acc x] (cond-> acc (= 3 (count x)) (conj x))))]\n (transduce (partition-all 3) rf [] '[a b c d e f g]))\n;; => [[a b c] [d e f]]\n\n;; Or we can add a take-while transducer…\n(into [] (comp (partition-all 3) (take-while #(= 3 (count %)))) '[a b c d e f g])\n;; => [[a b c] [d e f]]","author":{"avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4","account-source":"github","login":"tomdl89"},"created-at":1678019636162,"updated-at":1678019921400,"_id":"64048c34e4b08cf8563f4b76"}],"notes":null,"arglists":["n coll","n step coll","n step pad coll"],"doc":"Returns a lazy sequence of lists of n items each, at offsets step\n apart. If step is not supplied, defaults to n, i.e. the partitions\n do not overlap. If a pad collection is supplied, use its elements as\n necessary to complete last partition upto n items. In case there are\n not enough padding elements, return a partition with less than n items.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/partition"},{"added":"1.0","ns":"clojure.core","name":"loop","special-form":true,"file":"clojure/core.clj","type":"macro","column":1,"see-alsos":[{"created-at":1289617722000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"recur","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d7a"},{"created-at":1289618043000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"trampoline","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d7b"},{"created-at":1342652485000,"author":{"login":"john.r.woodward","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/22b6fbc4a386291e45b1cb4449377086?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"when","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d7c"},{"created-at":1360216647000,"author":{"login":"Phalphalak","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a684c0fd4f27597437de953e92a15d4b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"while","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d7d"},{"created-at":1551989726895,"author":{"login":"mars0i","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/1836941?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"for","ns":"clojure.core"},"_id":"5c817bdee4b0ca44402ef6ae"},{"created-at":1551989770924,"author":{"login":"mars0i","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/1836941?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"doseq","ns":"clojure.core"},"_id":"5c817c0ae4b0ca44402ef6af"},{"created-at":1551989783076,"author":{"login":"mars0i","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/1836941?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"reduce","ns":"clojure.core"},"_id":"5c817c17e4b0ca44402ef6b0"},{"created-at":1551989793853,"author":{"login":"mars0i","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/1836941?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"dotimes","ns":"clojure.core"},"_id":"5c817c21e4b0ca44402ef6b1"}],"line":4624,"examples":[{"updated-at":1703905263509,"created-at":1279054191000,"body":";; looping is recursive in Clojure, the loop construct is a hack so that\n;; something like tail-recursive-optimization works in Clojure.\n\nuser=> (defn my-re-seq \n \"Something like re-seq\"\n [re string]\n (let [matcher (re-matcher re string)]\n\n (loop [match (re-find matcher) ;loop starts with 2 set arguments\n result []]\n (if-not match\n result\n (recur (re-find matcher) ;loop with 2 new arguments\n (conj result match))))))\n\n#'user/my-re-seq\n\nuser=> (my-re-seq #\"\\d\" \"0123456789\")\n[\"0\" \"1\" \"2\" \"3\" \"4\" \"5\" \"6\" \"7\" \"8\" \"9\"]\n\n","editors":[{"login":"nipra","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/142529?v=3"},{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon","account-source":"clojuredocs","login":"boxie"},{"login":"avidrucker","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/6962664?v=4"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/142529?v=3","account-source":"github","login":"nipra"},"_id":"542692c8c026201cdc3269f4"},{"author":{"login":"devijvers","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/81018e4231ac1ce8b7a9e6d377092656?r=PG&default=identicon"},"editors":[{"login":"devijvers","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/81018e4231ac1ce8b7a9e6d377092656?r=PG&default=identicon"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":";; Read decoded MP3 data in loop (requires mp3plugin.jar on class path)\n;; http://java.sun.com/javase/technologies/desktop/media/jmf/mp3/download.html \n\n(import '(javax.sound.sampled AudioSystem AudioFormat$Encoding))\n\n(let [mp3-file (java.io.File. \"tryout.mp3\")\n audio-in (AudioSystem/getAudioInputStream mp3-file)\n audio-decoded-in (AudioSystem/getAudioInputStream AudioFormat$Encoding/PCM_SIGNED audio-in)\n buffer (make-array Byte/TYPE 1024)]\n (loop []\n (let [size (.read audio-decoded-in buffer)]\n (when (> size 0)\n ;do something with PCM data\n\t(recur)))))\n","created-at":1279556129000,"updated-at":1285499929000,"_id":"542692c8c026201cdc3269f8"},{"updated-at":1436709203928,"created-at":1342652380000,"body":"(loop [x 10]\n (when (> x 1)\n (println x)\n (recur (- x 2))))\n\n;;=> 10 8 6 4 2","editors":[{"login":"Miloas","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/11530682?v=3"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/22b6fbc4a386291e45b1cb4449377086?r=PG&default=identicon","account-source":"clojuredocs","login":"john.r.woodward"},"_id":"542692d4c026201cdc326ff6"},{"author":{"login":"dansalmo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e33ee460f5f61bc5ba9b598934766215?r=PG&default=identicon"},"editors":[],"body":"(defn find-needle [needle haystack]\n ;loop binds initial values once,\n ;then binds values from each recursion call\n (loop [needle needle\n maybe-here haystack\n not-here '()]\n\n (let [needle? (first maybe-here)]\n\n ;test for return or recur\n (if (or (= (str needle?) (str needle))\n (empty? maybe-here))\n\n ;return results\n [needle? maybe-here not-here]\n\n ;recur calls loop with new values\n (recur needle\n (rest maybe-here)\n (concat not-here (list (first maybe-here))))))))\n\nuser=>(find-needle \"|\" \"hay|stack\")\n[\\| (\\| \\s \\t \\a \\c \\k) (\\h \\a \\y)]","created-at":1345453816000,"updated-at":1345453816000,"_id":"542692d4c026201cdc326ff7"},{"author":{"login":"bartq","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/b434a6540e72bcb335a026eb370da200?r=PG&default=identicon"},"editors":[],"body":"; makes a simple template function that can be used in mustache way: http://mustache.github.com/\n(defn template [tpl env]\n (loop [tpl tpl\n env env]\n (cond (empty? env)\n tpl\n :else\n (let [[key value] (first env)]\n (recur (try (clojure.string/replace tpl \n (re-pattern (str \"\\\\{\\\\{\" (name key) \"\\\\}\\\\}\")) \n value)\n (catch Exception e tpl)) \n (rest env))))))","created-at":1363378523000,"updated-at":1363378523000,"_id":"542692d4c026201cdc326ff8"},{"updated-at":1436760791903,"created-at":1436760791903,"author":{"login":"Miloas","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/11530682?v=3"},"body":"(loop [iter 1\n acc 0]\n (if (> iter 10)\n (println acc)\n (recur (inc iter) (+ acc iter))))\n\n;; => 55\n;; sum from 1 to 10","_id":"55a33ad7e4b020189d740551"},{"editors":[{"login":"rauhs","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/11081351?v=3"}],"body":";; loop is the recursion point for recur. The symbols in loop's \n;; binding-forms are bound to their respective init-exprs and \n;; rebound to the values of recur's exprs before the next execution \n;; of loop's body.\n\n;; calculate the factorial of n\n\n(loop [n (bigint 5), accumulator 1]\n (if (zero? n)\n accumulator ; we're done\n (recur (dec n) (* accumulator n))))\n\n;;=> 120N\n\n\n;; square each number in the vector\n\n(loop [xs (seq [1 2 3 4 5])\n result []]\n (if xs\n (let [x (first xs)]\n (recur (next xs) (conj result (* x x))))\n result))\n\n;; => [1 4 9 16 25]","author":{"avatar-url":"https://avatars.githubusercontent.com/u/19415437?v=3","account-source":"github","login":"clojurianix"},"created-at":1463831813152,"updated-at":1511862332210,"_id":"57404d05e4b0a1a06bdee497"},{"editors":[{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"}],"body":";; A loop that sums the numbers 10 + 9 + 8 + ...\n\n;; Set initial values count (cnt) from 10 and down\n(loop [sum 0 cnt 10]\n ;; If count reaches 0 then exit the loop and return sum\n (if (= cnt 0)\n sum\n ;; Otherwise add count to sum, decrease count and \n ;; use recur to feed the new values back into the loop\n (recur (+ cnt sum) (dec cnt))))","author":{"avatar-url":"https://avatars3.githubusercontent.com/u/745748?v=4","account-source":"github","login":"RobinNagpal"},"created-at":1501353444891,"updated-at":1608672429068,"_id":"597cd5e4e4b0d19c2ce9d703"},{"editors":[{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"}],"body":"(loop [i 0] \n (when (< i 5) \n (println i) \n (recur (inc i)))) ; loop i will take this value","author":{"avatar-url":"https://avatars3.githubusercontent.com/u/745748?v=4","account-source":"github","login":"RobinNagpal"},"created-at":1501353818637,"updated-at":1608672449492,"_id":"597cd75ae4b0d19c2ce9d704"},{"updated-at":1511910753719,"created-at":1511908503199,"author":{"login":"phronmophobic","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/156241?v=4"},"body":";; Iterating over a collection using loop\n\n;; 1. First call (seq xs) on the given argument and then check for nil \n;; 2. Then call next/first and use these.\n\n(loop [xs (seq [1 2 3 4 5])\n result []]\n (if xs\n (let [x (first xs)]\n (recur (next xs) (conj result (* x x))))\n result))\n\n;; the same loop can be written using destructing,\n;; but the compiler will generate two consecutive\n;; seq calls and is slightly less efficient.\n\n(loop [[x & r :as xs] (seq [])\n result []]\n (if xs\n (recur r (conj result (* x x)))\n result))","editors":[{"avatar-url":"https://avatars2.githubusercontent.com/u/156241?v=4","account-source":"github","login":"phronmophobic"}],"_id":"5a1de497e4b0a08026c48cc4"},{"editors":[{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"}],"body":";;basic loop example #1\n\n(loop [x 0\n result []]\n (if (< x 10)\n (recur\n (inc x)\n (conj result x)) result))\n;;[0 1 2 3 4 5 6 7 8 9]\n\n;;basic loop example #2\n(def citrus-list [\"lemon\" \"orange\" \"grapefruit\"])\n\n(defn display-citrus [citruses]\n (loop [[citrus & citruses] citruses]\n (println citrus)\n (if citrus (recur citruses))))\n\n(display-citrus citrus-list)","author":{"avatar-url":"https://avatars0.githubusercontent.com/u/31028993?v=4","account-source":"github","login":"ibercode"},"created-at":1513260380816,"updated-at":1513946984454,"_id":"5a32855ce4b0a08026c48cd6"},{"editors":[{"login":"ibercode","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/31028993?v=4"}],"body":";;loop general strategy\n;;given a collection of numbers [1 2 3 4 5],\n;;return a new collection [10 20 30 40 50]\n\n\n(def my-vector [1 2 3 4 5])\n\n(defn my-new-vector\n [coll]\n (loop [remain coll\n final-vec []]\n (if (empty? remain)\n final-vec\n (let [[unit & remaining] remain]\n (recur remaining\n (into final-vec [(* 10 unit)]))))))\n\n(my-new-vector my-vector)\n;;[10 20 30 40 50]\n\n;;to sum all the elements from the newly created collection:\n\n(reduce + (my-new-vector my-vector))\n;;150","author":{"avatar-url":"https://avatars0.githubusercontent.com/u/31028993?v=4","account-source":"github","login":"ibercode"},"created-at":1515925474334,"updated-at":1515927057530,"_id":"5a5b2fe2e4b0a08026c48cf3"},{"updated-at":1542302761051,"created-at":1542302489864,"author":{"login":"jiro4989","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/13825004?v=4"},"body":";; loop -> recur sample with fizzbuzz code.\n\n(defn fizzbuzz\n [n]\n (loop [f []\n i 1]\n (if (< n i)\n f\n (recur (conj f (cond\n (zero? (mod i 15)) \"fizzbuzz\"\n (zero? (mod i 3)) \"fizz\"\n (zero? (mod i 5)) \"buzz\"\n :else i))\n (inc i)))))\n\n(println (fizzbuzz 100))\n;; output is \n;; [1 2 fizz 4 buzz fizz 7 8 fizz buzz 11 fizz 13 14 fizzbuzz 16 17 fizz 19 buzz fizz 22 23 fizz buzz 26 fizz 28 29 fizzbuzz 31 32 fizz 34 buzz fizz 37 38 fizz buzz 41 fizz 43 44 fizzbuzz 46 47 fizz 49 buzz fizz 52 53 fizz buzz 56 fizz 58 59 fizzbuzz 61 62 fizz 64 buzz fizz 67 68 fizz buzz 71 fizz 73 74 fizzbuzz 76 77 fizz 79 buzz fizz 82 83 fizz buzz 86 fizz 88 89 fizzbuzz 91 92 fizz 94 buzz fizz 97 98 fizz buzz]\n","editors":[{"avatar-url":"https://avatars0.githubusercontent.com/u/13825004?v=4","account-source":"github","login":"jiro4989"}],"_id":"5bedab19e4b00ac801ed9efb"},{"updated-at":1716890888038,"created-at":1716890888038,"author":{"login":"jimka2001","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/6414129?v=4"},"body":";; loop accepts pre and post conditions\n(loop [left -1.0\n right 1.0]\n {:pre [(< left right)]}\n ...)","_id":"6655ad0869fbcc0c226174cb"}],"macro":true,"notes":[{"updated-at":1279842159000,"body":"\"Acts as a recur target.\"\r\n\r\nWhat's a recur target? A recurring target? A recursive target? I'm not a big fan of abbreviations or ambiguous terms.\r\n\r\nWouldn't it be awesome if a script could annotate all occurrences of glossary terms? Or automatically wrap glossary terms in anchor tags linking to their definition?","created-at":1279842116000,"author":{"login":"Jacolyte","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1703a0c3ed358b787f4b1bf3b2799472?r=PG&default=identicon"},"_id":"542692ebf6e94c6970521f83"},{"updated-at":1279870294000,"body":"The problem `loop` is trying to solve is that recursively calling the same function on the JVM is expensive and doesn't scale. It might work if your data structure is a thousand levels deep but it will fail badly with a depth of millions of levels.\r\n\r\nWhat is not possible on the JVM is what is called \"tail-call optimization\". `loop` is like a `while` loop in java, except that if you don't call `recur` (with the correct number of arguments) the loop will exit. In while-loop terms, `recur` avoids that a `break` statement is executed.\r\n\r\n
    int counter = 0;\r\nwhile (true) {\r\n   if (counter < 10) {\r\n      // recur\r\n      counter = inc(counter);\r\n   } else {\r\n      break;\r\n   }\r\n}\r\n
    \r\n\r\nIn that sense `loop` is a recur target as in \"target for recursion\".","created-at":1279847110000,"author":{"login":"devijvers","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/81018e4231ac1ce8b7a9e6d377092656?r=PG&default=identicon"},"_id":"542692ebf6e94c6970521f84"},{"updated-at":1279866045000,"body":"I wish the word recur in this document linked to the recur function. That'd be... awesome.","created-at":1279866045000,"author":{"login":"Jacolyte","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1703a0c3ed358b787f4b1bf3b2799472?r=PG&default=identicon"},"_id":"542692ebf6e94c6970521f85"},{"updated-at":1279892164000,"body":"It really should (and will) show up in the 'vars in' section. \r\n\r\nThe problem is that recur is a special form, and is not parsed out correctly like other vars. This will be fixed in the future.","created-at":1279892142000,"author":{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},"_id":"542692ebf6e94c6970521f86"},{"body":"Majority of `loop`s that novices write can be expressed more elegantly using 3 fundamental functions `map`, `filter` and `reduce`. Or using list comprehension `for`.","created-at":1423042890947,"updated-at":1423043065278,"author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"_id":"54d1e94ae4b0e2ac61831d0e"},{"body":"To be clear, there's no *technical* reason the JVM can't support tail recursion (despite some complications to do with call stacks and security) - it just doesn't happen to support them currently.\n\nPeople have been requesting this enhancement for at least a decade - [here's one proposal](https://blogs.oracle.com/jrose/entry/tail_calls_in_the_vm), for example.","created-at":1430499038628,"updated-at":1430499038628,"author":{"login":"pmonks","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/54865?v=3"},"_id":"5543aedee4b06eaacc9cda86"}],"arglists":["bindings & body"],"doc":"Evaluates the exprs in a lexical context in which the symbols in\n the binding-forms are bound to their respective init-exprs or parts\n therein. Acts as a recur target.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/loop","forms":["(loop [bindings*] exprs*)"]},{"added":"1.0","ns":"clojure.core","name":"add-classpath","file":"clojure/core.clj","type":"function","column":1,"see-alsos":null,"line":5205,"examples":[{"updated-at":1507317464731,"created-at":1507317464731,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"},"body":";; There are alternatives\n\n;; https://github.com/cemerick/pomegranate\n\n;; http://grokbase.com/p/gg/clojure/12bnhbvmpy/how-to-add-an-url-into-the-classpath\n","_id":"59d7d6d8e4b03026fe14ea57"}],"deprecated":"1.1","notes":null,"arglists":["url"],"doc":"DEPRECATED \n\n Adds the url (String or URL object) to the classpath per\n URLClassLoader.addURL","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/add-classpath"},{"added":"1.0","ns":"clojure.core","name":"bit-flip","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":null,"line":1357,"examples":[{"author":{"login":"zmila","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/68dd6f50915854aa04fefcf4d6fa5c8e?r=PG&default=identicon"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":"user=> (bit-flip 2r1011 2)\n15 \n;; 15 = 2r1111\n\n(bit-flip 2r1111 2)\n11 \n;; 11 = 2r1011","created-at":1280339556000,"updated-at":1332952408000,"_id":"542692c8c026201cdc326a6b"}],"notes":null,"arglists":["x n"],"doc":"Flip bit at index n","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/bit-flip"},{"added":"1.0","ns":"clojure.core","name":"long-array","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"to-var":{"library-url":"https://github.com/clojure/clojure","name":"longs","ns":"clojure.core"},"author":{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},"created-at":1342917397000,"_id":"542692ebf6e94c6970521ea2"},{"created-at":1581624427170,"author":{"login":"Hindol","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/705227?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"int-array","ns":"clojure.core"},"_id":"5e45ac6be4b0ca44402ef834"},{"created-at":1581624433858,"author":{"login":"Hindol","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/705227?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"float-array","ns":"clojure.core"},"_id":"5e45ac71e4b0ca44402ef835"},{"created-at":1581624442586,"author":{"login":"Hindol","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/705227?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"double-array","ns":"clojure.core"},"_id":"5e45ac7ae4b0ca44402ef836"},{"created-at":1581624451957,"author":{"login":"Hindol","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/705227?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"boolean-array","ns":"clojure.core"},"_id":"5e45ac83e4b0ca44402ef837"}],"line":5393,"examples":[{"author":{"login":"shockbob","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon"},"editors":[{"login":"shockbob","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon"},{"login":"shockbob","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon"},{"login":"shockbob","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon"}],"body":";; create a long array using long-array and show it can be used\n;; with the standard Java Arrays functions binarySearch and fill\n;; note the needed coercions\n\nuser=> (def is (long-array (range 3 20)))\n#'user/is\nuser=> (vec is)\n[3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]\nuser=> (java.util.Arrays/binarySearch is (long 10))\n7\nuser=> (java.util.Arrays/fill is 3 8 (long 99))\nnil\nuser=> (vec is)\n[3 4 5 99 99 99 99 99 11 12 13 14 15 16 17 18 19]\nuser=>","created-at":1313907019000,"updated-at":1313963219000,"_id":"542692c7c026201cdc326962"}],"notes":null,"arglists":["size-or-seq","size init-val-or-seq"],"doc":"Creates an array of longs","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/long-array"},{"added":"1.0","ns":"clojure.core","name":"descendants","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1400492134000,"author":{"login":"ryo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3f7913b563c72083c74030d928ba407e?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"ancestors","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ead"}],"line":5667,"examples":[{"author":{"login":"shockbob","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon"},"editors":[],"body":";; simple example a toy poodle is a poodle is a dog is an animal\n\nuser=> (derive ::dog ::animal)\nnil\nuser=> (derive ::poodle ::dog)\nnil\nuser=> (derive ::toy_poodle ::poodle)\nnil\nuser=> (descendants ::animal)\n#{:user/toy_poodle :user/poodle :user/dog}\nuser=>","created-at":1313968073000,"updated-at":1313968073000,"_id":"542692c8c026201cdc326a24"},{"updated-at":1597842188323,"created-at":1597842188323,"author":{"login":"uosl","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/3865590?v=4"},"body":";; You can combine `descendants` with `parents` to only get the immediate children.\n\n(filter #(contains? (parents h %) tag)\n (descendants h tag))","_id":"5f3d230ce4b0b1e3652d7381"}],"notes":null,"arglists":["tag","h tag"],"doc":"Returns the immediate and indirect children of tag, through a\n relationship established via derive. h must be a hierarchy obtained\n from make-hierarchy, if not supplied defaults to the global\n hierarchy. Note: does not work on Java type inheritance\n relationships.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/descendants"},{"added":"1.11","ns":"clojure.core","name":"iteration","file":"clojure/core.clj","type":"function","column":1,"see-alsos":null,"line":7910,"examples":[{"updated-at":1698272254989,"created-at":1698272254989,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":";; Let's set up an atom to act like a paginated data source…\n(def pages\n (atom {\"a\" {:items [\"Rose\" \"Tulip\" \"Marigold\" \"Lavender\" \"Daffodil\"] :next-page \"b\"}\n \"b\" {:items [\"Sunflower\" \"Petunia\" \"Chrysanthemum\" \"Dandelion\" \"Pansy\"] :next-page \"c\"}\n \"c\" {:items [\"Orchid\" \"Daisy\" \"Lily\" \"Geranium\" \"Hyacinth\"] :next-page \"d\"}\n \"d\" {:items [\"Azalea\" \"Begonia\" \"Iris\" \"Poppy\" \"Jasmine\"]}}))\n\n;; And let's set up a function to access that atom, with a delay to simulate\n;; network slowness…\n(defn get-page! [id]\n (Thread/sleep 3000)\n (get @pages id))\n\n;; See that `iteration` allows for a very succinct, lazy way to get pages…\n(-> (iteration get-page! :initk \"a\", :vf :items, :kf :next-page)\n first\n time)\n\"Elapsed time: 3000.947447 msecs\"\n;; => [\"Rose\" \"Tulip\" \"Marigold\" \"Lavender\" \"Daffodil\"]\n\n(-> (iteration get-page! :initk \"a\", :vf :items, :kf :next-page)\n second\n time)\n\"Elapsed time: 6002.736159 msecs\"\n;; => [\"Sunflower\" \"Petunia\" \"Chrysanthemum\" \"Dandelion\" \"Pansy\"]\n\n;; Note that common methods to lazily concatenate pages can get hit by a\n;; chunking time penalty…\n(->> (iteration get-page! :initk \"a\", :vf :items, :kf :next-page)\n (sequence cat)\n second\n time)\n\"Elapsed time: 12013.729409 msecs\"\n;; => \"Tulip\"\n\n;; So consider using `lazy-seq` and/or `lazy-cat` for lazier performance","_id":"653993fe69fbcc0c226173e2"}],"notes":null,"arglists":["step & {:keys [somef vf kf initk], :or {vf identity, kf identity, somef some?, initk nil}}"],"doc":"Creates a seqable/reducible via repeated calls to step,\n a function of some (continuation token) 'k'. The first call to step\n will be passed initk, returning 'ret'. Iff (somef ret) is true,\n (vf ret) will be included in the iteration, else iteration will\n terminate and vf/kf will not be called. If (kf ret) is non-nil it\n will be passed to the next step call, else iteration will terminate.\n\n This can be used e.g. to consume APIs that return paginated or batched data.\n\n step - (possibly impure) fn of 'k' -> 'ret'\n\n :somef - fn of 'ret' -> logical true/false, default 'some?'\n :vf - fn of 'ret' -> 'v', a value produced by the iteration, default 'identity'\n :kf - fn of 'ret' -> 'next-k' or nil (signaling 'do not continue'), default 'identity'\n :initk - the first value passed to step, default 'nil'\n\n It is presumed that step with non-initk is unreproducible/non-idempotent.\n If step with initk is unreproducible it is on the consumer to not consume twice.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/iteration"},{"added":"1.0","ns":"clojure.core","name":"merge","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1294676416000,"author":{"login":"Nebulus","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/61aa4140c24b0cded6b20d88200e7f16?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"merge-with","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521ad7"},{"created-at":1317787765000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"hash-map","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521ad8"},{"created-at":1536776434976,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"assoc","ns":"clojure.core"},"_id":"5b9958f2e4b00ac801ed9e95"}],"line":3065,"examples":[{"author":{"login":"dpritchett","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/147981?v=3"},"editors":[{"login":"srid","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bd3a68d670372cd09876c26270a4299a?r=PG&default=identicon"},{"login":"srid","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bd3a68d670372cd09876c26270a4299a?r=PG&default=identicon"},{"login":"srid","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bd3a68d670372cd09876c26270a4299a?r=PG&default=identicon"},{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":"(merge {:a 1 :b 2 :c 3} {:b 9 :d 4})\n;;=> {:d 4, :a 1, :b 9, :c 3}","created-at":1279071769000,"updated-at":1422374016946,"_id":"542692cfc026201cdc326e73"},{"author":{"login":"ryo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3f7913b563c72083c74030d928ba407e?r=PG&default=identicon"},"editors":[{"login":"ryo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3f7913b563c72083c74030d928ba407e?r=PG&default=identicon"},{"login":"ryo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3f7913b563c72083c74030d928ba407e?r=PG&default=identicon"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":"(merge {:a 1} nil) ;=> {:a 1}\n(merge nil {:a 1}) ;=> {:a 1}\n(merge nil nil) ;=> nil\n","created-at":1401310493000,"updated-at":1422374049474,"_id":"542692d4c026201cdc32700c"},{"body":";; `merge` can be used to support the setting of default values\n(merge {:foo \"foo-default\" :bar \"bar-default\"} \n {:foo \"custom-value\"})\n;;=> {:foo \"custom-value\" :bar \"bar-default\"}\n\n;; This is useful when a function has a number of options\n;; with default values.\n(defn baz [& options]\n (let [options (merge {:opt1 \"default-1\" :opt2 \"default-2\"} \n (first options))]\n options))\n\n(baz {:opt1 \"custom-1\" :opt3 \"custom-3\"})\n;;=> {:opt3 \"custom-3\" :opt1 \"custom-1 :opt2 \"default-2\"}\n","author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"},"created-at":1422375001817,"updated-at":1422375001817,"_id":"54c7b859e4b0e2ac61831cdf"},{"editors":[{"login":"dijonkitchen","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/11434205?v=4"}],"body":";; For recursively merging deeply-nested maps:\n\n(defn deep-merge [v & vs]\n (letfn [(rec-merge [v1 v2]\n (if (and (map? v1) (map? v2))\n (merge-with deep-merge v1 v2)\n v2))]\n (if (some identity vs)\n (reduce #(rec-merge %1 %2) v vs)\n (last vs))))\n\n(deep-merge {:a {:b true}} {:a {:b false}} {:a {:b nil}})\n;; {:a {:b nil}}\n\n(deep-merge {:a 1} nil)\n;; nil ;; note that this isn't consistent with the regular merge function\n\n;; Source: https://gist.github.com/danielpcox/c70a8aa2c36766200a95#gistcomment-2677502","author":{"avatar-url":"https://avatars3.githubusercontent.com/u/11434205?v=4","account-source":"github","login":"dijonkitchen"},"created-at":1535149214818,"updated-at":1536856542156,"_id":"5b80849ee4b00ac801ed9e75"},{"updated-at":1548252366101,"created-at":1548252366101,"author":{"login":"genmeblog","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/38646601?v=4"},"body":";; latest comment under above gist provides another\n;; simpler and more consistent version of deep-merge\n;; Source: https://gist.github.com/danielpcox/c70a8aa2c36766200a95#gistcomment-2759497\n\n(defn deep-merge [a & maps]\n (if (map? a)\n (apply merge-with deep-merge a maps)\n (apply merge-with deep-merge maps)))\n\n(deep-merge {:a {:b true}} {:a {:b false}} {:a {:b nil}})\n;; => {:a {:b nil}}\n\n(deep-merge {:a 1} nil)\n;; => {:a 1}\n","_id":"5c4874cee4b0ca44402ef622"},{"updated-at":1566278942641,"created-at":1566278942641,"author":{"login":"liuchong","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/236058?v=4"},"body":"(merge {:x 1 :y 2} {:y 3 :z 4})\n;; => {:x 1, :y 3, :z 4}","_id":"5d5b851ee4b0ca44402ef7a8"},{"editors":[{"login":"Crowbrammer","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/19522656?v=4"}],"body":";; Looking at the source code, merge starts with the \n;; original collection and uses conj which adds elements \n;; as is into the collection, so merge can be used\n;; with more than just maps--i.e. using a vector returns a vector.\n\n(merge [:a \"Whoa\"] [:c \"Crash Bandicoot\"])\n;; => [:a \"Whoa\" [:c \"Crash Bandicoot\"]]\n(merge [:a \"Whoa\"] \"Crash Bandicoot\")\n;; => [:a \"Whoa\" \"Crash Bandicoot\"]","author":{"avatar-url":"https://avatars0.githubusercontent.com/u/19522656?v=4","account-source":"github","login":"Crowbrammer"},"created-at":1610333321854,"updated-at":1610333698491,"_id":"5ffbbc89e4b0b1e3652d7429"},{"updated-at":1693812802785,"created-at":1693812463082,"author":{"login":"rainspeaker","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/4544929?v=4"},"body":";; in the source, merge uses `or` to substitute an empty map if given\n;; `nil` for the first value. Since \"or\" also catches false, this works: \n\n(merge false {:a 1})\n;; => {:a 1}\n\n;; On the other hand, this throws a ClassCastException:\n\n(merge true {:a 1}) \n\n;; This probably shouldn't be relied on","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/4544929?v=4","account-source":"github","login":"rainspeaker"}],"_id":"64f586efe4b08cf8563f4be8"},{"updated-at":1726844460386,"created-at":1726844460386,"author":{"login":"raszi","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/76983?v=4"},"body":";; This could be handy in certain situations.\n\n(defn reverse-merge\n \"Same as `merge` but works in reverse order.\"\n [& maps]\n (apply merge (reverse maps)))\n\n(reverse-merge {:foo \"FOO\"}\n {:foo \"---\" :bar \"BAR\"}\n {:bar \"---\" :baz \"BAZ\"})\n;; => {:bar \"BAR\", :baz \"BAZ\", :foo \"FOO\"}","_id":"66ed8e2c69fbcc0c226174f9"}],"notes":[{"body":"### When to use assoc, conj, merge\n\n`assoc`, `conj` & `merge` behave very differently for different data structures\n\nIf you are writing a function that can handle multiple kinds of collections, then your choice will make a big difference.\n\nTreat merge as a maps-only function (its similar to conj for other collections).\n\nMy opinion:\n\n* `assoc` - use when you are 'changing' existing key/value pairs\n* `conj` - use when you are 'adding' new key/value pairs\n* `merge` - use when you are combining two or more maps\n\nRef : https://stackoverflow.com/a/3204346","created-at":1620798989281,"updated-at":1620799011530,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/1042312?v=4","account-source":"github","login":"udkl"},"_id":"609b6e0de4b0b1e3652d74f9"},{"author":{"login":"rainspeaker","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/4544929?v=4"},"updated-at":1693813134298,"created-at":1693813134298,"body":"Merge is more similar to concat than to conj IMO. ","_id":"64f5898ee4b08cf8563f4bed"}],"arglists":["& maps"],"doc":"Returns a map that consists of the rest of the maps conj-ed onto\n the first. If a key occurs in more than one map, the mapping from\n the latter (left-to-right) will be the mapping in the result.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/merge"},{"added":"1.0","ns":"clojure.core","name":"accessor","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1412886553460,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"},"to-var":{"ns":"clojure.core","name":"get","library-url":"https://github.com/clojure/clojure"},"_id":"5436f019e4b0ae795603157e"}],"line":4097,"examples":[{"author":{"login":"tormaroe","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8bc7bb10bee96efb190053fe92ffd250?r=PG&default=identicon"},"editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/50778?v=4","account-source":"github","login":"edipofederle"}],"body":"(defstruct car-struct :make :model :year :color)\n\n(def car (struct car-struct \"Toyota\" \"Prius\" 2010))\n\n(def make (accessor car-struct :make))\n\n; Same as both (car :make) and (:make car)\n(make car) \n;;=> \"Toyota\" \n\n","created-at":1289603045000,"updated-at":1700649761310,"_id":"542692cac026201cdc326b11"}],"notes":null,"arglists":["s key"],"doc":"Returns a fn that, given an instance of a structmap with the basis,\n returns the value at the key. The key must be in the basis. The\n returned function should be (slightly) more efficient than using\n get, but such use of accessors should be limited to known\n performance-critical areas.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/accessor"},{"added":"1.0","ns":"clojure.core","name":"integer?","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1440146014714,"author":{"login":"muhuk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/40178?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"number?","ns":"clojure.core"},"_id":"55d6e25ee4b0831e02cddf15"},{"created-at":1495654427514,"author":{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/94482?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"int?","ns":"clojure.core"},"_id":"5925e01be4b093ada4d4d73b"}],"line":1388,"examples":[{"author":{"login":"dpritchett","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/147981?v=3"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":"user=> (integer? 1)\ntrue\nuser=> (integer? 1.0)\nfalse","created-at":1279074074000,"updated-at":1332950732000,"_id":"542692c8c026201cdc326a30"},{"updated-at":1487037245803,"created-at":1487037245803,"author":{"login":"jungziege","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/405465?v=3"},"body":";; Note: tests if it's a math integer, not a Java Integer\nuser=> (integer? (inc Integer/MAX_VALUE))\ntrue","_id":"58a2633de4b01f4add58fe53"},{"updated-at":1495656170180,"created-at":1495656170180,"author":{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/94482?v=3"},"body":";; integer? returns true for BigInts. If you don't want this behavior, you can \n;; use the int? predicate instead in Clojure 1.9 or later:\n\n(integer? 13N)\n;; => true\n\n(int? 13N)\n;; => false","_id":"5925e6eae4b093ada4d4d742"}],"notes":null,"arglists":["n"],"doc":"Returns true if n is an integer","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/integer_q"},{"added":"1.4","ns":"clojure.core","name":"mapv","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1413326056085,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"},"to-var":{"ns":"clojure.core","name":"map","library-url":"https://github.com/clojure/clojure"},"_id":"543da4e8e4b02688d208b1b8"},{"created-at":1507137288794,"author":{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"vec","ns":"clojure.core"},"_id":"59d51708e4b03026fe14ea4f"},{"created-at":1516208408133,"author":{"login":"jcburley","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/430319?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"reduce","ns":"clojure.core"},"_id":"5a5f8118e4b0a08026c48cfa"},{"created-at":1516208418039,"author":{"login":"jcburley","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/430319?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"pmap","ns":"clojure.core"},"_id":"5a5f8122e4b0a08026c48cfb"}],"line":7050,"examples":[{"editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3","account-source":"github","login":"phreed"},{"login":"totorigolo","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/1183296?v=4"}],"updated-at":1542244482242,"created-at":1421096939041,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3","account-source":"github","login":"phreed"},"body":"(mapv inc [1 2 3 4 5])\n;;=> [2 3 4 5 6]\n\n\n;; mapv can be used with multiple collections. Collections will be consumed\n;; and passed to the mapping function in parallel:\n(mapv + [1 2 3] [4 5 6])\n;;=> [5 7 9]\n\n\n;; When mapv is passed more than one collection, the mapping function will\n;; be applied until one of the collections runs out:\n(mapv + [1 2 3] (iterate inc 1))\n;;=> [2 4 6]\n\n\n\n;; mapv is often used in conjunction with the # reader macro:\n(mapv #(str \"Hello \" % \"!\" ) [\"Ford\" \"Arthur\" \"Tricia\"])\n;;=> [\"Hello Ford!\" \"Hello Arthur!\" \"Hello Tricia!\"]\n\n;; A useful idiom to pull \"columns\" out of a collection of collections. \n;; Note, it is equivalent to:\n;; (mapv vector [:a :b :c] [:d :e :f] [:g :h :i])\n\n(apply mapv vector [[:a :b :c]\n [:d :e :f]\n [:g :h :i]])\n;;=> [[:a :d :g] [:b :e :h] [:c :f :i]]","_id":"54b437ebe4b081e022073c02"},{"updated-at":1584701507565,"created-at":1573719104514,"author":{"login":"kangbb","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/15232085?v=4"},"body":";; The difference between `map` and `mapv` is that:\n;; `map` return a lazy sequence,\n;; `mapv` return a sequence.\n(def result (map println [1 2 3]))\n;;=> #'user/result\nresult\n;;=> 1\n;; 2\n;; 3\n;; (nil nil nil)\n\n(def result (mapv println [1 2 3]))\n;;=> 1\n;; 2\n;; 3\n;; #'user/result\nresult\n;;=> [nil nil nil]\n\n;; So, we can use it when we want to get a side effect immediately.\n","editors":[{"avatar-url":"https://avatars1.githubusercontent.com/u/15232085?v=4","account-source":"github","login":"kangbb"},{"login":"graycodes","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/1530754?v=4"}],"_id":"5dcd0c40e4b0ca44402ef7de"},{"updated-at":1619002206128,"created-at":1619001516133,"author":{"login":"sFritsch09","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/58191603?v=4"},"body":";; convert number to vector:\n; numb = 210\n\n((fn [numb] (mapv #(Character/digit % 10) (str numb))) 210)\n;;=> [2 1 0]\n\n;; and the other way around:\n\n(read-string (reduce str [2 1 0]))\n;;=> 210","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/58191603?v=4","account-source":"github","login":"sFritsch09"}],"_id":"608000ace4b0b1e3652d74c9"}],"notes":[{"body":"Like `map` but returns a vector. In most cases equivalent to calling `(into [] (map f c1 c2 ...))`. Is much faster than map (but is not lazy!) in the `(mapv f coll)` case.","created-at":1430433040188,"updated-at":1430433049879,"author":{"login":"num1","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/466333?v=3"},"_id":"5542ad10e4b06eaacc9cda82"},{"author":{"login":"KingMob","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/946421?v=4"},"updated-at":1596048409289,"created-at":1596048409289,"body":"It's not necessarily true at all that `mapv` will be faster than `map`. `mapv` (and related fns like `filterv`) have increased memory needs (creating unused values, realizing intermediate sequences, etc) that hurt it.\n\nHere's a simple example showing how `mapv`/`filterv` can be slower. (Benchmarked with criterium.)\n\n```\n(let [nums (range 10000000)]\n (bench\n (reduce +' 0 (filter even? (map #(* % %) nums))))\n\n (bench\n (reduce +' 0 (filterv even? (mapv #(* % %) nums)))))\n```\nand the results, showing `map` is actually a little faster than `mapv`:\n\n```\nEvaluation count : 120 in 60 samples of 2 calls.\n Execution time mean : 768.870217 ms\n Execution time std-deviation : 21.043586 ms\n Execution time lower quantile : 756.049838 ms ( 2.5%)\n Execution time upper quantile : 835.719808 ms (97.5%)\n Overhead used : 1.805367 ns\n\nFound 9 outliers in 60 samples (15.0000 %)\n\tlow-severe\t 3 (5.0000 %)\n\tlow-mild\t 6 (10.0000 %)\n Variance from outliers : 14.2178 % Variance is moderately inflated by outliers\n\n\n\nEvaluation count : 120 in 60 samples of 2 calls.\n Execution time mean : 800.356084 ms\n Execution time std-deviation : 49.667013 ms\n Execution time lower quantile : 756.382597 ms ( 2.5%)\n Execution time upper quantile : 883.471627 ms (97.5%)\n Overhead used : 1.805367 ns\n\nFound 12 outliers in 60 samples (20.0000 %)\n\tlow-severe\t 5 (8.3333 %)\n\tlow-mild\t 1 (1.6667 %)\n\thigh-mild\t 6 (10.0000 %)\n Variance from outliers : 46.7536 % Variance is moderately inflated by outliers\n```\n\nThe takeaway is, don't pick `mapv` just for speed reasons.","_id":"5f21c419e4b0b1e3652d7327"}],"arglists":["f coll","f c1 c2","f c1 c2 c3","f c1 c2 c3 & colls"],"doc":"Returns a vector consisting of the result of applying f to the\n set of first items of each coll, followed by applying f to the set\n of second items in each coll, until any one of the colls is\n exhausted. Any remaining items in other colls are ignored. Function\n f should accept number-of-colls arguments.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/mapv"},{"added":"1.11","ns":"clojure.core","name":"infinite?","file":"clojure/core.clj","type":"function","column":1,"see-alsos":null,"line":8223,"examples":[{"updated-at":1698252954064,"created-at":1698252954064,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":";; This works for doubles…\n(infinite? (/ 1.0 0.0))\n;; => true\n\n;; But infinity is not a concept for longs…\n(infinite? (/ 1 0))\n;; Execution error (ArithmeticException) at…\n;; Divide by zero\n\n;; But it is worth being aware of what is considered to be infinite…\n(infinite? (+ Double/MAX_VALUE 1e292))\n;; => true\n;; And what isn't…\n(infinite? (+ Double/MAX_VALUE 1e291))\n;; => false","_id":"6539489a69fbcc0c226173d4"}],"notes":null,"arglists":["num"],"doc":"Returns true if num is negative or positive infinity, else false","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/infinite_q"},{"added":"1.2","ns":"clojure.core","name":"partition-all","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1313710375000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"partition","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c74"},{"created-at":1313710383000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"partition-by","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c75"}],"line":7388,"examples":[{"updated-at":1420742107199,"created-at":1279643883000,"body":"(partition 4 [0 1 2 3 4 5 6 7 8 9])\n;;=> ((0 1 2 3) (4 5 6 7))\n\n(partition-all 4 [0 1 2 3 4 5 6 7 8 9])\n;;=> ((0 1 2 3) (4 5 6 7) (8 9))\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3","account-source":"github","login":"phreed"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/142529?v=3","account-source":"github","login":"nipra"},"_id":"542692ccc026201cdc326c8e"},{"author":{"login":"Tap","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/925c5d43b739098e6f16f804f5dc4868?r=PG&default=identicon"},"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":"(partition-all 2 4 [0 1 2 3 4 5 6 7 8 9])\n;;=> ((0 1) (4 5) (8 9))","created-at":1349617127000,"updated-at":1420742136613,"_id":"542692d4c026201cdc327029"},{"updated-at":1599548333018,"created-at":1373311985000,"body":";; Caution: Partitioning lazy sequence code freeze\n;; Edit: Only because (rdr l) is buggy and returns an infinite sequence!\n\n(def l [1 2 3 4 5])\n;create a simple lazy sequence function testing only\n;(rdr l) returns a lazy sequence from l\n(def rdr (fn reader[x] (cons (first x) (lazy-seq (reader (rest x))))))\n\n;the line below will freeze\n(doall (partition-all 2 (rdr l)) )\n\n;add-in a take-while statement do exit the lazy sequence on nil\n(doall (partition-all 2 (take-while (complement nil?) (rdr l))))","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3","account-source":"github","login":"phreed"},{"login":"rbuchmann","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/611792?v=4"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/ee33873c26c4a6b7e1daa3ebb777d58c?r=PG&default=identicon","account-source":"clojuredocs","login":"gerritjvv"},"_id":"542692d4c026201cdc32702a"},{"updated-at":1561100812644,"created-at":1561100482422,"author":{"login":"ningDr","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/38251752?v=4"},"body":";; When the step parameter is provided, the starting index value of the first item in the \n;; next group steps relative to the current index value\n;; 提供step参数时,下一个分组的第一项的起始索引值相对于当前索引值的步进(+ pre-index step)\n(println (partition-all 2 3 '(0 1 2 3 4 5 6 7 8 9)))\n;; => ((0 1) (3 4) (6 7) (9))\n(println (partition-all 4 3 '(0 1 2 3 4 5 6 7 8 9)))\n;; => ((0 1 2 3) (3 4 5 6) (6 7 8 9) (9))\n;; When n is equal to step, it is equivalent to no step parameter\n;; 当n与step相等,相当于无step参数\n(println (partition-all 3 3 '(0 1 2 3 4 5 6 7 8 9)))\n;; => ((0 1 2) (3 4 5) (6 7 8) (9))","editors":[{"avatar-url":"https://avatars0.githubusercontent.com/u/38251752?v=4","account-source":"github","login":"ningDr"}],"_id":"5d0c80c2e4b0ca44402ef75b"}],"notes":[{"body":"be aware of the case of n is 0\n\n(partition-all 0 '(1 2 3))\n\nwill cause repl blocked and cpu 100%","created-at":1716860281141,"updated-at":1716860322687,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/46063475?v=4","account-source":"github","login":"kkprop"},"_id":"6655357969fbcc0c226174ca"}],"arglists":["n","n coll","n step coll"],"doc":"Returns a lazy sequence of lists like partition, but may include\n partitions with fewer than n items at the end. Returns a stateful\n transducer when no collection is provided.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/partition-all"},{"added":"1.2","ns":"clojure.core","name":"partition-by","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1313710412000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"partition","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ee1"},{"created-at":1313710420000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"partition-all","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ee2"},{"created-at":1331014947000,"author":{"login":"abrooks","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/69976?v=2"},"to-var":{"ns":"clojure.core","name":"group-by","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ee3"},{"created-at":1496446489487,"author":{"login":"stellingsimon","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/7038847?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"dedupe","ns":"clojure.core"},"_id":"5931f619e4b06e730307db21"},{"created-at":1553712274503,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"sort","ns":"clojure.core"},"_id":"5c9bc492e4b0ca44402ef6ea"},{"created-at":1659193765852,"author":{"login":"mars0i","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1836941?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"split-with","ns":"clojure.core"},"_id":"62e549a5e4b0b1e3652d7634"}],"line":7308,"examples":[{"author":{"login":"wilkes","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/20a7eb5b792999d37386ddf622543c71?r=PG&default=identicon"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":"user=> (partition-by #(= 3 %) [1 2 3 4 5])\n((1 2) (3) (4 5))","created-at":1279936678000,"updated-at":1332949621000,"_id":"542692c7c026201cdc3269da"},{"author":{"login":"wilkes","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/20a7eb5b792999d37386ddf622543c71?r=PG&default=identicon"},"editors":[{"login":"wilkes","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/20a7eb5b792999d37386ddf622543c71?r=PG&default=identicon"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":"user=> (partition-by odd? [1 1 1 2 2 3 3])\n((1 1 1) (2 2) (3 3))\n\nuser=> (partition-by even? [1 1 1 2 2 3 3])\n((1 1 1) (2 2) (3 3))\n","created-at":1279936736000,"updated-at":1285497469000,"_id":"542692c7c026201cdc3269dc"},{"updated-at":1597775773722,"created-at":1318525613000,"body":";; (this is part of a solution from 4clojure.com/problem 30)\nuser=> (partition-by identity \"Leeeeeerrroyyy\")\n((\\L) (\\e \\e \\e \\e \\e \\e) (\\r \\r \\r) (\\o) (\\y \\y \\y))","editors":[{"avatar-url":"https://www.gravatar.com/avatar/8d3c423e74750fa42c0386833e4b8209?r=PG&default=identicon","account-source":"clojuredocs","login":"belun"},{"avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3","account-source":"github","login":"jafingerhut"},{"login":"rfemygdio","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/26044589?v=4"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/8d3c423e74750fa42c0386833e4b8209?r=PG&default=identicon","account-source":"clojuredocs","login":"belun"},"_id":"542692d4c026201cdc32702b"},{"editors":[{"login":"smnplk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/380618?v=3"}],"updated-at":1466670505123,"created-at":1412082807145,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/1698238?v=2","account-source":"github","login":"martinhynar"},"body":";; Note that previously created 'bins' are not used when same value is seen again\nuser=> (partition-by identity \"ABBA\")\n((\\A) (\\B \\B) (\\A))\n\n;; That is why you use group-by function if you want all the the same values in the same 'bins' :) \n;; Which gives you a hash, but you can extract values from that if you need.\n\n(group-by identity \"ABBA\")\n=> {\\A [\\A \\A], \\B [\\B \\B]}","_id":"542aac77e4b0df9bb778a599"},{"body":";; Arbitrary partitioning\n(let [seen (atom true)]\n (partition-by #(cond\n (#{1} %) (reset! seen (not @seen))\n (or (and (string? %)\n (< (count %) 2))\n (char? %)) \"letter\"\n (string? %) \"string\"\n (#{0} %) 0\n (vector? %) (count %)\n :else \"rest\")\n [1 1 1 2 3 nil \"a\" \\l 0 4 5 {:a 1} \"bc\" \"aa\" \"k\" [0] [1 1] [2 2]]))\n;;=> ((1) (1) (1) (2 3 nil) (\"a\" \\l) (0) (4 5 {:a 1}) (\"bc\" \"aa\") (\"k\") ([0]) ([1 1] [2 2]))","author":{"login":"vede1","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8151095?v=2"},"created-at":1414773403982,"updated-at":1415348351870,"editors":[{"login":"vede1","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8151095?v=2"}],"_id":"5453ba9be4b0dc573b892fb5"},{"updated-at":1458482052841,"created-at":1458482052841,"author":{"login":"ertugrulcetin","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8271291?v=3"},"body":"user=> (partition-by count [\"a\" \"b\" \"ab\" \"ac\" \"c\"])\n\n;;=> ((\"a\" \"b\") (\"ab\" \"ac\") (\"c\"))","_id":"56eeab84e4b0b41f39d96cea"},{"updated-at":1557411490030,"created-at":1557411490030,"author":{"login":"artemiy312","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/13870342?v=4"},"body":"user=> (partition-by identity [1 1 1 1 2 2 3])\n;;=> ((1 1 1 1) (2 2) (3))\n","_id":"5cd436a2e4b0ca44402ef71e"},{"editors":[{"login":"johanatan","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/583903?v=4"}],"body":"I think this is a better (more agnostic & more declarative/functional)\narbitrary partitioning. The ratio of true:false can be tweaked for longer\naverage sequence length.\n\n(defn arbitrarily-partition [coll]\n (let [signals (take (count coll) (cycle [true false]))\n shuffled (shuffle signals)\n zipped (map vector shuffled coll)\n partitioned (partition-by first zipped)]\n (for [c partitioned]\n (map second c))))\n\n;;=> (arbitrarily-partition (range 100))\n((0 1) (2) (3) (4 5) (6 7) (8 9 10) (11) (12) (13 14 15) (16) (17 18) (19) (20) (21) (22 23 24 25 26) (27 28) (29) (30 31) (32) (33 34 35 36 37 38) (39 40 41) (42) (43 44 45 46 47) (48 49) (50) (51 52 53) (54) (55 56) (57 58) (59 60 61) (62) (63) (64) (65 66) (67 68) (69) (70) (71) (72 73 74 75) (76) (77 78) (79) (80) (81 82) (83 84 85) (86) (87 88) (89 90 91 92 93) (94) (95 96 97) (98) (99))","author":{"avatar-url":"https://avatars3.githubusercontent.com/u/583903?v=4","account-source":"github","login":"johanatan"},"created-at":1597704699181,"updated-at":1597724481351,"_id":"5f3b09fbe4b0b1e3652d737a"}],"notes":[{"updated-at":1338786617000,"body":"It's worth mentioning that `(partition-by identity …)` is equivalent to the `Data.List.group` function in Haskell:\r\n\r\n
     \r\n(defn group [coll]\r\n  (partition-by identity coll))\r\n
    \r\n\r\nWhich proves to be an interesting idiom:\r\n\r\n
    user=> (apply str \r\n         (for [ch (group \"fffffffuuuuuuuuuuuu\")] \r\n           (str (first ch) (count ch))))\r\n⇒ \"f7u12\"\r\n
    ","created-at":1338782914000,"author":{"login":"Iceland_jack","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/c889e0a95a3bb07f90ab28ad442f1127?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fe1"},{"author":{"login":"rauhs","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/11081351?v=3"},"updated-at":1511875643591,"created-at":1511875643591,"body":"Many other programming languages like Kotlin or Haskell define `partition` slightly different. They partition the given collection into two collections, the first containing all truthy values and the second elements all falsy elements. This function does it:\n\n```\n(defn partition-2\n \"Partitions the collection into exactly two [[all-truthy] [all-falsy]]\n collection.\"\n [pred coll]\n (mapv persistent!\n (reduce\n (fn [[t f] x]\n (if (pred x)\n [(conj! t x) f]\n [t (conj! f x)]))\n [(transient []) (transient [])]\n coll)))\n(partition-2 odd? (range 5))\n\n```","_id":"5a1d643be4b0a08026c48cc3"},{"author":{"login":"jcburley","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/430319?v=4"},"updated-at":1516207930627,"created-at":1516207930627,"body":"I tried this implementation of your Kotlin/Haskell `partition`, which is simpler but somewhat slower (less than 2x):\n\n```\n(defn partition-3\n \"Partitions the collection into exactly two [[all-truthy] [all-falsy]]\n collection.\"\n [pred coll]\n (let [m (group-by pred coll)]\n [(m true) (m false)]))\n```","_id":"5a5f7f3ae4b0a08026c48cf9"},{"body":"A third implementation which in my limited testing in cljs is the fastest so far:\n```\n(defn split-by\n \"Effectively though non-lazily splits the `coll`ection using `pred`,\n essentially like `[(filter coll pred) (remove coll pred)]`\"\n [pred coll]\n (let [match (transient [])\n no-match (transient [])]\n (doseq [v coll]\n (if (pred v)\n (conj! match v)\n (conj! no-match v)))\n [(persistent! match) (persistent! no-match)]))\n```\n\nUsing `simple-benchmark` in cljs, these are the results:\n```\n[r (range 1000)], (partition-2 odd? r), 1000 runs, 167 msecs\n[r (range 1000)], (partition-3 odd? r), 1000 runs, 364 msecs\n[r (range 1000)], (split-by odd? r), 1000 runs, 60 msecs\n```\n\nIt's worth noting that all implementations of the java-esque `partition` in this thread are non-lazy.\n\nOn big collections where you don't want to realize the whole list, this is the fastest:\n```\n[(filter odd? r) (filter (complement odd?) r)]\n```\n\nCan also be written as:\n\n```\n((juxt filter remove) odd? r)\n```\n\n(taken from: http://blog.jayfields.com/2011/08/clojure-partition-by-split-with-group.html)","created-at":1576139342503,"updated-at":1576139618518,"author":{"avatar-url":"https://avatars0.githubusercontent.com/u/2477927?v=4","account-source":"github","login":"Saikyun"},"_id":"5df1fa4ee4b0ca44402ef7f6"},{"author":{"login":"zackteo","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/7510179?v=4"},"updated-at":1620302811324,"created-at":1620302811324,"body":"Perhaps this will be of help someone trying to find the regions denoted by partitions\n```\n(defn partition-at\n \"Like partition-by but will start a new run when f returns true\"\n [f coll]\n (lazy-seq\n (when-let [s (seq coll)]\n (let [run (cons (first s) (take-while #(not (f %)) (rest s)))]\n (cons run (partition-at f (drop (count run) s)))))))\n```\n(taken from: http://cninja.blogspot.com/2011/02/clojure-partition-at.html#comments)","_id":"6093dbdbe4b0b1e3652d74f4"}],"arglists":["f","f coll"],"doc":"Applies f to each value in coll, splitting it each time f returns a\n new value. Returns a lazy seq of partitions. Returns a stateful\n transducer when no collection is provided.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/partition-by"},{"added":"1.2","ns":"clojure.core","name":"numerator","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1314000040000,"author":{"login":"shockbob","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"denominator","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c62"}],"line":3608,"examples":[{"updated-at":1596571068249,"created-at":1313999955000,"body":";; note that the function always returns the numerator of the reduced fraction\n\n(numerator (/ 2 3))\n;;=> 2\n\nuser=> (map numerator [(/ 2 4) (/ 4 6) (/ 6 8)])\n(1 2 3)\n","editors":[{"login":"wdhowe","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/4631165?v=4"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon","account-source":"clojuredocs","login":"shockbob"},"_id":"542692cbc026201cdc326be1"}],"notes":null,"tag":"java.math.BigInteger","arglists":["r"],"doc":"Returns the numerator part of a Ratio.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/numerator"},{"added":"1.2","ns":"clojure.core","name":"object-array","file":"clojure/core.clj","type":"function","column":1,"see-alsos":null,"line":5378,"examples":[{"author":{"login":"shockbob","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon"},"editors":[],"body":";; create an array of Java Objects using object-array\n;; and demonstrate that it can be used with the Java fill function\n\nuser=> (def os (object-array [nil 23.2 \"abc\" 33]))\n#'user/os\nuser=> (vec os)\n[nil 23.2 \"abc\" 33]\nuser=> (java.util.Arrays/fill os 31415)\nnil\nuser=> (vec os)\n[31415 31415 31415 31415]\nuser=>","created-at":1313961890000,"updated-at":1313961890000,"_id":"542692c6c026201cdc3268d2"}],"notes":null,"arglists":["size-or-seq"],"doc":"Creates an array of objects","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/object-array"},{"added":"1.0","ns":"clojure.core","name":"with-out-str","file":"clojure/core.clj","type":"macro","column":1,"see-alsos":[{"created-at":1398723561000,"author":{"login":"ryo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3f7913b563c72083c74030d928ba407e?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"with-in-str","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e63"}],"line":4765,"examples":[{"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"avatar-url":"https://avatars.githubusercontent.com/u/4142015?v=3","account-source":"github","login":"bkovitz"}],"body":";; Instead of printing, the following will place the output normally\n;; sent to stdout into a string.\n\nuser=> (with-out-str (println \"this should return as a string\"))\n\"this should return as a string\\n\"\n","created-at":1280928491000,"updated-at":1461945233822,"_id":"542692c8c026201cdc326a43"},{"editors":[{"login":"viebel","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/955710?v=3"},{"login":"bkovitz","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/4142015?v=3"}],"body":";; `time` prints the elapsed time. `with-out-str` can put it into a variable.\n\n(def elapsed\n (with-out-str\n (time (last (range 10000)))))\n\nelapsed\n;=> \"\\\"Elapsed time: 49.363055 msecs\\\"\\n\"\n","author":{"avatar-url":"https://avatars.githubusercontent.com/u/955710?v=3","account-source":"github","login":"viebel"},"created-at":1458892903287,"updated-at":1461945165867,"_id":"56f4f067e4b07ac9eeceed16"},{"updated-at":1493591261548,"created-at":1493591261548,"author":{"login":"ertugrulcetin","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/8271291?v=3"},"body":"(defmacro with-out-str-data-map\n [& body]\n `(let [s# (new java.io.StringWriter)]\n (binding [*out* s#]\n (let [r# ~@body]\n {:result r#\n :str (str s#)}))))\n\n(with-out-str-data-map (do\n (println \"Clojure is the best!\")\n 2))\n\n;;=> {:str \"Clojure is the best!\\n\", :result 2}","_id":"590664dde4b01f4add58fe9f"},{"updated-at":1504610437254,"created-at":1504610437254,"author":{"login":"yogsototh","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/93899?v=4"},"body":"(defn pp-str [x]\n (with-out-str (clojure.pprint/pprint x))\n\n\n(pp-str {:foo \"foo\" :bar \"bar\"})\n;;=> \"{:foo \\\"foo\\\", :bar \\\"bar\\\"}\\n\"\n","_id":"59ae8885e4b09f63b945ac5f"}],"macro":true,"notes":null,"arglists":["& body"],"doc":"Evaluates exprs in a context in which *out* is bound to a fresh\n StringWriter. Returns the string created by any nested printing\n calls.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/with-out-str"},{"added":"1.0","ns":"clojure.core","name":"condp","file":"clojure/core.clj","type":"macro","column":1,"see-alsos":[{"created-at":1289183336000,"author":{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},"to-var":{"ns":"clojure.core","name":"cond","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b46"},{"created-at":1334294023000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.core","name":"if","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b47"},{"created-at":1470961020992,"author":{"login":"cloojure","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7083783?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"case","ns":"clojure.core"},"_id":"57ad157ce4b0bafd3e2a04e5"}],"line":6430,"examples":[{"author":{"login":"jneira","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2c8ecc24181d171df85a26458b9cd5f?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"},{"login":"kimtg","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7685905?v=3"}],"body":";; Taken from the excellent clojure tutorial:\n;; http://java.ociweb.com/mark/clojure/article.html\n\n(print \"Enter a number: \")\n(flush) ; stays in a buffer otherwise\n(let [line (read-line)\n value (try\n (Integer/parseInt line)\n (catch NumberFormatException e line))] ; use string val if not int\n (println\n (condp = value\n 1 \"one\"\n 2 \"two\"\n 3 \"three\"\n (str \"unexpected value, \\\"\" value \\\")))\n (println\n (condp instance? value\n Number (* value 2)\n String (* (count value) 2))))\n","created-at":1278989834000,"updated-at":1425998195013,"_id":"542692cbc026201cdc326be2"},{"updated-at":1494204573950,"created-at":1279027225000,"body":";; (some #{4 5 9} [1 2 3 4]) \n;; is the first matching clause, \n;; the match value is 4 which is decremented\n(condp some [1 2 3 4]\n #{0 6 7} :>> inc\n #{4 5 9} :>> dec\n #{1 2 3} :>> #(+ % 3))\n;;=> 3","editors":[{"avatar-url":"https://www.gravatar.com/avatar/5db30f607f0b5fa70d690311aa3bfd3b?r=PG&default=identicon","account-source":"clojuredocs","login":"kotarak"},{"avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3","account-source":"github","login":"jafingerhut"},{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3","account-source":"github","login":"phreed"},{"login":"adamdavislee","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/8780347?v=3"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/5db30f607f0b5fa70d690311aa3bfd3b?r=PG&default=identicon","account-source":"clojuredocs","login":"kotarak"},"_id":"542692cbc026201cdc326be4"},{"author":{"login":"kotarak","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5db30f607f0b5fa70d690311aa3bfd3b?r=PG&default=identicon"},"editors":[{"login":"kotarak","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5db30f607f0b5fa70d690311aa3bfd3b?r=PG&default=identicon"},{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":";; in this case there is no matching clause\n;; so an exception is raised.\n(condp some [1 2 3 4]\n #{0 6 7} :>> inc\n #{5 9} :>> dec)\n\n;; java.lang.IllegalArgumentException: No matching clause: [1 2 3 4]","created-at":1279027251000,"updated-at":1421191702604,"_id":"542692cbc026201cdc326be7"},{"author":{"login":"kotarak","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5db30f607f0b5fa70d690311aa3bfd3b?r=PG&default=identicon"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":";; a composite predicate which parses a string with \"re-seq\" \n;; producing a list which is made into a \"seq\".\n(condp (comp seq re-seq) \"foo=bar\"\n #\"[+](\\w+)\" :>> #(vector (-> % first (nth 1) keyword) true)\n #\"[-](\\w+)\" :>> #(vector (-> % first (nth 1) keyword) false)\n #\"(\\w+)=(\\S+)\" :>> #(let [x (first %)]\n [(keyword (nth x 1)) (nth x 2)]))\n;;=> [:foo \"bar\"]","created-at":1279027512000,"updated-at":1421192246892,"_id":"542692cbc026201cdc326bea"},{"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"editors":[],"body":";; See examples for \"if\" explaining Clojure's idea of logical true\n;; and logical false.","created-at":1334294027000,"updated-at":1334294027000,"_id":"542692d2c026201cdc326f69"},{"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"editors":[],"body":";;this is with liberator\n;;branching on request method\n(defresource my-resource\n :exists? (fn [{:keys [db] {query-params :query-params \n body :body \n method :request-method} \n :request}]\n \n (condp = method\n :get (my-get-exists-fn)\n :post (my-post-exists-fn))))","created-at":1367366404000,"updated-at":1367366404000,"_id":"542692d2c026201cdc326f6a"},{"author":{"login":"leesper","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/f150e0f851c74d1b9c001b901b29a287?r=PG&default=identicon"},"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":";; a recursive function to calculate length\n;; same as 'count'\n(defn length [lst]\n (condp = lst\n (list) 0 ; if empty list result 0\n (+ 1 (length (rest lst))))) ; default expression\n\n(length '(1 2 3))\n;;=> 3","created-at":1375971960000,"updated-at":1421192464881,"_id":"542692d2c026201cdc326f6b"},{"updated-at":1598097023549,"created-at":1402793361000,"body":";; test arguments against various binary predicates\n(condp apply [2 3]\n = \"eq\"\n < \"lt\"\n > \"gt\")\n;;=> \"lt\"\n\n;; test argument against various unary predicates\n(condp apply [:foo]\n string? \"it's a string\"\n keyword? \"it's a keyword\"\n symbol? \"it's a symbol\"\n fn? \"it's a function\"\n \"something else!\")\n;;=> \"it's a keyword\"","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3","account-source":"github","login":"phreed"},{"avatar-url":"https://avatars.githubusercontent.com/u/1195619?v=3","account-source":"github","login":"jeffi"},{"login":"titogarcia","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/699549?v=4"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/f2fad9c9c81cfdf191f10265371f1d72?r=PG&default=identicon","account-source":"clojuredocs","login":"vee"},"_id":"542692d2c026201cdc326f6c"},{"body":"; This function is part of a great solution to the \"fizzbuzz\" interview question.\n; Let's review \n; Players take turns to count incrementally, \n; replacing any number divisible by three with the word \"fizz\", \n; any number divisible by five with the word \"buzz\", and \n; any number divisible by both three and five with the word \"fizzbuzz\".\n(defn fizz-buzz [n]\n (condp #(zero? (mod %2 %1)) n\n 15 \"fizzbuzz\"\n 3 \"fizz\"\n 5 \"buzz\"\n n))\n\n(into [] (map fizz-buzz) (range 1 20))\n;;=> [1 2 \"fizz\" 4 \"buzz\" \"fizz\" 7 8 \"fizz\" \"buzz\" \n;; 11 \"fizz\" 13 14 \"fizzbuzz\" 16 17 \"fizz\" 19]","author":{"login":"dfletcher","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/189317?v=3"},"created-at":1433388096371,"updated-at":1510263672104,"editors":[{"login":"dfletcher","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/189317?v=3"},{"avatar-url":"https://avatars.githubusercontent.com/u/200617?v=3","account-source":"github","login":"bsima"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"}],"_id":"556fc440e4b03e2132e7d185"},{"updated-at":1506692074248,"created-at":1506692074248,"author":{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"},"body":";; Test a string against multiple regexps, and do something different\n;; with the match each time. \n(condp re-matches \"17->42\"\n #\"(\\w+)->(\\w+)\" :>> (fn [[_ p1 p2]]\n {:start p1 :end p2})\n\n #\"(\\w+)->$\" :>> (fn [[_ p1]]\n {:start p1})\n\n #\"\\w+\" :>> (fn [[p]]\n {:fixed p})\n\n nil)\n; => {:start \"17\" :end \"42\"}","_id":"59ce4beae4b03026fe14ea4d"},{"updated-at":1534346599711,"created-at":1534346599711,"author":{"login":"ernstroux","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/20518350?v=4"},"body":";if you are using the function literal already and can't nest\n\n(#(condp (fn [clause expr] (clojure.string/includes? expr clause)) \"transaction-result-kafka\"\n \"transaction-result\" 1\n \"transaction-failure\" 4\n (do\n (str \"got message with nil topic\")\n nil)))\n;=> 1","_id":"5b744567e4b00ac801ed9e5b"},{"editors":[{"login":"berczeck","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/1321842?v=4"}],"body":";; We can use symbols in the test-expression; this isn't possible with 'case'\n(defn id-resolver\n [id]\n (let [id-a \"a\"\n id-b \"b\"\n\t id-c \"c\"]\n (condp = id\n\t id-a {:response-a \"id-a\"}\n\t id-b {:response-b \"id-b\"}\n\t id-c {:response-c \"id-c\"})))\n\n(id-resolver \"a\")\n;; => {:response-a \"id-a\"}","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/1321842?v=4","account-source":"github","login":"berczeck"},"created-at":1598155978713,"updated-at":1598156087855,"_id":"5f41eccae4b0b1e3652d738d"},{"editors":[{"login":"Rovanion","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/632775?v=4"}],"body":";; Want to apply multiple predicates to the same expr? \n;; Not saying you should, but here is how you could.\n\n(def events [{:timestamp \"2021-01-01\" :source nil :destination 1 :litres 1 :price-per-litres 1}\n {:timestamp \"2021-01-02\" :source 1 :destination 2 :litres 0.5 :price-per-litres nil}\n {:timestamp \"2021-01-02\" :source nil :destination 1 :litres 1 :price-per-litres 2}\n {:timestamp \"2021-01-02\" :source 2 :destination nil :litres 0.25 :price-per-litres nil}])\n\n(map (fn [event]\n (condp (fn [preds e] ((apply every-pred preds) e)) event\n [:price-per-litres :destination] :insert\n [:source :destination] :transfer\n [:source (complement :destination)] :withdrawal))\n events)\n;; => (:insert :transfer :insert :withdrawal)\n","author":{"avatar-url":"https://avatars.githubusercontent.com/u/632775?v=4","account-source":"github","login":"Rovanion"},"created-at":1655813285477,"updated-at":1655813318085,"_id":"62b1b4a5e4b0b1e3652d760c"}],"macro":true,"notes":[{"author":{"login":"bsima","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/200617?v=3"},"updated-at":1470339463090,"created-at":1470339463090,"body":"A lot of these examples show the pattern:\n\n```\n(condp = value\n :a \"a\"\n :b \"b\"\n ...)\n```\n\nWhich is the same as:\n\n```\n(case value\n :a \"a\"\n :b \"b\"\n ...)\n```","_id":"57a39987e4b0bafd3e2a04c7"}],"arglists":["pred expr & clauses"],"doc":"Takes a binary predicate, an expression, and a set of clauses.\n Each clause can take the form of either:\n\n test-expr result-expr\n\n test-expr :>> result-fn\n\n Note :>> is an ordinary keyword.\n\n For each clause, (pred test-expr expr) is evaluated. If it returns\n logical true, the clause is a match. If a binary clause matches, the\n result-expr is returned, if a ternary clause matches, its result-fn,\n which must be a unary function, is called with the result of the\n predicate as its argument, the result of that call being the return\n value of condp. A single default expression can follow the clauses,\n and its value will be returned if no clause matches. If no default\n expression is provided and no clause matches, an\n IllegalArgumentException is thrown.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/condp"},{"added":"1.0","ns":"clojure.core","name":"derive","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1308310489000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"parents","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c78"},{"created-at":1308310496000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"ancestors","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c79"},{"created-at":1308310502000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"descendants","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c7a"},{"created-at":1308310508000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"isa?","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c7b"},{"created-at":1332885397000,"author":{"login":"luskwater","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/f3b2650c3d4aa47c9e22bf9ba5596a9f?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"make-hierarchy","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c7c"},{"created-at":1341101591000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"underive","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c7d"}],"line":5679,"examples":[{"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"editors":[],"body":";; derive let you build a hierarchy but parents/ancestors/descendants and isa? let you query the hierarchy\n(derive ::rect ::shape)\n(derive ::square ::rect)\n","created-at":1308310469000,"updated-at":1308310469000,"_id":"542692c7c026201cdc3269d0"},{"author":{"login":"OnesimusUnbound","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2fa4c391db0d2d1744cc2cd0d787dd3d?r=PG&default=identicon"},"editors":[],"body":"user=> (derive ::Cat ::Feline)\nnil\n\nuser=> (derive ::Lion ::Feline)\nnil\n\nuser=> (isa? ::Lion ::Feline)\ntrue\n\nuser=> (isa? ::Tuna ::Feline)\nfalse","created-at":1313009794000,"updated-at":1313009794000,"_id":"542692c7c026201cdc3269d1"},{"updated-at":1503164433228,"created-at":1503164433228,"author":{"login":"mhmdsalem1993","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10787314?v=4"},"body":"(derive java.util.Map ::collection)\n(derive java.util.Collection ::collection)\n\n(isa? java.util.HashMap ::collection)\n-> true","_id":"59987811e4b09f63b945ac51"},{"editors":[{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/94482?v=4"}],"body":";; (derive) can be handy in multimethods that switch on field values:\n\n(def data [{:record/type :types/integer :record/number 123}\n {:record/type :types/float :record/number 123.45}\n {:record/type :types/text :record/text \"hello\"}])\n\n(derive :types/float ::number)\n(derive :types/integer ::number)\n(derive :types/text ::text)\n\n(defmulti record-str :record/type)\n\n(defmethod record-str ::number [r] (str \"Number: \" (:record/number r)))\n(defmethod record-str ::text [r] (str \"Text: \" (:record/text r)))\n\n(map record-str data)\n;; => (\"Number: 123\" \"Number: 123.45\" \"Text: hello\")\n","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/94482?v=4","account-source":"github","login":"timgilbert"},"created-at":1551112001815,"updated-at":1551112172422,"_id":"5c741741e4b0ca44402ef6a3"}],"notes":null,"arglists":["tag parent","h tag parent"],"doc":"Establishes a parent/child relationship between parent and\n tag. Parent must be a namespace-qualified symbol or keyword and\n child can be either a namespace-qualified symbol or keyword or a\n class. h must be a hierarchy obtained from make-hierarchy, if not\n supplied defaults to, and modifies, the global hierarchy.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/derive"},{"added":"1.12","ns":"clojure.core","name":"partitionv-all","file":"clojure/core.clj","type":"function","column":1,"see-alsos":null,"line":7451,"examples":null,"notes":null,"arglists":["n","n coll","n step coll"],"doc":"Returns a lazy sequence of vector partitions, but may include\n partitions with fewer than n items at the end.\n Returns a stateful transducer when no collection is provided.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/partitionv-all"},{"added":"1.0","ns":"clojure.core","name":"load-string","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1334883949000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"read-string","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f04"},{"created-at":1519290621337,"author":{"login":"witek","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/209520?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"load-file","ns":"clojure.core"},"_id":"5a8e88fde4b0316c0f44f8e7"},{"created-at":1519290634633,"author":{"login":"witek","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/209520?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"load","ns":"clojure.core"},"_id":"5a8e890ae4b0316c0f44f8e8"}],"line":4115,"examples":[{"body":"(load-string \"(def x 1)\")\n;; => #'user/x\nx\n;; => 1","author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"created-at":1423012385897,"updated-at":1423012385897,"_id":"54d17221e4b0e2ac61831d00"},{"updated-at":1522768122029,"created-at":1522768122029,"author":{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"},"body":";; Don’t use this function on untrusted input; it can have unpleasant\n;; side-effects.\n(load-string \"(clojure.java.io/delete-file \\\"my-important-file\\\")\")\n;; => true","_id":"5ac398fae4b045c27b7fac35"},{"updated-at":1546454837037,"created-at":1546454837037,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"body":";; Differently from the equivalent \"(eval (read-string x))\", \"load-string\" keeps\n;; track of line numbers:\n\n(def s \"\\n\\n\\n(def c :line4)\")\n(:line (meta (load-string s)))\n;; 4\n(:line (meta (eval (read-string s))))\n;; 1","_id":"5c2d0735e4b0ca44402ef60c"}],"notes":null,"arglists":["s"],"doc":"Sequentially read and evaluate the set of forms contained in the\n string","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/load-string"},{"added":"1.0","ns":"clojure.core","name":"special-symbol?","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":null,"line":5021,"examples":[{"author":{"login":"franks42","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/b3ee701dd6c481e5d310467ddfe62c48?r=PG&default=identicon"},"editors":[{"login":"franks42","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/b3ee701dd6c481e5d310467ddfe62c48?r=PG&default=identicon"}],"body":"user=> (clojure-version)\n\"1.4.0\"\n;; the set of special symbols for this clojure-version are the following:\nuser=> (keys (. clojure.lang.Compiler specials))\n(deftype* new quote & var set! monitor-enter recur . case* clojure.core/import* reify* do fn* throw monitor-exit letfn* finally let* loop* try catch if def)\n\n;; for example, \"def\" is not a function, not a macro, not even a var, but a special form:\nuser=> (fn? 'def)\nfalse\nuser=> (:macro (meta (find-var 'clojure.core/def)))\nnil\nuser=> (find-var 'clojure.core/def)\nnil\nuser=> (special-symbol? 'def)\ntrue\n\n;; while \"defn\" is not a special form but a macro:\nuser=> (special-symbol? 'defn)\nfalse\nuser=> (:macro (meta (find-var 'clojure.core/defn)))\ntrue\n","created-at":1353815386000,"updated-at":1353815535000,"_id":"542692d5c026201cdc327099"}],"notes":null,"arglists":["s"],"doc":"Returns true if s names a special form","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/special-symbol_q"},{"added":"1.0","ns":"clojure.core","name":"ancestors","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1341101490000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"parents","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cd2"},{"created-at":1341101493000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"derive","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cd3"},{"created-at":1341101496000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"underive","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cd4"},{"created-at":1341101502000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"descendants","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cd5"},{"created-at":1341101507000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"make-hierarchy","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cd6"},{"created-at":1341101672000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"isa?","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cd7"},{"created-at":1374150921000,"author":{"login":"alilee","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2fb0196dc5a7cd3a5cc73f1b9941c209?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"supers","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cd8"}],"line":5651,"examples":[{"author":{"login":"shockbob","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon"},"editors":[{"login":"shockbob","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon"}],"body":";; make up a hierarchy a beagle is a sporting breed is a dog is a quadraped is an \n;; animal\n\nuser=> (derive ::quadruped ::animal)\nnil\nuser=> (derive ::dog ::quadruped)\nnil\nuser=> (derive ::sporting_breed ::dog)\nnil\nuser=> (derive ::beagle ::sporting_breed)\nnil\nuser=> (ancestors ::beagle)\n#{:user/dog :user/sporting_breed :user/animal :user/quadruped}\nuser=>","created-at":1313896987000,"updated-at":1313968195000,"_id":"542692cdc026201cdc326d1b"},{"author":{"login":"shockbob","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon"},"editors":[],"body":";; use ancestors to show which classes ArrayList derives from and which\n;; interfaces it implements\n\nuser=> (ancestors java.util.ArrayList)\n#{java.util.Collection java.util.AbstractList java.io.Serializable java.lang.Cloneable java.util.List java.lang.Object java.util.AbstractCollection java.util.RandomAccess java.lang.Iterable}\nuser=>","created-at":1313968946000,"updated-at":1313968946000,"_id":"542692cdc026201cdc326d1d"},{"updated-at":1598158917882,"created-at":1598158880926,"author":{"login":"berczeck","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/1321842?v=4"},"body":";; use ancestors in defrecords to show which defprotocols implements\nuser=> (defprotocol Fly\n (fly [this]))\n\nuser=> (defrecord Bird [name] Fly\n (fly [this] (str (:name this) \" flies....\")))\n\nuser=> (ancestors Bird)\n;; #{clojure.lang.IPersistentCollection \n;; user.Fly \n;; clojure.lang.IHashEq clojure.lang.ILookup \n;; java.util.Map java.lang.Iterable \n;; java.io.Serializable \n;; java.lang.Object \n;; clojure.lang.IMeta \n;; clojure.lang.Seqable \n;; clojure.lang.IRecord \n;; clojure.lang.IObj \n;; clojure.lang.Associative \n;; clojure.lang.Counted \n;; clojure.lang.IKeywordLookup \n;; clojure.lang.IPersistentMap}","editors":[{"avatar-url":"https://avatars1.githubusercontent.com/u/1321842?v=4","account-source":"github","login":"berczeck"}],"_id":"5f41f820e4b0b1e3652d7398"}],"notes":null,"arglists":["tag","h tag"],"doc":"Returns the immediate and indirect parents of tag, either via a Java type\n inheritance relationship or a relationship established via derive. h\n must be a hierarchy obtained from make-hierarchy, if not supplied\n defaults to the global hierarchy","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/ancestors"},{"added":"1.0","ns":"clojure.core","name":"subseq","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1330671591000,"author":{"login":"Chouser","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/7a0192050ed6488670acfd3f59405c10?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"rsubseq","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e25"},{"created-at":1330671627000,"author":{"login":"abrooks","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/69976?v=2"},"to-var":{"ns":"clojure.core","name":"sorted-map","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e26"},{"created-at":1330671638000,"author":{"login":"abrooks","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/69976?v=2"},"to-var":{"ns":"clojure.core","name":"sorted-set","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e27"},{"created-at":1330671646000,"author":{"login":"abrooks","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/69976?v=2"},"to-var":{"ns":"clojure.core","name":"sorted-map-by","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e28"},{"created-at":1330671652000,"author":{"login":"abrooks","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/69976?v=2"},"to-var":{"ns":"clojure.core","name":"sorted-set-by","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e29"},{"created-at":1423278345112,"author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"to-var":{"ns":"clojure.core","name":"subvec","library-url":"https://github.com/clojure/clojure"},"_id":"54d58109e4b0e2ac61831d29"}],"line":5162,"examples":[{"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":";; Note, that collection passed to subseq must implement Sorted. \n;; Just passing a collection that has been sorted is not enough.\n\nuser=> (subseq [1 2 3 4] > 2)\njava.lang.ClassCastException: clojure.lang.PersistentVector cannot be cast to clojure.lang.Sorted (NO_SOURCE_FILE:0)\n\nuser=> (subseq (sorted-set 1 2 3 4) > 2)\n(3 4)\n","created-at":1281618432000,"updated-at":1285494695000,"_id":"542692cfc026201cdc326e78"},{"body":";; Example of getting a subsequence of hashmaps sorted by key :a and\n;; secondarily :b.\n\n(defn compare-ab [x y]\n (compare [(get x :a) (get x :b)]\n [(get y :a) (get y :b)]))\n \n(def ss-ab (apply sorted-set-by compare-ab\n [{:a 42 :b 5000}\n {:a 1 :b 2}\n {:a 99 :b -1000}\n {:a -1 :b 7}]))\nuser=> ss-ab\n#{{:a -1, :b 7} {:a 1, :b 2} {:a 42, :b 5000} {:a 99, :b -1000}}\n\n;; Select all maps whose key :a is greater than 5. \nuser=> (subseq ss-ab > {:a 5})\n({:a 42, :b 5000} {:a 99, :b -1000})\n\n\n","author":{"login":"thirdreplicator","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/90335?v=2"},"created-at":1413610885024,"updated-at":1413610885024,"_id":"5441fd85e4b049fc676849cd"},{"updated-at":1463327979493,"created-at":1463327979493,"author":{"login":"TradeIdeasPhilip","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/18409827?v=3"},"body":";; If you use the 6 input form of this function, start-test should be > or\n;; >= and the end-test should be < or <=. The other forms don't give you\n;; an error, but don't give you what you expect, either. This is all based\n;; on experimentation. I don't see this documented.\n\n;; This suggests that there are no items in my set between 9 and 2.\nuser=> (subseq (sorted-set 1 2 3 4 5 6 7 8 9 0) < 9 > 2)\n;; => ()\n\n;; This correctly lists all items in my set between 2 and 9.\nuser=> (subseq (sorted-set 1 2 3 4 5 6 7 8 9 0) > 2 < 9)\n;; => (3 4 5 6 7 8)\n\n;; Again, this is not just the \"and\" of the two conditions. Lots of items\n;; in my set are #(and (% > 2) (% > 6)) but this returns nothing. \"> 2\"\n;; means skip to the first item that is #(% > 2). So we jump directly to 3.\n;; \"> 6\" means to stop looking as soon as we find an item where #(% > 6) is\n;; false. 3 <= 6, so we get the empty sequence.\nuser=> (subseq (sorted-set 1 2 3 4 5 6 7 8 9 0) > 2 > 6)\n;; => ()\n\n;; This works as expected, returning everything where #(and (% >= 2) (% <= 4)).\n;; That is to say it returns everything between 2 and 4, inclusive.\nuser=> (subseq (sorted-set 1 2 3 4 5 6 7 8 9 0) >= 2 <= 4)\n;; => (2 3 4)\n\n;; Naïvely you might expect this to give you the same results as the previous\n;; statement. Clearly the result is not the same. I'm not sure what's going\n;; on under the hood here. It's jumping directly to 4 as if I'd said \">= 4\"\n;; rather than \"<= 4\". (Looks like a bug in Clojure to me!) Then it\n;; continued to the end because all of the remaining items were #(% >= 2).\nuser=> (subseq (sorted-set 1 2 3 4 5 6 7 8 9 0) <= 4 >= 2)\n;; => (4 5 6 7 8 9)\nuser=> *clojure-version*\n;; => {:major 1, :minor 8, :incremental 0, :qualifier nil}\n\n;; This one at least makes sense. It jumps directly to the first item that\n;; satisfies the first test and continues until the second item is false.\nuser=> (subseq (sorted-set 1 2 3 4 5 6 7 8 9 0) >= 4 >= 2)\n;; => (4 5 6 7 8 9)\n","_id":"57389cebe4b071da7d6cfd0a"},{"updated-at":1522434900617,"created-at":1522434900617,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"body":";; Autocomplete using local Unix dictionary.\n(require '[clojure.string :refer [split]])\n\n(def dict\n (into (sorted-set)\n (split (slurp \"/usr/share/dict/words\") #\"\\s+\")))\n\n;; The vector contains a few simulated keystrokes.\n(map #(take 4 (subseq dict >= %)) [\"c\" \"cl\" \"clo\" \"clos\" \"closu\"])\n;; ((\"c\" \"ca\" \"caam\" \"caama\")\n;; (\"clabber\" \"clabbery\" \"clachan\" \"clack\")\n;; (\"cloaca\" \"cloacal\" \"cloacaline\" \"cloacean\")\n;; (\"closable\" \"close\" \"closecross\" \"closed\")\n;; (\"closure\" \"clot\" \"clotbur\" \"clote\"))","_id":"5abe8354e4b045c27b7fac2a"}],"notes":null,"arglists":["sc test key","sc start-test start-key end-test end-key"],"doc":"sc must be a sorted collection, test(s) one of <, <=, > or\n >=. Returns a seq of those entries with keys ek for\n which (test (.. sc comparator (compare ek key)) 0) is true","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/subseq"},{"added":"1.2","ns":"clojure.core","name":"error-handler","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1443938208744,"author":{"login":"devn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"set-error-handler!","ns":"clojure.core"},"_id":"5610bfa0e4b0686557fcbd54"},{"created-at":1443938218045,"author":{"login":"devn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"agent","ns":"clojure.core"},"_id":"5610bfaae4b08e404b6c1ca5"}],"line":2221,"examples":[{"editors":[{"login":"devn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3"}],"body":"(def error-atom (atom []))\n\n(def a (agent \"\"\n :validator string?\n :error-handler (fn [agnt ex]\n (swap! error-atom\n conj\n {:agent agnt\n :exception (.getMessage ex)}))))\n\n(send a 1) ;; will fail validation\n\n@error-atom\n[{:agent #,\n :exception \"java.lang.Long cannot be cast to clojure.lang.IFn\"}]\n\n(error-handler a)\n#","author":{"avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3","account-source":"github","login":"devn"},"created-at":1443938199376,"updated-at":1443938238017,"_id":"5610bf97e4b0686557fcbd53"}],"notes":null,"arglists":["a"],"doc":"Returns the error-handler of agent a, or nil if there is none.\n See set-error-handler!","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/error-handler"},{"added":"1.0","ns":"clojure.core","name":"gensym","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":null,"line":606,"examples":[{"updated-at":1285495689000,"created-at":1280776789000,"body":"user=> (gensym \"foo\")\nfoo2020\n\nuser=> (gensym \"foo\")\nfoo2027\n\nuser=> (gensym \"foo\")\n;; ...\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3","account-source":"github","login":"devn"},"_id":"542692c6c026201cdc32690b"},{"updated-at":1285495715000,"created-at":1280776909000,"body":"user=> (gensym)\nG__2034\n\nuser=> (let [my-unique-sym (gensym)]\n my-unique-sym)\nG__2075\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3","account-source":"github","login":"devn"},"_id":"542692c6c026201cdc32690d"},{"author":{"login":"gdavis","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/ae253eacd4cab9fb2580b8192351b641?r=PG&default=identicon"},"editors":[],"body":";; syntax-reader uses gensym for non-namespace-qualified symbols ending with '#'\n;; http://clojure.org/reader\n\nuser=> `(name0#) ; gensym, form is useful in defmacro\n(name0__1206__auto__)\n\nuser=> `(user/name1#) ; no gensym, namespace-qualified\n(user/name1#)\n\nuser=> `(:key0#) ; no gensym, keyword\n(:key0#)\n\nuser=> `(::key1#) ; no gensym, keyword\n(:user/key1#)\n","created-at":1394152357000,"updated-at":1394152357000,"_id":"542692d3c026201cdc326fbc"},{"updated-at":1656609206311,"created-at":1656609206311,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":";; syntax-reader gensyms are only generated once, at read time\n;; so recursive macros get the same generated symbol for all levels of recursion\n\n(defmacro reader-gensym-macro [[x & more :as xs] acc]\n (if (seq xs)\n `(let [x# ~x]\n (reader-gensym-macro ~more (conj ~acc x#)))\n acc))\n\n(reader-gensym-macro [1 2] []) ;; => [2 2]\n\n;; using the function `gensym` can overcome this problem\n;; so recursive macros get a different generated symbol for each level of recursion\n\n(defmacro function-gensym-macro [[x & more :as xs] acc]\n (if (seq xs)\n (let [gx (gensym 'x)]\n `(let [~gx ~x]\n (function-gensym-macro ~more (conj ~acc ~gx))))\n acc))\n\n(function-gensym-macro [1 2] []) ;; => [1 2]","_id":"62bdd9b6e4b0b1e3652d760f"}],"notes":[{"updated-at":1383198787000,"body":"The
    (. clojure.lang.RT (nextID))
    present gensym's source code (https://github.com/clojure/clojure/blob/clojure-1.5.1/src/jvm/clojure/lang/RT.java#L468) uses java.util.concurrent.atomic.AtomicInteger (and has for the past 6 years, if you trust the Git history).","created-at":1383198787000,"author":{"login":"mlb","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/11104d872c2bae6e0e98b7533818530a?r=PG&default=identicon"},"_id":"542692edf6e94c697052200c"}],"arglists":["","prefix-string"],"doc":"Returns a new symbol with a unique name. If a prefix string is\n supplied, the name is prefix# where # is some unique number. If\n prefix is not supplied, the prefix is 'G__'.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/gensym"},{"added":"1.0","ns":"clojure.core","name":"cond","file":"clojure/core.clj","type":"macro","column":1,"see-alsos":[{"created-at":1289183323000,"author":{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},"to-var":{"ns":"clojure.core","name":"condp","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ee8"},{"created-at":1290574959000,"author":{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},"to-var":{"ns":"clojure.core","name":"case","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ee9"},{"created-at":1302510857000,"author":{"login":"Havvy","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e799a79441c7543be48562403411cd13?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"if","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521eea"},{"created-at":1459890885195,"author":{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/94482?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"cond->","ns":"clojure.core"},"_id":"57042ac5e4b075f5b2c864ce"}],"line":576,"examples":[{"author":{"login":"dpritchett","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/147981?v=3"},"editors":[{"login":"dpritchett","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/147981?v=3"},{"login":"dpritchett","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/147981?v=3"},{"login":"bhenry","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/4bc423f6653d93f9185a5cdc9f5cd84f?r=PG&default=identicon"},{"login":"dpritchett","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/147981?v=3"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":"(defn pos-neg-or-zero\n \"Determines whether or not n is positive, negative, or zero\"\n [n]\n (cond\n (< n 0) \"negative\"\n (> n 0) \"positive\"\n :else \"zero\"))\n\nuser=> (pos-neg-or-zero 5)\n\"positive\"\nuser=> (pos-neg-or-zero -1)\n\"negative\"\nuser=> (pos-neg-or-zero 0)\n\"zero\"\n","created-at":1279070736000,"updated-at":1285501471000,"_id":"542692c7c026201cdc326966"},{"author":{"login":"bhenry","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/4bc423f6653d93f9185a5cdc9f5cd84f?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"TheJoe","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2789ff7d993fbf621e86768b3cce19d4?r=PG&default=identicon"}],"body":"user=> (let [grade 85]\n (cond\n (>= grade 90) \"A\"\n (>= grade 80) \"B\"\n (>= grade 70) \"C\"\n (>= grade 60) \"D\"\n :else \"F\"))\n\"B\"","created-at":1279071870000,"updated-at":1365525514000,"_id":"542692c7c026201cdc32696c"},{"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"editors":[],"body":";; See examples for \"if\" explaining Clojure's idea of logical true\n;; and logical false.","created-at":1334293315000,"updated-at":1334293315000,"_id":"542692d2c026201cdc326f67"},{"author":{"login":"Omer","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/dae0f434afde5246ccb030cdec81fb71?r=PG&default=identicon"},"editors":[],"body":";; Generates a random number compares it to user input\n(let [rnd (rand-int 10)\n guess (Integer/parseInt (read-line))]\n (cond\n (= rnd guess) (println \"You got my guess right!\")\n :else (println \"Sorry... guess again!\")))","created-at":1338273335000,"updated-at":1338273335000,"_id":"542692d2c026201cdc326f68"},{"updated-at":1459931468351,"created-at":1459931468351,"author":{"login":"mhmdsalem1993","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10787314?v=3"},"body":";; Simple Condition Example \n\n(defn test-x [x]\n\t(cond\n\t\t(< x 10) \"less than\"\n\t\t(> x 20) \"greater than\"\n\t)\n)\n\n============test============\n(test-x 9)\n\n=> \"less than\"","_id":"5704c94ce4b0fc95a97eab2c"},{"updated-at":1502632735612,"created-at":1502632735612,"author":{"login":"RobinNagpal","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/745748?v=4"},"body":"(defn print-cond [xx] \n (cond \n (< xx 6) \"less than 6\"\n (< xx 8) \"less than 8\"\n :else \"Greater than 8\"))\n=> #'aurora.system/print-cond\n(print-cond 5)\n=> \"less than 6\"\n(print-cond 7)\n=> \"less than 8\"\n(print-cond 8)\n=> \"Greater than 8\"\n(print-cond 10)\n=> \"Greater than 8\"\n","_id":"59905b1fe4b0d19c2ce9d716"},{"updated-at":1504194292107,"created-at":1504194292107,"author":{"login":"chrismurrph","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/10278575?v=4"},"body":";; If a condition is not matched `nil` will be returned\n(cond\n false \"sumfin\")\n;;=> nil","_id":"59a82ef4e4b09f63b945ac5b"},{"updated-at":1598227713206,"created-at":1598227713206,"author":{"login":"berczeck","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/1321842?v=4"},"body":";; Instead of use the :else keyword as the default path you can use \n;; whatever that gives meaning to the code\n\nuser=> (cond \n :whatever \"You can use any default keyword\")\n;; You can use any default keyword","_id":"5f430501e4b0b1e3652d73a9"},{"updated-at":1613750506091,"created-at":1613750506091,"author":{"login":"digash","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/30662?v=4"},"body":";; cond is a macro the easiest way to understand how it works is to macroexpand it\nuser=> (clojure.walk/macroexpand-all\n '(let [n 3] \n (cond\n (odd? n) \"odd\"\n (even? n) \"even\"\n (< n 0) \"negitive\"\n (< 0 n) \"positive\"\n :else \"zero\")))\n\n(let [n 3]\n (if (odd? n)\n \"odd\"\n (if (even? n)\n \"even\"\n (if (< n 0)\n \"negitive\"\n (if (< 0 n)\n \"positive\"\n (if :else\n \"zero\"\n nil))))))","_id":"602fe0eae4b0b1e3652d745e"}],"macro":true,"notes":[{"updated-at":1288294778000,"body":"We should add a comment in the docstring for the final usage of :else.","created-at":1288294778000,"author":{"login":"blais","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9142fc3ffa18ebeddbb03fe575199742?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fa0"},{"author":{"login":"kimtg","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7685905?v=3"},"updated-at":1441172051574,"created-at":1441172051574,"body":"`:else` is not special. Any keyword will do.","_id":"55e68a53e4b072d7f27980f9"},{"author":{"login":"seltzer1717","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1911117?v=3"},"updated-at":1445308247668,"created-at":1445308247668,"body":"Actually any non-nil or true will work. I prefer to use :default. :else implies truthiness in evaluation rather what it really is which is a 'default' value.","_id":"5625a757e4b04b157a6648d7"},{"author":{"login":"yubrshen","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/2638417?v=3"},"updated-at":1494713707387,"created-at":1494713707387,"body":"It seems the documentation is not accurate. From my experiment, it seems the function decscription should be like the following:\n\nTakes a set of test/expr pairs. It evaluates each test one at a time. \nIf a test returns logical true, cond evaluates the corresponding expr and\ncontinue to evaluate the next test/expr, until a test fails or \nno more pair of test(:else)/expr to evaluate,\nand returns the last evaluation value of the expr \nthat its corresponding test evaluated to truthy.\nIf there is no test evaluated to truthy, \nreturn the evaluation of :else clause.\nIf there is no :else clause return nil.\n\nThe above description can be supported by the following example:\n\n
    \n(defn pos-neg-or-zero\n  \"Determines whether or not n is positive, negative, or zero\"\n  [n]\n  (cond\n    (odd? n) \"odd\"\n    (even? n) \"even\"\n    (< n 0) \"negitive\"\n    (< 0 n) \"positive\"\n    :else \"zero\"))\n\n(odd? 3)                                ; => true\n(pos-neg-or-zero 3)                     ;=> \"positive\"\n(even? 0)                               ; => true\n(pos-neg-or-zero 0)                     ;=> \"zero\"\n(even? 4)                               ; => true\n(pos-neg-or-zero 4)                     ;=> \"positive\"\n\n","_id":"5917856be4b01920063ee05d"},{"author":{"login":"maruks","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/433989?v=3"},"updated-at":1499359558730,"created-at":1499359558730,"body":"yubrshen,   \n\n(pos-neg-or-zero 3) => \"odd\"","_id":"595e6946e4b06e730307db4f"},{"author":{"login":"dan-mcdonald","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/8184051?v=4"},"updated-at":1592425332445,"created-at":1592425332445,"body":"`:else` is just a convention. It works because\n\n
    \n=> (boolean :else)\ntrue\n
    \n\nIn fact anything except for `false` and `nil` will evaluate to `true` (see [boolean](https://clojuredocs.org/clojure.core/boolean)).","_id":"5eea7b74e4b0b1e3652d7306"}],"arglists":["& clauses"],"doc":"Takes a set of test/expr pairs. It evaluates each test one at a\n time. If a test returns logical true, cond evaluates and returns\n the value of the corresponding expr and doesn't evaluate any of the\n other tests or exprs. (cond) returns nil.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/cond"},{"added":"1.0","ns":"clojure.core","name":"ratio?","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1691574043389,"author":{"login":"ferdinand-beyer","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/23474334?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"rational?","ns":"clojure.core"},"_id":"64d35f1be4b08cf8563f4bd9"},{"created-at":1691574076933,"author":{"login":"ferdinand-beyer","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/23474334?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"denominator","ns":"clojure.core"},"_id":"64d35f3ce4b08cf8563f4bda"},{"created-at":1691574083991,"author":{"login":"ferdinand-beyer","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/23474334?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"numerator","ns":"clojure.core"},"_id":"64d35f43e4b08cf8563f4bdb"}],"line":3602,"examples":[{"author":{"login":"dpritchett","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/147981?v=3"},"editors":[{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"}],"body":"(ratio? 22/7)\n;; => true\n\n(ratio? 22)\n;; => false\n\n(ratio? 2.2)\n;; => false\n","created-at":1279074828000,"updated-at":1423040912016,"_id":"542692c9c026201cdc326a96"},{"updated-at":1463237750174,"created-at":1463237750174,"author":{"login":"TradeIdeasPhilip","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/18409827?v=3"},"body":";; Both True\nuser=> (ratio? 22/7) \n;; => true\nuser=> (rational? 22/7)\n;; => true\n\n;; Different\nuser=> (ratio? 22)\n;; => false\nuser=> (rational? 22)\n;; => true\n\n;; Both False\nuser=> (ratio? 0.5)\n;; => false\nuser=> (rational? 0.5)\n;; => false","_id":"57373c76e4b05449374f52ee"}],"notes":null,"arglists":["n"],"doc":"Returns true if n is a Ratio","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/ratio_q"},{"added":"1.0","ns":"clojure.core","name":"delay?","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1325375628000,"author":{"login":"moumar","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8fae5b9c9ffd332a24ff71a339fa6310?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"delay","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ca7"}],"line":757,"examples":[{"author":{"login":"yasuto","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cacfb7ecf08cb6461767e514c93b7bf9?r=PG&default=identicon"},"editors":[{"login":"yasuto","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cacfb7ecf08cb6461767e514c93b7bf9?r=PG&default=identicon"}],"body":"user=> (def v (delay (do (println \"start sleeping\") \n (Thread/sleep 1000) \n 10)))\n#'user/v\nuser=> (delay? v)\ntrue\nuser=> (force v)\nstart sleeping\n10\nuser=> (delay? v)\ntrue\nuser=> (force v)\n10\nuser=> ","created-at":1308628940000,"updated-at":1308629066000,"_id":"542692cec026201cdc326dc1"}],"notes":null,"arglists":["x"],"doc":"returns true if x is a Delay created with delay","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/delay_q"},{"added":"1.0","ns":"clojure.core","name":"intern","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1360641943000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"alter-var-root","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b72"},{"created-at":1484214992310,"author":{"login":"rauhs","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/11081351?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"ns-unmap","ns":"clojure.core"},"_id":"587752d0e4b09108c8545a56"},{"created-at":1649576842844,"author":{"login":"jungwookim","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/50188177?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"create-ns","ns":"clojure.core"},"_id":"62528b8ae4b0b1e3652d75cf"}],"line":6388,"examples":[{"author":{"login":"Miles","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bbb26d2a5e856c4fba0f72c3f7250f3f?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"Miles","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bbb26d2a5e856c4fba0f72c3f7250f3f?r=PG&default=identicon"}],"body":"user=> (intern 'user 'x \"Foobar\")\n#'user/x\n\nuser=> x\n\"Foobar\"\n","created-at":1283820694000,"updated-at":1287791800000,"_id":"542692cac026201cdc326b56"},{"updated-at":1649576567141,"created-at":1649576567141,"author":{"login":"jungwookim","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/50188177?v=4"},"body":";; being able to define fn as a val\nuser=> (intern 'user 'sum (fn [a b c]\n (+ a b c)))\n#'user/sum\n\nuser=> (sum 1 2 3)\n6","_id":"62528a77e4b0b1e3652d75ce"},{"updated-at":1649578114784,"created-at":1649577871265,"author":{"login":"jungwookim","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/50188177?v=4"},"body":";; you can defind defmethod as well by using intern.\n;; firstly, define defmulti so that upper-case can convert string and keyword into upper-case, respectively.\nuser=> (defmulti upper-case [this]\n (type this))\n\n;; defmethods can be created as a var by clojure.core/intern\nuser=> (intern 'user 'upper-case (defmethod upper-case java.lang.String [this]\n (clojure.string/upper-case this)))\n\nuser=> (intern 'user 'upper-case (defmethod upper-case clojure.lang.Keyword [this]\n (-> this name clojure.string/upper-case keyword)))\n\nuser=> (upper-case \"abc\")\n\"ABC\"\n\nuser=> (upper-case :abc)\n:ABC","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/50188177?v=4","account-source":"github","login":"jungwookim"}],"_id":"62528f8fe4b0b1e3652d75d0"},{"updated-at":1701598683066,"created-at":1701598683066,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":";; `intern` can be used to allow defining in other namespaces…\nuser> (create-ns 'other-ns)\n#namespace[other-ns]\n\nuser> (intern 'other-ns 'foo 42)\n#'other-ns/foo\n\nuser> (inc other-ns/foo)\n43","_id":"656c55db69fbcc0c2261746a"}],"notes":[{"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/211644?v=3"},"updated-at":1490886217995,"created-at":1490886217995,"body":"\"The Namespace system maintains global maps of symbols to Var objects (see Namespaces). If a def expression does not find an interned entry in the current namespace for the symbol being def-ed, it creates one, otherwise it uses the existing Var. This find-or-create process is called interning. This means that, unless they have been unmap-ed, Var objects are stable references and need not be looked up every time. It also means that namespaces constitute a global environment in which, as described in Evaluation, the compiler attempts to resolve all free symbols as Vars.\n\n\"The var special form or the #' reader macro (see Reader) can be used to get an interned Var object instead of its current value.\"\n\n-- [https://clojure.org/reference/vars]","_id":"58dd1e49e4b01f4add58fe81"}],"arglists":["ns name","ns name val"],"doc":"Finds or creates a var named by the symbol name in the namespace\n ns (which can be a symbol or a namespace), setting its root binding\n to val if supplied. The namespace must exist. The var will adopt any\n metadata from the name symbol. Returns the var.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/intern"},{"ns":"clojure.core","name":"print-simple","file":"clojure/core_print.clj","type":"function","column":1,"see-alsos":null,"line":83,"examples":[{"updated-at":1656622812157,"created-at":1656622812157,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":";; where o is an object to be printed, and w is a java.io.Writer\n;; prints metadata if *print-dup* or *print-meta* & *print-readably* are truthy\n;; stringifies and writes the object to the writer\n\n;; We can bind *out* to a writer and return that\n(let [s (java.io.StringWriter.)]\n (binding [*out* s]\n (print \"Hello!\")\n (str s)))\n;; => \"Hello!\"\n\n;; Or we can use print-simple with no binding necessary\n(let [s (java.io.StringWriter.)]\n (print-simple \"Hello!\" s)\n (str s))\n;; => \"Hello!\"\n","_id":"62be0edce4b0b1e3652d7610"}],"notes":null,"arglists":["o w"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core/print-simple"},{"added":"1.2","ns":"clojure.core","name":"flatten","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1489089374653,"author":{"login":"miner","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/25400?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"flatten","ns":"clojure.core.reducers"},"_id":"58c1b35ee4b01f4add58fe74"},{"created-at":1519124274538,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"tree-seq","ns":"clojure.core"},"_id":"5a8bff32e4b0316c0f44f8d6"},{"created-at":1550854184577,"author":{"login":"finalfantasia","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/2316604?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"sequential?","ns":"clojure.core"},"_id":"5c702828e4b0ca44402ef69f"},{"created-at":1580338242571,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"mapcat","ns":"clojure.core"},"_id":"5e320c42e4b0ca44402ef826"}],"line":7284,"examples":[{"author":{"login":"dakrone","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bcacd00a7f05c4772329cf9f446c7987?r=PG&default=identicon"},"editors":[{"login":"pkolloch","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/10b2fd3c0a4cc46dc241a48468dc551?r=PG&default=identicon"},{"login":"tonsky","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/4188c62c28a196e3e82363217c56fca5?r=PG&default=identicon"}],"body":"user=> (flatten [1 [2 3]])\n(1 2 3)\n\nuser=> (flatten '(1 2 3))\n(1 2 3)\n\nuser=> (flatten '(1 2 [3 (4 5)])) \n(1 2 3 4 5)\n\nuser=> (flatten nil)\n()\n\n; Attention with stuff which is not a sequence\n\nuser=> (flatten 5)\n()\n\nuser=> (flatten {:name \"Hubert\" :age 23})\n()\n\n; Workaround for maps\n\nuser=> (flatten (seq {:name \"Hubert\" :age 23}))\n(:name \"Hubert\" :age 23)","created-at":1279274687000,"updated-at":1341327489000,"_id":"542692cfc026201cdc326e49"},{"editors":[{"login":"bsima","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/200617?v=3"}],"body":";; Useful snippet: \"merge\" two or more vectors with `(comp vec flatten vector)`\n(let [a [{:a \"hi\"} {:b \"hey\"}]\n b [{:c \"yo\"} {:d \"hiya\"}]\n c {:e [\"hola\" \"bonjour\"]}]\n ((comp vec flatten vector) a b c))\n;;=> [{:a \"hi\"} {:b \"hey\"} {:c \"yo\"} {:d \"hiya\"} {:e [\"hola\" \"bonjour\"]}]","author":{"avatar-url":"https://avatars.githubusercontent.com/u/200617?v=3","account-source":"github","login":"bsima"},"created-at":1453767790696,"updated-at":1453767826738,"_id":"56a6bc6ee4b015010896bd6e"}],"notes":[{"updated-at":1335141716000,"body":"(flatten nil) actually returns an empty sequence, not nil. The doc string is fixed in 1.4.","created-at":1335141716000,"author":{"login":"steveminer","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d28543d134185d12d4006a74738d233e?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fde"},{"updated-at":1336946114000,"body":"As shown in the example, flatten will return an empty sequence when given any non-sequential thing. That can sometimes hide a bug. \r\n\r\nHere's another version that doesn't have that problem, and is faster as well.\r\n\r\n\r\n (defn flatten2\r\n \"Like `clojure.core/flatten` but better, stronger, faster.\r\n Takes any nested combination of sequential things (lists, vectors,\r\n etc.) and returns their contents as a single, flat, lazy sequence.\r\n If the argument is non-sequential (numbers, maps, strings, nil, \r\n etc.), returns the original argument.\"\r\n {:static true}\r\n [x]\r\n (letfn [(flat [coll] \r\n (lazy-seq \r\n (when-let [c (seq coll)] \r\n (let [x (first c)] \r\n (if (sequential? x) \r\n (concat (flat x) (flat (rest c))) \r\n (cons x (flat (rest c))))))))]\r\n (if (sequential? x) (flat x) x)))\r\n","created-at":1335142077000,"author":{"login":"steveminer","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d28543d134185d12d4006a74738d233e?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fdf"},{"updated-at":1341327474000,"body":"Actually, flatten on a vector returns list, not a collection:\r\n\r\n user=> (flatten [1 [2 3]])\r\n (1 2 3)\r\n","created-at":1341327474000,"author":{"login":"tonsky","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/4188c62c28a196e3e82363217c56fca5?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fe4"},{"updated-at":1398620003000,"body":"lazy version is much slower than this one:\r\n\r\n
    (defn my-flatten [l] \r\n  \"free of StackOverflow problem, not lazy and much faster version of flatten.\"\r\n(loop [l1 l, l2 `()]\r\n  (cond\r\n    (sequential? (first l1)) (recur (concat (first l1) (rest l1)) l2)\r\n    (empty? l1) (reverse l2)\r\n    :else (recur (rest l1) (cons (first l1) l2)))))\r\n
    \r\n\r\nfor complicated construction genereted by:\r\n
    (defn gen-list-wird [c] (reduce (fn [a b] (list a b)) (map vector (range c) (map str (range c (* 2 c))))))
    \r\ntimes are:\r\ncore/flatten (260 msec)\r\nsteveminer/flatten (135 msec)\r\nmy-flatten (2 msec). This version is slower than steveminder`s version for flat and very nested structures with small number of items.","created-at":1398617756000,"author":{"login":"slovic","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/b39b58f117a52d4f8ef3f388afb4554a?r=PG&default=identicon"},"_id":"542692edf6e94c6970522025"},{"author":{"login":"miner","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/25400?v=3"},"updated-at":1442172372482,"created-at":1442172372482,"body":"For a much faster implementation, use `clojure.core.reducers/flatten` (introduced in Clojure 1.5).","_id":"55f5cdd4e4b06a9ffaad4fc0"},{"author":{"login":"afhammad","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/147120?v=3"},"updated-at":1459255941235,"created-at":1459255941235,"body":"To only flatten one level, you can use (mapcat identity coll)\n\nWith flatten:\n
    \nuser=> (flatten [[[1]] [[2 3]]])\n(1 2 3)\n
    \n\nWith mapcat identity:\n
    \nuser=> (mapcat identity [[[1]] [[2 3]]])\n([1] [2 3])\n
    \n","_id":"56fa7a85e4b09295d75dbf43"},{"body":"afhammad, i think to flatten one level it may be useful
    (apply concat coll)
    ","created-at":1470329093649,"updated-at":1470329117379,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/834990?v=3","account-source":"github","login":"moskvo"},"_id":"57a37105e4b0bafd3e2a04c6"},{"author":{"login":"beluchin","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/6383047?v=4"},"updated-at":1613909662567,"created-at":1613909662567,"body":"does not flatten sets:\n\n user=> (flatten [#{1}])\n (#{1})","_id":"60324e9ee4b0b1e3652d7460"}],"arglists":["x"],"doc":"Takes any nested combination of sequential things (lists, vectors,\n etc.) and returns their contents as a single, flat lazy sequence.\n (flatten nil) returns an empty sequence.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/flatten"},{"added":"1.0","ns":"clojure.core","name":"doubles","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1656679496626,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"double-array","ns":"clojure.core"},"_id":"62beec48e4b0b1e3652d761b"}],"line":5431,"examples":[{"updated-at":1656673535693,"created-at":1656673535693,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":";; double-array will convert where possible\n(double-array [1 2 3]);; => [1.0, 2.0, 3.0]\n\n;; doubles will not\n(try (doubles [1 2 3])\n (catch ClassCastException e (ex-message e)))\n;; => \"clojure.lang.PersistentVector cannot be cast to [D\"","_id":"62bed4ffe4b0b1e3652d7616"},{"updated-at":1682271447230,"created-at":1682271447230,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":";; Casting avoids expensive reflection, so to see the benefit, enable warning:\n(set! *warn-on-reflection* true)\n\n;; We'll def a double-array but won't type-hint the var:\n(def my-array (double-array [10.0 20.0 30.0 40.0 50.0 60.0]))\n\n;; and try to amap over it without using `doubles` or type hinting amap's args:\n(amap my-array i _ (unchecked-inc ^double (aget my-array i)))\n;; Reflection warning… call to static method alength on clojure.lang.RT can't be resolved (argument types: unknown).\n;; Reflection warning… call to static method aclone on clojure.lang.RT can't be resolved (argument types: unknown).\n;; Reflection warning… call to static method aget on clojure.lang.RT can't be resolved (argument types: unknown, int).\n;; Reflection warning… call to static method aset on clojure.lang.RT can't be resolved (argument types: unknown, int, double).\n;; => [11.0, 21.0, 31.0, 41.0, 51.0, 61.0]\n\n;; We can use `doubles` to avoid reflection:\n(amap (doubles my-array) i _ (unchecked-inc ^double (aget (doubles my-array) i)))\n;; => [11.0, 21.0, 31.0, 41.0, 51.0, 61.0]\n\n;; Just as we can type hint in place:\n(amap ^doubles my-array i _ (unchecked-inc ^double (aget ^doubles my-array i)))\n;; => [11.0, 21.0, 31.0, 41.0, 51.0, 61.0]\n\n;; Or type hint the var:\n(def ^\"[D\" my-array (double-array [10 20 30 40 50 60]))\n(amap my-array i _ (unchecked-inc ^double (aget my-array i)))\n;; => [11.0, 21.0, 31.0, 41.0, 51.0, 61.0]\n","_id":"64456cd7e4b08cf8563f4b92"}],"notes":[{"updated-at":1313877730000,"body":"Anybody know what this is used for?\r\nAll I could find is that you can cast an existing double-array to another \r\ndouble-array???\r\n\r\n
    user=> (doubles [1 2 3 4 5])\r\njava.lang.ClassCastException: clojure.lang.PersistentVector cannot be cast to [D (NO_SOURCE_FILE:0)\r\nuser=> (doubles (int-array [2 3 2]))\r\njava.lang.ClassCastException: [I cannot be cast to [D (NO_SOURCE_FILE:0)\r\nuser=> (doubles (float-array [2 3 2]))\r\njava.lang.ClassCastException: [F cannot be cast to [D (NO_SOURCE_FILE:0)\r\nuser=> (doubles (double-array [2 3 2]))\r\n#\r\nuser=> (type (double-array [2 3 2]))\r\n[D\r\nuser=> (type (doubles (double-array [2 3 2])))\r\n[D\r\nuser=>\r\n
    \r\n","created-at":1313877675000,"author":{"login":"shockbob","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fc6"}],"arglists":["xs"],"doc":"Casts to double[]","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/doubles"},{"added":"1.9","ns":"clojure.core","name":"halt-when","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1658332219541,"author":{"login":"crimeminister","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/29072?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"transduce","ns":"clojure.core"},"_id":"62d8243be4b0b1e3652d762a"}],"line":7823,"examples":[{"updated-at":1520773717746,"created-at":1520773717746,"author":{"login":"glts","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/1483271?v=4"},"body":"(def letters (set \"abcdefghijklmnopqrstuvwxyz\"))\n(def vowels (set \"aeiou\"))\n\n;; Remove the vowels from a string.\n(transduce (remove vowels) str \"hello\")\n;;=> \"hll\"\n\n;; Same, but halt when seeing a non-letter (and return that non-letter).\n(transduce (comp (remove vowels) (halt-when (complement letters)))\n str \"hello\")\n;;=> \"hll\"\n(transduce (comp (remove vowels) (halt-when (complement letters)))\n str \"hello world\")\n;;=> \\space\n","_id":"5aa52a55e4b0316c0f44f91c"},{"updated-at":1698678471391,"created-at":1520774510308,"author":{"login":"glts","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/1483271?v=4"},"body":";; \"halt-when\" can only really be used with \"transduce\" (and \"into\" \n;; as of Clojure 1.11.1), but not with other functions that\n;; support transducers like \"sequence\".\n\n(def v (vec (concat (range 5) [:x])))\n(def xf (comp (take 10) (halt-when keyword?) (map inc)))\n\n(transduce xf conj [] v)\n;;=> :x\n\n(into [] xf v)\n;;=> ClassCastException!\n;; Clojure 1.11.0 Alpha 4 updates \"into\" so that this works and produces:\n;;=> :x\n\n(sequence xf v)\n;;=> (1 2 3 4 5), wrong result!\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/43875?v=4","account-source":"github","login":"seancorfield"},{"login":"daemianmack","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/24476?v=4"}],"_id":"5aa52d6ee4b0316c0f44f91d"},{"editors":[{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"}],"body":";; Using the second argument in halt-when\n\n(transduce\n (comp (halt-when #{30} ;; stop at 30th item\n (fn [acc itm] acc))) ;; return all items so far\n (completing conj #(reduce + %)) ;; sums items on exit\n (range))\n;; 435","author":{"avatar-url":"https://avatars.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"},"created-at":1642611299179,"updated-at":1656671302936,"_id":"61e84263e4b0b1e3652d75a0"},{"editors":[{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"}],"body":";; Like `take-while`'s complement when we return the completed result so far\n(transduce (take-while #(< % 10)) + (range));; => 45\n(transduce (halt-when #(>= % 10) (fn [acc _] acc)) + (range));; => 45\n\n;; So it's similar to medley's `take-upto` when `retf` = transduce's `f`\n(transduce (medley.core/take-upto #(>= % 10)) conj (range))\n;; => [0 1 2 3 4 5 6 7 8 9 10]\n(transduce (halt-when #(>= % 10) conj) conj (range))\n;; => [0 1 2 3 4 5 6 7 8 9 10]","author":{"avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4","account-source":"github","login":"tomdl89"},"created-at":1658423818398,"updated-at":1658425450347,"_id":"62d98a0ae4b0b1e3652d762b"},{"updated-at":1685471418885,"created-at":1685471418885,"author":{"login":"holyjak","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/624958?v=4"},"body":";; Since Clojure 1.11 we can also use this with e.g. into:\n(into {}\n (comp\n (map (juxt :l :n))\n (halt-when (comp (complement number?) second) \n (constantly ::invalid)))\n [{:l \"A\" :n 1}\n {:l \"B\" :n \"not a number!\"}\n {:l \"C\" :n 3}])\n;; => ::invalid\n;; (remove the B entry to get `=> {\"A\" 1, \"C\" 3}`)","_id":"647640bae4b08cf8563f4bc7"}],"notes":[{"author":{"login":"glts","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/1483271?v=4"},"updated-at":1520774998468,"created-at":1520774998468,"body":"`halt-when` is an odd transducer in that it is supposed to be used with `transduce`, but not in other transducible contexts like `sequence` or `into`.\n\nSays Alex Miller at https://dev.clojure.org/jira/browse/CLJ-1451: ‘Yeah, halt-when is a little tricky to use in transducible contexts other than transduce.’ Some more discussion at https://groups.google.com/d/msg/clojure/6HvmJIUsXKk/gLqUsfcnAwAJ.\n","_id":"5aa52f56e4b0316c0f44f91e"},{"author":{"login":"holyjak","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/624958?v=4"},"updated-at":1685471806059,"created-at":1685471806059,"body":"Not anymore, as pointed out above, at least `into` works fine under Clojure 1.11","_id":"6476423ee4b08cf8563f4bc8"}],"arglists":["pred","pred retf"],"doc":"Returns a transducer that ends transduction when pred returns true\n for an input. When retf is supplied it must be a fn of 2 arguments -\n it will be passed the (completed) result so far and the input that\n triggered the predicate, and its return value (if it does not throw\n an exception) will be the return value of the transducer. If retf\n is not supplied, the input that triggered the predicate will be\n returned. If the predicate never returns true the transduction is\n unaffected.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/halt-when"},{"added":"1.0","ns":"clojure.core","name":"with-in-str","file":"clojure/core.clj","type":"macro","column":1,"see-alsos":[{"created-at":1398723552000,"author":{"login":"ryo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3f7913b563c72083c74030d928ba407e?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"with-out-str","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f33"}],"line":4776,"examples":[{"author":{"login":"tormaroe","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8bc7bb10bee96efb190053fe92ffd250?r=PG&default=identicon"},"editors":[{"login":"tormaroe","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8bc7bb10bee96efb190053fe92ffd250?r=PG&default=identicon"}],"body":";; Given you have a function that will read from *in*\n(defn prompt [question]\n (println question)\n (read-line))\n\nuser=> (prompt \"How old are you?\")\nHow old are you?\n34 ; <== This is what you enter\n\"34\" ; <== This is returned by the function\n\n;; You can now simulate entering your age at the prompt by using with-in-str\n\nuser=> (with-in-str \"34\" (prompt \"How old are you?\"))\nHow old are you?\n\"34\" ; <== The function now returns immediately \n","created-at":1289600189000,"updated-at":1289600648000,"_id":"542692c7c026201cdc3269d8"}],"macro":true,"notes":null,"arglists":["s & body"],"doc":"Evaluates body in a context in which *in* is bound to a fresh\n StringReader initialized with the string s.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/with-in-str"},{"added":"1.0","ns":"clojure.core","name":"remove-watch","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1331136355000,"author":{"login":"pjlegato","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/4ce55cfd8b3ae2f63f5ecbc8fc1c05d4?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"add-watch","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c2f"},{"created-at":1498791146039,"author":{"login":"delonnewman","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/10404?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"atom","ns":"clojure.core"},"_id":"5955bceae4b06e730307db49"},{"created-at":1498791163420,"author":{"login":"delonnewman","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/10404?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"var","ns":"clojure.core"},"_id":"5955bcfbe4b06e730307db4a"},{"created-at":1498791180171,"author":{"login":"delonnewman","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/10404?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"ref","ns":"clojure.core"},"_id":"5955bd0ce4b06e730307db4b"},{"created-at":1661778678117,"author":{"login":"wactbprot","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/113518?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"agent","ns":"clojure.core"},"_id":"630cbaf6e4b0b1e3652d765e"}],"line":2179,"examples":[{"body":"(def a (atom nil))\n\n;; The key of the watch is `:logger`\n(add-watch a :logger #(println %4))\n\n(reset! a [1 2 3])\n\n;; Deactivate the watch by its assigned key\n(remove-watch a :logger)","author":{"login":"jkxyz","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10171367?v=3"},"created-at":1434458463428,"updated-at":1434458576224,"editors":[{"login":"jkxyz","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10171367?v=3"}],"_id":"5580195fe4b03e2132e7d197"}],"notes":null,"arglists":["reference key"],"doc":"Removes a watch (set by add-watch) from a reference","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/remove-watch"},{"added":"1.4","ns":"clojure.core","name":"ex-info","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1414982233911,"author":{"login":"also","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/15624?v=2"},"to-var":{"ns":"clojure.core","name":"ex-data","library-url":"https://github.com/clojure/clojure"},"_id":"5456ea59e4b03d20a102429b"},{"created-at":1504289816491,"author":{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/94482?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"throw","ns":"clojure.core"},"_id":"59a9a418e4b09f63b945ac5e"},{"created-at":1517620449117,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"try","ns":"clojure.core"},"_id":"5a750ce1e4b0e2d9c35f7407"},{"created-at":1517620458546,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"catch","ns":"clojure.core"},"_id":"5a750ceae4b0e2d9c35f7408"},{"created-at":1517620910204,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"finally","ns":"clojure.core"},"_id":"5a750eaee4b0e2d9c35f740f"},{"created-at":1518042214699,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"print-stack-trace","ns":"clojure.stacktrace"},"_id":"5a7b7c66e4b0316c0f44f8a4"}],"line":4832,"examples":[{"body":"(try\n (throw \n (ex-info \"The ice cream has melted!\" \n {:causes #{:fridge-door-open :dangerously-high-temperature} \n :current-temperature {:value 25 :unit :celsius}}))\n (catch Exception e (ex-data e)))\n\n;;=> {:causes #{:fridge-door-open :dangerously-high-temperature} \n;; :current-temperature {:value 25 :unit :celsius}}))\n\n","author":{"login":"claj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/353113?v=3"},"created-at":1424029233597,"updated-at":1457501094130,"editors":[{"login":"claj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/353113?v=3"},{"avatar-url":"https://avatars.githubusercontent.com/u/5733420?v=3","account-source":"github","login":"trimtab613"},{"login":"snufkon","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/490414?v=3"}],"_id":"54e0f631e4b01ed96c93c87a"},{"updated-at":1561362532798,"created-at":1561362532798,"author":{"login":"humorless","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/3061798?v=4"},"body":";; From https://stackoverflow.com/questions/25211457/\n;; Catching ExceptionInfo will only catch throwables created with ex-info:\n(try\n (throw (ex-info \"bad\" {:a 1 :b 2}))\n (catch clojure.lang.ExceptionInfo e\n (prn \"caught\" e)))\n;; => \"caught\" #","_id":"5d108064e4b0ca44402ef761"},{"updated-at":1680871851550,"created-at":1580222636013,"author":{"login":"daemianmack","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/24476?v=4"},"body":";; The 3-arg arity is for linking exceptions in accordance with Java convention.\n;; For example you could write an exception wrapper:\n\n(ns clojure.example)\n\n(defn exception-wrapper\n \"Wrap exceptions to embed `:event` information from the `request` such\n that we preserve the `Caused by` convention.\"\n [request exception]\n (let [event (:event request)\n exc (ex-info (.getMessage ^Throwable exception)\n {:event event}\n exception)]\n (throw exc)))\n\nclojure.example> (exception-wrapper {:event \"some-event-info\"}\n (ex-info \"Dang.\" {:trilobites :everywhere}))\n\n;; => Execution error (ExceptionInfo) at clojure.example/eval5596 (REPL:26).\n;; => Dang.\n\nclojure.example> (clojure.repl/pst *e)\n;; => ExceptionInfo Dang. {:event \"some-event-info\"}\n;; => \tclojure.example/exception-wrapper (NO_SOURCE_FILE:7)\n;; => [...]\n;; => \tclojure.main/repl (main.clj:458)\n;; => Caused by:\n;; => ExceptionInfo Dang. {:trilobites :everywhere}\n\n\n\n;; Like in Java, you should chain exceptions (ex-cause). \n;; This lets you rank the exception in context.\n;; An exception chain is like an interrogation \n;; -> Who are you? (type e) => clojure.lang.ExceptionInfo\n;; -> What is your meaning? (ex-message e) => Divide by Zero\n;; -> Why did you behave badly? (ex-data e) => :divisor was 0\n;; -> Who else was involved? (ex-cause e) => #ArithmeticException{}\n;; --> Who are you? (-> e ex-cause type) => ArithmeticException\n;; ---> Who are you? (-> e ex-cause ex-cause type) => ...\n(def a 1)\n(def b 0)\n\n(try (/ a b)\n (catch ArithmeticException ae ;; <-- \"defuse\" Throwable\n (throw ;; <-- re-throw exception\n (ex-info ;; <-- contextualize ae\n (ex-message ae) ;; <-- chain exception message\n {:divisor b :dividend a} ;; <-- give your new ex-info context\n ae)))) ;; <-- chain ae as cause\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/24317401?v=4","account-source":"github","login":"loeschzwerg"},{"login":"daemianmack","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/24476?v=4"}],"_id":"5e3048ace4b0ca44402ef823"},{"updated-at":1695980225974,"created-at":1590830551261,"author":{"login":"caumond","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/11491686?v=4"},"body":";; Be careful that when thrown in a future\n;; exceptions are cast into an ExecutionException\n(ns clojure.example)\n\n(try\n @(future \n (throw \n (ex-info \"This exception is not caught as an ExceptionInfo but an ExecutionException\" \n {:useless :data})))\n (catch clojure.lang.ExceptionInfo e \n (println \"Is not executed\"))\n (catch java.util.concurrent.ExecutionException e \n (println \"This one is executed\")))\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/24317401?v=4","account-source":"github","login":"loeschzwerg"},{"login":"caumond","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/11491686?v=4"}],"_id":"5ed225d7e4b087629b5a1920"}],"notes":null,"arglists":["msg map","msg map cause"],"doc":"Create an instance of ExceptionInfo, a RuntimeException subclass\n that carries a map of additional data.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/ex-info"},{"added":"1.0","ns":"clojure.core","name":"ifn?","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1321052090000,"author":{"login":"mmwaikar","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/29d36f4c9f39c9f8ff61c07033b13118?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"fn?","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c09"}],"line":6286,"examples":[{"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":";; An anonymous function is a function as you'd expect\nuser=> (ifn? #(\"my anonymous function\"))\ntrue\n\n;; Is a vector a function?\nuser=> (ifn? [1 2 3])\ntrue\n\n;; Sure is, lets call it.\nuser=> ([1 2 3] 0)\n1\n\n;; Maps and sets are functions, too.\n\n;; a number is definitely not a function\nuser=> (ifn? 1)\nfalse\n\n;; but a symbol is\nuser=> (ifn? 'foo)\ntrue\n\n;; and so is a keyword\nuser=> (ifn? :foo)\ntrue","created-at":1281077011000,"updated-at":1329991142000,"_id":"542692cdc026201cdc326d38"}],"notes":null,"arglists":["x"],"doc":"Returns true if x implements IFn. Note that many data structures\n (e.g. sets and maps) implement IFn","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/ifn_q"},{"added":"1.5","ns":"clojure.core","name":"some->","file":"clojure/core.clj","type":"macro","column":1,"see-alsos":[{"created-at":1412083935441,"author":{"login":"jw-00000","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2936?v=2"},"to-var":{"ns":"clojure.core","name":"some->>","library-url":"https://github.com/clojure/clojure"},"_id":"542ab0dfe4b0df9bb778a59b"},{"created-at":1412083945874,"author":{"login":"jw-00000","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2936?v=2"},"to-var":{"ns":"clojure.core","name":"->","library-url":"https://github.com/clojure/clojure"},"_id":"542ab0e9e4b0df9bb778a59c"},{"created-at":1412268640070,"author":{"login":"abrooks","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/69976?v=2"},"to-var":{"ns":"clojure.core","name":"cond->","library-url":"https://github.com/clojure/clojure"},"_id":"542d8260e4b05f4d257a298e"},{"created-at":1412268648681,"author":{"login":"abrooks","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/69976?v=2"},"to-var":{"ns":"clojure.core","name":"cond->>","library-url":"https://github.com/clojure/clojure"},"_id":"542d8268e4b05f4d257a298f"},{"created-at":1412268658944,"author":{"login":"abrooks","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/69976?v=2"},"to-var":{"ns":"clojure.core","name":"as->","library-url":"https://github.com/clojure/clojure"},"_id":"542d8272e4b05f4d257a2990"},{"created-at":1412268673788,"author":{"login":"abrooks","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/69976?v=2"},"to-var":{"ns":"clojure.core","name":"->>","library-url":"https://github.com/clojure/clojure"},"_id":"542d8281e4b05f4d257a2991"}],"line":7776,"examples":[{"body":"user=> (-> {:a 1} :b inc)\n;; NullPointerException clojure.lang.Numbers.ops (Numbers.java:942)\n\nuser=> (some-> {:a 1} :b inc)\n;; nil\n","author":{"login":"boxp","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1819576?v=2"},"created-at":1412868850592,"updated-at":1412868897594,"editors":[{"login":"boxp","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1819576?v=2"}],"_id":"5436aaf2e4b06dbffbbb00bd"},{"updated-at":1444741522705,"created-at":1444741522705,"author":{"login":"marick","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/71909?v=3"},"body":";; Often used to \"short-circuit out\" of a series of steps:\n\n(some-> val\n step1\n step2\n step3)\n\n;; When nil is returned by any step, the further steps are not executed. Thus\n;; the nil case need be handled only once, at the end.","_id":"561d0192e4b084e61c76ecc3"}],"macro":true,"notes":null,"arglists":["expr & forms"],"doc":"When expr is not nil, threads it into the first form (via ->),\n and when that result is not nil, through the next etc","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/some->"},{"added":"1.9","ns":"clojure.core","name":"nat-int?","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1495640911419,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"pos-int?","ns":"clojure.core"},"_id":"5925ab4fe4b093ada4d4d72e"},{"created-at":1495640921991,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"neg-int?","ns":"clojure.core"},"_id":"5925ab59e4b093ada4d4d72f"},{"created-at":1495705366734,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"int?","ns":"clojure.core"},"_id":"5926a716e4b093ada4d4d750"}],"line":1434,"examples":[{"updated-at":1495030925280,"created-at":1495030925280,"author":{"login":"larrychristensen","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/2092583?v=3"},"body":"user> (nat-int? 0)\ntrue\nuser> (nat-int? 1)\ntrue\nuser> (nat-int? -1)\nfalse\n;; especially useful for specs\nuser> (require '[clojure.spec :as spec])\nnil\nuser> (spec/def quantity nat-int?)\nuser/quantity\nuser> (spec/def ::quantity nat-int?)\n:user/quantity\nuser> (spec/valid? ::quantity -1)\nfalse","_id":"591c5c8de4b01920063ee060"},{"updated-at":1495703903990,"created-at":1495703903990,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"body":"(nat-int? 0)\n;;=> true\n(nat-int? 1)\n;;=> true\n(nat-int? 9223372036854775807)\n;;=> true\n\n;;;; false for negative values\n\n(nat-int? -1)\n;;=> false\n\n;;;; false for decimal values\n\n(nat-int? 0.0)\n;;=> false\n(nat-int? 1.0)\n;;=> false\n(nat-int? 1/2)\n;;=> false\n\n;;;; false for BigInt values\n\n(nat-int? 0N)\n;;=> false\n(nat-int? 1N)\n;;=> false\n(nat-int? 9223372036854775808)\n;;=> false","_id":"5926a15fe4b093ada4d4d74d"}],"notes":null,"arglists":["x"],"doc":"Return true if x is a non-negative fixed precision integer","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/nat-int_q"},{"ns":"clojure.core","name":"proxy-name","file":"clojure/core_proxy.clj","type":"function","column":1,"see-alsos":null,"line":37,"examples":null,"notes":null,"tag":"java.lang.String","arglists":["super interfaces"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core/proxy-name"},{"added":"1.0","ns":"clojure.core","name":"ns-interns","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1288055138000,"author":{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},"to-var":{"ns":"clojure.core","name":"ns-map","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521ae9"},{"created-at":1298556643000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.core","name":"ns-publics","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521aea"},{"created-at":1348479295000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"ns-aliases","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521aeb"},{"created-at":1348479323000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"ns-refers","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521aec"}],"line":4233,"examples":[{"author":{"login":"shockbob","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon"},"editors":[],"body":"user=> (take 2 (ns-interns `clojure.core))\n([sorted-map #'clojure.core/sorted-map] [read-line #'clojure.core/read-line])\n\nuser=> (take 5 (sort (keys (ns-interns `clojure.java.io))))\n(Coercions IOFactory append? as-file as-relative-path)\n\nuser=> (count (ns-interns `clojure.core)) ; only 621 functions to learn :-)\n621\nuser=>","created-at":1313988495000,"updated-at":1313988495000,"_id":"542692c8c026201cdc3269ea"},{"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"editors":[],"body":";; See also http://clojure.org/namespaces for information on namespaces in Clojure and how to inspect and manipulate them","created-at":1348479359000,"updated-at":1348479359000,"_id":"542692d4c026201cdc327018"}],"notes":null,"arglists":["ns"],"doc":"Returns a map of the intern mappings for the namespace.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/ns-interns"},{"added":"1.0","ns":"clojure.core","name":"all-ns","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1516472495588,"author":{"login":"bkovitz","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/4142015?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"ns-name","ns":"clojure.core"},"_id":"5a6388afe4b093a19c35dc09"}],"line":4173,"examples":[{"updated-at":1332953063000,"created-at":1281460579000,"body":"user=> (all-ns)\n(# # # # # # # # # # # # # # # # # # # # # # # # #)","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3","account-source":"github","login":"jafingerhut"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3","account-source":"github","login":"devn"},"_id":"542692c7c026201cdc326990"},{"updated-at":1516472462629,"created-at":1516472462629,"author":{"login":"bkovitz","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/4142015?v=4"},"body":";; The names of all your current namespaces that end in \"-test\":\n\n(->> (all-ns)\n (map ns-name)\n (map name)\n (filter #(clojure.string/ends-with? % \"-test\")))\n;;=> (\"core-test\" \"farg.pmatch-test\")","_id":"5a63888ee4b093a19c35dc08"}],"notes":null,"arglists":[""],"doc":"Returns a sequence of all namespaces.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/all-ns"},{"ns":"clojure.core","name":"find-protocol-method","file":"clojure/core_deftype.clj","type":"function","column":1,"see-alsos":null,"line":548,"examples":null,"notes":null,"arglists":["protocol methodk x"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core/find-protocol-method"},{"added":"1.0","ns":"clojure.core","name":"subvec","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1291975197000,"author":{"login":"alimoeeny","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e8dd06976ead4082d2181f3807117e1?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"vector","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521dee"},{"created-at":1291975205000,"author":{"login":"alimoeeny","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e8dd06976ead4082d2181f3807117e1?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"vector?","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521def"}],"line":3844,"examples":[{"updated-at":1423278293433,"created-at":1281558954000,"body":";; not supplying 'end' returns vector from 'start' to (count vector)\nuser=> (subvec [1 2 3 4 5 6 7] 2)\n[3 4 5 6 7]\n\n;; supplying 'end' returns vector from 'start' to element (- end 1)\nuser=> (subvec [1 2 3 4 5 6 7] 2 4)\n[3 4]","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"avatar-url":"https://avatars.githubusercontent.com/u/92894?v=3","account-source":"github","login":"rafmagana"},{"avatar-url":"https://avatars.githubusercontent.com/u/92894?v=3","account-source":"github","login":"rafmagana"},{"avatar-url":"https://avatars.githubusercontent.com/u/92894?v=3","account-source":"github","login":"rafmagana"},{"avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3","account-source":"github","login":"Dimagog"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/68dd6f50915854aa04fefcf4d6fa5c8e?r=PG&default=identicon","account-source":"clojuredocs","login":"zmila"},"_id":"542692cec026201cdc326d62"},{"editors":[{"login":"burnall","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1253998?v=3"}],"body":";; Remove one item by index\n\n(let [coll [0 1 2 3 4 5]\n i 3]\n (concat (subvec coll 0 i)\n (subvec coll (inc i))))\n;; => (0 1 2 4 5)","author":{"avatar-url":"https://avatars.githubusercontent.com/u/8399149?v=3","account-source":"github","login":"freckletonj"},"created-at":1476828499701,"updated-at":1485765017826,"_id":"58069d53e4b001179b66bdcd"},{"updated-at":1504176183534,"created-at":1503932170688,"author":{"login":"Sophia-Gold","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/19278114?v=4"},"body":";; To query the indices of a subvec:\n(def foo (vec (range 10)))\n(def bar (subvec foo 3 7)) \n=> (.start bar)\n3\n=> (.end bar)\n7\n\n;; Increments with repeated slicing:\n(def baz (subvec bar 2))\n=> (.start baz)\n5\n\n;; Return the original vector:\n=> (.v bar)\n[0 1 2 3 4 5 6 7 8 9]\n=> (.v baz)\n[0 1 2 3 4 5 6 7 8 9]","editors":[{"avatar-url":"https://avatars2.githubusercontent.com/u/19278114?v=4","account-source":"github","login":"Sophia-Gold"}],"_id":"59a42f0ae4b09f63b945ac58"},{"updated-at":1573491889014,"created-at":1573491506809,"author":{"login":"jonathan-chen-tda","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/17070766?v=4"},"body":";; IndexOutOfBoundsException for bad indices\n=> (subvec [0 1 2 3 4 5] 8 9)\nExecution error (IndexOutOfBoundsException) at ...","editors":[{"avatar-url":"https://avatars2.githubusercontent.com/u/17070766?v=4","account-source":"github","login":"jonathan-chen-tda"}],"_id":"5dc99332e4b0ca44402ef7d7"}],"notes":[{"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"updated-at":1522075347012,"created-at":1522075347012,"body":"
    \n;; Note that subvec holds a reference to the original vector. If you plan \n;; to split a large vector and never using it again, consider freeing up\n;; the reference.\n\n(let [v1 (subvec (vec (range 1e7)) 0 5)\n      v2 (subvec (vec (range 1e7)) 5 10)]\n      (into v1 v2))\n;; OutOfMem\n\n(let [v1 (into [] (subvec (vec (range 1e7)) 0 5))\n      v2 (into [] (subvec (vec (range 1e7)) 5 10))]\n      (into v1 v2))\n;; [0 1 2 3 4 5 6 7 8 9]\n
    ","_id":"5ab906d3e4b045c27b7fac25"}],"arglists":["v start","v start end"],"doc":"Returns a persistent vector of the items in vector from\n start (inclusive) to end (exclusive). If end is not supplied,\n defaults to (count vector). This operation is O(1) and very fast, as\n the resulting vector shares structure with the original and no\n trimming is done.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/subvec"},{"added":"1.0","ns":"clojure.core","name":"for","file":"clojure/core.clj","type":"macro","column":1,"see-alsos":[{"created-at":1318594692000,"author":{"login":"mmwaikar","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/29d36f4c9f39c9f8ff61c07033b13118?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"doseq","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c7f"},{"created-at":1338714786000,"author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"to-var":{"ns":"clojure.core","name":"doall","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c80"},{"created-at":1360362825000,"author":{"login":"ViljamiPeltola","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1535c08820796d57a212a46a6bdd4cca?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"recur","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c81"},{"created-at":1484942509711,"author":{"login":"bheesham","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/171007?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"range","ns":"clojure.core"},"_id":"58826cade4b09108c8545a5c"},{"created-at":1602104691947,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"let","ns":"clojure.core"},"_id":"5f7e2d73e4b0b1e3652d73cc"},{"created-at":1602104699060,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"when","ns":"clojure.core"},"_id":"5f7e2d7be4b0b1e3652d73cd"}],"line":4673,"examples":[{"updated-at":1421257348418,"created-at":1279388402000,"body":";; prepare a seq of the even values \n;; from the first six multiples of three\n(for [x [0 1 2 3 4 5]\n :let [y (* x 3)]\n :when (even? y)]\n y)\n;;=> (0 6 12)\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3","account-source":"github","login":"phreed"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/142529?v=3","account-source":"github","login":"nipra"},"_id":"542692c7c026201cdc326952"},{"updated-at":1588419699839,"created-at":1279947290000,"body":"(def digits [1 2 3])\n\n(for [x1 digits\n x2 digits]\n (* x1 x2))\n;;=> (1 2 3 2 4 6 3 6 9)","editors":[{"avatar-url":"https://www.gravatar.com/avatar/1703a0c3ed358b787f4b1bf3b2799472?r=PG&default=identicon","account-source":"clojuredocs","login":"Jacolyte"},{"avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3","account-source":"github","login":"jafingerhut"},{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3","account-source":"github","login":"phreed"},{"login":"YizhePKU","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/42838469?v=4"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/1703a0c3ed358b787f4b1bf3b2799472?r=PG&default=identicon","account-source":"clojuredocs","login":"Jacolyte"},"_id":"542692c7c026201cdc326954"},{"updated-at":1588419818008,"created-at":1283713265000,"body":";; produce a seq of all pairs drawn from two vectors\n(for [x ['a 'b 'c] \n y [1 2 3]]\n [x y])\n;;=> ([a 1] [a 2] [a 3] [b 1] [b 2] [b 3] [c 1] [c 2] [c 3])\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3","account-source":"github","login":"jafingerhut"},{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3","account-source":"github","login":"phreed"},{"login":"SubhaSingh","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/12873392?v=3"},{"login":"YizhePKU","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/42838469?v=4"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/4b163432c99a124feee4be046a3f9d66?r=PG&default=identicon","account-source":"clojuredocs","login":"james"},"_id":"542692c7c026201cdc326957"},{"author":{"login":"james","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/4b163432c99a124feee4be046a3f9d66?r=PG&default=identicon"},"editors":[{"login":"james","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/4b163432c99a124feee4be046a3f9d66?r=PG&default=identicon"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":";; produce a seq of the first three powers for a range of integers\n(for [x (range 1 6) \n :let [y (* x x) \n z (* x x x)]] \n [x y z])\n;;=> ([1 1 1] [2 4 8] [3 9 27] [4 16 64] [5 25 125])\n","created-at":1283713566000,"updated-at":1421257621209,"_id":"542692c7c026201cdc326959"},{"updated-at":1588419920709,"created-at":1292101988000,"body":";; produce a seq of squares\n(for [x (range 6)] \n (* x x))\n;;=> (0 1 4 9 16 25)","editors":[{"avatar-url":"https://www.gravatar.com/avatar/6ff7e838d2c47adf942be6df4d22b452?r=PG&default=identicon","account-source":"clojuredocs","login":"pashields"},{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3","account-source":"github","login":"phreed"},{"login":"YizhePKU","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/42838469?v=4"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/9e8dd06976ead4082d2181f3807117e1?r=PG&default=identicon","account-source":"clojuredocs","login":"alimoeeny"},"_id":"542692c7c026201cdc32695d"},{"author":{"login":"huahaiy","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/889685?v=2"},"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":";; prepare a seq of all keys from entries whose values are 0\n(for [[x y] '([:a 1] [:b 2] [:c 0]) :when (= y 0)] x)\n;;=> (:c)\n","created-at":1305076075000,"updated-at":1421257745017,"_id":"542692c7c026201cdc32695f"},{"author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":";; Demonstrating performance difference between :when and :while\n\n(time (dorun (for [x (range 1000) y (range 10000) :when (> x y)] [x y])))\n;; \"Elapsed time: 2898.908 msecs\"\n;;=> nil\n\n(time (dorun (for [x (range 1000) y (range 10000) :while (> x y)] [x y])))\n;; \"Elapsed time: 293.677 msecs\"\n;;=> nil\n","created-at":1338313241000,"updated-at":1421258673026,"_id":"542692d3c026201cdc326fa6"},{"author":{"login":"bzhou","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5ea589e907c3d7da52e3c76924fbe3f7?r=PG&default=identicon"},"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":";; Demonstrating functional difference between :when and :while\n\n(for [x (range 3) y (range 3)] [x y])\n;;=> ([0 0] [0 1] [0 2] \n;; [1 0] [1 1] [1 2]\n;; [2 0] [2 1] [2 2])\n\n(for [x (range 3) y (range 3) :when (not= x y)] [x y])\n;;=> ( [0 1] [0 2] \n;; [1 0] [1 2] \n;; [2 0] [2 1] )\n\n; Here we see the :while applied to the immediately preceding seq\n(for [x (range 3) y (range 3) :while (not= x y)] [x y])\n;;=> ( \n;; [1 0] \n;; [2 0] [2 1] )\n\n;; The placement of the :while is important\n;; :while can cause a halt for a particular sequence\n\n(for [x (range 3) y (range 3) :while (not= x 1)] [x y])\n;;=> ([0 0] [0 1] [0 2] [2 0] [2 1] [2 2])\n\n(for [x (range 3) :while (not= x 1) y (range 3)] [x y])\n;;=> ([0 0] [0 1] [0 2])\n","created-at":1340260912000,"updated-at":1510266180494,"_id":"542692d3c026201cdc326fa7"},{"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"editors":[],"body":";; More examples illustrating the difference between :when and :while\n\n;; Simple but inefficient method of checking whether a number is\n;; prime.\nuser=> (defn prime? [n]\n (not-any? zero? (map #(rem n %) (range 2 n))))\n#'user/prime?\n\nuser=> (range 3 33 2)\n(3 5 7 9 11 13 15 17 19 21 23 25 27 29 31)\n\n;; :when continues through the collection even if some have the\n;; condition evaluate to false, like filter\nuser=> (for [x (range 3 33 2) :when (prime? x)]\n x)\n(3 5 7 11 13 17 19 23 29 31)\n\n;; :while stops at the first collection element that evaluates to\n;; false, like take-while\nuser=> (for [x (range 3 33 2) :while (prime? x)]\n x)\n(3 5 7)\n\n;; The examples above can easily be rewritten with filter or\n;; take-while. When you have a for with multiple binding forms, so\n;; that the iteration occurs in a nested fashion, it becomes possible\n;; to write something briefly with 'for' that would be more verbose or\n;; unwieldy with nested filter or take-while expressions.\n\nuser=> (for [x (range 3 17 2) :when (prime? x)\n y (range 3 17 2) :when (prime? y)]\n [x y])\n([ 3 3] [ 3 5] [ 3 7] [ 3 11] [ 3 13]\n [ 5 3] [ 5 5] [ 5 7] [ 5 11] [ 5 13]\n [ 7 3] [ 7 5] [ 7 7] [ 7 11] [ 7 13]\n [11 3] [11 5] [11 7] [11 11] [11 13]\n [13 3] [13 5] [13 7] [13 11] [13 13])\n\nuser=> (for [x (range 3 17 2) :while (prime? x)\n y (range 3 17 2) :while (prime? y)]\n [x y])\n([3 3] [3 5] [3 7]\n [5 3] [5 5] [5 7]\n [7 3] [7 5] [7 7])\n\n;; This example only gives a finite result because of the :while\n;; expressions.\nuser=> (for [x (range) :while (< x 10) \n y (range) :while (<= y x)]\n [x y])\n\n([0 0]\n [1 0] [1 1]\n [2 0] [2 1] [2 2]\n [3 0] [3 1] [3 2] [3 3]\n [4 0] [4 1] [4 2] [4 3] [4 4]\n [5 0] [5 1] [5 2] [5 3] [5 4] [5 5]\n [6 0] [6 1] [6 2] [6 3] [6 4] [6 5] [6 6]\n [7 0] [7 1] [7 2] [7 3] [7 4] [7 5] [7 6] [7 7]\n [8 0] [8 1] [8 2] [8 3] [8 4] [8 5] [8 6] [8 7] [8 8]\n [9 0] [9 1] [9 2] [9 3] [9 4] [9 5] [9 6] [9 7] [9 8] [9 9])\n","created-at":1345760672000,"updated-at":1345760672000,"_id":"542692d3c026201cdc326fa8"},{"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"editors":[],"body":";; Here are a couple of examples where the only difference is where\n;; the :while is placed, but it makes a significant difference in the\n;; behavior.\n\n;; When x=2 y=1 is reached, :while (<= x y) evaluates false, so all\n;; further items in the y collection are skipped. When x=3 y=1 is\n;; reached, the same thing happens.\n\nuser=> (for [x [1 2 3]\n y [1 2 3]\n :while (<= x y)\n z [1 2 3]]\n [x y z])\n([1 1 1] [1 1 2] [1 1 3]\n [1 2 1] [1 2 2] [1 2 3]\n [1 3 1] [1 3 2] [1 3 3])\n\n;; This is different. When x=2 y=1 z=1 is reached, :while (<= x y)\n;; evaluates false, but since the :while is after the binding for z,\n;; all further items in the z collection are skipped. Then x=2 y=2\n;; z=1 is tried, where the while expresssion evaluates true.\n\nuser=> (for [x [1 2 3]\n y [1 2 3]\n z [1 2 3]\n :while (<= x y)]\n [x y z])\n([1 1 1] [1 1 2] [1 1 3]\n [1 2 1] [1 2 2] [1 2 3]\n [1 3 1] [1 3 2] [1 3 3]\n [2 2 1] [2 2 2] [2 2 3]\n [2 3 1] [2 3 2] [2 3 3]\n [3 3 1] [3 3 2] [3 3 3])\n","created-at":1345760698000,"updated-at":1345760698000,"_id":"542692d3c026201cdc326fa9"},{"author":{"login":"octopusgrabbus","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/fd31b8bcea99fa7b0711fbc424587774?r=PG&default=identicon"},"editors":[],"body":"(defn all-files-present?\n\"Takes a list of real file names, and returns a map of files present 1\nand not present 0.\"\n[file-seq]\n(for [fnam file-seq\n :let [stat-map {(keyword fnam) (look-for fnam \"f\")}]]\n stat-map))\n\n(into {} (all-files-present? '(\"Makefile\" \"build.sh\" \"real-estate.csv\")))\n\n{:Makefile 1, :build.sh 1, :real-estate.csv 0}","created-at":1356651292000,"updated-at":1356651292000,"_id":"542692d3c026201cdc326faa"},{"editors":[{"login":"alvarogarcia7","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/4199136?v=3"}],"updated-at":1456570106848,"created-at":1425980108716,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/6026368?v=3","account-source":"github","login":"m-combinator"},"body":";; Flattening a seq of pairs using for comprehensions\n\n(def pairs (for [i (range 10)] [i (inc i)]))\n;; ([0 1] [1 2] [2 3] [3 4] [4 5] [5 6] [6 7] [7 8] [8 9] [9 10])\n\n(def flattened (for [pair pairs element pair] element))\n;; (0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 10)","_id":"54febacce4b0b716de7a6536"},{"editors":[{"login":"colorgmi","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/9025191?v=3"},{"avatar-url":"https://avatars.githubusercontent.com/u/4199136?v=3","account-source":"github","login":"alvarogarcia7"},{"login":"cloojure","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7083783?v=3"}],"body":";; Given an array of integers, return indices of the two numbers such that they \n;; add up to a specific target.\n\n;; You may assume that each input would have exactly one solution.\n;; Given nums = [2, 7, 11, 15], target = 9,\n\n;; Because nums[0] + nums[1] = 2 + 7 = 9,\n;; return [0, 1].\n\n(defn two-sum [nums target]\n (let [nums-index (zipmap nums (range))\n indexs (for [[x i] nums-index\n [y j] nums-index\n :when (< i j)\n :when (= (+ x y) target)]\n [i j])]\n (first indexs)))\n\n(two-sum [2 7 11 15] 9)\n;; [0 1]\n","author":{"avatar-url":"https://avatars.githubusercontent.com/u/9025191?v=3","account-source":"github","login":"colorgmi"},"created-at":1455449257369,"updated-at":1460403168325,"_id":"56c064a9e4b060004fc217c4"},{"updated-at":1494499956872,"created-at":1494499956872,"author":{"login":"abhilater","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/1904958?v=3"},"body":";;; Cartesian products of two sets\n\n(#(set\n (for[x %1, y %2]\n [x y])) #{1 2 3} #{4 5})\n\n;=> #{[2 5] [3 4] [1 4] [1 5] [2 4] [3 5]}","_id":"59144274e4b01f4add58feb5"},{"updated-at":1506265801327,"created-at":1506265801327,"author":{"login":"cuspymd","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/8870299?v=4"},"body":";; Nested 'for' example to produce indexes of Two-dimensional array\n(for [i (range 3)]\n (for [j (range 3)]\n [i j]))\n\n;=> (([0 0] [0 1] [0 2]) \n; ([1 0] [1 1] [1 2]) \n; ([2 0] [2 1] [2 2]))","_id":"59c7cac9e4b03026fe14ea49"},{"updated-at":1626035981287,"created-at":1626035981287,"author":{"login":"jr0cket","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/250870?v=4"},"body":";; Generate the hiccup for a collection of books, each book has unique details defined in each hash-map inside the collection.\n;; Destructure the keys in the hash-map for each book in turn\n\n(def practicalli-book-list\n [{:title \"Practicalli Spacemacs\"\n :url \"https://practical.li/spacemacs\"\n :image \"/practicalli-spacemacs-book-banner.png\"\n :description \"Coding Clojure with Emacs and Vim multi-modal editing\"}\n {:title \"Practicalli Clojure\"\n :url \"https://practical.li/clojure\"\n :image \"/practicalli-clojure-book-banner.png\"\n :description \"Learn the Clojure language through REPL driven development\"}])\n\n(defn books-list\n [books]\n (for [{:keys [title description url image]} books]\n [:div {:class \"column\"}\n [:a {:href url :target \"_blank\"}\n [:img {:src image}]]\n [:p [:a {:href url :target \"_blank\" }\n title]\n description]]))\n\n(book-list practicalli-book-list)\n;; => [:div {:class \"box\"} [:div {:class \"column\"} [:h2 {:class \"title has-text-centered\"} \"Freely available online books\"]] nil ([:div {:class \"column\"} [:div {:class \"columns\"} [:div {:class \"column\"} [:a {:href \"https://practical.li/spacemacs\", :target \"_blank\"} [:figure {:class \"image\"} [:img {:src \"/practicalli-spacemacs-book-banner.png\"}]]]] [:div {:class \"column\"} [:p [:a {:href \"https://practical.li/spacemacs\", :target \"_blank\", :class \"has-text-weight-bold\"} \"Practicalli Spacemacs\"] \"Emacs and Vim multi-modal editing\"]]]] [:div {:class \"column\"} [:div {:class \"columns\"} [:div {:class \"column\"} [:a {:href \"https://practical.li/clojure\", :target \"_blank\"} [:figure {:class \"image\"} [:img {:src \"/practicalli-clojure-book-banner.png\"}]]]] [:div {:class \"column\"} [:p [:a {:href \"https://practical.li/clojure\", :target \"_blank\", :class \"has-text-weight-bold\"} \"Practicalli Clojure\"] \"Learn the Clojure language through REPL driven development\"]]]])]\n","_id":"60eb570de4b0b1e3652d7516"},{"updated-at":1652121747673,"created-at":1652121747673,"author":{"login":"vipermark7","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/9751748?v=4"},"body":";; Easy iteration through nested vectors\n\n(def matrix \n [[\"a\" \"b\"] [\"c\" \"d\"]])\n\n(for [row matrix letter row] \n letter)\n\n;; (\"a\" \"b\" \"c\" \"d\")","_id":"62796093e4b0b1e3652d75ed"},{"updated-at":1706781086822,"created-at":1706781086822,"author":{"login":"jimka2001","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/6414129?v=4"},"body":";; to map across a hashmap\n(for [[k v] {:a 1 :b 10 :c 100}]\n (list k v))\n\n;; -> ((:a 1) (:b 10) (:c 100))\n","_id":"65bb699e69fbcc0c22617496"},{"updated-at":1733228483818,"created-at":1733228483818,"author":{"login":"ottonascarella","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1014206?v=4"},"body":";; all right triangles with integer sides from 1 to 11\n(for [a (range 1 11)\n b (range 1 a)\n c (range 1 b)\n :when (= (* a a) (+ (* b b) (* c c)))]\n [a b c])","_id":"674ef7c369fbcc0c22617522"}],"macro":true,"notes":[{"updated-at":1279948874000,"body":"My English parser was choking on the description of this function.\r\n\r\n[This SO question](http://stackoverflow.com/questions/3322552/how-do-i-multiply-all-elements-in-one-collection-with-all-the-elements-in-another) has helped clarify how this function works.","created-at":1279948874000,"author":{"login":"Jacolyte","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1703a0c3ed358b787f4b1bf3b2799472?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521f87"},{"updated-at":1279949964000,"body":"Example 1 can be rewritten without using the for macro. Pure functional should be preferred if possible:\r\n
    \r\n(filter even? (map (partial * 3)  [0 1 2 3 4 5]))\r\n
    ","created-at":1279949964000,"author":{"login":"juergenhoetzel","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2736dfffc803c704dcf25b45ff63cede?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521f88"},{"updated-at":1313975247000,"body":"On juergenhoetzel's comment:\r\n\r\nAll the examples could be re-written in some combination of map and filter, but they are still valid examples of using the for comprehension, AFAIK:\r\n\r\nExamples:\r\n
    user=> (mapcat (fn [e] (map (fn [x] (* x e)) [1 2 3])) [1 2 3])\r\n(1 2 3 2 4 6 3 6 9)\r\nuser=> (mapcat (fn [e] (map (fn [x] [e x]) [1 2 3])) ['a 'b 'c])\r\n([a 1] [a 2] [a 3] [b 1] [b 2] [b 3] [c 1] [c 2] [c 3])\r\nuser=> (map (fn [e] [e (* e e)(* e e e)]) (range 1 6))\r\n([1 1 1] [2 4 8] [3 9 27] [4 16 64] [5 25 125])\r\nuser=> (map (fn [e] (* e e)) (range 3 7))\r\n(9 16 25 36)\r\nuser=> (map first (filter (fn [[x y]] (= y 0)) '([:a 1] [:b 2] [:c 0])))\r\n(:c)\r\nuser=>\r\n
    \r\n\r\n","created-at":1313973784000,"author":{"login":"shockbob","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fc7"},{"updated-at":1356553692000,"body":"Take careful note of the description's wording:\r\n\r\n binding-form/collection-expr pairs, \r\n each followed by zero or more modifiers\r\n\r\nA consequence is that the binding list may *not* begin with a modifier, i.e a `:let`, `:when` or `:while`!\r\n\r\nThe following example is **illegal** syntax:\r\n\r\n (for [:let [a 1] b (range 5)] \r\n {a b})\r\n\r\nWhile it might sometimes be convenient to start a `for` with a `:let` to reduce code clutter, the \"correct\" procedure is to nest the `for` in a \"proper\" `let`, like this:\r\n\r\n (let [a 1]\r\n (for [b (range 5)] \r\n {a b}))\r\n\r\nSimilarly, a `:when` is better represented by nesting in an `if`.\r\n\r\n","created-at":1356553540000,"author":{"login":"csmotricz","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/6c620615dfb537dbd5325380bd2eaa07?r=PG&default=identicon"},"_id":"542692edf6e94c6970521ffa"},{"updated-at":1375377539000,"body":"The fifth example should probably be shown in first position, it's the most straightforward and readable for a beginner : \r\n\r\n(for [x (range 3 7)] (* x x))","created-at":1375377539000,"author":{"login":"Joan Charmant","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/75a5fdba1a164425d43d3b9c4b830287?r=PG&default=identicon"},"_id":"542692edf6e94c6970522009"},{"updated-at":1395006875000,"body":"\"**Sequence** comprehension\", not \"list comprehension\". ","created-at":1395006875000,"author":{"login":"Thumbnail","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/db68e51797a2382e185b42ce6534b7a4?r=PG&default=identicon"},"_id":"542692edf6e94c6970522021"}],"arglists":["seq-exprs body-expr"],"doc":"List comprehension. Takes a vector of one or more\n binding-form/collection-expr pairs, each followed by zero or more\n modifiers, and yields a lazy sequence of evaluations of expr.\n Collections are iterated in a nested fashion, rightmost fastest,\n and nested coll-exprs can refer to bindings created in prior\n binding-forms. Supported modifiers are: :let [binding-form expr ...],\n :while test, :when test.\n\n (take 100 (for [x (range 100000000) y (range 1000000) :while (< y x)] [x y]))","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/for"},{"added":"1.0","ns":"clojure.core","name":"binding","file":"clojure/core.clj","type":"macro","column":1,"see-alsos":[{"created-at":1322088130000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"with-redefs","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e9a"},{"created-at":1374313487000,"author":{"login":"alilee","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2fb0196dc5a7cd3a5cc73f1b9941c209?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"with-bindings","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e9b"},{"created-at":1374512208000,"author":{"login":"alilee","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2fb0196dc5a7cd3a5cc73f1b9941c209?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"with-local-vars","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e9c"},{"created-at":1425742740372,"author":{"login":"kimtg","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7685905?v=3"},"to-var":{"ns":"clojure.core","name":"def","library-url":"https://github.com/clojure/clojure"},"_id":"54fb1b94e4b01ed96c93c886"}],"line":1964,"examples":[{"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"editors":[{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":";; Here are the definitions.\n(defn mymax [x y]\n (min x y))\n\n(defn find-max [x y]\n (max x y))\n\nuser=> (let [max mymax]\n (find-max 10 20))\n\n20 ;let is ineffective outside current lexical scope\n\n\nuser=> (binding [max mymax]\n (find-max 10 20))\n\n10 ;because max is now acting as min","created-at":1281546900000,"updated-at":1287628874000,"_id":"542692cfc026201cdc326e66"},{"updated-at":1579643060326,"created-at":1321652674000,"body":";; As of Clojure 1.3, vars need to be explicitly marked as ^:dynamic in order for\n;; them to be dynamically rebindable:\n\nuser=> (def ^:dynamic x 1)\nuser=> (def ^:dynamic y 1)\nuser=> (+ x y)\n2\n\n;; Within the scope of the binding, x = 2 and y = 3\n\nuser=> (binding [x 2 \n y 3]\n (+ x y))\n5\n\n;; But once you leave the binding's scope, x and y maintain their original\n;; bindings:\n\nuser=> (+ x y)\n2","editors":[{"login":"dijonkitchen","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/11434205?v=4"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/cab456ee2c30d86ce89400390ad812c6?r=PG&default=identicon","account-source":"clojuredocs","login":"onlyafly"},"_id":"542692d2c026201cdc326f54"},{"author":{"login":"Claj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5fd658a8d2ef549071cb5286b1b874aa?r=PG&default=identicon"},"editors":[{"login":"Claj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5fd658a8d2ef549071cb5286b1b874aa?r=PG&default=identicon"}],"body":";;Use t like a \"template\"\n\n(declare ^:dynamic t)\n\n(defn addt [] \n (+ t 10))\n\n(binding [t 1]\n (addt))\n=> 11","created-at":1326330032000,"updated-at":1326330097000,"_id":"542692d2c026201cdc326f55"},{"body":"; You can set! bindings. Useful in a stateful programming.\nuser=> (def ^:dynamic d)\n#'user/d\nuser=> d\n#\nuser=> (binding [d 0] (prn d) (set! d 1) (prn d))\n0\n1\nnil\nuser=> d\n#\n\n; Note that you can't use set! outside of binding [] \"stack\":\n(set! d 1) ; => ...Can't change/establish root binding...\n; You can use set! anywhere under binding [] \"stack\", including from lazy sequences:\n(defn set-d [v] (set! d v))\n(binding [d 0] (set-d 1) (prn d)) ;=> 1\n(first (binding [d 0] (set-d 1) (repeat d)) ) ;=> 1\n; But NOT from delay/force:\n(force (binding [d 0] (set-d 1) (delay d)) ) ;=> ...clojure.lang.Var$Unbound...","author":{"login":"kimtg","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7685905?v=3"},"created-at":1425741813941,"updated-at":1546186846359,"editors":[{"login":"kimtg","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7685905?v=3"},{"avatar-url":"https://avatars2.githubusercontent.com/u/4270240?v=4","account-source":"github","login":"peter-kehl"},{"login":"green-coder","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/598193?v=4"}],"_id":"54fb17f5e4b01ed96c93c883"},{"body":"; Speed test. recur is the preferred way.\nuser=> (def a (atom 0))\n#'user/a\nuser=> (def ^:dynamic b)\n#'user/b\nuser=> (def d)\n#'user/d\nuser=> (time (loop [r 0] (when (< r 10000000) (recur (inc r)))))\n\"Elapsed time: 8.062612 msecs\"\nnil\nuser=> (time (dotimes [_ 10000000] (reset! a 1)))\n\"Elapsed time: 93.428704 msecs\"\nnil\nuser=> (time (binding [b 0] (dotimes [_ 10000000] (set! b 1))))\n\"Elapsed time: 484.331821 msecs\"\nnil\nuser=> (time (with-local-vars [w 0] (dotimes [_ 10000000] (var-set w 1))))\n\"Elapsed time: 490.598696 msecs\"\nnil\nuser=> (time (dotimes [_ 10000000] (def d 1)))\n\"Elapsed time: 2154.646688 msecs\"\nnil\n","author":{"login":"kimtg","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7685905?v=3"},"created-at":1425742394706,"updated-at":1425747333974,"editors":[{"login":"kimtg","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7685905?v=3"}],"_id":"54fb1a3ae4b0b716de7a6534"},{"editors":[{"login":"coldnew","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/39703?v=3"},{"avatar-url":"https://avatars.githubusercontent.com/u/4142015?v=3","account-source":"github","login":"bkovitz"}],"body":";; You can modify the variable inside a binding, \n;; inside a let, you can't.\n\n(def ^:dynamic z)\n\n(binding [z nil]\n (doseq [x (range 4) y (range 4)]\n (set! z [x y]))\n z)\n\n; => [3 3]\n\n;; You can modify the variable inside a for, with dorun.\n\n(binding [z nil]\n (dorun\n (for [x (range 4) y (range 4)]\n (set! z [x y])))\n z)\n\n; => [3 3]","author":{"avatar-url":"https://avatars.githubusercontent.com/u/39703?v=3","account-source":"github","login":"coldnew"},"created-at":1446002313487,"updated-at":1461711689159,"_id":"56303e89e4b0290a56055d15"},{"editors":[{"login":"tizac","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1741276?v=3"}],"body":";; from stackoverflow http://stackoverflow.com/questions/1523240/let-vs-binding-in-clojure\n;; let creates a lexically scoped immutable alias for some value. \n;; binding creates a dynamically scoped binding for some Var.\n\n;; Dynamic binding means that the code inside your binding form and any code \n;; which that code calls (even if not in the local lexical scope) will see the new binding.\n\nuser> (def ^:dynamic x 0)\n#'user/x\n\n;; Lexical vs. dynamic binding:\n\nuser> (defn foo [] (println x))\n#'user/foo\nuser> (binding [x 1] (foo))\n1\nnil\nuser> (let [x 1] (foo))\n0\nnil","author":{"avatar-url":"https://avatars.githubusercontent.com/u/1741276?v=3","account-source":"github","login":"tizac"},"created-at":1463969516607,"updated-at":1463969570676,"_id":"574266ece4b0a1a06bdee498"},{"updated-at":1468290506436,"created-at":1468290319127,"author":{"login":"eyelidlessness","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/199830?v=3"},"body":";; Beware usage in ClojureScript around asynchronous calls, as the bound\n;; var's original value will be re-established before the async code executes:\n\n(def ^:dynamic *foo* nil)\n\n(binding [*foo* :bar]\n (js/setTimeout\n (fn []\n *foo* ;;=> nil\n ))\n\n;; Also beware *synchronous* usage inside `cljs.test/async`, as the bound\n;; var's original value will not be re-established:\n\n(ns my-ns\n (:require [cljs.test :refer-macros [async deftest is]]))\n\n(def ^:dynamic *foo* nil)\n\n(deftest my-test\n (async done\n (binding [*foo* :bar]\n (done))))\n\n(deftest another-test\n (async done\n (is (nil? *foo*))))\n\n;; FAIL in (another-test)\n;; expected: (nil? *foo*)\n;; actual: (not (nil? :bar))\n\n;; At time of writing, the stable ClojureScript version is 1.9.89.","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/199830?v=3","account-source":"github","login":"eyelidlessness"}],"_id":"5784550fe4b0bafd3e2a049e"},{"updated-at":1556458271939,"created-at":1556458271939,"author":{"login":"Hindol","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/705227?v=4"},"body":";; Re-bind `*in*` so that `read-line` reads from a file instead of stdin.\n;; Taken from here: https://stackoverflow.com/a/24826485/1019491\n\n(with-open [is (clojure.java.io/reader \"/tmp/foo.txt\")]\n (binding [*in* is]\n (println (read-line))))\n\n","_id":"5cc5ab1fe4b0ca44402ef712"},{"updated-at":1565050473837,"created-at":1565050473837,"author":{"login":"stribb","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/7216352?v=4"},"body":";; Seed the random number generator so every invocation comes out the same.\n\n(require '[clojure.data.generators :as gen])\n\n(defn not-random-at-all []\n (let [wordlist '[one two three four five]]\n (binding [gen/*rnd* (java.util.Random. 42)]\n (gen/shuffle wordlist))))\n\n(not-random-at-all)\n;; => [two five one three four]\n(not-random-at-all)\n;; => [two five one three four]\n(not-random-at-all)\n;; => [two five one three four]\n","_id":"5d48c669e4b0ca44402ef791"},{"editors":[{"login":"PEZ","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/30010?v=4"}],"body":";; Beware of lazyness\n(def ^:dynamic *foo* :FOO)\n(defn foo [x] [*foo* x])\n\n;; realized when bindings are reset\n(binding [*foo* :BAR]\n (map foo [1 2 3]))\n=> ([:FOO 1] [:FOO 2] [:FOO 3])\n\n;; force realization while bindings active\n(binding [*foo* :BAR]\n (doall (map foo [1 2 3])))\n=> ([:BAR 1] [:BAR 2] [:BAR 3]) \n\n;; closure `bound-foo` with bindings\n(binding [*foo* :BAR]\n (let [bound-foo (bound-fn [x] (foo x))]\n (map bound-foo [1 2 3])))\n=> ([:BAR 1] [:BAR 2] [:BAR 3]) \n\n;; more convenient closuring\n(binding [*foo* :BAR]\n (let [bound-foo (bound-fn* foo)]\n (map bound-foo [1 2 3])))\n=> ([:BAR 1] [:BAR 2] [:BAR 3]) \n","author":{"avatar-url":"https://avatars.githubusercontent.com/u/30010?v=4","account-source":"github","login":"PEZ"},"created-at":1618243197010,"updated-at":1618346238324,"_id":"60746e7de4b0b1e3652d74c4"},{"updated-at":1741597242017,"created-at":1741597242017,"author":{"login":"ertugrulcetin","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8271291?v=4"},"body":"In ClojureScript, binding won’t work for event handler callbacks.\n\n(binding [*scene* scene]\n (js/console.log *scene*)\n (js/setTimeout (fn []\n (println \"Callback here!\")\n ;; THIS WILL PRINT undefined!\n (js/console.log *scene*)) 2000))","_id":"67ceaa3acd84df5de54e2081"}],"macro":true,"notes":[{"updated-at":1409723156000,"body":"The first example (binding mymax to max) appears to be broken. The last line generates the error:\r\n
    \r\n  IllegalStateException Can't dynamically bind non-dynamic var: clojure.core/max\r\n
    \r\n\r\nI tried inserting (.setDynamic #'max) at the top, and it got rid of the error, but the binding didn't seem to actually happen. I.e. the last line prints 20.\r\n\r\n
    The only way I could get it to work is by redefining max from scratch as dynamic:\r\n\r\n
    \r\n(defn ^:dynamic max\r\n  ([x] x)\r\n  ([x y] (. clojure.lang.Numbers (max x y)))\r\n  ([x y & more]\r\n   (reduce max (max x y) more)))\r\n
    \r\n\r\nAfter THIS the first example succeeds.\r\n\r\n
    The moral of the story - I guess you can't easily bind built-in functions. You need to write your functions with the intention of them being bindable. And I guess the first example should simply be removed?","created-at":1409723015000,"author":{"login":"fordsfords","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/ab6989cb3f3a81269d91a003d45dab25?r=PG&default=identicon"},"_id":"542692edf6e94c697052202f"},{"author":{"login":"NeedMoreDesu","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/3812527?v=4"},"updated-at":1509569062961,"created-at":1509569062961,"body":"So about first example --\n
    \n(defn find-max [x y]\n  (max x y)) ;; => #'user/find-max\n(binding [max clojure.core/min]\n  (find-max 10 20)) ;; Can't dynamically bind non-dynamic var: clojure.core/max\n(def ^:dynamic max clojure.core/max)\n(binding [max clojure.core/min]\n  (find-max 10 20)) ;; => 20\n(defn find-max [x y]\n  (max x y)) ;; => #'user/find-max\n(binding [max clojure.core/min]\n  (find-max 10 20)) ;; => 10\n
    \nLong story short: var needs to be defined `^:dynamic` before you create your function with var being bound here, or else no dynamic building occur (which is intended behavior, I guess).","_id":"59fa3226e4b0a08026c48c8c"},{"author":{"login":"finalfantasia","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2316604?v=4"},"updated-at":1677133081409,"created-at":1677133058906,"body":"There's a great blog post from Chas Emerick about `binding`, [Be Mindful of Clojure's `binding`](https://cemerick.com/blog/2009/11/03/be-mindful-of-clojures-binding.html), that discusses two common pitfalls that one can fall into when using `binding`.","_id":"63f70502e4b08cf8563f4b72"}],"arglists":["bindings & body"],"doc":"binding => var-symbol init-expr\n\n Creates new bindings for the (already-existing) vars, with the\n supplied initial values, executes the exprs in an implicit do, then\n re-establishes the bindings that existed before. The new bindings\n are made in parallel (unlike let); all init-exprs are evaluated\n before the vars are bound to their new values.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/binding"},{"added":"1.0","ns":"clojure.core","name":"partial","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1358904778000,"author":{"login":"Ljos","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/45b996a79abca465acaf6c0f10b0437?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"comp","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ccb"},{"created-at":1358904783000,"author":{"login":"Ljos","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/45b996a79abca465acaf6c0f10b0437?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"juxt","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ccc"},{"created-at":1598161159341,"author":{"login":"berczeck","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/1321842?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"apply","ns":"clojure.core"},"_id":"5f420107e4b0b1e3652d739e"}],"line":2631,"examples":[{"author":{"login":"nipra","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/142529?v=3"},"editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/142529?v=3","account-source":"github","login":"nipra"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":"user=> (def to-english (partial clojure.pprint/cl-format nil \"~@(~@[~R~]~^ ~A.~)\"))\n#'user/to-english\n\nuser=> (to-english 1234567890)\n\"One billion, two hundred thirty-four million, five hundred sixty-seven thousand, eight hundred ninety\"\n","created-at":1279053300000,"updated-at":1285501907000,"_id":"542692cdc026201cdc326ceb"},{"author":{"login":"nipra","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/142529?v=3"},"editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/142529?v=3","account-source":"github","login":"nipra"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"mmwaikar","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/29d36f4c9f39c9f8ff61c07033b13118?r=PG&default=identicon"}],"body":"user=> (def hundred-times (partial * 100))\n#'user/hundred-times\n\nuser=> (hundred-times 5)\n500\n\nuser=> (hundred-times 4 5 6)\n12000\n\nuser=> (def add-hundred (partial + 100))\n#'user/add-hundred\n\nuser=> (add-hundred 5)\n105\n","created-at":1279053544000,"updated-at":1310120171000,"_id":"542692cdc026201cdc326cee"},{"author":{"login":"philos99","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1de5617efb013ca7c9cf8e5646818ffa?r=PG&default=identicon"},"editors":[{"login":"philos99","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1de5617efb013ca7c9cf8e5646818ffa?r=PG&default=identicon"},{"login":"philos99","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1de5617efb013ca7c9cf8e5646818ffa?r=PG&default=identicon"}],"body":"(def subtract-from-hundred (partial - 100))\n\nuser=> (subtract-from-hundred 10) ; same as (- 100 10)\n90\n\nuser=> (subtract-from-hundred 10 20) ; same as (- 100 10 20)\n70","created-at":1317743830000,"updated-at":1318431084000,"_id":"542692d4c026201cdc327023"},{"author":{"login":"mihirmp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a8fd3b9768ad2d1fe09405348276705c?r=PG&default=identicon"},"editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/7412474?v=3","account-source":"github","login":"Lacty"},{"login":"pbalduino","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/32979?v=4"}],"body":"; Maps exponent to coefficient\n; x^3 + 2x + 1\n(def poly (fn [n]\n (cond\n (= 0 n) 1\n (= 1 n) 2\n (= 3 n) 1\n :else 0)))\n\n; Differentiates input by returning a polynomial that is curried\n; 3x^2 + 2\n(defn diff [p]\n (partial (fn [p n] (* (+ 1 n) (p (+ 1 n)))) p))\n\n(poly 3)\n;=> 1\n((diff poly) 3)\n;=> 0\n((diff poly) 2)\n;=> 3\n","created-at":1339255851000,"updated-at":1575656058223,"_id":"542692d4c026201cdc327026"},{"updated-at":1440758720254,"created-at":1440758720254,"author":{"login":"ftravers","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/443507?v=3"},"body":"user=> (defn fun-full [x y] (+ x y))\n;=> # (fun-full 2 3)\n;=> 5\n\nuser=> (def fun-half (partial fun-full 2))\n;=> # (fun-half 3)\n;=> 5\n","_id":"55e03bc0e4b072d7f27980f2"},{"editors":[{"login":"liango2","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/5696817?v=3"}],"body":";;Takes a function f and the normal full arguments is allowed\n\nuser=> (defn add [x y] (+ x y))\n#'user/add\nuser=> (partial add 1 1 )\n#object[clojure.core$partial$fn__4529 0x5eb8fe04 \"clojure.core$partial$fn__4529@5eb8fe04\"]\nuser=> (apply (partial add 1 1 ) nil)\n2\nuser=> ((partial add 1 1 ))\n2\nuser=> ((partial add 1 1 1))\nArityException Wrong number of args (3) passed to: user/add clojure.lang.AFn.throwArity (AFn.java:429)\n\nuser=>","author":{"avatar-url":"https://avatars.githubusercontent.com/u/5696817?v=3","account-source":"github","login":"liango2"},"created-at":1451241930491,"updated-at":1451242239728,"_id":"568031cae4b0e0706e05bd8c"},{"updated-at":1470796972437,"created-at":1470796972437,"author":{"login":"gosukiwi","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/161972?v=3"},"body":"user=> (def add1 (partial + 1))\n#'user/add1\nuser=> (add1)\n;=> 1\nuser=> (add1 2)\n;=> 3\nuser=> (add1 2 3 4)\n;=> 10\nuser=> (= (add1 2 3 4) (+ 1 2 3 4))\n;=> true","_id":"57aa94ace4b0bafd3e2a04d7"},{"editors":[{"login":"Lacty","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7412474?v=3"}],"body":"(def times (partial *))\n\n(times 1) ; -> 1\n\n(times 1 2 3) ; -> 6\n\n(* 1 2 3) ; -> 6\n\n\n(def add-hundred (partial + 100))\n\n(add-hundred 1) ; -> 101\n\n(add-hundred 1 2 3) ; -> 106\n\n(+ 100 1 2 3) ; -> 106","author":{"avatar-url":"https://avatars.githubusercontent.com/u/7412474?v=3","account-source":"github","login":"Lacty"},"created-at":1470811578410,"updated-at":1470811725631,"_id":"57aacdbae4b0bafd3e2a04d8"},{"updated-at":1484410971744,"created-at":1484410971744,"author":{"login":"codxse","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/5813694?v=3"},"body":";; Check if a character is vowel\n\n(def vowel? #(some (partial = %) \"aiueo\"))\n\n(vowel? \\e)\n;;=> true\n\n(vowel? \\c)\n;;=> nil","_id":"587a505be4b09108c8545a5a"},{"updated-at":1494497949851,"created-at":1494497949851,"author":{"login":"abhilater","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/1904958?v=3"},"body":";; apply feeds sequence items as variable args to the conj function\n;; variable args gets converted to list in the function arg and hence conj \n;; adds them as a list\n(apply #(conj [0 1] %&) [2 3 4 5])\n;;=> [0 1 (2 3 4 5)]\n\n;; Partial offers are mechanism to feed the variable args as is to the conj \n;; function effectively like (conj [] 2 3 4 5)\n(apply (partial conj [0 1]) [2 3 4 5])\n;;=> [0 1 2 3 4 5]","_id":"59143a9de4b01f4add58feb4"},{"editors":[{"login":"asifm","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/3958387?v=4"}],"body":";;practical example\n\n(def add-domain\n (partial #(str % \"@clojure.com\")))\n\n(add-domain \"info\")\n;;\"info@clojure.com\"","author":{"avatar-url":"https://avatars0.githubusercontent.com/u/31028993?v=4","account-source":"github","login":"ibercode"},"created-at":1517160889010,"updated-at":1706424706107,"_id":"5a6e09b9e4b0c974fee49d11"},{"updated-at":1518786294793,"created-at":1518786294793,"author":{"login":"ibercode","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/31028993?v=4"},"body":"(defn email-struct\n [username domain]\n (str username \"@\" domain))\n\n(def build-email\n #(partial email-struct %))\n\n((build-email \"info\") \"example.com\")\n;;\"info@example.com\"","_id":"5a86d6f6e4b0316c0f44f8c7"},{"updated-at":1556081366466,"created-at":1556081366466,"author":{"login":"Hindol","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/705227?v=4"},"body":";; partial does not gel well with pure java methods\n\n;; Wrap Java method in Clojure fn\n(defn letter? [ch]\n (Character/isLetter ch))\n\n;; Idiomatic\n(filter letter? \"hello, world!\")\n;; => (\\h \\e \\l \\l \\o \\w \\o \\r \\l \\d)\n\n;; This works\n(filter (partial letter?) \"hello, world!\")\n;; => (\\h \\e \\l \\l \\o \\w \\o \\r \\l \\d)\n\n;; This also works\n(filter #(Character/isLetter %) \"hello, world!\")\n;; => (\\h \\e \\l \\l \\o \\w \\o \\r \\l \\d)\n\n;; This doesn't\n(filter (partial Character/isLetter) \"hello, world!\")\n;; => Unable to find static field: isLetter in class java.lang.Character","_id":"5cbfead6e4b0ca44402ef70f"},{"updated-at":1580488372127,"created-at":1580488372127,"author":{"login":"sulami","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/1843193?v=4"},"body":";; Beware that partial \"bakes in\" the original function and does not look it up\n;; again at call time, which can be confusing when mocking.\n\n(defn foo [] \"hit foo\")\n;; => #'user/foo\n(defn mock [] \"hit the mock\")\n;; => #'user/mock\n(def par (partial foo))\n;; => #'user/par\n(with-redefs-fn {#'foo mock} #(foo))\n;; => \"hit the mock\"\n(with-redefs-fn {#'foo mock} #(par))\n;; => \"hit foo\"","_id":"5e3456b4e4b0ca44402ef82a"},{"editors":[{"login":"jvw-git","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/3646688?v=4"}],"body":";; Partial application by calling partial significantly differs from partial\n;; application by wrapping a function call in an anonymous function.\n\n;; The code representing the to-be-applied function and to-be-applied-to arguments\n;; - with the 'call to partial' approach\n;; - is evaluated exactly once, when the call to partial is evaluated.\n;; - is not evaluated when a call to the resulting function is evaluated.\n;; - with the 'wrapped in an anonymous function' approach\n;; - is not evaluated when the anonymous function is evaluated.\n;; - is evaluated anew each time a call to the anonymous function is evaluated.\n\n;; If there are side effects involved in obtaining the to-be-applied function or\n;; to-be-applied-to arguments (because of with-redefs, this includes referring to a\n;; var by providing a symbol), carefully consider which approach to take.\n\n(defn fetch-processing-fn! [] (prn \"fetching...\") (fn [entity] entity))\n\n(defn load-entity! [id] (prn \"loading...\") :entity)\n\n\n(def top-level-fn-1 (partial (fetch-processing-fn!) (load-entity! 123)))\n;; \"fetching...\" is printed.\n;; \"loading...\" is printed.\n\n(top-level-fn-1)\n;; Nothing is printed.\n\n(top-level-fn-1)\n;; Nothing is printed.\n\n\n(def top-level-fn-2 #((fetch-processing-fn!) (load-entity! 123)))\n;; Nothing is printed.\n\n(top-level-fn-2)\n;; \"fetching...\" is printed.\n;; \"loading...\" is printed.\n\n(top-level-fn-2)\n;; \"fetching...\" is printed.\n;; \"loading...\" is printed.","author":{"avatar-url":"https://avatars0.githubusercontent.com/u/3646688?v=4","account-source":"github","login":"jvw-git"},"created-at":1596472064570,"updated-at":1596697721148,"_id":"5f283b00e4b0b1e3652d7331"}],"notes":[{"updated-at":1385283247000,"body":"This function implements the concept of “[currying](http://en.wikipedia.org/wiki/Currying)â€�.","created-at":1385283247000,"author":{"login":"roryokane","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5b2b185c814bb25f2f95a1152e58f033?r=PG&default=identicon"},"_id":"542692edf6e94c697052200e"}],"arglists":["f","f arg1","f arg1 arg2","f arg1 arg2 arg3","f arg1 arg2 arg3 & more"],"doc":"Takes a function f and fewer than the normal arguments to f, and\n returns a fn that takes a variable number of additional args. When\n called, the returned function calls f with args + additional args.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/partial"},{"ns":"clojure.core","name":"chunked-seq?","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1443935187252,"author":{"login":"devn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"chunk","ns":"clojure.core"},"_id":"5610b3d3e4b08e404b6c1c97"},{"created-at":1443935201452,"author":{"login":"devn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"chunk-first","ns":"clojure.core"},"_id":"5610b3e1e4b08e404b6c1c98"},{"created-at":1443935208310,"author":{"login":"devn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"chunk-rest","ns":"clojure.core"},"_id":"5610b3e8e4b08e404b6c1c99"},{"created-at":1443935214143,"author":{"login":"devn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"chunk-buffer","ns":"clojure.core"},"_id":"5610b3eee4b0686557fcbd46"},{"created-at":1443935221866,"author":{"login":"devn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"chunk-next","ns":"clojure.core"},"_id":"5610b3f5e4b0686557fcbd47"}],"line":717,"examples":[{"updated-at":1694176864286,"created-at":1335431382000,"body":"user=> (chunked-seq? (range 1000))\ntrue\n\nuser=> (chunked-seq? (range))\nfalse\n\nuser=> (chunked-seq? (seq (range 1000)))\ntrue\n\nuser=> (chunked-seq? (iterate inc 10))\nfalse\n\nuser=> (chunked-seq? (seq (iterate inc 10)))\nfalse","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/1639862?v=4","account-source":"github","login":"BrunoBonacci"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3","account-source":"github","login":"devn"},"_id":"542692d2c026201cdc326f60"}],"notes":null,"arglists":["s"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core/chunked-seq_q"},{"added":"1.3","ns":"clojure.core","name":"find-keyword","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1430167074779,"author":{"login":"ljosa","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/197881?v=3"},"to-var":{"ns":"clojure.core","name":"keyword","library-url":"https://github.com/clojure/clojure"},"_id":"553e9e22e4b01bb732af0a88"},{"created-at":1430167092343,"author":{"login":"ljosa","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/197881?v=3"},"to-var":{"ns":"clojure.core","name":"name","library-url":"https://github.com/clojure/clojure"},"_id":"553e9e34e4b01bb732af0a89"},{"created-at":1430167188442,"author":{"login":"ljosa","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/197881?v=3"},"to-var":{"ns":"clojure.core","name":"keyword?","library-url":"https://github.com/clojure/clojure"},"_id":"553e9e94e4b06eaacc9cda7d"},{"created-at":1430167194731,"author":{"login":"ljosa","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/197881?v=3"},"to-var":{"ns":"clojure.core","name":"symbol","library-url":"https://github.com/clojure/clojure"},"_id":"553e9e9ae4b01bb732af0a8a"},{"created-at":1430167201482,"author":{"login":"ljosa","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/197881?v=3"},"to-var":{"ns":"clojure.core","name":"intern","library-url":"https://github.com/clojure/clojure"},"_id":"553e9ea1e4b06eaacc9cda7e"}],"line":627,"examples":[{"body":"user=> (find-keyword \"a\")\nnil\nuser=> :a\n:a\nuser=> (find-keyword \"a\")\n:a","author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"created-at":1422932628869,"updated-at":1422932628869,"_id":"54d03a94e4b081e022073c45"}],"notes":null,"tag":"clojure.lang.Keyword","arglists":["name","ns name"],"doc":"Returns a Keyword with the given namespace and name if one already\n exists. This function will not intern a new keyword. If the keyword\n has not already been interned, it will return nil. Do not use :\n in the keyword strings, it will be added automatically.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/find-keyword"},{"added":"1.0","ns":"clojure.core","name":"replicate","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1385848235000,"author":{"login":"Alexey Tarasevich","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/43e0398b89022d32b43de4c968069312?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"repeat","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d08"}],"line":3029,"examples":[{"author":{"login":"zmila","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/68dd6f50915854aa04fefcf4d6fa5c8e?r=PG&default=identicon"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":"user=> (apply str (replicate 7 \\space))\n ; 7 spaces\n\nuser=> (replicate 7 (rand-int 10))\n(3 3 3 3 3 3 3) ; the same number","created-at":1281549294000,"updated-at":1332950215000,"_id":"542692c9c026201cdc326a82"}],"deprecated":"1.3","notes":[{"updated-at":1281553461000,"body":"Note that `replicate` is obsolete. It's functionality is now available via the two-arg arity form of [`repeat`](http://clojuredocs.org/v/1578).","created-at":1281553461000,"author":{"login":"kotarak","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5db30f607f0b5fa70d690311aa3bfd3b?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521f94"}],"arglists":["n x"],"doc":"DEPRECATED: Use 'repeat' instead.\n Returns a lazy seq of n xs.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/replicate"},{"added":"1.0","ns":"clojure.core","name":"min-key","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1371841141000,"author":{"login":"adereth","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5ad11b4e208a6cdb3bd45fe01dea59b7?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"min","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521df4"},{"created-at":1371841145000,"author":{"login":"adereth","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5ad11b4e208a6cdb3bd45fe01dea59b7?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"max-key","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521df5"}],"line":5062,"examples":[{"updated-at":1672874240930,"created-at":1280009320000,"body":";; we have a list of key colours\n;; We want to find the one closest to a supplied colour\n;; We're storing rgb values as [r g b]\n;; use min-key to find colour that minimizes \n;; the euclidean distance between the supplied colour \n;; and each key colour\n;; thanks to rhudson, raek and mfex on #clojure\n\n(defn distance-squared\n \"Euclidean distance between two collections considered as coordinates\"\n [c1 c2]\n (->> (map - c1 c2) (map #(* % %)) (reduce +)))\n\n(def key-colours\n {[224 41 224] :purple\n [24 180 46] :green\n [12 129 245] :blue\n [254 232 23] :yellow\n [233 233 233] :white\n [245 27 55] :red\n [231 119 41] :orange\n })\n\n(defn rgb-to-key-colour\n \"Find colour in colour map closest to the supplied [r g b] triple\"\n [rgb-triple colour-map]\n (colour-map\n (apply min-key (partial distance-squared rgb-triple) (keys colour-map))))\n\nuser=> (rgb-to-key-colour [255 0 0] key-colours)\n:red\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"login":"jimberry1","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/73443103?v=4"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/583358786e336bb14a400ca17722ec3b?r=PG&default=identicon","account-source":"clojuredocs","login":"lozh"},"_id":"542692ccc026201cdc326ca7"},{"author":{"login":"jamesqiu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bc1268deaa7f2e78fe2b5ea76e6481d8?r=PG&default=identicon"},"editors":[{"login":"jamesqiu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bc1268deaa7f2e78fe2b5ea76e6481d8?r=PG&default=identicon"}],"body":"; \"min-key\"/\"max-key\" to \"min\"/\"max\" like \"sort-by\" to \"sort\"\n(min-key #(Math/abs %) -3 1 4)\n; 1\n\n(apply min-key #(Math/abs %) [-3 1 4])\n; 1\n","created-at":1311522786000,"updated-at":1328006403000,"_id":"542692ccc026201cdc326ca9"},{"updated-at":1593445838944,"created-at":1593445838944,"author":{"login":"guillaume","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/368?v=4"},"body":"user=> (min-key second [\"Jon\" 1] [\"Rich\" 6] [\"Nancy\" 3])\n[\"Jon\" 1]","_id":"5efa0dcee4b0b1e3652d731a"}],"notes":null,"arglists":["k x","k x y","k x y & more"],"doc":"Returns the x for which (k x), a number, is least.\n\n If there are multiple such xs, the last one is returned.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/min-key"},{"added":"1.5","ns":"clojure.core","name":"reduced","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1416151548299,"author":{"login":"ljos","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/585174?v=2"},"to-var":{"ns":"clojure.core","name":"reduce","library-url":"https://github.com/clojure/clojure"},"_id":"5468c1fce4b0dc573b892fd4"},{"created-at":1416151556515,"author":{"login":"ljos","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/585174?v=2"},"to-var":{"ns":"clojure.core","name":"reduced?","library-url":"https://github.com/clojure/clojure"},"_id":"5468c204e4b03d20a10242ab"},{"created-at":1456683943617,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"unreduced","ns":"clojure.core"},"_id":"56d33ba7e4b02a6769b5a4ba"},{"created-at":1464286469066,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"ensure-reduced","ns":"clojure.core"},"_id":"57473d05e4b0af2c9436d1f3"}],"line":2853,"examples":[{"body":";; Suppose you want to short-circuit a sum like:\n(reduce (fn [a v] (+ a v)) (range 10))\n;;=> 45\n\n;; So that it returns the sum of the integers if less than 100:\n(reduce (fn [a v] (if (< a 100) (+ a v) (reduced :big))) (range 10))\n;;=> 45\n\n;; But the keyword :big otherwise:\n(reduce (fn [a v] (if (< a 100) (+ a v) (reduced :big))) (range 20))\n;;=> :big\n\n;; The value returned by (reduced :big) short-circuits the reduction so that \n;; it returns the wrapped value without ranging over the entire sequence.\n;; This is useful for infinite lazy sequences:\n(reduce (fn [a v] (if (< a 100) (+ a v) (reduced :big))) (range))\n;;=>:big\n\n;; Which would otherwise not terminate.","author":{"login":"silasdavis","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/99715?v=2"},"created-at":1412246795536,"updated-at":1495285680591,"editors":[{"avatar-url":"https://avatars1.githubusercontent.com/u/4996067?v=3","account-source":"github","login":"matanster"}],"_id":"542d2d0be4b05f4d257a2985"},{"updated-at":1516387837196,"created-at":1447889898907,"author":{"login":"teymuri","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/13352033?v=3"},"body":";;re-implementing (some) using (reduce) and (reduced):\n\n(defn resome [pred koll]\n (reduce (fn [_ c] (when-let [x (pred c)] (reduced x)))\n nil koll))\n\n;;user> (resome #{4} [3 4 2 3 2])\n;;>>> 4\n;;user> (resome even? [3 41 25 3 2])\n;;>>> true\n;;user> (resome even? [3 41 25 3 27])\n;;>>> nil","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/13352033?v=3","account-source":"github","login":"teymuri"},{"login":"functor-soup","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/6382230?v=3"},{"avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4","account-source":"github","login":"bfontaine"},{"login":"featheredtoast","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1322534?v=4"}],"_id":"564d0beae4b0be225c0c4795"},{"updated-at":1545247173119,"created-at":1545247173119,"author":{"login":"TravisHeppner","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/9536486?v=4"},"body":";;note the return from f must be from reduced for reduce to terminate early.\n\n;;no early termination as the return of f is nil\n(reduce (fn f [a b]\n (when (> b 2)\n (reduced \"Done early!\"))\n (println b)) [1 2 3 4 5])\n;;2\n;;3\n;;4\n;;5\n;;=> nil\n\n;;early termination as the return of f is \"Done early!\" wrapped in a reduce object.\n(reduce (fn f [a b]\n (if (> b 2)\n (reduced \"Done early!\")\n (println b))) [1 2 3 4 5])\n;;2\n;;=> \"Done early!\"","_id":"5c1a99c5e4b0ca44402ef5ee"}],"notes":null,"arglists":["x"],"doc":"Wraps x in a way such that a reduce will terminate with the value x","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/reduced"},{"added":"1.0","ns":"clojure.core","name":"char-escape-string","file":"clojure/core_print.clj","type":"var","column":1,"see-alsos":[{"created-at":1375209851000,"author":{"login":"alilee","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2fb0196dc5a7cd3a5cc73f1b9941c209?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"char-name-string","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cd9"},{"created-at":1534950301941,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"escape","ns":"clojure.string"},"_id":"5b7d7b9de4b00ac801ed9e6b"}],"line":200,"examples":[{"author":{"login":"shockbob","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon"},"editors":[],"body":";; simple examples\n\nuser=> (char-escape-string \\newline)\n\"\\\\n\"\nuser=> (char-escape-string \\c) ; no escape sequence for 'c'\nnil\nuser=> (char-escape-string \\tab)\n\"\\\\t\"\nuser=> (char-escape-string \\backspace)\n\"\\\\b\"\nuser=>","created-at":1313928437000,"updated-at":1313928437000,"_id":"542692c7c026201cdc3269b6"},{"updated-at":1534950256834,"created-at":1534950256834,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"body":"(require '[clojure.string :as s])\n\n;; Would like to print \"s\" as shown literally:\n(def s \"Type backslash-t '\\t' followed by backslash-n '\\n'\")\n\n;; This doesn't work, as \\t and \\n are interpreted:\n(println s)\n;; Type backslash-t ' ' followed by backslash-n '\n;; '\n\n;; Use with escape to print literally:\n(println (s/escape s char-escape-string))\n;; Type backslash-t '\\t' followed by backslash-n '\\n'","_id":"5b7d7b70e4b00ac801ed9e6a"}],"notes":null,"tag":"java.lang.String","arglists":[],"doc":"Returns escape string for char or nil if none","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/char-escape-string"},{"added":"1.0","ns":"clojure.core","name":"re-matches","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1324028223000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.core","name":"re-find","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d06"},{"created-at":1379040151000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.core","name":"subs","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d07"},{"created-at":1432238328876,"author":{"login":"bobpoekert","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/45596?v=3"},"to-var":{"ns":"clojure.core","name":"re-groups","library-url":"https://github.com/clojure/clojure"},"_id":"555e38f8e4b01ad59b65f4d9"},{"created-at":1521975114344,"author":{"login":"witek","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/209520?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"re-pattern","ns":"clojure.core"},"_id":"5ab77f4ae4b045c27b7fac24"}],"line":4939,"examples":[{"author":{"login":"ysph","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/eed512f3595f1baa31fd91f3b297ebbf?r=PG&default=identicon"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":";; The distinction is that re-find tries to find _any part_ of the string\n;; that matches the pattern, but re-matches only matches if the _entire_\n;; string matches the pattern.\nuser=> (re-matches #\"hello\" \"hello, world\")\nnil\n\nuser=> (re-matches #\"hello.*\" \"hello, world\")\n\"hello, world\"\n\nuser=> (re-matches #\"hello, (.*)\" \"hello, world\")\n[\"hello, world\" \"world\"]\n","created-at":1294394717000,"updated-at":1324028606000,"_id":"542692c8c026201cdc3269eb"},{"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"editors":[],"body":";; Note: See clojure.core/subs for discussion of behavior of substrings\n;; holding onto references of the original strings, which can\n;; significantly affect your memory usage in some cases.","created-at":1379040148000,"updated-at":1379040148000,"_id":"542692d4c026201cdc32704f"},{"author":{"login":"cloojure","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1ad3de25d00d953de6e8c82f554cdbf5?r=PG&default=identicon"},"editors":[{"login":"cloojure","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1ad3de25d00d953de6e8c82f554cdbf5?r=PG&default=identicon"},{"login":"cloojure","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1ad3de25d00d953de6e8c82f554cdbf5?r=PG&default=identicon"},{"login":"cloojure","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1ad3de25d00d953de6e8c82f554cdbf5?r=PG&default=identicon"}],"body":"; Regex match flags can be embedded in the regex string. So, we can convert the normal case-sensitive matching into case-insensitive matching.\n\nuser=> (re-matches #\"hello\" \"HELLO\") ; case-sensitive\nnil\n\nuser=> (re-matches #\"(?i)hello\" \"hello\") ; case-insensitive\n\"hello\"\nuser=> (re-matches #\"(?i)hello\" \"HELLO\") ; case-insensitive\n\"HELLO\"\nuser=> (re-matches #\"(?i)HELLO\" \"heLLo\") ; case-insensitive\n\"heLLo\"\n","created-at":1399524098000,"updated-at":1399524286000,"_id":"542692d4c026201cdc327050"}],"notes":[{"author":{"login":"caumond","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/11491686?v=4"},"updated-at":1615713542191,"created-at":1615713542191,"body":"Here is the [java official documentation](https://docs.oracle.com/en/java/javase/15/docs/api/java.base/java/util/regex/Pattern.html) for pattern specifications","_id":"604dd506e4b0b1e3652d748e"}],"arglists":["re s"],"doc":"Returns the match, if any, of string to pattern, using\n java.util.regex.Matcher.matches(). Uses re-groups to return the\n groups.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/re-matches"},{"added":"1.0","ns":"clojure.core","name":"array-map","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1283650361000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"assoc","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c4c"},{"created-at":1397668962000,"author":{"login":"ryo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3f7913b563c72083c74030d928ba407e?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"hash-map","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c4d"},{"created-at":1397668975000,"author":{"login":"ryo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3f7913b563c72083c74030d928ba407e?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"sorted-map","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c4e"}],"line":4405,"examples":[{"author":{"login":"Jacolyte","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1703a0c3ed358b787f4b1bf3b2799472?r=PG&default=identicon"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":"user=> (array-map [1 2] [3 4 5])\n{[1 2] [3 4 5]}","created-at":1280205415000,"updated-at":1332949878000,"_id":"542692cec026201cdc326d8c"},{"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"editors":[{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":"user=> (array-map :a 10)\n{:a 10}\n\nuser=> (array-map :a 10 :b 20)\n{:a 10 :b 20}\n\nuser=> (apply array-map [:a 10 :b 20 :c 30])\n{:a 10 :b 20 :c 30}\n\nuser=> (apply assoc {} [:a 10 :b 20 :c 30]) ;same result using assoc\n{:a 10 :b 20 :c 30}\n","created-at":1283649638000,"updated-at":1285492106000,"_id":"542692cec026201cdc326d8e"},{"updated-at":1463365462869,"created-at":1303524077000,"body":"user=> (keys (assoc (array-map :foo 10 :bar 20) :baz 30))\n(:baz :foo :bar)\n; baz is first; :foo and :bar follow the order given to array-map\n\n\n;; My results have consistently been different from what's listed above.\nuser=> (keys (assoc (array-map :foo 10 :bar 20) :baz 30))\n; => (:foo :bar :baz)\nuser=> (assoc (array-map :foo 10 :bar 20) :baz 30)\n; => {:foo 10, :bar 20, :baz 30}\nuser=> *clojure-version*\n; => {:major 1, :minor 8, :incremental 0, :qualifier nil}\n;; As long as I have an array map, new items get added to the end, not\n;; the beginning.","editors":[{"login":"TradeIdeasPhilip","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/18409827?v=3"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/d28543d134185d12d4006a74738d233e?r=PG&default=identicon","account-source":"clojuredocs","login":"steveminer"},"_id":"542692cec026201cdc326d93"},{"updated-at":1463365157869,"created-at":1463365157869,"author":{"login":"TradeIdeasPhilip","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/18409827?v=3"},"body":";; Sometimes Clojure will automatically choose between a hash map and\n;; an array map. What's the rule? Let's try a few experiments.\n\n;; Start with a quick way to make a map with N items.\nuser=> (defn make-map [count] (zipmap (range count) (range count)))\n;; => #'user/make-map\nuser=> (make-map 3)\n;; => {0 0, 1 1, 2 2}\n\n;; Try a few maps. The cutoff seems to be 9.5. If you have fewer than\n;; 9.5 items you get an array map. If you have more than 9.5 items you\n;; get a hash map.\nuser=> (type (make-map 8))\n;; => clojure.lang.PersistentArrayMap\nuser=> (type (make-map 9))\n;; => clojure.lang.PersistentArrayMap\nuser=> (type (make-map 10))\n;; => clojure.lang.PersistentHashMap\nuser=> (type (make-map 11))\n;; => clojure.lang.PersistentHashMap\n\n;; Using assoc we get similar results. 9 or fewer items yields an array\n;; map. 10 or more yields a hash map.\nuser=> (type (assoc (make-map 9) :x 1)) ; 10 items -> hash map.\n;; => clojure.lang.PersistentHashMap\nuser=> (type (assoc (make-map 8) :x 1)) ; 9 items -> array map.\n;; => clojure.lang.PersistentArrayMap\nuser=> (type (assoc (make-map 8) :x 1 :y 2)) ; 10 items -> hash map.\n;; => clojure.lang.PersistentHashMap\nuser=> (type (assoc (assoc (make-map 8) :x 1) :y 2)) ; 10 items -> hash map.\n;; => clojure.lang.PersistentHashMap\n\n;; But when we use { and } to create a map, the cutoff seems to move to 8.5.\n;; A map with 9 items created with assoc or zipmap would be an array map,\n;; but a map with 9 items created by { } is a hash map.\nuser=> (type {0 0, 1 1, 2 2, 3 3, 4 4, 5 5, 6 6, 7 7}) ; 8 items -> array map.\n;; => clojure.lang.PersistentArrayMap\nuser=> (type {0 0, 1 1, 2 2, 3 3, 4 4, 5 5, 6 6, 7 7, 8 8}) ; 9 items -> hash\n;; => clojure.lang.PersistentHashMap\n\n;; Calling dissoc on an array map always yields an array map, regardless of\n;; the size of the map.\n;; Let's start by making a large array map then remove a few items. This will\n;; give us array maps larger than you could create with assoc.\nuser=> (def array20 (apply array-map (range 40)))\n;; => #'user/array20\nuser=> (type array20)\n;; => clojure.lang.PersistentArrayMap\nuser=> (type (dissoc array20 6))\n;; => clojure.lang.PersistentArrayMap\nuser=> (count (dissoc array20 6))\n;; => 19\nuser=> (type (dissoc array20 6 2))\n;; => clojure.lang.PersistentArrayMap\nuser=> (count (dissoc array20 6 2))\n;; => 18\n\n;; Calling dissoc on a hash map always yields another hash map, regardless\n;; of the size of the map.\n;; Let's start by making a large hash map then remove a lot of items. This\n;; will give us hash maps smaller than you could create with assoc.\nuser=> (type (make-map 40))\n;; => clojure.lang.PersistentHashMap\nuser=> (type (apply dissoc (make-map 40) (range 1 80)))\n;; => clojure.lang.PersistentHashMap\nuser=> (count (apply dissoc (make-map 40) (range 1 80)))\n;; => 1\nuser=> (apply dissoc (make-map 40) (range 1 80))\n;; => {0 0}\nuser=> (type (apply dissoc (make-map 40) (range 0 80)))\n;; => clojure.lang.PersistentHashMap\nuser=> (count (apply dissoc (make-map 40) (range 0 80)))\n;; => 0\nuser=> (apply dissoc (make-map 40) (range 0 80))\n;; => {}\n","_id":"57392e25e4b071da7d6cfd0c"},{"editors":[{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"}],"body":";; Maybe you generated a sequence of kv pairs\n(def kvs [[:a 1] [:b 2] [:c 3] [:d 4] [:e 5] [:f 6] [:g 7] [:h 8] [:i 9]])\n\n;; A naïve approach to putting into an array-map…\n(into (array-map) kvs)\n;; => {:e 5, :g 7, :c 3, :h 8, :b 2, :d 4, :f 6, :i 9, :a 1}\n;; …loses order\n(type *1)\n;; => clojure.lang.PersistentHashMap\n\n;; This approach…\n(apply array-map (sequence cat kvs))\n;; => {:a 1, :b 2, :c 3, :d 4, :e 5, :f 6, :g 7, :h 8, :i 9}\n;; …preserves order\n(type *1)\n;; => clojure.lang.PersistentArrayMap","author":{"avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4","account-source":"github","login":"tomdl89"},"created-at":1659043605194,"updated-at":1682634761186,"_id":"62e2ff15e4b0b1e3652d7631"}],"notes":[{"updated-at":1280205606000,"body":"The definition is kind of short, IMO. More descriptively, `array-map` creates a mapping with arrays being the keys and the values. It doesn't seem like `array-map` cares whether or not the keys/values are arrays, although it doesn't seem to like sequences.","created-at":1280205606000,"author":{"login":"Jacolyte","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1703a0c3ed358b787f4b1bf3b2799472?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521f8d"},{"updated-at":1303523878000,"body":"An array-map maintains the insertion order of the keys. Look up is linear, which is not a problem for small maps (say less than 10 keys). If your map is large, you should use hash-map instead. \r\n\r\nWhen you assoc onto an existing array-map, the result is a new array-map with the new key as the first key. The rest of the keys are in the same order as the original. Functions such as seq and keys will respect the key order. \r\n\r\nNote that assoc will decide to return a hash-map if the result is too big to be efficient.

    \r\n","created-at":1303523878000,"author":{"login":"steveminer","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d28543d134185d12d4006a74738d233e?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fba"}],"arglists":["","& keyvals"],"doc":"Constructs an array-map. If any keys are equal, they are handled as\n if by repeated uses of assoc.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/array-map"},{"added":"1.3","ns":"clojure.core","name":"unchecked-byte","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1496262162534,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"byte","ns":"clojure.core"},"_id":"592f2612e4b06e730307db1c"}],"line":3542,"examples":[{"body":"user=> (unchecked-byte 127)\n127\nuser=> (unchecked-byte 128)\n-128\nuser=> (unchecked-byte 255)\n-1\nuser=> (unchecked-byte 256)\n0\nuser=> (unchecked-byte 257)\n1","author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"created-at":1423522274775,"updated-at":1423522274775,"_id":"54d939e2e4b081e022073c74"},{"updated-at":1496262153952,"created-at":1496262153952,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"body":"(unchecked-byte 1)\n;;=> 1\n(unchecked-byte 1N)\n;;=> 1\n(unchecked-byte 1.1)\n;;=> 1\n(unchecked-byte 1.9)\n;;=> 1\n(unchecked-byte 5/3)\n;;=> 1\n\n(unchecked-byte -1)\n;;=> -1\n(unchecked-byte -1N)\n;;=> -1\n(unchecked-byte -1.1)\n;;=> -1\n(unchecked-byte -1.9)\n;;=> -1\n(unchecked-byte -5/3)\n;;=> -1\n\n;;;; Note that (unchecked-byte) does not range check its argument\n;;;; so integer overflow or rounding may occur. \n;;;; Use (byte) if you want to throw an exception in such cases.\n\n(unchecked-byte 128)\n;;=> -128\n(unchecked-byte -129)\n;;=> 129\n\n(byte 128)\n;;=> IllegalArgumentException Value out of range for byte: 128\n(byte -129)\n;;=> IllegalArgumentException Value out of range for byte: -129\n\n(unchecked-byte 1.0E2)\n;;=> 100\n(unchecked-byte 1.0E3)\n;;=> -24\n\n(byte 1.0E2)\n;;=> 100\n(byte 1.0E3)\n;;=> IllegalArgumentException Value out of range for byte: 1000.0","_id":"592f2609e4b06e730307db1b"}],"notes":null,"arglists":["x"],"doc":"Coerce to byte. Subject to rounding or truncation.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/unchecked-byte"},{"added":"1.0","ns":"clojure.core","name":"with-local-vars","file":"clojure/core.clj","type":"macro","column":1,"see-alsos":[{"created-at":1374310504000,"author":{"login":"alilee","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2fb0196dc5a7cd3a5cc73f1b9941c209?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"with-bindings","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cea"},{"created-at":1423524505831,"author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"to-var":{"ns":"clojure.core","name":"var-set","library-url":"https://github.com/clojure/clojure"},"_id":"54d94299e4b081e022073c7d"},{"created-at":1437143798426,"author":{"login":"claj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/353113?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"volatile!","ns":"clojure.core"},"_id":"55a912f6e4b06a85937088aa"},{"created-at":1461815729270,"author":{"login":"cloojure","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7083783?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"var-get","ns":"clojure.core"},"_id":"572189b1e4b0f8c89e75b110"}],"line":4366,"examples":[{"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"editors":[],"body":";; with-local-vars allows you to write more imperative-style code, for cases\n;; where you really want to. factorial isn't a case where it helps, but\n;; it is short and familiar. Note that (var-get acc) can be abbreviated\n;; as @acc\nuser=> (defn factorial [x]\n (with-local-vars [acc 1, cnt x]\n (while (> @cnt 0)\n (var-set acc (* @acc @cnt))\n (var-set cnt (dec @cnt)))\n @acc))\n#'user/factorial\nuser=> (factorial 7)\n5040\n","created-at":1331249053000,"updated-at":1331249053000,"_id":"542692d6c026201cdc3270b9"},{"updated-at":1492497328392,"created-at":1492497328392,"author":{"login":"didibus","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/601540?v=3"},"body":"(with-local-vars [a-local-var-variable \"value\"]\n ;; If you use the symbol by itself, you get the Var back\n (println a-local-var-variable)\n ;; So when using local var variables, you must explicitly\n ;; get the value inside the Var\n (println (var-get a-local-var-variable))\n ;; You can also get the value of a Var by using deref\n (println (deref a-local-var-variable))\n ;; Or the @ reader macro\n (println @a-local-var-variable))","_id":"58f5b3b0e4b01f4add58fe96"},{"updated-at":1567623091068,"created-at":1500198345816,"author":{"login":"char16t","account-source":"github","avatar-url":"https://avatars6.githubusercontent.com/u/5310476?v=4"},"body":";; with-local-vars allows you to write more imperative-style code, for cases\n;; where you really want to. This example demonstrate how to change variable value\n;; like in for-loop. There used doseq instead of for, because `for` is a macro\n;; that generates lazy sequence that will be realized out of ranges\n;; with-local-vars block \n(with-local-vars [n 0] \n (doseq [x (range 3)]\n (do (var-set n (inc (var-get n)))\n (println (var-get n)))))\n; 1\n; 2\n; 3\n;=> nil\n","editors":[{"avatar-url":"https://avatars6.githubusercontent.com/u/5310476?v=4","account-source":"github","login":"char16t"},{"login":"cloojure","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/7083783?v=4"}],"_id":"596b35c9e4b0d19c2ce9d6fc"}],"macro":true,"notes":null,"arglists":["name-vals-vec & body"],"doc":"varbinding=> symbol init-expr\n\n Executes the exprs in a context in which the symbols are bound to\n vars with per-thread bindings to the init-exprs. The symbols refer\n to the var objects themselves, and must be accessed with var-get and\n var-set","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/with-local-vars"},{"added":"1.0","ns":"clojure.core","name":"ns-imports","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1288055178000,"author":{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},"to-var":{"ns":"clojure.core","name":"ns-map","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e00"}],"line":4226,"examples":[{"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"editors":[],"body":"user> (ns-imports 'clojure.core)\n{ClassVisitor clojure.asm.ClassVisitor, ProcessBuilder java.lang.ProcessBuilder, Enum java.lang.Enum, SuppressWarnings java.lang.SuppressWarnings, Throwable java.lang.Throwable, InterruptedException ...chop...}","created-at":1288074884000,"updated-at":1288074884000,"_id":"542692ccc026201cdc326c68"}],"notes":null,"arglists":["ns"],"doc":"Returns a map of the import mappings for the namespace.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/ns-imports"},{"added":"1.0","ns":"clojure.core","name":"send-off","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1282635172000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"send","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e37"},{"created-at":1282635178000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"agent","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e38"},{"created-at":1282635185000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"shutdown-agents","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e39"},{"created-at":1614551206060,"author":{"login":"Crowbrammer","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/19522656?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"send-via","ns":"clojure.core"},"_id":"603c18a6e4b0b1e3652d7468"}],"line":2139,"examples":[{"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"editors":[{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},{"login":"sfreund","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a288ab5288d2c86c37f8ae3aaa133b1a?r=PG&default=identicon"},{"login":"sfreund","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a288ab5288d2c86c37f8ae3aaa133b1a?r=PG&default=identicon"},{"login":"fordsfords","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7671908?v=3"}],"body":"user=> (def my-agent (agent \"\"))\n#'user/my-agent\nuser=> @my-agent\n\"\"\n\n;; Note the following happens asynchronously in a thread\n;; pool\nuser=> (send-off my-agent #(slurp %2) \"file.txt\")\n#\n\n;; while the slurp is in-progress, @my-agent will return \"\".\n\n;; Once the request has completed, the value will\n;; be updated when we look at it.\nuser=> @my-agent\n\"file contents\"\n","created-at":1285922554000,"updated-at":1417372052900,"_id":"542692c8c026201cdc326a5a"},{"editors":[{"login":"kwladyka","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/3903726?v=3"}],"body":";; send should be used for actions that are CPU limited,\n;; while send-off is appropriate for actions that may block on IO.\n\n;; send is like async/go, send-off is like async/thread\n;; so send use limited pool by CPU for agents to not overload CPU,\n;; while send-off use independent threads without limitations.","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/3903726?v=3","account-source":"github","login":"kwladyka"},"created-at":1496609297326,"updated-at":1496609746458,"_id":"59347211e4b06e730307db22"}],"notes":[{"updated-at":1396535611000,"body":"The example uses \"send\", this is supposed to be an example for \"send-off\".","created-at":1396535611000,"author":{"login":"Benissimo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e580eaf74a5f97c7ea01e0c026221a1d?r=PG&default=identicon"},"_id":"542692edf6e94c6970522022"},{"body":"\"send\" and \"send-off\" are identical in syntax and semantics. The only difference is the thread pool used to dispatch the agent. \"send\" uses a fixed-sized thread pool initialized at startup to contain a few more threads than the number of cores on the host computer. Since \"send\"s thread pool is fixed size, using it to dispatch blocking code can result in all the pool's threads being blocked, and other \"send\"s queued waiting for a thread to finish its work. This can produce artificially low performance, and in rare conditions, can deadlock (if a queued thread is needed to unblock the blocked pool threads).\n\n\"send-off\" uses a separate thread pool which can grow as-needed. I.e. a \"send-off\" request will never be queued waiting for a thread; if the existing pool is empty, a new thread is created. However, if many long-running CPU-bound (not blocking) requests are being submitted, \"send-off\" can be counter-productive; having more CPU-bound threads than cores results in unnecessary scheduling overhead as the threads are timeshared across the cores. \"send\"s limited thread pool produces higher throughput for CPU-bound requests.","created-at":1417371642071,"updated-at":1417372219777,"author":{"login":"fordsfords","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7671908?v=3"},"_id":"547b5ffae4b0dc573b892fe6"}],"arglists":["a f & args"],"doc":"Dispatch a potentially blocking action to an agent. Returns the\n agent immediately. Subsequently, in a separate thread, the state of\n the agent will be set to the value of:\n\n (apply action-fn state-of-agent args)","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/send-off"},{"added":"1.0","ns":"clojure.core","name":"defmacro","file":"clojure/core.clj","type":"macro","column":1,"see-alsos":[{"created-at":1336311079000,"author":{"login":"redraiment","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/33087654dbc710e81f51fda5f8241f28?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"macroexpand","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f7d"},{"created-at":1336311088000,"author":{"login":"redraiment","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/33087654dbc710e81f51fda5f8241f28?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"macroexpand-1","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f7e"},{"created-at":1336311122000,"author":{"login":"redraiment","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/33087654dbc710e81f51fda5f8241f28?r=PG&default=identicon"},"to-var":{"ns":"clojure.walk","name":"macroexpand-all","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f7f"}],"line":446,"examples":[{"author":{"login":"Kototama","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a54a4dc204925d397ca010b9a332e74d?r=PG&default=identicon"},"editors":[{"login":"Kototama","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a54a4dc204925d397ca010b9a332e74d?r=PG&default=identicon"},{"login":"kochb","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1012892?v=3"}],"body":"(defmacro with-tree\n \"works on a JTree and restores its expanded paths after executing body\"\n [tree & body]\n `(let [tree# ~tree\n root# (.getRoot (.getModel tree#))\n expanded# (if-let [x# (.getExpandedDescendants\n tree# (TreePath. root#))]\n (enumeration-seq x#)\n ())\n selectionpaths# (. selectionmodel# getSelectionPaths)]\n ~@body\n (doseq [path# expanded#]\n (.expandPath tree# path#))))\n\n;; usage:\n\n(with-tree *one-jtree-instance*\n ;; some code here...\n )","created-at":1286492372000,"updated-at":1421193676346,"_id":"542692ccc026201cdc326c86"},{"author":{"login":"Clinton","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e460563f35b0b25d8671d6ef83f54ce?r=PG&default=identicon"},"editors":[],"body":"(defmacro unless [pred a b]\n `(if (not ~pred) ~a ~b))\n\n;; usage:\n\n(unless false (println \"Will print\") (println \"Will not print\"))","created-at":1327060274000,"updated-at":1327060274000,"_id":"542692d2c026201cdc326f7a"},{"author":{"login":"octopusgrabbus","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/fd31b8bcea99fa7b0711fbc424587774?r=PG&default=identicon"},"editors":[],"body":"(def dbg 1)\n\n(defmacro chk-flagM\n \"Throws an exception if flag does not resolve; else returns flag's value.\"\n [flag]\n (if (not (resolve flag))\n (throw (Exception. (str 'flag \" is not a valid var.\")))\n flag))\n\n(defn write-csv-file\n \"Writes a csv file using a key and an s-o-s\"\n [out-sos out-file]\n\n (if (>= (chk-flagM dbg) 2)\n (println (first out-sos), \"\\n\", out-file))\n\n (spit out-file \"\" :append false)\n (with-open [out-data (io/writer out-file)]\n (csv/write-csv out-data (map #(concat % [\"\"]) out-sos))))\n\n","created-at":1361941726000,"updated-at":1361941726000,"_id":"542692d2c026201cdc326f7b"},{"updated-at":1592919257677,"created-at":1592919257677,"author":{"login":"vale981","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/4025991?v=4"},"body":";; We can implement algebraic infix notation, which is quite handy for\n;; typing in formulas. :-)\n\n(defmacro __\n \"Expands algebraic infix notation to standard clojure forms. Supports\n operator precedence.\"\n [[item op & rst :as lst]]\n (let [item (if (seq? item)\n `(__ ~item)\n item)]\n (if op\n (case op\n (+ -) `(~op ~item (__ ~rst))\n (* /) (let [[next & rst] rst]\n `(__\n ((~op ~item\n ~(if (seq? next)\n `(__ ~next) next)) ~@rst)))\n ;; we already have a clojure form\n lst)\n item)))\n\n(clojure.walk/macroexpand-all '(__ (1 * 2 + 3 * 4 + (1 + 2))))\n;; => (+ (* 1 2) (+ (* 3 4) (+ 1 2)))\n\n;; parens for precedence\n(clojure.walk/macroexpand-all '(__ (1 + 2 * (3 + 4))))\n;; => (+ 1 (* 2 (+ 3 4)))\n\n;; usual clojure notation in the middle of it\n(clojure.walk/macroexpand-all '(__ (1 + 2 * (+ 3 4))))\n;; => (+ 1 (* 2 (+ 3 4)))","_id":"5ef204d9e4b0b1e3652d730e"},{"updated-at":1603447108371,"created-at":1603446989723,"author":{"login":"jimka2001","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/6414129?v=4"},"body":";; The meta data notation `^:dynamic` can be used to force a variable to be dynamic.\n\n(def ^:dynamic *my-dynamic-variable* \"my doc string\" the-initial-value)\n\n;; However, using this notation within a macro does not have the same semantics.\n;; For example the following macro *will not* expand to a definition of a dynamic \n;; variable whose value is a function.\n\n\n(defmacro dyn-fun [name lambda-list & body]. ;; WRONG\n `(def ^:dynamic ~name (fn ~lambda-list ~@body)))\n\n\n;; The macro should be written something like the following.\n\n\n(defmacro dyn-fun [name lambda-list & body]\n `(def ~(with-meta name {:dynamic true}) (fn ~lambda-list ~@body)))\n","editors":[{"avatar-url":"https://avatars1.githubusercontent.com/u/6414129?v=4","account-source":"github","login":"jimka2001"}],"_id":"5f92a8cde4b0b1e3652d73e8"}],"macro":true,"notes":[{"updated-at":1332614198000,"body":"The body of a macro has two implicitly bound symbols: &form and &env. They work like two extra unnamed args. The names begin with '&' to avoid name clashes with normal user-defined symbols. The value of &form is the form of the original macro call before macro expansion. There's useful meta-data on &form. The value of &env is the \"environment\", which is basically a map of lexical bindings. The keys of &env are the lexically bound symbols. The values are internal compiler details, and probably aren't useful for user code.\r\n\r\n\r\nSee also:\r\n[http://blog.jayfields.com/2011/02/clojure-and.html](http://blog.jayfields.com/2011/02/clojure-and.html)","created-at":1332559647000,"author":{"login":"steveminer","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d28543d134185d12d4006a74738d233e?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fdc"},{"updated-at":1348338864000,"body":"Due to syntax-quote resolving symbols (see the [Clojure reader docs](http://clojure.org/reader)), you won't be able to include a regular `let` statement inside a macro, i.e.:\r\n\r\n
    (defmacro m [] `(let [x 1] x))\r\n(m) ; => CompilerException java.lang.RuntimeException: Can't let qualified name: user/x, compiling:(NO_SOURCE_PATH:1)
    \r\n\r\nWe can see why:\r\n\r\n
    (macroexpand-1 '(m)) ; => (clojure.core/let [user/x 1] user/x)
    \r\nThe syntax-quote has resolved `x` to `user/x`—which can't be `let`. This is a good thing, as it's signalling to us that we should use gensyms by appending `#`:\r\n\r\n
    (defmacro m [] `(let [x# 1] x#))\r\n(m) ; => 1\r\n(macroexpand-1 '(m)) ; => (clojure.core/let [x__383__auto__ 1] x__383__auto__)
    ","created-at":1348338864000,"author":{"login":"Arlen","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8bfb3a1eb9879049b4886cd3f9f321c4?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fe7"},{"updated-at":1396943327000,"body":"@Arlen:\r\nIf you want to capture the local variables, or create a non-locally scoped variable, you can prepend them with ~', allow a namespace capture:\r\n\r\n
    (defmacro m [] `(let [~'x 1] ~'x))\r\n(m) ; => 1\r\n(macroexpand-1 '(m)) ; => (clojure.core/let [x 1] x)\r\n
    \r\nuseful, if you desire it.","created-at":1396943283000,"author":{"login":"travis_rodman","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/988e7de687c27107309bebe02aee1984?r=PG&default=identicon"},"_id":"542692edf6e94c6970522024"},{"body":"When debugging macros that use &env, beware that
    clojure.walk/macroexpand-all
    doesn't \"set up\" any symbols. It ignores any symbols from
    (let [...] ...)
    and similar. To test &env, run the macro directly.","created-at":1547117881414,"updated-at":1547117901908,"author":{"avatar-url":"https://avatars2.githubusercontent.com/u/4270240?v=4","account-source":"github","login":"peter-kehl"},"_id":"5c372539e4b0ca44402ef619"},{"body":"```\n(defn foldl\n [p i ss]\n (if (andmap seq ss)\n ;; `recur` is not a procedure\n (recur p (p i (map first ss)) (map rest ss))\n i))\n(defn andmap [p s] (reduce #(and %1 (p %2)) true s))\n(defn seq-of-len?\n [l t n]\n (and (t l) (= n (count l))))\n\n(defmacro for-fold\n \"A macro like for/fold in Racket\"\n [[& accs] [& itrs] & body]\n\n (doseq\n [cl (into `~accs `~itrs)]\n (assert (and (seq-of-len? cl list? 2) (symbol? (first cl))) (str \"Invalid accumulator or iterator:\" cl)))\n\n (let [acc-ids (map first `~accs)\n inits (map second `~accs)\n itr-ids (map first `~itrs)\n seqs (map second `~itrs)\n sym `result#\n len (count `~accs)\n\n all (into acc-ids itr-ids)]\n\n (assert (= (count all) (count (set all)))\n \"Duplicate names\")\n\n `(foldl (fn [[~@acc-ids] [~@itr-ids]]\n (let [~sym (let [] ~@body)]\n (assert (seq-of-len? ~sym vector? ~len) (str \"Invalid result:\" ~sym))\n ~sym))\n [~@inits]\n [~@seqs])))\n\n```","created-at":1720783640888,"updated-at":1720783703839,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/93880182?v=4","account-source":"github","login":"Antigen-1"},"_id":"6691131869fbcc0c226174dc"}],"arglists":["name doc-string? attr-map? [params*] body","name doc-string? attr-map? ([params*] body) + attr-map?"],"doc":"Like defn, but the resulting function name is declared as a\n macro and will be used as a macro by the compiler when it is\n called.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/defmacro"},{"added":"1.3","ns":"clojure.core","name":"every-pred","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1348529552000,"author":{"login":"hugoduncan","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/80fa2a15219b987664e4d6f5c78b4c27?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"some-fn","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bf2"},{"created-at":1422932166689,"author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"to-var":{"ns":"clojure.core","name":"every?","library-url":"https://github.com/clojure/clojure"},"_id":"54d038c6e4b0e2ac61831cf4"}],"line":7588,"examples":[{"updated-at":1335431607000,"created-at":1335431607000,"body":"user=> ((every-pred number? odd?) 3 9 11)\ntrue","editors":[],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3","account-source":"github","login":"devn"},"_id":"542692d2c026201cdc326fa0"},{"editors":[{"login":"daveliepmann","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/974443?v=4"}],"body":"(filter (every-pred pos? ratio?)\n [0 2/3 -2/3 1/4 -1/10 5 3/3])\n=> (2/3 1/4)","author":{"avatar-url":"https://avatars3.githubusercontent.com/u/974443?v=4","account-source":"github","login":"daveliepmann"},"created-at":1549903494471,"updated-at":1551557625726,"_id":"5c61a686e4b0ca44402ef67b"},{"updated-at":1549903552234,"created-at":1549903552234,"author":{"login":"daveliepmann","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/974443?v=4"},"body":"((every-pred string? (comp (partial > 5) count)) \"abc\")\ntrue\n((every-pred string? (comp (partial > 5) count)) \"abcdef\")\nfalse","_id":"5c61a6c0e4b0ca44402ef67c"}],"notes":[{"body":"Careful—every predicate with no arguments is considered true:\n
    \nuser> ((every-pred (constantly false)))\ntrue\nuser> ((every-pred (constantly false)) 1)\nfalse\n
    ","created-at":1468616330948,"updated-at":1468616364083,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/7443?v=3","account-source":"github","login":"harold"},"_id":"57894e8ae4b0bafd3e2a04a3"}],"arglists":["p","p1 p2","p1 p2 p3","p1 p2 p3 & ps"],"doc":"Takes a set of predicates and returns a function f that returns true if all of its\n composing predicates return a logical true value against all of its arguments, else it returns\n false. Note that f is short-circuiting in that it will stop execution on the first\n argument that triggers a logical false result against the original predicates.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/every-pred"},{"added":"1.0","ns":"clojure.core","name":"keys","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1289979132000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"vals","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cef"},{"created-at":1289979143000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"hash-map","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cf0"},{"created-at":1318592870000,"author":{"login":"mmwaikar","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/29d36f4c9f39c9f8ff61c07033b13118?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"key","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cf1"},{"created-at":1470842025768,"author":{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/94482?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"select-keys","ns":"clojure.core"},"_id":"57ab44a9e4b0bafd3e2a04db"}],"line":1570,"examples":[{"author":{"login":"pkolloch","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/10b2fd3c0a4cc46dc241a48468dc551?r=PG&default=identicon"},"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"},{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"}],"body":"(keys {:keys :and, :some :values})\n;;=> (:keys :some)\n\n(keys {})\n;;=> nil\n\n(keys nil)\n;;=> nil","created-at":1280458583000,"updated-at":1423522822893,"_id":"542692c7c026201cdc326951"},{"updated-at":1477296966414,"created-at":1477296966414,"author":{"login":"gzmask","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/132936?v=3"},"body":";; although doc says it only takes a map, this still works:\n(keys (filter (fn [[_ v]] (-> v :t)) {:a {:t true} :b {:t false} :c {:t true}}))\n;;=> (:a :c)","_id":"580dc346e4b001179b66bddb"}],"notes":[{"updated-at":1385457055000,"body":"Functions keys and vals return sequences such that\r\n
    \r\n(= (zipmap (keys m) (vals m)) m)\r\n
    ","created-at":1385457055000,"author":{"login":"akhudek","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/aaf21f137b69cc5154c8afb29b793e18?r=PG&default=identicon"},"_id":"542692edf6e94c6970522010"},{"body":"I noticed that the keys are not always returned in the same order. Usually they are, but not always.","created-at":1443420358374,"updated-at":1443420375336,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/5528061?v=3","account-source":"github","login":"Jarzka"},"_id":"5608d8c6e4b08e404b6c1c8a"},{"author":{"login":"ac1dr3d","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10298138?v=4"},"updated-at":1522928591363,"created-at":1522928591363,"body":"Map with 8 or more keys order are unexpected.","_id":"5ac60bcfe4b045c27b7fac36"}],"arglists":["map"],"doc":"Returns a sequence of the map's keys, in the same order as (seq map).","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/keys"},{"added":"1.0","ns":"clojure.core","name":"rationalize","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":null,"line":1291,"examples":[{"author":{"login":"Miles","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bbb26d2a5e856c4fba0f72c3f7250f3f?r=PG&default=identicon"},"editors":[],"body":"
    \r\nuser=> (rationalize 1.5)\r\n3/2\r\n
    ","created-at":1283819843000,"updated-at":1283819843000,"_id":"542692cbc026201cdc326c27"},{"updated-at":1335430728000,"created-at":1335430728000,"body":"user=> (rationalize Math/PI)\n3141592653589793/1000000000000000\n\nuser=> (rationalize (Math/sqrt 2))\n14142135623730951/10000000000000000","editors":[],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3","account-source":"github","login":"devn"},"_id":"542692d4c026201cdc327049"},{"body":"(rationalize 2/4)\n;; => 1/2\n\n(rationalize 4/2)\n;; => 2\n\n(rationalize 2)\n;; => 2\n\n(rationalize 2.0)\n;; => 2N","author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"created-at":1423041167517,"updated-at":1423041167517,"_id":"54d1e28fe4b0e2ac61831d0c"},{"updated-at":1495120328324,"created-at":1495120328324,"author":{"login":"mhmdsalem1993","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/10787314?v=3"},"body":";; To quickly convert a mixed number to an improper fraction, \n;; multiply the denominator\n;; by the whole number and add to the numerator\n\n(= (+ 20 3/4) (rationalize (/ (+ (* 20 4) 3) 4)))\n;; => true","_id":"591db9c8e4b01920063ee061"}],"notes":[{"updated-at":1388083523000,"body":"Remember that for irrational numbers, like sqrt 2, this is only an estimate (pretty good one). ","created-at":1388083523000,"author":{"login":"wikopl","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/ebf7a80146fda866cb2737cbabf79d63?r=PG&default=identicon"},"_id":"542692edf6e94c6970522017"}],"arglists":["num"],"doc":"returns the rational value of num","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/rationalize"},{"added":"1.0","ns":"clojure.core","name":"load-file","type":"function","see-alsos":[{"created-at":1286271536000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"load","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d3c"},{"created-at":1350073018000,"author":{"login":"AtKaaZ","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e10dfa345f44b0fe72bbe081fd51b83?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"spit","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d3d"},{"created-at":1519290658085,"author":{"login":"witek","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/209520?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"load-string","ns":"clojure.core"},"_id":"5a8e8922e4b0316c0f44f8e9"}],"examples":[{"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"editors":[{"login":"shawnmorel","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/4a701b9e9467b6ccee6b83c698ea6b15?r=PG&default=identicon"},{"login":"Jeff Terrell","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/658b2643cf2a8192286b5bb1ecb62cf8?r=PG&default=identicon"}],"body":";; Very useful from a REPL\n;; Paths are specified as strings using canonical file path notation \n;; (rather than clojure-style namespaces dependent on the JVM classpath).\n;; The working directory is set to wherever you invoked the JVM from, \n;; likely the project root.\n\n(load-file \"src/mylib/core.clj\")\n\n;; now you can go and evaluate vars defined in that file.","created-at":1286271505000,"updated-at":1344912514000,"_id":"542692cdc026201cdc326d3e"},{"author":{"login":"lambder","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1c0c20072f52de3a6335cae183b865f6?r=PG&default=identicon"},"editors":[{"login":"lambder","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1c0c20072f52de3a6335cae183b865f6?r=PG&default=identicon"}],"body":";; file located at src/address_book/core.clj\n;; current dir is src/..\n\n(load-file \"src/address_book/core.clj\")","created-at":1307936530000,"updated-at":1307936548000,"_id":"542692cdc026201cdc326d41"},{"updated-at":1709613053865,"created-at":1313970180000,"body":";; create a clojure file on the fly using spit\n;; then load it into the REPL and use its function\n;; notice the return value is var quote of the last form of file\n\nuser=> (spit \"mycode.clj\" \"(defn doub [x] (* x 2))\")\nnil\nuser=> (load-file \"mycode.clj\")\n#'user/doub\nuser=> (doub 23)\n46\n\n;; Note this is similar to using load-string:\nuser=> (load-string \"(defn doub [x] (* x 2))\")\n#'user/doub","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3","account-source":"github","login":"Dimagog"},{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"},{"avatar-url":"https://avatars.githubusercontent.com/u/24317401?v=4","account-source":"github","login":"loeschzwerg"},{"login":"zenfey","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/6791543?v=4"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon","account-source":"clojuredocs","login":"shockbob"},"_id":"542692cdc026201cdc326d43"}],"notes":[{"updated-at":1350351731000,"body":"

    Be aware that this function is intended to load code only. If your data structures or a string in them grow bigger than around 65,535 it crashes.

    \r\n\r\n

    Exception similar to:

    \r\n
    java.lang.ClassFormatError: Unknown constant tag 49 in class file parse$eval13
    \r\n\r\n

    Please use read-string instead.

    \r\n\r\nExample:
    (read-string (slurp \"data.clj\"))
    \r\n\r\nSource: Google Groups","created-at":1350351731000,"author":{"login":"dedeibel","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e89e54d864f1e584c5ef4102f98bc83?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fee"},{"updated-at":1371613686000,"body":"

    The following marginally helpful error will be thrown if you have a typo in your file:

    \r\n\r\n
    CompilerException java.lang.RuntimeException: Unable to resolve symbol: load-file in this context, compiling:(NO_SOURCE_PATH:1:1)
    \r\n\r\n

    Fix the syntax error(s) in and you'll be able to use load-file again.

    \r\n\r\n\r\n","created-at":1371447277000,"author":{"login":"arkh","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1c6ed9b963d758914c2744befd4974ca?r=PG&default=identicon"},"_id":"542692edf6e94c6970522005"}],"arglists":["name"],"doc":"Sequentially read and evaluate the set of forms contained in the file.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/load-file"},{"added":"1.0","ns":"clojure.core","name":"distinct?","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1396938477000,"author":{"login":"ryo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3f7913b563c72083c74030d928ba407e?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"distinct","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bf7"}],"line":5738,"examples":[{"updated-at":1521560626736,"created-at":1279073728000,"body":"user=> (distinct? 1 2 3)\ntrue\nuser=> (distinct? 1 2 3 3)\nfalse\nuser=> (distinct? 1 2 3 1)\nfalse","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/675861?v=3","account-source":"github","login":"fellipebrito"},{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/147981?v=3","account-source":"github","login":"dpritchett"},"_id":"542692c9c026201cdc326a8f"},{"editors":[{"login":"Crowbrammer","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/19522656?v=4"},{"login":"rmfbarker","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/4708454?v=4"}],"body":"(distinct? ['A 'A 'c]) ;;=> true\n(distinct? 'A 'A 'c) ;;=> false\n(apply distinct? ['A 'A 'c]) ;;=> false\n\n(distinct? [1 1 'c]) ;;=> true\n(distinct? 1 1 'c) ;;=> false\n\n;; Like `min` or `max` and unlike `distinct` the \n;; parameters are taken separately, i.e. not in a \n;; collection. ","author":{"avatar-url":"https://avatars.githubusercontent.com/u/19522656?v=4","account-source":"github","login":"Crowbrammer"},"created-at":1615302123852,"updated-at":1687644700733,"_id":"60478debe4b0b1e3652d747d"}],"notes":null,"tag":"java.lang.Boolean","arglists":["x","x y","x y & more"],"doc":"Returns true if no two of the arguments are =","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/distinct_q"},{"added":"1.9","ns":"clojure.core","name":"pos-int?","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1495640931493,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"neg-int?","ns":"clojure.core"},"_id":"5925ab63e4b093ada4d4d730"},{"created-at":1495640936398,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"nat-int?","ns":"clojure.core"},"_id":"5925ab68e4b093ada4d4d731"},{"created-at":1495705345491,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"int?","ns":"clojure.core"},"_id":"5926a701e4b093ada4d4d74e"}],"line":1422,"examples":[{"editors":[{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"}],"body":"(pos-int? 1)\n;;=> true\n(pos-int? 9223372036854775807)\n;;=> true\n\n;;;; false for non-positive values\n\n(pos-int? 0)\n;;=> false\n(pos-int? -1)\n;;=> false\n\n;;;; false for decimal values\n\n(pos-int? 1.0)\n;;=> false\n(pos-int? 1/2)\n;;=> false\n\n;;;; false for BigInt values\n\n(pos-int? 1N)\n;;=> false\n(pos-int? 9223372036854775808)\n;;=> false","author":{"avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3","account-source":"github","login":"svenschoenung"},"created-at":1495703711193,"updated-at":1495703782768,"_id":"5926a09fe4b093ada4d4d74b"}],"notes":null,"arglists":["x"],"doc":"Return true if x is a positive fixed precision integer","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/pos-int_q"},{"added":"1.2","ns":"clojure.core","name":"extenders","file":"clojure/core_deftype.clj","type":"function","column":1,"see-alsos":[{"created-at":1542365699743,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"defprotocol","ns":"clojure.core"},"_id":"5beea203e4b00ac801ed9eff"},{"created-at":1542365712085,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"extends?","ns":"clojure.core"},"_id":"5beea210e4b00ac801ed9f00"}],"line":565,"examples":[{"author":{"login":"leifp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d2f37720f063404ef83b987d2824353d?r=PG&default=identicon"},"editors":[],"body":"user=> (defprotocol P (id [this]))\nP\nuser=> (extend-protocol P \n String \n (id [this] this)\n clojure.lang.Symbol \n (id [this] (name this))\n clojure.lang.Keyword\n (id [this] (name this)))\nnil\nuser=> (extenders P)\n(java.lang.String clojure.lang.Symbol clojure.lang.Keyword)\n","created-at":1342531381000,"updated-at":1342531381000,"_id":"542692d3c026201cdc326fa3"}],"notes":[{"author":{"login":"jumarko","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1083629?v=4"},"updated-at":1719483648471,"created-at":1719483648471,"body":";;; it doesn't cover defrecord or deftype\n;;; (Using example of the P protocol defined above)\n(defrecord PP []\n P\n (id [this] (str this \":\" this)))\n\n(deftype PPP []\n P\n (id [this] (str this \":\" this \":\" this)))\n\n(extenders P)\n;; => (java.lang.String clojure.lang.Symbol clojure.lang.Keyword)\n","_id":"667d3d0069fbcc0c226174d9"}],"arglists":["protocol"],"doc":"Returns a collection of the types explicitly extending protocol","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/extenders"},{"added":"1.3","ns":"clojure.core","name":"unchecked-short","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1496261308269,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"short","ns":"clojure.core"},"_id":"592f22bce4b06e730307db19"}],"line":3548,"examples":[{"editors":[{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"}],"body":"(unchecked-short 1)\n;;=> 1\n(unchecked-short 1N)\n;;=> 1\n(unchecked-short 1.1)\n;;=> 1\n(unchecked-short 1.9)\n;;=> 1\n(unchecked-short 5/3)\n;;=> 1\n\n(unchecked-short -1)\n;;=> -1\n(unchecked-short -1N)\n;;=> -1\n(unchecked-short -1.1)\n;;=> -1\n(unchecked-short -1.9)\n;;=> -1\n(unchecked-short -5/3)\n;;=> -1\n\n;;;; Note that (unchecked-short) does not range check its argument\n;;;; so integer overflow or rounding may occur. \n;;;; Use (short) if you want to throw an exception in such cases.\n\n(unchecked-short 32768)\n;;=> -32768\n(unchecked-short -32769)\n;;=> 32767\n\n(short 32768)\n;;=> IllegalArgumentException Value out of range for short: 32768\n(short -32769)\n;;=> IllegalArgumentException Value out of range for short: -32769\n\n(unchecked-short 1.0E4)\n;;=> 10000\n(unchecked-short 1.0E5)\n;;=> -31072\n\n(short 1.0E4)\n;;=> 10000\n(short 1.0E5)\n;;=> IllegalArgumentException Value out of range for short: 100000.0\n","author":{"avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3","account-source":"github","login":"svenschoenung"},"created-at":1496261208846,"updated-at":1496261256909,"_id":"592f2258e4b06e730307db17"}],"notes":null,"arglists":["x"],"doc":"Coerce to short. Subject to rounding or truncation.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/unchecked-short"},{"added":"1.0","ns":"clojure.core","name":"methods","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1337585063000,"author":{"login":"abrooks","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/69976?v=2"},"to-var":{"ns":"clojure.core","name":"get-method","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f4f"},{"created-at":1337585066000,"author":{"login":"abrooks","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/69976?v=2"},"to-var":{"ns":"clojure.core","name":"remove-method","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f50"},{"created-at":1337585074000,"author":{"login":"abrooks","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/69976?v=2"},"to-var":{"ns":"clojure.core","name":"prefer-method","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f51"},{"created-at":1337585077000,"author":{"login":"abrooks","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/69976?v=2"},"to-var":{"ns":"clojure.core","name":"prefers","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f52"}],"line":1828,"examples":[{"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"editors":[{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"}],"body":"user=> (use 'clojure.pprint)\nuser=> (pprint (methods print-dup))\n{nil #,\n java.lang.String #,\n java.lang.Boolean #,\n clojure.lang.IPersistentList\n #,\n java.sql.Timestamp\n #,\n java.util.UUID #,\n clojure.lang.Var #,\n clojure.lang.PersistentVector\n #,\n java.util.Calendar\n #,\n java.util.Map #,\n java.lang.Class #,\n java.util.regex.Pattern #,\n java.lang.Number #,\n java.lang.Long #,\n clojure.lang.Namespace #,\n java.math.BigDecimal #,\n clojure.lang.Symbol #,\n clojure.lang.Keyword #,\n clojure.lang.LazilyPersistentVector\n #,\n java.util.Collection #,\n java.lang.Double #,\n clojure.lang.Fn #,\n clojure.lang.IRecord #,\n clojure.lang.PersistentHashSet\n #,\n clojure.lang.IPersistentCollection\n #,\n clojure.lang.BigInt #,\n clojure.lang.ISeq #,\n java.util.Date #,\n clojure.lang.PersistentHashMap\n #,\n clojure.lang.IPersistentMap\n #,\n clojure.lang.Ratio #,\n java.lang.Character #}","created-at":1286272206000,"updated-at":1423014816147,"_id":"542692ccc026201cdc326cc5"},{"updated-at":1456200644152,"created-at":1456200644152,"author":{"login":"runningskull","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/187989?v=3"},"body":"user=> (defmulti do-math (fn [operation x y] operation))\n\n#'user/do-math\n\nuser=> (defmethod do-math :add [_ x y] (+ x y))\n... (defmethod do-math :subtract [_ x y] (- x y))\n... (defmethod do-math :hypotenuse [_ x y] (Math/sqrt (+ (* x x) (* y y))))\n\n#multifn[do-math 0x3a1c348]\n\nuser=> (methods do-math)\n\n{:hypotenuse #function[user/eval42540$fn--42541],\n :add #function[user/eval42521$fn--42522],\n :subtract #function[user/eval42525$fn--42526]}\n","_id":"56cbdbc4e4b0b41f39d96cd2"}],"notes":[{"updated-at":1286272245000,"body":"Not the most useful output format I've ever seen. :-)","created-at":1286272245000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521f99"}],"arglists":["multifn"],"doc":"Given a multimethod, returns a map of dispatch values -> dispatch fns","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/methods"},{"added":"1.0","ns":"clojure.core","name":"odd?","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"to-var":{"library-url":"https://github.com/clojure/clojure","name":"even?","ns":"clojure.core"},"author":{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},"created-at":1354423246000,"_id":"542692ebf6e94c6970521d53"}],"line":1408,"examples":[{"author":{"login":"dpritchett","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/147981?v=3"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":"user=> (odd? 1)\ntrue\nuser=> (odd? 2)\nfalse\nuser=> (odd? 0)\nfalse","created-at":1279074688000,"updated-at":1332952870000,"_id":"542692c8c026201cdc3269e5"},{"body":"user=> (filter odd? (range 15))\n(1 3 5 7 9 11 13)","author":{"login":"mookid","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7757342?v=3"},"created-at":1429217504160,"updated-at":1429217504160,"_id":"553020e0e4b033f34014b76f"}],"notes":null,"arglists":["n"],"doc":"Returns true if n is odd, throws an exception if n is not an integer","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/odd_q"},{"ns":"clojure.core","name":"->ArrayChunk","file":"clojure/gvec.clj","type":"function","column":1,"see-alsos":null,"line":37,"examples":null,"notes":null,"arglists":["am arr off end"],"doc":"Positional factory function for class clojure.core.ArrayChunk.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/->ArrayChunk"},{"added":"1.0","ns":"clojure.core","name":"float-array","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1657816974619,"author":{"login":"rosejn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/36590?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"aset","ns":"clojure.core"},"_id":"62d0478ee4b0b1e3652d7620"},{"created-at":1657816984539,"author":{"login":"rosejn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/36590?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"aget","ns":"clojure.core"},"_id":"62d04798e4b0b1e3652d7621"}],"line":5330,"examples":[{"updated-at":1657817072470,"created-at":1281617421000,"body":"user=> (float-array [1 2 3])\n#\nuser=> (aget *1 2)\n3.0\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3","account-source":"github","login":"jafingerhut"},{"login":"rosejn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/36590?v=4"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon","account-source":"clojuredocs","login":"gstamp"},"_id":"542692c9c026201cdc326ae0"},{"editors":[{"login":"JulienRouse","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/5703619?v=4"}],"body":"user=> (def f (float-array [1 2 3]))\n#'user/f\n\nuser=> f\n#object[\"[F\" 0x56ce4eda \"[F@56ce4eda\"]\n\n;;You can transform the array back into a Clojure vector with vec\nuser=> (vec f)\n[1.0 2.0 3.0]\n\n;;Also with into, works with list vector and set but not map\nuser=> (into [] f)\n[1.0 2.0 3.0]\n\nuser=> (into () f)\n(3.0 2.0 1.0)\n\nuser=> (into #{} f)\n=> #{3.0 2.0 1.0}\n\nuser=> (into {} f)\nExecution error (IllegalArgumentException) at user/eval1691 \n(form-init8077017244851884694.clj:1).\nDon't know how to create ISeq from: java.lang.Float","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/5703619?v=4","account-source":"github","login":"JulienRouse"},"created-at":1550505235553,"updated-at":1550515519268,"_id":"5c6ad513e4b0ca44402ef68f"},{"editors":[{"login":"JulienRouse","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/5703619?v=4"}],"body":";;Works for vector, list and set\nuser=> (float-array [1 2 3])\n#object[\"[F\" 0x6a86faa1 \"[F@6a86faa1\"]\n\nuser=> (float-array '(1 2 3))\n#object[\"[F\" 0xd5e9fe8 \"[F@d5e9fe8\"]\n\nuser=> (float-array #{1 2 3})\n#object[\"[F\" 0x7b327946 \"[F@7b327946\"]\n\n;;But not map\nuser=> (float-array {1 2})\nExecution error (ClassCastException) at user/eval2022 \n(form-init8077017244851884694.clj:1).\nclojure.lang.MapEntry cannot be cast to java.lang.Number","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/5703619?v=4","account-source":"github","login":"JulienRouse"},"created-at":1550515507149,"updated-at":1550515532633,"_id":"5c6afd33e4b0ca44402ef694"}],"notes":null,"arglists":["size-or-seq","size init-val-or-seq"],"doc":"Creates an array of floats","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/float-array"},{"added":"1.0","ns":"clojure.core","name":"*3","file":"clojure/core.clj","type":"var","column":1,"see-alsos":[{"created-at":1302912219000,"author":{"login":"hoornet","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5834f829a9def19620d4014c46642172?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"*1","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d6a"},{"created-at":1302912225000,"author":{"login":"hoornet","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5834f829a9def19620d4014c46642172?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"*2","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d6b"}],"dynamic":true,"line":6355,"examples":[{"updated-at":1285502085000,"created-at":1279048146000,"body":"user=> \"Hello!\"\n\"Hello!\"\n\nuser=> \"Hello World!\"\n\"Hello World!\"\n\nuser=> \"Hi Everyone!\"\n\"Hi Everyone!\"\n\nuser=> [*1 *2 *3]\n[\"Hi Everyone!\" \"Hello World!\" \"Hello!\"]\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/142529?v=3","account-source":"github","login":"nipra"},"_id":"542692c6c026201cdc326913"},{"updated-at":1285502101000,"created-at":1279048336000,"body":"user=> (range 5)\n(0 1 2 3 4)\nuser=> (last *1)\n4\nuser=> (last *2)\n4\nuser=> (last *3)\n4\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/142529?v=3","account-source":"github","login":"nipra"},"_id":"542692c6c026201cdc326915"}],"notes":null,"arglists":[],"doc":"bound in a repl thread to the third most recent value printed","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/*3"},{"added":"1.0","ns":"clojure.core","name":"alias","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1374148345000,"author":{"login":"alilee","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2fb0196dc5a7cd3a5cc73f1b9941c209?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"ns-aliases","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d62"},{"created-at":1390613584000,"author":{"login":"abrooks","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/69976?v=2"},"to-var":{"ns":"clojure.core","name":"ns-unalias","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d63"},{"created-at":1412905255114,"author":{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},"to-var":{"ns":"clojure.core","name":"require","library-url":"https://github.com/clojure/clojure"},"_id":"54373927e4b0ae7956031580"},{"created-at":1416004697043,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"},"to-var":{"ns":"clojure.core","name":"ns","library-url":"https://github.com/clojure/clojure"},"_id":"54668459e4b03d20a10242a5"}],"line":4290,"examples":[{"author":{"login":"teyc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bd6e62afb4881ab0f617611b8b65d003?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":"(require 'clojure.string)\n;;=> nil\n\n(alias 'string 'clojure.string)\n;;=> nil\n\n(string/capitalize \"hONdURas\")\n;;=> \"Honduras\"","created-at":1283925470000,"updated-at":1416004474780,"_id":"542692cec026201cdc326e01"},{"body":";; The alias can also be created when the \n;; namespace is required using the :as keyword.\n\n(require '[clojure.string :as string])\n(string/capitalize \"hONdURas\")\n;;=> \"Honduras\"","author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"},"created-at":1412886822918,"updated-at":1412886822918,"_id":"5436f126e4b0ae795603157f"}],"notes":null,"arglists":["alias namespace-sym"],"doc":"Add an alias in the current namespace to another\n namespace. Arguments are two symbols: the alias to be used, and\n the symbolic name of the target namespace. Use :as in the ns macro in preference\n to calling this directly.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/alias"},{"added":"1.2","ns":"clojure.core","name":"frequencies","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1325040915000,"author":{"login":"Claj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5fd658a8d2ef549071cb5286b1b874aa?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"group-by","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d38"},{"created-at":1396938657000,"author":{"login":"ryo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3f7913b563c72083c74030d928ba407e?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"distinct","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d39"}],"line":7351,"examples":[{"author":{"login":"pkolloch","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/10b2fd3c0a4cc46dc241a48468dc551?r=PG&default=identicon"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":"user=> (frequencies ['a 'b 'a 'a])\n{a 3, b 1}","created-at":1282321661000,"updated-at":1332952608000,"_id":"542692cac026201cdc326b14"},{"updated-at":1492057390955,"created-at":1492057390955,"author":{"login":"pharcosyle","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/60688?v=3"},"body":";; Turn a frequency map back into a coll.\n\n(mapcat (fn [[x n]] (repeat n x)) {:a 2 :b 1 :c 3})\n;;=> (:a :a :b :c :c :c)\n","_id":"58eefd2ee4b01f4add58fe8d"},{"updated-at":1617958558047,"created-at":1617958558047,"author":{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1334295?v=4"},"body":";; combine it with map to apply a function\n\n(def students\n [{:name \"Alice\" :age 23 :gender :female}\n {:name \"Bob\" :age 21 :gender :male}\n {:name \"John\" :age 23 :gender :male}\n {:name \"Maria\" :age 22 :gender :female}\n {:name \"Julie\" :age 22 :gender :female}])\n\n(frequencies (map :gender students))\n;; => {:female 3, :male 2}\n\n(frequencies (map :age students))\n;;=> {23 2, 21 1, 22 2}\n","_id":"6070169ee4b0b1e3652d74ba"}],"notes":[{"updated-at":1358885265000,"body":"
    (fn [coll]\r\n   (let [gp (group-by identity coll)] \r\n      (zipmap (keys gp) (map #(count (second %)) gp))))
    ","created-at":1358885188000,"author":{"login":"lispro06","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/20c3faad6f66a434dae42b5ed8ad305?r=PG&default=identicon"},"_id":"542692edf6e94c6970521ffb"},{"updated-at":1370062406000,"body":" (into {} (for [[k v] (group-by identity \"abbbc\")] [k (count v)]))\r\n","created-at":1370062406000,"author":{"login":"danneu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/c42635853936e509f76ece9d8187c4aa?r=PG&default=identicon"},"_id":"542692edf6e94c6970522004"},{"author":{"login":"ppsreejith","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1743700?v=3"},"updated-at":1453125303725,"created-at":1453125303725,"body":"
    \nuser=> (frequencies [3 6 2 6 8 7 'b 'c 3 5 3 4 7 6 'a])\n{2 1, 3 3, 4 1, 5 1, 6 3, 7 2, 8 1, a 1, c 1, b 1}\nuser=> (frequencies [3 6 2 6 8 7 'b 'c])\n{3 1, 6 2, 2 1, 8 1, 7 1, b 1, c 1}\n;Note that the order of keys need not be in order of vector\n
    ","_id":"569ceeb7e4b060004fc217ae"},{"author":{"login":"humorless","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/3061798?v=4"},"updated-at":1557220455720,"created-at":1557220455720,"body":"```\n(defn frequencies-by\n \"a generalized version of frequencies\"\n [f coll]\n (let [gp (group-by f coll)]\n (zipmap (keys gp) (map #(count (second %)) gp))))\n```","_id":"5cd14c67e4b0ca44402ef71b"}],"arglists":["coll"],"doc":"Returns a map from distinct items in coll to the number of times\n they appear.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/frequencies"},{"added":"1.0","ns":"clojure.core","name":"read-string","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1289454685000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"pr-str","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521a90"},{"created-at":1289454689000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"str","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521a91"},{"created-at":1313054776000,"author":{"login":"TimMc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5d532e51427ef2f4ded31aaca16c8baf?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"read","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521a92"},{"created-at":1334883935000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"load-string","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521a93"},{"created-at":1352963672000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.core","name":"*read-eval*","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521a94"},{"created-at":1422653056995,"author":{"login":"delonnewman","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10404?v=2"},"to-var":{"ns":"clojure.main","name":"load-script","library-url":"https://github.com/clojure/clojure"},"_id":"54cbf680e4b0e2ac61831cef"},{"created-at":1422653083632,"author":{"login":"delonnewman","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10404?v=2"},"to-var":{"ns":"clojure.edn","name":"read-string","library-url":"https://github.com/clojure/clojure"},"_id":"54cbf69be4b0e2ac61831cf0"}],"line":3831,"examples":[{"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":"user=> (read-string \"1.1\") \n1.1\n\nuser=> (read-string \"1.1.1 (+ 1 1)\")\njava.lang.RuntimeException: java.lang.NumberFormatException: Invalid number: 1.1.1 (NO_SOURCE_FILE:0)\n\nuser=> (read-string \"(+ 1 1)\")\n(+ 1 1)\n","created-at":1282634798000,"updated-at":1285494370000,"_id":"542692c9c026201cdc326ad6"},{"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"editors":[{"login":"tormaroe","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8bc7bb10bee96efb190053fe92ffd250?r=PG&default=identicon"}],"body":"user=> (eval (read-string \"(+ 1 1)\"))\n2\n\nuser=> (read-string (prn-str (+ 1 1)))\n2\n","created-at":1289408002000,"updated-at":1289710230000,"_id":"542692c9c026201cdc326ad8"},{"author":{"login":"benjiiiiii","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/fd1adaf32d9dc6531d6041dbc379efb0?r=PG&default=identicon"},"editors":[],"body":"user=> (+ 11 (read-string \"23\"))\n34\n","created-at":1291246357000,"updated-at":1291246357000,"_id":"542692c9c026201cdc326ada"},{"author":{"login":"devn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3"},"editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3","account-source":"github","login":"devn"}],"body":"user=> (read-string \"; foo\\n5\")\n5\n\nuser=> (read-string \"#^String x\")\nx\n\nuser=> (read-string \"(1)\")\n(1)\n\nuser=> (read-string \"(+ 1 2) (- 3 2)\")\n(+ 1 2)\n\nuser=> (read-string \"@a\")\n(clojure.core/deref a)\n\nuser=> (read-string \"(+ 1 2))))))\")\n(+ 1 2)\n\nuser=> (read-string \"::whatever-namespace-you-are-in\")\n:user/whatever-namespace-you-are-in","created-at":1335430367000,"updated-at":1335430553000,"_id":"542692d5c026201cdc32705f"},{"author":{"login":"dansalmo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e33ee460f5f61bc5ba9b598934766215?r=PG&default=identicon"},"editors":[{"login":"dansalmo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e33ee460f5f61bc5ba9b598934766215?r=PG&default=identicon"}],"body":";convert a string representing a sequence,\n;to the sequence that the string represents\nuser=> (read-string \"(\\\\( \\\\x \\\\y \\\\) \\\\z)\")\n(\\( \\x \\y \\) \\z)\n\n;then you can convert to the string that the string-sequence represents\nuser=> (apply str (read-string \"(\\\\( \\\\x \\\\y \\\\) \\\\z)\"))\n\"(xy)z\"\n\n;which is the inverse of\nuser=> (str (first (list (seq \"(xy)z\"))))\n\"(\\\\( \\\\x \\\\y \\\\) \\\\z)\"","created-at":1345526514000,"updated-at":1345526600000,"_id":"542692c9c026201cdc326adb"},{"author":{"login":"dansalmo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e33ee460f5f61bc5ba9b598934766215?r=PG&default=identicon"},"editors":[],"body":";; you can think of read-string as the inverse of pr-str\n;; turn string into symbols\nuser=> (read-string \"(a b foo :bar)\")\n(a b foo :bar)\n\n;;turn symbols into a string\nuser=> (pr-str '(a b foo :bar))\n\"(a b foo :bar)\"","created-at":1346843994000,"updated-at":1346843994000,"_id":"542692d5c026201cdc327061"},{"updated-at":1518357675254,"created-at":1360635743000,"body":";; WARNING: You SHOULD NOT use clojure.core/read-string to read data from\n;; untrusted sources. See the examples for clojure.core/read, because the same\n;; issues exist for both read and read-string.","editors":[{"login":"green-coder","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/598193?v=4"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3","account-source":"github","login":"jafingerhut"},"_id":"542692d5c026201cdc327062"},{"updated-at":1455932713195,"created-at":1455932713195,"author":{"login":"one-finger","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/17347889?v=3"},"body":";; convert binary number provided in the form of a string to its numerical value.\nuser=> (read-string (str \"2r\" \"1011\"))\n11\n","_id":"56c7c529e4b0b41f39d96ccf"},{"updated-at":1613109472732,"created-at":1557061665574,"author":{"login":"loeschzwerg","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/24317401?v=4"},"body":";; be careful with octal values\nuser=> (read-string \"042\")\n34\n\nuser=> (read-string \"08\")\nExecution error (NumberFormatException)\nInvalid number: 08\n\n;; replace leading zeroes with regex\nuser=> (read-string (clojure.string/replace \"042\" #\"^0+(?!$)\" \"\"))\n42\n\nuser=> (read-string (clojure.string/replace \"00\" #\"^0+(?!$)\" \"\"))\n0","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/39972994?v=4","account-source":"github","login":"jocatelo"}],"_id":"5ccee021e4b0ca44402ef71a"},{"editors":[{"login":"adanhawth","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/36526095?v=4"}],"body":";; if someone littered your csv fields with escaped double quotes...\n(def quoted-string \"\\\"1.23\\\"\")\n\n;; and you find yourself in angst, cause this won't work...\n(Double. quoted-string)\n\t;; Execution error (IllegalArgumentException) at user/eval6365 (form-init17453115089215840832.clj:1).\n\t;; No matching ctor found for class java.lang.Double\n\n;; you don't have to hate the player; but you can come prepared for the game\n(Double. (read-string quoted-string))\n\t;; 1.23","author":{"avatar-url":"https://avatars2.githubusercontent.com/u/36526095?v=4","account-source":"github","login":"adanhawth"},"created-at":1582746730566,"updated-at":1582746790901,"_id":"5e56cc6ae4b087629b5a18aa"},{"updated-at":1660763271174,"created-at":1660763271174,"author":{"login":"ertugrulcetin","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8271291?v=4"},"body":";;;; Data representation is same as the one produced by (read-string)\n;;;; and (read) when provided with the option to preserve data conditionals\n\n(read-string {:read-cond :preserve} \"#?(:clj (println \\\"Hey World!\\\"))\")\n;;=> #?(:clj (println \"Hey World!\"))\n","_id":"62fd3c87e4b0b1e3652d763d"}],"notes":[{"updated-at":1289408055000,"body":"read-string is useful for running clojure code from a script or translator.","created-at":1289408055000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fa2"},{"author":{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"},"updated-at":1568111197675,"created-at":1568111197675,"body":"Never **EVER** use `read-string` on data from an untrusted source. Prefer `clojure.edn/read-string` to parse EDN. The former can execute arbitrary code, including calling external URLs or reading/writing/erasing files.","_id":"5d777a5de4b0ca44402ef7af"}],"arglists":["s","opts s"],"doc":"Reads one object from the string s. Optionally include reader\n options, as specified in read.\n\n Note that read-string can execute code (controlled by *read-eval*),\n and as such should be used only with trusted sources.\n\n For data structure interop use clojure.edn/read-string","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/read-string"},{"added":"1.0","ns":"clojure.core","name":"proxy","file":"clojure/core_proxy.clj","type":"macro","column":1,"see-alsos":[{"created-at":1360270636000,"author":{"login":"AtKaaZ","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e10dfa345f44b0fe72bbe081fd51b83?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"gen-class","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521c9e"},{"created-at":1360270701000,"author":{"login":"AtKaaZ","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e10dfa345f44b0fe72bbe081fd51b83?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"gen-interface","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521c9f"},{"created-at":1361858921000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"reify","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ca0"}],"line":334,"examples":[{"author":{"login":"Kototama","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a54a4dc204925d397ca010b9a332e74d?r=PG&default=identicon"},"editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/4142015?v=3","account-source":"github","login":"bkovitz"}],"body":";; adding a mouse-pressed callback to a Swing component:\n\n(defn add-mousepressed-listener\n [component f & args]\n (let [listener (proxy [MouseAdapter] []\n (mousePressed [event]\n (apply f event args)))]\n (.addMouseListener component listener)\n listener))\n","created-at":1287523639000,"updated-at":1460780025090,"_id":"542692cdc026201cdc326d5c"},{"author":{"login":"TimMc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5d532e51427ef2f4ded31aaca16c8baf?r=PG&default=identicon"},"editors":[],"body":";; BUG: proxy dispatches *only* on name, not arity:\nuser=> (let [p (proxy [java.io.InputStream] [] (read [] -1))]\n (println (.read p))\n (println (.read p (byte-array 3) 0 3)))\n\n-1\nArityException Wrong number of args (4) passed to: core$eval213$fn clojure.lang.AFn.throwArity (AFn.java:437)\n","created-at":1336686490000,"updated-at":1336686490000,"_id":"542692d4c026201cdc327040"},{"updated-at":1586252027510,"created-at":1363059784000,"body":";; You can, however, provide multiple-arity functions to get some support \n;; for overloading\nuser> (let [p (proxy [java.io.InputStream] []\n (read\n ([] 1)\n ([^bytes bytes] 2)\n ([^bytes bytes off len] 3)))]\n (println (.read p))\n (println (.read p (byte-array 3)))\n (println (.read p (byte-array 3) 0 3)))\n\n1\n2\n3\nnil","editors":[{"login":"Hindol","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/705227?v=4"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/61b4809de147650070a5e209be48fe7f?r=PG&default=identicon","account-source":"clojuredocs","login":"craigandera"},"_id":"542692d4c026201cdc327041"},{"updated-at":1586252042920,"created-at":1542943086091,"author":{"login":"gluer","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/22495106?v=4"},"body":";; a simple example\n\n(defn f [& i]\n (proxy [clojure.lang.ISeq][]\n (seq [] (sort i))\n (toString [] (apply str (interpose \"-\" i)))))\n\n(seq (f 4 3 2 1))\n;;=> (1 2 3 4)\n\n\n(str (f 4 3 2 1))\n;;=> \"4-3-2-1\"","editors":[{"avatar-url":"https://avatars3.githubusercontent.com/u/22495106?v=4","account-source":"github","login":"gluer"},{"login":"Hindol","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/705227?v=4"}],"_id":"5bf7716ee4b0ca44402ef5c6"},{"updated-at":1587490591311,"created-at":1587490591311,"author":{"login":"audriu","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/41568862?v=4"},"body":";; usage of implicit 'this\n(def prx (proxy [java.lang.Runnable] []\n (run \n ([] (println \"We can use this inside here\" this) 1))))\n\n(.run prx)\n;;=>We can use this inside here #object[user.proxy$java.lang.Object$Runnable.....","_id":"5e9f2f1fe4b087629b5a18db"}],"macro":true,"notes":[{"author":{"login":"p-himik","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/4410314?v=4"},"updated-at":1740861513006,"created-at":1740861513006,"body":"Note that the proxied methods are set up only after the constructor is called, so if you want to override anything that the constructor of the superclass calls, `proxy` is not the right thing to do it.","_id":"67c37049cd84df5de54e2080"}],"arglists":["class-and-interfaces args & fs"],"doc":"class-and-interfaces - a vector of class names\n\n args - a (possibly empty) vector of arguments to the superclass\n constructor.\n\n f => (name [params*] body) or\n (name ([params*] body) ([params+] body) ...)\n\n Expands to code which creates a instance of a proxy class that\n implements the named class/interface(s) by calling the supplied\n fns. A single class, if provided, must be first. If not provided it\n defaults to Object.\n\n The interfaces names must be valid interface types. If a method fn\n is not provided for a class method, the superclass method will be\n called. If a method fn is not provided for an interface method, an\n UnsupportedOperationException will be thrown should it be\n called. Method fns are closures and can capture the environment in\n which proxy is called. Each method fn takes an additional implicit\n first arg, which is bound to 'this. Note that while method fns can\n be provided to override protected methods, they have no other access\n to protected members, nor to super, as these capabilities cannot be\n proxied.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/proxy"},{"added":"1.0","ns":"clojure.core","name":"rsubseq","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1330671605000,"author":{"login":"Chouser","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/7a0192050ed6488670acfd3f59405c10?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"subseq","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521efe"}],"line":5179,"examples":[{"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"editors":[],"body":"user> (rsubseq (sorted-set 1 2 3 4 5) < 3)\n(2 1)","created-at":1286871962000,"updated-at":1286871962000,"_id":"542692c9c026201cdc326af4"},{"editors":[{"login":"TradeIdeasPhilip","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/18409827?v=3"}],"body":";; If you use the longer form, with the end condition, there are some rules.\n;; start-key should be <= end-key. start-test should be \">\" or \">=\".\n;; end-test should be \"<\" or \"<=\". If follow these rules you'll get all the\n;; values between start-key and end-key. If you don't you won't get an error,\n;; but you probably won't get the result you expect. These rules are exactly\n;; the same for subseq.\n\n;; As expected, returns everything between 2 and 4, in reverse order.\nuser=> (rsubseq (sorted-set 1 2 3 4 5) >= 2 <= 4)\n;; => (4 3 2)\n\n;; Probably not what you expected!\nuser=> (rsubseq (sorted-set 1 2 3 4 5) <= 4 >= 2)\n;; => (2 1)\n\n;; As expected, returns everything between 2 and 4, in order.\nuser=> (subseq (sorted-set 1 2 3 4 5) >= 2 <= 4)\n;; => (2 3 4)\n\n;; Probably not what you expected!\nuser=> (subseq (sorted-set 1 2 3 4 5) <= 4 >= 2)\n;; => (4 5)\n","author":{"avatar-url":"https://avatars.githubusercontent.com/u/18409827?v=3","account-source":"github","login":"TradeIdeasPhilip"},"created-at":1463328932267,"updated-at":1463329023275,"_id":"5738a0a4e4b071da7d6cfd0b"}],"notes":null,"arglists":["sc test key","sc start-test start-key end-test end-key"],"doc":"sc must be a sorted collection, test(s) one of <, <=, > or\n >=. Returns a reverse seq of those entries with keys ek for\n which (test (.. sc comparator (compare ek key)) 0) is true","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/rsubseq"},{"added":"1.2","ns":"clojure.core","name":"inc","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1325850434000,"author":{"login":"frangio","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/646001f0ba2b7df47a16c0a1d5b62225?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"dec","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d99"},{"created-at":1415177507055,"author":{"login":"rvlieshout","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/139665?v=2"},"to-var":{"ns":"clojure.core","name":"inc'","library-url":"https://github.com/clojure/clojure"},"_id":"5459e523e4b03d20a102429d"},{"created-at":1525271648690,"author":{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"unchecked-inc","ns":"clojure.core"},"_id":"5ae9cc60e4b045c27b7fac5b"}],"line":924,"examples":[{"author":{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":"user=> (inc 1)\n2\n\nuser=> (inc 1.0)\n2.0\n\nuser=> (inc 1/2)\n3/2\n\nuser=> (inc -1)\n0","created-at":1279992305000,"updated-at":1411874902968,"_id":"542692cac026201cdc326b45"},{"updated-at":1516199380227,"created-at":1516199380227,"author":{"login":"ibercode","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/31028993?v=4"},"body":";;increment all the element in a collection\n\n(map inc [1 2 3 4 5])\n;;(2 3 4 5 6) return type list\n\n(into [] (map inc [1 2 3 4 5]))\n;;[2 3 4 5 6] return type vector","_id":"5a5f5dd4e4b0a08026c48cf8"},{"updated-at":1524688467780,"created-at":1524688121378,"author":{"login":"wuleicanada","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/5652075?v=4"},"body":";; Careful when using ClojureScript\n;; Make sure you're passing a number\n;; because JavaScript + also does string concatenation\ncljs.user=> (inc \"1\")\n\"11\"\ncljs.user=> (inc 1)\n2\n\n;; Although it's not the case with dec\n;; In JavaScript \"1\" - 1 = 0\ncljs.user=> (dec \"1\")\n0\ncljs.user=> (dec 1)\n0\n\n","editors":[{"avatar-url":"https://avatars0.githubusercontent.com/u/5652075?v=4","account-source":"github","login":"wuleicanada"}],"_id":"5ae0e4f9e4b045c27b7fac53"},{"updated-at":1633068446525,"created-at":1633068446525,"author":{"login":"Crowbrammer","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/19522656?v=4"},"body":";; You cannot `inc` a `nil` in Clojure, but you\n;; can in ClojureScript\n\n;; Clojure\n(inc nil) ;;=> NullPointerException\n\n;; ClojureScript\n(inc nil) ;;=> 1","_id":"6156a59ee4b0b1e3652d754f"}],"notes":[{"updated-at":1316509073000,"body":"Is the documentation suppose to be: \"Returns a number one greater than x.\" ? If not what is num?","created-at":1316509073000,"author":{"login":"icefox","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/dc848256f8954abd612cbe7e81859f91?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fcc"},{"author":{"login":"arashgithub","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1148053?v=3"},"updated-at":1457669616170,"created-at":1457669616170,"body":"is code \"(def i (inc i))\" is conflict with the notion of immutable of data in Clojure. ","_id":"56e245f0e4b0119038be0212"},{"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/20086?v=3"},"updated-at":1458583922104,"created-at":1458583922104,"body":"Nope, quite the opposite. \"def\" defines a var: \n
    \nuser=> (type (def i 1))\nclojure.lang.Var\n
    \nA var is one of the 4 types dealing with mutable state (it is not an immutable data structure, like maps, vectors, sets and so on) and it does so following a specific semantic (see http://clojure.org/reference/vars).","_id":"56f03972e4b09295d75dbf35"}],"arglists":["x"],"doc":"Returns a number one greater than num. Does not auto-promote\n longs, will throw on overflow. See also: inc'","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/inc"},{"added":"1.0","ns":"clojure.core","name":"get-method","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1337585046000,"author":{"login":"abrooks","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/69976?v=2"},"to-var":{"ns":"clojure.core","name":"remove-method","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e3c"},{"created-at":1337585052000,"author":{"login":"abrooks","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/69976?v=2"},"to-var":{"ns":"clojure.core","name":"methods","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e3d"}],"line":1834,"examples":[{"author":{"login":"shockbob","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon"},"editors":[],"body":";; define a multi-method, then demonstrate that you may use \n;; get-method in the same way you can call the method directly\n\nuser=> (defmulti tos :Ob)\n#'user/tos\nuser=> (defn line [p1 p2] {:Ob :line :p1 p1 :p2 p2})\n#'user/line\nuser=> (defn circle [cent rad] {:Ob :circle :cent cent :rad rad})\n#'user/circle\nuser=> (defmethod tos :line [l] (str \"Line:\" (l :p1) (l :p2)))\n#\nuser=> (defmethod tos :circle [c] (str \"Circle:\" (c :cent) (c :rad)))\n#\nuser=> (println (tos (circle [2 3] 3.3)))\nCircle:[2 3]3.3\nnil\nuser=> (println (tos (line [1 1][0 0])))\nLine:[1 1][0 0]\nnil\nuser=> (println ((get-method tos :line) (line [1 2][3 4]) ))\nLine:[1 2][3 4]\nnil\nuser=>","created-at":1313922883000,"updated-at":1313922883000,"_id":"542692cfc026201cdc326e6b"}],"notes":null,"arglists":["multifn dispatch-val"],"doc":"Given a multimethod and a dispatch value, returns the dispatch fn\n that would apply to that value, or nil if none apply and no default","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/get-method"},{"added":"1.3","ns":"clojure.core","name":"with-redefs","file":"clojure/core.clj","type":"macro","column":1,"see-alsos":[{"created-at":1322088077000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"with-redefs-fn","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b7b"},{"created-at":1322088155000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"alter-var-root","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b7c"},{"created-at":1365637645000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"with-bindings","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b7d"}],"line":7710,"examples":[{"updated-at":1335591486000,"created-at":1335591486000,"body":"user=> [(type []) (class [])]\n[clojure.lang.PersistentVector clojure.lang.PersistentVector]\n\nuser=> (with-redefs [type (constantly java.lang.String)\n class (constantly 10)]\n [(type [])\n (class [])])\n[java.lang.String 10]","editors":[],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3","account-source":"github","login":"devn"},"_id":"542692d6c026201cdc3270bc"},{"author":{"login":"johnnyluu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1ba99f2dc1064733c7badbb16db9254a?r=PG&default=identicon"},"editors":[{"login":"johnnyluu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1ba99f2dc1064733c7badbb16db9254a?r=PG&default=identicon"},{"login":"rebcabin","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/880b0bb3a4be9237326dd69565444dee?r=PG&default=identicon"}],"body":"(ns http)\n\n(defn post [url]\n {:body \"Hello world\"})\n\n(ns app\n (:require [clojure.test :refer [deftest is run-tests]]))\n\n(deftest is-a-macro\n (with-redefs [http/post (fn [url] {:body \"Goodbye world\"})]\n (is (= {:body \"Goodbye world\"} (http/post \"http://service.com/greet\")))))\n\n(run-tests) ;; test is passing","created-at":1350024154000,"updated-at":1366582892000,"_id":"542692d6c026201cdc3270bd"},{"author":{"login":"w01fe","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e6b62d981155b5945a29d84a2e439663?r=PG&default=identicon"},"editors":[],"body":";; be careful, with-redefs can permanently change a var if applied concurrently:\n\nuser> (defn ten [] 10)\n#'user/ten\nuser> (doall (pmap #(with-redefs [ten (fn [] %)] (ten)) (range 20 100)))\n...\nuser> (ten)\n79","created-at":1352471112000,"updated-at":1352471112000,"_id":"542692d6c026201cdc3270c0"},{"author":{"login":"nickzam","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/89377?v=2"},"editors":[],"body":";; redefine var\n(def foo 1)\n#'user/foo\n(with-redefs [foo 2] foo)\n2\n\n;; redefine private var\n(ns first)\n(def ^:private foo 1)\n#'first/foo\n\n(ns second)\n(with-redefs [first/foo 2] @#'first/foo)\n2\n\n;; @#' is the macros of (deref (var first/foo))\n(with-redefs [first/foo 2] (deref (var first/foo))\n2","created-at":1405030383000,"updated-at":1405030383000,"_id":"542692d6c026201cdc3270c1"},{"updated-at":1625736978558,"created-at":1625736978558,"author":{"login":"deadghost","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1156996?v=4"},"body":";; Vars return to their previous value outside of `with-redefs` body\n\n(with-redefs [first last] (first [1 2]))\n;; => 2\n((with-redefs [first last] #(first [1 2])))\n;; => 1","_id":"60e6c712e4b0b1e3652d7514"},{"editors":[{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"}],"body":";; Macros are not stored in vars, so `with-redefs` doesn't work on them.\n(defmacro a [] 1)\n=> #'user/a\n(a)\n=> 1\n(with-redefs [a (constantly 2)] (a))\n=> 1\n\n;; Inlined functions are also not affected in their inlined form:\n(defn b {:inline (fn [_] 1)} [_] 1)\n(with-redefs [b (constantly 2)] (b :foo))\n=> 1\n;; but their non-inlined form will be affected:\n(with-redefs [b (constantly 2)] (map b [:foo :bar]))\n=> (2 2)","author":{"avatar-url":"https://avatars.githubusercontent.com/u/8080718?v=4","account-source":"github","login":"owenRiddy"},"created-at":1658537792859,"updated-at":1732793065518,"_id":"62db4740e4b0b1e3652d762f"},{"updated-at":1766416010014,"created-at":1766416010014,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":";; \"…each resulting value will replace in parallel the root value of its Var.\"\n;; \"parallel\" means redefs can't reference each other:\n\n(def foo :f)\n(def bar :b)\n\n(with-redefs [foo :e, bar foo]\n bar)\n;; => :f\n\n;; n.b. bar gets foo's original value, not its redeffed value","_id":"69495e8ab7956e24e4cb4ec5"}],"macro":true,"notes":null,"arglists":["bindings & body"],"doc":"binding => var-symbol temp-value-expr\n\n Temporarily redefines Vars while executing the body. The\n temp-value-exprs will be evaluated and each resulting value will\n replace in parallel the root value of its Var. After the body is\n executed, the root values of all the Vars will be set back to their\n old values. These temporary changes will be visible in all threads.\n Useful for mocking out functions during testing.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/with-redefs"},{"added":"1.9","ns":"clojure.core","name":"uuid?","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1698256426925,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"random-uuid","ns":"clojure.core"},"_id":"6539562a69fbcc0c226173e0"},{"created-at":1698256433369,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"parse-uuid","ns":"clojure.core"},"_id":"6539563169fbcc0c226173e1"}],"line":6934,"examples":[{"updated-at":1495999029126,"created-at":1495999029126,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"body":"(uuid? (java.util.UUID/randomUUID))\n;;=> true\n(uuid? (read-string \"#uuid \\\"f81d4fae-7dec-11d0-a765-00a0c91e6bf6\\\"\"))\n;;=> true\n\n(uuid? \"f81d4fae-7dec-11d0-a765-00a0c91e6bf6\")\n;;=> false","_id":"592b2235e4b093ada4d4d780"},{"updated-at":1692976383675,"created-at":1527711361366,"author":{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/94482?v=4"},"body":";; If using a version of Clojure >= 1.11 use `parse-uuid`\n(def new-u (parse-uuid \"4fe5d828-6444-11e8-8222-720007e40350\"))\n;;=> #'user/new-u\nnew-u\n;;=> #uuid \"4fe5d828-6444-11e8-8222-720007e40350\"\n(uuid? new-u)\n;;=> true\n\n;; There is no (uuid) function to coerce a string to a UUID prior to Clojure v1.11,\n;; but you can produce one via Java interop:\n\n(def old-u (java.util.UUID/fromString \"4fe5d828-6444-11e8-8222-720007e40350\"))\n;;=> #'user/old-u\nold-u\n;;=> #uuid \"4fe5d828-6444-11e8-8222-720007e40350\"\n(uuid? old-u)\n;;=> true","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/53583563?v=4","account-source":"github","login":"E-A-Griffin"},{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/94482?v=4"}],"_id":"5b0f0681e4b045c27b7fac86"},{"updated-at":1539315353361,"created-at":1539315353361,"author":{"login":"ashton314","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/2874507?v=4"},"body":";; Change a UUID to a string:\n\n\n(.toString (java.util.UUID/randomUUID))\n;;=>\"91bb281c-4cdd-4bea-bd9c-27b5f9c75812\"","_id":"5bc01699e4b00ac801ed9ed9"}],"notes":[{"author":{"login":"E-A-Griffin","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/53583563?v=4"},"updated-at":1665246371235,"created-at":1665246331215,"body":";; Docs for added UUID functions in Clojure 1.11\n\n`parse-uuid`: https://clojure.github.io/clojure/clojure.core-api.html#clojure.core/parse-uuid\n\n`random-uuid`: https://clojure.github.io/clojure/clojure.core-api.html#clojure.core/random-uuid","_id":"6341a47be4b0b1e3652d7673"}],"arglists":["x"],"doc":"Return true if x is a java.util.UUID","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/uuid_q"},{"added":"1.0","ns":"clojure.core","name":"bit-clear","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1527805067810,"author":{"login":"NealEhardt","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/1338977?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"bit-set","ns":"clojure.core"},"_id":"5b10748be4b045c27b7fac8b"}],"line":1345,"examples":[{"author":{"login":"zmila","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/68dd6f50915854aa04fefcf4d6fa5c8e?r=PG&default=identicon"},"editors":[{"login":"zmila","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/68dd6f50915854aa04fefcf4d6fa5c8e?r=PG&default=identicon"},{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":"user=> (bit-clear 2r1011 3) ; index is 0-based\n3 \n;; 3 = 2r0011\n\n;; the same in decimal\nuser=> (bit-clear 11 3) \n3","created-at":1280337817000,"updated-at":1332950801000,"_id":"542692cbc026201cdc326bbf"}],"notes":null,"arglists":["x n"],"doc":"Clear bit at index n","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/bit-clear"},{"added":"1.0","ns":"clojure.core","name":"filter","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1282310761000,"author":{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},"to-var":{"ns":"clojure.core","name":"remove","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e17"},{"created-at":1399907449000,"author":{"login":"ryo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3f7913b563c72083c74030d928ba407e?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"keep","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e19"},{"created-at":1413316825235,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"},"to-var":{"ns":"clojure.core","name":"filterv","library-url":"https://github.com/clojure/clojure"},"_id":"543d80d9e4b02688d208b1b6"},{"created-at":1487135971846,"author":{"login":"chrismurrph","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10278575?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"group-by","ns":"clojure.core"},"_id":"58a3e4e3e4b01f4add58fe56"}],"line":2810,"examples":[{"updated-at":1420743803007,"created-at":1279065921000,"body":"(filter even? (range 10))\n;;=> (0 2 4 6 8)\n\n(filter (fn [x]\n (= (count x) 1))\n [\"a\" \"aa\" \"b\" \"n\" \"f\" \"lisp\" \"clojure\" \"q\" \"\"])\n;;=> (\"a\" \"b\" \"n\" \"f\" \"q\")\n\n(filter #(= (count %) 1)\n [\"a\" \"aa\" \"b\" \"n\" \"f\" \"lisp\" \"clojure\" \"q\" \"\"])\n;;=> (\"a\" \"b\" \"n\" \"f\" \"q\")\n\n; When coll is a map, pred is called with key/value pairs.\n(filter #(> (second %) 100)\n {:a 1\n :b 2\n :c 101\n :d 102\n :e -1})\n;;=> ([:c 101] [:d 102])\n\n(into {} *1)\n;;=> {:c 101, :d 102}\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"avatar-url":"https://avatars.githubusercontent.com/u/263299?v=2","account-source":"github","login":"zw"},{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3","account-source":"github","login":"phreed"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/142529?v=3","account-source":"github","login":"nipra"},"_id":"542692cac026201cdc326b5f"},{"updated-at":1435879726137,"created-at":1435879726137,"author":{"login":"bsvingen","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1647562?v=3"},"body":";; Used without a collection, filter will create a transducer:\n(def xf (filter odd?))\n\n;; We can now apply this transducer to a sequence:\n(transduce xf conj (range 10))\n;; => [1 3 5 7 9]\n","_id":"5595c92ee4b00f9508fd66f4"},{"updated-at":1446483945707,"created-at":1446482046531,"author":{"login":"Art-B","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1143795?v=3"},"body":";;When filtering a map, the predicate takes a _list_ of length 2\n(filter (fn [[k v]] (even? k))\n {1 \"a\", 2 \"b\", 3 \"c\", 4 \"d\"}\n)\n;;output:: ([2 \"b\"] [4 \"d\"])\n\n;;A function of arity two will cause an error\n(comment will fail!) \n(filter (fn [k v] (even? k))\n {1 \"a\", 2 \"b\", 3 \"c\", 4 \"d\"}\n)\n;;output:: clojure.lang.ArityException: Wrong number of args (1) passed to: ...","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/1143795?v=3","account-source":"github","login":"Art-B"}],"_id":"5637907ee4b04b157a6648df"},{"updated-at":1638750543664,"created-at":1446999529588,"author":{"login":"puppybits","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/140163?v=3"},"body":"; remove empty vectors from the root vector\n(def vector-of-vectors [[1 2 3] [] [1] []])\n\n(def populated-vector? \n (fn \n [item] \n (not= item [])))\n\n(filter populated-vector? vector-of-vectors)\n\n; => ([1 2 3] [1])\n\n; or\n(filter seq vector-of-vectors)","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/140163?v=3","account-source":"github","login":"puppybits"},{"login":"KyleErhabor","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/40676441?v=4"}],"_id":"563f75e9e4b0290a56055d22"},{"updated-at":1471132372267,"created-at":1471132372267,"author":{"login":"sleyzerzon","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/528932?v=3"},"body":";;filter a map on its values\n(filter (comp #{2 3} last) {:x 1 :y 2 :z 3})\n;;=> ([:y 2] [:z 3])","_id":"57afb2d4e4b02d8da95c26fd"},{"updated-at":1471132498612,"created-at":1471132498612,"author":{"login":"sleyzerzon","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/528932?v=3"},"body":";;filter a map on its values\n(filter (comp #{2 3} last) {:x 1 :y 2 :z 3})\n;;=> ([:y 2] [:z 3])\n\n;;extract keys for certain values\n(map first (filter (comp #{2 3} last) {:x 1 :y 2 :z 3}))\n=> (:y :z)","_id":"57afb352e4b02d8da95c26fe"},{"editors":[{"login":"mdubakov","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/465999?v=3"}],"body":";; You can use set as a filter predicate. In this case it is sets intersection\n(filter #{0 1 2 3} #{2 3 4 5})\n=> (3 2) ","author":{"avatar-url":"https://avatars2.githubusercontent.com/u/465999?v=3","account-source":"github","login":"mdubakov"},"created-at":1491555992092,"updated-at":1491556073772,"_id":"58e75698e4b01f4add58fe86"},{"updated-at":1494575824785,"created-at":1494575824785,"author":{"login":"st-keller","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/476463?v=3"},"body":";; That's how to get everything from a seq that is not nil;\n(filter some? '(1 nil [] :a nil))\n=> (1 [] :a)","_id":"59156ad0e4b01920063ee05a"},{"updated-at":1517054565714,"created-at":1517054565714,"author":{"login":"ibercode","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/31028993?v=4"},"body":";;practical example using an anonymous function \n;;which return a boolean value\n(def entries [{:month 1 :val 12 :s1 true :s2 false}\n {:month 2 :val 3 :s1 false :s2 true}\n {:month 3 :val 32 :s1 true :s2 false}\n {:month 4 :val 18 :s1 true :s2 false}\n {:month 5 :val 32 :s1 false :s2 true}\n {:month 6 :val 62 :s1 false :s2 true}\n {:month 7 :val 12 :s1 false :s2 true}\n {:month 8 :val 142 :s1 true :s2 false}\n {:month 9 :val 52 :s1 true :s2 false}\n {:month 10 :val 18 :s1 true :s2 false}\n {:month 11 :val 23 :s1 false :s2 true}\n {:month 12 :val 56 :s1 false :s2 true}])\n\n(filter #(:s2 %) entries)\n\n(filter #(and (:s2 %) (> (:val %) 30)) entries)\n","_id":"5a6c6a65e4b076dac5a728aa"},{"editors":[{"login":"ahmadrasyidsalim","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/18344132?v=4"}],"body":";; given users\n;; [\"pinisi\" \"sikad\" \"zenius\" \"teacher\" \"law\" \"calvin\" \"ijul\"]\n;; \n;; kick \"law\" and \"teacher\"\n\n(filter #(not (some (fn [u] (= u %)) \n [\"law\" \"teacher\"])) \n [\"pinisi\" \"sikad\" \"zenius\" \"teacher\" \"law\" \"calvin\" \"ijul\"])","author":{"avatar-url":"https://avatars3.githubusercontent.com/u/5813694?v=4","account-source":"github","login":"codxse"},"created-at":1530620467973,"updated-at":1632120981728,"_id":"5b3b6a33e4b00ac801ed9e23"},{"editors":[{"login":"tmountain","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/135297?v=4"}],"body":";; if you want to apply multiple predicates, use every-pred\n;; in conjunction with filter\n;; output: (2, 4)\n\n(filter\n (apply every-pred [even? #(< % 5)]) [1, 2, 3, 4, 5])\n\n;; if you want to apply any predicate, use some-fn\n;; output: (0 2 4 6 7 8 9)\n\n(filter\n (some-fn even? #(> % 5))\n (range 10))","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/135297?v=4","account-source":"github","login":"tmountain"},"created-at":1539887379558,"updated-at":1539888985733,"_id":"5bc8d113e4b00ac801ed9ee4"}],"notes":[{"author":{"login":"brunchboy","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2228869?v=3"},"updated-at":1441227184007,"created-at":1441227184007,"body":"Although the documentation states that the predicate must be free of side effects, it would be more accurate to say that you should not rely on filter to induce side effects that may be caused by the predicate, nor on the timing of when the predicate will be evaluated, because of the lazy and chunked nature of filter.","_id":"55e761b0e4b0efbd681fbb93"},{"author":{"login":"mattiasw2","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1294931?v=3"},"updated-at":1474933697182,"created-at":1474933697182,"body":"Note that filtering a map will not create a map. If you want to do a lookup on the result, you need to surround the call to filter with (into {} (filter ...))","_id":"57e9b3c1e4b0709b524f050e"}],"arglists":["pred","pred coll"],"doc":"Returns a lazy sequence of the items in coll for which\n (pred item) returns logical true. pred must be free of side-effects.\n Returns a transducer when no collection is provided.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/filter"},{"added":"1.0","ns":"clojure.core","name":"locking","file":"clojure/core.clj","type":"macro","column":1,"see-alsos":[{"created-at":1410129605000,"author":{"login":"SQuest","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/14c2b5159bb6d42d41ab04b1c714bd1b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"future","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c76"}],"line":1662,"examples":[{"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"editors":[{"login":"Ljos","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/45b996a79abca465acaf6c0f10b0437?r=PG&default=identicon"},{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"}],"body":"(def o (Object.))\n(future (locking o \n (Thread/sleep 5000) \n (println \"done1\")))\n\n;; Now run this before 5 seconds is up and you'll \n;; find the second instance waits for the first instance to print done1\n;; and release the lock, and then it waits for 1 second and prints done2\n\n(Thread/sleep 1000) ; give first instance 1 sec to acquire the lock\n(locking o \n (Thread/sleep 1000)\n (println \"done2\"))\n;; => done1\n;; => done2\n;; => nil\n\n;; locking operates like the synchronized keyword in Java.\n","created-at":1286271996000,"updated-at":1423012941325,"_id":"542692cdc026201cdc326d21"},{"updated-at":1563441285293,"created-at":1563441285293,"author":{"login":"liuchong","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/236058?v=4"},"body":"(def x 1)\n\n;; Reentrant\n\n(locking x (locking x (println \"hehe in\")) (println \"hehe out\"))\n;; => hehe in\n;; => hehe out\n;; => nil","_id":"5d303885e4b0ca44402ef787"}],"macro":true,"notes":null,"arglists":["x & body"],"doc":"Executes exprs in an implicit do, while holding the monitor of x.\n Will release the monitor of x in all circumstances.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/locking"},{"added":"1.0","ns":"clojure.core","name":"list","file":"clojure/core.clj","type":"function","column":1,"see-alsos":null,"line":16,"examples":[{"author":{"login":"dpritchett","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/147981?v=3"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":"user=> (list 'a 'b 'c 'd 'e 'f 'g)\n(a b c d e f g)\nuser=> (list 1 2 3)\n(1 2 3)","created-at":1279072062000,"updated-at":1332950370000,"_id":"542692cfc026201cdc326e52"},{"author":{"login":"devijvers","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/81018e4231ac1ce8b7a9e6d377092656?r=PG&default=identicon"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":"user=> (let [m {:1 1 :2 2 :3 3 :4 4}] (map list (keys m) (vals m)))\n((:1 1) (:2 2) (:3 3) (:4 4))","created-at":1279557389000,"updated-at":1332950386000,"_id":"542692cfc026201cdc326e54"},{"body":";; Lists can also be constructed literally using quote, but note the difference\n\n;; When using list the arguments are evaluated\n(let [x 1 y 2]\n (list x y))\n;; => (1 2)\n\n;; ... and when using quote ' they are not:\n(let [x 1 y 2]\n '(x y))\n;; => (x y)\n\n;; there is syntax quote ` (back tick) that allows selective evaluation inside it with ~:\n(let [x 1 y 2]\n `(~x ~y))\n;; => (1 2)\n\n;; But syntax quote ` is mostly used in macro definitions where most elements\n;; should not be evaluated and unquoted with ~ and list form above feels\n;; more idiomatic for simple list construction.","author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"created-at":1423011991402,"updated-at":1423012027889,"editors":[{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"}],"_id":"54d17097e4b0e2ac61831cfe"}],"notes":null,"arglists":["& items"],"doc":"Creates a new list containing the items.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/list"},{"added":"1.2","ns":"clojure.core","name":"+","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1351919360000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.core","name":"+'","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cb3"},{"created-at":1314343076000,"author":{"login":"Havvy","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e799a79441c7543be48562403411cd13?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"*","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521eaa"},{"created-at":1314343079000,"author":{"login":"Havvy","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e799a79441c7543be48562403411cd13?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"-","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521eab"},{"created-at":1423526895712,"author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"to-var":{"ns":"clojure.core","name":"unchecked-add","library-url":"https://github.com/clojure/clojure"},"_id":"54d94befe4b081e022073c82"},{"created-at":1525303139502,"author":{"login":"NealEhardt","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/1338977?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"inc","ns":"clojure.core"},"_id":"5aea4763e4b045c27b7fac5d"}],"line":986,"examples":[{"updated-at":1598154469428,"created-at":1279418175000,"body":"(+)\n;;=> 0\n\n(+ 1)\n;;=> 1\n\n(+ -10)\n;;=> -10\n\n(+ 1 2)\n;;=> 3\n\n(+ 1 2 3)\n;;=> 6\n\n(+ 1/2 1/2)\n;;=> 1N\n\n(apply + (range 10000000000000 10000000001000))\n;; ArithmeticException: integer overflow","editors":[{"login":"MrHus","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/22608?v=4"},{"avatar-url":"https://www.gravatar.com/avatar/edeae8e7534b3d554e4ec2c35ffc68d?r=PG&default=identicon","account-source":"clojuredocs","login":"semperos"},{"avatar-url":"https://www.gravatar.com/avatar/5d532e51427ef2f4ded31aaca16c8baf?r=PG&default=identicon","account-source":"clojuredocs","login":"TimMc"},{"avatar-url":"https://www.gravatar.com/avatar/611bdccae60c79419a30df0e2d6adc2b?r=PG&default=identicon","account-source":"clojuredocs","login":"csophys"},{"avatar-url":"https://www.gravatar.com/avatar/60838f7abe2eb311a6e00b10597f34c2?r=PG&default=identicon","account-source":"clojuredocs","login":"BenjyCui"},{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2","account-source":"github","login":"phreed"},{"login":"berczeck","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/1321842?v=4"}],"author":{"avatar-url":"https://avatars2.githubusercontent.com/u/22608?v=4","account-source":"github","login":"MrHus"},"_id":"542692c8c026201cdc326a18"}],"notes":null,"arglists":["","x","x y","x y & more"],"doc":"Returns the sum of nums. (+) returns 0. Does not auto-promote\n longs, will throw on overflow. See also: +'","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/+"},{"added":"1.0","ns":"clojure.core","name":"split-with","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1314290648000,"author":{"login":"Havvy","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e799a79441c7543be48562403411cd13?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"split-at","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c05"},{"created-at":1314291178000,"author":{"login":"Havvy","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e799a79441c7543be48562403411cd13?r=PG&default=identicon"},"to-var":{"ns":"clojure.string","name":"split","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c06"},{"created-at":1347077825000,"author":{"login":"dansalmo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e33ee460f5f61bc5ba9b598934766215?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"take-while","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c07"},{"created-at":1347077831000,"author":{"login":"dansalmo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e33ee460f5f61bc5ba9b598934766215?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"drop-while","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c08"},{"created-at":1659193713800,"author":{"login":"mars0i","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1836941?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"partition-by","ns":"clojure.core"},"_id":"62e54971e4b0b1e3652d7633"}],"line":3015,"examples":[{"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"editors":[{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"}],"body":"user=> (split-with (partial >= 3) [1 2 3 4 5])\n[(1 2 3) (4 5)]\n\nuser=> (split-with (partial > 3) [1 2 3 2 1])\n[(1 2) (3 2 1)]\n\nuser=> (split-with (partial > 10) [1 2 3 2 1])\n[(1 2 3 2 1) ()]","created-at":1281512571000,"updated-at":1423277699986,"_id":"542692c8c026201cdc3269ee"},{"editors":[{"login":"achesnais","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/6626105?v=3"},{"avatar-url":"https://avatars.githubusercontent.com/u/1200122?v=3","account-source":"github","login":"Bediako"},{"login":"v-kolesnikov","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/6506296?v=4"}],"body":";; If your plan is to split based on a certain value, using sets as\n;; predicates here isn't entirely straightforward.\n\nuser=> (split-with #{:c} [:a :b :c :d])\n[() (:a :b :c :d)]\n\n;; This is because the split happens at the first false/nil predicate result.\n;; Your predicate should thus return false upon hitting the desired split value!\n\nuser=> (split-with (complement #{:c}) [:a :b :c :d])\n[(:a :b) (:c :d)]\n\n;; In short, the predicate defines an attribute valid for the whole left\n;; side of the split. There's no such guarantee for the right side!\n\nuser=> (split-with odd? [1 3 5 6 7 9])\n[(1 3 5) (6 7 9)]\n\n;; Except if your predicate never returns false.\nuser=> (split-with (complement #{:e}) [:a :b :c :d])\n[(:a :b :c :d) ()]\n","author":{"avatar-url":"https://avatars.githubusercontent.com/u/6626105?v=3","account-source":"github","login":"achesnais"},"created-at":1470855993350,"updated-at":1511009715200,"_id":"57ab7b39e4b0bafd3e2a04dd"},{"updated-at":1623499263951,"created-at":1581787276541,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"body":";; The following split-by builds on top of split-with. Instead of \n;; splitting only the first time pred returns false, it splits (lazily)\n;; every time it turns from true to false.\n\n(defn split-by [pred coll]\n (lazy-seq\n (when-let [s (seq coll)]\n (let [[xs ys] (split-with pred s)]\n (if (seq xs)\n (cons xs (split-by pred ys))\n (let [!pred (complement pred)\n skip (take-while !pred s)\n others (drop-while !pred s)\n [xs ys] (split-with pred others)]\n (cons (concat skip xs)\n (split-by pred ys))))))))\n\n(split-by #(zero? (mod % 2)) [1 1 2 3 3 4 5 6 7 9])\n;; => ((1 1 2) (3 3 4) (5 6) (7 9))","editors":[{"avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"},{"login":"frwdrik","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/13023061?v=4"}],"_id":"5e48288ce4b0ca44402ef839"}],"notes":null,"arglists":["pred coll"],"doc":"Returns a vector of [(take-while pred coll) (drop-while pred coll)]","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/split-with"},{"added":"1.0","ns":"clojure.core","name":"aset","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1588281651305,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"aget","ns":"clojure.core"},"_id":"5eab4133e4b087629b5a18ee"},{"created-at":1668707576824,"author":{"login":"claj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/353113?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"aset-int","ns":"clojure.core"},"_id":"637674f8e4b0b1e3652d7683"},{"created-at":1668707583337,"author":{"login":"claj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/353113?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"aset-double","ns":"clojure.core"},"_id":"637674ffe4b0b1e3652d7684"}],"line":3949,"examples":[{"author":{"login":"dakrone","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bcacd00a7f05c4772329cf9f446c7987?r=PG&default=identicon"},"editors":[],"body":"user=> (def my-array (into-array Integer/TYPE [1 2 3]))\n#'user/my-array\n\nuser=> (aset my-array 1 10) ; Set the element with index 1 to 10\n10\n\nuser=> (into [] my-array)\n[1 10 3]","created-at":1286508598000,"updated-at":1286508598000,"_id":"542692cbc026201cdc326ba0"},{"body":"; Two dimensional example\n(use 'clojure.pprint)\n(let [the-array (make-array Long/TYPE 2 3) ]\n (dotimes [nn 6]\n (let [ii (quot nn 3)\n jj (rem nn 3) ]\n (aset the-array ii jj nn)\n ))\n (pprint the-array)\n)\n;=> [[0, 1, 2], [3, 4, 5]]\n\n; Types are defined in clojure/genclass.clj:\n; Boolean/TYPE\n; Character/TYPE\n; Byte/TYPE\n; Short/TYPE\n; Integer/TYPE\n; Long/TYPE\n; Float/TYPE\n; Double/TYPE\n; Void/TYPE\n\n","author":{"login":"cloojure","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7083783?v=3"},"created-at":1423782804290,"updated-at":1423783298831,"editors":[{"login":"cloojure","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7083783?v=3"}],"_id":"54dd3394e4b0e88f43c5afa1"},{"body":";; Simple 2D example:\n(def a (to-array-2d [[1 2] [3 4]]))\n;=> #'expt.core/a\n(aset a 0 1 \"foo\")\n;=> \"foo\"\nexpt.core=> (map vec a)\n;=> ([1 \"foo\"] [3 4])","author":{"login":"mars0i","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1836941?v=3"},"created-at":1432828883628,"updated-at":1432829193467,"editors":[{"login":"mars0i","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1836941?v=3"}],"_id":"55673bd3e4b01ad59b65f4dc"},{"updated-at":1588283235231,"created-at":1588282039336,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"body":";; transpose a matrix (two-dimensional array of doubles)\n;; using in-place mutation and no additional memory space.\n\n(defn transpose! [^\"[[D\" matrix]\n (dotimes [i (alength matrix)]\n (doseq [j (range (inc i) (alength matrix))]\n (let [copy (aget matrix i j)]\n (aset matrix i j (aget matrix j i))\n (aset matrix j i copy)))))\n\n(def matrix\n (into-array\n (map double-array\n [[1.0 2.0 3.0]\n [4.0 5.0 6.0]\n [7.0 8.0 9.0]])))\n\n(transpose! matrix)\n(mapv vec matrix)\n\n;; [[1.0 4.0 7.0]\n;; [2.0 5.0 8.0]\n;; [3.0 6.0 9.0]]\n","editors":[{"avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"}],"_id":"5eab42b7e4b087629b5a18ef"},{"updated-at":1682634188137,"created-at":1682634188137,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":";; Doubles are converted to floats; longs to ints, and vice versa:\n(aset (int-array [1 2 3]) 0 (long 42))\n;; => 42\n\n(aset (long-array [1 2 3]) 0 (int 42))\n;; => 42\n\n(aset (float-array [1.0 2.0 3.0]) 0 (double 42.0))\n;; => 42.0\n\n(aset (double-array [1.0 2.0 3.0]) 0 (float 42.0))\n;; => 42.0\n\n;; But some other conversions that may seem possible, are not:\n(aset (byte-array [1 2 3]) 0 (int 42))\n;; => Execution error (IllegalArgumentException) at…\n;; No matching method aset found taking 3 args\n\n(aset (short-array [1 2 3]) 0 (long 42))\n;; => Execution error (IllegalArgumentException) at…\n;; No matching method aset found taking 3 args\n\n;; It's best to be explicit:\n(aset (short-array [1 2 3]) 0 (short 42))\n;; => 42\n","_id":"644af5cce4b08cf8563f4b9e"}],"notes":null,"arglists":["array idx val","array idx idx2 & idxv"],"doc":"Sets the value at the index/indices. Works on Java arrays of\n reference types. Returns val.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/aset"},{"ns":"clojure.core","name":"->VecNode","file":"clojure/gvec.clj","type":"function","column":1,"see-alsos":null,"line":18,"examples":null,"notes":null,"arglists":["edit arr"],"doc":"Positional factory function for class clojure.core.VecNode.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/->VecNode"},{"added":"1.11","ns":"clojure.core","name":"abs","file":"clojure/core.clj","type":"function","column":1,"see-alsos":null,"line":1137,"examples":[{"updated-at":1700649505518,"created-at":1700649505518,"author":{"login":"edipofederle","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/50778?v=4"},"body":"(abs -10) ;; => 10","_id":"655dda2169fbcc0c2261745b"},{"updated-at":1739044190423,"created-at":1739044190423,"author":{"login":"cljlc","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/36645452?v=4"},"body":";; As indicated in its documentation, abs can return a negative value!\n\n(abs Long/MIN_VALUE)\n;;=> -9223372036854775808\n\n;; This is, because -Long/MIN_VALUE > Long/MAX_VALUE:\n;; (* -1 Long/MIN_VALUE)\n;;=> Execution error (ArithmeticException) at java.lang.Math/multiplyExact\n;;=> (Math.java:1032).\n;;=> long overflow","_id":"67a7b55ecd84df5de54e2079"}],"notes":null,"arglists":["a"],"doc":"Returns the absolute value of a.\n If a is Long/MIN_VALUE => Long/MIN_VALUE\n If a is a double and zero => +0.0\n If a is a double and ##Inf or ##-Inf => ##Inf\n If a is a double and ##NaN => ##NaN","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/abs"},{"added":"1.0","ns":"clojure.core","name":"keyword","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1292127515000,"author":{"login":"bgruber","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/b3c2dc1a076ff6e60dfb085ecddcc9f6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"name","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cf9"},{"created-at":1318592819000,"author":{"login":"mmwaikar","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/29d36f4c9f39c9f8ff61c07033b13118?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"keyword?","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cfa"},{"created-at":1331680528000,"author":{"login":"franks42","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/b3ee701dd6c481e5d310467ddfe62c48?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"namespace","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cfb"},{"created-at":1331680582000,"author":{"login":"franks42","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/b3ee701dd6c481e5d310467ddfe62c48?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"find-keyword","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cfc"},{"created-at":1350410417000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"symbol","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cfd"}],"line":616,"examples":[{"updated-at":1406075185000,"created-at":1280546489000,"body":";; (keyword name): name can be string, symbol, or keyword.\n;; \n;; (keyword ns name): ns and name must both be string.\n;; \n;; A keyword string, like a symbol, begins with a non-numeric\n;; character and can contain alphanumeric characters and *, +, !, -,\n;; _, and ?. (see http://clojure.org/reader for details).\n;; \n;; keyword does not validate input strings for ns and name, and may\n;; return improper keywords with undefined behavior for non-conformant\n;; ns and name.\n\nuser=> (keyword 'foo)\n:foo\n\nuser=> (keyword \"foo\") \n:foo\n\nuser=> (keyword \"user\" \"foo\")\n:user/foo\n\n;; keyword in current namespace\nuser=> (keyword (str *ns*) \"foo\")\n:user/foo","editors":[{"avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon","account-source":"clojuredocs","login":"gstamp"},{"avatar-url":"https://www.gravatar.com/avatar/7567c12df3f5e8f8ca031d4320b476ba?r=PG&default=identicon","account-source":"clojuredocs","login":"Alan"},{"avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3","account-source":"github","login":"jafingerhut"},{"avatar-url":"https://avatars.githubusercontent.com/u/92894?v=3","account-source":"github","login":"rafmagana"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/bcacd00a7f05c4772329cf9f446c7987?r=PG&default=identicon","account-source":"clojuredocs","login":"dakrone"},"_id":"542692cec026201cdc326d70"},{"author":{"login":"franks42","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/b3ee701dd6c481e5d310467ddfe62c48?r=PG&default=identicon"},"editors":[{"login":"rafmagana","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/92894?v=3"},{"login":"cljlc","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/36645452?v=4"}],"body":";; some gotchas to be aware of:\n\nuser=> (keyword \"user\" 'abc)\nClassCastException clojure.lang.Symbol cannot be cast to java.lang.String clojure.core/keyword (core.clj:558)\n\nuser=> (keyword *ns* \"abc\")\nClassCastException clojure.lang.Namespace cannot be cast to java.lang.String clojure.core/keyword (core.clj:558)\n\nuser=> (keyword 'user \"abc\")\nClassCastException clojure.lang.Symbol cannot be cast to java.lang.String clojure.core/keyword (core.clj:558)\n\n\n;; Warning - the following generated keywords are non-conformant and may wreak\n;; serious havoc in the near/far future when least expected...\n;; Even if `keyword?` might return true for them and they seem to work with\n;; `name` and `namespace` as well, and they can be used as functions\n;; (e.g. `(:/// {:/// \"x\"})` works), problems usually come at e.g. destructuring... \n\nuser=> (keyword \"abc def\")\n:abc def\n\nuser=> (keyword \"123def\")\n:123def\n\nuser=> (keyword \"/abc/def/ghi\")\n:/abc/def/ghi\n\nuser=> (keyword \":\" \":\")\n::/:\n\nuser=> (keyword \"/\" \"/\")\n:///\n\nuser=> (keyword \"\")\n:\n\nuser=> (keyword \"\" \"/\")\n://\n\nuser=> (keyword \"...\")\n:...","created-at":1331680488000,"updated-at":1548520687081,"_id":"542692d3c026201cdc326fde"},{"updated-at":1406075556000,"created-at":1392677011000,"body":";; You can define namespaced keywords using '::'\nuser=> (def a :foo)\n#'user/a\n\nuser=> (def b ::foo)\n#'user/b\n\nuser=> (ns foo)\nfoo=> user/a\n:foo\n\nfoo=> user/b\n:user/foo\n\nfoo=> ::foo\n:foo/foo\n\nfoo=> (= user/a :foo)\ntrue\n\nfoo=> (= user/b ::foo)\nfalse\n\nfoo=> (= user/b :user/foo)\ntrue","editors":[{"avatar-url":"https://www.gravatar.com/avatar/a684c0fd4f27597437de953e92a15d4b?r=PG&default=identicon","account-source":"clojuredocs","login":"Phalphalak"},{"avatar-url":"https://www.gravatar.com/avatar/a684c0fd4f27597437de953e92a15d4b?r=PG&default=identicon","account-source":"clojuredocs","login":"Phalphalak"},{"avatar-url":"https://avatars.githubusercontent.com/u/92894?v=3","account-source":"github","login":"rafmagana"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/a684c0fd4f27597437de953e92a15d4b?r=PG&default=identicon","account-source":"clojuredocs","login":"Phalphalak"},"_id":"542692d3c026201cdc326fe0"},{"updated-at":1445848617591,"created-at":1445848617591,"author":{"login":"ShayMatasaro","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1350551?v=3"},"body":";;only convert strings\nuser=> (keyword 1)\nnil\n\n\nuser=> (keyword '1)\nnil\n","_id":"562de629e4b0290a56055d13"},{"editors":[{"login":"PetrGlad","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/124476?v=3"}],"body":"(keyword \"my.key\")\n;=> :my.key\n(qualified-keyword? :my.key)\n;=> nil ;; \"my.key\" is just name, dot does not count\n(keyword \"my.namespace\" \"my.key\") \n;=> :my.namespace/my.key\n(qualified-keyword? :my.namespace/my.key)\n;=> true \n(namespace :my.namespace/my.key) \n;=> \"my.namespace\"\n(name :my.namespace/my.key) \n;=> \"my.key\"\n","author":{"avatar-url":"https://avatars.githubusercontent.com/u/124476?v=3","account-source":"github","login":"PetrGlad"},"created-at":1482252029047,"updated-at":1482252099977,"_id":"58595efde4b004d3a355e2c9"},{"updated-at":1517353605671,"created-at":1517352728207,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"},"body":";; let's make an illustrative namespace\n(create-ns 'my.arbitrary.long.namespace)\n(alias 'maln 'my.arbitrary.long.namespace)\n;; more typically loaded and aliased with require\n;; (require '[my.arbitrary.long.namespace :as maln])\n\n;; Qualified keywords may be specified with the namespace or the alias.\n;; But unlike with symbols where the bare alias is used \n;; you need to prefix the alias with '::' \n:my.arbitrary.long.namespace/foo\n;=> :my.arbitrary.long.namespace/foo\n::maln/bar\n;=> :my.arbitrary.long.namespace/bar","editors":[{"avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4","account-source":"github","login":"phreed"}],"_id":"5a70f718e4b0c974fee49d14"},{"editors":[{"login":"jasonisgraham","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/3493406?v=4"},{"avatar-url":"https://avatars3.githubusercontent.com/u/11671382?v=4","account-source":"github","login":"dominem"}],"body":"\n;; You can use existing keywords (cljs only)\n\n(keyword :namespace :keyword)\n;;=> :namespace/keyword\n\n(keyword \"namespace\" :keyword)\n;;=> :namespace/keyword\n\n(keyword :namespace \"keyword\")\n;;=> :namespace/keyword\n\n(keyword :meta-namespace/namespace :meta-keyword/keyword)\n;;=> :namespace/keyword\n","author":{"avatar-url":"https://avatars2.githubusercontent.com/u/10955264?v=4","account-source":"github","login":"troglotit"},"created-at":1527776571957,"updated-at":1565335543185,"_id":"5b10053be4b045c27b7fac89"},{"editors":[{"login":"cljlc","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/36645452?v=4"}],"body":";; different (non-conformant) keywords can have the same printed representation:\n\n(= :a/b/c (keyword \"a\" \"b/c\"))\n;;=> true\n\n(keyword \"a/b\" \"c\")\n;;=> :a/b/c\n\n(= (str (keyword \"a/b\" \"c\")) (str (keyword \"a\" \"b/c\")))\n;;=> true\n\n(= (keyword \"a/b\" \"c\") (keyword \"a\" \"b/c\"))\n;;=> false\n","author":{"avatar-url":"https://avatars0.githubusercontent.com/u/36645452?v=4","account-source":"github","login":"cljlc"},"created-at":1548521622644,"updated-at":1548521923629,"_id":"5c4c9096e4b0ca44402ef63d"},{"updated-at":1599398418945,"created-at":1599398354277,"author":{"login":"luiszambon","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/41161270?v=4"},"body":"(defn creating-map\n [key value]\n {(keyword key) value})\n\n(:map-key (creating-map \"map-key\" \"map-value\"))\n;;=>\"map-value\"","editors":[{"avatar-url":"https://avatars0.githubusercontent.com/u/41161270?v=4","account-source":"github","login":"luiszambon"}],"_id":"5f54e1d2e4b0b1e3652d73b0"},{"updated-at":1641596456686,"created-at":1641596456686,"author":{"login":"jkndrkn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/91959?v=4"},"body":";; Be careful because it is possible to create keywords that contain whitespace\n\n(keyword \"my-keyword\\t\")\n;;=> :my-keyword\n\n(name (keyword \"my-keyword\\t\"))\n;;=> \"my-keyword\\t\"\n\n\n(= (keyword \"my-keyword\") :my-keyword)\n;;=> true\n\n(= (keyword \"my-keyword\\t\") :my-keyword)\n;;=> false\n","_id":"61d8c628e4b0b1e3652d759d"},{"updated-at":1763338351907,"created-at":1763338351907,"author":{"login":"bombaywalla","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/4961347?v=4"},"body":";; A string with a slash happens to create a namespace qualified keyword\n;; Do not rely on this behavior\n\n(qualified-keyword? (keyword \"foo/bar\"))\n;;=> true\n\n(let [x (keyword \"foo/bar\")]\n (println \"ns:\" (namespace x))\n (println \"name:\" (name x)))\nns: foo\nname: bar\n;;=> nil","_id":"691a686f848d032713abce3e"}],"notes":null,"tag":"clojure.lang.Keyword","arglists":["name","ns name"],"doc":"Returns a Keyword with the given namespace and name. Do not use :\n in the keyword strings, it will be added automatically.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/keyword"},{"added":"1.0","ns":"clojure.core","name":"*ns*","type":"var","see-alsos":null,"examples":[{"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"editors":[],"body":"user=> *ns*\n#","created-at":1289039963000,"updated-at":1289039963000,"_id":"542692c7c026201cdc3269c7"},{"author":{"login":"rafmagana","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/92894?v=3"},"editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/92894?v=3","account-source":"github","login":"rafmagana"}],"body":"user=> (ns foo.bar)\nnil\n\nfoo.bar=> *ns*\n#","created-at":1406094577000,"updated-at":1406094613000,"_id":"542692d1c026201cdc326f35"},{"editors":[{"login":"Artiavis","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/1834136?v=3"}],"body":";; A (rare) trap which can happen is attempting to dynamically call `in-ns`, due to how\n;; `*ns*` is really an instance of `clojure.lang.Var` with a root binding.\nuser=> (ns my.namespace)\nnil\n\nmy.namespace=> *ns*\n#\n\n;; This will *only* work in the REPL (or REPL-like environments)!!\n;; Tools like Boot and Lein may or may not provide this (read the manual/code)\nmy.namespace=> (defn swap-ns! [ns-name] (in-ns ns-name))\n#'my.namespace/swap-ns!\n\nmy.namespace=> (swap-ns! 'other.ns)\n#namespace[other.ns]\n\n;; Later, at runtime...\n;; Throws IllegalStateException(\"Can't change/establish root binding of: *ns* with set\")\n;; Remember, *ns* is a root var and in-ns calls set!, which only works after\n;; someone somewhere calls the binding macro (or Java equivalent)\n(defn -main\n [& args]\n (println *ns*)\n (swap-ns! 'arbitrary-namespace))\n;; prints #namespace[clojure.core] and then will crash","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/1834136?v=3","account-source":"github","login":"Artiavis"},"created-at":1497795113128,"updated-at":1497795249422,"_id":"59468a29e4b06e730307db35"}],"notes":[{"updated-at":1310470085000,"body":"A trap I fell into was that *ns* seems to get assigned to clojure.core when run as a \"gen-class\" compiled class.","created-at":1310470085000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fc4"},{"body":"To clarify the above point, see my example above. Although within Lein/Boot/REPL/Compiler contexts, `*ns*` is thread-local due to the use of the `binding` machinery, and so `in-ns` works in those situtations, `*ns*` has a root of `clojure.core`. That means that, at runtime, you cannot call `in-ns` within functions until you've first called `binding`. (This could be relevant for e.g. `eval` calls.)","created-at":1497579558843,"updated-at":1497795316359,"author":{"avatar-url":"https://avatars1.githubusercontent.com/u/1834136?v=3","account-source":"github","login":"Artiavis"},"_id":"59434026e4b06e730307db34"}],"tag":"clojure.lang.Namespace","arglists":[],"doc":"A clojure.lang.Namespace object representing the current namespace.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/*ns*"},{"ns":"clojure.core","name":"destructure","file":"clojure/core.clj","type":"function","column":1,"see-alsos":null,"line":4427,"examples":[{"updated-at":1727698812962,"created-at":1396388229000,"body":"(destructure '[[a b] [\"a\" \"b\"]])\n;;=> [vec__10263 [\"a\" \"b\"]\n;; a (clojure.core/nth vec__10263 0 nil)\n;; b (clojure.core/nth vec__10263 1 nil)]\n\n; look ma, no let!\n(map #(intern *ns* (first %) (eval (last %))) (partition 2 (destructure '[[a b] [\"a\" \"b\"]])))\nuser=> a\n\"a\"\nuser=> b\n\"b\"","editors":[{"login":"conao3","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/4703128?v=4"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/5b2768c3c24e6e96d838c4c43038de93?r=PG&default=identicon","account-source":"clojuredocs","login":"reborg"},"_id":"542692d2c026201cdc326f8d"},{"updated-at":1519692244573,"created-at":1519675914364,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"},"body":";; Based on the previous example...\n\n;; Suppose you want to do some work at the repl.\n;; It would be nice if the def and let had similar syntax but they do not.\n\n(defn def+ [bindings] \n (let [bings (partition 2 (destructure bindings))\n obj (first bings)\n redef (rest bings)]\n \n (intern *ns* (first obj) (eval (second obj))) \n (map #(intern *ns* (first %) (eval (last %))) redef)))\n\n(def+ '[[u s v] [1 5 9]]) \n \n;; def+ is better implemented as a macro.\n;; It does have the drawback of introducing some intermediate gen variables.\n;; But, it prints the names of all variables.\n\n(defmacro def+\n \"binding => binding-form\n internalizes binding-forms as if by def.\"\n {:added \"1.9\", :special-form true, :forms '[(def+ [bindings*])]}\n [& bindings]\n (let [bings (partition 2 (destructure bindings))]\n (sequence cat \n ['(do) \n (map (fn [[var value]] `(def ~var ~value)) bings)\n [(mapv (fn [[var _]] (str var)) bings)]])))\n\n(def+ [u s v] [1 5 9] \n foo \"bar\" \n [a b] [\"abc\" \"bcd\"])\n;=> #'user/b\n\na\n;=> \"abc\"\n\n;; The justification for such a macro is manifest when\n;; debugging at the repl.\n;; Suppose the following is in a function and \n(let [[a b] [\"a\" \"b\"]] \n (str a b) ; is this correct?\n (conj a b) ; how about this?\n (cat a b)) ; or this?\n\n;; Now in this case the problem is clear but in general it may not be.\n;; So you get set up to track down this problem. \n(def+ [a b] [\"a\" \"b\"])\n\n;; Without def+ you would have to do something like the following...\n(def ab [\"a\" \"b\"])\n(def a (nth ab 0))\n(def b (nth ab 1))\n;; ...to get set up in the repl.","editors":[{"avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4","account-source":"github","login":"phreed"}],"_id":"5a946a0ae4b0316c0f44f8f2"}],"notes":[{"author":{"login":"Ragsboss","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/3869936?v=3"},"updated-at":1494263800930,"created-at":1494263800930,"body":"I found https://clojure.org/guides/destructuring extremely useful","_id":"5910a7f8e4b01f4add58feb1"},{"body":"\"[The `destructure` function] implements the destructuring logic and [...] is designed to be invoked in a macro\". For more info about `desctructure` see https://clojure.org/guides/destructuring#_macros.","created-at":1519164976336,"updated-at":1519165254309,"author":{"avatar-url":"https://avatars0.githubusercontent.com/u/36645452?v=4","account-source":"github","login":"cljlc"},"_id":"5a8c9e30e4b0316c0f44f8d8"}],"arglists":["bindings"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core/destructure"},{"added":"1.0","ns":"clojure.core","name":"*assert*","type":"var","see-alsos":[{"created-at":1301778092000,"author":{"login":"TimMc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5d532e51427ef2f4ded31aaca16c8baf?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"assert","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d09"}],"examples":[{"updated-at":1475615278407,"created-at":1475615278407,"author":{"login":"ertugrulcetin","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8271291?v=3"},"body":"user=> (set! *assert* true)\n\nuser=> (defn str->int\n [x]\n {:pre [(string? x)]}\n (Integer/valueOf x))\n\nuser=> (str->int 12.2)\n;;=> AssertionError Assert failed: (string? x) user/str->int...","_id":"57f41a2ee4b0709b524f051e"}],"notes":[{"updated-at":1406676369000,"body":"A little digging through the RT.java code confirms that this is dynamic, and defaults to true.","created-at":1406676369000,"author":{"login":"hlship","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cb598cc180c2363c093e92e8e87e0493?r=PG&default=identicon"},"_id":"542692edf6e94c697052202e"},{"author":{"login":"taehee-kim-sherpas","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/160077355?v=4"},"updated-at":1757391592552,"created-at":1757391592552,"body":"It is also used in many schema libraries like malli. see [`malli.core/assert`](https://github.com/metosin/malli/blob/0.17.0/src/malli/core.cljc#L2450) for example.","_id":"68bfaae8cd84df5de54e2096"}],"arglists":[],"doc":"When set to logical false, 'assert' will omit assertion checks in\n compiled code. Defaults to true.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/*assert*"},{"added":"1.0","ns":"clojure.core","name":"defmulti","file":"clojure/core.clj","type":"macro","column":1,"see-alsos":[{"created-at":1285162568000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"defmethod","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c30"},{"created-at":1341270331000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"remove-method","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c31"},{"created-at":1341270338000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"remove-all-methods","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c32"},{"created-at":1341270344000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"prefers","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c33"},{"created-at":1341270349000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"methods","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c34"},{"created-at":1341270355000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"get-method","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c35"},{"created-at":1351463879000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"defprotocol","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c36"},{"created-at":1413313710551,"author":{"login":"kgann","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1098962?v=2"},"to-var":{"ns":"clojure.core","name":"make-hierarchy","library-url":"https://github.com/clojure/clojure"},"_id":"543d74aee4b02688d208b1b5"},{"created-at":1485980931712,"author":{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/94482?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"multi-spec","ns":"clojure.spec"},"_id":"58924503e4b01f4add58fe38"},{"created-at":1693261789329,"author":{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/94482?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"derive","ns":"clojure.core"},"_id":"64ed1fdde4b08cf8563f4be6"}],"line":1742,"examples":[{"author":{"login":"Victor","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bc41ebab54cc0e0fbe99d753876d45ce?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"avatar-url":"https://avatars.githubusercontent.com/u/200617?v=3","account-source":"github","login":"bsima"},{"avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4","account-source":"github","login":"bfontaine"},{"login":"Luke1298","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7078861?v=4"}],"body":";; Define the multimethod\n(defmulti service-charge (juxt account-level :tag))\n\n;; Handlers for resulting dispatch values\n(defmethod service-charge [::acc/Basic ::acc/Checking] [_] 25)\n(defmethod service-charge [::acc/Basic ::acc/Savings] [_] 10)\n(defmethod service-charge [::acc/Premium ::acc/Account] [_] 0)","created-at":1290489704000,"updated-at":1643237673567,"_id":"542692cdc026201cdc326d58"},{"author":{"login":"Victor","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bc41ebab54cc0e0fbe99d753876d45ce?r=PG&default=identicon"},"editors":[{"login":"stand","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d7f9ed2753f8b3517f1539f6129f0a17?r=PG&default=identicon"},{"avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4","account-source":"github","login":"bfontaine"},{"login":"blue0513","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/8979468?v=4"}],"body":";this example illustrates that the dispatch type\n;does not have to be a symbol, but can be anything (in this case, it's a string)\n\n(defmulti greeting\n (fn[x] (get x \"language\")))\n\n;params is not used, so we could have used [_]\n(defmethod greeting \"English\" [params]\n \"Hello!\")\n\n(defmethod greeting \"French\" [params]\n \"Bonjour!\")\n\n;;default handling\n(defmethod greeting :default [params]\n (throw (IllegalArgumentException. \n (str \"I don't know the \" (get params \"language\") \" language\"))))\n\n;then can use this like this:\n(def english-map {\"id\" \"1\", \"language\" \"English\"})\n(def french-map {\"id\" \"2\", \"language\" \"French\"})\n(def spanish-map {\"id\" \"3\", \"language\" \"Spanish\"})\n\n=>(greeting english-map)\n\"Hello!\"\n=>(greeting french-map)\n\"Bonjour!\"\n=>(greeting spanish-map)\n java.lang.IllegalArgumentException: I don't know the Spanish language","created-at":1290492895000,"updated-at":1589637326870,"_id":"542692cdc026201cdc326d59"},{"author":{"login":"OnesimusUnbound","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2fa4c391db0d2d1744cc2cd0d787dd3d?r=PG&default=identicon"},"editors":[{"login":"cddr","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/48030?v=3"}],"body":";; Implementing factorial using multimethods Note that factorial-like function \n;; is best implemented using `recur` which enables tail-call optimization to avoid \n;; a stack overflow error. This is a only a demonstration of clojure's multimethod\n\n;; identity form returns the same value passed\n(defmulti factorial identity)\n\n(defmethod factorial 0 [_] 1)\n(defmethod factorial :default [num] \n (* num (factorial (dec num))))\n\n(factorial 0) ; => 1\n(factorial 1) ; => 1\n(factorial 3) ; => 6\n(factorial 7) ; => 5040","created-at":1313197324000,"updated-at":1433710661793,"_id":"542692cdc026201cdc326d5b"},{"body":";; defmulti/defmethods support variadic arguments and dispatch functions.\n\n(defmulti bat \n (fn ([x y & xs] \n (mapv class (into [x y] xs)))))\n(defmethod bat [String String] [x y & xs] \n (str \"str: \" x \" and \" y))\n(defmethod bat [String String String] [x y & xs] \n (str \"str: \" x \", \" y \" and \" (first xs)))\n(defmethod bat [String String String String] [x y & xs] \n (str \"str: \" x \", \" y \", \" (first xs) \" and \" (second xs)))\n(defmethod bat [Number Number] [x y & xs] \n (str \"number: \" x \" and \" y))\n\n;; you call it like this...\n\n(bat \"mink\" \"stoat\")\n;; => \"str: mink and stoat\"\n\n(bat \"bear\" \"skunk\" \"sloth\")\n;; => \"str: bear, skunk and sloth\"\n\n(bat \"dog\" \"cat\" \"cow\" \"horse\")\n;; => \"str: dog, cat, cow and horse\"\n\n(bat 1 2)\n;; => \"number: 1 and 2\"","author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"},"created-at":1412178008616,"updated-at":1412178054860,"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"}],"_id":"542c2058e4b05f4d257a2966"},{"body":";; defmulti - custom hierarchy\n\n(def h (-> (make-hierarchy)\n (derive :foo :bar)))\n\n(defmulti f identity :hierarchy #'h) ;; hierarchy must be a reference type\n\n(defmethod f :default [_] \"default\")\n(defmethod f :bar [_] \"bar\")\n\n(f :unknown) ;; \"default\"\n(f :bar) ;; \"bar\"\n(f :foo) ;; \"bar\"\n\n;; Note that any deref'able type is fine. \n;; Using an atom instead of (var h) is preferable in clojurescript \n;; (which adds a lot of meta information to vars)","author":{"login":"kgann","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1098962?v=2"},"created-at":1413313971298,"updated-at":1440343358927,"editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/671872?v=3","account-source":"github","login":"hura"}],"_id":"543d75b3e4b0a3cf052fe476"},{"updated-at":1440343192893,"created-at":1440343192893,"author":{"login":"hura","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/671872?v=3"},"body":";; If you're REPLing you might want to re-define the defmulti dispatch function \n;; (which defmulti won't allow you to do). For this you can use `ns-unmap`:\n\n(defmulti x (fn[_] :inc))\n(defmethod x :inc [y] (inc y))\n(defmethod x :dec [y] (dec y))\n(x 0) ;; => 1\n(defmulti x (fn[_] :dec)) ;; Can't redefine :(\n(x 0) ;; => 1 ;; STILL :(\n(ns-unmap *ns* 'x) ;; => unmap the var from the namespace\n(defmulti x (fn[_] :dec))\n(x 0) ;; => Exception, we now need to redefine our defmethods.\n\n;; So in your file while developing you'd put the ns-unmap to the top of the file\n","_id":"55d9e498e4b0831e02cddf1b"},{"updated-at":1444625178263,"created-at":1444625178263,"author":{"login":"metasoarous","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/88556?v=3"},"body":";; It's nice for multimethods to have arglists metadata so that calling `doc`\n;; prints the arglist, instead of just the docstring. For example:\n\n(defmulti f \"Great function\" (fn [x] :blah))\n(doc f)\n;; -------------------------\n;; user/f\n;; Great function\n\n;; However, we can add `:arglists` metadata via a third (optional) argument to `defmulti` (`attr-map?` in the docstring for `defmulti`):\n\n(defmulti g \"Better function\" {:arglists '([x])} (fn [x] :blah))\n(doc g)\n;; -------------------------\n;; user/f\n;; ([x])\n;; Better function\n","_id":"561b3b1ae4b0b41dac04c957"},{"updated-at":1452157994440,"created-at":1452156707338,"author":{"login":"peter","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2008?v=3"},"body":"(defmulti compact map?)\n\n(defmethod compact true [map]\n (into {} (remove (comp nil? second) map)))\n\n(defmethod compact false [col]\n (remove nil? col))\n\n; Usage:\n\n(compact [:foo 1 nil :bar])\n; => (:foo 1 :bar)\n\n(compact {:foo 1 :bar nil :baz \"hello\"})\n; => {:foo 1, :baz \"hello\"}\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/2008?v=3","account-source":"github","login":"peter"}],"_id":"568e2723e4b0f37b65a3c27f"},{"editors":[{"login":"rauhs","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/11081351?v=3"},{"login":"MatthewDarling","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1369423?v=4"}],"body":";; This show how to do a wildcard match to a dispatch value:\n(defmulti xyz (fn [x y] [x y]))\n\n;; We don't care about the first argument:\n(defmethod xyz [::default :b]\n [x y]\n :d-b)\n\n;; We have to implement this manually:\n(defmethod xyz :default\n [x y]\n (let [existing (get-method xys [x y]\n recover (get-method xyz [::default y])\n ;; Prevent infinite loops with self-check\n self (get-method xyz :default)]\n (cond\n\n (and existing (not= existing self))\n (existing x y)\n\n (and recover (not= recover self))\n (do\n (println \"Found a default\")\n ;; Add the default to the internal cache:\n ;; Clojurescript will want (-add-method ...)\n (.addMethod ^MultiFn xyz [x y] recover)\n (recover ::default y))\n\n :else\n :default-return)))\n\n(xyz nil :b) ;; => :d-b\n;; only prints \"Found a default\" once!","author":{"avatar-url":"https://avatars.githubusercontent.com/u/11081351?v=3","account-source":"github","login":"rauhs"},"created-at":1465221190822,"updated-at":1731035983630,"_id":"57558046e4b0bafd3e2a0474"},{"updated-at":1484939584615,"created-at":1484939584615,"author":{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/94482?v=3"},"body":";; Extremely simple example, dispatching on a single field of the input map.\n;; Here we have a polymorphic map that looks like one of these two examples:\n\n;; {:name/type :split :name/first \"Bob\" :name/last \"Dobbs\"}\n;; {:name/type :full :name/full \"Bob Dobbs\"}\n\n(defmulti full-name :name/type)\n\n(defmethod full-name :full [name-data] \n (:name/full name-data))\n\n(defmethod full-name :split [name-data] \n (str (:name/first name-data) \" \" (:name/last name-data)))\n\n(defmethod full-name :default [_] \"???\")\n\n(full-name {:name/type :full :name/full \"Bob Dobbs\"})\n;; => \"Bob Dobbs\"\n\n(full-name {:name/type :split :name/first \"Bob\" :name/last \"Dobbs\"})\n;; => \"Bob Dobbs\"\n\n(full-name {:name/type :oops :name/full \"Bob Dobbs\"})\n;; => \"???\"\n","_id":"58826140e4b09108c8545a5b"},{"editors":[{"login":"green-coder","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/598193?v=4"}],"body":";;polymorphism classic example\n\n;;defmulti\n(defmulti draw :shape)\n\n;;defmethod\n(defmethod draw :square [geo-obj] (str \"Drawing a \" (:clr geo-obj) \" square\"))\n(defmethod draw :triangle [geo-obj] (str \"Drawing a \" (:clr geo-obj) \" triangle\"))\n\n(defn square [color] {:shape :square :clr color})\n(defn triangle [color] {:shape :triangle :clr color})\n\n(draw (square \"red\"))\n(draw (triangle \"green\"))","author":{"avatar-url":"https://avatars0.githubusercontent.com/u/31028993?v=4","account-source":"github","login":"ibercode"},"created-at":1510785469752,"updated-at":1531155016694,"_id":"5a0cc1bde4b0a08026c48cb9"},{"editors":[{"login":"siddharthjain-in","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/6537820?v=4"}],"body":";;defmulti with dispatch function\n(defmulti salary (fn [amount] (get amount :t)))\n\n;;defmethod provides a function implementation for a particular value\n(defmethod salary \"com\" [amount] (+ (:b amount) (/ (:b amount) 2)))\n(defmethod salary \"bon\" [amount] (+ (:b amount) 99))\n\n(salary {:t \"com\" :b 1000}) ;;1500\n(salary {:t \"bon\" :b 1000}) ;;1099 ","author":{"avatar-url":"https://avatars0.githubusercontent.com/u/31028993?v=4","account-source":"github","login":"ibercode"},"created-at":1510845199326,"updated-at":1707359331403,"_id":"5a0dab0fe4b0a08026c48cba"},{"updated-at":1568297637555,"created-at":1568297637555,"author":{"login":"the-frey","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/2385077?v=4"},"body":";; dispatch on the first argument\n(defmulti example-multimethod\n (fn [arg-one opts] arg-one))\n\n;; the opts are available in the defmethods\n(defmethod example-multimethod :path-one [_ opts]\n (println (:first-opt opts)))\n\n(defmethod example-multimethod :path-two [_ opts]\n (println (:second-opt opts)))\n\n(example-multimethod :path-one {:first-opt 1\n :second-opt 2})\n;; 1\n;; => nil","_id":"5d7a52a5e4b0ca44402ef7b3"},{"updated-at":1598457058014,"created-at":1598457058014,"author":{"login":"Gavlooth","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10321050?v=4"},"body":";; You can use multiarity in multimethods \n(defmulti foo (fn [x & _] x))\n\n(defmethod foo :default [_ & _] \"DEFAULT VALUE DISPACHED\")\n\n;; Like a standar multi-arity function\n(defmethod foo :bar \n ([_ _] \"ONE ARGUMENT\")\n ([_ _ _] \"TWO ARGUMENTs\")\n ([_ _ _ _] \"THREE ARGUMENTs\")\n ([_ _ _ _ & more] (cl-format nil \"~d ARGUMENTS\" (+ 3 (count more)))))\n \n(foo :baz 1)\n;; => \"DEFAULT VALUE DISPACHED\"\n\n(foo :bar 1)\n;; => \"ONE ARGUMENT\"\n\n(foo :bar 1 2)\n;; => \"TWO ARGUMENTs\"\n\n(foo :bar 1 2 3)\n;; => \"THREE ARGUMENTs\"\n\n(foo :bar 1 2 3 4 )\n;; => \"4 ARGUMENTS\"\n\n(foo :bar 1 2 3 4 5)\n;; => \"5 ARGUMENTS\"\n\n(foo :baz 1)\n;; => \"DEFAULT VALUE DISPACHED\"\n\n(foo :bar)\n; eval (current-form): (foo :bar)\n; (err) Execution error (ArityException) at user/eval22248 \n; (err) Wrong number of args (1) passed to: user/eval22204/fn--22205\n\n","_id":"5f4684e2e4b0b1e3652d73ad"},{"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/109629?v=4"}],"body":";; To call the dispatch function without dispatching to a method, \n;; just to examine the dispatch key\n(defmulti xyzzy (fn [x y] (+ x y)))\n((.dispatchFn xyzzy) 3 7)\n;; => 10\n\n;; The above is specific to Clojure on the JVM. In ClojureScript it is\n;; slightly different:\n((.-dispatch-fn xyzzy) 3 7)\n;; => 10","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/6414129?v=4","account-source":"github","login":"jimka2001"},"created-at":1601239335909,"updated-at":1601314098960,"_id":"5f70f927e4b0b1e3652d73c3"},{"updated-at":1712175357116,"created-at":1712175357116,"author":{"login":"kroncatti","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/56690659?v=4"},"body":";; Define the multimethod\n(defmulti my-test\n (fn [param1 param2] {:param1 param1 :param2 param2}))\n\n;; Defining handlers/implementation for resulting dispatch values \n(s/defmethod my-test {:param1 :something\n :param2 :something-else}\n [param1 :- s/Keyword\n param2 :- s/Keyword]\n (+ 3 4))\n\n(s/defmethod my-test {:param1 :this\n :param2 :that}\n [param1 :- s/Keyword\n param2 :- s/Keyword]\n (+ 4 5))\n\n(s/defmethod my-test :default\n [param1 :- s/Keyword\n param2 :- s/Keyword]\n \"ERROR\")\n\n;; Invoking it\n(my-test :something :something-else)\n;; => 7\n\n(my-test :something :undefined)\n;; Should go do the default because no other implementation was found, return \n;; => \"ERROR\"","_id":"660db8fd69fbcc0c226174b8"}],"macro":true,"notes":[{"updated-at":1290493285000,"body":"See also\r\n\r\nhttp://clojure.org/runtime_polymorphism\r\n\r\nhttp://clojure.org/multimethods\r\n\r\n","created-at":1290493285000,"author":{"login":"Victor","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bc41ebab54cc0e0fbe99d753876d45ce?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fa5"}],"arglists":["name docstring? attr-map? dispatch-fn & options"],"doc":"Creates a new multimethod with the associated dispatch function.\n The docstring and attr-map are optional.\n\n Options are key-value pairs and may be one of:\n\n :default\n\n The default dispatch value, defaults to :default\n\n :hierarchy\n\n The value used for hierarchical dispatch (e.g. ::square is-a ::shape)\n\n Hierarchies are type-like relationships that do not depend upon type\n inheritance. By default Clojure's multimethods dispatch off of a\n global hierarchy map. However, a hierarchy relationship can be\n created with the derive function used to augment the root ancestor\n created with make-hierarchy.\n\n Multimethods expect the value of the hierarchy option to be supplied as\n a reference type e.g. a var (i.e. via the Var-quote dispatch macro #'\n or the var special form).","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/defmulti"},{"added":"1.1","ns":"clojure.core","name":"chars","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"to-var":{"library-url":"https://github.com/clojure/clojure","name":"char-array","ns":"clojure.core"},"author":{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},"created-at":1342917427000,"_id":"542692eaf6e94c6970521bcf"}],"line":5411,"examples":[{"updated-at":1486713986324,"created-at":1486713986324,"author":{"login":"zezhenyan","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8064559?v=3"},"body":"user=> (seq (chars (char-array \"this is a good one\")))\n(\\t \\h \\i \\s \\space \\i \\s \\space \\a \\space \\g \\o \\o \\d \\space \\o \\n \\e)","_id":"589d7482e4b01f4add58fe44"},{"editors":[{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"}],"body":";; char-array will convert where possible\n(char-array \"foo\");; => [\\f, \\o, \\o]\n\n;; chars will not\n(try (chars \"foo\")\n (catch ClassCastException e (ex-message e)))\n;; => \"java.lang.String cannot be cast to [C\"\n","author":{"avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4","account-source":"github","login":"tomdl89"},"created-at":1656673310214,"updated-at":1656673548489,"_id":"62bed41ee4b0b1e3652d7615"},{"updated-at":1682278412171,"created-at":1682278412171,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":";; Casting avoids expensive reflection, so to see the benefit, enable warning:\n(set! *warn-on-reflection* true)\n\n;; We'll def a char-array but won't type-hint the var:\n(def my-array (char-array [\\f \\g \\h \\i \\j]))\n\n;; and try to amap over it without using `chars` or type hinting:\n(amap my-array i _ (-> my-array (aget i) clojure.string/capitalize first unchecked-char))\n;; Reflection warning… call to static method alength on clojure.lang.RT can't be resolved (argument types: unknown).\n;; Reflection warning… call to static method aclone on clojure.lang.RT can't be resolved (argument types: unknown).\n;; Reflection warning… call to static method aget on clojure.lang.RT can't be resolved (argument types: unknown, int).\n;; Reflection warning… call to static method aset on clojure.lang.RT can't be resolved (argument types: unknown, int, char).\n;; => [\\F, \\G, \\H, \\I, \\J]\n\n;; We can use `chars` to avoid reflection:\n(amap (chars my-array) i _ (-> (chars my-array) (aget i) clojure.string/capitalize first unchecked-char))\n;; => [\\F, \\G, \\H, \\I, \\J]\n\n;; Just as we can type hint in place:\n(amap ^chars my-array i _ (-> ^chars my-array (aget i) clojure.string/capitalize first unchecked-char))\n;; => [\\F, \\G, \\H, \\I, \\J]\n\n;; Or type hint the var:\n(def ^\"[C\" my-array (char-array [\\f \\g \\h \\i \\j]))\n(amap my-array i _ (-> my-array (aget i) clojure.string/capitalize first unchecked-char))\n;; => [\\F, \\G, \\H, \\I, \\J]\n","_id":"6445880ce4b08cf8563f4b94"}],"notes":null,"arglists":["xs"],"doc":"Casts to chars[]","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/chars"},{"added":"1.0","ns":"clojure.core","name":"str","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1347870090000,"author":{"login":"JR0cket","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1ff5786158c0be54051ef8e5c544555d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"pr","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e5e"},{"created-at":1347870109000,"author":{"login":"JR0cket","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1ff5786158c0be54051ef8e5c544555d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"prn","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e5f"},{"created-at":1423277783809,"author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"to-var":{"ns":"clojure.core","name":"pr-str","library-url":"https://github.com/clojure/clojure"},"_id":"54d57ed7e4b0e2ac61831d22"},{"created-at":1423277796681,"author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"to-var":{"ns":"clojure.core","name":"prn-str","library-url":"https://github.com/clojure/clojure"},"_id":"54d57ee4e4b0e2ac61831d23"},{"created-at":1423277811434,"author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"to-var":{"ns":"clojure.core","name":"print-str","library-url":"https://github.com/clojure/clojure"},"_id":"54d57ef3e4b0e2ac61831d24"},{"created-at":1423277823482,"author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"to-var":{"ns":"clojure.core","name":"println-str","library-url":"https://github.com/clojure/clojure"},"_id":"54d57effe4b0e2ac61831d25"}],"line":546,"examples":[{"author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"editors":[{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"belun","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8d3c423e74750fa42c0386833e4b8209?r=PG&default=identicon"},{"avatar-url":"https://avatars2.githubusercontent.com/u/24441401?v=4","account-source":"github","login":"themustafabasit"}],"body":"user=> \"some string\"\n\"some string\"\n\nuser=> (str)\n\"\"\n\nuser=> (str nil)\n\"\"\n\nuser=> (str 1)\n\"1\"\n\nuser=> (str 1 2 3)\n\"123\"\n\nuser=> (str 1 'symbol :keyword)\n\"1symbol:keyword\"\n\n;; A very common usage of str is to apply it to an existing collection:\nuser=> (apply str [1 2 3])\n\"123\"\n\n;; compare it with:\nuser=> (str [1 2 3])\n\"[1 2 3]\"\n\n","created-at":1279191631000,"updated-at":1599671667197,"_id":"542692ccc026201cdc326c5f"},{"author":{"login":"belun","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8d3c423e74750fa42c0386833e4b8209?r=PG&default=identicon"},"editors":[{"login":"belun","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8d3c423e74750fa42c0386833e4b8209?r=PG&default=identicon"},{"login":"belun","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8d3c423e74750fa42c0386833e4b8209?r=PG&default=identicon"}],"body":";; Destructuring with a string, getting just a few characters from it\nuser=> (let [[first-char second-char] \"abcde\"] \n (prn 'first= first-char) \n (prn 'second= second-char))\nfirst= \\a\nsecond= \\b\nnil\n\n;; More destructuring with a string\nuser=> (let [[first-char second-char & rest-of-chars] \"abcde\"] \n (prn 'first= first-char) \n (prn 'second= second-char) \n (prn 'rest= rest-of-chars))\nfirst= \\a\nsecond= \\b\nrest= (\\c \\d \\e)\nnil\n\n;; Destructuring, getting the first character of a string\n;; and then a reference to the entire string\nuser=> (let [[first-char :as all-the-string] \"abcde\"] \n (prn 'first= first-char) \n (prn 'all= all-the-string))\nfirst= \\a\nall= \"abcde\"\nnil","created-at":1285683003000,"updated-at":1285683237000,"_id":"542692ccc026201cdc326c64"},{"updated-at":1471001180731,"created-at":1471001180731,"author":{"login":"Lacty","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7412474?v=3"},"body":"user=> (str \"L\" \"a\")\n\"La\"\n\nuser=> (str \"L\" 5 \"a\")\n\"L5a\"","_id":"57adb25ce4b0bafd3e2a04ef"},{"updated-at":1517964096633,"created-at":1517964096633,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"},"body":";; sometimes when printing lazy sequences you do not get what you want.\n(str (take 5 (range 10)))\n;=> \"clojure.lang.LazySeq@1b554e1\"\n\n;; in those cases `pr-str` to the rescue.\n(pr-str (take 5 (range 10)))\n;=> \"(0 1 2 3 4)\"","_id":"5a7a4b40e4b0e2d9c35f7422"},{"updated-at":1527025723311,"created-at":1527025723311,"author":{"login":"operasfantom","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/31903947?v=4"},"body":";; be careful with java.lang.Double to java.lang.String conversion\n(str -128004972.0)\n;=> \"-1.28004972E8\"\n","_id":"5b04903be4b045c27b7fac74"},{"updated-at":1547468102218,"created-at":1547468102218,"author":{"login":"RayceeM","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/28865179?v=4"},"body":";; Using str in maps\n(def user-map {:fname \"Jane\" :sname \"Doe\"})\n\n;;getting the value of the first key \n(:fname user-map)\n;=> \"Jane\"\n\n(str (:fname user-map) \" \" (:sname user-map))\n;=> \"Jane Doe\"","_id":"5c3c7d46e4b0ca44402ef61b"},{"updated-at":1599671842283,"created-at":1599671842283,"author":{"login":"themustafabasit","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/24441401?v=4"},"body":"(str nil)\n;; => \"\"\n\n(str true)\n;; => \"true\"\n\n(str false)\n;; => \"false\"\n","_id":"5f590e22e4b0b1e3652d73b6"},{"updated-at":1755666382343,"created-at":1755666382343,"author":{"login":"E-A-Griffin","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/53583563?v=4"},"body":";; Characters are converted to strings of size 1\n(str \\space)\n;; => \" \"\n\n;; Occasionally you may want a string representation of clojure's character syntax \n;; for a particular character, wrapping the char in a data structure \n;; before calling [[str]] is one workaround\n(defn char->str [c] (let [s (str [c])] (subs s 1 (dec (count s)))))\n;; => #'user/char->str\n\n(char->str \\space)\n;; => \"\\\\space\"","_id":"68a557cecd84df5de54e208e"}],"notes":null,"tag":"java.lang.String","arglists":["","x","x & ys"],"doc":"With no args, returns the empty string. With one arg x, returns\n x.toString(). (str nil) returns the empty string. With more than\n one arg, returns the concatenation of the str values of the args.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/str"},{"added":"1.0","ns":"clojure.core","name":"next","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1289038123000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"rest","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cc7"},{"created-at":1289038131000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"first","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cc8"},{"created-at":1344490440000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"fnext","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cc9"},{"created-at":1505013547909,"author":{"login":"didibus","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/601540?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"nthrest","ns":"clojure.core"},"_id":"59b4af2be4b09f63b945ac6c"},{"created-at":1505013554008,"author":{"login":"didibus","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/601540?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"nthnext","ns":"clojure.core"},"_id":"59b4af32e4b09f63b945ac6d"}],"line":57,"examples":[{"author":{"login":"dpritchett","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/147981?v=3"},"editors":[{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"}],"body":"user=> (next '(:alpha :bravo :charlie))\n(:bravo :charlie)\n\nuser=> (next (next '(:one :two :three)))\n(:three)\n\nuser=> (next (next (next '(:one :two :three))))\nnil","created-at":1279071284000,"updated-at":1289038286000,"_id":"542692c8c026201cdc3269fb"},{"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"editors":[{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},{"login":"steveminer","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d28543d134185d12d4006a74738d233e?r=PG&default=identicon"},{"login":"steveminer","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d28543d134185d12d4006a74738d233e?r=PG&default=identicon"}],"body":";; next is used in the recursive call. (This is a naive implementation for illustration only. Using `rest` is usually preferred over `next`.)\n\n(defn my-map [func a-list]\n (when a-list\n (cons (func (first a-list))\n (my-map func (next a-list)))))","created-at":1289038112000,"updated-at":1306984795000,"_id":"542692c8c026201cdc3269fd"},{"body":";; Difference between next and rest:\n\n(next [:a])\n;; => nil\n(rest [:a])\n;; => ()\n\n(next [])\n;; => nil\n(rest [])\n;; => ()\n\n(next nil)\n;; => nil\n(rest nil)\n;; => ()","author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"created-at":1423016858063,"updated-at":1423094962892,"editors":[{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"}],"_id":"54d1839ae4b0e2ac61831d05"}],"notes":[{"updated-at":1306987897000,"body":"
    (next aseq) === (seq (rest aseq))
    \r\n\r\nWhen writing lazy sequence functions, you should use [rest](../clojure.core/rest), not next.","created-at":1306984569000,"author":{"login":"steveminer","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d28543d134185d12d4006a74738d233e?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fc0"}],"tag":"clojure.lang.ISeq","arglists":["coll"],"doc":"Returns a seq of the items after the first. Calls seq on its\n argument. If there are no more items, returns nil.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/next"},{"added":"1.0","ns":"clojure.core","name":"hash-map","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1317787775000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"merge","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b50"},{"created-at":1320356522000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"assoc","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b51"},{"created-at":1320356532000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"dissoc","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b52"},{"created-at":1397669031000,"author":{"login":"ryo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3f7913b563c72083c74030d928ba407e?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"array-map","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b53"},{"created-at":1397669038000,"author":{"login":"ryo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3f7913b563c72083c74030d928ba407e?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"sorted-map","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b54"},{"created-at":1437362390089,"author":{"login":"ljosa","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/197881?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"into","ns":"clojure.core"},"_id":"55ac68d6e4b06a85937088b2"},{"created-at":1474932016523,"author":{"login":"olivergeorge","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/99447?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"zipmap","ns":"clojure.core"},"_id":"57e9ad30e4b0709b524f050d"},{"created-at":1517623031883,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"keys","ns":"clojure.core"},"_id":"5a7516f7e4b0e2d9c35f7413"},{"created-at":1517623038263,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"vals","ns":"clojure.core"},"_id":"5a7516fee4b0e2d9c35f7414"}],"line":381,"examples":[{"author":{"login":"zmila","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/68dd6f50915854aa04fefcf4d6fa5c8e?r=PG&default=identicon"},"editors":[{"login":"belun","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8d3c423e74750fa42c0386833e4b8209?r=PG&default=identicon"},{"login":"rafmagana","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/92894?v=3"},{"login":"AtKaaZ","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e10dfa345f44b0fe72bbe081fd51b83?r=PG&default=identicon"},{"login":"pilku","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/2970556?v=4"}],"body":";; create hash map the long way\nuser=> (hash-map)\n{}\n\n;; create array map the short way\nuser=> {}\n{}\n\n;; sending a key more times, will remap it to the last value\nuser=> (hash-map :key1 1, :key1 2) \n{:key1 2} \n\nuser=> {:key1 1, :key1 2}\nIllegalArgumentException Duplicate key: :key1 clojure.lang.PersistentArrayMap.createWithCheck (PersistentArrayMap.java:70)\n\n\nuser=> (hash-map :key1 'val1, 'key2 :val2, [:compound :key] nil)\n{[:compound :key] nil, :key1 val1, key2 :val2} \n\n","created-at":1280353272000,"updated-at":1591472591014,"_id":"542692cfc026201cdc326e1f"},{"author":{"login":"zmila","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/68dd6f50915854aa04fefcf4d6fa5c8e?r=PG&default=identicon"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":"user=> (map #(hash-map % 0) (seq \"abcdefgh\"))\n({\\a 0} {\\b 0} {\\c 0} {\\d 0} {\\e 0} {\\f 0} {\\g 0} {\\h 0}) \n\nuser=> (apply hash-map (.split \"a 1 b 2 c 3\" \" \"))\n{\"a\" \"1\", \"b\" \"2\", \"c\" \"3\"}","created-at":1280353365000,"updated-at":1332950168000,"_id":"542692cfc026201cdc326e23"},{"author":{"login":"dipto_sarkar","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/c1d3141a40d240f0918260201aaa0b01?r=PG&default=identicon"},"editors":[{"login":"dipto_sarkar","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/c1d3141a40d240f0918260201aaa0b01?r=PG&default=identicon"},{"login":"roryokane","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5b2b185c814bb25f2f95a1152e58f033?r=PG&default=identicon"}],"body":"; a hash map can be stored in a var by using `def`\nuser=> (def person {:name \"Steve\" :age 24 :salary 7886 :company \"Acme\"})\n#'user/person\nuser=> person\n{:age 24, :name \"Steve\", :salary 7886, :company \"Acme\"}","created-at":1341478710000,"updated-at":1388572400000,"_id":"542692d3c026201cdc326fc4"},{"updated-at":1463334174783,"created-at":1342846621000,"body":";; Take a sequence of sequences (vector of vectors), and create a map\n;; using date as the map key.\n(def csv1 [[\"01/01/2012\" 1 2 3 4][\"06/15/2012\" 38 24 101]])\n\n(map #(hash-map (keyword (first %1)) (vec (rest %1))) csv1)\n;;=> ({:01/01/2012 [1 2 3 4]} {:06/15/2012 [38 24 101]})\n\n;; merge the list of maps into a single map\n(apply merge '({\"01/01/2012\" [1 2 3 4]} {\"06/15/2012\" [38 24 101]}))\n;;=> {\"06/15/2012\" [38 24 101], \"01/01/2012\" [1 2 3 4]}\n\n","editors":[{"avatar-url":"https://www.gravatar.com/avatar/b11cdeef90d84ff8af2a2c5012402939?r=PG&default=identicon","account-source":"clojuredocs","login":"Deadron"},{"avatar-url":"https://www.gravatar.com/avatar/b11cdeef90d84ff8af2a2c5012402939?r=PG&default=identicon","account-source":"clojuredocs","login":"Deadron"},{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3","account-source":"github","login":"phreed"},{"login":"TradeIdeasPhilip","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/18409827?v=3"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/fd31b8bcea99fa7b0711fbc424587774?r=PG&default=identicon","account-source":"clojuredocs","login":"octopusgrabbus"},"_id":"542692d3c026201cdc326fc7"},{"updated-at":1459028606947,"created-at":1459028606947,"author":{"login":"smnplk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/380618?v=3"},"body":"(apply hash-map [:a 1 :b 2])\n;;=> {:b 2 :a 1}\n\n;;is the same as\n(def build-map (partial assoc {}))\n(apply build-map [:a 1 :b 2])\n;;=> {:b 2 :a 1}","_id":"56f7027ee4b0103e9c7d9d26"},{"editors":[{"login":"rebcabin","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/207047?v=4"},{"avatar-url":"https://avatars3.githubusercontent.com/u/11434205?v=4","account-source":"github","login":"dijonkitchen"}],"body":";; A hash map acts like a lookup function taking a key as first argument:\n({:a 1, :b 2} :a)\n;;=> 1\n\n;; If the key is not present, nil is returned...\n({:a 1, :b 2} :qwerty)\n;;=> nil\n\n;; ... unless there is a second argument, which becomes the default value to\n;; return when the lookup key is not found:\n({:a 1, :b 2} :qwerty :uiop)\n;;=> :uiop\n\n;; That behavior can lead to surprises:\n(let [map-example {:a 1, :b 2}]\n (map-example #(* % %) (range 10)))\n;;=> (0 1 2 3 4 5 6 7 8 9) \n;; since (range 10) is the default and #(* % %) is an anonymous function that isn't a key in map-example\n\n;; It may be more explicit to use get instead\n(get {:a 1, :b 2} :qwerty :uiop)\n;;=> :uiop","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/207047?v=4","account-source":"github","login":"rebcabin"},"created-at":1563554106051,"updated-at":1587741064160,"_id":"5d31f13ae4b0ca44402ef788"}],"notes":[{"author":{"login":"er2","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/4515131?v=4"},"updated-at":1670789233819,"created-at":1670789233819,"body":"If you want to create a map from a sequence of pairs, e.g. `[[k1 v1] [k2 v2]]`, see [`into`](https://clojuredocs.org/clojure.core/into).","_id":"63963871e4b0b1e3652d7698"}],"arglists":["","& keyvals"],"doc":"keyval => key val\n Returns a new hash map with supplied mappings. If any keys are\n equal, they are handled as if by repeated uses of assoc.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/hash-map"},{"added":"1.0","ns":"clojure.core","name":"if-let","file":"clojure/core.clj","type":"macro","column":1,"see-alsos":[{"created-at":1293436184000,"author":{"login":"0x89","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/56bc4acd59315ed4dc1cb99c3be71102?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"when-let","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d88"},{"created-at":1315004464000,"author":{"login":"srid","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bd3a68d670372cd09876c26270a4299a?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"if","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d89"},{"created-at":1440455843468,"author":{"login":"brunchboy","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2228869?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"if-some","ns":"clojure.core"},"_id":"55db9ca3e4b072d7f27980f0"}],"line":1858,"examples":[{"updated-at":1285499963000,"created-at":1279379785000,"body":"user=> (defn sum-even-numbers [nums]\n (if-let [nums (seq (filter even? nums))]\n (reduce + nums)\n \"No even numbers found.\"))\n#'user/sum-even-numbers\n\nuser=> (sum-even-numbers [1 3 5 7 9])\n\"No even numbers found.\"\n\nuser=> (sum-even-numbers [1 3 5 7 9 10 12])\n22\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/142529?v=3","account-source":"github","login":"nipra"},"_id":"542692cdc026201cdc326cf5"},{"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"editors":[{"login":"nipra","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/142529?v=3"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"}],"body":" (if-let [x false y true]\n \"then\"\n \"else\")\n;; java.lang.IllegalArgumentException: if-let requires exactly 2 forms in binding vector (NO_SOURCE_FILE:1)\n;; see if-let* below\n\n(defn if-let-demo [arg]\n (if-let [x arg]\n \"then\"\n \"else\"))\n\n(if-let-demo 1) ; anything except nil/false\n;;=> \"then\"\n(if-let-demo nil)\n;;=> \"else\"\n(if-let-demo false)\n;;=> \"else\"\n","created-at":1279489140000,"updated-at":1508883080013,"_id":"542692cdc026201cdc326cf7"},{"updated-at":1529851111869,"created-at":1305844049000,"body":";; This macro is nice when you need to calculate something big. And you need \n;; to use the result but only when it's true:\n\n(if-let [life (meaning-of-life 12)]\n life\n (if-let [origin (origin-of-life 1)]\n origin\n (if-let [shooter (who-shot-jr 5)]\n shooter\n\t 42)))\n\n;; As you can see in the above example it will return the answer \n;; to the question only if the answer is not nil. If the answer\n;; is nil it will move to the next question. Until finally it\n;; gives up and returns 42.","editors":[{"avatar-url":"https://avatars2.githubusercontent.com/u/22608?v=4","account-source":"github","login":"MrHus"},{"avatar-url":"https://avatars2.githubusercontent.com/u/22608?v=4","account-source":"github","login":"MrHus"},{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"login":"green-coder","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/598193?v=4"}],"author":{"login":"MrHus","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/22608?v=4"},"_id":"542692cdc026201cdc326cfa"},{"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"editors":[],"body":";; See examples for \"if\" explaining Clojure's idea of logical true\n;; and logical false.","created-at":1334293326000,"updated-at":1334293326000,"_id":"542692d3c026201cdc326fcb"},{"author":{"login":"ryo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3f7913b563c72083c74030d928ba407e?r=PG&default=identicon"},"editors":[{"login":"schmee","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/3405586?v=3"}],"body":";;; with destructuring binding\n\n;; successful case\n(if-let [[w n] (re-find #\"a(\\d+)x\" \"aaa123xxx\")]\n [w n]\n :not-found) ;=> [\"a123x\" \"123\"]\n\n;; unsuccessful case\n(if-let [[w n] (re-find #\"a(\\d+)x\" \"bbb123yyy\")]\n [w n]\n :not-found) ;=> :not-found\n\n;; same as above\n(if-let [[w n] nil]\n [w n]\n :not-found) ;=> :not-found\n\n;; on Map\n(if-let [{:keys [a b]} nil]\n [a b]\n :not-found) ;=> :not-found\n","created-at":1399644384000,"updated-at":1420673793910,"_id":"542692d3c026201cdc326fcc"},{"body":";; Note that the binding only extends to the then form, not to the else:\nuser=> (if-let [x nil] \"then\" x)\nCompilerException java.lang.RuntimeException: Unable to resolve symbol:\nx in this context, compiling: ...","author":{"login":"mars0i","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1836941?v=3"},"created-at":1418536023963,"updated-at":1418536080362,"editors":[{"login":"mars0i","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1836941?v=3"}],"_id":"548d2457e4b04e93c519ffa7"},{"body":";; Works well with collections\n\n(def x {:whatever 1})\n\n(if-let [value (:whatever x)] value \"Not found\")\n;=> 1\n\n(if-let [value (:no-match x)] value \"Not found\")\n;=> \"Not found\"\n\n\n;; But destructuring presents a gotcha\n\n(if-let [{:keys [whatever]} x] whatever \"Not found\")\n;=> 1\n\n(if-let [{:keys [:no-match]} nil] no-match \"Not found\")\n;=> \"Not found\"\n\n(if-let [{:keys [no-match]} x] no-match \"Not found\")\n;=> nil\n\n(if-let [[a] [1 2 3]] a \"Not found\")\n;=> 1\n\n(if-let [[a] nil] a \"Not found\")\n;=> \"Not found\"\n\n(if-let [[a] []] a \"Not found\")\n;=> nil","author":{"login":"mattvvhat","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/367789?v=3"},"created-at":1428550556244,"updated-at":1768813183289,"editors":[{"login":"mattvvhat","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/367789?v=3"},{"avatar-url":"https://avatars.githubusercontent.com/u/2713?v=3","account-source":"github","login":"antonmos"},{"login":"pikariop","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1998952?v=4"}],"_id":"5525f39ce4b033f34014b76a"},{"updated-at":1587464733428,"created-at":1469577276189,"author":{"login":"ertugrulcetin","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8271291?v=3"},"body":";; if-let multiple bindings version\n;; Edited: Else branch did not work with expressions.\n\n(defmacro if-let*\n ([bindings then]\n `(if-let* ~bindings ~then nil))\n ([bindings then else]\n (if (seq bindings)\n `(if-let [~(first bindings) ~(second bindings)]\n (if-let* ~(drop 2 bindings) ~then ~else)\n ~else)\n then)))\n\n(if-let* [a 1\n b (+ a 1) ]\n b)\n;;=> 2\n\n(if-let* [a 1\n b (+ a 1)\n c false] ;;false or nil - does not matter\n b\n a)\n;;=> 1\n\n;; Note that this implementation short-curcuits on false so that the prn form \n;; is _not_ evaluated in the below form.\n(if-let* [a false\n b (prn \"Do we evaluate this?\")]\n true\n false)\n;;=> false","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/8271291?v=3","account-source":"github","login":"ertugrulcetin"},{"login":"LukasRychtecky","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/585068?v=3"},{"avatar-url":"https://avatars2.githubusercontent.com/u/632775?v=4","account-source":"github","login":"Rovanion"}],"_id":"5797f83ce4b0bafd3e2a04b9"},{"updated-at":1499190178133,"created-at":1499190178133,"author":{"login":"claresudbery","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/8990232?v=3"},"body":";; (if-let [definition condition] then else):\n;; if the value of condition is truthy, then that value is assigned to the definition, \n;; and \"then\" is evaluated.\n;; Otherwise the value is NOT assigned to the definition, and \"else\" is evaluated.\n\n;; Although you can use this structure with booleans, \n;; there's not much point unless you only want to\n;; use the resulting boolean if it's true - as evidenced in the first example below.\n;; if-let is mostly useful when checking for nil.\n\n;; In this first example if Clare is old, it outputs \"Clare is old\".\n;; (the let part of the statement is rather pointless, \n;; as the definition old-clare-age is never used).\n\n(def clare-age 47)\n(if-let [old-clare-age (> clare-age 100)] \n \"Clare is old\" \n \"Clare is not old\")\n;;=> Clare is not old\n\n;; In the next two examples, it only outputs Clare's age if it is valid (ie not nil)\n\n(def clare-age nil)\n(if-let [valid-clare-age clare-age] \n (str \"Clare has a valid age: \" valid-clare-age) \n \"Clare's age is invalid\")\n;;=> Clare's age is invalid\n\n(def clare-age 47)\n(if-let [valid-clare-age clare-age] \n (str \"Clare has a valid age: \" valid-clare-age) \n \"Clare's age is invalid\")\n;;=> Clare has a valid age: 47","_id":"595bd3a2e4b06e730307db4d"},{"updated-at":1534962715587,"created-at":1534962715587,"author":{"login":"midnio","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/36359066?v=4"},"body":"(if-let [value true]\n \"The expression is true!\"\n \"Sorry, it's not true.\")","_id":"5b7dac1be4b00ac801ed9e6c"},{"updated-at":1535296034148,"created-at":1535296034148,"author":{"login":"cuspymd","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/8870299?v=4"},"body":";; Destructuring maps\n(def x {:it 1 :that 2})\n(def y {:that 2}\n(if-let [{value :it} x] value \"Not found\") ;;=> 1\n(if-let [{value :it} nil] value \"Not found\") ;;=> \"Not found\"\n(if-let [{value :it} false] value \"Not found\") ;;=> \"Not found\"\n(if-let [{value :it} y] value \"Not found\") ;;=> nil\n(if-let [{value :it} {}] value \"Not found\") ;;=> nil\n(if-let [{value :it} 1] value \"Not found\") ;;=> nil","_id":"5b82c222e4b00ac801ed9e78"},{"editors":[{"login":"arlicle","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/153773?v=4"},{"avatar-url":"https://avatars2.githubusercontent.com/u/632775?v=4","account-source":"github","login":"Rovanion"}],"body":";; if-let multiple bindings version\n(defmacro if-let*\n ([bindings-vec then] `(if-let* ~bindings-vec ~then nil))\n ([bindings-vec then else]\n (if (seq bindings-vec)\n `(let ~bindings-vec\n (if (and ~@(take-nth 2 bindings-vec))\n ~then\n ~else)))))\n\n\n(if-let* [a 1\n b (+ a 1) ]\n b)\n;;=> 2\n\n(if-let* [a 1\n b (+ a 1)\n c false] ;;false or nil - does not matter\n b\n a)\n;;=> 1 \n\n;; Note that this implementation does _not_ short-circuit on falsey forms.\n(if-let* [a false\n b (prn \"Do we evaluate this?\")]\n true\n false)\n;; \"Do we evaluate this?\"\n;;=> false\n","author":{"avatar-url":"https://avatars3.githubusercontent.com/u/153773?v=4","account-source":"github","login":"arlicle"},"created-at":1536027516561,"updated-at":1587464633192,"_id":"5b8deb7ce4b00ac801ed9e81"},{"updated-at":1565305899936,"created-at":1565305899936,"author":{"login":"metacritical","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/760429?v=4"},"body":";; Check if the value is true print it otherwise not.\n\n(def log-output \"\") \n\n;; Assume log-output could be the result of another operation like\n;; (def log-output (Gl/ShaderInfoLog shader))\n;; The Following will only print, when logout is not empty.\n\n(if-let [out (not-empty logout)]\n (println out))\n","_id":"5d4cac2be4b0ca44402ef794"},{"updated-at":1590171632153,"created-at":1590171632153,"author":{"login":"themustafabasit","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/24441401?v=4"},"body":";; fun of if-let \n(defn some-condition\n [data]\n true)\n\n(let [result (some-condition \"ABC\")]\n (if (true? result)\n \"Success\"\n \"Failure\"))\n;; => \"success\"\n\n;; if-let in Action\n(if-let [result (some-condition \"ABC\")]\n \"Success\"\n \"Failure\")\n;; => \"success\"\n","_id":"5ec817f0e4b087629b5a1911"}],"macro":true,"notes":[{"updated-at":1299054285000,"body":"The difference between when-let and if-let is that when-let doesn't have an else clause and and also accepts multiple forms so you don't need to use a (do...).","created-at":1299054285000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fb5"},{"updated-at":1326335082000,"body":"I wonder what motivates the restriction of only one binding, e.g. many Schemes implement an `and-let*` form which allows multiple bindings, evaluating them in order and breaking out on the first binding that evaluates to false. Can somebody shed some light on this?","created-at":1326335082000,"author":{"login":"DerGuteMoritz","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/66bba784787f4f725b1568ec69a616cc?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fd6"}],"arglists":["bindings then","bindings then else & oldform"],"doc":"bindings => binding-form test\n\n If test is true, evaluates then with binding-form bound to the value of \n test, if not, yields else","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/if-let"},{"added":"1.0","ns":"clojure.core","name":"underive","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1524236415414,"author":{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"derive","ns":"clojure.core"},"_id":"5ada007fe4b045c27b7fac49"}],"line":5717,"examples":[{"author":{"login":"shockbob","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon"},"editors":[{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"}],"body":";; create a simple hierarchy using the global hierarchy\n;; and demonstrate how underive is used\n\nuser=> (derive ::dog ::animal)\nnil\nuser=> (derive ::spaniel ::dog)\nnil\nuser=> (derive ::tabby ::dog)\nnil\nuser=> (ancestors ::tabby)\n#{:user/dog :user/animal}\nuser=> (underive ::tabby ::dog)\nnil\nuser=> (ancestors ::tabby)\nnil","created-at":1313962237000,"updated-at":1423522531628,"_id":"542692cdc026201cdc326d0f"}],"notes":null,"arglists":["tag parent","h tag parent"],"doc":"Removes a parent/child relationship between parent and\n tag. h must be a hierarchy obtained from make-hierarchy, if not\n supplied defaults to, and modifies, the global hierarchy.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/underive"},{"added":"1.1","ns":"clojure.core","name":"ref-max-history","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1323973069000,"author":{"login":"Claj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5fd658a8d2ef549071cb5286b1b874aa?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"ref","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ecf"},{"created-at":1364770314000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"ref-min-history","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ed0"},{"created-at":1364770319000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"ref-history-count","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ed1"}],"line":2496,"examples":null,"notes":null,"arglists":["ref","ref n"],"doc":"Gets the max-history of a ref, or sets it and returns the ref","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/ref-max-history"},{"added":"1.7","ns":"clojure.core","name":"Throwable->map","file":"clojure/core_print.clj","type":"function","column":1,"see-alsos":[{"created-at":1538988481625,"author":{"login":"cljlc","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/36645452?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"ex-data","ns":"clojure.core"},"_id":"5bbb19c1e4b00ac801ed9eb7"}],"line":473,"examples":[{"updated-at":1450285594446,"created-at":1450285594446,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/20086?v=3"},"body":"(def trace (try (/ 1 0) (catch Throwable t (Throwable->map t))))\n(keys trace)\n;; (:cause :via :trace)\n(:cause trace)\n;; \"Divide by zero\"\n(count (:trace trace))\n;; 33 (this stack trace is 33 invocations deep) ","_id":"56719a1ae4b08a391679537c"}],"notes":null,"arglists":["o"],"doc":"Constructs a data representation for a Throwable with keys:\n :cause - root cause message\n :phase - error phase\n :via - cause chain, with cause keys:\n :type - exception class symbol\n :message - exception message\n :data - ex-data\n :at - top stack element\n :trace - root cause stack elements","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/Throwable->map"},{"added":"1.0","ns":"clojure.core","name":"false?","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1375213349000,"author":{"login":"alilee","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2fb0196dc5a7cd3a5cc73f1b9941c209?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"not","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521efc"}],"line":507,"examples":[{"author":{"login":"samaaron","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/ee3512261f38df2541b9adca77f025cb?r=PG&default=identicon"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":"(false? false) ;=> true\n(false? true) ;=> false\n(false? nil) ;=> false\n(false? \"foo\") ;=> false","created-at":1278738764000,"updated-at":1332950044000,"_id":"542692c7c026201cdc32699d"}],"notes":null,"tag":"java.lang.Boolean","arglists":["x"],"doc":"Returns true if x is the value false, false otherwise.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/false_q"},{"added":"1.0","ns":"clojure.core","name":"*print-readably*","type":"var","see-alsos":null,"examples":[{"updated-at":1620478814999,"created-at":1620478814999,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/20086?v=4"},"body":";; Showing how *print-readably* is used internally to escape/unescape control\n;; characters:\n\n(binding [*print-readably* false]\n (pr \"a\\nb\\nc\"))\n;; a\n;; b\n;; cnil\n\n;; Only use to change behaviour of code you don't control.\n;; Otherwise, it's equivalent to `print`:\n(print \"a\\nb\\nc\")\n;; a\n;; b\n;; cnil\n","_id":"60968b5ee4b0b1e3652d74f6"}],"notes":null,"arglists":[],"doc":"When set to logical false, strings and characters will be printed with\n non-alphanumeric characters converted to the appropriate escape sequences.\n\n Defaults to true","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/*print-readably*"},{"added":"1.0","ns":"clojure.core","name":"ints","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1299221089000,"author":{"login":"TimMc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5d532e51427ef2f4ded31aaca16c8baf?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"int-array","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bc6"}],"line":5426,"examples":[{"updated-at":1656672965213,"created-at":1656672965213,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":"(def my-floats (float-array [1.1 2.2 3.3]));; => #'user/my-floats\n\n;; int-array will convert where possible\n(int-array my-floats);; => [1, 2, 3]\n\n;; ints will not\n(try (ints my-floats)\n (catch ClassCastException e (ex-message e)));; => \"[F cannot be cast to [I\"\n","_id":"62bed2c5e4b0b1e3652d7613"},{"updated-at":1682268162146,"created-at":1682268162146,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":";; Casting avoids expensive reflection, so to see the benefit, enable warning:\n(set! *warn-on-reflection* true)\n\n;; We'll def an int-array but won't type-hint the var:\n(def my-array (int-array [10 20 30 40 50 60]))\n\n;; and try to amap over it without using `ints` or type hinting:\n(amap my-array i _ (unchecked-inc-int (aget my-array i)))\n;; Reflection warning… call to static method alength on clojure.lang.RT can't be resolved (argument types: unknown).\n;; Reflection warning… call to static method aclone on clojure.lang.RT can't be resolved (argument types: unknown).\n;; Reflection warning… call to static method aget on clojure.lang.RT can't be resolved (argument types: unknown, int).\n;; Reflection warning… call to static method aset on clojure.lang.RT can't be resolved (argument types: unknown, int, int).\n;; => [11, 21, 31, 41, 51, 61]\n\n;; We can use `ints` to avoid reflection:\n(amap (ints my-array) i _ (unchecked-inc-int (aget (ints my-array) i)))\n;; => [11, 21, 31, 41, 51, 61]\n\n;; Just as we can type hint in place:\n(amap ^ints my-array i _ (unchecked-inc-int (aget ^ints my-array i)))\n;; => [11, 21, 31, 41, 51, 61]\n\n;; Or type hint the var:\n(def ^\"[I\" my-array (int-array [10 20 30 40 50 60]))\n(amap my-array i _ (unchecked-inc-int (aget my-array i)))\n;; => [11, 21, 31, 41, 51, 61]\n","_id":"64456002e4b08cf8563f4b8e"}],"notes":null,"arglists":["xs"],"doc":"Casts to int[]","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/ints"},{"added":"1.0","ns":"clojure.core","name":"class","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1281949437000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"type","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521a95"},{"created-at":1325041755000,"author":{"login":"Claj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5fd658a8d2ef549071cb5286b1b874aa?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"class?","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521a96"},{"created-at":1357883208000,"author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"to-var":{"ns":"clojure.core","name":"instance?","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521a97"}],"line":3486,"examples":[{"updated-at":1451352065851,"created-at":1280546296000,"body":"user=> (class 1)\njava.lang.Long\n\nuser=> (class [1 2 3])\nclojure.lang.PersistentVector\n\nuser=> (class (String. \"foo\"))\njava.lang.String","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3","account-source":"github","login":"jafingerhut"},{"login":"rtoal","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/538615?v=3"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/bcacd00a7f05c4772329cf9f446c7987?r=PG&default=identicon","account-source":"clojuredocs","login":"dakrone"},"_id":"542692cac026201cdc326b68"},{"editors":[{"login":"rtoal","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/538615?v=3"}],"body":"user=> (class class)\nclojure.core$class","author":{"avatar-url":"https://avatars.githubusercontent.com/u/538615?v=3","account-source":"github","login":"rtoal"},"created-at":1451352054083,"updated-at":1451352297752,"_id":"5681dff6e4b01f598e267e93"},{"updated-at":1474629795271,"created-at":1474629795271,"author":{"login":"jfacorro","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1522569?v=3"},"body":"user=> (class nil)\nnil","_id":"57e510a3e4b0709b524f0509"},{"updated-at":1726884771055,"created-at":1726884771055,"author":{"login":"wlkr","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/5406568?v=4"},"body":";; attempting to get the class of a macro fails (see also `type`)\nuser=> (class let)\nCan't take value of a macro: #'clojure.core/let","_id":"66ee2ba369fbcc0c226174fa"}],"notes":null,"arglists":["x"],"doc":"Returns the Class of x","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/class"},{"added":"1.3","ns":"clojure.core","name":"some-fn","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1348529537000,"author":{"login":"hugoduncan","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/80fa2a15219b987664e4d6f5c78b4c27?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"every-pred","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ecd"},{"created-at":1374512408000,"author":{"login":"alilee","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2fb0196dc5a7cd3a5cc73f1b9941c209?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"some","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ece"},{"created-at":1461817364964,"author":{"login":"bkovitz","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/4142015?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"some->","ns":"clojure.core"},"_id":"57219014e4b0fc95a97eab5f"},{"created-at":1461817376595,"author":{"login":"bkovitz","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/4142015?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"some->>","ns":"clojure.core"},"_id":"57219020e4b0fc95a97eab60"},{"created-at":1582756004670,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"or","ns":"clojure.core"},"_id":"5e56f0a4e4b087629b5a18ac"},{"created-at":1609357926155,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"fnil","ns":"clojure.core"},"_id":"5fecda66e4b0b1e3652d7425"}],"line":7628,"examples":[{"updated-at":1462556528065,"created-at":1321364478000,"body":"\nuser=> ((some-fn even?) 1)\nfalse\nuser=> ((some-fn even?) 2)\ntrue\nuser=> ((some-fn even?) 1 2)\ntrue\n","editors":[{"login":"huahaiy","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/889685?v=3"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/e7869fe1a48cb1814c657eaca6bea3eb?r=PG&default=identicon","account-source":"clojuredocs","login":"replore"},"_id":"542692d5c026201cdc32708b"},{"author":{"login":"uvtc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/34f159f89cbd1d9beac0276f5a7af552?r=PG&default=identicon"},"editors":[],"body":";; `some-fn` is useful for when you'd use `some` (to find out if any\n;; values in a given coll satisfy some predicate), but have more than\n;; one predicate. For example, to check if any values in a coll are\n;; either even or less than 10:\n\n(or (some even? [1 2 3])\n (some #(< % 10) [1 2 3]))\n\n;; but `some-fn` can save you some duplication here:\n\n((some-fn even? #(< % 10)) 1 2 3)\n\n;; Minor note: the former returns nil if it doesn't find\n;; what it's looking for. The latter returns false.","created-at":1343775095000,"updated-at":1343775095000,"_id":"542692d5c026201cdc32708c"},{"updated-at":1477665180894,"created-at":1399749753000,"body":";;; http://en.wikipedia.org/wiki/Fizz_buzz\n(def fizzbuzz\n (some-fn #(and (= (mod % 3) 0) (= (mod % 5) 0) \"FizzBuzz\")\n #(and (= (mod % 3) 0) \"Fizz\")\n #(and (= (mod % 5) 0) \"Buzz\")\n str))\n\n(run! println (map fizzbuzz (range 1 18)))\n\n1\n2\nFizz\n4\nBuzz\nFizz\n7\n8\nFizz\nBuzz\n11\nFizz\n13\n14\nFizzBuzz\n16\n17","editors":[{"login":"GordonGustafson","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/6244646?v=3"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/3f7913b563c72083c74030d928ba407e?r=PG&default=identicon","account-source":"clojuredocs","login":"ryo"},"_id":"542692d5c026201cdc32708d"},{"updated-at":1461825756902,"created-at":1461820011453,"author":{"login":"bkovitz","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/4142015?v=3"},"body":";; Here's an easy way to apply several functions in succession to the same\n;; value and get the first true result. Note the double parentheses at the\n;; beginning: because some-fn returns a function, you have to apply it.\n\n((some-fn :a :b :c :d) {:c 3 :d 4})\n;=> 3\n\n;; Here's how to do the same thing but with a vector of functions. Note\n;; the 'apply' as well as the double parentheses, since you have to make\n;; some-fn take its arguments from the vector.\n\n(def parsers\n [parse-custom-command\n parse-basic-command\n parse-weird-command\n reject-command])\n\n((apply some-fn parsers) text-from-user)\n\n;; Each element of parsers is a function that returns a data structure if\n;; it successfully parses its argument or nil if it fails. reject-command\n;; always succeeds, returning a representation of an error.\n\n;; Note the technique of putting a catch-all function for errors last.\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/4142015?v=3","account-source":"github","login":"bkovitz"}],"_id":"57219a6be4b0f8c89e75b111"}],"notes":null,"arglists":["p","p1 p2","p1 p2 p3","p1 p2 p3 & ps"],"doc":"Takes a set of predicates and returns a function f that returns the first logical true value\n returned by one of its composing predicates against any of its arguments, else it returns\n logical false. Note that f is short-circuiting in that it will stop execution on the first\n argument that triggers a logical true result against the original predicates.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/some-fn"},{"added":"1.2","ns":"clojure.core","name":"case","file":"clojure/core.clj","type":"macro","column":1,"see-alsos":[{"created-at":1294148893000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"cond","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d1e"},{"created-at":1294148897000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"condp","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d1f"}],"line":6789,"examples":[{"author":{"login":"jneira","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2c8ecc24181d171df85a26458b9cd5f?r=PG&default=identicon"},"editors":[{"login":"jneira","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2c8ecc24181d171df85a26458b9cd5f?r=PG&default=identicon"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"dale","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a7a1eca257c6cea943fea41e5cc3e9a3?r=PG&default=identicon"},{"login":"dale","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a7a1eca257c6cea943fea41e5cc3e9a3?r=PG&default=identicon"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":"(let [mystr \"hello\"]\n (case mystr\n \"\" 0\n \"hello\" (count mystr)))\n;;=> 5\n\n(let [mystr \"no match\"]\n (case mystr\n \"\" 0\n \"hello\" (count mystr)))\n;; No matching clause: no match\n;; [Thrown class java.lang.IllegalArgumentException]\n\n(let [mystr \"no match\"]\n (case mystr\n \"\" 0\n \"hello\" (count mystr)\n \"default\"))\n;;=> \"default\"\n\n;; You can give multiple values for the same condition by putting\n;; those values in a list.\n(case 'y\n (x y z) \"x, y, or z\"\n \"default\")\n;;=> \"x, y, or z\"\n\n(let [myseq '(1 2)]\n (case myseq\n (()) \"empty seq\"\n ((1 2)) \"my seq\"\n \"default\"))\n;;=> \"my seq\"\n\n;; \"The test-constants are not evaluated.They must be compile-time\n;; literals, and need not be quoted.\" \n(let [myvec [1 2]]\n (case myvec\n [] \"empty vec\"\n (vec '(1 2)) \"my vec\"\n \"default\"))\n;;=> \"default\"\n","created-at":1278987914000,"updated-at":1422376846462,"_id":"542692ccc026201cdc326c89"},{"editors":[{"login":"rmprescott","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/224805?v=4"}],"body":";; From: The Clojure Style Guide \n;; https://github.com/bbatsov/clojure-style-guide#case\n;; License: Creative Commons Attribution 3.0 Unported License\n;;\n;; Prefer case instead of cond or condp when test expressions are compile-time constants.\n\n;; good\n(cond\n (= x 10) :ten\n (= x 20) :twenty\n (= x 30) :forty\n :else :dunno)\n\n;; better\n(condp = x\n 10 :ten\n 20 :twenty\n 30 :forty\n :dunno)\n\n;; best\n(case x\n 10 :ten\n 20 :twenty\n 30 :forty\n :dunno)","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/224805?v=4","account-source":"github","login":"rmprescott"},"created-at":1539061331613,"updated-at":1539061466913,"_id":"5bbc3653e4b00ac801ed9ecc"},{"updated-at":1575502428174,"created-at":1575502355101,"author":{"login":"huahaiy","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/889685?v=4"},"body":";; test-constants are not evaluated, so the symbols should NOT be quoted\n(let [x 'a-symbol] ; quoted\n (case x \n a-symbol :a ; not quoted\n b-symbol :b)) ; not quoted\n;;=> :a","editors":[{"avatar-url":"https://avatars3.githubusercontent.com/u/889685?v=4","account-source":"github","login":"huahaiy"}],"_id":"5de84213e4b0ca44402ef7f1"},{"updated-at":1582540498084,"created-at":1582540498084,"author":{"login":"bnii","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/22633514?v=4"},"body":";; Other example on\n;; \"The test-constants are not evaluated. They must be compile-time\n;; literals, and need not be quoted.\" \n\n(def one 1)\n;;=> #'user/one\n(case 1 \n one :one \n :not-one)\n;;=> :not-one","_id":"5e53a6d2e4b087629b5a18a1"},{"updated-at":1587638962866,"created-at":1587638962866,"author":{"login":"uosl","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/3865590?v=4"},"body":";; You can use a macro to inline test-constants you wish to define separately.\n\n(def ops-single '(\"=\" \"!=\" \"<\" \"<=\" \">\" \">=\"))\n\n(def ops-multi '(\"ONE OF\" \"NONE OF\"))\n\n(defmacro ops-type [op]\n `(case ~op\n ~ops-single :single\n ~ops-multi :multi))","_id":"5ea172b2e4b087629b5a18df"},{"updated-at":1587918490021,"created-at":1587918490021,"author":{"login":"ertugrulcetin","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/8271291?v=4"},"body":"(case :blocking\n (:blocking :compute) :block-or-compute\n :async :async)\n\n;;=> :block-or-compute\n\n\n(case :async\n (:blocking :compute) :block-or-compute\n :async :async)\n\n;;=> :async","_id":"5ea5b69ae4b087629b5a18e9"},{"updated-at":1629037974768,"created-at":1615140525278,"author":{"login":"Crowbrammer","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/19522656?v=4"},"body":";; I timed rmprescott's example:\n\n(let [x 30] \n ;; \"good\"\n (time (cond\n (= x 10) :ten\n (= x 20) :twenty\n (= x 30) :thirty\n :else :dunno)) ;;=> \"Elapsed time: 0.0666 msecs\"\n\n ;; \"better\"\n (time (condp = x\n 10 :ten\n 20 :twenty\n 30 :thirty\n :dunno)) ;;=> \"Elapsed time: 0.4197 msecs\"\n\n ;; best in performance if else statement is executed (not shown)\n ;; best in readability\n (time (case x\n 10 :ten\n 20 :twenty\n 30 :thirty\n :dunno)) ;;=> \"Elapsed time: 0.0032 msecs\"\n \n ;; best in performance if known branches are executed\n ;; worst in readability\n (time (if (= x 10)\n :ten\n (if (= x 20)\n :twenty\n (if (= x 30)\n :thirty\n :dunno)))))) ;;=> \"Elapsed time: 0.0021 msecs\" \n\n;;=> :thirty","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/19522656?v=4","account-source":"github","login":"Crowbrammer"}],"_id":"604516ade4b0b1e3652d746d"},{"updated-at":1643907667427,"created-at":1643907667427,"author":{"login":"fdhenard","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/884972?v=4"},"body":";; demonstrates inclusion on the test\n;; ... could be one of \"what\" or \"why\"\n\n(case \"what\"\n (\"what\" \"why\") :question\n :something-else)\n\n;;=> :question","_id":"61fc0a53e4b0b1e3652d75a6"}],"macro":true,"notes":[{"updated-at":1290270646000,"body":"the third example describing myseq may be incorrect. I think we have to use vectors for comparing list of compile time constants.\r\n
    \r\n(let [myseq [1 2]]\r\n (case myseq\r\n  [] \"empty seq\"\r\n  [1 2] \"my seq\"\r\n  \"default\"))\r\n
    \r\n\r\nThe parenthesized test conditions are used when multiple test conditions give the same output (output expression). In my case , since both [true, true] and [false, false] return true, i have put them within parenthesis.\r\n\r\n
    \r\n(defn equ\r\n [a b]\r\n (case [a b]\r\n   ([true true] [false false]) true\r\n   true))\r\n\r\n(equ true true) ;; returns true\r\n(equ false false) ;; returns true\r\n(equ false true) ;; return false\r\n(equ true false) ;; returns false\r\n
    ","created-at":1290269788000,"author":{"login":"dpani","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3229d0eee8f780b9baa64657ff561fd3?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fa4"},{"updated-at":1290655074000,"body":"I updated that example with myseq to reflect behavior of Clojure 1.2.0 on my machine. I also added an additional example to explicitly demonstrate multiple values for the same condition.","created-at":1290655074000,"author":{"login":"dale","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a7a1eca257c6cea943fea41e5cc3e9a3?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fa6"},{"body":"Java enums are not compile-time literals.","created-at":1613272178203,"updated-at":1613272197403,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/6383047?v=4","account-source":"github","login":"beluchin"},"_id":"60289472e4b0b1e3652d7455"},{"body":"Keep in mind this is not quite like pattern matching.\n\n```\n(case [:a :b]\n [:a :b] \"a b combo\"\n [_ :b] \"at least b\" \n)\n```\n\nWill not work. Instead install and use core.match:\n\n```\n(clojure.core.match/match [:a :b]\n [:a :b] \"a b combo\"\n [_ :b] \"at least b\")\n```\n(Thanks to potetm and Martin Půda on Clojurians Slack)","created-at":1648411010714,"updated-at":1648411421228,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/590297?v=4","account-source":"github","login":"eccentric-j"},"_id":"6240c182e4b0b1e3652d75c3"},{"author":{"login":"KingMob","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/946421?v=4"},"updated-at":1680176304321,"created-at":1680176304321,"body":"Reminder: compile-time *literals* are not the same thing as compile-time *constants*. The Clojure macro/compiler is not smart enough to work with things like Java constants or `^:const` vars.\n\nE.g.: \n\n```\n(case Math/PI\n Math/PI :pi\n Math/E :e\n :default)\n=> :default\n\n\n\n(def ^:const pi Math/PI)\n=> #'user/pi\n(case Math/PI\n pi :pi\n Math/E :e\n :default)\n=> :default\n```\n\nwill not work.","_id":"642574b0e4b08cf8563f4b87"}],"arglists":["e & clauses"],"doc":"Takes an expression, and a set of clauses.\n\n Each clause can take the form of either:\n\n test-constant result-expr\n\n (test-constant1 ... test-constantN) result-expr\n\n The test-constants are not evaluated. They must be compile-time\n literals, and need not be quoted. If the expression is equal to a\n test-constant, the corresponding result-expr is returned. A single\n default expression can follow the clauses, and its value will be\n returned if no clause matches. If no default expression is provided\n and no clause matches, an IllegalArgumentException is thrown.\n\n Unlike cond and condp, case does a constant-time dispatch, the\n clauses are not considered sequentially. All manner of constant\n expressions are acceptable in case, including numbers, strings,\n symbols, keywords, and (Clojure) composites thereof. Note that since\n lists are used to group multiple constants that map to the same\n expression, a vector can be used to match a list if needed. The\n test-constants need not be all of the same type.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/case"},{"added":"1.0","ns":"clojure.core","name":"*flush-on-newline*","type":"var","see-alsos":null,"examples":null,"notes":null,"arglists":[],"doc":"When set to true, output will be flushed whenever a newline is printed.\n\n Defaults to true.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/*flush-on-newline*"},{"added":"1.0","ns":"clojure.core","name":"to-array","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1329377518000,"author":{"login":"Claj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5fd658a8d2ef549071cb5286b1b874aa?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"alength","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521ba2"},{"created-at":1329377602000,"author":{"login":"Claj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5fd658a8d2ef549071cb5286b1b874aa?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"char-array","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521ba3"},{"created-at":1329377609000,"author":{"login":"Claj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5fd658a8d2ef549071cb5286b1b874aa?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"int-array","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521ba4"},{"created-at":1329377615000,"author":{"login":"Claj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5fd658a8d2ef549071cb5286b1b874aa?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"long-array","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521ba5"},{"created-at":1374150114000,"author":{"login":"alilee","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2fb0196dc5a7cd3a5cc73f1b9941c209?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"into-array","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521ba6"},{"created-at":1374150319000,"author":{"login":"alilee","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2fb0196dc5a7cd3a5cc73f1b9941c209?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"make-array","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521ba7"},{"created-at":1375613635000,"author":{"login":"alilee","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2fb0196dc5a7cd3a5cc73f1b9941c209?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"to-array-2d","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521ba8"}],"line":340,"examples":[{"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"editors":[{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"}],"body":"user=> (to-array [1 2 3])\n#","created-at":1285922749000,"updated-at":1423279139981,"_id":"542692cfc026201cdc326e1e"},{"author":{"login":"Claj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5fd658a8d2ef549071cb5286b1b874aa?r=PG&default=identicon"},"editors":[{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"}],"body":"(def hello (to-array \"Hello World!\"))\n\n(aget hello 1)\n;; => \\e\n\n(aset hello 1 \\b) ;;Mutability! Watch out!\n;; => \\b\n\n(dotimes [n (alength hello)] (print (aget hello n)))\n;; => Hbllo World!\n\n;; Calling `to-array` on array returns the original, not a copy\n(identical? (to-array hello) hello)\n;; => true","created-at":1329377512000,"updated-at":1423279331082,"_id":"542692d5c026201cdc3270a9"},{"editors":[{"login":"luiszambon","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/41161270?v=4"}],"body":"user> (class '(1 2 3 4))\n;=> clojure.lang.PersistentList\n\nuser> (class (to-array '(1 2 3 4)))\n;=> [Ljava.lang.Object;\n\nuser> (get (to-array '(1 2 3 4)) 0)\n;=> 1\n","author":{"avatar-url":"https://avatars0.githubusercontent.com/u/41161270?v=4","account-source":"github","login":"luiszambon"},"created-at":1599766069962,"updated-at":1600132120029,"_id":"5f5a7e35e4b0b1e3652d73b8"}],"notes":null,"tag":"[Ljava.lang.Object;","arglists":["coll"],"doc":"Returns an array of Objects containing the contents of coll, which\n can be any Collection. Maps to java.util.Collection.toArray().","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/to-array"},{"added":"1.0","ns":"clojure.core","name":"bigdec","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1374317032000,"author":{"login":"alilee","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2fb0196dc5a7cd3a5cc73f1b9941c209?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"decimal?","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ec2"},{"created-at":1514475884312,"author":{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/94482?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"with-precision","ns":"clojure.core"},"_id":"5a45116ce4b0a08026c48ce7"},{"created-at":1579780078637,"author":{"login":"Hindol","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/705227?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"bigint","ns":"clojure.core"},"_id":"5e2987eee4b0ca44402ef81e"},{"created-at":1579780089811,"author":{"login":"Hindol","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/705227?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"double","ns":"clojure.core"},"_id":"5e2987f9e4b0ca44402ef81f"},{"created-at":1579780098355,"author":{"login":"Hindol","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/705227?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"float","ns":"clojure.core"},"_id":"5e298802e4b0ca44402ef820"}],"line":3673,"examples":[{"updated-at":1321355928000,"created-at":1280814320000,"body":"user=> (bigdec 3.0)\n3.0M\n\nuser=> (bigdec 5)\n5M\n\nuser=> (bigdec -1)\n-1M\n\nuser=> (bigdec -1.0)\n-1.0M\n\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"avatar-url":"https://www.gravatar.com/avatar/e7869fe1a48cb1814c657eaca6bea3eb?r=PG&default=identicon","account-source":"clojuredocs","login":"replore"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3","account-source":"github","login":"devn"},"_id":"542692cec026201cdc326d80"},{"updated-at":1535909835189,"created-at":1535909835189,"author":{"login":"cloojure","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/7083783?v=4"},"body":"; It also works for strings:\n(bigdec \"123.45\") => 123.45M\n","_id":"5b8c1fcbe4b00ac801ed9e7d"},{"updated-at":1598220594241,"created-at":1598220594241,"author":{"login":"berczeck","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/1321842?v=4"},"body":";; Works with ratios too\n\nuser => (bigdec 1/2)\n;; 0.5M","_id":"5f42e932e4b0b1e3652d73a6"},{"updated-at":1605204244578,"created-at":1605204244578,"author":{"login":"Arvantos","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/74289274?v=4"},"body":"user=> (+ 0.1 0.1 0.1)\n0.30000000000000004\nuser=> (def a (bigdec 0.1))\n#'user/a\nuser=> (+ a a a)\n0.3M","_id":"5fad7914e4b0b1e3652d7404"}],"notes":null,"tag":"java.math.BigDecimal","arglists":["x"],"doc":"Coerce to BigDecimal","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/bigdec"},{"added":"1.0","ns":"clojure.core","name":"list?","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1318710916000,"author":{"login":"steveminer","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d28543d134185d12d4006a74738d233e?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"seq?","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b5e"},{"created-at":1356063872000,"author":{"login":"hugoduncan","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/80fa2a15219b987664e4d6f5c78b4c27?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"sequential?","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b5f"},{"created-at":1356066804000,"author":{"login":"hugoduncan","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/80fa2a15219b987664e4d6f5c78b4c27?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"coll?","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b60"},{"created-at":1414509201213,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"},"to-var":{"ns":"clojure.core","name":"map?","library-url":"https://github.com/clojure/clojure"},"_id":"544fb291e4b0dc573b892fac"},{"created-at":1414509214198,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"},"to-var":{"ns":"clojure.core","name":"set?","library-url":"https://github.com/clojure/clojure"},"_id":"544fb29ee4b0dc573b892fad"},{"created-at":1414509226885,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"},"to-var":{"ns":"clojure.core","name":"vector?","library-url":"https://github.com/clojure/clojure"},"_id":"544fb2aae4b03d20a1024287"}],"line":6275,"examples":[{"updated-at":1414509176872,"created-at":1279074216000,"body":";; an idiomatic persistent-list is a list\n(list? '(1 2 3))\n;;=> true\n\n;; a persistent-list is a list\n;; (list? (list 1 2))\n;;=> true\n\n;; a numeric value (long) is not a list\n(list? 0)\n;;=> false\n\n;; a persistent-array-map is not a list\n(list? {})\n;;=> false\n\n;; a persistent-vector is not a list\n(list? [])\n;;=> false\n\n;; a lazy-sequence is not always a list\n(list? (range 10))\n;;=> false\n","editors":[{"avatar-url":"https://avatars2.githubusercontent.com/u/22608?v=4","account-source":"github","login":"MrHus"},{"avatar-url":"https://www.gravatar.com/avatar/d28543d134185d12d4006a74738d233e?r=PG&default=identicon","account-source":"clojuredocs","login":"steveminer"},{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2","account-source":"github","login":"phreed"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/147981?v=3","account-source":"github","login":"dpritchett"},"_id":"542692cbc026201cdc326b9d"},{"editors":[{"login":"muhuk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/40178?v=3"}],"body":";; not all lists are lists\n(cons 1 '(2 3))\n;; => (1 2 3)\n(= '(1 2 3) (cons 1 '(2 3)))\n;; => true\n(list? (cons 1 '(2 3)))\n;; => false\n\n;; good news is:\n(seq? (cons 1 '(2 3)))\n;; => true\n(seq? [1 2 3])\n;; => false\n\n;; So seq? might be what you are looking \n;; for when you want to test listness.\n\n\n\n\n\n","author":{"avatar-url":"https://avatars.githubusercontent.com/u/40178?v=3","account-source":"github","login":"muhuk"},"created-at":1448895002974,"updated-at":1455541780305,"_id":"565c621ae4b0be225c0c47a3"}],"notes":[{"updated-at":1318711577000,"body":"You may want to use `seq?` instead of `list?`, especially if you might be dealing with a lazy sequence as returned by `filter`, `range`, etc.","created-at":1318711577000,"author":{"login":"steveminer","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d28543d134185d12d4006a74738d233e?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fcf"}],"arglists":["x"],"doc":"Returns true if x implements IPersistentList","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/list_q"},{"added":"1.9","ns":"clojure.core","name":"simple-ident?","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1495714925553,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"ident?","ns":"clojure.core"},"_id":"5926cc6de4b093ada4d4d755"},{"created-at":1495714934749,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"qualified-ident?","ns":"clojure.core"},"_id":"5926cc76e4b093ada4d4d756"},{"created-at":1596595008529,"author":{"login":"wdhowe","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/4631165?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"simple-symbol?","ns":"clojure.core"},"_id":"5f2a1b40e4b0b1e3652d736b"},{"created-at":1596595016865,"author":{"login":"wdhowe","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/4631165?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"simple-keyword?","ns":"clojure.core"},"_id":"5f2a1b48e4b0b1e3652d736c"}],"line":1632,"examples":[{"updated-at":1596595653208,"created-at":1596595653208,"author":{"login":"wdhowe","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/4631165?v=4"},"body":"(simple-ident? 'asymbol)\n;;=> true\n\n(simple-ident? :akeyword)\n;;=> true\n\n(simple-ident? 'clojure.core/asymbol)\n;;=> false\n\n(simple-ident? ::akeyword)\n;;=> false\n\n(simple-ident? \"hello\")\n;;=> false\n\n(simple-ident? 7)\n;;=> false\n\n(simple-ident? nil)\n;;=> false","_id":"5f2a1dc5e4b0b1e3652d736d"}],"notes":null,"arglists":["x"],"doc":"Return true if x is a symbol or keyword without a namespace","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/simple-ident_q"},{"added":"1.0","ns":"clojure.core","name":"bit-not","file":"clojure/core.clj","type":"function","column":1,"see-alsos":null,"line":1300,"examples":[{"author":{"login":"zmila","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/68dd6f50915854aa04fefcf4d6fa5c8e?r=PG&default=identicon"},"editors":[{"login":"zmila","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/68dd6f50915854aa04fefcf4d6fa5c8e?r=PG&default=identicon"},{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":"user=> (bit-not 2r0111)\n-8 \n\nuser=> (bit-not -2r1000)\n7","created-at":1280338423000,"updated-at":1332951542000,"_id":"542692cac026201cdc326b50"}],"notes":null,"arglists":["x"],"doc":"Bitwise complement","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/bit-not"},{"added":"1.11","ns":"clojure.core","name":"parse-uuid","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1698256400307,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"uuid?","ns":"clojure.core"},"_id":"6539561069fbcc0c226173de"},{"created-at":1698256407536,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"random-uuid","ns":"clojure.core"},"_id":"6539561769fbcc0c226173df"}],"line":8192,"examples":[{"updated-at":1698256393524,"created-at":1698256393524,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":"(parse-uuid \"b6883c0a-0342-4007-9966-bc2dfa6b109e\")\n;; => #uuid \"b6883c0a-0342-4007-9966-bc2dfa6b109e\"\n\n;; Note, this is not a commonly valid UUID, but is still parsed…\n(parse-uuid \"b6883c0a-0342-6007-9966-bc2dfa6b109e\")\n;; => #uuid \"b6883c0a-0342-6007-9966-bc2dfa6b109e\"\n\n(parse-uuid \"foo\")\n;; => nil\n(parse-uuid \"\")\n;; => nil","_id":"6539560969fbcc0c226173dd"}],"notes":[{"author":{"login":"rbatista","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/609780?v=4"},"updated-at":1742909496264,"created-at":1742909496264,"body":"Be careful when parsing invalid UUIDs, as it may return a valid, but unexpected uuid:\n\n```\n=> (parse-uuid \" 17392216-6CA5-491A-B38C-920BA\")\nnil\n\n=> (parse-uuid \"17392216-6CA5-491A-B38C-920BA\")\n#uuid \"17392216-6ca5-491a-b38c-0000000920ba\" ; <== Filled missing chars with 0000000\n```","_id":"67e2b038cd84df5de54e2083"}],"arglists":["s"],"doc":"Parse a string representing a UUID and return a java.util.UUID instance,\n or nil if parse fails.\n\n Grammar: https://docs.oracle.com/javase/8/docs/api/java/util/UUID.html#toString--","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/parse-uuid"},{"added":"1.0","ns":"clojure.core","name":"io!","file":"clojure/core.clj","type":"macro","column":1,"see-alsos":[{"created-at":1554127057477,"author":{"login":"daveliepmann","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/974443?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"dosync","ns":"clojure.core"},"_id":"5ca218d1e4b0ca44402ef6f6"}],"line":2529,"examples":[{"author":{"login":"mstoeckli","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/271f1fe6c39e19db5714ce29b64d3ad5?r=PG&default=identicon"},"editors":[],"body":"user=> (def a (ref 0))\n#'user/a\n\nuser=> (dosync\n (io! (println \"hello\"))\n (alter a inc))\nIllegalStateException I/O in transaction\n\nuser=> (dosync\n (println \"hello\")\n (alter a inc))\n\"hello\"\n1\n\nuser=> (defn fn-with-io []\n (io! (println \"hello\")))\n#'user/fn-with-io\n\nuser=> (dosync\n (fn-with-io)\n (alter a inc))\nIllegalStateException I/O in transaction","created-at":1337147168000,"updated-at":1337147168000,"_id":"542692d3c026201cdc326fdc"}],"macro":true,"notes":null,"arglists":["& body"],"doc":"If an io! block occurs in a transaction, throws an\n IllegalStateException, else runs body in an implicit do. If the\n first expression in body is a literal string, will use that as the\n exception message.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/io!"},{"added":"1.0","ns":"clojure.core","name":"xml-seq","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":null,"line":5011,"examples":[{"author":{"login":"ed-g","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9b506528a954f5a5e83bd7041d287f68?r=PG&default=identicon"},"editors":[{"login":"biggert","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/ebd5e5aaf54f2bb5b8b01872d8ffe5d0?r=PG&default=identicon"},{"login":"biggert","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/ebd5e5aaf54f2bb5b8b01872d8ffe5d0?r=PG&default=identicon"},{"login":"biggert","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/ebd5e5aaf54f2bb5b8b01872d8ffe5d0?r=PG&default=identicon"}],"body":";; data.xml from https://github.com/clojure/data.xml/\n(use '[clojure.data.xml :only [parse-str]])\n\nuser=> (let [xml-text \"\n 123\"]\n (let [root (parse-str xml-text)]\n (xml-seq root)))\n\n({:tag :foo, \n :attrs {:key \"val\"}, \n :content (\"1\" {:tag :bar, :attrs {}, :content (\"2\")} \"3\")} \n \"1\" \n {:tag :bar, :attrs {}, :content (\"2\")} \n \"2\" \n \"3\") \n","created-at":1357886858000,"updated-at":1367460525000,"_id":"542692d6c026201cdc3270c6"},{"updated-at":1474877368412,"created-at":1367493904000,"body":"(use '[clojure.data.xml :only [parse]])\n\n;; clojure.xml/parse requires string to be ByteArrayInputStream\nuser-> (let [xml-text \"\n 123\"]\n (let [input (java.io.ByteArrayInputStream. \n (.getBytes xml-text))]\n (let [root (parse input)]\n (xml-seq root))))\n\n({:tag :foo, \n :attrs {:key \"val\"}, \n :content (\"1\" {:tag :bar, :attrs {}, :content (\"2\")} \"3\")} \n \"1\" \n {:tag :bar, :attrs {}, :content (\"2\")} \n \"2\" \n \"3\")","editors":[{"login":"pho-coder","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/6576686?v=3"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/ebd5e5aaf54f2bb5b8b01872d8ffe5d0?r=PG&default=identicon","account-source":"clojuredocs","login":"biggert"},"_id":"542692d6c026201cdc3270ca"},{"updated-at":1580661283196,"created-at":1519297750007,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"body":";; Any breaking news today?\n(require '[clojure.java.io :as io])\n(require '[clojure.xml :as xml])\n\n(def feeds\n [[:guardian \"https://www.theguardian.com/world/rss\"]\n [:wash-post \"http://feeds.washingtonpost.com/rss/rss_blogpost\"]\n [:nytimes \"https://rss.nytimes.com/services/xml/rss/nyt/World.xml\"]\n [:wsj \"https://feeds.a.dj.com/rss/RSSWorldNews.xml\"]\n [:reuters \"http://feeds.reuters.com/reuters/UKTopNews\"]])\n\n(pmap\n (fn [[feed url]]\n (let [content (comp first :content)]\n [feed\n (sequence\n (comp\n (filter (comp string? content))\n (filter (comp #{:title} :tag))\n (filter #(re-find #\"(?i)breaking\" (content %)))\n (map content))\n (xml-seq (xml/parse url)))]))\n feeds)\n\n;; Only a false positive...\n;;([:guardian (\"Climate change 'will push European cities towards breaking point'\")]\n;; [:wash-post ()]\n;; [:nytimes ()]\n;; [:wsj ()]\n;; [:reuters ()])","editors":[{"avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"}],"_id":"5a8ea4d6e4b0316c0f44f8eb"}],"notes":null,"arglists":["root"],"doc":"A tree seq on the xml elements as per xml/parse","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/xml-seq"},{"added":"1.0","ns":"clojure.core","name":"byte","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1334358069000,"author":{"login":"Havvy","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e799a79441c7543be48562403411cd13?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"byte-array","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e67"},{"to-var":{"library-url":"https://github.com/clojure/clojure","name":"bytes","ns":"clojure.core"},"author":{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},"created-at":1342917284000,"_id":"542692ebf6e94c6970521e68"},{"to-var":{"library-url":"https://github.com/clojure/clojure","name":"short","ns":"clojure.core"},"author":{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},"created-at":1342917760000,"_id":"542692ebf6e94c6970521e69"},{"created-at":1496262181439,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"unchecked-byte","ns":"clojure.core"},"_id":"592f2625e4b06e730307db1d"}],"line":3530,"examples":[{"author":{"login":"Miles","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bbb26d2a5e856c4fba0f72c3f7250f3f?r=PG&default=identicon"},"editors":[{"login":"Miles","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bbb26d2a5e856c4fba0f72c3f7250f3f?r=PG&default=identicon"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"Miles","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bbb26d2a5e856c4fba0f72c3f7250f3f?r=PG&default=identicon"}],"body":"user=> (def x (byte-array [(byte 0x43) \n (byte 0x6c)\n (byte 0x6f)\n (byte 0x6a)\n (byte 0x75)\n (byte 0x72)\n (byte 0x65)\n (byte 0x21)]))\n#'user/x\n\nuser=> (String. x)\n\"Clojure!\"\n","created-at":1283813146000,"updated-at":1287791649000,"_id":"542692cbc026201cdc326c11"},{"updated-at":1596590375648,"created-at":1596572702674,"author":{"login":"wdhowe","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/4631165?v=4"},"body":";; Casting a string does not work\n(byte \"123\")\n;;=> Execution error (ClassCastException) at user/eval157 (REPL:1).\n;;java.lang.String cannot be cast to java.lang.Number\n\n;; Use Java interop instead\n(Byte/parseByte \"123\")\n;;=> 123\n\n;; Content originally posted by u/didibus on https://clojuredocs.org/clojure.core/num","editors":[{"avatar-url":"https://avatars0.githubusercontent.com/u/4631165?v=4","account-source":"github","login":"wdhowe"}],"_id":"5f29c41ee4b0b1e3652d735d"},{"updated-at":1722778246074,"created-at":1722778246074,"author":{"login":"marceloschreiber","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/13343185?v=4"},"body":";; Supports casting within the range -128 to 127.\n(byte -128) ;;=> -128\n(byte 127) ;; => 127\n\n;; Casting outside of this range throws IllegalArgumentException\n(byte 142)\n;; => Execution error (IllegalArgumentException) at core/eval11809 (REPL.1).\n;; Value out of range for byte: 142\n\n\n;; Use unchecked-byte when rounding or truncation is desired","_id":"66af828669fbcc0c226174e6"}],"notes":null,"arglists":["x"],"doc":"Coerce to byte","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/byte"},{"added":"1.0","ns":"clojure.core","name":"max","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1343257166000,"author":{"login":"john.r.woodward","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/22b6fbc4a386291e45b1cb4449377086?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"max-key","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cf7"},{"created-at":1371841162000,"author":{"login":"adereth","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5ad11b4e208a6cdb3bd45fe01dea59b7?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"min","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cf8"}],"line":1117,"examples":[{"updated-at":1411918995332,"created-at":1279417705000,"body":";; `max` returns the largest of its arguments\nuser=> (max 1 2 3 4 5) \n5\n\n;; regardless of order of those arguments\nuser=> (max 5 4 3 2 1)\n5\n\nuser=> (max 100)\n100","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"}],"author":{"avatar-url":"https://avatars2.githubusercontent.com/u/22608?v=4","account-source":"github","login":"MrHus"},"_id":"542692ccc026201cdc326c99"},{"author":{"login":"mydoghasworms","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e1e4692b0c0b2fcc1844f11cb43191da?r=PG&default=identicon"},"editors":[],"body":";; If elements are already in a sequence, use apply\nuser=> (apply max [1 2 3 4 3])\n4\nuser=> (apply max '(4 3 5 6 2))\n6","created-at":1367237523000,"updated-at":1367237523000,"_id":"542692d4c026201cdc32700b"},{"updated-at":1482367699298,"created-at":1482367699298,"author":{"login":"zjliu1984","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1556007?v=3"},"body":"user> (reduce max [1 2 3 4 5 6 7 6 5 4 3])\n7","_id":"585b22d3e4b004d3a355e2d5"}],"notes":[{"body":"As of 1.6, `max`'s behavior differs when it's passed single / multiple non-numeric arguments:\n\n```\n(max \"foo\") ;;=> \"foo\"\n\n(max \"foo\" \"bar\") ;;=> ClassCastException thrown\n```","created-at":1411919387514,"updated-at":1411919387514,"author":{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},"_id":"54282e1be4b0ba57bdbcf25d"},{"author":{"login":"burbma","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/7841889?v=4"},"updated-at":1553102150973,"created-at":1553102150973,"body":"```\n;; Be warned\nuser=> (max 1 nil)\njava.lang.NullPointerException\n```","_id":"5c927546e4b0ca44402ef6bb"}],"arglists":["x","x y","x y & more"],"doc":"Returns the greatest of the nums.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/max"},{"added":"1.11","ns":"clojure.core","name":"update-keys","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1698251692954,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"update-vals","ns":"clojure.core"},"_id":"653943ac69fbcc0c226173d1"},{"created-at":1698251705666,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"keywordize-keys","ns":"clojure.walk"},"_id":"653943b969fbcc0c226173d2"},{"created-at":1698251712163,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"stringify-keys","ns":"clojure.walk"},"_id":"653943c069fbcc0c226173d3"}],"line":8148,"examples":[{"updated-at":1698250665596,"created-at":1698250665596,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":";; It's quite common to keywordize keys using `keyword`…\n(update-keys {\"foo\" 42 \"bar\" 1337} keyword)\n;; => {:foo 42, :bar 1337}\n\n;; Or stringify them using `name`…\n(update-keys {:foo 42 :bar 1337} name)\n;; => {\"foo\" 42, \"bar\" 1337}\n\n;; But remember this doesn't work recursively for nested structures…\n(update-keys {\"foo\" {\"qux\" 404} \"bar\" 1337} keyword)\n;; => {:foo {\"qux\" 404}, :bar 1337}\n\n;; You'll want to reach for `clojure.walk` instead for that…\n(clojure.walk/keywordize-keys {\"foo\" {\"qux\" 404} \"bar\" 1337})\n;; => {:foo {:qux 404}, :bar 1337}\n\n(clojure.walk/stringify-keys {:foo {:qux 404} :bar 1337})\n;; => {\"foo\" {\"qux\" 404}, \"bar\" 1337}","_id":"65393fa969fbcc0c226173ce"}],"notes":null,"arglists":["m f"],"doc":"m f => {(f k) v ...}\n\n Given a map m and a function f of 1-argument, returns a new map whose\n keys are the result of applying f to the keys of m, mapped to the\n corresponding values of m.\n f must return a unique key for each key of m, else the behavior is undefined.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/update-keys"},{"added":"1.0","ns":"clojure.core","name":"==","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1287469513000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"=","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e4b"},{"created-at":1350778281000,"author":{"login":"dansalmo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e33ee460f5f61bc5ba9b598934766215?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"identical?","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f34"},{"created-at":1548959844037,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/109629?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"compare","ns":"clojure.core"},"_id":"5c534064e4b0ca44402ef65f"}],"line":1102,"examples":[{"author":{"login":"james","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/4b163432c99a124feee4be046a3f9d66?r=PG&default=identicon"},"editors":[{"login":"james","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/4b163432c99a124feee4be046a3f9d66?r=PG&default=identicon"},{"login":"james","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/4b163432c99a124feee4be046a3f9d66?r=PG&default=identicon"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"}],"body":";; true:\n(== 1)\n(== 1 1) \n(== 1/1, 2/2, 3/3, 4/4) \n(== 1, 1.0, 1/1)\n(== :foo)\n\n\n;; false:\n(== 1 2)\n\n;; ClassCastException\n(== 1 \\1)\n(== 1 \"1\")","created-at":1283399494000,"updated-at":1412882998472,"_id":"542692c6c026201cdc3268dd"},{"body":"user=> (= 0.0 0)\nfalse\nuser=> (== 0.0 0)\ntrue","author":{"login":"h3x3d","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1663557?v=2"},"created-at":1415298297003,"updated-at":1415298297003,"_id":"545bbcf9e4b0dc573b892fbe"},{"body":";; Just what you would expect\n(== 2.0 1.9999999)\n;;=> false\n\n;; a suprising result\n(== 2.0 2 6/3 1.9999999999999999)\n;;=> true ??!?\n;; Yes, there is some rounding off going on.\n;; if you take off just one of the repeating 9 (on my machine) these compare.\n","author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"},"created-at":1415650668901,"updated-at":1415650668901,"_id":"54611d6ce4b0dc573b892fc1"},{"editors":[{"login":"wontheone1","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/11784756?v=4"}],"body":"\n;; When floating point numbers are far enough from each other\n(== 2.0 1.9999999)\n;;=> false\n(- 100.0 100.00000000000001) ;13(Thirteen) 0s after floating point in the last number\n;;=> -1.4210854715202004E-14\n\n;; When two floating point numbers are too close some basic algebraic properties don't strictly hold.\n(== 2.0 1.9999999999999999)\n;;=> true\n\n(* 100 (- 1.0 1.0000000000000001)) ;15(fifteen) 0s after floating point in the last number\n;;=> 0.0\n\n;; They are still different types\n(= 2 1.9999999999999999)\n;;=> false\n\n;; see more from https://en.wikibooks.org/wiki/Floating_Point/Epsilon\n;; I found above example was distracting by putting 6/3 and 2 in the equality check that is why I decided to write up a similar but new example.","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/11784756?v=4","account-source":"github","login":"wontheone1"},"created-at":1504857100867,"updated-at":1504857144266,"_id":"59b24c0ce4b09f63b945ac62"},{"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/109629?v=4"}],"body":";; See the Clojure Equality guide for more details:\n;; https://clojure.org/guides/equality\n\n;; == returns false whenever comparing the special \"not a number\" value to any\n;; number, including itself.\n\nuser=> (== 1 ##NaN)\nfalse ;; this result you probably expect\n\nuser=> (== ##NaN ##NaN)\nfalse ;; this one may surprise you\n","author":{"avatar-url":"https://avatars2.githubusercontent.com/u/109629?v=4","account-source":"github","login":"jafingerhut"},"created-at":1548789636747,"updated-at":1565641625053,"_id":"5c50a784e4b0ca44402ef659"},{"updated-at":1598156432612,"created-at":1598156432612,"author":{"login":"berczeck","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/1321842?v=4"},"body":"user => (= 1/2 0.5)\n;; => false\n\nuser => (== 1/2 0.5)\n;; => true","_id":"5f41ee90e4b0b1e3652d738f"}],"notes":[{"updated-at":1287470809000,"body":"There is a difference between \"=\" and \"==\". For primitives you definitely want to use \"==\" as \"=\" will result in a cast to the wrapped types for it's arguments.\r\n\r\nThis may not be the case come Clojure 1.3 (see [1])\r\n\r\n[1] http://github.com/clojure/clojure/commit/df8c65a286e90e93972bb69392bc106128427dde","created-at":1287470809000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521f9c"},{"updated-at":1363156271000,"body":"So what is difference with =? ","created-at":1363156271000,"author":{"login":"popopome","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/f764e6667c2664b9979227fc40be024e?r=PG&default=identicon"},"_id":"542692edf6e94c6970521ffe"},{"updated-at":1363512387000,"body":"'== is defined only for numbers, where '= is general equality. The example showing (== :foo) as true is a bit misleading because (== :foo :foo) produces an exception. Unary == always returns true as an optimization.","created-at":1363512387000,"author":{"login":"mattharden","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a0f377e9263784a0036c5417d0a18aef?r=PG&default=identicon"},"_id":"542692edf6e94c6970521fff"}],"arglists":["x","x y","x y & more"],"doc":"Returns non-nil if nums all have the equivalent\n value (type-independent), otherwise false","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/=="},{"added":"1.0","ns":"clojure.core","name":"*agent*","type":"var","see-alsos":[{"created-at":1399893914000,"author":{"login":"ryo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3f7913b563c72083c74030d928ba407e?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"agent","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d10"}],"examples":[{"author":{"login":"goodmike","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/42e0998c3077ba0ac435423941a3978e?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":";; *agent* is often used with send or send-off to set up a repeated\n;; transformation of an agent's value. For example, to repeatedly \n;; increment the integer value of an agent 'myagent' until some \n;; flag value 'running' evaluates to false:\n\n;; Create an agent set to an initial value of 0:\n(def myagent (agent 0))\n\n;; Define a variable to act as a boolean flag:\n(def running true)\n\n;; Define a function to increment agent value repeatedly:\n(defn inc-while-running [agent-value]\n (when running\n (send-off *agent* inc-while-running)) ;sets up another call\n (inc agent-value))\n\n;; Dereference myagent to confirm it is set to value 0:\nuser=> @myagent\n0\n\n;; Start the fun:\nuser=> (send-off myagent inc-while-running)\n#<Agent@5fb9f88b: 20>\n\n;; The agent has already been incremented many times (20 when I ran this)\n;; by the time the REPL prints.\n\n;; Redefine running as false to stop repeated send-off:\n(def running false)\n\n;; Dereference myagent to find its new value:\nuser=> @myagent\n848167\n\n;; Dereference again to make sure incrementation has stopped:\nuser=> @myagent\n848167","created-at":1279046895000,"updated-at":1285502273000,"_id":"542692cec026201cdc326d88"}],"notes":null,"tag":"clojure.lang.Agent","arglists":[],"doc":"The agent currently running an action on this thread, else nil","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/*agent*"},{"added":"1.0","ns":"clojure.core","name":"lazy-cat","file":"clojure/core.clj","type":"macro","column":1,"see-alsos":[{"created-at":1318396486000,"author":{"login":"haplo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/890d46f8c0e24dd6fb8546095b1144e?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"lazy-seq","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cfe"},{"created-at":1318396500000,"author":{"login":"haplo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/890d46f8c0e24dd6fb8546095b1144e?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"concat","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cff"},{"created-at":1464035689604,"author":{"login":"cloojure","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7083783?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"conj","ns":"clojure.core"},"_id":"57436969e4b0d7ce46a59c3c"},{"created-at":1550609183419,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"mapcat","ns":"clojure.core"},"_id":"5c6c6b1fe4b0ca44402ef69b"}],"line":4663,"examples":[{"author":{"login":"pashields","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/6ff7e838d2c47adf942be6df4d22b452?r=PG&default=identicon"},"editors":[],"body":"user=> (lazy-cat [1 2 3] [4 5 6])\n(1 2 3 4 5 6)\n","created-at":1295304229000,"updated-at":1295304229000,"_id":"542692c7c026201cdc3269d5"},{"author":{"login":"kij","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/153ba8c871d2f98e6683850790f27f60?r=PG&default=identicon"},"editors":[{"login":"kij","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/153ba8c871d2f98e6683850790f27f60?r=PG&default=identicon"},{"login":"bmabey","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1837?v=2"}],"body":";; N.B. this example holds onto the head of a lazy seq which should generally be avoided\n(def fib-seq\n (lazy-cat [0 1] (map + (rest fib-seq) fib-seq)))\n\n(take 10 fib-seq)","created-at":1332777683000,"updated-at":1347405980000,"_id":"542692d3c026201cdc326fe4"},{"author":{"login":"guruma","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/ade3cfcd37c594a590528e352528bba2?r=PG&default=identicon"},"editors":[{"login":"guruma","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/ade3cfcd37c594a590528e352528bba2?r=PG&default=identicon"},{"login":"guruma","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/ade3cfcd37c594a590528e352528bba2?r=PG&default=identicon"},{"login":"rahulpilani","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3c3585fc1c6bf074ed5f268c9ebcb2f?r=PG&default=identicon"}],"body":";; When the producer function produces a collection, not an element,\n;; lazy-cat is usable.\nuser=> (defn n-repeat [n] (lazy-cat (repeat n n) (n-repeat (inc n))))\n#'user/n-repeat\n\nuser=> (take 6 (n-repeat 1))\n(1 2 2 3 3 3)\n\nuser=> (take 12 (n-repeat 1))\n(1 2 2 3 3 3 4 4 4 4 5 5)\n","created-at":1355523910000,"updated-at":1360760950000,"_id":"542692d3c026201cdc326fe7"},{"updated-at":1441150658101,"created-at":1441150658101,"author":{"login":"mattvvhat","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/367789?v=3"},"body":"(lazy-cat (seq [\"lazy-cat\" \"is\" \"my\" \"favorite\" \"function\"]))","_id":"55e636c2e4b072d7f27980f6"},{"updated-at":1490842223357,"created-at":1490842223357,"author":{"login":"parkeristyping","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/9487556?v=3"},"body":"user=> (defn loop-endlessly\n \"Block thread with endless loop when evaluated\"\n []\n (while true))\n#'user/loop-endlessly\n\nuser=> (take 3 (lazy-cat [\"will\" \"it\" \"return?\"] (loop-endlessly)))\n(\"will\" \"it\" \"return?\")\n\nuser=> (take 4 (lazy-cat [\"will\" \"it\" \"return?\"] (loop-endlessly)))\n;; This gets stuck on loop-endlessly and never returns","_id":"58dc726fe4b01f4add58fe7f"},{"editors":[{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"}],"body":";; Prefer lazy-cat to build a lazy seq out of \n;; non-lazy collections with different creation costs\n\n(time (first (concat (sort > (range 10)) (sort > (range 1e7)))))\n;; \"Elapsed time: 17442.084309 msecs\"\n(time (first (lazy-cat (sort > (range 10)) (sort > (range 1e7)))))\n;; \"Elapsed time: 0.458283 msecs\"","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"},"created-at":1520442196806,"updated-at":1520457888627,"_id":"5aa01b54e4b0316c0f44f910"},{"updated-at":1728499614983,"created-at":1728499614983,"author":{"login":"sanel","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/213914?v=4"},"body":";; Be aware that lazy-cat can be slower on smaller collections\n\n(time (first (concat (sort > (range 100)) (sort > (range 100)))))\n;; \"Elapsed time: 0.058254 msecs\"\n(time (first (lazy-cat (sort > (range 100)) (sort > (range 100)))))\n;; \"Elapsed time: 0.182578 msecs\"\n\n(time (first (concat (sort > (range 10)) (sort > (range 100)))))\n;; \"Elapsed time: 0.051935 msecs\"\n(time (first (lazy-cat (sort > (range 10)) (sort > (range 100)))))\n;; \"Elapsed time: 0.149794 msecs\"","_id":"6706cf9e69fbcc0c22617502"}],"macro":true,"notes":[{"body":"It looks like `lazy-cat` is on deprecation path in favor of `lazy-seq`.","created-at":1423002660607,"updated-at":1423002660607,"author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"_id":"54d14c24e4b081e022073c48"}],"arglists":["& colls"],"doc":"Expands to code which yields a lazy sequence of the concatenation\n of the supplied colls. Each coll expr is not evaluated until it is\n needed. \n\n (lazy-cat xs ys zs) === (concat (lazy-seq xs) (lazy-seq ys) (lazy-seq zs))","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/lazy-cat"},{"added":"1.0","ns":"clojure.core","name":"comment","file":"clojure/core.clj","type":"macro","column":1,"see-alsos":null,"line":4760,"examples":[{"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":";; The commented forms do not get executed\nuser=> (comment\n (functioncall-1)\n (functioncall-2))\nnil","created-at":1279395666000,"updated-at":1285500093000,"_id":"542692cac026201cdc326b64"},{"editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3","account-source":"github","login":"jafingerhut"},{"login":"zk","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/7194?v=4"}],"updated-at":1600227856975,"created-at":1416432947075,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3","account-source":"github","login":"jafingerhut"},"body":";; What is inside the (comment ...) form is not completely ignored. Clojure\n;; still tries to use the normal reader to read it, so it must consist of\n;; a sequence of readable forms with balanced parens, braces, square brackets,\n;; with no unreadable elements.\n\n;; If you want lines to be completely ignored, you must use a ; to comment from\n;; the ; until the end of the line. If you want to quickly comment or uncomment\n;; a range of consecutive lines, most text editors have special commands\n;; specifically for that. e.g. Emacs has comment-region\n;; http://www.gnu.org/software/emacs/manual/html_node/emacs/Comment-Commands.html\n;; Vim has visual commands to do this, and probably many other text editors.\n;; (Feel free to edit this text to add links to docs for other editors).\n\n;; What is inside the (comment ...) is readable, so no error for this,\n;; and no code will be generated by the compiler.\n(comment\n(defn foo [x]\n (inc x))\n)\n\n;; What is inside the (comment ...) is NOT readable, so this will give an error\n(comment\na : b\n)","_id":"546d0d33e4b03d20a10242b0"},{"body":";; Another thing to watch out for: the comment form IS a form, and is usually\n;; the wrong way to comment out code. For example, let's say that you want to\n;; try out a new \"then\" form in an \"if\":\n(if true (comment :old-then) :new-then) ;;=> nil (Oops, :new-then was desired.)\n\n;; Instead, use the \"ignore next form\" reader macro #_:\n(if true #_(:old-then) :new-then) ;;=> :new-then\n\n;; Note that #_ also allows non-readable code:\n#_(a : b) 1 ;;=> 1 (contrast to (comment a : b) which doesn't compile.)\n","author":{"login":"fordsfords","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7671908?v=3"},"created-at":1416776582477,"updated-at":1416776582477,"_id":"54724b86e4b03d20a10242b1"},{"updated-at":1591912144471,"created-at":1562932314262,"author":{"login":"loeschzwerg","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/24317401?v=4"},"body":";; You can use comment to work with a journal\n;; (but beware if you want to denote it as a journal)\n\n(comment) ;; works\n(comment ^:journal []) ;; works\n\n;; Doesn't work\n(comment\n ^:journal \n ;; I did some really cool stuff\n)\nERROR Could not Read: Unmatched delimiter ).","editors":[{"avatar-url":"https://avatars3.githubusercontent.com/u/24317401?v=4","account-source":"github","login":"loeschzwerg"},{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/109629?v=4"}],"_id":"5d28745ae4b0ca44402ef783"}],"macro":true,"notes":[{"updated-at":1389835580000,"body":"it doesn't 100% ignore the body. If your comment has a map in it, for example, and that map isn't 100% correct it will fail to compile in some environments. I found that using Light Table. I am certain it would fail on other platforms that won't know to exclude it before parsing.\r\n\r\nExample:\r\n(comment\r\n here is some TeX: \\frac{\\sum_{m=1}^{m}x_{m}}{x_{s}}\r\n)\r\n\r\nThat will produce an error.","created-at":1389835580000,"author":{"login":"Pete","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8e398ff59e0c0073ccb6770938de769e?r=PG&default=identicon"},"_id":"542692edf6e94c6970522019"}],"arglists":["& body"],"doc":"Ignores body, yields nil","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/comment"},{"added":"1.12","ns":"clojure.core","name":"*repl*","file":"clojure/core.clj","type":"var","column":1,"see-alsos":null,"dynamic":true,"line":6365,"examples":null,"notes":null,"arglists":[],"doc":"Bound to true in a repl thread","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/*repl*"},{"added":"1.0","ns":"clojure.core","name":"parents","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1341101519000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"descendants","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521be0"},{"created-at":1341101522000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"ancestors","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521be1"},{"created-at":1341101538000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"derive","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521be2"},{"created-at":1341101540000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"underive","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521be3"},{"created-at":1341101544000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"make-hierarchy","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521be4"},{"created-at":1341101631000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"isa?","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521be5"}],"line":5638,"examples":[{"author":{"login":"shockbob","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon"},"editors":[],"body":";; simple example showing single parented derivation\n;; then adding another parent\n\nuser=> (derive ::toy_poodle ::poodle)\nnil\nuser=> (parents ::toy_poodle)\n#{:user/poodle}\nuser=> (derive ::toy_poodle ::toy_dogs)\nnil\nuser=> (parents ::toy_poodle)\n#{:user/poodle :user/toy_dogs}\nuser=>","created-at":1313967813000,"updated-at":1313967813000,"_id":"542692cbc026201cdc326bde"},{"updated-at":1678607760647,"created-at":1678607760647,"author":{"login":"KingMob","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/946421?v=4"},"body":";; This works on Java classes as well. Note that\n;; it will only show direct parents, not the entire\n;; ancestor hierarchy.\n\n(parents CompletableFuture)\n=> #{java.util.concurrent.Future java.lang.Object java.util.concurrent.CompletionStage}\n\n(parents ConcurrentHashMap)\n=> #{java.io.Serializable java.util.AbstractMap java.util.concurrent.ConcurrentMap}","_id":"640d8590e4b08cf8563f4b7d"}],"notes":null,"arglists":["tag","h tag"],"doc":"Returns the immediate parents of tag, either via a Java type\n inheritance relationship or a relationship established via derive. h\n must be a hierarchy obtained from make-hierarchy, if not supplied\n defaults to the global hierarchy","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/parents"},{"added":"1.0","ns":"clojure.core","name":"count","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1467307156453,"author":{"login":"miner","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/25400?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"counted?","ns":"clojure.core"},"_id":"57755494e4b0bafd3e2a049b"}],"line":876,"examples":[{"updated-at":1424124841816,"created-at":1279416590000,"body":"(count nil)\n;;=> 0\n\n(count [])\n;;=> 0\n\n(count [1 2 3])\n;;=> 3\n\n(count {:one 1 :two 2})\n;;=> 2\n\n(count [1 \\a \"string\" [1 2] {:foo :bar}])\n;;=> 5\n\n(count \"string\")\n;;=> 6","editors":[{"avatar-url":"https://www.gravatar.com/avatar/b29dd31d183124d9e87d8037bb30e326?r=PG&default=identicon","account-source":"clojuredocs","login":"matthewg"},{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3","account-source":"github","login":"phreed"}],"author":{"avatar-url":"https://avatars2.githubusercontent.com/u/22608?v=4","account-source":"github","login":"MrHus"},"_id":"542692cbc026201cdc326bf9"},{"author":{"login":"rquinn","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/b3f3b40ea11b41b503df93d8b4a17043?r=PG&default=identicon"},"editors":[{"login":"Noneo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e66c8f6c768e29808bddd38ed2f21349?r=PG&default=identicon"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":"(count '(1 2 3 3 1))\n;;=> 5\n\n;; and as a koan\n(= (count '(1 2 3 3 1)) 5)\n;;=> true","created-at":1389437673000,"updated-at":1424124671851,"_id":"542692d2c026201cdc326f75"},{"updated-at":1579258350735,"created-at":1579258350735,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"body":";; count can't count beyond (Integer/MAX_VALUE)\n;; (in partial compliance with Java's Collection::size() returning int)\n\n(count (range (inc (Integer/MAX_VALUE))))\n;; Execution error (ArithmeticException)\n;; integer overflow","_id":"5e2191eee4b0ca44402ef818"},{"updated-at":1656427246940,"created-at":1656427246940,"author":{"login":"JeniferDalcin","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/83920579?v=4"},"body":"(def items-to-buy {:milk 2 :bread 10 :chocolate 1})\n\n(count items-to-buy)\n\n;;=> 3","_id":"62bb12eee4b0b1e3652d760e"},{"updated-at":1717617382042,"created-at":1717617382042,"author":{"login":"aanacarolina","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/79257314?v=4"},"body":";;be aware that calling count on lazy sequences realizes them\n\n(type (map #(println \"lazy\" %) [1 2 3]))\n;clojure.lang.LazySeq\n\n(type (count (map #(println \"not-lazy-anymore\" %) [1 2 3])))\n;not-lazy-anymore 1\n;not-lazy-anymore 2\n;not-lazy-anymore 3\n;java.lang.Integer\n","_id":"6660c2e669fbcc0c226174d2"}],"notes":null,"arglists":["coll"],"doc":"Returns the number of items in the collection. (count nil) returns\n 0. Also works on strings, arrays, and Java Collections and Maps","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/count"},{"added":"1.0","ns":"clojure.core","name":"supers","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1285511319000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"type","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d64"},{"created-at":1285513946000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"instance?","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d65"},{"created-at":1307530958000,"author":{"login":"stand","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d7f9ed2753f8b3517f1539f6129f0a17?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"bases","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d66"},{"created-at":1374150792000,"author":{"login":"alilee","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2fb0196dc5a7cd3a5cc73f1b9941c209?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"ancestors","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d67"}],"line":5606,"examples":[{"author":{"login":"stand","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d7f9ed2753f8b3517f1539f6129f0a17?r=PG&default=identicon"},"editors":[],"body":";;find superclasses and interfaces of Java objects...\nuser> (supers Object)\nnil\n\nuser> (supers String)\n#{java.lang.Comparable java.lang.CharSequence java.io.Serializable java.lang.Object}\n\n;;...or Java interfaces\nuser> (supers javax.naming.Name)\n#{java.lang.Cloneable java.lang.Comparable java.io.Serializable}\n\n;;Also with clojure types...\nuser> (defrecord MyThing [a b c])\nuser.MyThing\n\nuser> (supers MyThing)\n#{clojure.lang.Counted java.lang.Iterable clojure.lang.IKeywordLookup clojure.lang.IObj clojure.lang.IPersistentMap clojure.lang.Associative clojure.lang.Seqable java.util.Map clojure.lang.IMeta java.io.Serializable java.lang.Object clojure.lang.IPersistentCollection clojure.lang.ILookup}\n","created-at":1307530922000,"updated-at":1307530922000,"_id":"542692cdc026201cdc326cce"},{"updated-at":1546970349060,"created-at":1546970349060,"author":{"login":"mikebohdan","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/9021802?v=4"},"body":";; get all superclasses and interfaces for functions\nuser> (defn foo [x] (+ x 1))\nuser> (supers (class foo))\n#{java.lang.Runnable java.util.Comparator java.io.Serializable java.util.concurrent.Callable clojure.lang.AFn clojure.lang.IFn clojure.lang.Fn java.lang.Object clojure.lang.IMeta clojure.lang.AFunction clojure.lang.IObj}","_id":"5c34e4ede4b0ca44402ef618"}],"notes":null,"arglists":["class"],"doc":"Returns the immediate and indirect superclasses and interfaces of c, if any","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/supers"},{"ns":"clojure.core","name":"*fn-loader*","type":"var","see-alsos":null,"examples":null,"notes":null,"arglists":[],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core/*fn-loader*"},{"added":"1.0","ns":"clojure.core","name":"sorted-map-by","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1281961885000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"sorted-map","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e6b"},{"created-at":1330671660000,"author":{"login":"Chouser","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/7a0192050ed6488670acfd3f59405c10?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"subseq","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e6c"},{"created-at":1330671664000,"author":{"login":"Chouser","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/7a0192050ed6488670acfd3f59405c10?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"rsubseq","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e6d"},{"created-at":1353458254000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.core","name":"sorted-set-by","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e6e"},{"created-at":1427316125890,"author":{"login":"cloojure","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7083783?v=3"},"to-var":{"ns":"clojure.core","name":"compare","library-url":"https://github.com/clojure/clojure"},"_id":"55131d9de4b08eb9aa0a8d38"},{"created-at":1427316135655,"author":{"login":"cloojure","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7083783?v=3"},"to-var":{"ns":"clojure.core","name":"comparator","library-url":"https://github.com/clojure/clojure"},"_id":"55131da7e4b08eb9aa0a8d39"}],"line":409,"examples":[{"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"editors":[{"login":"STeveShary","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/5167622?v=3"},{"login":"cloojure","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7083783?v=3"}],"body":"; The basic function requires discrete elements, and cannot accept a \n; pre-existing map:\nuser=> (sorted-map-by > 1 \"a\", 2 \"b\", 3 \"c\")\n{3 \"c\", 2 \"b\", 1 \"a\"}\n\n; We can use the syntax \"(sorted-map >)\" to create an empty sorted map that sorts \n; in reverse order (i.e. the opposite of \"(sorted-map)\"). It we can then fill\n; it using (into ...) with a pre-existing map:\nuser=> (into (sorted-map-by >) {1 :a 2 :b 3 :c} )\n{3 :c, 2 :b, 1 :a}\n\n; This two are the same\nuser=> (into (sorted-map-by <) {1 :a 2 :b 3 :c} )\n{1 :a, 2 :b, 3 :c}\nuser=> (into (sorted-map) {1 :a 2 :b 3 :c} )\n{1 :a, 2 :b, 3 :c}\n\n","created-at":1286955811000,"updated-at":1423716874311,"_id":"542692cac026201cdc326b5e"},{"updated-at":1548548894859,"created-at":1331260029000,"body":";; If you wish to sort the map according to the values, instead of by keys \n;; the following code WILL NOT WORK! This is because the map values are not unique.\n\nuser=> (let [results {:A 1 :B 2 :C 2 :D 5 :E 1 :F 1}]\n (into (sorted-map-by (fn [key1 key2]\n (compare (get results key2)\n (get results key1))))\n results))\n\n=> {:D 5, :C 2, :A 1}\n\n;; To make sure that the sorting works, we can make sure that the comparator \n;; works on unique values\n\nuser=> (let [results {:A 1 :B 2 :C 2 :D 5 :E 1 :F 1}]\n (into (sorted-map-by (fn [key1 key2]\n (compare [(get results key2) key2]\n [(get results key1) key1])))\n results))\n\n=> {:D 5, :C 2, :B 2, :F 1, :E 1, :A 1}\n\n;; See this article for more details: https://clojure.org/guides/comparators","editors":[{"avatar-url":"https://www.gravatar.com/avatar/24b2f585e6df92df9885e37b3b285c43?r=PG&default=identicon","account-source":"clojuredocs","login":"defiantt"},{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/109629?v=4"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/24b2f585e6df92df9885e37b3b285c43?r=PG&default=identicon","account-source":"clojuredocs","login":"defiantt"},"_id":"542692d5c026201cdc327094"},{"editors":[{"login":"aarkerio","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/226965?v=4"}],"body":";; Ordering using nested values\n\n(def rows {:45 {:ordnen 5} :55 {:ordnen 8} :66 {:ordnen 3} :68 {:ordnen 90} :13 {:ordnen 1}})\n\n(into (sorted-map-by (fn [key1 key2]\n (compare\n (get-in rows [key1 :ordnen])\n (get-in rows [key2 :ordnen]))))\n rows)\n\n{:13 {:ordnen 1},\n :66 {:ordnen 3},\n :45 {:ordnen 5},\n :55 {:ordnen 8},\n :68 {:ordnen 90}}\n ","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/226965?v=4","account-source":"github","login":"aarkerio"},"created-at":1585685462057,"updated-at":1585685482087,"_id":"5e83a3d6e4b087629b5a18c8"},{"updated-at":1588694823302,"created-at":1588694823302,"author":{"login":"ejschoen","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10605666?v=4"},"body":";; Note that when querying values from the map, the comparator will be called, \n;; and must work on values that are not keys in the map:\n\nuser=> (get (into (sorted-map-by (fn [a b] (println a b) (compare a b))) \n {\"a\" 1 \"b\" 2})) \n \"c\")\nb a\nc a\nc b\n=> nil\n\n;; If the comparator looks into an auxiliary data structure for a comparison\n;; value, ensure that the comparator can handle a missing value in that data\n;; structure:\n\nuser=> (let [other {\"a\" 10 \"b\" 1}\n m (into (sorted-map-by (fn [a b] (< (get other a) (get other b)))) \n {\"a\" 1 \"b\" 2})]\n (println (get m \"a\"))\n (println (get m \"b\"))\n (println (get m \"c\")))\n1\n2\nNullPointerException clojure.lang.Numbers.ops (Numbers.java:1013)\nuser=>","_id":"5eb18f27e4b087629b5a1900"}],"notes":[{"author":{"login":"noisesmith","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/169654?v=4"},"updated-at":1517725988658,"created-at":1517725696549,"body":"an unstable sorting function will give nonsense results:\n\n
    \nuser=> (into (sorted-map-by (fn [_ _] (rand-int Integer/MAX_VALUE))) [[:a 0] [:a 1] [:a 2]])\n\n{:a 0, :a 1, :a 2}\n
    ","_id":"5a76a800e4b0e2d9c35f7416"},{"author":{"login":"elias94","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8095533?v=4"},"updated-at":1659590612300,"created-at":1659589967366,"body":"As previously noted, using an unstable sorting function could lead to unexpected results and hard to find bug. The `PersistentTreeMap` object returned by `sorted-map-by`, stores the `comparator` function and will reuse it in consecutive operations as `assoc`.\n\n```\n(def ord [:a :b :c])\n(def m (into (sorted-map-by (fn [a b] \n                              (compare (.indexOf ord a) \n                                       (.indexOf ord b))))  \n             {:a 1 :b 2 :c 3}))\n(assoc m :d 4) ; => {:d 4, :a 1, :b 2, :c 3}\n(-> (assoc m :d 4)\n    (assoc :e 5)) ; => {:d 5, :a 1, :b 2, :c 3} WRONG\n```\n\n[Source reference](https://github.com/clojure/clojure/blob/master/src/jvm/clojure/lang/PersistentTreeMap.java#L28)\n","_id":"62eb554fe4b0b1e3652d7637"}],"arglists":["comparator & keyvals"],"doc":"keyval => key val\n  Returns a new sorted map with supplied mappings, using the supplied\n  comparator.  If any keys are equal, they are handled as if by\n  repeated uses of assoc.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/sorted-map-by"},{"added":"1.0","ns":"clojure.core","name":"apply","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1285116731000,"author":{"login":"gregg-williams","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/58610a64fc8638eec8d2239d80d4046f?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"map","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521eae"},{"created-at":1289278196000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"eval","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521eaf"},{"created-at":1289278244000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.template","name":"apply-template","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521eb1"},{"created-at":1411938673196,"author":{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},"to-var":{"ns":"clojure.core","name":"reduce","library-url":"https://github.com/clojure/clojure"},"_id":"54287971e4b0ba57bdbcf25f"},{"created-at":1598160814660,"author":{"login":"berczeck","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/1321842?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"partial","ns":"clojure.core"},"_id":"5f41ffaee4b0b1e3652d739d"}],"line":662,"examples":[{"updated-at":1422053574794,"created-at":1279062643000,"body":"(def *strings* [\"str1\" \"str2\" \"str3\"])\n;; #'user/*strings*\n\n;; Oops!\n(str *strings*)\n;;=> \"[\\\"str1\\\" \\\"str2\\\" \\\"str3\\\"]\"\n\n;; Yay!\n(apply str *strings*)\n;;=> \"str1str2str3\"\n\n;; Note the equivalence of the following two forms\n(apply str [\"str1\" \"str2\" \"str3\"])  ;;=> \"str1str2str3\"\n(str \"str1\" \"str2\" \"str3\")          ;;=> \"str1str2str3\"\n","editors":[{"avatar-url":"https://www.gravatar.com/avatar/58610a64fc8638eec8d2239d80d4046f?r=PG&default=identicon","account-source":"clojuredocs","login":"gregg-williams"},{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3","account-source":"github","login":"phreed"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/142529?v=3","account-source":"github","login":"nipra"},"_id":"542692cdc026201cdc326d46"},{"updated-at":1739045093020,"created-at":1280207658000,"body":";; If you were to try\n(max [1 2 3])\n;;=> [1 2 3]\n\n;; You would get '[1 2 3]' for the result. In this case, 'max' has received one\n;; vector argument, and the largest of its arguments is that single vector.\n\n;; If you would like to find the largest item **within** the vector, you would need\n;; to use `apply`\n\n(apply max [1 2 3])\n;;=> 3\n\n;; which is the same as \n(max 1 2 3)\n;;=> 3\n\n;; the last argument can be a list\n(apply max (list 2 5 3))\n;;=> 5\n\n;; the last argument can be a set\n(apply max #{2 5 3})\n;;=> 5","editors":[{"avatar-url":"https://www.gravatar.com/avatar/58610a64fc8638eec8d2239d80d4046f?r=PG&default=identicon","account-source":"clojuredocs","login":"gregg-williams"},{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3","account-source":"github","login":"phreed"},{"login":"cljlc","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/36645452?v=4"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/1703a0c3ed358b787f4b1bf3b2799472?r=PG&default=identicon","account-source":"clojuredocs","login":"Jacolyte"},"_id":"542692cdc026201cdc326d49"},{"updated-at":1647518010897,"created-at":1285120582000,"body":";; Here's an example that uses a optional second argument, x:\n\n(apply map vector [[:a :b] [:c :d]])\n;;=> ([:a :c] [:b :d])\n\n;; In this example, 'f' = 'map', 'x' = 'vector', and args = '[:a :b] [:c :d]',\n;; making the above code equivalent to\n\n(map vector [:a :b] [:c :d])\n;;=> ([:a :c] [:b :d]) ;Same answer as above\n\n;; It might help to think of 'map' and 'vector' as \"slipping inside\" the argument\n;; list ( '[[:a :b] [:c :d]]' ) to give '[map vector [:a :b] [:c :d]]' , which \n;; then becomes the executable form '(map vector [:a :b] [:c :d])' .","editors":[{"avatar-url":"https://www.gravatar.com/avatar/58610a64fc8638eec8d2239d80d4046f?r=PG&default=identicon","account-source":"clojuredocs","login":"gregg-williams"},{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"avatar-url":"https://avatars.githubusercontent.com/u/200617?v=3","account-source":"github","login":"bsima"},{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3","account-source":"github","login":"phreed"},{"login":"gunnarx","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7410653?v=4"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/58610a64fc8638eec8d2239d80d4046f?r=PG&default=identicon","account-source":"clojuredocs","login":"gregg-williams"},"_id":"542692cdc026201cdc326d4d"},{"updated-at":1543265664647,"created-at":1288763486000,"body":";; only functions can be used with apply.  'and' is a macro\n;; because it needs to evaluate its arguments lazily and so\n;; does not work with apply.\n(apply and (list true true false true))\n;; RuntimeException : cannot take value of a macro\n\n;; This can be circumvented with another macro.\n;; But understand what is happening\n;; http://stackoverflow.com/questions/5531986/treat-clojure-macro-as-a-function\n(defmacro make-fn [m] \n `(fn [& args#]\n    (eval \n      (cons '~m args#))))\n\n(apply (make-fn and) '(true true false true))\n;;=> false\n\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3","account-source":"github","login":"phreed"},{"login":"mdave16","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/15642321?v=4"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon","account-source":"clojuredocs","login":"gstamp"},"_id":"542692cdc026201cdc326d50"},{"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"editors":[{"login":"jasonrudolph.com","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/c4e34ac0818591402a41b2e9cfb4747b?r=PG&default=identicon"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":";; 'apply' is used to apply an operator to its operands. \n(apply + '(1 2))  ; equivalent to (+ 1 2)\n;;=> 3\n\n\n;; You can also put operands before the list of \n;; operands and they'll be consumed in the list of operands\n\n(apply + 1 2 '(3 4))  ; equivalent to (apply + '(1 2 3 4))\n;;=> 10","created-at":1289278192000,"updated-at":1422054628109,"_id":"542692cdc026201cdc326d51"},{"author":{"login":"shockbob","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon"},"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":";; You can use map and apply together to drill one level deep in a collection\n;; of collections, in this case returning a collection of the max of each\n;; nested collection\n\n(map #(apply max %) [[1 2 3][4 5 6][7 8 9]])\n;;=> (3 6 9)","created-at":1310850474000,"updated-at":1422054659726,"_id":"542692cdc026201cdc326d53"},{"author":{"login":"Jeff Terrell","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/658b2643cf2a8192286b5bb1ecb62cf8?r=PG&default=identicon"},"editors":[],"body":";; Using `apply` with optional keyword parameters:\n\n(defn add2 [a & {:keys [plus] :or {plus 0}}]\n  (+ 2 plus a))\n\n(add2 4)                    ; => 6\n(add2 4 :plus 1)            ; => 7\n(apply add2 [4])            ; => 6\n(apply add2 [4 {:plus 1}])  ; => IllegalArgumentException\n(apply add2 [4 :plus 1])    ; => 7\n","created-at":1409438218000,"updated-at":1409438218000,"_id":"542692d2c026201cdc326f4a"},{"editors":[{"login":"nbren12","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1386642?v=3"}],"body":";; Transpose a matrix\n(def A [[1 2]\n        [3 4]])\n\n(apply map vector A) ;  ([1 3] [2 4])\n","author":{"avatar-url":"https://avatars.githubusercontent.com/u/1386642?v=3","account-source":"github","login":"nbren12"},"created-at":1437005741779,"updated-at":1437005816540,"_id":"55a6f7ade4b0080a1b79cda1"},{"updated-at":1447364097315,"created-at":1447364097315,"author":{"login":"bsima","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/200617?v=3"},"body":";; Use apply to map a function over a collection of pairs of arguments\n\n(map (partial apply +) [[1 2] [3 4]]) ; => (3 7)\n\n;; this is equivalent to '((+ 1 2) (+ 3 4))","_id":"56450601e4b053844439826e"},{"updated-at":1487799337630,"created-at":1487799337630,"author":{"login":"smnplk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/380618?v=3"},"body":"; Remove elements from a set with disj\n\n(disj #{1 2 3} 2 3) \n=> #{1}\n\n; Relative complement of two sets (difference)\n\n(apply disj #{2 3 4} #{1 2 3})\n=> #{4}\n\n; the above is same as calling\n(disj #{2 3 4} 1 2 3)","_id":"58ae0429e4b01f4add58fe5d"},{"updated-at":1517124285557,"created-at":1517124285557,"author":{"login":"ibercode","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/31028993?v=4"},"body":";;practical example\n\n(def entries [{:month 1 :val 12}\n              {:month 2 :val 3}\n              {:month 3 :val 32}\n              {:month 4 :val 18}\n              {:month 5 :val 32}\n              {:month 6 :val 62}\n              {:month 7 :val 12}\n              {:month 8 :val 142}\n              {:month 9 :val 52}\n              {:month 10 :val 18}\n              {:month 11 :val 23}\n              {:month 12 :val 56}])\n\n(apply max (map\n            #(:val %)\n            entries))\n;;return 142\n;;this translates into (max 12 3 32 18 32 62 12 142 52 18 23 56)","_id":"5a6d7abde4b0c974fee49d10"},{"editors":[{"login":"Okwori","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/16775439?v=4"}],"body":"(apply + [2 3 4])\n;;9\n\n(apply + 1 [2 3 4])\n;;10\n\n(apply max [1 3 2])\n;;3\n\n(apply max 4 [1 3 2])\n;;4\n\n(apply str [\"a\" \"b\" \"c\"])\n;;\"abc\"\n\n(apply str \"d\" [\"a\" \"b\" \"c\"])\n;;\"dabc\"\n\n(str \"Hi, here: \" (apply str (for [i (range 5)] i)) \" Cheers!\")\n;; \"Hi, here: 01234 Cheers!\"","author":{"avatar-url":"https://avatars0.githubusercontent.com/u/31028993?v=4","account-source":"github","login":"ibercode"},"created-at":1518885671189,"updated-at":1627950640374,"_id":"5a885b27e4b0316c0f44f8c9"},{"editors":[{"login":"cljlc","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/36645452?v=4"}],"body":"(reduce #(apply assoc %1 %2) {} [[:a 1] [:b 2]])\n;;=> {:a 1, :b 2}\n\n;; The other direction works as well, i.e. the last argument can be a map\n(apply list {:a 1 :b 2})\n;;=> ([:a 1][:b 2])","author":{"avatar-url":"https://avatars2.githubusercontent.com/u/1223207?v=4","account-source":"github","login":"hadielmougy"},"created-at":1535318272487,"updated-at":1739045977812,"_id":"5b831900e4b00ac801ed9e79"},{"updated-at":1550289947317,"created-at":1550285729081,"author":{"login":"jdf-id-au","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/9016301?v=4"},"body":"(defn chunks\n  \"Lazily break up map of colls into maps of chunks of n records (default 100 000).\n  Truncates at shortest coll (chunk-wise).\"\n  ([m] (chunks 100000 m))\n  ([n m] (apply map merge (repeatedly sorted-map)\n           (for [[k v] m]\n             (for [part (partition-all n v)]\n               {k part})))))\n\n(chunks 2 {:b [1 2 3] :a [1 2 3 4] :c [1 2 3 4 5]})\n=> ({:a (1 2), :b (1 2), :c (1 2)}\n    {:a (3 4), :b (3), :c (3 4)})\n\n(defn non-truncating-chunks\n  ([m] (chunks 100000 m))\n  ([n m] (let [partitioned-lists\n               ;; '(({k0 part0} {k0 part1} ... nil nil ...)\n               ;;   ({k1 part0} {k1 part1} ... nil nil ...)\n               ;;   ...)\n               (for [[k v] m]\n                 ;; '({k part0} {k part1} ... nil nil ... )\n                 (concat ; append nils to prevent map truncating at shortest\n                   (for [part (partition-all n v)]\n                     {k part})\n                   (repeat nil)))]\n           ;; '(({k0 part0} {k1 part0} ...)\n           ;;   ({k0 part1} {k1 part1} ...)\n           ;;   ...)\n           (for [ls (apply map list partitioned-lists)\n                 :while (not-every? nil? ls)]\n             (apply merge (sorted-map) ls)))))\n\n(non-truncating-chunks 2 {:b [1 2 3] :a [1 2 3 4] :c [1 2 3 4 5]})\n=> ({:a (1 2), :b (1 2), :c (1 2)}\n    {:a (3 4), :b (3), :c (3 4)}\n    {:c (5)})","editors":[{"avatar-url":"https://avatars3.githubusercontent.com/u/9016301?v=4","account-source":"github","login":"jdf-id-au"}],"_id":"5c677ba1e4b0ca44402ef688"},{"editors":[{"login":"berczeck","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/1321842?v=4"}],"body":";; Based in the example from the great book CLOJURE for the BRAVE and TRUE\n;; https://www.braveclojure.com/core-functions-in-depth/\n\n(def countries [:peru :mexico])\n\n(defn add-first\n   [target addition]\n   (apply conj [addition] target))\n\n(add-first countries :brazil)\n\n;; [:brazil :peru :mexico]","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/1321842?v=4","account-source":"github","login":"berczeck"},"created-at":1598163155919,"updated-at":1598165224331,"_id":"5f4208d3e4b0b1e3652d739f"},{"editors":[{"login":"jimka2001","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/6414129?v=4"}],"body":";; If `apply` is called on a function having optional arguments as shown in\n;; `function-2`, you must pre-manipulate the arguments before calling `apply`\n\n(defn function-2\n  [arg1 & {:keys [a b c]\n           :as all-optionals\n           :or {a 42}}]\n  (list arg1 a b c all-optionals))\n\n;; Suppose you'd like to call `function-2` from `function-1` passing along \n;; the *same* optional arguments.\n\n;; In this example, the call-site of `function-1` may contain any keyword \n;; argument for `function-1` or for `function-2`.\n\n(defn function-1\n  [arg1 & {:keys [c d e]\n           :as all-optionals\n           :or {d 42}}]\n  (apply function-2 arg1 (mapcat identity all-optionals)))\n\n(function-1 1)\n;; [arg1 1 a 42 b nil c nil all-optionals nil]\n\n(function-1 1 :c 2)\n;; [arg1 1 a 42 b nil c 2 all-optionals {:c 2}]\n\n(function-1 1 :c 2 :a 3)\n;; [arg1 1 a 3 b nil c 2 all-optionals {:c 2, :a 3}]\n","author":{"avatar-url":"https://avatars.githubusercontent.com/u/6414129?v=4","account-source":"github","login":"jimka2001"},"created-at":1626948876981,"updated-at":1626949139811,"_id":"60f9450ce4b0b1e3652d7519"},{"editors":[{"login":"pradeepbishnoi","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1634146?v=4"}],"body":"(def input-2 [\"P1\" \"R2\" \"A3\" \"D4\" \"E5\" \"e6\" \"p7\"])\n\n(apply map vector input-2)\n;; => ([\\P \\R \\A \\D \\E \\e \\p] [\\1 \\2 \\3 \\4 \\5 \\6 \\7])\n\nis same as writing using map form :\n\n(map vector (nth input-2 0)\n     (nth input-2 1)\n     (nth input-2 2)\n     (nth input-2 3)\n     (nth input-2 4)\n     #_(nth input-2 5)\n     ,)\n;; => ([\\P \\R \\A \\D \\E] [\\1 \\2 \\3 \\4 \\5])\n\n(apply map #(println %&) input-2)\n;; => (P R A D E e p)\n;;    (nil(1 2 3 4 5 6 7)\n;;     nil)\n\nfurther playaround like below to get more comfortable\n(map vector \"P1\" \"R2\")\n;; => ([\\P \\R] [\\1 \\2])\n","author":{"avatar-url":"https://avatars.githubusercontent.com/u/1634146?v=4","account-source":"github","login":"pradeepbishnoi"},"created-at":1638598080447,"updated-at":1638598196914,"_id":"61ab05c0e4b0b1e3652d7580"},{"updated-at":1696636793892,"created-at":1696636793892,"author":{"login":"0xjlanka","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/60111771?v=4"},"body":";; apply can be used to check if a sequence is already sorted\n\n;; Ascending order\n(apply < [1 2 3 4 5])\n;; => true\n\n(apply < (range 100))\n;; => true\n\n;; Descending order\n(apply > [5 4 3 2 1])\n;; => true\n\n(apply < (range 100 0 -1))\n;; => true","_id":"65209f79e4b08cf8563f4bfd"}],"notes":[{"author":{"login":"virajpurang","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1843638?v=3"},"updated-at":1444440195862,"created-at":1444440123734,"body":"The first example on the page, does not work on the REPL. It gives the following error: \n
     (def *strings* [\"str1\" \"str2\" \"str3\"])\" 
    \n\n*Warning: *strings* not declared dynamic and thus is not dynamically rebindable, but its name suggests otherwise. Please either indicate ^:dynamic *strings* or change the name.*\n\nShould this be prefixed by - \"^:dynamic\"?\n","_id":"5618683be4b084e61c76ecc0"},{"author":{"login":"didibus","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/601540?v=4"},"updated-at":1534908180799,"created-at":1534906692760,"body":"It looks like apply when used with a lazy sequence forces the realization of the first four elements.\n\n```\n(take 1\n (apply concat\n (repeatedly #(do\n (println \"called\")\n (range 1 10)))))\n\n=> \"called\"\n=> \"called\"\n=> \"called\"\n=> \"called\"\n```\n\nSee: https://stackoverflow.com/questions/51959298/clojure-apply-that-does-not-realize-the-first-four-elements-of-a-lazy-sequence","_id":"5b7cd144e4b00ac801ed9e69"}],"arglists":["f args","f x args","f x y args","f x y z args","f a b c d & args"],"doc":"Applies fn f to the argument list formed by prepending intervening arguments to args.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/apply"},{"added":"1.0","ns":"clojure.core","name":"interpose","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1293096431000,"author":{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},"to-var":{"ns":"clojure.core","name":"interleave","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bbb"},{"created-at":1334733658000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.string","name":"join","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bbc"}],"line":5259,"examples":[{"updated-at":1598971367289,"created-at":1278174751000,"body":";; The quintessential interpose example:\nuser> (def my-strings [\"one\" \"two\" \"three\"])\n\nuser> (interpose \", \" my-strings)\n=> (\"one\" \", \" \"two\" \", \" \"three\")\n\nuser> (apply str (interpose \", \" my-strings))\n=> \"one, two, three\"\n\n;; Might use clojure.string/join if the plan is to join\n(require '[clojure.string :as str])\nuser> (str/join \", \" my-strings)\n=> \"one, two, three\"","editors":[{"avatar-url":"https://www.gravatar.com/avatar/1de5617efb013ca7c9cf8e5646818ffa?r=PG&default=identicon","account-source":"clojuredocs","login":"philos99"},{"avatar-url":"https://www.gravatar.com/avatar/c889e0a95a3bb07f90ab28ad442f1127?r=PG&default=identicon","account-source":"clojuredocs","login":"Iceland_jack"},{"avatar-url":"https://www.gravatar.com/avatar/c889e0a95a3bb07f90ab28ad442f1127?r=PG&default=identicon","account-source":"clojuredocs","login":"Iceland_jack"},{"avatar-url":"https://www.gravatar.com/avatar/c889e0a95a3bb07f90ab28ad442f1127?r=PG&default=identicon","account-source":"clojuredocs","login":"Iceland_jack"},{"avatar-url":"https://www.gravatar.com/avatar/c889e0a95a3bb07f90ab28ad442f1127?r=PG&default=identicon","account-source":"clojuredocs","login":"Iceland_jack"},{"login":"daveliepmann","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/974443?v=4"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},"_id":"542692cdc026201cdc326d31"},{"updated-at":1519242639737,"created-at":1352930917000,"body":";; This example converts what would be comma-separated values into pipe '|'\n;; separated values for alternate database loads. By switching delimiters, \n;; quotes can be eliminated from each sequence element, which are not \n;; needed for some databases.\n\n(def test-data-in '((\"43\" \"MORRISON, VAN X DMD\" \"43 ROADWAY\" \\;)\n (\"25\" \"JANE SMITH N\" \"25 GARDEN PATH\" \\!)))\n\n(def test-data-out (map #(concat (interpose \\| %) (list \\| \"\\n\"))\n test-data-in))\n\ntest-data-out\n\n=> ((\"43\" \\| \"MORRISON, VAN X DMD\" \\| \"43 ROADWAY\" \\| \\; \\| \"\\n\")\n (\"25\" \\| \"JANE SMITH N\" \\| \"25 GARDEN PATH\" \\| \\! \\| \"\\n\"))\n\n(doseq [in-seq test-data-out]\n (doseq [val in-seq]\n (spit \"temp1.csv\" val :append true)))\n\n;; cat temp1.csv:\n\n;; 43|MORRISON, VAN X DMD|43 ROADWAY|;|\n;; 25|JANE SMITH N|25 GARDEN PATH|!|","editors":[{"avatar-url":"https://www.gravatar.com/avatar/fd31b8bcea99fa7b0711fbc424587774?r=PG&default=identicon","account-source":"clojuredocs","login":"octopusgrabbus"},{"avatar-url":"https://www.gravatar.com/avatar/fd31b8bcea99fa7b0711fbc424587774?r=PG&default=identicon","account-source":"clojuredocs","login":"octopusgrabbus"},{"avatar-url":"https://www.gravatar.com/avatar/fd31b8bcea99fa7b0711fbc424587774?r=PG&default=identicon","account-source":"clojuredocs","login":"octopusgrabbus"},{"avatar-url":"https://www.gravatar.com/avatar/fd31b8bcea99fa7b0711fbc424587774?r=PG&default=identicon","account-source":"clojuredocs","login":"octopusgrabbus"},{"login":"dosbol","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/6149147?v=4"},{"avatar-url":"https://avatars0.githubusercontent.com/u/36645452?v=4","account-source":"github","login":"cljlc"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/fd31b8bcea99fa7b0711fbc424587774?r=PG&default=identicon","account-source":"clojuredocs","login":"octopusgrabbus"},"_id":"542692d3c026201cdc326fd3"}],"notes":null,"arglists":["sep","sep coll"],"doc":"Returns a lazy seq of the elements of coll separated by sep.\n Returns a stateful transducer when no collection is provided.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/interpose"},{"added":"1.0","ns":"clojure.core","name":"deref","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1343082385000,"author":{"login":"john.r.woodward","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/22b6fbc4a386291e45b1cb4449377086?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"atom","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e70"},{"created-at":1343082392000,"author":{"login":"john.r.woodward","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/22b6fbc4a386291e45b1cb4449377086?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"agent","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e71"},{"created-at":1343082402000,"author":{"login":"john.r.woodward","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/22b6fbc4a386291e45b1cb4449377086?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"ref","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e72"},{"created-at":1423531286944,"author":{"login":"delonnewman","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10404?v=2"},"to-var":{"ns":"clojure.core","name":"realized?","library-url":"https://github.com/clojure/clojure"},"_id":"54d95d16e4b081e022073c8a"},{"created-at":1510406134570,"author":{"login":"l3nz","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/1101849?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"future","ns":"clojure.core"},"_id":"5a06f7f6e4b0a08026c48caf"}],"line":2323,"examples":[{"author":{"login":"dakrone","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bcacd00a7f05c4772329cf9f446c7987?r=PG&default=identicon"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":"user=> (def a (atom 0))\n#'user/a\nuser=> @a\n0\nuser=> (deref a)\n0\n\nuser=> (def b (ref 1))\n#'user/b\nuser=> @b\n1\nuser=> (deref b)\n1\n\nuser=> (def c (agent 2))\n#'user/c\nuser=> @c\n2\nuser=> (deref c)\n2\n\nuser=> (def d (future 3))\n#'user/d\nuser=> @d\n3\nuser=> (deref d)\n3","created-at":1280548071000,"updated-at":1332951465000,"_id":"542692c8c026201cdc326a12"},{"body":"user=> (def a (promise))\n#'user/a\nuser=> (deref a) ;; blocking until a delivery occurs \n\nuser=> (deref a 100 :timeout) ;; block for at most 100ms\n:timeout","author":{"login":"kgann","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1098962?v=2"},"created-at":1421253947329,"updated-at":1421253947329,"_id":"54b69d3be4b081e022073c0b"},{"updated-at":1534311765139,"created-at":1534311765139,"author":{"login":"viebel","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/955710?v=4"},"body":"user=> (def b 1)\n#'user/b\nuser=> (var b)\n#'user/b\nuser=> (deref (var b))\n1","_id":"5b73bd55e4b00ac801ed9e5a"}],"notes":null,"arglists":["ref","ref timeout-ms timeout-val"],"doc":"Also reader macro: @ref/@agent/@var/@atom/@delay/@future/@promise. Within a transaction,\n returns the in-transaction-value of ref, else returns the\n most-recently-committed value of ref. When applied to a var, agent\n or atom, returns its current state. When applied to a delay, forces\n it if not already forced. When applied to a future, will block if\n computation not complete. When applied to a promise, will block\n until a value is delivered. The variant taking a timeout can be\n used for blocking references (futures and promises), and will return\n timeout-val if the timeout (in milliseconds) is reached before a\n value is available. See also - realized?.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/deref"},{"added":"1.11","ns":"clojure.core","name":"parse-boolean","file":"clojure/core.clj","type":"function","column":1,"see-alsos":null,"line":8203,"examples":[{"updated-at":1698255506954,"created-at":1698255506954,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":"(parse-boolean \"true\")\n;; => true\n\n(parse-boolean \"false\")\n;; => false\n\n(parse-boolean \"False\")\n;; => nil\n(parse-boolean \"TRUE\")\n;; => nil\n(parse-boolean \"foo\")\n;; => nil\n(parse-boolean \"\")\n;; => nil","_id":"6539529269fbcc0c226173da"}],"notes":null,"arglists":["s"],"doc":"Parse strings \"true\" or \"false\" and return a boolean, or nil if invalid","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/parse-boolean"},{"added":"1.0","ns":"clojure.core","name":"assoc","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1291975387000,"author":{"login":"alimoeeny","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e8dd06976ead4082d2181f3807117e1?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"assoc-in","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ef1"},{"created-at":1295211937000,"author":{"login":"pauldoo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5cb916d3c8abc9f45a093209e72489fb?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"dissoc","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ef2"},{"created-at":1320356554000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"merge","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ef3"},{"created-at":1551138257703,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"update","ns":"clojure.core"},"_id":"5c747dd1e4b0ca44402ef6a7"},{"created-at":1570520695399,"author":{"login":"xmo-odoo","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/7571158?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"associative?","ns":"clojure.core"},"_id":"5d9c3e77e4b0ca44402ef7c9"},{"created-at":1714062841121,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"into","ns":"clojure.core"},"_id":"662a85f969fbcc0c226174c2"}],"line":183,"examples":[{"updated-at":1582579932440,"created-at":1278953718000,"body":"(assoc {} :key1 \"value\" :key2 \"another value\")\n;;=> {:key2 \"another value\", :key1 \"value\"}\n\n;; Here we see an overwrite by a second entry with the same key\n(assoc {:key1 \"old value1\" :key2 \"value2\"} \n :key1 \"value1\" :key3 \"value3\")\n;;=> {:key3 \"value3\", :key2 \"value2\", :key1 \"value1\"}\n\n;; We see a nil being treated as an empty map\n(assoc nil :key1 4)\n;;=> {:key1 4}\n\n;; 'assoc' can be used on a vector (but not a list), in this way: \n;; (assoc vec index replacement)\n(assoc [1 2 3] 0 10) ;;=> [10 2 3]\n(assoc [1 2 3] 2 '(4 6)) ;;=> [1 2 (4 6)]\n;; Next, 0 < index <= n, so the following will work\n(assoc [1 2 3] 3 10) ;;=> [1 2 3 10]\n;; However, when index > n, an error is thrown\n(assoc [1 2 3] 4 10)\n;; java.lang.IndexOutOfBoundsException (NO_SOURCE_FILE:0)\n\n;; From http://clojure-examples.appspot.com/clojure.core/assoc","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"avatar-url":"https://www.gravatar.com/avatar/b3ee701dd6c481e5d310467ddfe62c48?r=PG&default=identicon","account-source":"clojuredocs","login":"franks42"},{"avatar-url":"https://www.gravatar.com/avatar/497a50e2eb50bb7a8dbb839adc473f1f?r=PG&default=identicon","account-source":"clojuredocs","login":"MikeT"},{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3","account-source":"github","login":"phreed"},{"login":"Eleonore9","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2502761?v=3"},{"login":"borkdude","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/284934?v=4"},{"avatar-url":"https://avatars2.githubusercontent.com/u/36526095?v=4","account-source":"github","login":"adanhawth"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},"_id":"542692c9c026201cdc326acd"},{"author":{"login":"octopusgrabbus","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/fd31b8bcea99fa7b0711fbc424587774?r=PG&default=identicon"},"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"}],"body":";; here is an example of updating a field in a map.\n(def test-map {:account-no 12345678 :lname \"Jones\" :fnam \"Fred\"})\n(assoc test-map :fnam \"Sue\")\n;;=> {:account-no 12345678, :lname \"Jones\", :fnam \"Sue\"}\n\n;; notice that test-map is unchanged\ntest-map\n;;=> {:account-no 12345678 :lname \"Jones\" :fnam \"Fred\"})","created-at":1366772136000,"updated-at":1412883533397,"_id":"542692d2c026201cdc326f4b"},{"updated-at":1439568723313,"created-at":1439568723313,"author":{"login":"nickzam","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/89377?v=3"},"body":";; beware of this\n(assoc {} nil nil)\n;;=> {nil nil}","_id":"55ce1353e4b0831e02cddf14"},{"updated-at":1516724671337,"created-at":1516724671337,"author":{"login":"ibercode","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/31028993?v=4"},"body":";;transform a map´s values using reduce and assoc\n\n(defn transform\n [coll]\n (reduce (fn [ncoll [k v]]\n (assoc ncoll k (* 10 v)))\n {}\n coll))\n\n(transform {:a 1 :b 2 :c 3})\n;;{:a 10 :b 20 :c 30}\n","_id":"5a6761bfe4b09621d9f53a75"},{"updated-at":1518707659300,"created-at":1518707659300,"author":{"login":"ibercode","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/31028993?v=4"},"body":";;assoc applied to a vector\n\n(def my-vec [1 2 5 6 8 9])\n\n(assoc my-vec 0 77)\n;;[77 2 5 6 8 9]\n","_id":"5a85a3cbe4b0316c0f44f8bf"},{"updated-at":1535116887042,"created-at":1535116887042,"author":{"login":"eddy147","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1145595?v=4"},"body":";; convert a vector into a set with assoc\n\n(def book-city {:awards [\"Hugo\" \"World Fantasy Award\" \"Arthur C. Clarke Award\"\n \"British Science Fiction Award\"]\n :title \"The City and the City\"\n :authors [{:birth-year 1972, :name \"China Miéville\"}]})\n\n(assoc book-city :authors (set (:authors book-city)))\n\n;; {:awards [\"Hugo\" \"World Fantasy Award\" \"Arthur C. Clarke Award\" \"British Science Fiction Award\"], :title \"The City and the City\", :authors #{{:birth-year 1972, :name \"China Miéville\"}}}","_id":"5b800657e4b00ac801ed9e73"},{"updated-at":1562960552703,"created-at":1562960552703,"author":{"login":"victorb","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/459764?v=4"},"body":";; You can also change multiple keys at once\n\n(def my-map {:name \"Victor\" :age 27 :city \"Barcelona\"})\n\n(assoc my-map :name \"Tom\" :age 47)\n\n;; {:name \"Tom\", :age 47, :city \"Barcelona\"}\n","_id":"5d28e2a8e4b0ca44402ef785"},{"updated-at":1582580850878,"created-at":1582580850878,"author":{"login":"adanhawth","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/36526095?v=4"},"body":";; You can add some more fields (kvs) to your map\n(assoc {:type \"chicken\"} :home \"Kentucky\" :cooking-method \"fried\" :tasty \"definitely\")","_id":"5e544472e4b087629b5a18a6"},{"updated-at":1593400361528,"created-at":1593400361528,"author":{"login":"kimim","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/5523431?v=4"},"body":";; add new key-value from original key value\n(let [contact {:name \"kimim\" :home \"Hangzhou\"}\n new-name \"ivy\"]\n (assoc contact :modified? (not (= (contact :name) new-name)) :name new-name))\n;; {:name \"ivy\" :home \"Hangzhou\" :modified? true}\n","_id":"5ef95c29e4b0b1e3652d7319"}],"notes":[{"updated-at":1352836452000,"body":"Here is a version that will create a vector when the key is numerical.\r\nThis may be useful instead of throwing an IndexOutOfBoundsException.\r\n\r\n
    \r\n(defn assoc-in-idx [m [k & ks] v]\r\n  (let [value (get m k (when (number? (first ks)) []))\r\n\tm (if (and (vector? m) (number? k) (-> m count (< k)))\r\n\t    (reduce (fn [m _] (conj m nil)) m (range (count m) k))\r\n\t    m)\r\n\tv (if ks\r\n\t    (assoc-in-idx value ks v)\r\n\t    v)]\r\n    (assoc m k v)))\r\n
    \r\n","created-at":1352836452000,"author":{"login":"l0st3d","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cc23d1f40d9cfa1c5015ea972759cbf4?r=PG&default=identicon"},"_id":"542692edf6e94c6970521ff4"},{"updated-at":1378937381000,"body":"the API is blurry When applied to a vector\r\n\r\n
    \r\n;; should indicate following\r\n(assoc vector index val) 
    ","created-at":1378937381000,"author":{"login":"simlegate","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/313f9e3c2c4d3492222c1efd2fd955a4?r=PG&default=identicon"},"_id":"542692edf6e94c697052200b"}],"arglists":["map key val","map key val & kvs"],"doc":"assoc[iate]. When applied to a map, returns a new map of the\n same (hashed/sorted) type, that contains the mapping of key(s) to\n val(s). When applied to a vector, returns a new vector that\n contains val at index. Note - index must be <= (count vector).","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/assoc"},{"added":"1.0","ns":"clojure.core","name":"rational?","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1691574246920,"author":{"login":"ferdinand-beyer","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/23474334?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"ratio?","ns":"clojure.core"},"_id":"64d35fe6e4b08cf8563f4bde"},{"created-at":1691574276076,"author":{"login":"ferdinand-beyer","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/23474334?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"decimal?","ns":"clojure.core"},"_id":"64d36004e4b08cf8563f4bdf"}],"line":3638,"examples":[{"author":{"login":"dpritchett","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/147981?v=3"},"editors":[{"login":"dpritchett","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/147981?v=3"},{"login":"dpritchett","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/147981?v=3"},{"login":"dpritchett","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/147981?v=3"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":"user=> (rational? 1)\ntrue\nuser=> (rational? 1.0)\nfalse\nuser=> (class 1.0)\njava.lang.Double\n\n;; Note that decimal? only returns true if n is a BigDecimal.","created-at":1279074804000,"updated-at":1285501218000,"_id":"542692cec026201cdc326dc9"},{"editors":[{"login":"TradeIdeasPhilip","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/18409827?v=3"}],"body":";; Both True\nuser=> (ratio? 22/7) \n;; => true\nuser=> (rational? 22/7)\n;; => true\n\n;; Different\nuser=> (ratio? 22)\n;; => false\nuser=> (rational? 22)\n;; => true\n\n;; Both False\nuser=> (ratio? 0.5)\n;; => false\nuser=> (rational? 0.5)\n;; => false","author":{"avatar-url":"https://avatars.githubusercontent.com/u/18409827?v=3","account-source":"github","login":"TradeIdeasPhilip"},"created-at":1463237386081,"updated-at":1463237705871,"_id":"57373b0ae4b05449374f52ed"}],"notes":null,"arglists":["n"],"doc":"Returns true if n is a rational number","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/rational_q"},{"added":"1.1","ns":"clojure.core","name":"transient","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1286870150000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"persistent!","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521da8"},{"created-at":1286870156000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"conj!","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521da9"},{"created-at":1321399323000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"assoc!","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521daa"},{"created-at":1321399624000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"pop!","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521dab"},{"created-at":1324959569000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"dissoc!","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521dac"},{"created-at":1358908056000,"author":{"login":"jjcomer","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/ef581bba2f97adb539c67a35465b3e1b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"disj!","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521dad"}],"line":3360,"examples":[{"updated-at":1577917667056,"created-at":1286870136000,"body":";; As seen on http://clojure.org/transients\n;; array is initially made transient, modified, then finally made persistent.\n;; See assoc! for further discussion of why it must be done this way.\n;; Also see one example for conj! that contains a detailed example\n;; of a wrong result that can occur if you do not use its return value.\n\n(defn vrange2 [n]\n (loop [i 0 v (transient [])]\n (if (< i n)\n (recur (inc i) (conj! v i))\n (persistent! v))))\n\nuser=> (vrange2 10)\n[0 1 2 3 4 5 6 7 8 9]","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3","account-source":"github","login":"jafingerhut"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon","account-source":"clojuredocs","login":"gstamp"},"_id":"542692cbc026201cdc326bb5"},{"author":{"login":"yasuto","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cacfb7ecf08cb6461767e514c93b7bf9?r=PG&default=identicon"},"editors":[{"login":"yasuto","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cacfb7ecf08cb6461767e514c93b7bf9?r=PG&default=identicon"},{"login":"yasuto","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cacfb7ecf08cb6461767e514c93b7bf9?r=PG&default=identicon"},{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":"user> (def foo (transient [1 2 3]))\n#'user/foo\nuser> (get foo 0)\n1\nuser> (count foo)\n3\nuser> (nth foo 0)\n1\nuser> (def bar (transient {:honda 7 :kagawa 23 :ienaga 14}))\n#'user/bar\nuser> (get bar :kagawa)\n23\nuser> (count bar)\n3\n\n;; There is a known bug in Clojure 1.3 thru 1.6 where contains? always returns\n;; false for transients. http://dev.clojure.org/jira/browse/CLJ-700\n;; contains? works fine for persistent data structures.\nuser> (contains? bar :kagawa) ; Caution! \nfalse\nuser> (def bar2 (persistent! bar))\n#'user/bar2\nuser> (contains? bar2 :kagawa) ; Caution!\ntrue\n","created-at":1307738808000,"updated-at":1417201029755,"_id":"542692cbc026201cdc326bb6"},{"editors":[{"login":"sanel","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/213914?v=4"}],"body":";; transient works only on vectors and maps\n\nuser=> (transient (map inc (range 10)))\n;; ClassCastException clojure.lang.LazySeq cannot be cast to clojure.lang.IEditableCollection\n\nuser=> (transient (range 10))\n;; ClassCastException clojure.lang.LongRange cannot be cast to clojure.lang.IEditableCollection\n\n;; but these will work\n\nuser=> (transient (into [] (map inc (range 10))))\n;; #object[clojure.lang.PersistentVector$TransientVector 0x3ed4e323 \"clojure.lang.PersistentVector$TransientVector@3ed4e323\"]\n\nuser=> (transient (mapv inc (range 10)))\n;; #object[clojure.lang.PersistentVector$TransientVector 0x4d978d5f \"clojure.lang.PersistentVector$TransientVector@4d978d5f\"]\n\nuser=> (transient (into {} (zipmap (range 3) (range 3))))\n;; #object[clojure.lang.PersistentArrayMap$TransientArrayMap 0xa4153b7 \"clojure.lang.PersistentArrayMap$TransientArrayMap@a4153b7\"]\n;; produce {0 0, 1 1, 2 2}\n","author":{"avatar-url":"https://avatars.githubusercontent.com/u/213914?v=4","account-source":"github","login":"sanel"},"created-at":1728579477888,"updated-at":1728595332975,"_id":"6708079569fbcc0c22617503"},{"updated-at":1763816900064,"created-at":1763816269126,"author":{"login":"claj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/353113?v=4"},"body":";; This pattern emerges in serialized php-data, where both associative arrays \n;; (hash-maps) and vectors are serialized in the same way, but vectors only have\n;; ordered positional keys.\n\n;; The fun trick here is to do transient versions of both a hash-map and vector\n;; but then only persist the accumulator we need.\n\n(defn to-map-or-vector [kv-pairs]\n (let [n-keys (count kv-pairs)]\n (loop [[[k v] & rest-of-kv-pairs] kv-pairs \n n 0\n ;; ^^ in reality k and v would be read from \n ;; an input stream, hence the imperative `loop`\n\n only-positional-keys? true\n\n ;; transient hash-map accumulator\n map-acc (transient {})\n ;; transient vector accumulator\n vec-acc (transient [])]\n (if (= n n-keys)\n ;; End case, now only persist the result we need:\n (if only-positional-keys?\n (persistent! vec-acc)\n (persistent! map-acc))\n (recur\n rest-of-kv-pairs\n (inc n)\n\n ;; when (not= n k) once this stays false\n (and only-positional-keys? (= n k))\n\n ;; update both accumulators optimistically\n (assoc! map-acc k v)\n ;; the vector thing could be optimized with the only-positional-keys? \n ;; (but branching also has a cost)\n (conj! vec-acc v))))))\n\n;; a vector\n(to-map-or-vector [[0 :a] [1 :b] [2 :c]]) \n;;=>\n[:a :b :c]\n\n;; a hash-map. Could have be a vector at first glance, but no, it was a map!\n(to-map-or-vector [[0 :a] [:cat :b] [:dog :c]]) \n;;=>\n{0 :a, :cat :b, :dog :c}\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/353113?v=4","account-source":"github","login":"claj"}],"_id":"6921b34d848d032713abce4c"}],"notes":null,"arglists":["coll"],"doc":"Returns a new, transient version of the collection, in constant time.\n\n Transients support a parallel set of 'changing' operations, with similar names\n followed by ! - assoc!, conj! etc. These do the same things as their persistent\n counterparts except the return values are themselves transient.\n\n Note in particular that transients are not designed to be bashed in-place. You\n must capture and use the return value in the next call. In this way, they support\n the same code structure as the functional persistent code they replace.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/transient"},{"added":"1.0","ns":"clojure.core","name":"clojure-version","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1458928229284,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"*clojure-version*","ns":"clojure.core"},"_id":"56f57a65e4b0103e9c7d9d25"}],"line":7229,"examples":[{"author":{"login":"mattdw","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/ee24aacb65359196b0a1bad050f9a62f?r=PG&default=identicon"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":"user=> (clojure-version)\n\"1.2.0-master-SNAPSHOT\"","created-at":1280323117000,"updated-at":1332951038000,"_id":"542692cec026201cdc326da5"}],"notes":null,"arglists":[""],"doc":"Returns clojure version as a printable string.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/clojure-version"},{"ns":"clojure.core","name":"chunk-cons","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1443936300090,"author":{"login":"devn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"chunk-buffer","ns":"clojure.core"},"_id":"5610b82ce4b0686557fcbd4e"},{"created-at":1443936308702,"author":{"login":"devn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"chunk","ns":"clojure.core"},"_id":"5610b834e4b08e404b6c1c9c"},{"created-at":1443936314187,"author":{"login":"devn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"chunk-append","ns":"clojure.core"},"_id":"5610b83ae4b08e404b6c1c9d"},{"created-at":1443936320194,"author":{"login":"devn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"chunk-rest","ns":"clojure.core"},"_id":"5610b840e4b08e404b6c1c9e"},{"created-at":1443936325789,"author":{"login":"devn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"chunk-next","ns":"clojure.core"},"_id":"5610b845e4b08e404b6c1c9f"},{"created-at":1443936329931,"author":{"login":"devn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"chunk-first","ns":"clojure.core"},"_id":"5610b849e4b08e404b6c1ca0"}],"line":712,"examples":[{"editors":[{"login":"devn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3"}],"body":"(let [chunked-cons (-> (chunk-buffer 32)\n (chunk)\n (chunk-cons (seq (range 42))))]\n\n chunked-cons\n ;; => (0 1 2 3 4 5 6 7 8 9 10\n ;; 11 12 13 14 15 16 17 18\n ;; 19 20 21 22 23 24 25 26\n ;; 27 28 29 30 31 32 33 34\n ;; 35 36 37 38 39 40 41)\n\n (class chunked-cons)\n ;; => clojure.lang.ChunkedCons\n\n)","author":{"avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3","account-source":"github","login":"devn"},"created-at":1443936277294,"updated-at":1443936290379,"_id":"5610b815e4b08e404b6c1c9b"},{"editors":[{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"}],"body":";; byte-seq creates a lazy chunked sequence of bytes from an InputStream.\n;; It takes the optimal chunk \"size\" to model a physical resource \n;; (for a disk this would be the block size).\n\n(import '[java.io FileInputStream InputStream])\n\n(defn byte-seq [^InputStream is size]\n (let [ib (byte-array size)]\n ((fn step []\n (lazy-seq\n (let [n (.read is ib)]\n (when (not= -1 n)\n (let [cb (chunk-buffer size)]\n (dotimes [i size] (chunk-append cb (aget ib i)))\n (chunk-cons (chunk cb) (step))))))))))\n\n;; Example with a text file and block size 4096.\n(with-open [is (FileInputStream. \"/usr/share/dict/words\")]\n (let [bs (byte-seq is 4096)]\n (String. (byte-array (take 20 bs)))))\n;; \"A\\na\\naa\\naal\\naalii\\naam\"","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"},"created-at":1522963811986,"updated-at":1522966589373,"_id":"5ac69563e4b045c27b7fac37"}],"notes":null,"arglists":["chunk rest"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core/chunk-cons"},{"added":"1.0","ns":"clojure.core","name":"comparator","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1668766070221,"author":{"login":"holyjak","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/624958?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"compare","ns":"clojure.core"},"_id":"63775976e4b0b1e3652d7685"}],"line":3102,"examples":[{"author":{"login":"shockbob","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon"},"editors":[{"login":"Chouser","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/7a0192050ed6488670acfd3f59405c10?r=PG&default=identicon"}],"body":";; simple example to create an ArrayList, initially [1,2,0]\n;; and sort it in descending order\n\nuser=> (def a (new java.util.ArrayList [1 2 0]))\n#'user/a\nuser=> (def compx (comparator (fn [x y] (> x y))))\n#'user/compx\nuser=> (java.util.Collections/sort a compx)\nnil\nuser=> a\n#\n\n;; Note however that 'comparator' is rarely (never?) needed because if\n;; the fn returns a boolean, the .compare implementation Clojure provides\n;; causes it to behave the same as if 'comparator' were wrapped around it:\n\n(sort (comparator (fn [x y] (> x y))) [1 2 0]) ;=> (2 1 0)\n(sort (fn [x y] (> x y)) [1 2 0]) ;=> (2 1 0)\n(sort > [1 2 0]) ;=> (2 1 0)\n(sort < [1 2 0]) ;=> (0 1 2)","created-at":1313490576000,"updated-at":1345156531000,"_id":"542692cdc026201cdc326cfd"}],"notes":null,"arglists":["pred"],"doc":"Returns an implementation of java.util.Comparator based upon pred.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/comparator"},{"added":"1.0","ns":"clojure.core","name":"sorted-map","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1281961873000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"sorted-map-by","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cbd"},{"created-at":1330671636000,"author":{"login":"Chouser","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/7a0192050ed6488670acfd3f59405c10?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"subseq","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cbe"},{"created-at":1330671641000,"author":{"login":"Chouser","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/7a0192050ed6488670acfd3f59405c10?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"rsubseq","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cbf"},{"created-at":1330671776000,"author":{"login":"Chouser","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/7a0192050ed6488670acfd3f59405c10?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"sorted-set","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cc0"},{"created-at":1397669012000,"author":{"login":"ryo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3f7913b563c72083c74030d928ba407e?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"array-map","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cc1"},{"created-at":1397669018000,"author":{"login":"ryo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3f7913b563c72083c74030d928ba407e?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"hash-map","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cc2"},{"created-at":1494705692726,"author":{"login":"miner","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/25400?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"sorted?","ns":"clojure.core"},"_id":"5917661ce4b01920063ee05b"},{"created-at":1548549104189,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/109629?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"compare","ns":"clojure.core"},"_id":"5c4cfbf0e4b0ca44402ef644"}],"line":400,"examples":[{"updated-at":1711017078763,"created-at":1280746350000,"body":";; Sorted maps are sorted by their keys, not their values.\n\nuser=> (sorted-map :z 0, :a 28, :b 35)\n{:a 28, :b 35, :z 0}\nuser=> (into (sorted-map) {:a 2 :b 1})\n{:a 2, :b 1}\n\n;; (sorted-map ...) is equivalent in behavior to (sorted-map-by compare ...)\n;; where compare is Clojure's default comparator function clojure.core/compare\n\n;; For a map sorted by values, see the priority-map data structure:\n;; https://github.com/clojure/data.priority-map\n\n;; For a map sorted by the order that key/value pairs were added,\n;; see array-map\n\n;; Another sorted map variant is the ordering-map:\n;; https://github.com/clj-commons/useful/blob/dc5cdebf8983a2e2ea24ec8951fbb4dfb037da45/src/flatland/useful/map.clj#L243-L245\n\n;; If you deal with many large maps where the keys are all integers, and\n;; want a faster data structure for those, see int-map:\n;; https://github.com/clojure/data.int-map","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3","account-source":"github","login":"jafingerhut"},{"avatar-url":"https://www.gravatar.com/avatar/92625b8a6be91bb8c688d0d07b4e2a32?r=PG&default=identicon","account-source":"clojuredocs","login":"clojureking"},{"avatar-url":"https://www.gravatar.com/avatar/92625b8a6be91bb8c688d0d07b4e2a32?r=PG&default=identicon","account-source":"clojuredocs","login":"clojureking"},{"avatar-url":"https://www.gravatar.com/avatar/92625b8a6be91bb8c688d0d07b4e2a32?r=PG&default=identicon","account-source":"clojuredocs","login":"clojureking"},{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3","account-source":"github","login":"phreed"},{"login":"delonnewman","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/10404?v=4"},{"avatar-url":"https://avatars1.githubusercontent.com/u/7503672?v=4","account-source":"github","login":"olfal"},{"login":"iGEL","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/36442?v=4"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon","account-source":"clojuredocs","login":"gstamp"},"_id":"542692c6c026201cdc3268c0"},{"body":"; 'seq' can be used to turn a map into a list of vectors\n; notice how the list is built in the sorted order as with vectors.\n(seq (into (sorted-map) {:key1 \"value1\" :key2 \"value2\"}))\n;;=> ([:key1 \"value1\"] [:key2 \"value2\"])","author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"},"created-at":1422039046100,"updated-at":1426562359420,"editors":[{"login":"InSuperposition","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/433871?v=3"}],"_id":"54c29806e4b081e022073c28"},{"updated-at":1548623900767,"created-at":1446961734028,"author":{"login":"chrismurrph","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10278575?v=3"},"body":"; sorting on integer keys\n; also notice how each pair becomes a `MapEntry` ('key' 'val')\n(into (sorted-map) [[23 :x] [17 :y]])\n;;=> {17 :y, 23 :x}","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/10278575?v=3","account-source":"github","login":"chrismurrph"},{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/109629?v=4"}],"_id":"563ee246e4b04b157a6648e7"},{"updated-at":1494705953587,"created-at":1457752219009,"author":{"login":"fasiha","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/37649?v=3"},"body":";; clojure doesn't have a `sorted-map?` function to distinguish a sorted-map\n;; from a regular map. use `instance?`:\n(def unremarkable-map {:k1 \"v1\" :k2 \"v2\"})\n(def very-remarkable-map (into (sorted-map) unremarkable-map))\n(instance? clojure.lang.PersistentTreeMap unremarkable-map)\n;;=> false\n(instance? clojure.lang.PersistentTreeMap very-remarkable-map)\n;;=> true\n\n;; This works because:\n(type unremarkable-map)\n;;=> clojure.lang.PersistentArrayMap (PersistentHashMap if many key-val-pairs)\n(type very-remarkable-map)\n;;=> clojure.lang.PersistentTreeMap\n\n;; Clojure does have a `sorted?` predicate so you could define `sorted-map?`\n(def sorted-map? (every-pred map? sorted?))\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/37649?v=3","account-source":"github","login":"fasiha"},{"login":"miner","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/25400?v=3"}],"_id":"56e3889be4b0ce130120e038"},{"updated-at":1564573338675,"created-at":1564573338675,"author":{"login":"ertugrulcetin","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/8271291?v=4"},"body":";; Sort hash map by it's keys\n(def data {\"k\" 11 \"z\" 12 \"a\" 13 \"d\" 14 })\n\n(into (sorted-map) (sort-by first (seq data)))\n\n;;=> {\"a\" 13, \"d\" 14, \"k\" 11, \"z\" 12}","_id":"5d417e9ae4b0ca44402ef790"},{"updated-at":1610531070746,"created-at":1610531070746,"author":{"login":"dupuchba","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/911705?v=4"},"body":";; (from previous comment) clojure doesn't have a `sorted-map?` function to distinguish a sorted-map\n;; from a regular map. use `instance?`:\n\n;;You can indeed check if the sorted-map is an instance of a clojure.lang.PersistentTreeMap but it won't work for cljs/cljc code.\n\n;; +1 for the use of `map?` and `sorted?` \n\n(and (sorted? m) (map? m))","_id":"5ffec0fee4b0b1e3652d742f"},{"updated-at":1665400786595,"created-at":1665400754728,"author":{"login":"CapableWeb","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/112625454?v=4"},"body":";; In ClojureScript, no exception gets thrown if you pass it a map\n;; rather than keyvals, leading to potentially unexpected data\n\n;; In Clojure (1.11.1):\n\n(sorted-map {:b 1 :a 2})\n\n;; Execution error (IllegalArgumentException) at user/eval1 (REPL:1).\n;; No value supplied for key: {:b 1, :a 2}\n\n;; In ClojureScript (1.8.40):\n\n(sorted-map {:b 1 :a 2})\n\n;; => {{:b 1, :a 2} nil}\n\n;; ^ is a sorted map, containing the passed in map as the key, with nil as the value\n\n;; What you probably want instead, as illustrated by the other examples:\n\n(into (sorted-map) {:b 1 :a 2})\n\n;; => {:a 2, :b 1}","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/112625454?v=4","account-source":"github","login":"CapableWeb"}],"_id":"6343ffb2e4b0b1e3652d7674"},{"updated-at":1685115685170,"created-at":1685115685170,"author":{"login":"hoodr","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/15623686?v=4"},"body":";; sorted-map requires that all keys are of the same type, otherwise the default\n;; clojure compare will throw a ClassCastException when attempt to get/insert\n\n(sorted-map :b \"bar\" :a \"foo\")\n;;=> {:a \"foo\" :b \"bar\"}\n\n(sorted-map \"b\" \"bar\" :a \"foo\")\n;;=> Execution error (ClassCastException) at user/eval1 (REPL:1).\n;;=> class java.lang.String cannot be cast to class clojure.lang.Keyword\n\n;; In addition, if you attempt to access keys of a different type from those\n;; that exist in the sorted-map you'll also get a ClassCastException from the\n;; default compare fn\n\n(def m (sorted-map :b \"bar\" :a \"foo\"))\n\n(get m :a) ;;=> \"foo\"\n\n(get m :b) ;;=> \"bar\"\n\n(get m \"a\")\n;;=> Execution error (ClassCastException) at user/eval1 (REPL:1).\n;; class java.lang.String cannot be cast to class clojure.lang.Keyword\n\n;; If you find yourself in a situation where you cannot guarantee the type of\n;; the key to lookup, you will need to write a custom compare fn and use\n;; sorted-map-by to have the same behavior as PersistentArrayMap and avoid an\n;; exception being thrown.\n\n(def p (sorted-map-by (fn [a b] (try (compare a b) (catch Exception _ 1)))\n :b \"bar\"\n :a \"foo\"))\n\n(get p :a) ;;=> \"foo\"\n\n(get p \"a\") ;;=> nil","_id":"6470d325e4b08cf8563f4bbe"}],"notes":[{"body":"If transient operations are needed for sorted-map, use [data.avl](https://github.com/clojure/data.avl) instead of this built-in one.","created-at":1648838946843,"updated-at":1648838981619,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/889685?v=4","account-source":"github","login":"huahaiy"},"_id":"62474922e4b0b1e3652d75c6"}],"arglists":["& keyvals"],"doc":"keyval => key val\n Returns a new sorted map with supplied mappings. If any keys are\n equal, they are handled as if by repeated uses of assoc.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/sorted-map"},{"added":"1.0","ns":"clojure.core","name":"send","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1282635091000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"shutdown-agents","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d0a"},{"created-at":1282635102000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"send-off","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d0b"},{"created-at":1282635125000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"agent","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d0c"}],"line":2128,"examples":[{"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":"user=> (def my-agent (agent 100))\n#'user/my-agent\nuser=> @my-agent\n100\n\n;; Note the following happens asynchronously in a thread\n;; pool\nuser=> (send my-agent + 100)\n#\n\n;; Assuming the addition has completed the value will\n;; now be updated when we look at it.\nuser=> @my-agent\n200","created-at":1282635077000,"updated-at":1332951644000,"_id":"542692cbc026201cdc326bf5"},{"updated-at":1508861291847,"created-at":1508861291847,"author":{"login":"elect000","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/18697629?v=4"},"body":";; update agent value\nuser => (def foo (agent 100)) \n#'user/my-agent\nuser => @foo\n100\n\n;; function get \"old value\"\nuser => (send foo (fn [old-foo] \n (println old-foo \"foo will change\")\n (+ old-foo 100)))\n100 foo will change\n#agent[{:status :ready, :val 200} 0x000000]\n\nuser => @foo\n200","_id":"59ef656be4b0a08026c48c74"}],"notes":[{"body":"See \"send-off\" for the differences between \"send\" and \"send-off\".","created-at":1417371874620,"updated-at":1417371874620,"author":{"login":"fordsfords","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7671908?v=3"},"_id":"547b60e2e4b03d20a10242ba"}],"arglists":["a f & args"],"doc":"Dispatch an action to an agent. Returns the agent immediately.\n Subsequently, in a thread from a thread pool, the state of the agent\n will be set to the value of:\n\n (apply action-fn state-of-agent args)","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/send"},{"added":"1.0","ns":"clojure.core","name":"drop-while","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1301365967000,"author":{"login":"pauldoo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5cb916d3c8abc9f45a093209e72489fb?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"take-while","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e46"},{"created-at":1347077852000,"author":{"login":"dansalmo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e33ee460f5f61bc5ba9b598934766215?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"split-with","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e47"},{"created-at":1473454505566,"author":{"login":"huahaiy","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/889685?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"some","ns":"clojure.core"},"_id":"57d321a9e4b0709b524f04f3"}],"line":2975,"examples":[{"updated-at":1331882398000,"created-at":1279378804000,"body":";; Note: Documentation should be \"starting from the first item for which\n;; (pred item) returns logical false, i.e. either of the values false or nil.\n\nuser=> (drop-while neg? [-1 -2 -6 -7 1 2 3 4 -5 -6 0 1])\n(1 2 3 4 -5 -6 0 1)\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3","account-source":"github","login":"jafingerhut"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/142529?v=3","account-source":"github","login":"nipra"},"_id":"542692cfc026201cdc326e45"},{"updated-at":1518209200339,"created-at":1518209200339,"author":{"login":"ibercode","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/31028993?v=4"},"body":"(def my-vec [1 2 3 4 5 6])\n\n(drop-while #(> 3 %) my-vec)\n;;(3 4 5 6)\n\n(drop-while #(>= 3 %) my-vec)\n;;(4 5 6)\n\n;;Returns a lazy sequence of the items in coll starting from the\n;;first item for which (pred item) returns logical FALSE","_id":"5a7e08b0e4b0316c0f44f8b3"}],"notes":[{"updated-at":1280202567000,"body":"The description of this function is throwing me off. I think it should say: returns a sequence of items from `coll` dropping the initial items that evaluate to true when passed to `pred`, once a non-true value is encountered, the rest of the list is returned.","created-at":1280202567000,"author":{"login":"Jacolyte","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1703a0c3ed358b787f4b1bf3b2799472?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521f8c"}],"arglists":["pred","pred coll"],"doc":"Returns a lazy sequence of the items in coll starting from the\n first item for which (pred item) returns logical false. Returns a\n stateful transducer when no collection is provided.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/drop-while"},{"ns":"clojure.core","name":"proxy-call-with-super","file":"clojure/core_proxy.clj","type":"function","column":1,"see-alsos":null,"line":389,"examples":null,"notes":null,"arglists":["call this meth"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core/proxy-call-with-super"},{"added":"1.3","ns":"clojure.core","name":"realized?","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1334256253000,"author":{"login":"tcrawley","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9262893211442b0081f2bcd75bfd47f3?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"promise","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c53"},{"created-at":1334256260000,"author":{"login":"tcrawley","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9262893211442b0081f2bcd75bfd47f3?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"delay","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c54"},{"created-at":1334256266000,"author":{"login":"tcrawley","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9262893211442b0081f2bcd75bfd47f3?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"future","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c55"}],"line":7725,"examples":[{"author":{"login":"neotyk","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/366ff985977b3aab09510bc335cd44a4?r=PG&default=identicon"},"editors":[],"body":";; Create a promise\nuser> (def p (promise))\n#'user/p ; p is our promise\n\n;; Check if was delivered/realized\nuser> (realized? p)\nfalse ; No yet\n\n;; Delivering the promise\nuser> (deliver p 42)\n#\n\n;; Check again if it was delivered\nuser> (realized? p)\ntrue ; Yes!\n\n;; Deref to see what has been delivered\nuser> @p\n42\n\n;; Note that @ is shorthand for deref\nuser> (deref p)\n42","created-at":1329847539000,"updated-at":1329847539000,"_id":"542692d5c026201cdc327063"},{"body":";; For lazy sequences\n\nuser=> (def r (range 5))\n#'user/r\nuser=> (realized? r)\nfalse\nuser=> (first r)\n0\nuser=> (realized? r)\ntrue\n\n; As of Clojure 1.7.0 range may return things other than a LazySeq.\n; see https://groups.google.com/forum/#!topic/clojure/NFwHkZxUFuY\n; and another example here.\n\nuser=> (def r (lazy-seq (range 5)))\n#'user/r\nuser=> (realized? r)\nfalse\nuser=> (first r)\n0\nuser=> (realized? r)\ntrue","author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"created-at":1423041981596,"updated-at":1646323852599,"editors":[{"avatar-url":"https://avatars1.githubusercontent.com/u/6127708?v=3","account-source":"github","login":"mhuerster"},{"login":"mars0i","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1836941?v=4"}],"_id":"54d1e5bde4b081e022073c56"},{"updated-at":1609789065763,"created-at":1609789065763,"author":{"login":"timrobinson33","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/57178390?v=4"},"body":";; Note that for delay (but not future), if the body is currently executing\n;; realized? will block until it completes.","_id":"5ff36e89e4b0b1e3652d7427"},{"editors":[{"login":"mars0i","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1836941?v=4"}],"body":";; realized? does not work with all lazy sequences (since Clojure 1.7.0),\n;; and some functions that return lazy sequences might not always return\n;; a sequence to which realized? is applicable.\n\n;; realized? works with a bare call to range:\nuser=> (realized? (range))\ntrue\nuser=> (realized? (rest (range)))\nfalse\n;; but not when range is given an argument:\nuser=> (realized? (range 10000))\nExecution error (ClassCastException) at user/eval2036 (form-init1890379966749060098.clj:1).\nclojure.lang.LongRange cannot be cast to clojure.lang.IPending\n\n;; The reason is that range returns instances of different classes:\nuser=> (class (range))\nclojure.lang.Iterate\nuser=> (class (range 10000))\nclojure.lang.LongRange\n\n;; repeat is another example:\nuser=> (realized? (repeat 10000))\nExecution error (ClassCastException) at user/eval5991 (form-init1890379966749060098.clj:1).\nclojure.lang.Repeat cannot be cast to clojure.lang.IPending\nuser=> (class (repeat 10000))\nclojure.lang.Repeat\n\n;; All of the sequences returned above behave lazily, however.\n\n;; The upshot is that realized? is not considered an important tool for use\n;; with lazy sequences and probably shouldn't be depended on, except in \n;; special cases.\n\n;; As noted in another example, there's an old discussion here:\n;; https://groups.google.com/forum/#!topic/clojure/NFwHkZxUFu","author":{"avatar-url":"https://avatars.githubusercontent.com/u/1836941?v=4","account-source":"github","login":"mars0i"},"created-at":1646325203994,"updated-at":1646325368517,"_id":"6220edd3e4b0b1e3652d75b1"}],"notes":null,"arglists":["x"],"doc":"Returns true if a value has been produced for a promise, delay, future or lazy sequence.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/realized_q"},{"added":"1.1","ns":"clojure.core","name":"char-array","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1293675171000,"author":{"login":"dakrone","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bcacd00a7f05c4772329cf9f446c7987?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"into-array","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bd9"},{"created-at":1293675177000,"author":{"login":"dakrone","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bcacd00a7f05c4772329cf9f446c7987?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"to-array","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bda"},{"to-var":{"library-url":"https://github.com/clojure/clojure","name":"chars","ns":"clojure.core"},"author":{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},"created-at":1342917444000,"_id":"542692eaf6e94c6970521bdb"}],"line":5354,"examples":[{"author":{"login":"dakrone","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bcacd00a7f05c4772329cf9f446c7987?r=PG&default=identicon"},"editors":[],"body":"user> (char-array \"asdf\")\n#\n\nuser> (seq (char-array \"asdf\"))\n(\\a \\s \\d \\f)\n\nuser> (seq (char-array 10))\n(\\^@ \\^@ \\^@ \\^@ \\^@ \\^@ \\^@ \\^@ \\^@ \\^@)","created-at":1293675165000,"updated-at":1293675165000,"_id":"542692c7c026201cdc32698c"},{"updated-at":1563833139082,"created-at":1563833139082,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"body":";; `slurp` is polymorphic and supports many types. Sometimes you \n;; need to `slurp` a generic argument that could be already a string\n;; (perhaps it was loaded somewhere else). Use `char-array` to convert\n;; the string into a format suitable for `slurp`:\n\n(defn fetch [x]\n (slurp (if (string? x) (char-array x) x)))\n \n(take 10 (fetch \"http://clojure.org\"))\n;;(\\h \\t \\t \\p \\: \\/ \\/ \\c \\l \\o)\n(take 10 (fetch \"Also loading from a string\"))\n;; (\\A \\l \\s \\o \\space \\l \\o \\a \\d \\i)","_id":"5d363333e4b0ca44402ef78a"}],"notes":null,"arglists":["size-or-seq","size init-val-or-seq"],"doc":"Creates an array of chars","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/char-array"},{"added":"1.0","ns":"clojure.core","name":"resolve","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1289660999000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"ns-resolve","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c5e"},{"created-at":1450428036535,"author":{"login":"blx","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/887504?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"symbol","ns":"clojure.core"},"_id":"5673c684e4b09a2675a0ba7a"},{"created-at":1571179430280,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"deref","ns":"clojure.core"},"_id":"5da64ba6e4b0ca44402ef7ce"},{"created-at":1654081047171,"author":{"login":"PEZ","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/30010?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"requiring-resolve","ns":"clojure.core"},"_id":"62974617e4b0b1e3652d75f5"}],"line":4398,"examples":[{"author":{"login":"jonase","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5e0b0bd287633db6fccf32a2aa5efd42?r=PG&default=identicon"},"editors":[{"login":"jonase","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5e0b0bd287633db6fccf32a2aa5efd42?r=PG&default=identicon"},{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":"user=> ((-> \"first\" symbol resolve) [1 2 3])\n1","created-at":1280971203000,"updated-at":1332950641000,"_id":"542692cdc026201cdc326cde"},{"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"editors":[],"body":";; See also http://clojure.org/namespaces for information on namespaces in Clojure and how to inspect and manipulate them","created-at":1348479395000,"updated-at":1348479395000,"_id":"542692d5c026201cdc327074"},{"body":"user=> (resolve 'x)\nnil\nuser=> (def x 1)\n#'user/x\nuser=> (resolve 'x)\n#'user/x\n\nuser=> (resolve 'join)\nnil\nuser=> (use '[clojure.string :only [join]])\nnil\nuser=> (resolve 'join)\n#'clojure.string/join\n\nuser=> (join \", \" [\"a\" \"b\"])\n\"a, b\"\nuser=> ((resolve 'join) \", \" [\"a\" \"b\"])\n\"a, b\"","author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"created-at":1423094803389,"updated-at":1423094803389,"_id":"54d2b413e4b081e022073c61"},{"updated-at":1533277711352,"created-at":1533277711352,"author":{"login":"philoskim","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/5637280?v=4"},"body":"user=> (resolve 'Exception)\njava.lang.Exception\n\nuser=> (type (resolve 'Exception))\njava.lang.Class\n","_id":"5b63f60fe4b00ac801ed9e46"},{"updated-at":1545993870224,"created-at":1545992641368,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"body":";; Also resolve Array classes\n(resolve (symbol \"[I\"))\n;; [I","editors":[{"avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"}],"_id":"5c25f9c1e4b0ca44402ef5f9"},{"updated-at":1545994118006,"created-at":1545994118006,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"body":";; Also takes a set/map of symbols to ignore while resolving.\n\n(defn replace-var [name value]\n (let [protected #{'+ '- '* '/}]\n (when (resolve protected name)\n (intern *ns* name value))))\n\n(replace-var 'first last)\n(first [1 2 3 4])\n;; 4\n\n;; plus is protected.\n(replace-var '+ -)\n(+ 1 1)\n;; 2","_id":"5c25ff86e4b0ca44402ef5fe"},{"updated-at":1645559019391,"created-at":1645559019391,"author":{"login":"tekacs","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/63247?v=4"},"body":";; Also works fine on namespaced symbols\n\n;; some-ns\n(def x 1)\n\n;; other-ns\n@(resolve 'some-ns/x)\n;; 1","_id":"62153cebe4b0b1e3652d75ad"},{"updated-at":1709237287007,"created-at":1709180143805,"author":{"login":"onionpancakes","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/639985?v=4"},"body":";; (resolve env sym) can be used to detect what\n;; the user is referring to at macro time.\n\n;; The implied macro arg &env contains local bindings\n;; of symbols when the macro is called. Resolve checks\n;; if the symbol is contained within env. If (contains? env sym)\n;; is true, resolve returns nil, meaning the symbol not referring\n;; to anything globally, but rather to a local binding.\n\n;; See (source ns-resolve). It's literally just a when check on the env arg.\n\n;; Essentially, it boils down to four cases with (resolve env sym):\n;; 1. Resolve returning a var. User is referring to a global var.\n;; 2. Resolve returning a class. User is referring to global class.\n;; 3. Resolve returning nil, and sym is contained in &env.\n;; User is referring to something local.\n;; 4. Resolve returning nil, and sym is not contained in &env.\n;; It's an unresolvable symbol.\n\n;; The &env map can be further examined to see what exactly the\n;; local binding is, but bewarned that this is entering Clojure\n;; compiler territory.\n\n(defmacro check-call\n \"Checks if valid function call.\"\n [[sym & _ :as this]]\n (if (and (seq? this) (symbol? sym))\n (if-some [v (resolve &env sym)] ; Resolve with &env\n (if (var? v)\n (println \"Calling function on var:\" v)\n (println \"Cannot call class as function:\" v))\n (if (contains? &env sym)\n (println \"Calling function on local binding:\" sym)\n (println \"Cannot call unresolvable symbol as function:\" sym)))\n (println \"Not function call.\")))\n\n(check-call (map inc (range 10)))\n\n;; => Calling function on var: #'clojure.core/map\n\n(check-call (java.util.Map))\n\n;; => Cannot call class as function: java.util.Map\n\n(let [map (fn [arg] (str \"shadowed map \" arg))]\n (check-call (map \"foo\"))) ; Calling the shadowed map, not clojure.core/map!\n\n;; => Calling function on local binding: map\n\n(check-call (foobar))\n\n;; => Cannot call unresolvable symbol as function: foobar\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/639985?v=4","account-source":"github","login":"onionpancakes"}],"_id":"65e004ef69fbcc0c226174aa"}],"notes":null,"arglists":["sym","env sym"],"doc":"same as (ns-resolve *ns* symbol) or (ns-resolve *ns* &env symbol)","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/resolve"},{"added":"1.0","ns":"clojure.core","name":"compare","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1361334293000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"sort-by","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e7f"},{"created-at":1361334307000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"sorted-set-by","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e80"},{"created-at":1361334315000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"sorted-map-by","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e81"},{"created-at":1548959861545,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/109629?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"==","ns":"clojure.core"},"_id":"5c534075e4b0ca44402ef660"}],"line":833,"examples":[{"updated-at":1450882235668,"created-at":1313565230000,"body":";; various examples\n;; comparing vectors of different sizes does not work as you may expect\n;; the longer vector is always \"greater\" regardless of contents \n\nuser=> (compare [0 1 2] [0 1 2])\n0\nuser=> (compare [1 2 3] [0 1 2 3])\n-1\nuser=> (compare [0 1 2] [3 4])\n1\nuser=> (compare nil [1 2 3])\n-1\nuser=> (compare [1 2 3] nil)\n1\nuser=> (compare [2 11] [99 1])\n-1\nuser=> (compare \"abc\" \"def\")\n-3\nuser=> (compare \"abc\" \"abd\")\n-1","editors":[{"avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon","account-source":"clojuredocs","login":"shockbob"},{"avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon","account-source":"clojuredocs","login":"shockbob"},{"login":"liango2","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/5696817?v=3"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon","account-source":"clojuredocs","login":"shockbob"},"_id":"542692ccc026201cdc326cc6"},{"editors":[{"login":"nwallace","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1614172?v=3"}],"body":";; number comparisons give results of either 1, 0 or -1\n(compare 1 0) ;; => 1\n(compare 1 1) ;; => 0\n(compare 1 2) ;; => -1\n(compare 1 3) ;; => -1\n\n;; string comparisons give results of the distance between the first characters\n(compare \"B\" \"A\") ;; => 1\n(compare \"B\" \"B\") ;; => 0\n(compare \"B\" \"C\") ;; => -1\n(compare \"AA\" \"ZZ\") ;; => -25\n","author":{"avatar-url":"https://avatars.githubusercontent.com/u/1614172?v=3","account-source":"github","login":"nwallace"},"created-at":1458443574384,"updated-at":1458443996870,"_id":"56ee1536e4b09295d75dbf2e"},{"updated-at":1490657533575,"created-at":1490657533575,"author":{"login":"ercliou","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/6700692?v=3"},"body":"(compare true false)\n;;=> 1\n(compare false true)\n;;=> -1\n(compare true true)\n;;=> 0\n(compare false false)\n;;=> 0","_id":"58d9a0fde4b01f4add58fe79"},{"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/109629?v=4"}],"body":";; `compare` is the default comparator for sorting with `sort` and\n;; `sort-by`, for ordering the elements of a `sorted-set`, and for\n;; ordering the keys of a `sorted-map`.\n\n;; See https://clojure.org/guides/comparators for advice on writing\n;; your own custom comparators.\n\n;; As for all 3-way comparators, compare takes two arguments `x` and\n;; `y`. It returns an int (i.e. a Java 32-bit Integer) that is\n;; negative if `x` should come before `y`, positive if `x` should come\n;; after `y`, or 0 if they are equal.\n\n;; `compare` works for many types of values, ordering values as\n;; follows.\n\n;; Numbers are sorted in increasing numeric order, returning 0 if two\n;; numbers are numerically equal by `==`, even if `=` returns false\n\nuser=> (sort [22/7 2.71828 ##-Inf 1 55 3N])\n(##-Inf 1 2.71828 3N 22/7 55)\n\n;; Regular sets use `=` for detecting duplicates, so all of the\n;; numbers in this example are considered distinct elements. Numbers\n;; in different \"categories\" (integer & ratio, floating point,\n;; BigDecimal) are never `=` to each other.\nuser=> (set [1.5 1.5M 3/2])\n#{1.5 3/2 1.5M}\n\n;; Sorted sets use `compare` for detecting duplicates, which is more\n;; like `==` for determining when numbers have the same numeric value\n;; regardless of \"category\", so all of the numbers in this example are\n;; considered equal. Thus only the first one is added.\nuser=> (sorted-set 1.5 1.5M 3/2)\n#{1.5}\n\n;; An oddity: (compare ##NaN x) and (compare x ##NaN) returns 0 (equal) for any\n;; number x, including ##NaN, but (== ##NaN x) and (== x ##NaN) returns false\n\nuser=> (== 1 ##NaN)\nfalse\nuser=> (compare 1 ##NaN)\n0\nuser=> (== ##NaN ##NaN)\nfalse\nuser=> (compare ##NaN ##NaN)\n0","author":{"avatar-url":"https://avatars2.githubusercontent.com/u/109629?v=4","account-source":"github","login":"jafingerhut"},"created-at":1548617891609,"updated-at":1548789812583,"_id":"5c4e08a3e4b0ca44402ef647"},{"updated-at":1548617914105,"created-at":1548617914105,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/109629?v=4"},"body":";; Strings are sorted in lexicographic order, aka dictionary order\n;; (http://en.wikipedia.org/wiki/Lexicographical_order) by their\n;; representation as sequences of UTF-16 code units. This is\n;; alphabetical order (case-sensitive) for strings restricted to the\n;; ASCII subset. See Java documentation of String's `compareTo`\n;; method for additional details on `String` comparison.\n;; https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#compareTo-java.lang.String-\n\nuser=> (sorted-set \"aardvark\" \"boo\" \"a\" \"Antelope\" \"bar\")\n#{\"Antelope\" \"a\" \"aardvark\" \"bar\" \"boo\"}\n\n;; Symbols are sorted by their representation as strings, sorting\n;; first by their namespace name, and if they are in the same\n;; namespace, then by their name. If no namespace is included, those\n;; symbols will be sorted before any symbol with a namespace.\nuser=> (sorted-set 'user/foo 'clojure.core/pprint 'bar\n 'clojure.core/apply 'user/zz)\n#{bar clojure.core/apply clojure.core/pprint user/foo user/zz}\n\n;; Keywords are sorted similarly to symbols.\nuser=> (sorted-map :map-key 10, :amp [3 2 1], :blammo \"kaboom\")\n{:amp [3 2 1], :blammo \"kaboom\", :map-key 10}","_id":"5c4e08bae4b0ca44402ef648"},{"updated-at":1548617930499,"created-at":1548617930499,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/109629?v=4"},"body":";; Vectors are sorted by their length first, from shortest to longest,\n;; then lexicographically among equal-length vectors.\n\nuser=> (sort [[-8 2 5] [-5 -1 20] [1 2] [1 -5] [10000]])\n([10000] [1 -5] [1 2] [-8 2 5] [-5 -1 20])","_id":"5c4e08cae4b0ca44402ef649"},{"updated-at":1548791137396,"created-at":1548617944751,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/109629?v=4"},"body":";; All Java types implementing the `Comparable` interface such as\n;; characters, booleans, `File`, `URI`, and `UUID` are compared via\n;; their `compareTo` methods.\n;; https://docs.oracle.com/javase/8/docs/api/java/lang/Comparable.html\n\nuser=> (import '(java.util UUID))\njava.util.UUID\nuser=> (def u1 (UUID. 5 10))\n#'user/u1\nuser=> (def u2 (UUID. 5 17))\n#'user/u2\nuser=> (def u3 (UUID. 10 0))\n#'user/u3\nuser=> u1\n#uuid \"00000000-0000-0005-0000-00000000000a\"\nuser=> u2\n#uuid \"00000000-0000-0005-0000-000000000011\"\nuser=> u3\n#uuid \"00000000-0000-000a-0000-000000000000\"\n\nuser=> (sort [u3 u2 u1])\n(#uuid \"00000000-0000-0005-0000-00000000000a\"\n #uuid \"00000000-0000-0005-0000-000000000011\"\n #uuid \"00000000-0000-000a-0000-000000000000\")\n\n;; `nil` can be compared to all values above, and is considered less\n;; than anything else.\n\nuser=> (sort [:ns2/kw1 :ns2/kw2 :ns1/kw2 :kw2 nil])\n(nil :kw2 :ns1/kw2 :ns2/kw1 :ns2/kw2)","editors":[{"avatar-url":"https://avatars2.githubusercontent.com/u/109629?v=4","account-source":"github","login":"jafingerhut"}],"_id":"5c4e08d8e4b0ca44402ef64a"},{"updated-at":1548617960867,"created-at":1548617960867,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/109629?v=4"},"body":";; `compare` throws an exception if given two values whose types are\n;; \"too different\", e.g. it can compare integers, longs, and doubles\n;; to each other, but not strings to keywords or keywords to symbols.\n;; It cannot compare lists, sequences, sets, or maps at all.\n;; See https://clojure.org/guides/comparators for advice on writing\n;; your own custom comparators.\n\nuser=> (sort [5 \"a\"])\nExecution error (ClassCastException) at java.lang.String/compareTo (String.java:111).\njava.lang.Long cannot be cast to java.lang.String\n\nuser=> (sort [:foo 'bar])\nExecution error (ClassCastException) at java.util.TimSort/countRunAndMakeAscending (TimSort.java:355).\nclojure.lang.Keyword cannot be cast to clojure.lang.Symbol\n\nuser=> (sort [#{1 2} #{2 4}])\nExecution error (ClassCastException) at java.util.TimSort/countRunAndMakeAscending (TimSort.java:355).\nclojure.lang.PersistentHashSet cannot be cast to java.lang.Comparable\n\nuser=> (sort [{:a 1 :b 3} {:c -2 :d 4}])\nExecution error (ClassCastException) at java.util.TimSort/countRunAndMakeAscending (TimSort.java:355).\nclojure.lang.PersistentArrayMap cannot be cast to java.lang.Comparable\n\nuser=> (sort [[1 2] '(3 4)])\nExecution error (ClassCastException) at java.util.TimSort/countRunAndMakeAscending (TimSort.java:355).\nclojure.lang.PersistentList cannot be cast to java.lang.Comparable\n\nuser=> (sort [[1 2] (seq [3 4])])\nExecution error (ClassCastException) at java.util.TimSort/countRunAndMakeAscending (TimSort.java:355).\nclojure.lang.PersistentVector$ChunkedSeq cannot be cast to java.lang.Comparable","_id":"5c4e08e8e4b0ca44402ef64b"},{"updated-at":1595864314210,"created-at":1595864314210,"author":{"login":"uosl","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/3865590?v=4"},"body":";; You can reverse the sort order returned by `compare` by swapping its arguments.\n\n#(compare %2 %1)\n\nuser=> (sort #(compare %2 %1) [3 2 4 1])\n(4 3 2 1)\n\n;; Source: https://clojure.org/guides/comparators#_reverse_order","_id":"5f1ef4fae4b0b1e3652d7325"}],"notes":[{"author":{"login":"glts","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/1483271?v=4"},"updated-at":1526151376043,"created-at":1526151376043,"body":"It is clear what `compare` does, but how do you turn its output into an answer to questions like ‘is x less than y’ or ‘is x greater than or equal to y’?\n\nWhile the numeric `<` `<=` `=` `>=` `>` provide that answer in Boolean form right away, with `compare` a second step is required.\n\n ((juxt < <= = >= >) 2 3)\n ;;=> [true true false false false]\n\nHere is a listing of the same relations using `compare`:\n\n ((juxt (comp neg? compare)\n (comp not pos? compare)\n (comp zero? compare)\n (comp not neg? compare)\n (comp pos? compare))\n \"2\" \"3\")\n ;;=> [true true false false false]\n","_id":"5af738d0e4b045c27b7fac66"}],"arglists":["x y"],"doc":"Comparator. Returns a negative number, zero, or a positive number\n when x is logically 'less than', 'equal to', or 'greater than'\n y. Same as Java x.compareTo(y) except it also works for nil, and\n compares numbers and collections in a type-independent manner. x\n must implement Comparable","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/compare"},{"added":"1.0","ns":"clojure.core","name":"complement","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1301366589000,"author":{"login":"pauldoo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5cb916d3c8abc9f45a093209e72489fb?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"not","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b3f"}],"line":1447,"examples":[{"author":{"login":"mattdw","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/ee24aacb65359196b0a1bad050f9a62f?r=PG&default=identicon"},"editors":[{"login":"mattdw","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/ee24aacb65359196b0a1bad050f9a62f?r=PG&default=identicon"},{"login":"mattdw","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/ee24aacb65359196b0a1bad050f9a62f?r=PG&default=identicon"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":";; a simple not-empty? predicate\n(def not-empty? (complement empty?))\n;; #'user/not-empty?\n\n(not-empty? []) ;;=> false\n(not-empty? [1 2]) ;;=> true\n\n\n;; a slightly more complex example\n;; this function takes two arguments, and sometimes returns nil\n(defn contains-char? [the-string, the-char]\n (some #(= the-char %) the-string))\n;; #'user/contains-char?\n\n(contains-char? \"abc\" \\b) ;;=> true\n(contains-char? \"abc\" \\j) ;;=> nil\n\n;; define the complement, to check if a char is absent\n(def does-not-contain-char? (complement contains-char?))\n;; #'user/does-not-contain-char?\n\n;; our complement does exactly what we expect\n(does-not-contain-char? \"abc\" \\b) ;;=> false\n(does-not-contain-char? \"abc\" \\j) ;;=> true\n","created-at":1280324273000,"updated-at":1420648560124,"_id":"542692c7c026201cdc3269b7"},{"updated-at":1583065242138,"created-at":1503907232338,"author":{"login":"MokkeMeguru","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/30849444?v=4"},"body":"(map (complement even?) '(1 2 3 4))\n\n;; return...\n;; (true false true false)\n\n;; see also ...\n(map even? '(1 2 3 4))\n;; (false true false true)\n\n;; WARNING\n;; This function returns ERROR!!!\n(map (not even?) '(1 2 3 4))\n\n(map #(not (even? %)) '(1 2 3 4)) ; This works\n","editors":[{"avatar-url":"https://avatars0.githubusercontent.com/u/655969?v=4","account-source":"github","login":"kopos"},{"login":"wplj","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/12292887?v=4"}],"_id":"59a3cda0e4b09f63b945ac53"},{"editors":[{"login":"kopos","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/655969?v=4"}],"body":"(def not-empty? (complement empty?))\n\n(not-empty? \"abcde\")\n;;true\n\n(not-empty? \"\")\n;;false","author":{"avatar-url":"https://avatars0.githubusercontent.com/u/31028993?v=4","account-source":"github","login":"ibercode"},"created-at":1518787297119,"updated-at":1542283642709,"_id":"5a86dae1e4b0316c0f44f8c8"},{"updated-at":1583065367049,"created-at":1583065367049,"author":{"login":"wplj","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/12292887?v=4"},"body":";; flatten function from Clojure core:\n(defn flatten\n \"Takes any nested combination of sequential things (lists, vectors,\n etc.) and returns their contents as a single, flat lazy sequence.\n (flatten nil) returns an empty sequence.\"\n {:added \"1.2\"\n :static true}\n [x]\n (filter (complement sequential?)\n (rest (tree-seq sequential? seq x))))","_id":"5e5ba917e4b087629b5a18af"}],"notes":null,"arglists":["f"],"doc":"Takes a fn f and returns a fn that takes the same arguments as f,\n has the same effects, if any, and returns the opposite truth value.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/complement"},{"added":"1.4","ns":"clojure.core","name":"*compiler-options*","type":"var","see-alsos":null,"examples":[{"updated-at":1483010010444,"created-at":1483010010444,"author":{"login":"PetrGlad","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/124476?v=3"},"body":";; Toggle locals clearing (set it to true to aid with debugging)\n(alter-var-root #'clojure.core/*compiler-options* \n update :disable-locals-clearing not)","_id":"5864efdae4b0fd5fb1cc964a"},{"updated-at":1615669432545,"created-at":1615140629289,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/20086?v=4"},"body":";; If example.clj is on the classpath and contains something like:\n;; (ns example)\n;; (def ^{:t1 \"secret metadata\"\n;; :doc \"here's some useful info\"}\n;; foo 1))\n\n(binding [*compiler-options* {:elide-meta [:doc :t1]}]\n (compile 'example))\n\n;; AOT-compiles \"example.clj\" removing \":doc\" and \":t1\" values from\n;; the constant pool of the generated class.\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"}],"_id":"60451715e4b0b1e3652d746f"}],"notes":null,"arglists":[],"doc":"A map of keys to options.\n Note, when binding dynamically make sure to merge with previous value.\n Supported options:\n :elide-meta - a collection of metadata keys to elide during compilation.\n :disable-locals-clearing - set to true to disable clearing, useful for using a debugger\n :direct-linking - set to true to use direct static invocation of functions, rather than vars\n Note that call sites compiled with direct linking will not be affected by var redefinition.\n Use ^:redef (or ^:dynamic) on a var to prevent direct linking and allow redefinition.\n See https://clojure.org/reference/compilation for more information.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/*compiler-options*"},{"added":"1.0","ns":"clojure.core","name":"*print-dup*","type":"var","see-alsos":[{"created-at":1732181980473,"author":{"login":"johannesCmayer","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/24253624?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"read","ns":"clojure.edn"},"_id":"673effdc69fbcc0c2261751c"}],"examples":[{"updated-at":1522749214303,"created-at":1281149003000,"body":";; `*print-dup*` is very handy when we want to write clojure code/data\n;; to a file to read it in later.\n\n(defn serialize\n \"Print a data structure to a file so that we may read it in later.\"\n [data-structure #^String filename]\n (with-out-writer\n (java.io.File. filename)\n (binding [*print-dup* true] (prn data-structure))))\n\n\n;; This allows us to then read in the structure at a later time, like so:\n(defn deserialize [filename]\n (with-open [r (PushbackReader. (FileReader. filename))]\n (read r)))\n\n\nuser=> (deserialize \"config.clj\")\n{:name \"Fred\", :age \"23\"}\n","editors":[{"login":"devn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3"},{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"avatar-url":"https://www.gravatar.com/avatar/57126d684344e156ede4592945b54366?r=PG&default=identicon","account-source":"clojuredocs","login":"bmillare"},{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3","account-source":"github","login":"devn"},"_id":"542692cec026201cdc326da7"}],"notes":[{"author":{"avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3","account-source":"github","login":"devn"},"created-at":1281149184000,"body":"It is sometimes preferable (depending on the size of the structure you're serializing) to wrap the `(with-out-writer ...)` inside a `(dorun (with-out-writer ...) nil)` in order to suppress the output at your REPL.","updated-at":1281149184000,"_id":"542692ecf6e94c6970521f93"},{"updated-at":1293075429000,"body":"Note, I'm making changes to deserialize, there are a few typos.","created-at":1293075226000,"author":{"login":"bmillare","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/57126d684344e156ede4592945b54366?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521faf"}],"arglists":[],"doc":"When set to logical true, objects will be printed in a way that preserves\n their type when read in later.\n\n Defaults to false.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/*print-dup*"},{"added":"1.2","ns":"clojure.core","name":"defrecord","file":"clojure/core_deftype.clj","type":"macro","column":1,"see-alsos":[{"created-at":1289817120000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"deftype","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d16"},{"created-at":1289817125000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"defstruct","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d17"},{"created-at":1289817134000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"defprotocol","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d18"},{"created-at":1416251002018,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"},"to-var":{"ns":"clojure.core","name":"instance?","library-url":"https://github.com/clojure/clojure"},"_id":"546a467ae4b0dc573b892fdb"},{"created-at":1439234754688,"author":{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/94482?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"record?","ns":"clojure.core"},"_id":"55c8fac2e4b0080a1b79cdb8"}],"line":314,"examples":[{"author":{"login":"Kototama","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a54a4dc204925d397ca010b9a332e74d?r=PG&default=identicon"},"editors":[{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},{"login":"Ljos","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/45b996a79abca465acaf6c0f10b0437?r=PG&default=identicon"},{"login":"pvesna","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a9e4f72971f946e55c71222a37d8e947?r=PG&default=identicon"}],"body":";; from Stu's examples:\n\n(defrecord Person [fname lname address])\n-> user.Person\n\n(defrecord Address [street city state zip])\n-> user.Address\n\n(def stu (Person. \"Stu\" \"Halloway\"\n (Address. \"200 N Mangum\"\n \"Durham\"\n \"NC\"\n 27701)))\n-> #'user/stu\n\n(:lname stu)\n-> \"Halloway\"\n\n(-> stu :address :city)\n-> \"Durham\"\n\n(assoc stu :fname \"Stuart\")\n-> #:user.Person{:fname \"Stuart\", :lname \"Halloway\", :address #:user.Address{:street \"200 N Mangum\", :city \"Durham\", :state \"NC\", :zip 27701}}\n\n(update-in stu [:address :zip] inc)\n-> #:user.Person{:fname \"Stu\", :lname \"Halloway\", :address #:user.Address{:street \"200 N Mangum\", :city \"Durham\", :state \"NC\", :zip 27702}}","created-at":1286314411000,"updated-at":1359584504000,"_id":"542692c8c026201cdc326a32"},{"author":{"login":"puredanger","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/89c8afd032c7b3473f67c9b00d3acd5a?r=PG&default=identicon"},"editors":[{"login":"puredanger","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/89c8afd032c7b3473f67c9b00d3acd5a?r=PG&default=identicon"},{"login":"puredanger","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/89c8afd032c7b3473f67c9b00d3acd5a?r=PG&default=identicon"},{"login":"steveminer","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d28543d134185d12d4006a74738d233e?r=PG&default=identicon"},{"login":"Ljos","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/45b996a79abca465acaf6c0f10b0437?r=PG&default=identicon"},{"login":"pvesna","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a9e4f72971f946e55c71222a37d8e947?r=PG&default=identicon"}],"body":";; This example shows how to implement a Java interface in defrecord.\n;; We'll implement FileNameMap (because it has a simple interface, \n;; not for its real purpose). \n\n(import java.net.FileNameMap)\n-> java.net.FileNameMap\n\n;; Define a record named Thing with a single field a. Implement\n;; FileNameMap interface and provide an implementation for the single\n;; method: String getContentTypeFor(String fileName)\n(defrecord Thing [a]\n FileNameMap\n (getContentTypeFor [this fileName] (str a \"-\" fileName)))\n-> user.Thing\n\n;; construct an instance of the record\n(def thing (Thing. \"foo\"))\n-> #'user/thing\n\n;; check that the instance implements the interface\n(instance? FileNameMap thing)\n-> true\n\n;; get all the interfaces for the record type\n(map #(println %) (.getInterfaces Thing))\n-> java.net.FileNameMap\n-> clojure.lang.IObj\n-> clojure.lang.ILookup\n-> clojure.lang.IKeywordLookup\n-> clojure.lang.IPersistentMap\n-> java.util.Map\n-> java.io.Serializable\n\n;; actually call the method on the thing instance and pass \"bar\"\n(.getContentTypeFor thing \"bar\")\n-> \"foo-bar\"","created-at":1290599788000,"updated-at":1359589207000,"_id":"542692c8c026201cdc326a36"},{"author":{"login":"belun","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8d3c423e74750fa42c0386833e4b8209?r=PG&default=identicon"},"editors":[{"login":"belun","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8d3c423e74750fa42c0386833e4b8209?r=PG&default=identicon"},{"login":"belun","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8d3c423e74750fa42c0386833e4b8209?r=PG&default=identicon"},{"login":"belun","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8d3c423e74750fa42c0386833e4b8209?r=PG&default=identicon"},{"login":"Ljos","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/45b996a79abca465acaf6c0f10b0437?r=PG&default=identicon"},{"avatar-url":"https://avatars.githubusercontent.com/u/4142015?v=3","account-source":"github","login":"bkovitz"},{"login":"green-coder","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/598193?v=4"},{"avatar-url":"https://avatars.githubusercontent.com/u/4068533?v=4","account-source":"github","login":"lmartelli"}],"body":";; prepare a protocol\nuser=> (defprotocol Fun-Time (drinky-drinky [_]))\nFun-Time\n\n;; define a record and extend the previous protocol, implementing its function\nuser=> (defrecord Someone [nick-name preferred-drink] \n Fun-Time \n (drinky-drinky [_] (str nick-name \"(having \" preferred-drink \"): uuumm\")))\nuser.Someone\n;; NOTE how 'nick-name' and 'preferred-drink' are symbols\n;; that are not declared anywhere, they are 'provided' inside the function\n\n;; instantiate the protocol once and store it\nuser=> (def dude (->Someone \"belun\" \"daiquiri\"))\n#'user/dude\n\n;; use the function defined inside the protocol on the protocol instance\nuser=> (drinky-drinky dude)\n\"belun(having daiquiri): uuumm\"\n\n\n;; courtesy of Howard Lewis Ship - http://java.dzone.com/articles/changes-cascade-and-cautionary","created-at":1317098332000,"updated-at":1672591553613,"_id":"542692d2c026201cdc326f82"},{"updated-at":1442089153715,"created-at":1319420075000,"body":"; If you define a defrecord in one namespace and want to use it\n; from another, there are 2 options:\n; 1. use the constructor (->Record) \n; (only available in clojure >= 1.4)\n;\n; 2. first require the namespace and then import\n; the record as a regular class.\n; The require+import order makes sense if you consider that first\n; the namespace has to be compiled--which generates a class for\n; the record--and then the generated class must be imported.\n; (Thanks to raek in #clojure for the explanations!)\n\n; Namespace \"my/data.clj\", where a defrecord is declared\n(ns my.data)\n\n(defrecord Employee [name surname])\n\n; Option 1: \n; Namescape \"my/queries-option-one.clj\", where a defrecord is used\n(ns my-queries-one\n (:use [my.data]))\n\n(println\n \"Employees named Albert:\"\n (filter #(= \"Albert\" (.name %))\n [(->Employee \"Albert\" \"Smith\")\n (->Employee \"John\" \"Maynard\")\n (->Employee \"Albert\" \"Cheng\")]))\n\n; Option 2:\n; Namescape \"my/queries-option-two.clj\", where a defrecord is used\n(ns my.queries-option-two\n (:require my.data)\n (:import [my.data Employee]))\n\n(println\n \"Employees named Albert:\"\n (filter #(= \"Albert\" (.name %))\n [(Employee. \"Albert\" \"Smith\")\n (Employee. \"John\" \"Maynard\")\n (Employee. \"Albert\" \"Cheng\")]))","editors":[{"avatar-url":"https://www.gravatar.com/avatar/fea4948490b77a00b8c10bffd792f9d8?r=PG&default=identicon","account-source":"clojuredocs","login":"albertcardona"},{"avatar-url":"https://www.gravatar.com/avatar/45b996a79abca465acaf6c0f10b0437?r=PG&default=identicon","account-source":"clojuredocs","login":"Ljos"},{"avatar-url":"https://www.gravatar.com/avatar/45b996a79abca465acaf6c0f10b0437?r=PG&default=identicon","account-source":"clojuredocs","login":"Ljos"},{"login":"edeustace","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/101623?v=3"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/fea4948490b77a00b8c10bffd792f9d8?r=PG&default=identicon","account-source":"clojuredocs","login":"albertcardona"},"_id":"542692d2c026201cdc326f87"},{"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"editors":[],"body":";; The map->Recordclass form works only in Clojure 1.3 or higher\n\n(defrecord Foo [a b])\n\n(defrecord Bar [a b c])\n\n(defrecord Baz [a c])\n\n(def f (Foo. 10 20))\n(println f)\n-> #user.Foo{:a 10, :b 20}\n\n(def r (map->Bar (merge f {:c 30})))\n(println r)\n-> #user.Bar{:a 10, :b 20, :c 30}\n\n(def z (map->Baz (merge f {:c 30})))\n(println z)\n-> #user.Baz{:a 10, :c 30, :b 20}","created-at":1335392908000,"updated-at":1335392908000,"_id":"542692d2c026201cdc326f8b"},{"body":";; Construct a record from a vector.\n(def info [\"Carl\" 20])\n\n(defrecord Person [name age])\n\n(apply ->Person info)\n-> #user.Person{:name \"Carl\", :age 20}\n\n;; This is particularly useful for mapping parsed CSV files to records\n(map #(apply ->Person %) parsed-csv-file)","author":{"login":"EduardoMRB","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2163269?v=3"},"created-at":1419039522858,"updated-at":1419039522858,"_id":"5494d322e4b04e93c519ffaa"},{"updated-at":1444173053403,"created-at":1444173053403,"author":{"login":"minutetominute","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/3320594?v=3"},"body":";; Destructuring a record\n\n(defrecord Cat [age weight])\n\n(def Jasper (Cat. 2 10))\n\n(defn about-cat [{:keys [age weight]}] \n (str age \" yrs old and \" weight \" lbs\"))\n\n(about-cat Jasper)\n->\"2 yrs old and 10 lbs\"","_id":"561454fde4b0b41dac04c953"},{"updated-at":1479124081391,"created-at":1479124081391,"author":{"login":"ertugrulcetin","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8271291?v=3"},"body":"(defrecord Person [name age])\n;;=> user.Person\n\n(def ertu (->Person \"Ertu\" 24))\n;;=> #'user/ertu\n\n(record? ertu)\n;;=> true\n\n(record? (assoc ertu :address \"Somewhere\"))\n;;=> true\n\n;;removing base fields converts record to regular map\n(record? (dissoc ertu :name))\n;;=> false","_id":"5829a471e4b0782b632278c0"},{"updated-at":1486752453677,"created-at":1486752453677,"author":{"login":"bunbutter","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/5318739?v=3"},"body":";;iterate over the keys\n\n;;define the record\n(defrecord record-class [alplha beta])\n\n;;create a defrecord variable\n(def record (record-class. 1 2))\n\n;;iterate over the keys\n(for [key (keys record)]\n (println (key record)))","_id":"589e0ac5e4b01f4add58fe45"},{"updated-at":1510128100976,"created-at":1510128100976,"author":{"login":"ibercode","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/31028993?v=4"},"body":";;define Address record\n(defrecord Address [city state])\n\n;;define Person record\n(defrecord Person [firstname lastname ^Address address])\n\n;;buid the constructor\n(defn make-person ([fname lname city state]\n (->Person fname lname (->Address city state))))\n\n;;create a person\n(def person1 (make-person \"John\" \"Doe\" \"LA\" \"CA\"))\n\n;;retrieve values\n(:firstname person1)\n(:city (:address person1))","_id":"5a02b9e4e4b0a08026c48ca3"},{"updated-at":1649147987152,"created-at":1528333981519,"author":{"login":"jennydickinson","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/1972655?v=4"},"body":";; Binary Search Tree (variation on implementation by Edd Mann)\n\n(defrecord Node [value left right])\n\n(defn insert [{:keys [value left right] :as node} item]\n (cond\n (nil? node) (->Node item nil nil)\n (< item value) (->Node value (insert left item) right)\n (> item value) (->Node value left (insert right item))\n :else (update node :count (fnil inc 1)))) ; Use of :count, not in defrecord\n\n(defn coll->bst [coll] (reduce insert nil coll))\n\n(coll->bst [10 5 20 10 10])\n=> #example.bst.Node{:value 10,\n :left #example.bst.Node{:value 5, :left nil, :right nil},\n :right #example.bst.Node{:value 20, :left nil, :right nil},\n :count 3}\n","editors":[{"avatar-url":"https://avatars0.githubusercontent.com/u/1972655?v=4","account-source":"github","login":"jennydickinson"},{"login":"mjul","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/142868?v=4"}],"_id":"5b18869de4b00ac801ed9e0f"},{"updated-at":1658250170033,"created-at":1658250170033,"author":{"login":"quoll","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/358875?v=4"},"body":"(defrecord Person [first-name last-name age]\n ;; Provide a default string representation\n Object\n (toString [_] (format \"%s, %s (%d)\" last-name first-name age)))\n\n;; Construct a person with the auto-generated construction function\n(def p (->Person \"Alice\" \"Smith\" 22))\n\n;; use this object in a string\n(str \"The person is: \" p)\n\n;; output:\n;; \"The person is: Smith, Alice (22)\"","_id":"62d6e3bae4b0b1e3652d7628"},{"updated-at":1708547018833,"created-at":1708547018833,"author":{"login":"teodorlu","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/5285452?v=4"},"body":";; If your record contains open resources, implementing java.io.Closeable on\n;; your record will make macros like `with-open` work out-of-the-box with your\n;; new type.\n\nuser=> (defrecord Person [name age]\n java.io.Closeable\n (close [this] (println \"bye, \" name \"!\")))\nuser=> (with-open [p (Person. \"Teodor\" 123)]\n (println \"working with \" (.name p)))\n;; prints:\nworking with Teodor\nbye, Teodor !\n","_id":"65d65bca69fbcc0c226174a6"},{"updated-at":1716965943513,"created-at":1716965943513,"author":{"login":"holyjak","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/624958?v=4"},"body":";; Implementing multi-arity protocol fns with a record\n(defprotocol Proto\n (foo [this] [this some-arg])) ; 2 arities\n\n(defrecord Imp []\n Proto\n (foo [_this] \"0-arg\")\n (foo [_this _some-arg] \"1-arg\")) ; each def. as a separate entry","_id":"6656d23769fbcc0c226174cc"}],"macro":true,"notes":[{"updated-at":1302904571000,"body":"http://tech.puredanger.com/2010/11/23/implementing-java-interfaces-with-clojure-records/","created-at":1302904571000,"author":{"login":"Havvy","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e799a79441c7543be48562403411cd13?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fb9"}],"arglists":["name [& fields] & opts+specs"],"doc":"(defrecord name [fields*] options* specs*)\n\n Options are expressed as sequential keywords and arguments (in any order).\n\n Supported options:\n :load-ns - if true, importing the record class will cause the\n namespace in which the record was defined to be loaded.\n Defaults to false.\n\n Each spec consists of a protocol or interface name followed by zero\n or more method bodies:\n\n protocol-or-interface-or-Object\n (methodName [args*] body)*\n\n Dynamically generates compiled bytecode for class with the given\n name, in a package with the same name as the current namespace, the\n given fields, and, optionally, methods for protocols and/or\n interfaces.\n\n The class will have the (immutable) fields named by\n fields, which can have type hints. Protocols/interfaces and methods\n are optional. The only methods that can be supplied are those\n declared in the protocols/interfaces. Note that method bodies are\n not closures, the local environment includes only the named fields,\n and those fields can be accessed directly.\n\n Method definitions take the form:\n\n (methodname [args*] body)\n\n The argument and return types can be hinted on the arg and\n methodname symbols. If not supplied, they will be inferred, so type\n hints should be reserved for disambiguation.\n\n Methods should be supplied for all methods of the desired\n protocol(s) and interface(s). You can also define overrides for\n methods of Object. Note that a parameter must be supplied to\n correspond to the target object ('this' in Java parlance). Thus\n methods for interfaces will take one more argument than do the\n interface declarations. Note also that recur calls to the method\n head should *not* pass the target object, it will be supplied\n automatically and can not be substituted.\n\n In the method bodies, the (unqualified) name can be used to name the\n class (for calls to new, instance? etc).\n\n The class will have implementations of several (clojure.lang)\n interfaces generated automatically: IObj (metadata support) and\n IPersistentMap, and all of their superinterfaces.\n\n In addition, defrecord will define type-and-value-based =,\n and will defined Java .hashCode and .equals consistent with the\n contract for java.util.Map.\n\n When AOT compiling, generates compiled bytecode for a class with the\n given name (a symbol), prepends the current ns as the package, and\n writes the .class file to the *compile-path* directory.\n\n Two constructors will be defined, one taking the designated fields\n followed by a metadata map (nil for none) and an extension field\n map (nil for none), and one taking only the fields (using nil for\n meta and extension fields). Note that the field names __meta,\n __extmap, __hash and __hasheq are currently reserved and should not\n be used when defining your own records.\n\n Given (defrecord TypeName ...), two factory functions will be\n defined: ->TypeName, taking positional parameters for the fields,\n and map->TypeName, taking a map of keywords to field values.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/defrecord"},{"added":"1.3","ns":"clojure.core","name":"with-redefs-fn","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1322088065000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"with-redefs","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d81"}],"line":7690,"examples":[{"author":{"login":"johnnyluu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1ba99f2dc1064733c7badbb16db9254a?r=PG&default=identicon"},"editors":[{"login":"johnnyluu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1ba99f2dc1064733c7badbb16db9254a?r=PG&default=identicon"},{"login":"avasenin","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/154699?v=3"}],"body":"(ns http)\n\n(defn post [url]\n {:body \"Hello world\"})\n\n(ns app\n (:require [clojure.test :refer [run-tests]]))\n\n(deftest is-a-fn\n (with-redefs-fn {#'http/post (fn [url] {:body \"Hello world again\"})}\n #(is (= {:body \"Hello world again\"} (http/post \"http://service.com/greet\")))))\n\n(run-tests) ;; test is passing","created-at":1350024230000,"updated-at":1352471467000,"_id":"542692d6c026201cdc3270c2"},{"author":{"login":"tonsky","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/4188c62c28a196e3e82363217c56fca5?r=PG&default=identicon"},"editors":[],"body":"=> (defn f [] false)\n\n=> (println (f))\n;; false\n\n=> (with-redefs-fn {#'f (fn [] true)} \n #(println (f)))\n;; true","created-at":1352394593000,"updated-at":1352394593000,"_id":"542692d6c026201cdc3270c5"},{"updated-at":1452611657323,"created-at":1452611657323,"author":{"login":"Sangdol","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/803223?v=3"},"body":"(defn add-5 [n] (+ n 5))\n(with-redefs-fn {#'add-5 (fn [n] (+ n 50))}\n #(is (= 60 (add-5 10))))\n\n;; Cannot redefine the reference in the partial function\n(def partial-add-5 (partial add-5))\n(with-redefs-fn {#'add-5 (fn [n] (+ n 50))}\n #(is (= 15 (partial-add-5 10)))) \n","_id":"56951849e4b051fe5ede7753"}],"notes":null,"arglists":["binding-map func"],"doc":"Temporarily redefines Vars during a call to func. Each val of\n binding-map will replace the root value of its key which must be\n a Var. After func is called with no args, the root values of all\n the Vars will be set back to their old values. These temporary\n changes will be visible in all threads. Useful for mocking out\n functions during testing.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/with-redefs-fn"},{"added":"1.0","ns":"clojure.core","name":"sequence","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1374149058000,"author":{"login":"alilee","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2fb0196dc5a7cd3a5cc73f1b9941c209?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"seq","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521a7e"},{"created-at":1520634654207,"author":{"login":"glts","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/1483271?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"eduction","ns":"clojure.core"},"_id":"5aa30b1ee4b0316c0f44f91a"}],"line":2664,"examples":[{"author":{"login":"yasuto","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cacfb7ecf08cb6461767e514c93b7bf9?r=PG&default=identicon"},"editors":[{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"}],"body":"user> (sequence [1 2 3])\n(1 2 3)\nuser> (class (sequence '(1 2 3)))\nclojure.lang.PersistentList","created-at":1307740020000,"updated-at":1423275662256,"_id":"542692c8c026201cdc326a16"},{"updated-at":1477624741486,"created-at":1477624741486,"author":{"login":"G1enY0ung","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/15034155?v=3"},"body":";; let us make a transducer\nuser=> (def xf (comp (filter odd?) (take 5)))\n#'user/xf\nuser=> (sequence xf (range 1 10))\n(1 3 5 7 9)","_id":"5812c3a5e4b024b73ca35a1c"},{"updated-at":1519251895765,"created-at":1519251895765,"author":{"login":"cljlc","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/36645452?v=4"},"body":";; turns a string into a sequence of characters:\n(sequence \"abc\")\n=> (\\a \\b \\c)","_id":"5a8df1b7e4b0316c0f44f8e4"},{"updated-at":1646145858679,"created-at":1519691165450,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"},"body":";; combine a bunch of collections together\n(sequence cat [[1 2 3] [5 6 7] [8 9 0]])\n;=> (1 2 3 5 6 7 8 9 0) \n(sequence cat [ '(1 2 3) '(5 6 7) '(8 9 0) ])\n;=> (1 2 3 5 6 7 8 9 0)","editors":[{"avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4","account-source":"github","login":"phreed"},{"login":"siddharthjain-in","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/6537820?v=4"}],"_id":"5a94a59de4b0316c0f44f8fb"},{"updated-at":1585287974225,"created-at":1585287974225,"author":{"login":"green-coder","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/598193?v=4"},"body":";; When called with multiples collections.\n\n(sequence (map vector) [1 2 3] [:a :b :c])\n;=> ([1 :a] [2 :b] [3 :c])","_id":"5e7d9326e4b087629b5a18c4"},{"updated-at":1614561640162,"created-at":1614561640162,"author":{"login":"Crowbrammer","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/19522656?v=4"},"body":";; Comparison to seq\n(def v [1 2 3])\n(def l '(1 2 3))\n(def ss (sorted-set 1 2 3))\n(= (seq [1 2 3]) (sequence [1 2 3])) ;;=> true\n(= (sequence v) (seq v)) ;;=> true\n(= (sequence l) (seq l)) ;;=> true\n(= (sequence ss) (seq ss)) ;;=> true\n\n;; Comparison for non-ordered stuff\n(def m {:a 1 :b 2 :c 3})\n(def s #{1 2 3})\n(sequence m) ;;=> ([:a 1] [:b 2] [:c 3])\n(seq m) ;;=> ([:a 1] [:b 2] [:c 3])\n(sequence s) ;;=> (1 3 2)\n(seq s) ;;=> (1 3 2)","_id":"603c4168e4b0b1e3652d7469"}],"notes":[{"author":{"login":"glts","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/1483271?v=4"},"updated-at":1520634679847,"created-at":1520634679847,"body":"Interesting background about `sequence` versus `eduction`: https://groups.google.com/d/msg/clojure/9I6MtgOTD0w/NiG5PimBCP8J","_id":"5aa30b37e4b0316c0f44f91b"},{"author":{"login":"divs1210","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/3773773?v=4"},"updated-at":1708597180110,"created-at":1708597180110,"body":"Since Clojure's implementation of `sequence` is in Java, and is pretty involved, I wrote a [pure Clojure version](https://gist.github.com/divs1210/53c86ddad2fc0f1bd30917e3d03840f0) to build intuition.","_id":"65d71fbc69fbcc0c226174a7"}],"arglists":["coll","xform coll","xform coll & colls"],"doc":"Coerces coll to a (possibly empty) sequence, if it is not already\n one. Will not force a lazy seq. (sequence nil) yields (), When a\n transducer is supplied, returns a lazy sequence of applications of\n the transform to the items in coll(s), i.e. to the set of first\n items of each coll, followed by the set of second\n items in each coll, until any one of the colls is exhausted. Any\n remaining items in other colls are ignored. The transform should accept\n number-of-colls arguments","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/sequence"},{"added":"1.0","ns":"clojure.core","name":"constantly","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1345605389000,"author":{"login":"abrooks","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/69976?v=2"},"to-var":{"ns":"clojure.core","name":"repeatedly","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521aa4"},{"created-at":1544362994989,"author":{"login":"Ramblurr","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/14830?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"identity","ns":"clojure.core"},"_id":"5c0d1bf2e4b0ca44402ef5ea"}],"line":1459,"examples":[{"author":{"login":"pkolloch","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/10b2fd3c0a4cc46dc241a48468dc551?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":"user=> (def boring (constantly 10))\n#'user/boring\n\nuser=> (boring 1 2 3)\n10\n\nuser=> (boring)\n10\n\nuser=> (boring \"Is anybody home?\")\n10\n","created-at":1282320404000,"updated-at":1413580544498,"_id":"542692cbc026201cdc326c18"},{"author":{"login":"shockbob","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon"},"editors":[{"avatar-url":"https://avatars1.githubusercontent.com/u/598193?v=4","account-source":"github","login":"green-coder"}],"body":";; A really goofy way to find the size of a collection\nuser=> (reduce + (map (constantly 1) [:a :b :c]))\n3","created-at":1310850642000,"updated-at":1554005351294,"_id":"542692cbc026201cdc326c1a"},{"author":{"login":"john.r.woodward","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/22b6fbc4a386291e45b1cb4449377086?r=PG&default=identicon"},"editors":[{"login":"donkey","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/b1c297c3ac97ef732eb689213c3337b9?r=PG&default=identicon"},{"login":"donkey","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/b1c297c3ac97ef732eb689213c3337b9?r=PG&default=identicon"}],"body":";; constantly returns a function which always returns the same value\n(map (constantly 9) [1 2 3])\nuser=> (9 9 9)\n\n(map (constantly (rand-int 100)) [:a :b :c])\nuser=> (43 43 43)","created-at":1342722368000,"updated-at":1345367153000,"_id":"542692d2c026201cdc326f72"},{"editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/9038715?v=2","account-source":"github","login":"icemaze"},{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"login":"Jjunior130","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7597818?v=3"}],"updated-at":1483822847346,"created-at":1412612363149,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/9038715?v=2","account-source":"github","login":"icemaze"},"body":";; 'Removed' example that was more about transducers than `constantly`.\n\n:O","_id":"5432c10be4b0069c44347255"}],"notes":[{"updated-at":1291196938000,"body":"any examples of when this would be useful? I think it is weird to want a function that always returns \"x\" regardless of the number of arguments passed to it - however since this exists in core I'm sure it is sensible, more a case of I've not enough experience to appreciate its value.","created-at":1291196938000,"author":{"login":"ossareh","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9d0f447aca573ecf21a45c9272211140?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fa7"},{"updated-at":1292309493000,"body":"I asked about use cases for this function in #clojure and got a good response from amalloy:\r\n\r\nSay you want to call a library function that asks you to pass it a function; it's going to call that function ten times with different arguments to decide how to populate a list it gives you. But your program is really simple and you want the list to just be full of zeroes. So you call:\r\n\r\n (libfn (constantly 0))\r\n\r\nHope that's useful!","created-at":1292309381000,"author":{"login":"clizzin","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/555813697e5dc358bb27d5efd3ffa23?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fae"},{"author":{"avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3","account-source":"github","login":"devn"},"created-at":1306502622000,"body":"(constantly 1) is often useful when it comes to testing. You can think of it like you would a \"stub\".","updated-at":1306502622000,"_id":"542692ecf6e94c6970521fbe"},{"updated-at":1403826661000,"body":"constantly is typically used as an argument to a higher order function when a constant value is needed. ","created-at":1403826661000,"author":{"login":"phreed","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3a0c739cf289be18be932dc3022e6fd3?r=PG&default=identicon"},"_id":"542692edf6e94c697052202b"},{"body":"It is also quite useful in unit tests:\n\n
    \n(deftest foo\n  (testing \"Clojure tweets only\"\n    (with-redefs [twitter/get-tweets\n                  (constantly [\"#clojure is awesome!\" \"Yay! #winning\"])]\n      (is (= [\"#clojure is awesome!\"]\n             (only-clojure \"@happyguy\"))))))\n
    \n","created-at":1413545107841,"updated-at":1413545107841,"author":{"login":"jmglov","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/224070?v=2"},"_id":"5440fc93e4b049fc676849cc"},{"body":"Basically, when you already know the result of a function that you would need\nto pass to a higher order function, you can simply wrap it in a constantly to\navoid creating a variadic anonymous function.\n\n (defn hof [f]\n (do-something-with (f ...))\n\n (def x \"result\")\n\n (hof (constantly x)) ","created-at":1428223494135,"updated-at":1428223494135,"author":{"login":"dexterous","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/94739?v=3"},"_id":"5520f606e4b0b96203a0d59c"},{"author":{"login":"bradleesand","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/810411?v=3"},"updated-at":1484963377505,"created-at":1484963377505,"body":"I've used this to create a `no-op` function.\n\n```clojure\n(let [handler (if (some? value)\n #(do-something-with value)\n ; else no-op\n (constantly nil))]\n ; call handler\n (handler \"foo\" \"bar\"))\n```","_id":"5882be31e4b01f4add58fe2c"},{"author":{"login":"defHLT","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/1539296?v=4"},"updated-at":1517096514668,"created-at":1517096514668,"body":"Just a shortcut to
    (fn [& args] x)
    \n","_id":"5a6d0e42e4b0c974fee49d0f"},{"author":{"login":"eneroth","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/333974?v=4"},"updated-at":1743061593788,"created-at":1743060268665,"body":"> Just a shortcut to…\n\nNote that it's not the same as `(fn [& args] x)`. `constantly` will eagerly evaluate the code in the closure to provide a constant return value, as the name implies.\n\n```clojure \n(constantly (println :hello))\n;; :hello\n;; => #function[clojure.core/constantly/fn--5759]\n\n(fn [& args] (println :hello))\n;; => #function[…/eval712692/f--712693]\n```\n\n","_id":"67e4fd2ccd84df5de54e2084"}],"arglists":["x"],"doc":"Returns a function that takes any number of arguments and returns x.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/constantly"},{"added":"1.0","ns":"clojure.core","name":"get-proxy-class","file":"clojure/core_proxy.clj","type":"function","column":1,"see-alsos":[{"created-at":1539820739801,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"construct-proxy","ns":"clojure.core"},"_id":"5bc7ccc3e4b00ac801ed9edd"}],"line":281,"examples":[{"updated-at":1539820731584,"created-at":1539820731584,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"body":";; generates a new Java class extending/implementing the given classes/interfaces:\n;; See \"construct-proxy\" on how to get an instance.\n\n(import '[clojure.lang IDeref IObj])\n(def DocumentException (get-proxy-class Exception IDeref))\n\n(type DocumentException)\n;; java.lang.Class\n\n(ancestors DocumentException)\n;; #{java.io.Serializable \n;; clojure.lang.IProxy \n;; java.lang.Exception \n;; clojure.lang.IDeref \n;; java.lang.Object \n;; java.lang.Throwable}\n","_id":"5bc7ccbbe4b00ac801ed9edc"}],"notes":null,"arglists":["& bases"],"doc":"Takes an optional single class followed by zero or more\n interfaces. If not supplied class defaults to Object. Creates an\n returns an instance of a proxy class derived from the supplied\n classes. The resulting value is cached and used for any subsequent\n requests for the same class set. Returns a Class object.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/get-proxy-class"},{"added":"1.0","ns":"clojure.core","name":"make-array","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1299713235000,"author":{"login":"sergey","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/fbf950615302e00a14bceec914af32ca?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"int-array","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f6c"},{"created-at":1299713241000,"author":{"login":"sergey","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/fbf950615302e00a14bceec914af32ca?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"double-array","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f6d"},{"created-at":1299713244000,"author":{"login":"sergey","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/fbf950615302e00a14bceec914af32ca?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"float-array","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f6e"},{"created-at":1299713281000,"author":{"login":"sergey","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/fbf950615302e00a14bceec914af32ca?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"short-array","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f6f"},{"created-at":1299713289000,"author":{"login":"sergey","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/fbf950615302e00a14bceec914af32ca?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"long-array","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f70"},{"created-at":1299713301000,"author":{"login":"sergey","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/fbf950615302e00a14bceec914af32ca?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"char-array","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f71"},{"created-at":1299713305000,"author":{"login":"sergey","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/fbf950615302e00a14bceec914af32ca?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"byte-array","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f72"},{"created-at":1299713311000,"author":{"login":"sergey","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/fbf950615302e00a14bceec914af32ca?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"boolean-array","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f73"},{"created-at":1299713319000,"author":{"login":"sergey","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/fbf950615302e00a14bceec914af32ca?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"object-array","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f74"},{"created-at":1299713350000,"author":{"login":"sergey","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/fbf950615302e00a14bceec914af32ca?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"to-array","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f75"},{"created-at":1299713355000,"author":{"login":"sergey","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/fbf950615302e00a14bceec914af32ca?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"to-array-2d","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f76"},{"created-at":1299713359000,"author":{"login":"sergey","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/fbf950615302e00a14bceec914af32ca?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"into-array","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f77"},{"created-at":1299713411000,"author":{"login":"sergey","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/fbf950615302e00a14bceec914af32ca?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"aget","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f78"},{"created-at":1299713415000,"author":{"login":"sergey","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/fbf950615302e00a14bceec914af32ca?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"aset","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f79"},{"created-at":1299713422000,"author":{"login":"sergey","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/fbf950615302e00a14bceec914af32ca?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"alength","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f7a"},{"created-at":1299713425000,"author":{"login":"sergey","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/fbf950615302e00a14bceec914af32ca?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"amap","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f7b"},{"created-at":1299713428000,"author":{"login":"sergey","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/fbf950615302e00a14bceec914af32ca?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"areduce","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f7c"}],"line":4012,"examples":[{"author":{"login":"sergey","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/fbf950615302e00a14bceec914af32ca?r=PG&default=identicon"},"editors":[{"login":"cloojure","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7083783?v=3"}],"body":"(make-array Integer/TYPE 3)\n\n; Types are defined in clojure/genclass.clj:\n; Boolean/TYPE\n; Character/TYPE\n; Byte/TYPE\n; Short/TYPE\n; Integer/TYPE\n; Long/TYPE\n; Float/TYPE\n; Double/TYPE\n; Void/TYPE","created-at":1299713202000,"updated-at":1423783350038,"_id":"542692cec026201cdc326dfb"},{"author":{"login":"sergey","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/fbf950615302e00a14bceec914af32ca?r=PG&default=identicon"},"editors":[{"login":"kawas44","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/fbe17f4245ddacea6f46aaff3b051429?r=PG&default=identicon"}],"body":"user=> (pprint (make-array Double/TYPE 3))\n[0.0, 0.0, 0.0]\n\nuser=> (pprint (make-array Integer/TYPE 2 3))\n[[0, 0, 0], [0, 0, 0]]\n\n\n;; Create an array of Threads, then show content and type\nuser=> (def ar (make-array Thread 3))\n#'user/ar\n\nuser=> (pprint ar)\n[nil, nil, nil]\n\nuser=> (type ar)\n[Ljava.lang.Thread;\n","created-at":1299713210000,"updated-at":1331510349000,"_id":"542692cec026201cdc326dfc"}],"notes":null,"arglists":["type len","type dim & more-dims"],"doc":"Creates and returns an array of instances of the specified class of\n the specified dimension(s). Note that a class object is required.\n Class objects can be obtained by using their imported or\n fully-qualified name. Class objects for the primitive types can be\n obtained using, e.g., Integer/TYPE.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/make-array"},{"added":"1.1","ns":"clojure.core","name":"shorts","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"to-var":{"library-url":"https://github.com/clojure/clojure","name":"short-array","ns":"clojure.core"},"author":{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},"created-at":1342917710000,"_id":"542692ebf6e94c6970521f31"}],"line":5416,"examples":[{"updated-at":1656674521947,"created-at":1656674521947,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":";; short-array will convert where possible\n(short-array [32767 32768 32769]);; => [32767, -32768, -32767]\n\n;; shorts will not\n(try (shorts [32767 32768 32769])\n (catch ClassCastException e (ex-message e)))\n;; => \"clojure.lang.PersistentVector cannot be cast to [S\"\n","_id":"62bed8d9e4b0b1e3652d7619"},{"editors":[{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"}],"body":";; Casting avoids expensive reflection, so to see the benefit, enable warning:\n(set! *warn-on-reflection* true)\n\n;; We'll def a short-array but won't type-hint the var:\n(def my-array (short-array [10 20 30 40 50 60]))\n\n;; and try to amap over it without using `shorts` or type hinting:\n(amap my-array i _ (unchecked-short (unchecked-inc (aget my-array i))))\n;; Reflection warning… call to static method alength on clojure.lang.RT can't be resolved (argument types: unknown).\n;; Reflection warning… call to static method aclone on clojure.lang.RT can't be resolved (argument types: unknown).\n;; Reflection warning… call to static method aget on clojure.lang.RT can't be resolved (argument types: unknown, int).\n;; Reflection warning… call to static method aset on clojure.lang.RT can't be resolved (argument types: unknown, int, short).\n;; => [11, 21, 31, 41, 51, 61]\n\n;; We can use `shorts` to avoid reflection:\n(amap (shorts my-array) i _ (unchecked-short (unchecked-inc (aget (shorts my-array) i))))\n;; => [11, 21, 31, 41, 51, 61]\n\n;; Just as we can type hint in place:\n(amap ^shorts my-array i _ (unchecked-short (unchecked-inc (aget ^shorts my-array i))))\n;; => [11, 21, 31, 41, 51, 61]\n\n;; Or type hint the var:\n(def ^\"[S\" my-array (short-array [10 20 30 40 50 60]))\n(amap my-array i _ (unchecked-short (unchecked-inc (aget my-array i))))\n;; => [11, 21, 31, 41, 51, 61]\n","author":{"avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4","account-source":"github","login":"tomdl89"},"created-at":1682270458965,"updated-at":1682271131562,"_id":"644568fae4b08cf8563f4b8f"}],"notes":null,"arglists":["xs"],"doc":"Casts to shorts[]","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/shorts"},{"added":"1.7","ns":"clojure.core","name":"completing","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1510099302386,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"transduce","ns":"clojure.core"},"_id":"5a024966e4b0a08026c48c9c"}],"line":7000,"examples":[{"editors":[{"login":"reborg","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/20086?v=4"}],"body":";; Fix apparently inconsistent behaviour of \"-\" (minus) with transduce:\n(transduce (map inc) - 0 (range 10))\n;; 55\n(transduce (map inc) (completing -) 0 (range 10))\n;; -55","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"},"created-at":1509576734100,"updated-at":1620508070476,"_id":"59fa501ee4b0a08026c48c8d"},{"editors":[{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"}],"body":";; the reducing fn arity-1 executes the last transformation in transduce.\n;; completing defaults to \"identity\" but you can change it.\n;; Use this fact for example with transients and go back to persistent once done.\n(require '[clojure.string :refer [lower-case]])\n(transduce\n (comp\n (remove nil?)\n (map lower-case))\n (completing #(assoc! %1 %2 (inc (get %1 %2 0))) persistent!)\n (transient {})\n [\"hi\" \"ho\" \"Hello\" \"hoi\" \"Hi\" \"Ha\" \"ha\" \"hello\"])\n;; {\"hi\" 2, \"ho\" 1, \"hello\" 2, \"hoi\" 1, \"ha\" 2}","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"},"created-at":1510933087748,"updated-at":1510936504930,"_id":"5a0f025fe4b0a08026c48cbe"},{"updated-at":1670417339254,"created-at":1670417339254,"author":{"login":"naxels","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/3195443?v=4"},"body":";; Example calculating the average from \n;; https://aphyr.com/posts/360-loopr-a-loop-reduction-macro-for-clojure#comment-3800\n\n(transduce (map inc)\n (completing (fn [[sum cnt] x] [(+ sum x) (inc cnt)])\n (fn [[sum cnt]] (/ sum cnt)))\n [0 0]\n (range 7))\n\n;; 4","_id":"63908bbbe4b0b1e3652d7696"}],"notes":null,"arglists":["f","f cf"],"doc":"Takes a reducing function f of 2 args and returns a fn suitable for\n transduce by adding an arity-1 signature that calls cf (default -\n identity) on the result argument.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/completing"},{"added":"1.0","ns":"clojure.core","name":"update-proxy","file":"clojure/core_proxy.clj","type":"function","column":1,"see-alsos":[{"created-at":1539943028356,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"init-proxy","ns":"clojure.core"},"_id":"5bc9aa74e4b00ac801ed9ee8"}],"line":313,"examples":[{"author":{"login":"jneira","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2c8ecc24181d171df85a26458b9cd5f?r=PG&default=identicon"},"editors":[],"body":";; from http://groups.google.com/group/clojure/msg/71702435ccd1d189\nuser> (import java.util.Date)\njava.util.Date\n\nuser> (def d (proxy [Date] [] (toString [] \"hello\")))\n#'user/d\n\nuser> d\n#\n\nuser> (.toString d)\n\"hello\"\n\nuser> (.toGMTString d)\n\"17 Nov 2010 12:57:28 GMT\"\n\nuser> (update-proxy d {\"toGMTString\" (fn [this] \"goodbye\")})\nnil\n\nuser> (.toGMTString d)\n\"goodbye\" ","created-at":1290029291000,"updated-at":1290029291000,"_id":"542692cdc026201cdc326d30"}],"notes":null,"arglists":["proxy mappings"],"doc":"Takes a proxy instance and a map of strings (which must\n correspond to methods of the proxy superclass/superinterfaces) to\n fns (which must take arguments matching the corresponding method,\n plus an additional (explicit) first arg corresponding to this, and\n updates (via assoc) the proxy's fn map. nil can be passed instead of\n a fn, in which case the corresponding method will revert to the\n default behavior. Note that this function can be used to update the\n behavior of an existing instance without changing its identity.\n Returns the proxy.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/update-proxy"},{"added":"1.0","ns":"clojure.core","name":"unchecked-negate-int","file":"clojure/core.clj","type":"function","column":1,"see-alsos":null,"line":1191,"examples":[{"author":{"login":"Jens","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/7f9a46b88f30d9461fea5670fd185f65?r=PG&default=identicon"},"editors":[],"body":"user=> (unchecked-negate-int 4)\n-4\nuser=> (unchecked-negate-int 0)\n0\nuser=> (unchecked-negate-int -7)\n7\nuser=> (unchecked-negate-int Integer/MAX_VALUE)\n-2147483647\nuser=> (unchecked-negate-int Integer/MIN_VALUE) ;overflow\n-2147483648","created-at":1331729438000,"updated-at":1331729438000,"_id":"542692d5c026201cdc3270ae"}],"notes":null,"arglists":["x"],"doc":"Returns the negation of x, an int.\n Note - uses a primitive operator subject to overflow.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/unchecked-negate-int"},{"added":"1.6","ns":"clojure.core","name":"hash-unordered-coll","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1495647921750,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"hash","ns":"clojure.core"},"_id":"5925c6b1e4b093ada4d4d735"},{"created-at":1495647929367,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"hash-ordered-coll","ns":"clojure.core"},"_id":"5925c6b9e4b093ada4d4d736"}],"line":5248,"examples":[{"editors":[{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"}],"body":";;;; Clojure's (hash-unordered-coll) ALWAYS produces the same hash code EVEN:\n;;;; (1) for different collection types\n;;;; (2) for differently ordered collections of the same type\n;;;; AS LONG AS the collections contain the same elements \n\n(hash-unordered-coll #{1 2})\n;;=> 460223544\n(hash-unordered-coll (sorted-set 1 2))\n;;=> 460223544\n(hash-unordered-coll (doto (new java.util.HashSet) (.add 1) (.add 2)))\n;;=> 460223544\n(hash-unordered-coll (doto (new java.util.TreeSet) (.add 1) (.add 2)))\n;;=> 460223544\n(hash-unordered-coll [1 2])\n;;=> 460223544\n(hash-unordered-coll [2 1])\n;;=> 460223544\n(hash-unordered-coll (doto (new java.util.ArrayList) (.add 1) (.add 2)))\n;;=> 460223544\n(hash-unordered-coll (doto (new java.util.ArrayList) (.add 2) (.add 1)))\n;;=> 460223544\n\n;;;; On the other hand: both Clojure's (hash) and Java's .hashCode()\n;;;; CAN (and often WILL) produce different hash codes:\n;;;; (1) for different collection types\n;;;; (2) for differently ordered collections of the same type\n;;;; EVEN if the collections contain the same elements\n\n(hash #{1 2})\n;;=> 460223544\n(hash (sorted-set 1 2))\n;;=> 460223544\n(hash (doto (new java.util.HashSet) (.add 1) (.add 2)))\n;;=> 3\n(hash (doto (new java.util.TreeSet) (.add 1) (.add 2)))\n;;=> 3\n(hash [1 2])\n;;=> 156247261\n(hash [2 1])\n;;=> -1994590503\n(hash (doto (new java.util.ArrayList) (.add 1) (.add 2)))\n;;=> 994\n(hash (doto (new java.util.ArrayList) (.add 2) (.add 1)))\n;;=> 1024\n\n(.hashCode #{1 2})\n;;=> 3\n(.hashCode (sorted-set 1 2))\n;;=> 3\n(.hashCode (doto (new java.util.HashSet) (.add 1) (.add 2)))\n;;=> 3\n(.hashCode (doto (new java.util.TreeSet) (.add 1) (.add 2)))\n;;=> 3\n(.hashCode [1 2])\n;;=> 994\n(.hashCode [2 1])\n;;=> 1024\n(.hashCode (doto (new java.util.ArrayList) (.add 1) (.add 2)))\n;;=> 994\n(.hashCode (doto (new java.util.ArrayList) (.add 2) (.add 1)))\n;;=> 1024\n","author":{"avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3","account-source":"github","login":"svenschoenung"},"created-at":1495647903722,"updated-at":1495649000733,"_id":"5925c69fe4b093ada4d4d734"},{"updated-at":1495657051233,"created-at":1495657051233,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"body":";;;;\n;;;; Only accepts implementations of java.lang.Iterable\n;;;;\n\n(hash-unordered-coll true)\n;;=> ClassCastException java.lang.Boolean cannot be cast to java.lang.Iterable\n(hash-unordered-coll 1)\n;;=> ClassCastException java.lang.Long cannot be cast to java.lang.Iterable\n(hash-unordered-coll \\c)\n;;=> ClassCastException java.lang.Character cannot be cast to java.lang.Iterable\n\n;;;;\n;;;; Being seqable is not sufficient!\n;;;;\n\n(hash-unordered-coll \"12\")\n;;=> ClassCastException java.lang.String cannot be cast to java.lang.Iterable\n(hash-unordered-coll (int-array [1 2]))\n;;=> ClassCastException [I cannot be cast to java.lang.Iterable\n(hash-unordered-coll nil)\n;;=> NullPointerException","_id":"5925ea5be4b093ada4d4d746"}],"notes":null,"arglists":["coll"],"doc":"Returns the hash code, consistent with =, for an external unordered\n collection implementing Iterable. For maps, the iterator should\n return map entries whose hash is computed as\n (hash-ordered-coll [k v]).\n See http://clojure.org/data_structures#hash for full algorithms.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/hash-unordered-coll"},{"added":"1.0","ns":"clojure.core","name":"repeat","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1286195040000,"author":{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},"to-var":{"ns":"clojure.core","name":"repeatedly","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521dae"},{"created-at":1291970208000,"author":{"login":"alimoeeny","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e8dd06976ead4082d2181f3807117e1?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"cycle","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521daf"},{"created-at":1302045956000,"author":{"login":"TimMc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5d532e51427ef2f4ded31aaca16c8baf?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"constantly","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521db0"},{"created-at":1327501829000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"dotimes","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521db1"}],"line":3022,"examples":[{"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"john.r.woodward","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/22b6fbc4a386291e45b1cb4449377086?r=PG&default=identicon"}],"body":"user=> (take 5 (repeat \"x\"))\n(\"x\" \"x\" \"x\" \"x\" \"x\")\n\n;; which is the same as:\nuser=> (repeat 5 \"x\")\n(\"x\" \"x\" \"x\" \"x\" \"x\")\n\n;; It should be noted that repeat simply repeats the value n number of times.\n;; If you wish to execute a function to calculate the value each time you \n;; probably want the repeatedly function.\n\n","created-at":1279092799000,"updated-at":1343165038000,"_id":"542692c7c026201cdc3269a5"},{"updated-at":1520873825360,"created-at":1520873825360,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"body":"(defn tally [n]\n (apply str\n (concat\n (repeat (quot n 5) \"卌\")\n (repeat (mod n 5) \"|\"))))\n\n(map tally (range 1 11))\n;; (\"|\" \"||\" \"|||\" \"||||\" \"卌\" \"卌|\" \"卌||\" \"卌|||\" \"卌||||\" \"卌卌\")","_id":"5aa6b161e4b0316c0f44f922"}],"notes":null,"arglists":["x","n x"],"doc":"Returns a lazy (infinite!, or length n if supplied) sequence of xs.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/repeat"},{"added":"1.0","ns":"clojure.core","name":"unchecked-inc","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1289217232000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"unchecked-add","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521ba9"},{"created-at":1289217236000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"unchecked-dec","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521baa"},{"created-at":1289217238000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"unchecked-inc","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bab"},{"created-at":1289217241000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"unchecked-negate","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bac"},{"created-at":1289217244000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"unchecked-divide","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bad"},{"created-at":1289217247000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"unchecked-subtract","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bae"},{"created-at":1289217251000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"unchecked-multiply","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521baf"},{"created-at":1289217253000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"unchecked-remainder","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bb0"},{"created-at":1488018916400,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"inc","ns":"clojure.core"},"_id":"58b15de4e4b01f4add58fe60"},{"created-at":1488018923070,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"inc'","ns":"clojure.core"},"_id":"58b15debe4b01f4add58fe61"}],"line":1170,"examples":[{"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"editors":[],"body":"users=> (unchecked-inc Integer/MAX_VALUE)\n-2147483648\n\nusers=> (unchecked-inc 0)\n1","created-at":1289217223000,"updated-at":1289217223000,"_id":"542692c8c026201cdc326a14"},{"updated-at":1488018795920,"created-at":1488018795920,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10583730?v=3"},"body":";; Illustrates the difference between (inc), (inc') and (unchecked-inc)\n\n;; The \"N\" suffix denotes a BigInt instance\n;; https://github.com/clojure/clojure/blob/master/src/jvm/clojure/lang/BigInt.java\n\nLong/MAX_VALUE\n;;=> 9223372036854775807\n\n(inc Long/MAX_VALUE)\n;;=> ArithmeticException integer overflow clojure.lang.Numbers.throwIntOverflow (Numbers.java:1501)\n\n(inc' Long/MAX_VALUE)\n;;=> 9223372036854775808N\n\n;; Notice how the resulting number becomes NEGATIVE:\n(unchecked-inc Long/MAX_VALUE)\n;;=> -9223372036854775808","_id":"58b15d6be4b01f4add58fe5f"}],"notes":null,"arglists":["x"],"doc":"Returns a number one greater than x, a long.\n Note - uses a primitive operator subject to overflow.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/unchecked-inc"},{"ns":"clojure.core","name":"*reader-resolver*","type":"var","see-alsos":null,"examples":null,"notes":null,"arglists":[],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core/*reader-resolver*"},{"added":"1.0","ns":"clojure.core","name":"nthnext","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1303125684000,"author":{"login":"Havvy","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e799a79441c7543be48562403411cd13?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"nth","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ca9"},{"created-at":1303125696000,"author":{"login":"Havvy","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e799a79441c7543be48562403411cd13?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"drop","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521caa"},{"created-at":1356088874000,"author":{"login":"TimMc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5d532e51427ef2f4ded31aaca16c8baf?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"nthrest","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cab"}],"line":3172,"examples":[{"author":{"login":"zmila","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/68dd6f50915854aa04fefcf4d6fa5c8e?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":"(nthnext (range 10) 3)\n;;=> (3 4 5 6 7 8 9)\n\n(nthnext [] 3)\n;;=> nil\n\n(nthnext [1 2 3 4 5 6 7] 4)\n;;=> (5 6 7)\n\n","created-at":1281033770000,"updated-at":1420736472299,"_id":"542692cec026201cdc326d86"},{"body":";; drop is also similar, but different \n(nthnext (range 10) 5) ;;=> (5 6 7 8 9)\n(drop 5 (range 10)) ;;=> (5 6 7 8 9)\n\n;; here is a case where the results differ\n(nthnext [] 3) ;;=> nil\n(drop 3 []) ;;=> () ; a lazy sequence","author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"},"created-at":1420737401357,"updated-at":1420737401357,"_id":"54aebb79e4b0e2ac61831c97"}],"notes":[{"updated-at":1306331938000,"body":"`nthnext` is similar to `drop`.\r\nBut `nthnext` is eager, while `drop` is lazy.

    \r\nAlso parameters are in opposite order.","created-at":1306324912000,"author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"_id":"542692ecf6e94c6970521fbd"}],"arglists":["coll n"],"doc":"Returns the nth next of coll, (seq coll) when n is 0.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/nthnext"},{"added":"1.0","ns":"clojure.core","name":"and","file":"clojure/core.clj","type":"macro","column":1,"see-alsos":[{"created-at":1286508452000,"author":{"login":"dakrone","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bcacd00a7f05c4772329cf9f446c7987?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"or","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521eb2"},{"created-at":1334293964000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.core","name":"if","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521eb3"},{"created-at":1592404851986,"author":{"login":"lunik1","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/13547699?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"every-pred","ns":"clojure.core"},"_id":"5eea2b73e4b0b1e3652d7305"}],"line":844,"examples":[{"updated-at":1479826446023,"created-at":1286508448000,"body":"user=> (and true true)\ntrue\n\nuser=> (and true false)\nfalse\n\nuser=> (and false false)\nfalse\n\nuser=> (and '() '())\n()\n\nuser=> (and '[] '[])\n[]\n\nuser=> (and 0 1) ; Note that this is *not* bitwise 'and'\n1\n\nuser=> (and 1 0)\n0\n","editors":[{"login":"mlanza","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/39192?v=3"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/bcacd00a7f05c4772329cf9f446c7987?r=PG&default=identicon","account-source":"clojuredocs","login":"dakrone"},"_id":"542692cdc026201cdc326d0a"},{"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"editors":[],"body":";; See examples for \"if\" explaining Clojure's idea of logical true\n;; and logical false.","created-at":1334293968000,"updated-at":1334293968000,"_id":"542692d2c026201cdc326f49"},{"updated-at":1569963753241,"created-at":1472792960038,"author":{"login":"Lacty","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7412474?v=3"},"body":"; Note that, and does not evaluate if the first value is false\nuser=> (and false nil)\nfalse\n\nuser=> (and nil false)\nnil\n\nuser=> (and false (println \"foo\"))\nfalse\n\nuser=> (and (println \"foo\") false)\nfoo\nnil\n\nuser=> (and nil nil)\nnil","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/5894926?v=3","account-source":"github","login":"slipset"},{"login":"allmonty","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/4502764?v=4"}],"_id":"57c90980e4b0709b524f04e0"},{"updated-at":1490369604947,"created-at":1490369604947,"author":{"login":"Rovanion","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/632775?v=3"},"body":"; From the Clojure 1.9 source code.\n(defn qualified-keyword?\n \"Return true if x is a keyword with a namespace\"\n [x] (and (keyword? x) (namespace x) true))\n\n; Note how the return value of and is value of the last expression.\nuser=> (qualified-keyword? :hi/there)\ntrue\n\n; If we instead define the function as:\n(defn qualified-keyword?\n [x] (and (keyword? x) (namespace x)))\n; we get the namespace as return value:\nuser=> (qualified-keyword? :hi/there)\n\"hi\"","_id":"58d53c44e4b01f4add58fe78"}],"macro":true,"notes":[{"updated-at":1305106125000,"body":"Note add is a macro, so you cannot apply it. For example, there is a vector of some Boolean values [true true false true], which you want to test to see if they are all true. The code below will not work:

    (apply add [true true false true]) ;won't work
    \r\nInstead, use this:
    (every? identity [true  true false true])
    More discussion can be found at http://osdir.com/ml/clojure/2010-01/msg01242.html","created-at":1305106125000,"author":{"login":"huahaiy","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/889685?v=2"},"_id":"542692ecf6e94c6970521fbb"},{"author":{"login":"dilipd","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/164585?v=4"},"updated-at":1635725779315,"created-at":1635725779315,"body":"typo: 'and' instead of 'add'?","_id":"617f31d3e4b0b1e3652d7568"}],"arglists":["","x","x & next"],"doc":"Evaluates exprs one at a time, from left to right. If a form\n returns logical false (nil or false), and returns that value and\n doesn't evaluate any of the other expressions, otherwise it returns\n the value of the last expr. (and) returns true.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/and"},{"added":"1.0","ns":"clojure.core","name":"create-struct","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1468878705351,"author":{"login":"bradcypert","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1455979?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"struct","ns":"clojure.core"},"_id":"578d4f71e4b0bafd3e2a04a5"},{"created-at":1468878716309,"author":{"login":"bradcypert","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1455979?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"defstruct","ns":"clojure.core"},"_id":"578d4f7ce4b0bafd3e2a04a6"},{"created-at":1468878831043,"author":{"login":"bradcypert","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1455979?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"defrecord","ns":"clojure.core"},"_id":"578d4fefe4b0bafd3e2a04a8"}],"line":4064,"examples":[{"updated-at":1468878648375,"created-at":1468878648375,"author":{"login":"bradcypert","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1455979?v=3"},"body":";;Creates a person structure\n(def person (create-struct :name :age))\n\n;;Creates a structure with the given values associated with the structure keys\n(struct person \"Brad Cypert\" 23)\n{:name \"Brad Cypert\", :age 23}","_id":"578d4f38e4b0bafd3e2a04a4"}],"notes":[{"author":{"login":"bradcypert","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1455979?v=3"},"updated-at":1468878818445,"created-at":1468878818445,"body":"Structs are becoming obsolete. Use records instead. See defrecord.","_id":"578d4fe2e4b0bafd3e2a04a7"},{"author":{"login":"metasoarous","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/88556?v=4"},"updated-at":1605646130347,"created-at":1605646130347,"body":"In _general_, records should be preferred over structs. However, structs aren't _entirely_ obsolete.\n\nThey can still be useful when you need/want to create record-like objects dynamically; That is, when you don't know the field names at compile time. A typical example of this might be loading rows from a CSV (as [semantic-csv](https://github.com/metasoarous/semantic-csv) does). The advantage in this case over using regular maps is significantly improved performance creating and using these objects.","_id":"5fb43732e4b0b1e3652d740c"}],"arglists":["& keys"],"doc":"Returns a structure basis object.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/create-struct"},{"added":"1.0","ns":"clojure.core","name":"get-validator","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1553694544702,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"set-validator!","ns":"clojure.core"},"_id":"5c9b7f50e4b0ca44402ef6e3"}],"line":2417,"examples":[{"editors":[{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"}],"body":"(require '[clojure.repl :refer [demunge]])\n\n(def a 1)\n\n(get-validator #'a) ; no validator set yet\n;; nil\n\n(set-validator! #'a pos?) ; \"a\" should be positive number\n\n(-> (get-validator #'a) ; get-validator returns the function object\n class ; get the Class instance\n .getSimpleName ; access the inner class name, no package\n demunge ; demunge is the opposite of munge\n symbol) ; back to a symbol\n;; core/pos?\n\n(def a 0) ; this is now unacceptable\n;; IllegalStateException Invalid reference state\n\n(set-validator! #'a nil) ; make it ok again","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"},"created-at":1553694538283,"updated-at":1553771408277,"_id":"5c9b7f4ae4b0ca44402ef6e2"}],"notes":null,"arglists":["iref"],"doc":"Gets the validator-fn for a var/ref/agent/atom.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/get-validator"},{"added":"1.0","ns":"clojure.core","name":"number?","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"to-var":{"library-url":"https://github.com/clojure/clojure","name":"num","ns":"clojure.core"},"author":{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},"created-at":1342917515000,"_id":"542692eaf6e94c6970521b4d"},{"created-at":1440146030366,"author":{"login":"muhuk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/40178?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"integer?","ns":"clojure.core"},"_id":"55d6e26ee4b0831e02cddf16"}],"line":3585,"examples":[{"author":{"login":"dpritchett","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/147981?v=3"},"editors":[{"login":"benjiiiiii","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/fd1adaf32d9dc6531d6041dbc379efb0?r=PG&default=identicon"},{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"login":"xantheon","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10231554?v=3"}],"body":"user=> (number? 1)\ntrue\nuser=> (number? 1.0)\ntrue\nuser=> (number? :a)\nfalse\nuser=> (number? nil)\nfalse\nuser=> (number? \"23\")\nfalse\n\n","created-at":1279074614000,"updated-at":1421848806945,"_id":"542692c8c026201cdc326a1e"},{"body":";; map number? over the vector\n(map number? [1 0.44 3e6 0xFF])\n;;=> (true true true true)\n\n;; map number? over the vector created by converting a list into a vector \n;; with the function \"into\"\n(map number? (into [] '(1 0.44 3e6 0xFF)))\n;;=> (true true true true)\n\n","author":{"login":"xantheon","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10231554?v=3"},"created-at":1421848794036,"updated-at":1421850409437,"editors":[{"login":"xantheon","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10231554?v=3"}],"_id":"54bfb0dae4b0e2ac61831cc5"},{"editors":[{"login":"sixofhearts","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/283702?v=4"}],"body":";; Works for rationals\nuser=> (number? (/ 2 3))\ntrue","author":{"avatar-url":"https://avatars.githubusercontent.com/u/283702?v=4","account-source":"github","login":"sixofhearts"},"created-at":1638921869968,"updated-at":1638921911526,"_id":"61aff68de4b0b1e3652d7584"},{"updated-at":1729784552097,"created-at":1729784552097,"author":{"login":"g-tardy","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/102146886?v=4"},"body":";; Warning! NaN is considered as a number in member of the class Double.\n;; this may be confusing, but it's good to know,\n;; especially if you are working with filters\nuser=> (number? Double/NaN)\ntrue\nuser=> (filter number? [nil 0 1.1 \"String\" {:key :val} Double/NaN])\n(0 1.1 ##NaN)","_id":"671a6ae869fbcc0c2261750c"}],"notes":null,"arglists":["x"],"doc":"Returns true if x is a Number","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/number_q"},{"added":"1.0","ns":"clojure.core","name":"await-for","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1298860372000,"author":{"login":"ninjudd","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/7ced25585a7556e9b9b975c1f9e136e3?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"await","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ced"}],"line":3314,"examples":[{"updated-at":1616191765486,"created-at":1616191540527,"author":{"login":"gs","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/79596?v=4"},"body":";; construct simple agent\n(def agnt (agent 5))\n\n;; increment agent\n(send agnt inc) \n\n;; system does not wait for the value change\n(println @agnt) \n;; => 5 \n\n;; increment agent\n(send agnt inc)\n\n;; wait for maximum 1000 ms\n(await-for 1000 agnt) \n\n;; print out the value of the agent \n(println @agnt) \n;; => 7","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/79596?v=4","account-source":"github","login":"gs"}],"_id":"60552034e4b0b1e3652d74a4"}],"notes":null,"arglists":["timeout-ms & agents"],"doc":"Blocks the current thread until all actions dispatched thus\n far (from this thread or agent) to the agents have occurred, or the\n timeout (in milliseconds) has elapsed. Returns logical false if\n returning due to timeout, logical true otherwise.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/await-for"},{"ns":"clojure.core","name":"chunk-next","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1443933552687,"author":{"login":"devn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"chunk-first","ns":"clojure.core"},"_id":"5610ad70e4b0686557fcbd40"},{"created-at":1443933558893,"author":{"login":"devn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"chunk-rest","ns":"clojure.core"},"_id":"5610ad76e4b08e404b6c1c8e"},{"created-at":1443933581024,"author":{"login":"devn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"chunk-cons","ns":"clojure.core"},"_id":"5610ad8de4b08e404b6c1c90"},{"created-at":1443933589741,"author":{"login":"devn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"chunk-buffer","ns":"clojure.core"},"_id":"5610ad95e4b0686557fcbd41"},{"created-at":1443933597715,"author":{"login":"devn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"chunk","ns":"clojure.core"},"_id":"5610ad9de4b0686557fcbd42"},{"created-at":1443933620082,"author":{"login":"devn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"chunk-append","ns":"clojure.core"},"_id":"5610adb4e4b08e404b6c1c91"},{"created-at":1443933691622,"author":{"login":"devn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"chunked-seq?","ns":"clojure.core"},"_id":"5610adfbe4b08e404b6c1c92"}],"line":709,"examples":[{"updated-at":1443934272580,"created-at":1443934272580,"author":{"login":"devn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3"},"body":"(let [chunked-cons (seq (range 1 42))]\n\n (class chunked-cons)\n ;; => clojure.lang.ChunkedCons\n\n ;; Returns the next chunk when there are more than 32 elements\n ;; in the ChunkedCons.\n (chunk-next chunked-cons)\n ;; => (33 34 35 36 37 38 39 40 41)\n\n)","_id":"5610b040e4b0686557fcbd43"}],"notes":null,"tag":"clojure.lang.ISeq","arglists":["s"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core/chunk-next"},{"added":"1.0","ns":"clojure.core","name":"print-str","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1297554870000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"println-str","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f5d"},{"created-at":1374264258000,"author":{"login":"lbeschastny","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/416170465e4045f810f09a9300dda4dd?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"print","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f5e"}],"line":4803,"examples":[{"author":{"login":"Miles","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bbb26d2a5e856c4fba0f72c3f7250f3f?r=PG&default=identicon"},"editors":[{"login":"Miles","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bbb26d2a5e856c4fba0f72c3f7250f3f?r=PG&default=identicon"},{"login":"Miles","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bbb26d2a5e856c4fba0f72c3f7250f3f?r=PG&default=identicon"},{"login":"Miles","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bbb26d2a5e856c4fba0f72c3f7250f3f?r=PG&default=identicon"},{"login":"Miles","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bbb26d2a5e856c4fba0f72c3f7250f3f?r=PG&default=identicon"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"Miles","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bbb26d2a5e856c4fba0f72c3f7250f3f?r=PG&default=identicon"},{"login":"matthewg","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/b29dd31d183124d9e87d8037bb30e326?r=PG&default=identicon"}],"body":";; Create a string from the given items and store it in x.\nuser=> (def x (print-str 1 \"foo\" \\b \\a \\r {:a 2}))\n#'user/x\n\n;; It's a string.\nuser=> (string? x)\ntrue\n\n;; Notice that each item is separated by a space.\nuser=> x\n\"1 foo b a r {:a 2}\"\n\n","created-at":1284257174000,"updated-at":1323233208000,"_id":"542692c9c026201cdc326aea"}],"notes":null,"tag":"java.lang.String","arglists":["& xs"],"doc":"print to a string, returning it","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/print-str"},{"added":"1.0","ns":"clojure.core","name":"not-any?","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1330526858000,"author":{"login":"kisielk","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/55fd56dfef815d7aa543be09ad3ed3e9?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"some","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d5b"},{"created-at":1369837609000,"author":{"login":"avasenin","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/154699?v=3"},"to-var":{"ns":"clojure.core","name":"every?","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d5c"}],"line":2720,"examples":[{"updated-at":1566222779775,"created-at":1279074514000,"body":"user=> (not-any? odd? '(2 4 6))\ntrue\n\nuser=> (not-any? odd? '(1 2 3))\nfalse\n\nuser=> (not-any? nil? [true false false])\ntrue\n\nuser=> (not-any? nil? [true false nil])\nfalse\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3","account-source":"github","login":"jafingerhut"},{"login":"cromptone","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/11131392?v=4"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/147981?v=3","account-source":"github","login":"dpritchett"},"_id":"542692cbc026201cdc326ba8"}],"notes":[{"author":{"login":"bsima","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/200617?v=3"},"updated-at":1454193022420,"created-at":1454193022420,"body":"Why is there a `not-any?` but no `any?`?","_id":"56ad397ee4b0ceed88ce8d1f"},{"author":{"login":"ertugrulcetin","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8271291?v=3"},"updated-at":1454445515187,"created-at":1454445515187,"body":"You can use this for any?:\n\n(def any?\n (complement not-any?))","_id":"56b113cbe4b0ceed88ce8d20"},{"author":{"login":"chendesheng","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2094891?v=3"},"updated-at":1459589289487,"created-at":1459589289487,"body":"You can also use some for any?","_id":"56ff90a9e4b09295d75dbf44"},{"body":"`some` is not quite the same as `any?` because the latter returns a Boolean\n\n```\nuser> (def any? (complement not-any?))\n#'user/any?\nuser> (some #{:a} [:a :b :c])\n:a\nuser> (any? #{:a} [:a :b :c])\ntrue\nuser> (some #{:d} [:a :b :c])\nnil\nuser> (any? #{:d} [:a :b :c])\nfalse\n```\n\nI also find `one-of?` handy:\n\n```\n(defn one-of? [x coll]\n (any? #{x} coll))\n```","created-at":1464895655850,"updated-at":1464895698716,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/200617?v=3","account-source":"github","login":"bsima"},"_id":"575088a7e4b0bafd3e2a0473"},{"body":"
     \n(not-any?   #(= \"query\"  %)   (list \"hola\" \"query\" \"fin\"))   ;false\n(not-any?   #(= \"query\"  %)   (list \"hola\" \"fin\"))           ;true\n(not-any?   #(= \"query\"  %)   (list))                        ;true\n(not-any?   #(= \"query\"  %)   nil)                           ;true\n(not-any?   #(= \"query\"  %)   '())                           ;true\n","created-at":1505952377693,"updated-at":1505952747406,"author":{"avatar-url":"https://avatars0.githubusercontent.com/u/31183833?v=4","account-source":"github","login":"abibilonilombardi"},"_id":"59c30279e4b03026fe14ea47"},{"author":{"login":"naxels","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/3195443?v=4"},"updated-at":1674408880024,"created-at":1674408880024,"body":"Here's another version for `any?`\n\n
    (def any? (comp boolean some))
    ","_id":"63cd73b0e4b08cf8563f4b69"}],"tag":"java.lang.Boolean","arglists":["pred coll"],"doc":"Returns false if (pred x) is logical true for any x in coll,\n else true.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/not-any_q"},{"added":"1.0","ns":"clojure.core","name":"into-array","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1374150173000,"author":{"login":"alilee","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2fb0196dc5a7cd3a5cc73f1b9941c209?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"to-array","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521aa7"},{"created-at":1374150354000,"author":{"login":"alilee","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2fb0196dc5a7cd3a5cc73f1b9941c209?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"make-array","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521aa8"}],"line":3469,"examples":[{"author":{"login":"ysph","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/eed512f3595f1baa31fd91f3b297ebbf?r=PG&default=identicon"},"editors":[{"login":"ysph","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/eed512f3595f1baa31fd91f3b297ebbf?r=PG&default=identicon"},{"login":"Ambrose Bonnaire-Sergeant","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/f4b6f2ea0cd9cac02ecd8101c482a41f?r=PG&default=identicon"},{"login":"Phalphalak","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a684c0fd4f27597437de953e92a15d4b?r=PG&default=identicon"},{"login":"Phalphalak","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a684c0fd4f27597437de953e92a15d4b?r=PG&default=identicon"},{"login":"Phalphalak","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a684c0fd4f27597437de953e92a15d4b?r=PG&default=identicon"},{"login":"Phalphalak","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a684c0fd4f27597437de953e92a15d4b?r=PG&default=identicon"}],"body":";; Array's component type is set to (class 2), cannot add Strings.\n;; This will result in an IllegalArgumentException\nuser=> (into-array [2 \"4\" \"8\" 5])\n;; Evaluation aborted.\n\n;; However, if the common type is specified, aforementioned values can be put into an array\nuser=> (into-array Object [2 \"4\" \"8\" 5])\n#\n\nuser=> (into-array (range 4))\n#\n\n;; if you assign a type, you still have to coerce values\nuser=> (into-array Byte/TYPE (range 4))\n;; Evaluation aborted.\n\nuser=> (into-array Byte/TYPE (map byte (range 4)))\n#","created-at":1294395323000,"updated-at":1368810887000,"_id":"542692c8c026201cdc326a25"},{"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"editors":[],"body":";; java.nio.file.Paths#get takes (String, String...)\nuser=> (java.nio.file.Paths/get \"/Users\" (into-array [\"username\" \"dev\" \"clojure\"]))\n#","created-at":1337936915000,"updated-at":1337936915000,"_id":"542692d3c026201cdc326fda"},{"author":{"login":"Phalphalak","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a684c0fd4f27597437de953e92a15d4b?r=PG&default=identicon"},"editors":[],"body":";; Creating an empty array defaults to Object[]\nuser=> (into-array [])\n#\n\n;; However, the type of an empty array can be coerced\nuser=> (into-array String [])\n#\n","created-at":1368810750000,"updated-at":1368810750000,"_id":"542692d3c026201cdc326fdb"}],"notes":null,"arglists":["aseq","type aseq"],"doc":"Returns an array with components set to the values in aseq. The array's\n component type is type if provided, or the type of the first value in\n aseq if present, or Object. All values in aseq must be compatible with\n the component type. Class objects for the primitive types can be obtained\n using, e.g., Integer/TYPE.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/into-array"},{"added":"1.9","ns":"clojure.core","name":"qualified-symbol?","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1495715117333,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"symbol?","ns":"clojure.core"},"_id":"5926cd2de4b093ada4d4d75f"},{"created-at":1495715125414,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"simple-symbol?","ns":"clojure.core"},"_id":"5926cd35e4b093ada4d4d760"},{"created-at":1507247303395,"author":{"login":"huahaiy","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/889685?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"namespace","ns":"clojure.core"},"_id":"59d6c4c7e4b03026fe14ea50"}],"line":1647,"examples":[{"updated-at":1495723309613,"created-at":1495723309613,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"body":"(qualified-symbol? 'clojure.core/symbol)\n;;=> true\n\n(qualified-symbol? 'symbol)\n;;=> nil\n\n(qualified-symbol? \"string\")\n;;=> false\n(qualified-symbol? 42)\n;;=> false\n(qualified-symbol? nil)\n;;=> false","_id":"5926ed2de4b093ada4d4d76b"}],"notes":null,"arglists":["x"],"doc":"Return true if x is a symbol with a namespace","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/qualified-symbol_q"},{"added":"1.11","ns":"clojure.core","name":"parse-long","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1775529533520,"author":{"login":"wlkr","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/5406568?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"parse-double","ns":"clojure.core"},"_id":"69d46e3d7955605a202df2a0"}],"line":8168,"examples":[{"updated-at":1698256038169,"created-at":1698256038169,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":"(parse-long \"42\")\n;; => 42\n\n(parse-long \"-42000\")\n;; => -42000\n\n(parse-long (apply str (repeat 18 \\9)))\n;; => 999999999999999999\n\n(parse-long (apply str (repeat 19 \\9)))\n;; => nil\n\n(parse-long \"42.0\")\n;; => nil\n(parse-long \"four\")\n;; => nil\n(parse-long \"\")\n;; => nil","_id":"653954a669fbcc0c226173dc"}],"notes":null,"arglists":["s"],"doc":"Parse string of decimal digits with optional leading -/+ and return a\n Long value, or nil if parse fails","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/parse-long"},{"added":"1.0","ns":"clojure.core","name":"init-proxy","file":"clojure/core_proxy.clj","type":"function","column":1,"see-alsos":[{"created-at":1539824483366,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"construct-proxy","ns":"clojure.core"},"_id":"5bc7db63e4b00ac801ed9ee2"},{"created-at":1539824665309,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"update-proxy","ns":"clojure.core"},"_id":"5bc7dc19e4b00ac801ed9ee3"}],"line":302,"examples":[{"updated-at":1539824459461,"created-at":1539824459461,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"body":";; Used as a one-off initialization for the proxy overrides when the\n;; instance was built with \"construct-proxy\".\n\n(import 'clojure.lang.IDeref)\n\n(def MyException (get-proxy-class Exception IDeref))\n\n(defn bail\n ([ex s]\n (-> ex\n (construct-proxy s)\n (init-proxy\n {\"deref\" (fn [this] (str \"Cause: \" s))})))\n ([ex s e]\n (-> ex\n (construct-proxy s e)\n (init-proxy\n {\"deref\" (fn [this] (str \"Root: \" (.getMessage e)))}))))\n\n@(bail MyException \"error\")\n;; \"Cause: error\"\n\n@(bail MyException \"s\" (RuntimeException. \"caused by root\"))\n;; \"Root: caused by root\"","_id":"5bc7db4be4b00ac801ed9ee1"}],"notes":null,"arglists":["proxy mappings"],"doc":"Takes a proxy instance and a map of strings (which must\n correspond to methods of the proxy superclass/superinterfaces) to\n fns (which must take arguments matching the corresponding method,\n plus an additional (explicit) first arg corresponding to this, and\n sets the proxy's fn map. Returns the proxy.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/init-proxy"},{"ns":"clojure.core","name":"chunk-buffer","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1443936382766,"author":{"login":"devn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"chunk-append","ns":"clojure.core"},"_id":"5610b87ee4b08e404b6c1ca1"},{"created-at":1443936387934,"author":{"login":"devn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"chunk","ns":"clojure.core"},"_id":"5610b883e4b0686557fcbd4f"}],"line":694,"examples":[{"updated-at":1443936790331,"created-at":1443936790331,"author":{"login":"devn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3"},"body":"(chunk-buffer 32)\n;; => #\n\n;; Coerce to an ArrayChunk via clojure.core/chunk, cons\n;; a chunked sequence onto it resulting in a\n;; clojure.lang.PersistentVector$ChunkedSeq, grab the first\n;; chunk to get an ArrayChunk, and pull the first element out\n;; using .nth/nth.\n(-> (chunk-buffer 32)\n (chunk)\n (chunk-cons (seq [1 2 3]))\n (chunk-first)\n (.nth 0))\n;; => 1","_id":"5610ba16e4b08e404b6c1ca2"}],"notes":null,"tag":"clojure.lang.ChunkBuffer","arglists":["capacity"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core/chunk-buffer"},{"added":"1.9","ns":"clojure.core","name":"seqable?","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1495638669315,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"seq","ns":"clojure.core"},"_id":"5925a28de4b093ada4d4d725"},{"created-at":1495638679916,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"seq?","ns":"clojure.core"},"_id":"5925a297e4b093ada4d4d726"}],"line":6281,"examples":[{"editors":[{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"}],"body":";;;; nil is seqable\n\n(seqable? nil)\n;;=> true\n\n;;;; Anything that implements CharSequence is seqable\n\n(seqable? \"\")\n;;=> true\n(seqable? (java.lang.StringBuilder.))\n;;=> true\n(seqable? (java.lang.StringBuffer.))\n;;=> true\n\n;;;; Anything that implements Seqable is seqable\n\n(seqable? [])\n;;=> true\n(seqable? {})\n;;=> true\n(seqable? #{})\n;;=> true\n(seqable? '())\n;;=> true\n(seqable? (lazy-seq))\n;;=> true\n\n;;;; Anything that implements Iterable is seqable\n\n(seqable? (java.util.ArrayList.))\n;;=> true\n(seqable? (java.util.HashMap.))\n;;=> true\n(seqable? (java.util.HashSet.))\n;;=> true\n\n;;;; Arrays are seqable\n\n(seqable? (int-array 5 1))\n;;=> true\n(seqable? (double-array 5 1.0))\n;;=> true\n(seqable? (char-array 5 \\c))\n;;=> true\n\n;;;; Some stuff that isn't seqable\n\n(seqable? true)\n;;=> false\n(seqable? \\c)\n;;=> false\n(seqable? 1)\n;;=> false\n(seqable? 1.0)\n;;=> false\n(seqable? (fn f []))\n;;=> false\n","author":{"avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3","account-source":"github","login":"svenschoenung"},"created-at":1495638659807,"updated-at":1495638914391,"_id":"5925a283e4b093ada4d4d724"},{"editors":[{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"}],"body":";; All collections that return true for coll? return true for seqable?\n(every? coll? [() [] #{} {} (clojure.lang.PersistentQueue/EMPTY)])\n;; => true\n(every? seqable? [() [] #{} {} (clojure.lang.PersistentQueue/EMPTY)])\n;; => true\n\n;; But some collections which are not persistent, are still seqable…\n(some coll? [(int-array [4 5 6]) (java.util.ArrayList.) (java.util.HashMap.)])\n;; => nil\n(every? seqable? [(int-array [4 5 6]) (java.util.ArrayList.) (java.util.HashMap.)])\n;; => true\n\n;; And there are some collections which aren't even directly seqable…\n(seqable? (java.nio.IntBuffer/allocate 4))\n;; => false\n\n;; But there's usually a way to get there…\n(seqable? (.array (java.nio.IntBuffer/allocate 4)))\n;; => true","author":{"avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4","account-source":"github","login":"tomdl89"},"created-at":1706796567670,"updated-at":1706796667192,"_id":"65bba61769fbcc0c22617498"}],"notes":null,"arglists":["x"],"doc":"Return true if the seq function is supported for x","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/seqable_q"},{"added":"1.0","ns":"clojure.core","name":"symbol?","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1495715056369,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"simple-symbol?","ns":"clojure.core"},"_id":"5926ccf0e4b093ada4d4d75b"},{"created-at":1495715063170,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"qualified-symbol?","ns":"clojure.core"},"_id":"5926ccf7e4b093ada4d4d75c"}],"line":564,"examples":[{"author":{"login":"dpritchett","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/147981?v=3"},"editors":[{"login":"dpritchett","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/147981?v=3"},{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":"user=> (symbol? 'a)\ntrue\nuser=> (symbol? 1)\nfalse\nuser=> (symbol? :a)\nfalse","created-at":1279075212000,"updated-at":1332949799000,"_id":"542692c8c026201cdc3269e7"}],"notes":null,"arglists":["x"],"doc":"Return true if x is a Symbol","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/symbol_q"},{"added":"1.6","ns":"clojure.core","name":"when-some","file":"clojure/core.clj","type":"macro","column":1,"see-alsos":[{"created-at":1417641526852,"author":{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/94482?v=3"},"to-var":{"ns":"clojure.core","name":"if-some","library-url":"https://github.com/clojure/clojure"},"_id":"547f7e36e4b0dc573b892fea"},{"created-at":1440455751477,"author":{"login":"brunchboy","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2228869?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"when-let","ns":"clojure.core"},"_id":"55db9c47e4b072d7f27980ee"},{"created-at":1602614544032,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"some","ns":"clojure.core"},"_id":"5f85f510e4b0b1e3652d73e0"},{"created-at":1602614575703,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"let","ns":"clojure.core"},"_id":"5f85f52fe4b0b1e3652d73e1"},{"created-at":1713009674265,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"when","ns":"clojure.core"},"_id":"661a740a69fbcc0c226174bb"}],"line":1913,"examples":[{"body":"user=> (when-some [x 1] [x :ok])\n[1 :ok]\n\nuser=> (when-some [x nil] [x :ok])\nnil","author":{"login":"Dimagog","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3"},"created-at":1423524396612,"updated-at":1423524396612,"_id":"54d9422ce4b0e2ac61831d3f"},{"body":"user=> (when-some [x \"Hello\"] (println x))\n\"Hello\"\nnil\n\nuser=> (when-some [x nil] (println x))\nnil","author":{"login":"viper110110","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1243583?v=3"},"created-at":1432756309762,"updated-at":1432756318672,"editors":[{"login":"viper110110","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1243583?v=3"}],"_id":"55662055e4b01ad59b65f4db"},{"editors":[{"login":"brunchboy","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2228869?v=3"}],"body":";; In contrast with when-let, when-some evaluates the body for false values:\n(when-some [x false] {:x x}) ; => {:x false}\n\n;; While when-let suppresses evaluation for false values:\n(when-let [x false] {:x x}) ; => nil","author":{"avatar-url":"https://avatars.githubusercontent.com/u/2228869?v=3","account-source":"github","login":"brunchboy"},"created-at":1440455542027,"updated-at":1440455687597,"_id":"55db9b76e4b0831e02cddf20"}],"macro":true,"notes":null,"arglists":["bindings & body"],"doc":"bindings => binding-form test\n\n When test is not nil, evaluates body with binding-form bound to the\n value of test","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/when-some"},{"added":"1.3","ns":"clojure.core","name":"unchecked-char","file":"clojure/core.clj","type":"function","column":1,"see-alsos":null,"line":3554,"examples":null,"notes":null,"arglists":["x"],"doc":"Coerce to char. Subject to rounding or truncation.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/unchecked-char"},{"added":"1.1","ns":"clojure.core","name":"->>","file":"clojure/core.clj","type":"macro","column":1,"see-alsos":[{"created-at":1293436689000,"author":{"login":"0x89","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/56bc4acd59315ed4dc1cb99c3be71102?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"->","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521deb"},{"created-at":1436359153901,"author":{"login":"jw-00000","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2936?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"some->>","ns":"clojure.core"},"_id":"559d19f1e4b00f9508fd66fe"},{"created-at":1510096703930,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"comp","ns":"clojure.core"},"_id":"5a023f3fe4b0a08026c48c9a"},{"created-at":1526843259499,"author":{"login":"boxxxie","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/440034?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"cond->>","ns":"clojure.core"},"_id":"5b01c77be4b045c27b7fac71"},{"created-at":1526843274587,"author":{"login":"boxxxie","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/440034?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"cond->","ns":"clojure.core"},"_id":"5b01c78ae4b045c27b7fac72"},{"created-at":1526843342457,"author":{"login":"boxxxie","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/440034?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"as->","ns":"clojure.core"},"_id":"5b01c7cee4b045c27b7fac73"}],"line":1710,"examples":[{"author":{"login":"tomoj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/854f0ed52f56be27c9919c2afaa665c2?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"tomoj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/854f0ed52f56be27c9919c2afaa665c2?r=PG&default=identicon"},{"login":"tomoj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/854f0ed52f56be27c9919c2afaa665c2?r=PG&default=identicon"},{"login":"uvtc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/34f159f89cbd1d9beac0276f5a7af552?r=PG&default=identicon"}],"body":";; An example of using the \"thread-last\" macro to get\n;; the sum of the first 10 even squares.\nuser=> (->> (range)\n (map #(* % %))\n (filter even?)\n (take 10)\n (reduce +))\n1140\n\n;; This expands to:\nuser=> (reduce +\n (take 10\n (filter even?\n (map #(* % %)\n (range)))))\n1140\n","created-at":1279952064000,"updated-at":1347320971000,"_id":"542692c8c026201cdc326a52"},{"author":{"login":"BertrandDechoux","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3"},"editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},{"login":"zenog","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8528397254e98a159c68bb0ce20eae71?r=PG&default=identicon"}],"body":"user=> (def c 5)\nuser=> (->> c (+ 3) (/ 2) (- 1)) \n3/4\n\n;; and if you are curious why\nuser=> (use 'clojure.walk)\nuser=> (macroexpand-all '(->> c (+ 3) (/ 2) (- 1)))\n(- 1 (/ 2 (+ 3 c)))\n\n","created-at":1339250191000,"updated-at":1343663486000,"_id":"542692d1c026201cdc326f40"},{"body":";; let's compare thread first (->) and thread last ( ->> )\nuser=> (macroexpand '(-> 0 (+ 1) (+ 2) (+ 3)))\n(+ (+ (+ 0 1) 2) 3)\nuser=> (macroexpand '(->> 0 (+ 1) (+ 2) (+ 3)))\n(+ 3 (+ 2 (+ 1 0)))","author":{"login":"deddu","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/3534263?v=3"},"created-at":1430351285440,"updated-at":1430351388761,"editors":[{"login":"deddu","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/3534263?v=3"}],"_id":"55416db5e4b01bb732af0a8c"},{"updated-at":1447795396746,"created-at":1447795396746,"author":{"login":"rsachdeva","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/232903?v=3"},"body":";; ->> and -> by simple string concatenation\n\n;; Effectively (str \" jmd\" \"hello\")\nuser=> (->> \"hello\" (str \" jmd\"))\n\" jmdhello\"\n\n;; Effectively (str \"hello\" \" jmd\")\nuser=> (-> \"hello\" (str \" jmd\"))\n=> \"hello jmd\"","_id":"564b9ac4e4b0538444398271"},{"editors":[{"login":"huahaiy","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/889685?v=3"}],"body":";; It is OK to omit the parentheses if a function takes only one argument\n(->> [1 2 [3 4] 5]\n flatten ; no parenthesis\n (map inc))\n=> (2 3 4 5 6)\n ","author":{"avatar-url":"https://avatars.githubusercontent.com/u/889685?v=3","account-source":"github","login":"huahaiy"},"created-at":1464376531961,"updated-at":1464377329122,"_id":"57489cd3e4b0bafd3e2a0468"},{"editors":[{"login":"huahaiy","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/889685?v=3"},{"avatar-url":"https://avatars.githubusercontent.com/u/15624487?v=4","account-source":"github","login":"pluieciel"}],"body":";; It's OK to include anonymous function in the thread, but don't forget\n;; to put in an extra pair of parentheses to call the function\n(->> [1 2 3 4 5]\n ((fn [coll] (map inc coll))) ; double parentheses\n (apply +)) \n=> 20\n\n;; the short hand form of the anonymous function works the same\n(->> [1 2 3 4 5]\n (#(map inc %)) ; double parentheses\n (apply +)) \n\n;; avoid function\n(->> [1 2 3 4 5]\n (map inc) ; single parentheses\n (apply +)) ","author":{"avatar-url":"https://avatars.githubusercontent.com/u/889685?v=3","account-source":"github","login":"huahaiy"},"created-at":1464378181434,"updated-at":1697570694338,"_id":"5748a345e4b0bafd3e2a046a"},{"editors":[{"login":"rafmagana","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/92894?v=3"}],"body":";; For large threads you can use commas (interpreted as whitespaces) \n;; to visualize where the items are going to be inserted.\n\n;; Takes the first 5 even numbers\nuser=> (->> (range)\n (filter even?)\n (take 5))\n=> (0 2 4 6 8)\n\n;; with two commas (you can use one if you prefer)\nuser=> (->> (range)\n (filter even? ,,)\n (take 5 ,,))\n=> (0 2 4 6 8)\n\n;; For instance:\n;; (filter even? ,,)\n;; means\n;; (filter even? (range))","author":{"avatar-url":"https://avatars.githubusercontent.com/u/92894?v=3","account-source":"github","login":"rafmagana"},"created-at":1464761492810,"updated-at":1464761589711,"_id":"574e7c94e4b0bafd3e2a046f"},{"editors":[{"login":"ibercode","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/31028993?v=4"}],"body":";;practical example\n\n(def entries [{:month 1 :val 12}\n {:month 2 :val 3}\n {:month 3 :val 32}\n {:month 4 :val 18}\n {:month 5 :val 32}\n {:month 6 :val 62}\n {:month 7 :val 12}\n {:month 8 :val 142}\n {:month 9 :val 52}\n {:month 10 :val 18}\n {:month 11 :val 23}\n {:month 12 :val 56}])\n(defn get-result\n [coll m]\n (->> coll\n (take-while\n #(<= (:month %) m))))\n\n(defn get-total\n [coll m]\n (->>\n (get-result coll m)\n (map #(:val %))\n (reduce +)))\n\n(get-total entries 3)\n","author":{"avatar-url":"https://avatars0.githubusercontent.com/u/31028993?v=4","account-source":"github","login":"ibercode"},"created-at":1517039587642,"updated-at":1517039791585,"_id":"5a6c2fe3e4b076dac5a728a9"},{"updated-at":1518895069987,"created-at":1518895069987,"author":{"login":"ibercode","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/31028993?v=4"},"body":"(defn new-map\n [coll]\n (->>\n coll\n (map\n (fn [[k v]]\n [k (inc v)]))\n (into {})))\n\n(new-map {:a 1 :b 2 :c 3})\n","_id":"5a887fdde4b0316c0f44f8ca"},{"updated-at":1561789924650,"created-at":1561789924650,"author":{"login":"ningDr","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/38251752?v=4"},"body":"(defn f [front a1 a2 end] (str front \"-\" a1 \"-\" a2 \"-\" end))\n(println (f 1 2 3 4))\n;; => 1-2-3-4\n(println (-> 1 (f 2 3 4)))\n;; => 1-2-3-4\n(println (->> 1 (f 2 3 4)))\n;; => 2-3-4-1","_id":"5d1705e4e4b0ca44402ef77b"},{"updated-at":1630497911164,"created-at":1630497911164,"author":{"login":"harelix","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2310608?v=4"},"body":"(->> (str \"A\") (str \"B\") (str \"C\"))\n;; => \"CBA\"\n(-> (str \"A\") (str \"B\") (str \"C\"))\n;; => \"ABC\"\n","_id":"612f6c77e4b0b1e3652d7537"}],"macro":true,"notes":[{"updated-at":1280212250000,"body":"I'm getting: `Exception in thread \"main\" java.lang.Exception: Unable to resolve symbol: ->> in this context (11.clj:25)`\r\n\r\nIt's also extremely hard to Google this method. It'd be nice if there was a non-symbol name for this that one could search for.\r\n\r\n**Update**\r\n\r\nThe name of this operator is called a thrush.","created-at":1280193441000,"author":{"login":"Jacolyte","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1703a0c3ed358b787f4b1bf3b2799472?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521f8b"},{"updated-at":1280208986000,"body":"See also -> which is similar but threads the first expr as the second argument of the forms.","created-at":1280208986000,"author":{"login":"steveminer","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d28543d134185d12d4006a74738d233e?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521f8f"},{"updated-at":1280211630000,"body":"My error was due to using an old version of Clojure. I was using 1.0.0.","created-at":1280211630000,"author":{"login":"Jacolyte","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1703a0c3ed358b787f4b1bf3b2799472?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521f90"},{"updated-at":1400187256000,"body":"There is something I don't get : in the case \"form\" is a seq, why should we write\r\n... (with-meta `(~(first form) ~@(next form) ~x) (meta form))\r\n\r\nand not \r\n... (with-meta `(~@form ~x) (meta form))\r\n\r\nas items order in \"form\" is not changed ?\r\n\r\n","created-at":1400187256000,"author":{"login":"nmichel","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/7c68edbc73c1d48f86e5c5f642fff93f?r=PG&default=identicon"},"_id":"542692edf6e94c6970522026"},{"author":{"login":"nzl-nott","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/458621?v=3"},"updated-at":1445935991335,"created-at":1445935991335,"body":"\"See also -> which is similar but threads the first expr as the second argument of the forms.\"\n\nThis is incorrect, it is not the second ARGUMENT, but the second ITEM.","_id":"562f3b77e4b04b157a6648da"}],"arglists":["x & forms"],"doc":"Threads the expr through the forms. Inserts x as the\n last item in the first form, making a list of it if it is not a\n list already. If there are more forms, inserts the first form as the\n last item in second form, etc.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/->>"},{"added":"1.1","ns":"clojure.core","name":"future-cancel","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"to-var":{"library-url":"https://github.com/clojure/clojure","name":"future","ns":"clojure.core"},"author":{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},"created-at":1339252235000,"_id":"542692eaf6e94c6970521afb"},{"to-var":{"library-url":"https://github.com/clojure/clojure","name":"future?","ns":"clojure.core"},"author":{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},"created-at":1339252240000,"_id":"542692eaf6e94c6970521afc"},{"to-var":{"library-url":"https://github.com/clojure/clojure","name":"future-cancelled?","ns":"clojure.core"},"author":{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},"created-at":1339252246000,"_id":"542692eaf6e94c6970521afd"},{"to-var":{"library-url":"https://github.com/clojure/clojure","name":"future-done?","ns":"clojure.core"},"author":{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},"created-at":1339252256000,"_id":"542692eaf6e94c6970521afe"}],"line":7147,"examples":[{"updated-at":1339252267000,"created-at":1339252267000,"body":"\nuser=> (def f (future (Thread/sleep 5000) (inc 0)))\n#'user/f\n\nuser=> (future-cancel f) \ntrue\n\nuser=> (future-cancelled? f) \ntrue","editors":[],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},"_id":"542692d3c026201cdc326fb3"},{"updated-at":1339252313000,"created-at":1339252313000,"body":"\nuser=> (def f (future (inc 0)))\n#'user/f\n\nuser=> (future-cancel f) \nfalse\n\nuser=> (future-cancelled? f) \nfalse","editors":[],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},"_id":"542692d3c026201cdc326fb4"},{"updated-at":1749992812809,"created-at":1749992812809,"author":{"login":"jimka2001","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/6414129?v=4"},"body":";; Inside the future, you can detect that a call to `future-cancel` \n;; was made from outside. This idiom should allow you to clean up\n;; temp files, kill sub-futures etc.\n(let [f (future (try (doseq [r (range)]\n (Thread/sleep 1000))\n (catch InterruptedException e (println (str\n \"caught exception: \" \n (.getMessage e))))))]\n\n (Thread/sleep 3000)\n (future-cancel f))","_id":"684ec56ccd84df5de54e2089"}],"notes":null,"arglists":["f"],"doc":"Cancels the future, if possible.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/future-cancel"},{"added":"1.0","ns":"clojure.core","name":"var-get","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1331249138000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.core","name":"with-local-vars","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521da4"},{"created-at":1461815751940,"author":{"login":"cloojure","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7083783?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"var-set","ns":"clojure.core"},"_id":"572189c7e4b0fc95a97eab5d"},{"created-at":1550004152087,"author":{"login":"cljlc","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/36645452?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"var","ns":"clojure.core"},"_id":"5c632fb8e4b0ca44402ef67e"}],"line":4353,"examples":[{"editors":[{"login":"cljlc","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/36645452?v=4"}],"updated-at":1550004271931,"created-at":1423523052402,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3","account-source":"github","login":"Dimagog"},"body":"user=> map\n#\n\nuser=> #'map ;; The reader macro #'x expands to (var x).\n#'clojure.core/map\n\nuser=> (var-get #'map)\n#","_id":"54d93cece4b0e2ac61831d3a"},{"updated-at":1550004358930,"created-at":1550004358930,"author":{"login":"cljlc","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/36645452?v=4"},"body":"user=> ((var-get (var inc)) 1)\n2","_id":"5c633086e4b0ca44402ef680"},{"updated-at":1648664740399,"created-at":1648664740399,"author":{"login":"huahaiy","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/889685?v=4"},"body":";; var-get is the same as @\nuser> (def a-var 1)\n#'user/a-var\nuser> (var-get #'a-var)\n1\nuser> @#'a-var\n1\nuser> (var-get (resolve 'a-var))\n1\nuser> @(resolve 'a-var)\n1","_id":"6244a0a4e4b0b1e3652d75c5"}],"notes":null,"arglists":["x"],"doc":"Gets the value in the var object","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/var-get"},{"added":"1.0","ns":"clojure.core","name":"commute","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1364879943000,"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"ref","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b4c"},{"created-at":1432239819741,"author":{"login":"Kejia","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1039073?v=3"},"to-var":{"ns":"clojure.core","name":"alter","library-url":"https://github.com/clojure/clojure"},"_id":"555e3ecbe4b03e2132e7d16a"},{"created-at":1432239835490,"author":{"login":"Kejia","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1039073?v=3"},"to-var":{"ns":"clojure.core","name":"dosync","library-url":"https://github.com/clojure/clojure"},"_id":"555e3edbe4b03e2132e7d16b"}],"line":2439,"examples":[{"author":{"login":"leifp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d2f37720f063404ef83b987d2824353d?r=PG&default=identicon"},"editors":[],"body":"user=> (def counter (ref 0))\n#'user/counter\n\n;; deciding whether to increment the counter takes the terribly long time\n;; of 100 ms -- it is decided by committee.\nuser=> (defn commute-inc! [counter]\n (dosync (Thread/sleep 100) (commute counter inc)))\n#'user/commute-inc!\nuser=> (defn alter-inc! [counter]\n (dosync (Thread/sleep 100) (alter counter inc)))\n#'user/alter-inc!\n\n;; what if n people try to hit the counter at once?\nuser=> (defn bombard-counter! [n f counter]\n (apply pcalls (repeat n #(f counter))))\n#'user/bombard-counter!\n\n;; first, use alter. Everyone is trying to update the counter, and\n;; stepping on each other's toes, so almost every transaction is getting \n;; retried lots of times:\nuser=> (dosync (ref-set counter 0))\n0\nuser=> (time (doall (bombard-counter! 20 alter-inc! counter)))\n\"Elapsed time: 2007.049224 msecs\"\n(3 1 2 4 7 10 5 8 6 9 13 14 15 12 11 16 17 20 18 19)\n;; note that it took about 2000 ms = (20 workers * 100 ms / update)\n\n;; now, since it doesn't matter what order people update a counter in, we\n;; use commute:\nuser=> (dosync (ref-set counter 0))\n0\nuser=> (time (doall (bombard-counter! 20 commute-inc! counter)))\n\"Elapsed time: 401.748181 msecs\"\n(1 2 3 4 5 9 10 6 7 8 11 15 13 12 14 16 19 17 18 20)\n;; notice that we got actual concurrency this time.","created-at":1342530933000,"updated-at":1342530933000,"_id":"542692d2c026201cdc326f63"},{"editors":[{"login":"danielgerigk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/9052027?v=3"}],"body":"; Note that commute will ALWAYS run the update function TWICE. \n; Example courtesy of \"Clojure for the Brave and True\"\n; https://github.com/flyingmachine/brave-clojure-web\n\n(defn sleep-print-update\n [sleep-time thread-name update-fn]\n (fn [state]\n (Thread/sleep sleep-time)\n (println (str thread-name \": \" state))\n (update-fn state)))\n\n(def counter (ref 0))\n(future (dosync (commute counter (sleep-print-update 100 \"Commute Thread A\" inc))))\n(future (dosync (commute counter (sleep-print-update 150 \"Commute Thread B\" inc))))\n\n; printed output is:\nCommute Thread A: 0 ; (after 100ms)\nCommute Thread B: 0 ; (after 150ms)\nCommute Thread A: 0 ; (after 200ms)\nCommute Thread B: 1 ; (after 300ms)\n","author":{"avatar-url":"https://avatars.githubusercontent.com/u/7083783?v=3","account-source":"github","login":"cloojure"},"created-at":1446615365082,"updated-at":1451344876442,"_id":"56399945e4b04b157a6648e5"}],"notes":[{"updated-at":1295818063000,"body":"Note to understand the difference to 'alter':\r\n\r\nCommute should be used when it doesn't matter whether anyone else has changed (altered or commuted) the ref using a successful transaction. This often implies that this ref is not affected by any conditions, i.e. it should be changed the same way no matter what. (thanks to raek for clarifying that for me)","created-at":1295818063000,"author":{"login":"dedeibel","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e89e54d864f1e584c5ef4102f98bc83?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fb1"},{"updated-at":1316668674000,"body":"In the concurrency video RH explains that commute is useful for actions where the order in which they alter the value doesn't matter, e.g. incrementing a counter.","created-at":1316668674000,"author":{"login":"m0wfo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/f4e90ce9fdf9e968587c7f9bec94721e?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fcd"}],"arglists":["ref fun & args"],"doc":"Must be called in a transaction. Sets the in-transaction-value of\n ref to:\n\n (apply fun in-transaction-value-of-ref args)\n\n and returns the in-transaction-value of ref.\n\n At the commit point of the transaction, sets the value of ref to be:\n\n (apply fun most-recently-committed-value-of-ref args)\n\n Thus fun should be commutative, or, failing that, you must accept\n last-one-in-wins behavior. commute allows for more concurrency than\n ref-set.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/commute"},{"added":"1.0","ns":"clojure.core","name":"coll?","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1357786211000,"author":{"login":"juan.facorro","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d6f59d93cc17c698f16e550034a2d1ad?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"seq?","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f37"},{"created-at":1357786229000,"author":{"login":"juan.facorro","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d6f59d93cc17c698f16e550034a2d1ad?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"list?","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f38"},{"created-at":1357786244000,"author":{"login":"juan.facorro","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d6f59d93cc17c698f16e550034a2d1ad?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"sequential?","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f39"},{"created-at":1414509285263,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"},"to-var":{"ns":"clojure.core","name":"map?","library-url":"https://github.com/clojure/clojure"},"_id":"544fb2e5e4b0dc573b892fae"},{"created-at":1414509297944,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"},"to-var":{"ns":"clojure.core","name":"vector?","library-url":"https://github.com/clojure/clojure"},"_id":"544fb2f1e4b03d20a1024289"},{"created-at":1414509320242,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"},"to-var":{"ns":"clojure.core","name":"set?","library-url":"https://github.com/clojure/clojure"},"_id":"544fb308e4b0dc573b892faf"}],"line":6269,"examples":[{"updated-at":1444295715914,"created-at":1280775820000,"body":";; a map is a collection\n(coll? {})\n;;=> true\n\n;; a set is a collection\n(coll? #{})\n;;=> true\n\n;; a vector is a collection\n(coll? [])\n;;=> true\n\n;; a list is a collection \n(coll? '())\n;;=> true\n\n;; a number (long) is not a collection\n(coll? 4)\n;;=> false\n\n;; a string is not a collection\n(coll? \"fred\")\n;;=> false\n\n;; ...but a string sequence is a collection\n(coll? (seq \"fred\"))\n;;=> true\n\n;; a boolean is not a collection\n(coll? true)\n;;=> false\n\n;; nil is not a collection\n(coll? nil)\n;;=> false\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"avatar-url":"https://avatars2.githubusercontent.com/u/22608?v=4","account-source":"github","login":"MrHus"},{"avatar-url":"https://avatars.githubusercontent.com/u/138993?v=3","account-source":"github","login":"Dimagog"},{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2","account-source":"github","login":"phreed"},{"avatar-url":"https://avatars.githubusercontent.com/u/40178?v=3","account-source":"github","login":"muhuk"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3","account-source":"github","login":"devn"},"_id":"542692cfc026201cdc326e40"},{"author":{"login":"kumarshantanu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/39f90a6c0ffe4995fb9dff4fb6b6bad6?r=PG&default=identicon"},"editors":[],"body":"user=> (coll? {:a 10 :b 20}) ; map is a collection of map-entries\ntrue","created-at":1290278420000,"updated-at":1290278420000,"_id":"542692cfc026201cdc326e44"},{"author":{"login":"gregginca","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bad5f5cb177b0968d4288596691ec3cd?r=PG&default=identicon"},"editors":[{"login":"dcj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/c18c35f1747ce57b4c1114cb12d600b1?r=PG&default=identicon"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=3"}],"body":";; contrast to example code for sequential?\n;;\nuser> (coll? '(1 2 3))\ntrue\nuser> (coll? [1 2 3])\ntrue\nuser> (coll? (range 1 5))\ntrue\nuser> (coll? 1)\nfalse\nuser> (coll? {:a 2 :b 1}) \ntrue\nuser> (coll? {:a 2 :b 1}) ; in contrast to sequential?, coll? returns true for\n ; a hash map\ntrue\nuser> (sequential? {:a 2 :b 1})\nfalse","created-at":1334018852000,"updated-at":1423811493909,"_id":"542692d2c026201cdc326f61"},{"editors":[{"login":"Crowbrammer","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/19522656?v=4"}],"body":";; I had major bugs before I realized `seq?` doesn't like vectors.\n\nuser=> (seq? [1 2 3])\nfalse\nuser=> (coll? [1 2 3])\ntrue\n","author":{"avatar-url":"https://avatars0.githubusercontent.com/u/19522656?v=4","account-source":"github","login":"Crowbrammer"},"created-at":1611002403798,"updated-at":1611002470366,"_id":"6005f223e4b0b1e3652d7436"}],"notes":null,"arglists":["x"],"doc":"Returns true if x implements IPersistentCollection","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/coll_q"},{"added":"1.2","ns":"clojure.core","name":"get-in","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1318010512000,"author":{"login":"jks","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/de50bee3396570d25f900873303c98f1?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"assoc-in","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ce6"},{"created-at":1318010548000,"author":{"login":"jks","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/de50bee3396570d25f900873303c98f1?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"update-in","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ce7"},{"created-at":1360286942000,"author":{"login":"AtKaaZ","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e10dfa345f44b0fe72bbe081fd51b83?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"find","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ce8"},{"created-at":1360286946000,"author":{"login":"AtKaaZ","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e10dfa345f44b0fe72bbe081fd51b83?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"get","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ce9"},{"created-at":1412262512260,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"},"to-var":{"ns":"clojure.core","name":"->","library-url":"https://github.com/clojure/clojure"},"_id":"542d6a70e4b05f4d257a2989"},{"created-at":1602017675512,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"some->","ns":"clojure.core"},"_id":"5f7cd98be4b0b1e3652d73ca"}],"line":6205,"examples":[{"author":{"login":"tomoj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/854f0ed52f56be27c9919c2afaa665c2?r=PG&default=identicon"},"editors":[{"login":"tomoj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/854f0ed52f56be27c9919c2afaa665c2?r=PG&default=identicon"},{"login":"tomoj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/854f0ed52f56be27c9919c2afaa665c2?r=PG&default=identicon"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":";; We can use get-in for reaching into nested maps:\nuser=> (def m {:username \"sally\"\n :profile {:name \"Sally Clojurian\"\n :address {:city \"Austin\" :state \"TX\"}}})\n#'user/m\n\nuser=> (get-in m [:profile :name])\n\"Sally Clojurian\"\nuser=> (get-in m [:profile :address :city])\n\"Austin\"\nuser=> (get-in m [:profile :address :zip-code])\nnil\nuser=> (get-in m [:profile :address :zip-code] \"no zip code!\")\n\"no zip code!\"\n\n\n;; Vectors are also associative:\nuser=> (def v [[1 2 3]\n [4 5 6]\n [7 8 9]])\n#'user/v\nuser=> (get-in v [0 2])\n3\nuser=> (get-in v [2 1])\n8\n\n\n;; We can mix associative types:\nuser=> (def mv {:username \"jimmy\"\n :pets [{:name \"Rex\"\n :type :dog}\n {:name \"Sniffles\"\n :type :hamster}]})\n#'user/mv\nuser=> (get-in mv [:pets 1 :type])\n:hamster\n","created-at":1279953166000,"updated-at":1285497184000,"_id":"542692c7c026201cdc3269af"},{"author":{"login":"octopusgrabbus","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/fd31b8bcea99fa7b0711fbc424587774?r=PG&default=identicon"},"editors":[],"body":"(def s1 [[:000-00-0000 \"TYPE 1\" \"JACKSON\" \"FRED\"]\n [:000-00-0001 \"TYPE 2\" \"SIMPSON\" \"HOMER\"]\n [:000-00-0002 \"TYPE 4\" \"SMITH\" \"SUSAN\"]])\n\n(def cols [0 2 3])\n\n(defn f1 \n [s1 col] \n (map #(get-in s1 [% col] nil) (range (count s1))))\n\n(apply interleave (map (partial f1 s1) cols))\n\n(:000-00-0000 \"JACKSON\" \"FRED\" :000-00-0001 \"SIMPSON\" \"HOMER\" :000-00-0002 \"SMITH\" \"SUSAN\")","created-at":1334887763000,"updated-at":1334887763000,"_id":"542692d3c026201cdc326fc1"},{"author":{"login":"fitswell","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/12550cf0cd2d5a801d70ec1bf282e8ba?r=PG&default=identicon"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":";; spam link removed","created-at":1377540628000,"updated-at":1379291978000,"_id":"542692d3c026201cdc326fc2"},{"body":";; Introduction of references is jarring to get-in usage\n\n(def owners [{:owner \"Jimmy\"\n :pets (ref [{:name \"Rex\"\n :type :dog}\n {:name \"Sniffles\"\n :type :hamster}])} \n {:owner \"Jacky\" \n :pets (ref [{:name \"Spot\" \n :type :mink}\n {:name \"Puff\" \n :type :magic-dragon}])}])\n;;=> 'user/owners\n\n(get-in owners [0 :pets])\n;;=> #\n\n;; In order to go deeper the get needs to be split \n;; as the deref cannot be used as part of the get.\n(-> (get-in owners [0 :pets]) deref (get-in [1 :type]))\n;;=> :hamster\n\n;; At this point it clear that the thread operator \n;; can be used to produce similar results. \n(-> owners (nth 0) :pets deref (nth 1) :type)\n;;=> :hamster","author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"},"created-at":1412262392950,"updated-at":1412262454783,"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"}],"_id":"542d69f8e4b05f4d257a2986"},{"body":";; If the nested structure contains list, it does not work, because list is \n;; not an associative structure.\n(def a {:a '({:b1 2} {:b2 4}) :c 3})\n;;=> 'user/a\n(get-in a [:a 0 :b1])\n;;=> nil\n\n;; However, if the nested structure contains a vector then it does work.\n(def a1 {:a [{:b1 2} {:b2 4}] :c 3})\n;; => 'user/a1\n\n(get-in a1 [:a 0 :b1])\n;; => 2","author":{"login":"huahaiy","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/889685?v=3"},"created-at":1416104154689,"updated-at":1583283192336,"editors":[{"login":"huahaiy","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/889685?v=3"},{"avatar-url":"https://avatars2.githubusercontent.com/u/4922694?v=4","account-source":"github","login":"Jeel-Shah"}],"_id":"546808dae4b03d20a10242a7"},{"updated-at":1514431489291,"created-at":1514431489291,"author":{"login":"titonbarua","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/13497834?v=4"},"body":";; If an empty sequence is used as keys, the whole structure is returned.\n(get-in {:a 1 :b 2} [])\n;;=> {:a 1, :b 2}\n(get-in {:a 1, :b 2} '())\n;;=> {:a 1, :b 2}\n\n;; nil also counts as an empty sequence!\n(get-in {:a 1 :b 2} nil)\n;;=> {:a 1, :b 2}\n\n;; Be careful if you use a nill-able key sequence with not-found value.\n;; This can be a source of bug.\n(get-in {:a 1 :b 2} nil :nothing)\n;;=> {:a 1, :b 2}","_id":"5a446401e4b0a08026c48ce3"},{"editors":[{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"}],"body":";;practical example\n\n(def employee\n {:name \"John\"\n :details {:email \"info@domain.com\"\n :phone \"555-144-300\"}})\n\n(get-in employee [:details :email])\n;;\"info@domain.com\"","author":{"avatar-url":"https://avatars0.githubusercontent.com/u/31028993?v=4","account-source":"github","login":"ibercode"},"created-at":1518296458140,"updated-at":1524762235792,"_id":"5a7f5d8ae4b0316c0f44f8b6"},{"editors":[{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"}],"body":";; Difference between nil values vs non-existing keys, and default values\n;; In this case, we don't know what will be the `:b` in our map,\n;; so attempting to guard with a 0 default value.\n(pos? (get-in {:a {:b 42}} [:a :b] 0)) ;=> 42 -> true (as expected)\n(pos? (get-in {:a nil} [:a :b] 0)) ;=> 0 -> false, no key (as expected)\n(pos? (get-in {:a {:b nil}} [:a :b] 0)) ;=> nil -> NPE (misleading code)\n(pos? (or (get-in {:a {:b nil}} [:a :b]) 0)) ;=> false (works but ugly)\n\n;; Better to use `some->` for such situations\n(some-> {:a {:b nil}} :a :b pos?) ;=> nil (YAY!)\n(some-> {:a {}} :a :b pos?) ;=> nil\n(some-> {:a {:b 42}} :a :b pos?) ;=> true\n","author":{"avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4","account-source":"github","login":"MicahElliott"},"created-at":1602017645815,"updated-at":1602017774458,"_id":"5f7cd96de4b0b1e3652d73c9"}],"notes":null,"arglists":["m ks","m ks not-found"],"doc":"Returns the value in a nested associative structure,\n where ks is a sequence of keys. Returns nil if the key\n is not present, or the not-found value if supplied.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/get-in"},{"added":"1.0","ns":"clojure.core","name":"fnext","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1348637428000,"author":{"login":"dansalmo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e33ee460f5f61bc5ba9b598934766215?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"ffirst","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d68"},{"created-at":1374512076000,"author":{"login":"alilee","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2fb0196dc5a7cd3a5cc73f1b9941c209?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"second","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d69"},{"created-at":1437661659830,"author":{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/94482?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"next","ns":"clojure.core"},"_id":"55b0f9dbe4b0080a1b79cda9"},{"created-at":1482183723442,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"nnext","ns":"clojure.core"},"_id":"5858542be4b004d3a355e2bd"},{"created-at":1482183735219,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"nfirst","ns":"clojure.core"},"_id":"58585437e4b004d3a355e2be"},{"created-at":1482184193486,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"first","ns":"clojure.core"},"_id":"58585601e4b004d3a355e2c7"}],"line":114,"examples":[{"author":{"login":"zmila","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/68dd6f50915854aa04fefcf4d6fa5c8e?r=PG&default=identicon"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":"user=> (fnext ['(a b c) '(b a c)])\n(b a c) \n\nuser=> (fnext '([a b c] [b a c]))\n[b a c] \n\nuser=> (fnext {:a 1 :b 2 :c 3})\n[:b 2] \n\nuser=> (fnext [])\nnil \n\nuser=> (fnext [1])\nnil","created-at":1280347120000,"updated-at":1332952453000,"_id":"542692ccc026201cdc326ca5"}],"notes":[{"author":{"login":"glts","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/1483271?v=4"},"updated-at":1520169710053,"created-at":1520169710053,"body":"Synonym of `second`.","_id":"5a9bf2eee4b0316c0f44f90a"}],"arglists":["x"],"doc":"Same as (first (next x))","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/fnext"},{"added":"1.2","ns":"clojure.core","name":"denominator","file":"clojure/core.clj","static":true,"type":"function","column":1,"see-alsos":[{"created-at":1401510175000,"author":{"login":"abrooks","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/69976?v=2"},"to-var":{"ns":"clojure.core","name":"numerator","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b91"}],"line":3616,"examples":[{"author":{"login":"shockbob","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon"},"editors":[],"body":";; denominator always returns the denominator of the reduced fraction\n;;\nuser=> (denominator (/ 2 3))\n3\nuser=> (denominator (/ 3 6))\n2\nuser=> (map denominator [(/ 3 2) (/ 2 3) (/ 4 5) (/ 4 6)])\n(2 3 5 3)\nuser=>","created-at":1313489509000,"updated-at":1313489509000,"_id":"542692ccc026201cdc326c35"}],"notes":null,"tag":"java.math.BigInteger","arglists":["r"],"doc":"Returns the denominator part of a Ratio.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/denominator"},{"added":"1.1","ns":"clojure.core","name":"bytes","file":"clojure/core.clj","type":"function","column":1,"see-alsos":[{"created-at":1334358122000,"author":{"login":"Havvy","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e799a79441c7543be48562403411cd13?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"byte-array","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c11"},{"created-at":1590885248124,"author":{"login":"huahaiy","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/889685?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"bytes?","ns":"clojure.core"},"_id":"5ed2fb80e4b087629b5a1921"}],"line":5406,"examples":[{"author":{"login":"leifp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d2f37720f063404ef83b987d2824353d?r=PG&default=identicon"},"editors":[{"avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4","account-source":"github","login":"phreed"},{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"}],"body":";; for fast interop\n(bytes (byte-array (map (comp byte int) \"ascii\")))\n;=> #\n(def the-bytes *1)\n;=> #'user/the-bytes\n(set! *warn-on-reflection* true)\n(defn get-byte [the-bytes i] (aget the-bytes i))\n;=> #'user/get-byte Reflection warning, NO_SOURCE_PATH:1 - call to aget can't be resolved.\n\n(defn get-byte [the-bytes i] \n (let [the-bytes (bytes the-bytes)] \n (aget the-bytes i)))\n;=> #'user/get-byte\n(get-byte the-bytes 0)\n;=> 97\n","created-at":1342528870000,"updated-at":1683029591856,"_id":"542692d2c026201cdc326f5e"},{"updated-at":1656674284283,"created-at":1656674284283,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":";; byte-array will convert where possible\n(byte-array [127 128 129]);; => [127, -128, -127]\n\n;; bytes will not\n(try (bytes [127 128 129])\n (catch ClassCastException e (ex-message e)))\n;; => \"clojure.lang.PersistentVector cannot be cast to [B\"\n","_id":"62bed7ece4b0b1e3652d7618"}],"notes":[{"updated-at":1369546475000,"body":"Why is the `(comp byte int)` required in the example? This seems to work just as well:\r\n\r\n
    \r\nuser=> (def b (bytes (byte-array (map byte \"ascii\"))))\r\nuser=> (String. b)\r\n\"ascii\"\r\n
    ","created-at":1369546475000,"author":{"login":"Brian Marick","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a523012f661f603806ab1c22d855216f?r=PG&default=identicon"},"_id":"542692edf6e94c6970522002"},{"updated-at":1369546620000,"body":"For that matter, why is the `bytes` needed? Consider:\r\n\r\n
    \r\nuser=> (String. (byte-array (map byte \"ascii\")))\r\n\"ascii\"\r\n
    \r\n","created-at":1369546620000,"author":{"login":"Brian Marick","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a523012f661f603806ab1c22d855216f?r=PG&default=identicon"},"_id":"542692edf6e94c6970522003"},{"updated-at":1402388003000,"body":"AFAIK, `bytes` is used for referring to `bytes[].class` from JAVA\r\n\r\nExample (midje):\r\n\r\n (fact (class (.getBytes \"test\")) => bytes) ; true\r\n","created-at":1402388003000,"author":{"login":"xcthulhu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/81c9adff485c35b7fdbbefe29589585a?r=PG&default=identicon"},"_id":"542692edf6e94c6970522028"}],"arglists":["xs"],"doc":"Casts to bytes[]","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/bytes"},{"added":"1.0","ns":"clojure.core","name":"refer-clojure","file":"clojure/core.clj","type":"macro","column":1,"see-alsos":[{"created-at":1327515371000,"author":{"login":"mmwaikar","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/29d36f4c9f39c9f8ff61c07033b13118?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"refer","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f4c"}],"line":5875,"examples":[{"author":{"login":"juergenhoetzel","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2736dfffc803c704dcf25b45ff63cede?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":";; Prevent namespace conflicts like:\n\n;; `WARNING: time already refers to: #'clojure.core/time in namespace: \n;; time, being replaced by: #'time/time`\n\nuser=> (ns time\n (:refer-clojure :exclude [time]))\n\n(defn time []\n (System/nanoTime))\n","created-at":1279945839000,"updated-at":1285497447000,"_id":"542692c8c026201cdc326a5f"},{"updated-at":1472145548582,"created-at":1472145548582,"author":{"login":"mars0i","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1836941?v=3"},"body":";; Copied from https://gist.github.com/jkk/284230 (ns-cheatsheet.clj):\n\n;; Excludes built-in print\n(:refer-clojure :exclude [print])\n\n;; Excludes all built-ins except print\n(:refer-clojure :only [print])\n\n;; Renames built-in print to core-print\n(:refer-clojure :rename {print core-print})","_id":"57bf288ce4b0709b524f04d4"}],"macro":true,"notes":null,"arglists":["& filters"],"doc":"Same as (refer 'clojure.core )","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/refer-clojure"},{"ns":"clojure.core.async","name":"Pub","file":"clojure/core/async.clj","type":"var","column":1,"see-alsos":null,"line":918,"examples":null,"notes":null,"arglists":[],"doc":null,"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.async/Pub"},{"ns":"clojure.core.async","name":"reduce","file":"clojure/core/async.clj","type":"function","column":1,"see-alsos":[{"created-at":1449944303196,"author":{"login":"jhn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/678798?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"merge","ns":"clojure.core.async"},"_id":"566c64efe4b08a3916795379"},{"created-at":1449944322632,"author":{"login":"jhn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/678798?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"map","ns":"clojure.core.async"},"_id":"566c6502e4b08a391679537a"},{"created-at":1449944389839,"author":{"login":"jhn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/678798?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"into","ns":"clojure.core.async"},"_id":"566c6545e4b09a2675a0ba75"}],"line":636,"examples":[{"editors":[{"login":"jhn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/678798?v=3"}],"body":"(require '[clojure.core.async :as async])\n\n;; some expensive io call\n(defn expensive-call [m] \n (Thread/sleep 2000) m)\n\n(->> [{:a 1} {:b 2} {:c 3} {:d 4}]\n (map (fn [m] \n (async/thread \n (expensive-call m)))) ; creates a thread per call\n (async/merge) ; merges the 4 chans returned into 1\n (async/reduce merge {}) ; reduces items in chan with merge\n (async/ {:a 1, :c 3, :b 2, :d 4}","author":{"avatar-url":"https://avatars.githubusercontent.com/u/678798?v=3","account-source":"github","login":"jhn"},"created-at":1449944130683,"updated-at":1449944487124,"_id":"566c6442e4b09a2675a0ba74"},{"updated-at":1449945764111,"created-at":1449945764111,"author":{"login":"jhn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/678798?v=3"},"body":"(require '[clojure.core.async :as async])\n\n(def c \n (async/to-chan (range 10)))\n\n(async/ 45","_id":"566c6aa4e4b08a391679537b"},{"updated-at":1528275453855,"created-at":1528275453855,"author":{"login":"agodde","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/18694682?v=4"},"body":"(require '[clojure.core.async :as async])\n\n; define a channel which yields a predefined value after a timeout\n; (function 'f' of async/reduce won't be called)\n(def c\n (async/reduce f :predefined-value (async/timeout 10000)))\n\n(async/ :predefined-value","_id":"5b17a1fde4b00ac801ed9e0e"}],"notes":null,"arglists":["f init ch"],"doc":"f should be a function of 2 arguments. Returns a channel containing\n the single result of applying f to init and the first item from the\n channel, then applying f to that result and the 2nd item, etc. If\n the channel closes without yielding items, returns init and f is not\n called. ch must close before reduce produces a result.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.async/reduce"},{"ns":"clojure.core.async","name":"remove>","file":"clojure/core/async.clj","type":"function","skip-wiki":true,"column":1,"see-alsos":null,"line":1147,"examples":null,"deprecated":"0.1.319.0-6b1aca-alpha","notes":null,"arglists":["p ch"],"doc":"Deprecated - this function will be removed. Use transducer instead","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.async/remove>"},{"ns":"clojure.core.async","name":"timeout","file":"clojure/core/async.clj","type":"function","column":1,"see-alsos":null,"line":111,"examples":[{"body":"user=> (go-loop [seconds (atom 0)\n add-seconds! #(swap! seconds + %)]\n (println \"Waiting 1 second\")\n (\n\n;; Waiting 1 second\n\n;; Waiting 2 seconds\n\n;; Waited 3 seconds\n","author":{"login":"runexec","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1487241?v=2"},"created-at":1412204562718,"updated-at":1412204562718,"_id":"542c8812e4b05f4d257a2979"},{"body":"user=> (doseq [n (range 10)\n :let [i (-> n\n inc\n range\n rand-nth)]] \n (go\n ( #'user/t \n(poll! t) ;; before AND after timeout\n;;=> nil\n\n(a/put! t 'foo) ;; before timeout\n=> true\n(a/poll! t)\n=> foo\n(a/poll! t)\n=> nil\n(a/put! t 'foo) ;; after timeout\n=> false\n\n;; You COULD use a timeout-channel as a normal channel.\n;; The preferred option however would be using alts!!\n(let [timout-chan (timeout 1000)\n comms-chan (chan 10 (map inc) #(log/error % \"whoops\")) ;; genuine channel\n [val port] (alts!! [timeout-chan\n some-other-chan])]\n (cond\n (= port timeout-chan)\n (throw (TimeoutException. \"Tooooo late.\"))\n\n (and (= port comms-chan) (int? val))\n (log/infof \"SMOOOoooth %d\" val)\n \n :else\n (throw (IllegalStateException. \"Well.. shit.\")))))","_id":"619ba064e4b0b1e3652d7579"}],"notes":[{"body":"*Never* close! the channel returned by timeout -- this is an unwritten rule. \n\nThe implementation sometimes will use an existing timeout channel, if it is within a few ms of the desired timeout. Closing the channel will affect multiple otherwise unrelated CSPs that may be blocked/parked waiting for the channel to close.\n\nIn our application, we saw this as spurious \"timed out after waiting X ms\" messages when the logged timestamps didn't support this possibility.\n\nThanks to Ryan Neufeld for identifying this!","created-at":1418342154119,"updated-at":1418342154119,"author":{"login":"hlship","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/52660?v=3"},"_id":"548a2f0ae4b04e93c519ffa3"},{"author":{"login":"raymcdermott","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/120437?v=3"},"updated-at":1454937406809,"created-at":1454937406809,"body":"Might be obvious but this construct is preferred in go blocks over Thread/sleep as it does not block","_id":"56b8953ee4b060004fc217be"}],"arglists":["msecs"],"doc":"Returns a channel that will close after msecs","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.async/timeout"},{"ns":"clojure.core.async","name":"unsub*","type":"function","see-alsos":null,"examples":null,"notes":null,"tag":null,"arglists":["p v ch"],"doc":null,"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.async/unsub*"},{"ns":"clojure.core.async","name":"admix*","type":"function","see-alsos":null,"examples":null,"notes":null,"tag":null,"arglists":["m ch"],"doc":null,"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.async/admix*"},{"ns":"clojure.core.async","name":"unmix*","type":"function","see-alsos":null,"examples":null,"notes":null,"tag":null,"arglists":["m ch"],"doc":null,"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.async/unmix*"},{"ns":"clojure.core.async","name":"mix","file":"clojure/core/async.clj","type":"function","column":1,"see-alsos":[{"created-at":1414157132485,"author":{"login":"jw-00000","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2936?v=2"},"to-var":{"ns":"clojure.core.async","name":"merge","library-url":"https://github.com/clojure/clojure"},"_id":"544a534ce4b03d20a1024278"},{"created-at":1477622634105,"author":{"login":"aaronj1331","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/349712?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"admix","ns":"clojure.core.async"},"_id":"5812bb6ae4b024b73ca35a17"},{"created-at":1477622639828,"author":{"login":"aaronj1331","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/349712?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"unmix","ns":"clojure.core.async"},"_id":"5812bb6fe4b024b73ca35a18"},{"created-at":1477622650504,"author":{"login":"aaronj1331","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/349712?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"unmix-all","ns":"clojure.core.async"},"_id":"5812bb7ae4b024b73ca35a19"},{"created-at":1477622656517,"author":{"login":"aaronj1331","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/349712?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"toggle","ns":"clojure.core.async"},"_id":"5812bb80e4b024b73ca35a1a"},{"created-at":1477622662278,"author":{"login":"aaronj1331","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/349712?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"solo-mode","ns":"clojure.core.async"},"_id":"5812bb86e4b024b73ca35a1b"}],"line":816,"examples":[{"body":"user=> (def ch-out (chan))\n#'user/ch-out\n\nuser=> (def mix-out (mix ch-out))\n#'user/mix-out\n\nuser=> (def ch-example1 (chan))\n#'user/ch-example1\n\nuser=> (def ch-example2 (chan))\n#'user/ch-example2\n\nuser=> (admix mix-out ch-example1)\ntrue\n\nuser=> (admix mix-out ch-example2)\ntrue\n\nuser=> (put! ch-example1 \"sent to chan 1\")\ntrue\n\nuser=> (put! ch-example2 \"sent to chan 2\")\ntrue\n\nuser=> ( ( (def c (chan 1))\n#'user/c\n\nuser=> (def sub-c (pub c :route))\n#'user/sub-c\n\nuser=> (def cx (chan 1))\n#'user/cx\n\nuser=> (sub sub-c :up-stream cx)\n#\n\nuser=> (def cy (chan 1))\n#'user/cy\n\nuser=> (sub sub-c :down-stream cy)\n#\n\nuser=> (go-loop [_ (\n\nuser=> (go-loop [_ (\n\nuser=> (put! c {:route :up-stream :data 123})\ntrue\nGot something coming up!\n\nuser=> (put! c {:route :down-stream :data 123})\nGot something going down!\ntrue\n","author":{"login":"runexec","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1487241?v=2"},"created-at":1412174292506,"updated-at":1412188913552,"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"_id":"542c11d4e4b05f4d257a2964"},{"updated-at":1475768259165,"created-at":1475768259165,"author":{"login":"freckletonj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8399149?v=3"},"body":"(def news (chan 1))\n(def shouter (pub news :topics))\n\n(def alice (chan 1))\n(def bob (chan 1))\n(def clyde (chan 1))\n\n(sub shouter :celebrity-gossip alice)\n(sub shouter :space-x bob)\n(sub shouter :space-x clyde)\n\n(go-loop [heard ( nil\n:alice - Alice says Hi!\n:bob - Bob says Hi!\n:alice - Alice says Hi again","editors":[{"avatar-url":"https://avatars0.githubusercontent.com/u/156290?v=4","account-source":"github","login":"milelo"}],"_id":"5f93ef45e4b0b1e3652d73ed"},{"editors":[{"login":"jdf-id-au","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/9016301?v=4"}],"body":"(defn pub-test\n \"Check how one topic subscription can block others.\"\n [bufsize]\n (let [out (chan)\n out-pub (if (zero? bufsize)\n (async/pub out first)\n (async/pub out first (fn [topic] (async/buffer bufsize))))\n blocking-sub (chan)\n blocked-sub (chan)]\n (async/sub out-pub :blocking blocking-sub)\n (async/sub out-pub :blocked blocked-sub)\n ; no sub so doesn't block pub:\n (doseq [n (range 5)] (async/put! out [:ignored n]))\n ; blocking-sub blocks blocked-sub until consumed or buffered:\n (doseq [n (range 5)] (async/put! out [:blocking n]))\n (doseq [n (range 5)] (async/put! out [:blocked n]))\n ; don't consume last three put!s on blocking-sub:\n (dotimes [n 2] (async/take! blocking-sub tap>))\n ; close!ing blocking-sub here unblocks blocked-sub\n ; (async/close! blocking-sub)\n (dotimes [n 5] (async/take! blocked-sub tap>))))\n\n(pub-test 0) ; blocks because 5 pub - 0 buffer - 1 on inner chan - 2 take > 0 left\n[:blocking 0]\n[:blocking 1]\n=> nil\n(pub-test 1) ; blocks because 5 - 1 - 1 - 2 > 0\n[:blocking 0]\n[:blocking 1]\n=> nil\n(pub-test 2) ; doesn't block because 5 - 2 - 1 - 2 = 0\n[:blocking 0]\n[:blocking 1]\n[:blocked 0]\n[:blocked 1]\n[:blocked 2]\n[:blocked 3]\n[:blocked 4]\n=> nil","author":{"avatar-url":"https://avatars.githubusercontent.com/u/9016301?v=4","account-source":"github","login":"jdf-id-au"},"created-at":1618977551159,"updated-at":1618977807505,"_id":"607fa30fe4b0b1e3652d74c7"},{"updated-at":1655787209524,"created-at":1655787209524,"author":{"login":"CalebMacdonaldBlack","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/5868450?v=4"},"body":"(def news (chan 1))\n\n(def shouter (pub news :topics))\n\n(def alice (chan 1))\n(def bob (chan 1))\n(def clyde (chan 1))\n\n(sub shouter :gossip alice)\n(sub shouter :space bob)\n(sub shouter :space clyde)\n\n(go-loop []\n (prn \"Alice heard: \" (!","ns":"clojure.core.async"},"_id":"571e7b43e4b0fc95a97eab56"}],"line":140,"examples":[{"body":"user=> (def c (chan 1))\n#'user/c\n\nuser=> (go-loop [data ( \" data)\n (println \"No recur. Won't print again\"))\n\n#\n\nuser=> (put! c \"Example Async Data\")\n\nnil\n\nWaited for => Example Async Data\nNo recur. Won't print again\n\nuser=> (put! c \"Example Async Data\")\nnil\n","author":{"login":"runexec","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1487241?v=2"},"created-at":1412145281681,"updated-at":1412197165245,"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"_id":"542ba081e4b05f4d257a2956"},{"body":";; Clojure 1.7\nuser=> (let [c (chan 1 (filter pos?))]\n \n (go-loop []\n (let [nums ( (def cx\n (to-chan\n (range 10)))\n#'user/cx\n\nuser=> (def cy\n (to-chan\n (range -10 0)))\n#'user/cy\n\nuser=> (def mapped-chans\n (clojure.core.async/map + [cx cy]))\n#'user/mapped-chans\n\n;;\nuser=> ( ( ( ( ( ( ( ( ( ( (","file":"clojure/core/async.clj","type":"function","skip-wiki":true,"column":1,"see-alsos":null,"line":1193,"examples":null,"deprecated":"0.1.319.0-6b1aca-alpha","notes":null,"arglists":["f out","f out buf-or-n"],"doc":"Deprecated - this function will be removed. Use transducer instead","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.async/mapcat>"},{"ns":"clojure.core.async","name":"buffer","file":"clojure/core/async.clj","type":"function","column":1,"see-alsos":[{"created-at":1451399869777,"author":{"login":"ljosa","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/197881?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"dropping-buffer","ns":"clojure.core.async"},"_id":"56829abde4b01f598e267e96"},{"created-at":1464291617409,"author":{"login":"eduardobull","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/6353416?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"sliding-buffer","ns":"clojure.core.async"},"_id":"57475121e4b0bafd3e2a0460"},{"created-at":1464291767701,"author":{"login":"eduardobull","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/6353416?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"chan","ns":"clojure.core.async"},"_id":"574751b7e4b0bafd3e2a0463"}],"line":58,"examples":[{"body":"user=> (def c (chan (buffer 3)))\n#'user/c\n\nuser=> (go (\n\nuser=> (doseq [_ (range 5)] (println (>!! c true)))\ntrue\ntrue\ntrue\nUnblocking buffer\ntrue\ntrue\nnil","author":{"login":"runexec","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1487241?v=2"},"created-at":1412149213685,"updated-at":1412188866844,"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"_id":"542bafdde4b05f4d257a295d"}],"notes":null,"arglists":["n"],"doc":"Returns a fixed buffer of size n. When full, puts will block/park.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.async/buffer"},{"ns":"clojure.core.async","name":"close!","file":"clojure/core/async.clj","type":"function","column":1,"see-alsos":[{"created-at":1464291803969,"author":{"login":"eduardobull","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/6353416?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"chan","ns":"clojure.core.async"},"_id":"574751dbe4b0af2c9436d1f7"}],"line":214,"examples":[{"editors":[{"login":"cloojure","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/7083783?v=4"}],"body":"(let [c (chan 2) ]\n (>!! c 1)\n (>!! c 2)\n (close! c)\n (println (!! c 1))","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/8271291?v=4","account-source":"github","login":"ertugrulcetin"},"created-at":1521203986699,"updated-at":1537832241555,"_id":"5aabbb12e4b0316c0f44f927"},{"editors":[{"login":"nvseenu","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/4986865?v=4"}],"body":";; Below example demonstrates go processes can take values (which were already put)\n;; from the unbuffered channel even after closing it.\n\n (let [c (chan)]\n (go (>! c 1))\n (go (>! c 2))\n ;; channel is closed even before \"2\" value is taken out. \n (go ( nil (it does not block even though there is no buffer!)\n\n(let [c (chan 1)]\n (offer! c 42))\n;;=> true","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/8271291?v=4","account-source":"github","login":"ertugrulcetin"},"created-at":1521204479205,"updated-at":1569062333646,"_id":"5aabbcffe4b0316c0f44f929"}],"notes":null,"arglists":["port val"],"doc":"Puts a val into port if it's possible to do so immediately.\n nil values are not allowed. Never blocks. Returns true if offer succeeds.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.async/offer!"},{"ns":"clojure.core.async","name":"chan","file":"clojure/core/async.clj","type":"function","column":1,"see-alsos":[{"created-at":1412171784700,"author":{"login":"halgari","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/654621?v=2"},"to-var":{"ns":"clojure.core.async","name":"buffer","library-url":"https://github.com/clojure/clojure"},"_id":"542c0808e4b05f4d257a295f"},{"created-at":1412171799578,"author":{"login":"halgari","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/654621?v=2"},"to-var":{"ns":"clojure.core.async","name":"dropping-buffer","library-url":"https://github.com/clojure/clojure"},"_id":"542c0817e4b05f4d257a2960"},{"created-at":1412171810126,"author":{"login":"halgari","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/654621?v=2"},"to-var":{"ns":"clojure.core.async","name":"sliding-buffer","library-url":"https://github.com/clojure/clojure"},"_id":"542c0822e4b05f4d257a2961"},{"created-at":1632011320526,"author":{"login":"didibus","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/601540?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"promise-chan","ns":"clojure.core.async"},"_id":"61468438e4b0b1e3652d7541"}],"line":83,"examples":[{"body":"user=> (def c (chan))\n#'user/c\nuser=> (def c (chan 1))\n#'user/c\nuser=> (def c (chan (buffer 2)))\n#'user/c\n;; Clojure 1.7\nuser=> (def c (chan 1 (filter string?)))\n#'user/c\n\n","author":{"login":"runexec","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1487241?v=2"},"created-at":1412149437066,"updated-at":1412149437066,"_id":"542bb0bde4b05f4d257a295e"},{"updated-at":1521204822665,"created-at":1521204822665,"author":{"login":"ertugrulcetin","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/8271291?v=4"},"body":"(let [c (chan 3 (map inc))] ;; providing transducer which increments values by one\n (>!! c 1)\n (>!! c 2)\n (>!! c 3)\n (println ( nil","_id":"5aabbe56e4b0316c0f44f92c"},{"updated-at":1611141061096,"created-at":1611141061096,"author":{"login":"liuchong","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/236058?v=4"},"body":"(def c (chan (buffer 1)\n (fn [xf] (fn [_ data]\n (throw (Exception. (when (= data \"hehe\")\n \"xform error\")))))\n (fn [e] (.getMessage e))))\n\n(>!! c \"hehe\")\n;;=> true\n\n;; any non-nil return value from transducer will be placed in the channel\n( \"xform error\"\n\n(>!! c \"haha\")\n;;=> true\n\n;; nil return value from transducer will NOT be placed in the channel\n( #'user/c\n(>!! c (range 3))\n;;=> true\n\n(loop [x ( #object[clojure.core.async.impl.channels.ManyToManyChannel...\n\n;; When provisioning more items than the channel buffer allows,\n;; mapcat will still put all items\n\n(>!! c (range 5))\n;;=> true\n;;0\n;;1\n;;2\n;;3\n;;4\n\n;; Avoid that with a dropping/sliding buffer:\n(def c (chan (sliding-buffer 3) (mapcat identity)))\n;;=> #'user/c\n(go-loop ...)\n;;=> #object[clojure.core.async.impl.channels.ManyToManyChannel...\n(>!! c (range 5))\n;;=> true\n;;2\n;;3\n;;4","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/24317401?v=4","account-source":"github","login":"loeschzwerg"}],"_id":"617ac388e4b0b1e3652d755d"}],"notes":null,"arglists":["","buf-or-n","buf-or-n xform","buf-or-n xform ex-handler"],"doc":"Creates a channel with an optional buffer, an optional transducer\n (like (map f), (filter p) etc or a composition thereof), and an\n optional exception-handler. If buf-or-n is a number, will create\n and use a fixed buffer of that size. If a transducer is supplied a\n buffer must be specified. ex-handler must be a fn of one argument -\n if an exception occurs during transformation it will be called with\n the Throwable as an argument, and any non-nil return value will be\n placed in the channel.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.async/chan"},{"ns":"clojure.core.async","name":"solo-mode*","type":"function","see-alsos":null,"examples":null,"notes":null,"tag":null,"arglists":["m mode"],"doc":null,"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.async/solo-mode*"},{"ns":"clojure.core.async","name":"onto-chan!","file":"clojure/core/async.clj","type":"function","column":1,"see-alsos":null,"line":673,"examples":null,"notes":null,"arglists":["ch coll","ch coll close?"],"doc":"Puts the contents of coll into the supplied channel.\n\n By default the channel will be closed after the items are copied,\n but can be determined by the close? parameter.\n\n Returns a channel which will close after the items are copied.\n\n If accessing coll might block, use onto-chan!! instead","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.async/onto-chan!"},{"ns":"clojure.core.async","name":"tap","file":"clojure/core/async.clj","type":"function","column":1,"see-alsos":[{"created-at":1420501362780,"author":{"login":"schmee","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/3405586?v=3"},"to-var":{"ns":"clojure.core.async","name":"mult","library-url":"https://github.com/clojure/clojure"},"_id":"54ab2172e4b09260f767ca88"},{"created-at":1420501451535,"author":{"login":"schmee","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/3405586?v=3"},"to-var":{"ns":"clojure.core.async","name":"untap","library-url":"https://github.com/clojure/clojure"},"_id":"54ab21cbe4b09260f767ca8b"}],"line":792,"examples":[{"body":"user=> (def sz 20)\n#'user/sz\n\nuser=> (def c (chan sz))\n#'user/c\n\nuser=> (def mult-c (mult c))\n#'user/mult-c\n\nuser=> (def cx (chan sz))\n#'user/cx\n\nuser=> (def cy (chan sz))\n#'user/cy\n\nuser=> (def cz (chan sz))\n#'user/cz\n\nuser=> (tap mult-c cx)\n#\n\nuser=> (tap mult-c cy)\n#\n\nuser=> (tap mult-c cz)\n#\n\nuser=> (put! c \"sent to all\")\ntrue\n\nuser=> ( ( ( (doseq [n (range 10)\n :let [i (-> n\n inc\n range\n rand-nth)]] \n (go\n ( (.getPlacePredictions ^js/google.maps.places.AutocompleteService \n svc {:input x})\n (get-place-predictions {:input x})\n ! and alt!/alts!\n channel operations within the body will block (if necessary) by\n 'parking' the calling thread rather than tying up an OS thread (or\n the only JS thread when in ClojureScript). Upon completion of the\n operation, the body will be resumed.\n\n go blocks should not (either directly or indirectly) perform operations\n that may block indefinitely. Doing so risks depleting the fixed pool of\n go block threads, causing all go block processing to stop. This includes\n core.async blocking ops (those ending in !!) and other blocking IO.\n\n Returns a channel which will receive the result of the body when\n completed","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.async/go"},{"ns":"clojure.core.async","name":"admix","file":"clojure/core/async.clj","type":"function","column":1,"see-alsos":[{"created-at":1477622395408,"author":{"login":"aaronj1331","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/349712?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"unmix","ns":"clojure.core.async"},"_id":"5812ba7be4b024b73ca35a0b"},{"created-at":1477622401065,"author":{"login":"aaronj1331","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/349712?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"unmix-all","ns":"clojure.core.async"},"_id":"5812ba81e4b024b73ca35a0c"},{"created-at":1477622405500,"author":{"login":"aaronj1331","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/349712?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"mix","ns":"clojure.core.async"},"_id":"5812ba85e4b024b73ca35a0d"}],"line":886,"examples":[{"body":"user=> (def ch-out (chan))\n#'user/ch-out\n\nuser=> (def mix-out (mix ch-out))\n#'user/mix-out\n\nuser=> (def ch-example1 (chan))\n#'user/ch-example1\n\nuser=> (def ch-example2 (chan))\n#'user/ch-example2\n\nuser=> (admix mix-out ch-example1)\ntrue\n\nuser=> (admix mix-out ch-example2)\ntrue\n\nuser=> (put! ch-example1 \"sent to chan 1\")\ntrue\n\nuser=> (put! ch-example2 \"sent to chan 2\")\ntrue\n\nuser=> ( ( 11\n\n;; Similar to `promise` and `future`, after a value has been delivered to the\n;; promise-chan, taking from it will continue to return that value immediately\n;; over and over\n\n(def inc-promise (inc-async 10))\n\n( 11\n( 11\n( 11\n\n;; That means unlike other channels, only one value can be put into a promise-chan, and \n;; taking from it afterwards will always return that value which is cached by the \n;; promise-chan, similar to what a promise or a future would.\n\n;; This makes using `promise-chan` very similar to async/await style of programming.\n;; You can create an async function by having a function return a promise-chan\n;; where it will `put!` (deliver) the value to it asynchronously as I showed with\n;; inc-async.\n\n;; You can then use `go` blocks like you'd mark `async` functions, and inside them\n;; use ` (def c (chan))\n#'user/c\n\nuser=> (onto-chan c (range 100))\n#\n\nuser=> ( ( ( false\n(identical? in-ch out-ch)\n;; => false\n","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/590297?v=4","account-source":"github","login":"jayzawrotny"},"created-at":1516398991682,"updated-at":1516399003356,"_id":"5a62698fe4b0a08026c48d05"}],"deprecated":"1.2","notes":null,"arglists":["ch coll","ch coll close?"],"doc":"Deprecated - use onto-chan! or onto-chan!!","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.async/onto-chan"},{"ns":"clojure.core.async","name":"to-chan","file":"clojure/core/async.clj","type":"function","column":1,"see-alsos":null,"line":711,"examples":[{"body":"user=> (def c (to-chan (range 10)))\n#'user/c\nuser=> ( ( ( (!! c x)\n (println \"Sent: \" x)))\n (println \"Done\")\n (future (dotimes [x 3]\n (println \"Got: \" ( (def c\n (clojure.core.async/into [:a :b :c]\n (to-chan\n (range 10))))\n#'user/c\n\nuser=> (!!","file":"clojure/core/async.clj","type":"function","column":1,"see-alsos":[{"created-at":1458597749932,"author":{"login":"royalaid","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2439803?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":">!","ns":"clojure.core.async"},"_id":"56f06f75e4b09295d75dbf39"},{"created-at":1458597770460,"author":{"login":"royalaid","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2439803?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"put!","ns":"clojure.core.async"},"_id":"56f06f8ae4b07ac9eeceed12"},{"created-at":1461615278468,"author":{"login":"cloojure","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7083783?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":" (>!! c \"Blocking - not in go-block\")\ntrue\nuser=> (!!:\n\"...Use the clojure.core.async.go-checking flag to detect invalid use (see\n namespace docs).\" see [github](https://github.com/clojure/core.async/blob/6450a57caa69b0eabee2e648893ee8f44ed7ac33/src/main/clojure/clojure/core/async.clj#L303)","_id":"63055985e4b0b1e3652d764a"}],"arglists":["port val"],"doc":"puts a val into port. nil values are not allowed. Will block if no\n buffer space is available. Returns true unless port is already closed.\n Not intended for use in direct or transitive calls from (go ...) blocks.\n Use the clojure.core.async.go-checking flag to detect invalid use (see\n namespace docs).","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.async/>!!"},{"ns":"clojure.core.async","name":"to-chan!","file":"clojure/core/async.clj","type":"function","column":1,"see-alsos":null,"line":690,"examples":null,"notes":null,"arglists":["coll"],"doc":"Creates and returns a channel which contains the contents of coll,\n closing when exhausted.\n\n If accessing coll might block, use to-chan!! instead","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.async/to-chan!"},{"ns":"clojure.core.async","name":"alt!","file":"clojure/core/async.clj","type":"macro","column":1,"see-alsos":[{"created-at":1417715418353,"author":{"login":"hlship","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/52660?v=3"},"to-var":{"ns":"clojure.core.async","name":"alts!","library-url":"https://github.com/clojure/clojure"},"_id":"54809edae4b03d20a10242c1"}],"line":387,"examples":[{"body":";; attempts to put trade on channel trade-ch within 1 second.\n;; yields :timed-out or :sent.\n\n(let [timeout-ch (timeout 1000)]\n (alt!\n timeout-ch :timed-out\n ;; note use of double-nested vector; [trade-ch trade]\n ;; would be interpreted as two channels to take from, resulting\n ;; in an odd error.\n [[trade-ch trade]] :sent))","author":{"login":"hlship","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/52660?v=3"},"created-at":1415724033428,"updated-at":1415724033428,"_id":"54623c01e4b0dc573b892fc3"},{"body":"(def trade-ch (chan))\n\n(go-loop []\n (\n (alt!\n [[trade-ch trade]] :sent\n timeout-ch :timed-out)\n print))) ;;eval this at will\n\n\n;;printout example\ncore.js[38]:\t\n:sent\ncore.js[38]:\t\n100\ncore.js[38]:\t\n100\ncore.js[38]:\t\n:sent\ncore.js[38]:\t\n:timed-out\ncore.js[38]:\t\n:timed-out\ncore.js[38]:\t\n:timed-out\ncore.js[38]:\t\n:timed-out\ncore.js[38]:\t\n:timed-out\ncore.js[38]:\t\n:timed-out\ncore.js[38]:\t\n:sent\ncore.js[38]:\t\n100\n\n\n\n","author":{"login":"boxxxie","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/440034?v=3"},"created-at":1418228084201,"updated-at":1418228084201,"_id":"54887174e4b09260f767ca75"},{"editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/1293832?v=3","account-source":"github","login":"spiralman"},{"login":"liuchong","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/236058?v=4"}],"updated-at":1636540050398,"created-at":1420914102914,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/1293832?v=3","account-source":"github","login":"spiralman"},"body":";; Reading from multiple channels, handling whichever gets data first\n(use 'clojure.core.async)\n\n(def result-chan (chan))\n\n(def error-chan (chan))\n\n(def dont-care-chan (chan))\n\n(go\n (alt!\n result-chan ([result] (println (str \"Success: \" result)))\n error-chan ([error] (println (str \"Error: \" error)))\n dont-care-chan (println \"Don't care about the value!\")))\n\n;; Given\n(put! result-chan \"Some result\")\n\n;; Output\n;; Success: Some result\n\n;; Given\n(put! error-chan \"Some error\")\n\n;; Output\n;; Error: Some error\n\n;; Given\n(put! dont-care-chan \"Some value\")\n\n;; Output\n;; Don't care about the value!","_id":"54b16db6e4b0e2ac61831ca5"},{"editors":[{"login":"cstml","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/29694576?v=4"}],"body":"(require [clojure.core.async :as a])\n(let [|a (a/chan)\n |b (a/chan)]\n\n (a/go\n (let [winner (a/alt! |a ([v] (do (println (str v \" won!\")) v))\n |b ([v] (do (println (str v \" won!\")) v)))]\n (println winner)))\n (a/put! |a :a)\n (a/put! |b :b))\n\n;; 1st run\n;; :a won!\n;; :a\n\n;; 2nd run\n;; :b won!\n;; :b\n\n;; etc.","author":{"avatar-url":"https://avatars.githubusercontent.com/u/29694576?v=4","account-source":"github","login":"cstml"},"created-at":1737497276623,"updated-at":1737497318945,"_id":"67901abccd84df5de54e2073"}],"macro":true,"notes":[{"author":{"login":"jzwolak","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/285725?v=4"},"updated-at":1661540240745,"created-at":1661540240745,"body":"alt! does not take a vector of ports as per alts!. alts! takes a vector of ports. alt! takes a _literal_ vector of ports _only_. Any symbol containing a value that is a vector of ports will not work with alt! even though such a value will work with alts!.\n\n
    \n(ns examples.failing-async\n  (:require [clojure.core.async :refer [chan go alt! >! alts!]]))\n\n(def c1 (chan))\n(def c2 (chan))\n(def two-chans [c1 c2])\n\n(println (vector? two-chans))\n\n; Fails\n(go (loop []\n      (alt! two-chans ([v c] (println \"got v =\" v)))\n      (recur)))\n\n(go (>! c1 \"hi on alt! two-chans\"))\n\n; Succeeds (must comment out above failing code for this to work)\n(go (loop []\n      (alt! [c1 c2] ([v c] (println \"got v =\" v)))\n      (recur)))\n\n(go (>! c1 \"hi on alt! [c1 c2]\"))\n\n; Succeeds\n(go (loop []\n      (let [[v c] (alts! two-chans)]\n        (println \"got v =\" v))\n      (recur)))\n\n(go (>! c1 \"hi on alts! two-chans\"))\n
    \n","_id":"63091790e4b0b1e3652d7653"}],"arglists":["& clauses"],"doc":"Makes a single choice between one of several channel operations,\n as if by alts!, returning the value of the result expr corresponding\n to the operation completed. Must be called inside a (go ...) block.\n\n Each clause takes the form of:\n\n channel-op[s] result-expr\n\n where channel-ops is one of:\n\n take-port - a single port to take\n [take-port | [put-port put-val] ...] - a vector of ports as per alts!\n :default | :priority - an option for alts!\n\n and result-expr is either a list beginning with a vector, whereupon that\n vector will be treated as a binding for the [val port] return of the\n operation, else any other expression.\n\n (alt!\n [c t] ([val ch] (foo ch val))\n x ([v] v)\n [[out val]] :wrote\n :default 42)\n\n Each option may appear at most once. The choice and parking\n characteristics are those of alts!.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.async/alt!"},{"ns":"clojure.core.async","name":"pipeline","file":"clojure/core/async.clj","type":"function","column":1,"see-alsos":[{"created-at":1462612004334,"author":{"login":"tyano","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/271573?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"pipeline-async","ns":"clojure.core.async"},"_id":"572db024e4b0b27c121b214b"},{"created-at":1462612021225,"author":{"login":"tyano","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/271573?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"pipeline-blocking","ns":"clojure.core.async"},"_id":"572db035e4b039e78aadabfa"}],"line":577,"examples":[{"editors":[{"login":"freckletonj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8399149?v=3"}],"body":";; SIMPLE EXAMPLE -----------------------\n\n(def ca (chan 1))\n(def cb (chan 1))\n\n(pipeline\n 4 ; thread count, i prefer egyptian cotton\n cb ; to\n (filter even?) ; transducer\n ca ; from\n )\n\n(doseq [i (range 10)]\n (go (>! ca i)))\n(go-loop []\n (println ( prints even numbers in 0-10, note: not necessarily in order\n\n\n\n","author":{"avatar-url":"https://avatars.githubusercontent.com/u/8399149?v=3","account-source":"github","login":"freckletonj"},"created-at":1475709906229,"updated-at":1475710233062,"_id":"57f58bd2e4b0709b524f0521"},{"editors":[{"login":"freckletonj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8399149?v=3"}],"body":";; EXTENDED EXAMPLE ---------------------------\n\n(def ca (chan 1))\n(def cb (chan 1))\n\n(pipeline\n 4 \n cb \n (filter (fn [x]\n (if (> x 100)\n (throw (Throwable. \"too big!\"))\n (even? x)))) \n ca \n false ; should it close when `from` runs out?\n (fn [error] (println \"ahhh: \" (.getMessage error))))\n\n\n(doseq [i (range 10)]\n (go (>! ca i)))\n(go-loop []\n (println (! ca 101)) ; this one throws an error\n","author":{"avatar-url":"https://avatars.githubusercontent.com/u/8399149?v=3","account-source":"github","login":"freckletonj"},"created-at":1475710315800,"updated-at":1475710444653,"_id":"57f58d6be4b0709b524f0523"}],"notes":null,"arglists":["n to xf from","n to xf from close?","n to xf from close? ex-handler"],"doc":"Takes elements from the from channel and supplies them to the to\n channel, subject to the transducer xf, with parallelism n. Because\n it is parallel, the transducer will be applied independently to each\n element, not across elements, and may produce zero or more outputs\n per input. Outputs will be returned in order relative to the\n inputs. By default, the to channel will be closed when the from\n channel closes, but can be determined by the close? parameter. Will\n stop consuming the from channel if the to channel closes. Note this\n should be used for computational parallelism. If you have multiple\n blocking operations to put in flight, use pipeline-blocking instead,\n If you have multiple asynchronous operations to put in flight, use\n pipeline-async instead. See chan for semantics of ex-handler.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.async/pipeline"},{"ns":"clojure.core.async","name":"sub","file":"clojure/core/async.clj","type":"function","column":1,"see-alsos":[{"created-at":1414157561892,"author":{"login":"jw-00000","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2936?v=2"},"to-var":{"ns":"clojure.core.async","name":"pub","library-url":"https://github.com/clojure/clojure"},"_id":"544a54f9e4b03d20a1024279"}],"line":978,"examples":[{"body":"user=> (def c (chan 1))\n#'user/c\n\nuser=> (def sub-c (pub c :route))\n#'user/sub-c\n\nuser=> (def cx (chan 1))\n#'user/cx\n\nuser=> (sub sub-c :up-stream cx)\n#\n\nuser=> (def cy (chan 1))\n#'user/cy\n\nuser=> (sub sub-c :down-stream cy)\n#\n\nuser=> (go-loop [_ (\n\nuser=> (go-loop [_ (\n\nuser=> (put! c {:route :up-stream :data 123})\ntrue\nGot something coming up!\n\nuser=> (put! c {:route :down-stream :data 123})\nGot something going down!\ntrue\n","author":{"login":"runexec","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1487241?v=2"},"created-at":1412174270351,"updated-at":1412188965721,"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"_id":"542c11bee4b05f4d257a2963"},{"updated-at":1603550036673,"created-at":1603550036673,"author":{"login":"milelo","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/156290?v=4"},"body":"(defn monitor! [publisher topic]\n (let [ nil\n:alice - Alice says Hi!\n:bob - Bob says Hi!\n:alice - Alice says Hi again","_id":"5f943b54e4b0b1e3652d73f4"}],"notes":null,"arglists":["p topic ch","p topic ch close?"],"doc":"Subscribes a channel to a topic of a pub.\n\n By default the channel will be closed when the source closes,\n but can be determined by the close? parameter.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.async/sub"},{"ns":"clojure.core.async","name":"go-loop","file":"clojure/core/async.clj","type":"macro","column":1,"see-alsos":[{"created-at":1435079791878,"author":{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/94482?v=3"},"to-var":{"ns":"clojure.core","name":"loop","library-url":"https://github.com/clojure/clojure"},"_id":"5589946fe4b05f167dcf2340"},{"created-at":1506702187689,"author":{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/94482?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"go","ns":"clojure.core.async"},"_id":"59ce736be4b03026fe14ea4e"}],"line":502,"examples":[{"body":"(go-loop [seconds 1]\n ( (def c (chan 1))\n#'user/c\n\nuser=> (go-loop []\n (let [x (\n\nuser=> (doseq [n (range 3)] (put! c n))\nnil\nGot a value in this loop: 0\nGot a value in this loop: 1\nGot a value in this loop: 2\n","author":{"login":"runexec","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1487241?v=2"},"created-at":1412204771239,"updated-at":1412204771239,"_id":"542c88e3e4b05f4d257a297b"}],"macro":true,"notes":null,"arglists":["bindings & body"],"doc":"Like (go (loop ...))","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.async/go-loop"},{"ns":"clojure.core.async","name":"map>","file":"clojure/core/async.clj","type":"function","skip-wiki":true,"column":1,"see-alsos":null,"line":1113,"examples":null,"deprecated":"0.1.319.0-6b1aca-alpha","notes":null,"arglists":["f ch"],"doc":"Deprecated - this function will be removed. Use transducer instead","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.async/map>"},{"ns":"clojure.core.async","name":"pipe","file":"clojure/core/async.clj","type":"function","column":1,"see-alsos":null,"line":507,"examples":[{"body":"user=> (def cx (chan 1))\n#'user/cx\n\nuser=> (def cy (chan 1))\n#'user/cy\n\nuser=> (pipe cx cy)\n#\n\nuser=> (put! cx \"Going into CX\")\ntrue\n\nuser=> ( (def ch-1 (async/chan 10))\n#'user/ch-1\n\nuser> (def ch-2 (async/chan 10))\n#'user/ch-2\n\n;; start a thread that takes from channel 1, sleeping after each take\nuser> (async/thread\n (loop []\n (when-let [v (async/ (async/thread\n (loop []\n (when-let [v (async/ (async/pipe ch-1 ch-2)\n#object[clojure.core.async.impl.channels.ManyToManyChannel ...]\n\n;; lets try to add a new listener to channel 1.\nuser> (async/thread\n (loop []\n (when-let [v (async/ (async/thread\n (doseq [x (range 10)]\n (async/>!! ch-1 x)\n (Thread/sleep 500)))\n#object[clojure.core.async.impl.channels.ManyToManyChannel ...]\n\nch-1 taker got 0\nch-2 taker got 1\nsecond ch-1 taker got 2\nch-2 taker got 3\nch-1 taker got 4\nch-2 taker got 5\nsecond ch-1 taker got 6\nch-2 taker got 7\nch-1 taker got 8\nch-2 taker got 9\n\n;; so a pipe is just a listener that tries to take from the from channel\n;; and put onto the to channel, a pipe does dot restrict the ability to \n;; *take* from the *from* channel.","editors":[{"avatar-url":"https://avatars2.githubusercontent.com/u/1413969?v=4","account-source":"github","login":"beoliver"}],"_id":"59f59c41e4b0a08026c48c85"},{"editors":[{"login":"ferdinand-beyer","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/23474334?v=4"}],"body":";;;; pipe is especially useful in combination with channel transducers,\n;;;; to transform items in a channel.\n\n;; Some input channel.\n(def input (to-chan (range 10)))\n\n;; Create a channel with all items from input transformed. Here, we\n;; create a transducer that multiplies by 5.\n;; Note that pipe returns the to channel.\n(def transformed (pipe input (chan 1 (map (partial * 5)))))\n\n;; Read transformed channel into a vector.\n(as/ [0 5 10 15 20 25 30 35 40 45]","author":{"avatar-url":"https://avatars.githubusercontent.com/u/23474334?v=4","account-source":"github","login":"ferdinand-beyer"},"created-at":1627285655574,"updated-at":1627285703564,"_id":"60fe6897e4b0b1e3652d751e"}],"notes":[{"author":{"login":"jayzawrotny","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/590297?v=4"},"updated-at":1517207457129,"created-at":1517207457129,"body":"Returns the `to` channel argument.","_id":"5a6ebfa1e4b0c974fee49d12"}],"arglists":["from to","from to close?"],"doc":"Takes elements from the from channel and supplies them to the to\n channel. By default, the to channel will be closed when the from\n channel closes, but can be determined by the close? parameter. Will\n stop consuming the from channel if the to channel closes","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.async/pipe"},{"ns":"clojure.core.async","name":"unmix","file":"clojure/core/async.clj","type":"function","column":1,"see-alsos":[{"created-at":1477622125589,"author":{"login":"aaronj1331","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/349712?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"unmix-all","ns":"clojure.core.async"},"_id":"5812b96de4b024b73ca35a08"},{"created-at":1477622170416,"author":{"login":"aaronj1331","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/349712?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"admix","ns":"clojure.core.async"},"_id":"5812b99ae4b024b73ca35a09"},{"created-at":1477622241225,"author":{"login":"aaronj1331","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/349712?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"mix","ns":"clojure.core.async"},"_id":"5812b9e1e4b024b73ca35a0a"},{"created-at":1477622605184,"author":{"login":"aaronj1331","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/349712?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"toggle","ns":"clojure.core.async"},"_id":"5812bb4de4b024b73ca35a15"},{"created-at":1477622612305,"author":{"login":"aaronj1331","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/349712?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"solo-mode","ns":"clojure.core.async"},"_id":"5812bb54e4b024b73ca35a16"}],"line":891,"examples":null,"notes":null,"arglists":["mix ch"],"doc":"Removes ch as an input to the mix","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.async/unmix"},{"ns":"clojure.core.async","name":"onto-chan!!","file":"clojure/core/async.clj","type":"function","column":1,"see-alsos":null,"line":717,"examples":null,"notes":null,"arglists":["ch coll","ch coll close?"],"doc":"Like onto-chan! for use when accessing coll might block,\n e.g. a lazy seq of blocking operations","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.async/onto-chan!!"},{"ns":"clojure.core.async","name":"filter<","file":"clojure/core/async.clj","type":"function","skip-wiki":true,"column":1,"see-alsos":null,"line":1153,"examples":null,"deprecated":"0.1.319.0-6b1aca-alpha","notes":[{"author":{"login":"jngbng","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/552977?v=4"},"updated-at":1642583596457,"created-at":1642583596457,"body":"For posterity's sake, below is an alternative implementation.\nSee https://stackoverflow.com/questions/31286167/how-to-create-a-channel-from-another-with-transducers\n
    \n(defn filter< [p ch]\n (let [co (chan 1 (filter p)]\n    (pipe ch co)\n    co))\n
    ","_id":"61e7d62ce4b0b1e3652d759f"}],"arglists":["p ch","p ch buf-or-n"],"doc":"Deprecated - this function will be removed. Use transducer instead","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.async/filter<"},{"ns":"clojure.core.async","name":"sub*","type":"function","see-alsos":null,"examples":null,"notes":null,"tag":null,"arglists":["p v ch close?"],"doc":null,"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.async/sub*"},{"ns":"clojure.core.async","name":"remove<","file":"clojure/core/async.clj","type":"function","skip-wiki":true,"column":1,"see-alsos":null,"line":1168,"examples":null,"deprecated":"0.1.319.0-6b1aca-alpha","notes":null,"arglists":["p ch","p ch buf-or-n"],"doc":"Deprecated - this function will be removed. Use transducer instead","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.async/remove<"},{"ns":"clojure.core.async","name":"alt!!","file":"clojure/core/async.clj","type":"macro","column":1,"see-alsos":[{"created-at":1465302937238,"author":{"login":"Kejia","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1039073?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"alt!","ns":"clojure.core.async"},"_id":"5756bf99e4b0bafd3e2a0479"},{"created-at":1465302967905,"author":{"login":"Kejia","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1039073?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"alts!!","ns":"clojure.core.async"},"_id":"5756bfb7e4b0bafd3e2a047a"},{"created-at":1465302980860,"author":{"login":"Kejia","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1039073?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"alts!","ns":"clojure.core.async"},"_id":"5756bfc4e4b0bafd3e2a047b"}],"line":380,"examples":[{"updated-at":1469659872470,"created-at":1469659872470,"author":{"login":"xiongtx","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1624090?v=3"},"body":";; This example is taken from Timothy Baldridge's `core.async` course on Udemy\n;; https://www.udemy.com/communicating-sequential-processes-with-coreasync/learn/v4/overview\n\n;; Create two channels, c1 and c2\n(let [c1 (chan 1)\n c2 (chan 1)]\n ;; Put a value in each channel\n (>!! c1 42)\n (>!! c2 44)\n (thread\n ;; Take a value from one of the channels.\n ;; - If the value is taken from c1, return the keyword :c1 and channel c1\n ;; - Analogously for c2\n (let [[v c] (alt!! [c1] [:c1 c1]\n [c2] [:c2 c2])]\n ;; Print the returned keyword and whether the value was taken from c1 or c2\n (println \"Value: \" v)\n (println \"Chan 1?: \" (= c1 c))\n (println \"Chan 1?: \" (= c2 c)))))","_id":"57993ae0e4b0bafd3e2a04c2"}],"macro":true,"notes":null,"arglists":["& clauses"],"doc":"Like alt!, except as if by alts!!, will block until completed, and\n not intended for use in (go ...) blocks.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.async/alt!!"},{"ns":"clojure.core.async","name":"untap*","type":"function","see-alsos":null,"examples":null,"notes":null,"tag":null,"arglists":["m ch"],"doc":null,"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.async/untap*"},{"ns":"clojure.core.async","name":"!!","ns":"clojure.core.async"},"_id":"571e7ad5e4b012fe4fb18b39"}],"line":127,"examples":[{"body":"user=> (>!! c \"Blocking - not in go-block\")\ntrue\nuser=> ( channel-state-map. A\n channel-state-map is a map of attrs -> boolean, where attr is one or\n more of :mute, :pause or :solo. Any states supplied are merged with\n the current state.\n\n Note that channels can be added to a mix via toggle, which can be\n used to add channels in a particular (e.g. paused) state.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.async/toggle"},{"ns":"clojure.core.async","name":"untap-all*","type":"function","see-alsos":null,"examples":null,"notes":null,"tag":null,"arglists":["m"],"doc":null,"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.async/untap-all*"},{"ns":"clojure.core.async","name":"sliding-buffer","file":"clojure/core/async.clj","type":"function","column":1,"see-alsos":[{"created-at":1464291652174,"author":{"login":"eduardobull","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/6353416?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"buffer","ns":"clojure.core.async"},"_id":"57475144e4b0af2c9436d1f5"},{"created-at":1464291665676,"author":{"login":"eduardobull","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/6353416?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"dropping-buffer","ns":"clojure.core.async"},"_id":"57475151e4b0af2c9436d1f6"},{"created-at":1464291782443,"author":{"login":"eduardobull","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/6353416?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"chan","ns":"clojure.core.async"},"_id":"574751c6e4b0bafd3e2a0465"}],"line":70,"examples":[{"updated-at":1448692514966,"created-at":1448692514966,"author":{"login":"srazzaque","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/810842?v=3"},"body":"(require '[clojure.core.async :refer [go-loop !! sliding-buffer chan]])\n\n;; Sliding buffers can be used to discard old values on a chan\n\n;; Define a chan with a sliding buffer of 1 (i.e. we care mainly\n;; about the latest value)\n(def sliding-chan (chan (sliding-buffer 1)))\n\n;; Print the values on the chan forever\n(go-loop []\n (println \"Received:\" (!! sliding-chan n))\n\n;;=> Received: 0 ;; <-- see note below\n;;=> Received: 99\n\n;; Results may vary for values from 0 to n-1\n;; but you should ALWAYS see 'Received: '","_id":"56594b22e4b0be225c0c479f"}],"notes":null,"arglists":["n"],"doc":"Returns a buffer of size n. When full, puts will complete, and be\n buffered, but oldest elements in buffer will be dropped (not\n transferred).","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.async/sliding-buffer"},{"ns":"clojure.core.async","name":"partition","file":"clojure/core/async.clj","type":"function","skip-wiki":true,"column":1,"see-alsos":null,"line":1220,"examples":null,"deprecated":"0.1.319.0-6b1aca-alpha","notes":null,"arglists":["n ch","n ch buf-or-n"],"doc":"Deprecated - this function will be removed. Use transducer instead","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.async/partition"},{"ns":"clojure.core.async","name":"Mult","file":"clojure/core/async.clj","type":"var","column":1,"see-alsos":null,"line":745,"examples":null,"notes":null,"arglists":[],"doc":null,"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.async/Mult"},{"ns":"clojure.core.async","name":"merge","file":"clojure/core/async.clj","type":"function","column":1,"see-alsos":[{"created-at":1414157124197,"author":{"login":"jw-00000","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2936?v=2"},"to-var":{"ns":"clojure.core.async","name":"mix","library-url":"https://github.com/clojure/clojure"},"_id":"544a5344e4b0dc573b892fa7"}],"line":1036,"examples":[{"body":"user=> (def cx (chan))\n#'user/cx\n\nuser=> (def cy (chan))\n#'user/cy\n\nuser=> (def mc (clojure.core.async/merge [cx cy]))\n#'user/mc\n\nuser=> (put! cx \"Going to x\")\ntrue\n\nuser=> (put! cy \"Goint to y\")\ntrue\n\nuser=> ( ( ((1 1) (2) (1 1 1) (3 3))","author":{"login":"princesspanda","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/120405?v=3"},"created-at":1426133159296,"updated-at":1426133187178,"editors":[{"login":"princesspanda","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/120405?v=3"}],"_id":"550110a7e4b08a4fe1ef7150"}],"deprecated":"0.1.319.0-6b1aca-alpha","notes":null,"arglists":["f ch","f ch buf-or-n"],"doc":"Deprecated - this function will be removed. Use transducer instead","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.async/partition-by"},{"ns":"clojure.core.async","name":"unsub-all","file":"clojure/core/async.clj","type":"function","column":1,"see-alsos":null,"line":991,"examples":null,"notes":null,"arglists":["p","p topic"],"doc":"Unsubscribes all channels from a pub, or a topic of a pub","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.async/unsub-all"},{"ns":"clojure.core.async","name":">!","file":"clojure/core/async.clj","type":"function","column":1,"see-alsos":[{"created-at":1461613777584,"author":{"login":"cloojure","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7083783?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":">!!","ns":"clojure.core.async"},"_id":"571e74d1e4b012fe4fb18b36"},{"created-at":1461614301689,"author":{"login":"cloojure","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7083783?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"put!","ns":"clojure.core.async"},"_id":"571e76dde4b0fc95a97eab53"},{"created-at":1461615245628,"author":{"login":"cloojure","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7083783?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":" (let [c (chan 1)]\n #_=> (go (>! c 1)\n #_=> (println \"Got => \" ( 1\n\n#\n","author":{"login":"runexec","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1487241?v=2"},"created-at":1412147143085,"updated-at":1412147143085,"_id":"542ba7c7e4b05f4d257a2958"}],"notes":null,"arglists":["port val"],"doc":"puts a val into port. nil values are not allowed. Must be called\n inside a (go ...) block. Will park if no buffer space is available.\n Returns true unless port is already closed.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.async/>!"},{"ns":"clojure.core.async","name":"to-chan!!","file":"clojure/core/async.clj","type":"function","column":1,"see-alsos":null,"line":729,"examples":null,"notes":null,"arglists":["coll"],"doc":"Like to-chan! for use when accessing coll might block,\n e.g. a lazy seq of blocking operations","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.async/to-chan!!"},{"ns":"clojure.core.async","name":"unmix-all*","type":"function","see-alsos":null,"examples":null,"notes":null,"tag":null,"arglists":["m"],"doc":null,"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.async/unmix-all*"},{"ns":"clojure.core.async","name":"split","file":"clojure/core/async.clj","type":"function","column":1,"see-alsos":null,"line":615,"examples":[{"updated-at":1457189785017,"created-at":1457189785017,"author":{"login":"ryoakg","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/23413?v=3"},"body":"(require '[clojure.core.async :refer :all])\n\n(def c (chan))\n\n(let [[c1 c2] (split odd? c)]\n (go-loop []\n (println \"c1: \" (!! c n))\n\n;; will prints\nc2: c1: 01\nc2: 2\nc1: 3\nc2: 4\nc1: 5\nc2: 6\nc1: 7\nc2: 8\nc1: 9","_id":"56daf399e4b0b41f39d96cdc"}],"notes":null,"arglists":["p ch","p ch t-buf-or-n f-buf-or-n"],"doc":"Takes a predicate and a source channel and returns a vector of two\n channels, the first of which will contain the values for which the\n predicate returned true, the second those for which it returned\n false.\n\n The out channels will be unbuffered by default, or two buf-or-ns can\n be supplied. The channels will close after the source channel has\n closed.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.async/split"},{"ns":"clojure.core.async","name":"unmix-all","file":"clojure/core/async.clj","type":"function","column":1,"see-alsos":[{"created-at":1477622473868,"author":{"login":"aaronj1331","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/349712?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"unmix","ns":"clojure.core.async"},"_id":"5812bac9e4b024b73ca35a0f"},{"created-at":1477622482943,"author":{"login":"aaronj1331","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/349712?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"admix","ns":"clojure.core.async"},"_id":"5812bad2e4b024b73ca35a10"},{"created-at":1477622487430,"author":{"login":"aaronj1331","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/349712?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"mix","ns":"clojure.core.async"},"_id":"5812bad7e4b024b73ca35a11"},{"created-at":1477622570483,"author":{"login":"aaronj1331","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/349712?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"toggle","ns":"clojure.core.async"},"_id":"5812bb2ae4b024b73ca35a12"},{"created-at":1477622582934,"author":{"login":"aaronj1331","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/349712?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"solo-mode","ns":"clojure.core.async"},"_id":"5812bb36e4b024b73ca35a14"}],"line":896,"examples":null,"notes":null,"arglists":["mix"],"doc":"removes all inputs from the mix","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.async/unmix-all"},{"ns":"clojure.core.async","name":"filter>","file":"clojure/core/async.clj","type":"function","skip-wiki":true,"column":1,"see-alsos":null,"line":1129,"examples":null,"deprecated":"0.1.319.0-6b1aca-alpha","notes":null,"arglists":["p ch"],"doc":"Deprecated - this function will be removed. Use transducer instead","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.async/filter>"},{"ns":"clojure.core.async","name":"tap*","type":"function","see-alsos":null,"examples":null,"notes":null,"tag":null,"arglists":["m ch close?"],"doc":null,"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.async/tap*"},{"ns":"clojure.core.async","name":"defblockingop","file":"clojure/core/async.clj","type":"macro","column":1,"see-alsos":null,"line":116,"examples":null,"macro":true,"notes":null,"arglists":["op doc arglist & body"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.async/defblockingop"},{"ns":"clojure.core.async","name":"untap","file":"clojure/core/async.clj","type":"function","column":1,"see-alsos":[{"created-at":1420501460660,"author":{"login":"schmee","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/3405586?v=3"},"to-var":{"ns":"clojure.core.async","name":"tap","library-url":"https://github.com/clojure/clojure"},"_id":"54ab21d4e4b04e93c519ffb4"},{"created-at":1420501464732,"author":{"login":"schmee","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/3405586?v=3"},"to-var":{"ns":"clojure.core.async","name":"mult","library-url":"https://github.com/clojure/clojure"},"_id":"54ab21d8e4b09260f767ca8c"},{"created-at":1420501510125,"author":{"login":"schmee","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/3405586?v=3"},"to-var":{"ns":"clojure.core.async","name":"untap-all","library-url":"https://github.com/clojure/clojure"},"_id":"54ab2206e4b09260f767ca8d"}],"line":800,"examples":[{"body":"(def c (chan))\n(def m (mult c))\n\n(def d (chan))\n(tap m d)\n\n\n(put! c 5)\n(go (println ( (let [chans (partition-all 2\n (interleave\n [\"Bob\"\n \"Jane\"\n \"GuyGirl22\"]\n (repeatedly 3 chan)))]\n (go\n (let [[owner port] (rand-nth chans)\n chans-only (mapv second chans)]\n\n (go\n (! port\n (str owner \": First!!!\")))\n\n (let [[v p] (alts! chans-only)]\n (println \"Message: \" v \"\\nFrom Object: \" p)))))\n\n;; Returns => #\n\n;; 1.5 seconds later =>\n;; Message: Bob: First!!! \n;; From Object: #\n","_id":"543232b4e4b0e5600098acc3"},{"editors":[{"login":"harrigan","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/140753?v=4"}],"body":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n;;\n;; THIS example shows `:default`s and `:priority`s\n\n(let [f (fn [x ch] (go (Thread/sleep (rand 100))\n (>! ch x)))\n a (chan)\n b (chan)\n c (chan)]\n (println \"----------\")\n (f 1 a)\n (f 2 b)\n (f 3 c)\n (Thread/sleep 200) ; if this is commented out, it returns the\n ; `:default` every time. If the thread *does*\n ; sleep, then it returns the `a` channel's `1`\n ; every time\n (let [[n ch2] (alts!! [a b c]\n :default 42\n :priority true\n )]\n (println \"received: \" n)))","author":{"avatar-url":"https://avatars.githubusercontent.com/u/8399149?v=3","account-source":"github","login":"freckletonj"},"created-at":1478496465164,"updated-at":1504778601998,"_id":"582010d1e4b024b73ca35a23"},{"updated-at":1737496258844,"created-at":1737496258844,"author":{"login":"cstml","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/29694576?v=4"},"body":"(require '[clojure.core.async :as a])\n\n(let [|a (a/chan)\n |b (a/chan)]\n\n (a/go\n (let [[result |chan] (a/alts! [|a |b])]\n (println [result (= |chan |a)])))\n\n (a/>!! |a 2))\n\n;; prints \n;; [2 true]","_id":"679016c2cd84df5de54e2072"}],"notes":null,"arglists":["ports & {:as opts}"],"doc":"Completes at most one of several channel operations. Must be called\n inside a (go ...) block. ports is a vector of channel endpoints,\n which can be either a channel to take from or a vector of\n [channel-to-put-to val-to-put], in any combination. Takes will be\n made as if by !. Unless\n the :priority option is true, if more than one port operation is\n ready a non-deterministic choice will be made. If no operation is\n ready and a :default value is supplied, [default-val :default] will\n be returned, otherwise alts! will park until the first operation to\n become ready completes. Returns [val port] of the completed\n operation, where val is the value taken for takes, and a\n boolean (true unless already closed, as per put!) for puts.\n\n opts are passed as :key val ... Supported options:\n\n :default val - the value to use if none of the operations are immediately ready\n :priority true - (default nil) when true, the operations will be tried in order.\n\n Note: there is no guarantee that the port exps or val exprs will be\n used, nor in what order should they be, so they should not be\n depended upon for side effects.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.async/alts!"},{"ns":"clojure.core.async","name":"unsub","file":"clojure/core/async.clj","type":"function","column":1,"see-alsos":null,"line":986,"examples":null,"notes":null,"arglists":["p topic ch"],"doc":"Unsubscribes a channel from a topic of a pub","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.async/unsub"},{"ns":"clojure.core.async","name":"poll!","file":"clojure/core/async.clj","type":"function","column":1,"see-alsos":[{"created-at":1464291718503,"author":{"login":"eduardobull","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/6353416?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"offer!","ns":"clojure.core.async"},"_id":"57475186e4b0bafd3e2a0462"}],"line":436,"examples":[{"updated-at":1521204570897,"created-at":1521204570897,"author":{"login":"ertugrulcetin","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/8271291?v=4"},"body":"(let [c (chan)]\n (println (poll! c)))\n\n;; nil\n;;=> nil (it does not block even though there is no buffer!)\n\n(let [c (chan 1)]\n (println (offer! c 10))\n (println (poll! c)))\n;; true\n;; 10\n;;=> nil","_id":"5aabbd5ae4b0316c0f44f92a"}],"notes":null,"arglists":["port"],"doc":"Takes a val from port if it's possible to do so immediately.\n Never blocks. Returns value if successful, nil otherwise.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.async/poll!"},{"ns":"clojure.core.async","name":"thread","file":"clojure/core/async.clj","type":"macro","column":1,"see-alsos":[{"created-at":1477621753853,"author":{"login":"aaronj1331","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/349712?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"thread-call","ns":"clojure.core.async"},"_id":"5812b7f9e4b024b73ca35a05"},{"created-at":1477621759508,"author":{"login":"aaronj1331","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/349712?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"go","ns":"clojure.core.async"},"_id":"5812b7ffe4b024b73ca35a06"}],"line":493,"examples":[{"editors":[{"login":"fmnoise","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/4033391?v=4"},{"login":"saitouena","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/40712240?v=4"}],"body":"(defn fake-fetch []\n (thread \n (Thread/sleep 5000) \n \"Ready!\"))\n\n;; returns immediately, prints \"Ready!\" after 5 secs\n(let [c (fake-fetch)]\n (go (println ( (chan 1))\n(def cb> (chan 1))\n(defn c-af [val result] ; notice the signature is different for `pipeline-async`, it includes a channel\n (go (! result (str val \"!!!\"))\n (close! result)))\n(pipeline-async\n 1\n cb>\n c-af\n ca>)\n(go (println ()))\n(go (>! ca> \"hello\"))","_id":"57f66c0ee4b0709b524f0528"}],"notes":[{"author":{"login":"dmarkhas","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/16191105?v=4"},"updated-at":1575466231681,"created-at":1575466231681,"body":"I think the phrase `af must close! the channel before returning.` is confusing, and should be changed to something along the lines of `af must close! the channel before the async operation completes`.","_id":"5de7b4f7e4b0ca44402ef7f0"}],"arglists":["n to af from","n to af from close?"],"doc":"Takes elements from the from channel and supplies them to the to\n channel, subject to the async function af, with parallelism n. af\n must be a function of two arguments, the first an input value and\n the second a channel on which to place the result(s). The\n presumption is that af will return immediately, having launched some\n asynchronous operation whose completion/callback will put results on\n the channel, then close! it. Outputs will be returned in order\n relative to the inputs. By default, the to channel will be closed\n when the from channel closes, but can be determined by the close?\n parameter. Will stop consuming the from channel if the to channel\n closes. See also pipeline, pipeline-blocking.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.async/pipeline-async"},{"ns":"clojure.core.async","name":"Mix","file":"clojure/core/async.clj","type":"var","column":1,"see-alsos":null,"line":809,"examples":null,"notes":null,"arglists":[],"doc":null,"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.async/Mix"},{"ns":"clojure.core.async","name":"toggle*","type":"function","see-alsos":null,"examples":null,"notes":null,"tag":null,"arglists":["m state-map"],"doc":null,"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.async/toggle*"},{"ns":"clojure.core.async","name":"mult","file":"clojure/core/async.clj","type":"function","column":1,"see-alsos":[{"created-at":1420501383575,"author":{"login":"schmee","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/3405586?v=3"},"to-var":{"ns":"clojure.core.async","name":"tap","library-url":"https://github.com/clojure/clojure"},"_id":"54ab2187e4b09260f767ca89"},{"created-at":1420501439113,"author":{"login":"schmee","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/3405586?v=3"},"to-var":{"ns":"clojure.core.async","name":"untap","library-url":"https://github.com/clojure/clojure"},"_id":"54ab21bfe4b09260f767ca8a"},{"created-at":1653095539882,"author":{"login":"rgkirch","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/6143833?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"mix","ns":"clojure.core.async"},"_id":"62883c73e4b0b1e3652d75f0"}],"line":750,"examples":[{"body":"user=> (def sz 20)\n#'user/sz\n\nuser=> (def c (chan sz))\n#'user/c\n\nuser=> (def mult-c (mult c))\n#'user/mult-c\n\nuser=> (def cx (chan sz))\n#'user/cx\n\nuser=> (def cy (chan sz))\n#'user/cy\n\nuser=> (def cz (chan sz))\n#'user/cz\n\nuser=> (tap mult-c cx)\n#\n\nuser=> (tap mult-c cy)\n#\n\nuser=> (tap mult-c cz)\n#\n\nuser=> (put! c \"sent to all\")\ntrue\n\nuser=> ( ( ( (def a (chan))\nuser> (def m (mult a))\nuser> (def b (chan))\nuser> (tap m b)\nuser> (go-loop [] (when-let [v ( (go-loop [] (when-let [v ( (put! a \"Hello \")\nb got Hello \nuser> (put! a \" World\")\na(source) got World\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/5214601?v=3","account-source":"github","login":"cuneoPauloCesar"}],"_id":"563432f8e4b0290a56055d17"}],"notes":null,"arglists":["ch"],"doc":"Creates and returns a mult(iple) of the supplied channel. Channels\n containing copies of the channel can be created with 'tap', and\n detached with 'untap'.\n\n Each item is distributed to all taps in parallel and synchronously,\n i.e. each tap must accept before the next item is distributed. Use\n buffering/windowing to prevent slow taps from holding up the mult.\n\n Items received when there are no taps get dropped.\n\n If a tap puts to a closed channel, it will be removed from the mult.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.async/mult"},{"ns":"clojure.core.async","name":"thread-call","file":"clojure/core/async.clj","type":"function","column":1,"see-alsos":[{"created-at":1477621565889,"author":{"login":"aaronj1331","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/349712?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"thread","ns":"clojure.core.async"},"_id":"5812b73de4b024b73ca35a03"},{"created-at":1477621729989,"author":{"login":"aaronj1331","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/349712?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"go","ns":"clojure.core.async"},"_id":"5812b7e1e4b024b73ca35a04"}],"line":475,"examples":[{"editors":[{"login":"earthfail","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/21296448?v=4"}],"body":"(defn fake-fetch []\n (Thread/sleep 5000) \n \"Ready!\")\n\n;; returns immediately, prints \"Ready!\" after 5 secs\n(let [c (thread-call fake-fetch)]\n (println ( (let [chans (partition-all 2\n (interleave\n [\"Bob\"\n \"Jane\"\n \"GuyGirl22\"]\n (for [_ (range 3)] \n (chan))))\n [owner port] (rand-nth chans)\n chans-only (mapv second chans)]\n \n (go\n (! port\n (str owner \": First!!!\")))\n\n (let [[v p] (alts!! chans-only)]\n (println \"Message: \" v \"\\nFrom Object: \" p)))\n\n;; Message: Bob: First!!! \n;; From Object: #\n;; nil\n","author":{"login":"runexec","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1487241?v=2"},"created-at":1412576406866,"updated-at":1412576646175,"editors":[{"login":"runexec","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1487241?v=2"}],"_id":"54323496e4b0e5600098acc4"},{"editors":[{"login":"quackingduck","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/9556?v=3"}],"body":"(require '[clojure.core.async :as async])\n\n;; n.b. alts!! returns a *pair* of [value channel-where-value-came-from]\n\n; a channel with a single value ready in the queue\n(def c (async/chan))\n(async/put! c \"foo\")\n\n(println (async/alts!! [(async/timeout 2000) c]))\n;; => [\"foo\" ]\n\n; no more values, so we will timeout\n(println (async/alts!! [(async/timeout 2000) c]))\n;; => [nil ]\n","author":{"avatar-url":"https://avatars.githubusercontent.com/u/9556?v=3","account-source":"github","login":"quackingduck"},"created-at":1466646608720,"updated-at":1466812798643,"_id":"576b4050e4b0bafd3e2a048e"}],"notes":null,"arglists":["ports & opts"],"doc":"Like alts!, except takes will be made as if by !!, will block until completed.\n Not intended for use in direct or transitive calls from (go ...) blocks.\n Use the clojure.core.async.go-checking flag to detect invalid use (see\n namespace docs).","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.async/alts!!"},{"ns":"clojure.core.async","name":"mapcat<","file":"clojure/core/async.clj","type":"function","skip-wiki":true,"column":1,"see-alsos":null,"line":1184,"examples":null,"deprecated":"0.1.319.0-6b1aca-alpha","notes":null,"arglists":["f in","f in buf-or-n"],"doc":"Deprecated - this function will be removed. Use transducer instead","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.async/mapcat<"},{"ns":"clojure.core.async","name":"ioc-alts!","file":"clojure/core/async.clj","type":"function","column":1,"see-alsos":null,"line":418,"examples":null,"notes":null,"arglists":["state cont-block ports & {:as opts}"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.async/ioc-alts!"},{"ns":"clojure.core.async","name":"unblocking-buffer?","file":"clojure/core/async.clj","type":"function","column":1,"see-alsos":null,"line":77,"examples":null,"notes":null,"arglists":["buff"],"doc":"Returns true if a channel created with buff will never block. That is to say,\n puts into this buffer will never cause the buffer to be full. ","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.async/unblocking-buffer_q"},{"ns":"clojure.core.async","name":"do-alt","file":"clojure/core/async.clj","type":"function","column":1,"see-alsos":null,"line":342,"examples":null,"notes":null,"arglists":["alts clauses"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.async/do-alt"},{"ns":"clojure.core.async","name":"put!","file":"clojure/core/async.clj","type":"function","column":1,"see-alsos":[{"created-at":1458597697805,"author":{"login":"royalaid","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2439803?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"take!","ns":"clojure.core.async"},"_id":"56f06f41e4b09295d75dbf38"},{"created-at":1458597821489,"author":{"login":"royalaid","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2439803?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":">!","ns":"clojure.core.async"},"_id":"56f06fbde4b09295d75dbf3b"},{"created-at":1458597828313,"author":{"login":"royalaid","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2439803?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":">!!","ns":"clojure.core.async"},"_id":"56f06fc4e4b07ac9eeceed14"}],"line":189,"examples":[{"body":"user=> (def c (chan 1))\n#'user/c\n\nuser=> (take! c\n (fn [x]\n (println \"Clojure callback value \" x)))\nnil\n\nuser=> (put! c \"XYZ\") ; return true unless the channel is closed.\nClojure callback value XYZ\ntrue\n\nuser=> (put! c \"XYZ\")\ntrue\n","author":{"login":"runexec","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1487241?v=2"},"created-at":1412203179922,"updated-at":1451943835304,"editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/1039073?v=3","account-source":"github","login":"Kejia"}],"_id":"542c82abe4b05f4d257a2975"},{"editors":[{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"}],"body":";; There is a maximum queue size of 1024\n(def foo-chan (chan))\n\n(dotimes [x 1025]\n (put! foo-chan x))\n\nExecution error (AssertionError) at clojure.core.async…\nAssert failed: No more than 1024 pending puts are allowed on a single channel.\nConsider using a windowed buffer…","author":{"avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4","account-source":"github","login":"tomdl89"},"created-at":1705944134722,"updated-at":1706000508674,"_id":"65aea44669fbcc0c22617489"}],"notes":[{"author":{"login":"hlship","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/52660?v=3"},"updated-at":1437168807833,"created-at":1437168807833,"body":"The documentation here is somewhat out of date, the real documentation for more recent versions of core.async (0.1.346.0-17112a-alpha, at the time of this note) removes the bit about throwing when the channel is closed. \n\nInstead, put! returns true unless the port is already closed, in which case false is returned.\n\nAn exception *is* thrown is you attempt to put! nil.","_id":"55a974a7e4b0080a1b79cda7"}],"arglists":["port val","port val fn1","port val fn1 on-caller?"],"doc":"Asynchronously puts a val into port, calling fn1 (if supplied) when\n complete, passing false iff port is already closed. nil values are\n not allowed. If on-caller? (default true) is true, and the put is\n immediately accepted, will call fn1 on calling thread.\n\n fn1 may be run in a fixed-size dispatch thread pool and should not\n perform blocking IO, including core.async blocking ops (those that\n end in !!).\n\n Returns true unless port is already closed.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.async/put!"},{"ns":"clojure.core.async","name":"take!","file":"clojure/core/async.clj","type":"function","column":1,"see-alsos":[{"created-at":1458597672855,"author":{"login":"royalaid","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2439803?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"put!","ns":"clojure.core.async"},"_id":"56f06f28e4b09295d75dbf37"},{"created-at":1458597792127,"author":{"login":"royalaid","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2439803?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":" (def c (chan 1))\n#'user/c\n\nuser=> (take! c\n (fn [x]\n (println \"Clojure callback value \" x)))\nnil\n\nuser=> (put! c \"XYZ\")\nClojure callback value XYZ\ntrue\n\nuser=> (put! c \"XYZ\")\ntrue\n","author":{"login":"runexec","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1487241?v=2"},"created-at":1412203153682,"updated-at":1412203153682,"_id":"542c8291e4b05f4d257a2974"},{"updated-at":1516398462305,"created-at":1516398462305,"author":{"login":"jayzawrotny","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/590297?v=4"},"body":"(require '[clojure.core.async :refer [chan take! put!]])\n\n(def input-channel (chan 1))\n\n;; Take the first message from a channel and print it\n(take! input-channel println)\n\n(put! input-channel \"A\")\n;; => \"A\"\n\n(put! input-channel \"B\")\n;; Does not output anything because take only takes the first message\n","_id":"5a62677ee4b0a08026c48d04"}],"notes":null,"arglists":["port fn1","port fn1 on-caller?"],"doc":"Asynchronously takes a val from port, passing to fn1. Will pass nil\n if closed. If on-caller? (default true) is true, and value is\n immediately available, will call fn1 on calling thread.\n\n fn1 may be run in a fixed-size dispatch thread pool and should not\n perform blocking IO, including core.async blocking ops (those that\n end in !!).\n\n Returns nil.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.async/take!"},{"ns":"clojure.core.logic","name":"run-db*","file":"clojure/core/logic.clj","type":"macro","column":1,"see-alsos":null,"line":1252,"examples":null,"macro":true,"notes":null,"arglists":["db bindings & goals"],"doc":"Executes goals until results are exhausted. Uses a specified logic database.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/run-db*"},{"ns":"clojure.core.logic","name":"choice","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":1102,"examples":null,"notes":null,"arglists":["a f"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/choice"},{"ns":"clojure.core.logic","name":"-conjo","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":2768,"examples":null,"notes":null,"arglists":["coll args out"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/-conjo"},{"ns":"clojure.core.logic","name":"to-subst-val","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":604,"examples":null,"notes":null,"arglists":["v"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/to-subst-val"},{"ns":"clojure.core.logic","name":"conde","file":"clojure/core/logic.clj","type":"macro","column":1,"see-alsos":[{"created-at":1651392672424,"author":{"login":"shenlebantongying","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/20123683?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"conda","ns":"clojure.core.logic"},"_id":"626e40a0e4b0b1e3652d75dd"}],"line":1175,"examples":[{"updated-at":1562865825354,"created-at":1562865825354,"author":{"login":"kannangce","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/8754040?v=4"},"body":";; conde accepts vectors of goals.\n;; makes 'or' of all the goals represented by each vector\n;; Where within each of those goals all condition must be met \n\n(run*\n [x y]\n (conde\n \t [(conso x y [1 2 3 4]) (== x 1)] ;; (conso x y [1 2 3 4]) and (== x 1)\n \t \t ;; OR\n \t [(== x y) (== x 2)])) \t ;; (== x y) and (== x 2)\n\n;; ([1 (2 3 4)] [2 2])","_id":"5d2770a1e4b0ca44402ef781"}],"macro":true,"notes":null,"arglists":["& clauses"],"doc":"Logical disjunction of the clauses. The first goal in\n a clause is considered the head of that clause. Interleaves the\n execution of the clauses.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/conde"},{"ns":"clojure.core.logic","name":"master","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":1976,"examples":null,"notes":null,"arglists":["argv cache"],"doc":"Take the argument to the goal and check that we don't\n have an alpha equivalent cached answer term in the cache.\n If it doesn't already exist in the cache add the new\n answer term.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/master"},{"ns":"clojure.core.logic","name":"sort-by-member-count","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":2218,"examples":null,"notes":null,"arglists":["a"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/sort-by-member-count"},{"ns":"clojure.core.logic","name":"matche","file":"clojure/core/logic.clj","type":"macro","column":1,"see-alsos":[{"created-at":1612485988783,"author":{"login":"cheukyin699","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/6824907?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"conde","ns":"clojure.core.logic"},"_id":"601c9564e4b0b1e3652d7448"}],"line":1705,"examples":[{"updated-at":1460222471941,"created-at":1460222150971,"author":{"login":"freckletonj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8399149?v=3"},"body":";; Taken from: https://github.com/frenchy64/Logic-Starter/wiki#matche\n;; These are equivalent:\n(run* [q]\n (conde\n ((== 'extra q) succeed)\n ((== 'virgin q) succeed)\n ((== 'olive q) succeed)\n ((== 'oil q) succeed)))\n;=> (extra virgin olive oil)\n\n(run* [q]\n (matche [q]\n (['extra] succeed)\n (['virgin] succeed)\n (['olive] succeed)\n (['oil] succeed)))\n;=> (extra virgin olive oil)\n\n;; Wild Cards and destructuring: https://github.com/frenchy64/Logic-Starter/wiki#matche-sugar-combining-wildcards-and-destructuring\n(run* [q]\n (fresh [a o]\n (== a [1 2 3 4 5])\n (matche [a]\n ([ [1 . _] ]\n (== q \"first\"))\n ([ [_ . o] ]\n (== q [\"second\" o])))))\n;=> (\"first\" \n; [\"second\" (2 3 4 5)])\n\n;; Implicit Variables: https://github.com/frenchy64/Logic-Starter/wiki#matche-sugar-implicit-variables\n(run* [q]\n (fresh [a o]\n (== a [1 2 3 4 5])\n (matche [a]\n ([ [1 . o] ]\n (== q [\"one\" o]))\n ([ [1 2 . ?o] ]\n (== q [\"two\" ?o]))\n ([ [o . ?o] ]\n (== q [\"third\" o ?o])))))\n;=> ([\"one\" (2 3 4 5)] \n; [\"two\" (3 4 5)] \n; [\"third\" 1 (2 3 4 5)] ","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/8399149?v=3","account-source":"github","login":"freckletonj"}],"_id":"570938c6e4b075f5b2c864db"}],"macro":true,"notes":null,"arglists":["xs & cs"],"doc":"Pattern matching macro. All patterns will be tried.\n See conde.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/matche"},{"ns":"clojure.core.logic","name":"appendo","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":1772,"examples":[{"editors":[{"login":"lenw","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/339388?v=3"}],"body":"(run* [q]\n (appendo [:a :b] [:c :d :e] q)) ;; ((:a :b :c :d :e))\n(run* [q]\n (appendo [:a :b] q [:a :b :c :d :e])) ;; ((:c :d :e))\n","author":{"avatar-url":"https://avatars.githubusercontent.com/u/8399149?v=3","account-source":"github","login":"freckletonj"},"created-at":1460064833781,"updated-at":1460410120788,"_id":"5706d241e4b0fc95a97eab33"}],"notes":null,"arglists":["x y z"],"doc":"A relation where x, y, and z are proper collections,\n such that z is x appended to y","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/appendo"},{"ns":"clojure.core.logic","name":"nafc","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":2725,"examples":null,"notes":null,"arglists":["c & args"],"doc":"EXPERIMENTAL: negation as failure constraint. All arguments to the goal c\n must be ground. If some argument is not ground the execution of this constraint\n will be delayed.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/nafc"},{"ns":"clojure.core.logic","name":"fnu","file":"clojure/core/logic.clj","type":"macro","column":1,"see-alsos":null,"line":1723,"examples":null,"macro":true,"notes":null,"arglists":["& rest"],"doc":"Define an anonymous committed choice goal. See condu.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/fnu"},{"ns":"clojure.core.logic","name":"!=c","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":2409,"examples":null,"notes":null,"arglists":["p"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/!=c"},{"ns":"clojure.core.logic","name":"composeg*","file":"clojure/core/logic.clj","type":"macro","column":1,"see-alsos":null,"line":1060,"examples":null,"macro":true,"notes":null,"arglists":["g0","g0 & gs"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/composeg*"},{"ns":"clojure.core.logic","name":"addcg","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":2036,"examples":null,"notes":null,"arglists":["c"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/addcg"},{"ns":"clojure.core.logic","name":"dissoc-meta","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":27,"examples":null,"notes":null,"arglists":["x k"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/dissoc-meta"},{"ns":"clojure.core.logic","name":"rem-attr","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":440,"examples":null,"notes":null,"arglists":["s x attr"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/rem-attr"},{"ns":"clojure.core.logic","name":"fk","file":"clojure/core/logic.clj","type":"var","column":1,"see-alsos":null,"line":19,"examples":null,"notes":null,"arglists":[],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/fk"},{"ns":"clojure.core.logic","name":"-predc","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":2659,"examples":null,"notes":null,"arglists":["x p","x p pform"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/-predc"},{"ns":"clojure.core.logic","name":"recover-vars-from-term","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":2389,"examples":null,"notes":null,"arglists":["x"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/recover-vars-from-term"},{"ns":"clojure.core.logic","name":"defna","file":"clojure/core/logic.clj","type":"macro","column":1,"see-alsos":[{"created-at":1460136622465,"author":{"login":"freckletonj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8399149?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"defnc","ns":"clojure.core.logic"},"_id":"5707eaaee4b075f5b2c864d6"},{"created-at":1460136638290,"author":{"login":"freckletonj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8399149?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"defne","ns":"clojure.core.logic"},"_id":"5707eabee4b0fc95a97eab3a"},{"created-at":1460136644492,"author":{"login":"freckletonj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8399149?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"defnu","ns":"clojure.core.logic"},"_id":"5707eac4e4b0fc95a97eab3b"}],"line":1728,"examples":null,"macro":true,"notes":null,"arglists":["& rest"],"doc":"Define a soft cut goal. See conda.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/defna"},{"ns":"clojure.core.logic","name":"recover-vars","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":2398,"examples":null,"notes":null,"arglists":["p"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/recover-vars"},{"ns":"clojure.core.logic","name":"defnu","file":"clojure/core/logic.clj","type":"macro","column":1,"see-alsos":[{"created-at":1460137178241,"author":{"login":"freckletonj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8399149?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"defna","ns":"clojure.core.logic"},"_id":"5707ecdae4b075f5b2c864d8"},{"created-at":1460137189155,"author":{"login":"freckletonj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8399149?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"defne","ns":"clojure.core.logic"},"_id":"5707ece5e4b0fc95a97eab3c"},{"created-at":1460137194453,"author":{"login":"freckletonj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8399149?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"defnc","ns":"clojure.core.logic"},"_id":"5707eceae4b075f5b2c864da"},{"created-at":1490672152735,"author":{"login":"tkocmathla","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/183459?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"condu","ns":"clojure.core.logic"},"_id":"58d9da18e4b01f4add58fe7c"}],"line":1733,"examples":null,"macro":true,"notes":null,"arglists":["& rest"],"doc":"Define a committed choice goal. See condu.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/defnu"},{"ns":"clojure.core.logic","name":"cgoal","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":2187,"examples":null,"notes":null,"arglists":["c"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/cgoal"},{"ns":"clojure.core.logic","name":"seqc","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":2887,"examples":null,"notes":null,"arglists":["v"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/seqc"},{"ns":"clojure.core.logic","name":"log","file":"clojure/core/logic.clj","type":"macro","column":1,"see-alsos":null,"line":1288,"examples":[{"updated-at":1668940522609,"created-at":1668940522609,"author":{"login":"claj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/353113?v=4"},"body":"(run* [q]\n (log \"* running program\")\n (fresh [c d]\n (conde\n [(log \"** in first clause\")\n (== c 0)]\n [(log \"** in second clause\")\n (== c 10)]\n [(log \"** in third clause\")\n (== d 2)\n (is c d (fn [a] (* a 2)))])\n (log \"ok finishing. \")\n (== c q)))\n;; =>\n;; * running program\n;; ** in first clause\n;; ok finishing. \n;; ** in second clause\n;; ok finishing. \n;; ** in third clause\n;; ok finishing. \n","_id":"637a02eae4b0b1e3652d7689"}],"macro":true,"notes":null,"arglists":["& s"],"doc":"Goal for println","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/log"},{"ns":"clojure.core.logic","name":"-reify*","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":259,"examples":null,"notes":null,"arglists":["s v"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/-reify*"},{"ns":"clojure.core.logic","name":"bind*","file":"clojure/core/logic.clj","type":"macro","column":1,"see-alsos":null,"line":1067,"examples":null,"macro":true,"notes":null,"arglists":["a g","a g & g-rest"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/bind*"},{"ns":"clojure.core.logic","name":"reifyg","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":2175,"examples":null,"notes":null,"arglists":["x"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/reifyg"},{"ns":"clojure.core.logic","name":"distincto","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":2472,"examples":[{"updated-at":1581848182644,"created-at":1581848182644,"author":{"login":"mdzaebel","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/415392?v=4"},"body":"(run* [a b] (membero a [1 2]) (membero b [1 2]) (distincto [a b]))\n;;=> ([1 2] [2 1])\n\n;; Without 'distincto':\n\n(run* [a b] (membero a [1 2]) (membero b [1 2]))\n;;=>([1 1] [1 2] [2 1] [2 2])","_id":"5e491676e4b0ca44402ef83b"}],"notes":null,"arglists":["l"],"doc":"A relation which guarantees no element of l will unify\n with another element of l.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/distincto"},{"ns":"clojure.core.logic","name":"assoc-dom","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":30,"examples":null,"notes":null,"arglists":["x k v"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/assoc-dom"},{"ns":"clojure.core.logic","name":"get-dom","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":515,"examples":null,"notes":null,"arglists":["s x dom"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/get-dom"},{"ns":"clojure.core.logic","name":"condu","file":"clojure/core/logic.clj","type":"macro","column":1,"see-alsos":null,"line":1425,"examples":null,"macro":true,"notes":null,"arglists":["& clauses"],"doc":"Committed choice. Once the head (first goal) of a clause\n has succeeded, remaining goals of the clause will only\n be run once. Non-relational.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/condu"},{"ns":"clojure.core.logic","name":"constrain-tree","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":2839,"examples":null,"notes":null,"arglists":["t fc"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/constrain-tree"},{"ns":"clojure.core.logic","name":"run-nc*","file":"clojure/core/logic.clj","type":"macro","column":1,"see-alsos":null,"line":1263,"examples":null,"macro":true,"notes":null,"arglists":["& goals"],"doc":"Executes goals until results are exhausted. Does not occurs-check.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/run-nc*"},{"ns":"clojure.core.logic","name":"empty-s","file":"clojure/core/logic.clj","type":"var","column":1,"see-alsos":null,"line":537,"examples":null,"notes":null,"arglists":[],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/empty-s"},{"ns":"clojure.core.logic","name":"var-rands","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":91,"examples":null,"notes":null,"arglists":["a c"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/var-rands"},{"ns":"clojure.core.logic","name":"merge-with-root","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":579,"examples":null,"notes":null,"arglists":["s x root"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/merge-with-root"},{"ns":"clojure.core.logic","name":"waiting-stream-check","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":1863,"examples":null,"notes":null,"arglists":["w success-cont failure-cont"],"doc":"Take a waiting stream, a success continuation, and a failure continuation.\n If we don't find any ready suspended streams, invoke the failure continuation.\n If we find a ready suspended stream calculate the remainder of the waiting\n stream. If we've reached the fixpoint just call the thunk of the suspended\n stream, otherwise call mplus on the result of the thunk and the remainder\n of the waiting stream. Pass this result to the success contination.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/waiting-stream-check"},{"ns":"clojure.core.logic","name":"tabled-s","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":529,"examples":null,"notes":null,"arglists":["","oc","oc meta"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/tabled-s"},{"ns":"clojure.core.logic","name":"fresh","file":"clojure/core/logic.clj","type":"macro","column":1,"see-alsos":null,"line":1207,"examples":[{"updated-at":1651390083912,"created-at":1651390083912,"author":{"login":"shenlebantongying","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/20123683?v=4"},"body":"(run* [q]\n (fresh [a]\n (membero a [2 3])\n (== a q)))\n; => (2 3)\n\n;; a is a member of [2 3]\n;; a and q are unified.\n;; Note that only q will occur in the result.","_id":"626e3683e4b0b1e3652d75dc"}],"macro":true,"notes":null,"arglists":["[& lvars] & goals"],"doc":"Creates fresh variables. Goals occuring within form a logical\n conjunction.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/fresh"},{"ns":"clojure.core.logic","name":"treec","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":2876,"examples":null,"notes":null,"arglists":["x fc reifier"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/treec"},{"ns":"clojure.core.logic","name":"partial-map","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":[{"created-at":1450638666311,"author":{"login":"qneo","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/5214601?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"featurec","ns":"clojure.core.logic"},"_id":"5676fd4ae4b08a391679537f"}],"line":2536,"examples":null,"notes":null,"arglists":["m"],"doc":"Given map m, returns partial map that unifies with maps even if it\n doesn't share all of the keys of that map.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/partial-map"},{"ns":"clojure.core.logic","name":"*logic-dbs*","file":"clojure/core/logic.clj","type":"var","column":1,"see-alsos":null,"dynamic":true,"line":1235,"examples":null,"notes":null,"arglists":[],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/*logic-dbs*"},{"ns":"clojure.core.logic","name":"and*","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":1273,"examples":null,"notes":null,"arglists":["goals"],"doc":"A function version of all, which takes a list of goals and succeeds only fi they all succeed.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/and*"},{"ns":"clojure.core.logic","name":"unify-with-map*","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":911,"examples":null,"notes":null,"arglists":["u v s"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/unify-with-map*"},{"ns":"clojure.core.logic","name":"runcg","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":2053,"examples":null,"notes":null,"arglists":["c"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/runcg"},{"ns":"clojure.core.logic","name":"matcha","file":"clojure/core/logic.clj","type":"macro","column":1,"see-alsos":null,"line":1738,"examples":null,"macro":true,"notes":null,"arglists":["xs & cs"],"doc":"Define a soft cut pattern match. See conda.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/matcha"},{"ns":"clojure.core.logic","name":"ientailed?","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":2061,"examples":null,"notes":null,"arglists":["c"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/ientailed_q"},{"ns":"clojure.core.logic","name":"lcons?","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":875,"examples":null,"notes":null,"arglists":["x"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/lcons_q"},{"ns":"clojure.core.logic","name":"ext-run-csg","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":1152,"examples":null,"notes":null,"arglists":["u v"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/ext-run-csg"},{"ns":"clojure.core.logic","name":"emptyo","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":1654,"examples":null,"notes":null,"arglists":["a"],"doc":"A relation where a is the empty list","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/emptyo"},{"ns":"clojure.core.logic","name":"unbound-rands","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":97,"examples":null,"notes":null,"arglists":["a c"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/unbound-rands"},{"ns":"clojure.core.logic","name":"updatecg","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":2045,"examples":null,"notes":null,"arglists":["c"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/updatecg"},{"ns":"clojure.core.logic","name":"reify-lvar-name","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":253,"examples":null,"notes":null,"arglists":["s"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/reify-lvar-name"},{"ns":"clojure.core.logic","name":"reify-constraints","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":2164,"examples":null,"notes":null,"arglists":["v r a"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/reify-constraints"},{"ns":"clojure.core.logic","name":"lvar","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":706,"examples":[{"updated-at":1480022982266,"created-at":1480022982266,"author":{"login":"freckletonj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8399149?v=3"},"body":"(let [x (lvar 'x)]\n (run 10 [q]\n (membero x [1 2 3])\n (== q x)))","_id":"58375bc6e4b0782b632278cb"}],"notes":null,"arglists":["","name","name unique"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/lvar"},{"ns":"clojure.core.logic","name":"unify","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":236,"examples":null,"notes":null,"arglists":["s u v"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/unify"},{"ns":"clojure.core.logic","name":"to-stream","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":1794,"examples":null,"notes":null,"arglists":["aseq"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/to-stream"},{"ns":"clojure.core.logic","name":"s#","file":"clojure/core/logic.clj","type":"var","column":1,"see-alsos":null,"line":1148,"examples":null,"notes":null,"arglists":[],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/s#"},{"ns":"clojure.core.logic","name":"trace-s","file":"clojure/core/logic.clj","type":"macro","column":1,"see-alsos":[{"created-at":1668965882210,"author":{"login":"claj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/353113?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"log","ns":"clojure.core.logic"},"_id":"637a65fae4b0b1e3652d768b"}],"line":1295,"examples":[{"updated-at":1668965824190,"created-at":1668965824190,"author":{"login":"claj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/353113?v=4"},"body":"\n(run* [q u v]\n (log \"no bindings:\")\n (trace-s)\n (== u 1)\n (log \"one binding:\")\n (trace-s)\n (== q 2)\n (== v 3)\n (log \"three bindings:\")\n (trace-s))\n\n;; => ([2 1 3])\n\n;; this is what gets printed from the run:\n\nno bindings:\n{ \n [ \n \n ]}\n\none binding:\n{ \n [ \n \n ], \n 1}\n\nthree bindings:\n{ \n [\n \n ],\n 1, \n 2, \n 3}","_id":"637a65c0e4b0b1e3652d768a"}],"macro":true,"notes":null,"arglists":[""],"doc":"Goal that prints the current substitution","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/trace-s"},{"ns":"clojure.core.logic","name":"->Substitutions","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":287,"examples":null,"notes":null,"arglists":["s vs ts cs cq cqs oc _meta"],"doc":"Positional factory function for class clojure.core.logic.Substitutions.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/->Substitutions"},{"ns":"clojure.core.logic","name":"enforce-constraints","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":2156,"examples":null,"notes":null,"arglists":["x"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/enforce-constraints"},{"ns":"clojure.core.logic","name":"rembero","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":2483,"examples":[{"editors":[{"login":"freckletonj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8399149?v=3"}],"body":";;https://github.com/clojure/core.logic/blob/master/src/main/clojure/clojure/core/logic.clj#L2483\n;; (rembero x l o)\n;; my simple reminder is: x+o=l (L, not 1)\n\n(run* [q]\n (fresh [a b x y]\n (== q [a b])\n (rembero a [:apple :banana :carrot] x)\n (rembero b x y)))\n;; ([:apple :banana] [:apple :carrot] [:banana :apple] [:banana :carrot] [:carrot :apple] [:carrot :banana])","author":{"avatar-url":"https://avatars.githubusercontent.com/u/8399149?v=3","account-source":"github","login":"freckletonj"},"created-at":1460390058189,"updated-at":1460390756178,"_id":"570bc8aae4b075f5b2c864e4"}],"notes":null,"arglists":["x l o"],"doc":"A relation between l and o where x is removed from\n l exactly one time.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/rembero"},{"ns":"clojure.core.logic","name":"permuteo","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":1781,"examples":[{"editors":[{"login":"freckletonj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8399149?v=3"}],"body":"(run* [q]\n (permuteo [:c q :a] [:b :a :c])) ;; :b","author":{"avatar-url":"https://avatars.githubusercontent.com/u/8399149?v=3","account-source":"github","login":"freckletonj"},"created-at":1460065748768,"updated-at":1460065872775,"_id":"5706d5d4e4b075f5b2c864d0"}],"notes":null,"arglists":["xl yl"],"doc":"A relation that will permute xl into the yl. May not\n terminate if xl is not ground.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/permuteo"},{"ns":"clojure.core.logic","name":"llist","file":"clojure/core/logic.clj","type":"macro","column":1,"see-alsos":[{"created-at":1460389651286,"author":{"login":"freckletonj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8399149?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"lcons","ns":"clojure.core.logic"},"_id":"570bc713e4b0fc95a97eab43"}],"line":878,"examples":[{"editors":[{"login":"freckletonj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8399149?v=3"}],"body":"(run* [q]\n (fresh [a d]\n (== [1 2 3 4] (llist a d))\n (== q d))) ;; ((2 3 4))\n\n(run* [q]\n (fresh [a d r]\n (== [1 2 3 4] (llist a d r))\n (== q r))) ;; a=1, d=2, r=(3 4)","author":{"avatar-url":"https://avatars.githubusercontent.com/u/8399149?v=3","account-source":"github","login":"freckletonj"},"created-at":1460389406664,"updated-at":1460389513893,"_id":"570bc61ee4b075f5b2c864e0"}],"macro":true,"notes":null,"arglists":["f s","f s & rest"],"doc":"Constructs a sequence from 2 or more arguments, with the last argument as the\n tail. The tail is improper if the last argument is a logic variable.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/llist"},{"ns":"clojure.core.logic","name":"ext","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":220,"examples":null,"notes":null,"arglists":["s u v"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/ext"},{"ns":"clojure.core.logic","name":"onceo","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":1434,"examples":null,"notes":null,"arglists":["g"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/onceo"},{"ns":"clojure.core.logic","name":"run","file":"clojure/core/logic.clj","type":"macro","column":1,"see-alsos":null,"line":1237,"examples":[{"updated-at":1593353821796,"created-at":1593353821796,"author":{"login":"ertugrulcetin","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/8271291?v=4"},"body":";; Solves 3X + 2Y + Z = 3 equation\n(let [symbols '[X Y Z]\n vars (repeatedly (count symbols) lvar)\n [x y z] vars\n sum 3]\n (run 1 [q]\n (everyg #(fd/in % (fd/interval 0 sum)) vars)\n (fresh [pro-x pro-y pro-z sum-x-y]\n (fd/* 3 x pro-x)\n (fd/* 2 y pro-y)\n (fd/* 1 z pro-z)\n (fd/+ pro-x pro-y sum-x-y)\n (fd/+ sum-x-y pro-z sum))\n (== q (zipmap symbols vars))))\n\n;;=> ({X 0, Y 0, Z 3})\n;; since we limit number of results with 1, only one solution is returned\n;; if we replace (run 1 ...) with (run* ...) then we get 3 (all) results\n","_id":"5ef8a65de4b0b1e3652d7317"}],"macro":true,"notes":null,"arglists":["n bindings & goals"],"doc":"Executes goals until a maximum of n results are found.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/run"},{"ns":"clojure.core.logic","name":"unify-with-pmap*","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":2497,"examples":null,"notes":null,"arglists":["u v s"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/unify-with-pmap*"},{"ns":"clojure.core.logic","name":"defnc","file":"clojure/core/logic.clj","type":"macro","column":1,"see-alsos":[{"created-at":1460136453300,"author":{"login":"freckletonj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8399149?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"defnu","ns":"clojure.core.logic"},"_id":"5707ea05e4b0fc95a97eab38"},{"created-at":1460136464708,"author":{"login":"freckletonj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8399149?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"defna","ns":"clojure.core.logic"},"_id":"5707ea10e4b075f5b2c864d4"},{"created-at":1460136479959,"author":{"login":"freckletonj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8399149?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"defne","ns":"clojure.core.logic"},"_id":"5707ea1fe4b0fc95a97eab39"},{"created-at":1571647061473,"author":{"login":"svdo","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/4028554?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"fnc","ns":"clojure.core.logic"},"_id":"5dad6e55e4b0ca44402ef7d0"}],"line":2653,"examples":[{"updated-at":1460067011666,"created-at":1460067011666,"author":{"login":"freckletonj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8399149?v=3"},"body":";; I'm not exactly sure what `defnc` is, but I know a little how to use it\n;; The following gets all multiples of 3 in the `(range 50)`\n\n(defnc dev3c [x]\n (zero? (mod x 3)))\n\n(run* [x]\n (membero x (range 50))\n (dev3c x))","_id":"5706dac3e4b075f5b2c864d1"}],"macro":true,"notes":null,"arglists":["name args & body"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/defnc"},{"ns":"clojure.core.logic","name":"tramp","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":2695,"examples":null,"notes":null,"arglists":["f"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/tramp"},{"ns":"clojure.core.logic","name":"->Pair","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":43,"examples":null,"notes":null,"arglists":["lhs rhs"],"doc":"Positional factory function for class clojure.core.logic.Pair.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/->Pair"},{"ns":"clojure.core.logic","name":"mplus*","file":"clojure/core/logic.clj","type":"macro","column":1,"see-alsos":null,"line":1072,"examples":null,"macro":true,"notes":null,"arglists":["e","e & e-rest"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/mplus*"},{"ns":"clojure.core.logic","name":"fnc","file":"clojure/core/logic.clj","type":"macro","column":1,"see-alsos":null,"line":2611,"examples":null,"macro":true,"notes":null,"arglists":["args & body"],"doc":"Define an anonymous constraint that can be used with the unifier:\n\n (let [oddc (fnc [x] (odd? x))]\n\n (unifier {:a '?a} {:a 1} :when {'?a oddc})\n ;;=> {:a 1}\n\n (unifier {:a '?a} {:a 2} :when {'?a oddc})\n ;;=> nil\n )\n\n Note, the constraint will not run until all arguments are fully ground.\n\n Use defnc to define a constraint and assign a toplevel var.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/fnc"},{"ns":"clojure.core.logic","name":"run-nc","file":"clojure/core/logic.clj","type":"macro","column":1,"see-alsos":null,"line":1257,"examples":null,"macro":true,"notes":null,"arglists":["n bindings & goals"],"doc":"Executes goals until a maximum of n results are found. Does not\n occurs-check.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/run-nc"},{"ns":"clojure.core.logic","name":"lcons","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":[{"created-at":1460389630764,"author":{"login":"freckletonj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8399149?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"llist","ns":"clojure.core.logic"},"_id":"570bc6fee4b075f5b2c864e3"}],"line":868,"examples":[{"updated-at":1460389621203,"created-at":1460389621203,"author":{"login":"freckletonj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8399149?v=3"},"body":"(run* [q]\n (fresh [a d]\n (== [1 2 3 4] (lcons a d))\n (== q d))) ;; ((2 3 4))","_id":"570bc6f5e4b075f5b2c864e2"},{"updated-at":1581848387951,"created-at":1581286402438,"author":{"login":"mdzaebel","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/415392?v=4"},"body":"(run* [t] (== [1 2 3] (lcons 1 t)))\n;;=> ((2 3))","editors":[{"avatar-url":"https://avatars3.githubusercontent.com/u/415392?v=4","account-source":"github","login":"mdzaebel"}],"_id":"5e408402e4b0ca44402ef82e"}],"notes":null,"arglists":["a d"],"doc":"Constructs a sequence a with an improper tail d if d is a logic variable.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/lcons"},{"ns":"clojure.core.logic","name":"solutions","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":1279,"examples":null,"notes":null,"arglists":["s g","s q g"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/solutions"},{"ns":"clojure.core.logic","name":"stopcg","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":2057,"examples":null,"notes":null,"arglists":["c"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/stopcg"},{"ns":"clojure.core.logic","name":"copy-term","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":1439,"examples":null,"notes":null,"arglists":["u v"],"doc":"Copies a term u into v. Non-relational.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/copy-term"},{"ns":"clojure.core.logic","name":"disunify","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":2290,"examples":null,"notes":null,"arglists":["s u v","s u v cs"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/disunify"},{"ns":"clojure.core.logic","name":"sort-by-strategy","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":2223,"examples":null,"notes":null,"arglists":["v x a"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/sort-by-strategy"},{"ns":"clojure.core.logic","name":"add-dom","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":467,"examples":null,"notes":null,"arglists":["s x dom domv","s x dom domv seenset"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/add-dom"},{"ns":"clojure.core.logic","name":"fnm","file":"clojure/core/logic.clj","type":"macro","column":1,"see-alsos":null,"line":1632,"examples":null,"macro":true,"notes":null,"arglists":["t as tabled? & cs"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/fnm"},{"ns":"clojure.core.logic","name":"pred","file":"clojure/core/logic.clj","type":"macro","column":1,"see-alsos":null,"line":1336,"examples":[{"updated-at":1450639518107,"created-at":1450639518107,"author":{"login":"qneo","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/5214601?v=3"},"body":"user> (run* [q] (pred q symbol?))\n()\nuser> (run* [q] (== q 'x) (pred q symbol?))\n(x)\nuser> (run* [q] (== q 1) (pred q symbol?))\n()\nuser> (run* [q] (== q 1) (pred q number?))\n(1)","_id":"5677009ee4b08a3916795380"},{"updated-at":1640474969522,"created-at":1640474969522,"author":{"login":"hank-lenzi","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/48740267?v=4"},"body":"Example From PC3\n\nuser> (defn indexed [coll] (map-indexed vector coll))\n#'user/indexed\n\nuser> (indexed \"abcde\")\n([0 \\a] [1 \\b] [2 \\c] [3 \\d] [4 \\e])\n\n(defn index-filter [pred coll]\n (when pred\n (for [[idx elt] (indexed coll) :when (pred elt)] idx)))\n\n(index-filter #{\\a \\b} \"abcdbbb\")\n-> (0 1 4 5 6)\n\n;;; NOTES\n;; 'for' used destructuring above. 'for' is not a loop - \n;; it's 'list comprehension'.\n;; 'pred' is a predicate and a lisp form (i.e., 'keyword') in core.logic\n;; - https://clojuredocs.org/clojure.core.logic/pred\n;; It's from https://clojuredocs.org/clojure.core.logic\n;; and NOT included in core\n;; https://github.com/clojure/core.logic\n;; for forms accept bindings (':let') , filters (with ':when')\n;; and restraints (':when') .\n","_id":"61c7a959e4b0b1e3652d758d"},{"editors":[{"login":"wactbprot","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/113518?v=4"}],"body":"user> (use '[clojure.core.logic :only [run* membero pred]])\n\n;; The position of the pred expression matters:\n\nuser> (run* [q]\n (pred q keyword?)\n (membero q [1 :a :b])\n (membero q [1 :a :c]))\n;; => ()\n\nuser> (run* [q]\n (membero q [1 :a :b])\n (membero q [1 :a :c])\n (pred q keyword?))\n;; => (:a)\n","author":{"avatar-url":"https://avatars.githubusercontent.com/u/113518?v=4","account-source":"github","login":"wactbprot"},"created-at":1640857443937,"updated-at":1640858964293,"_id":"61cd7f63e4b0b1e3652d7590"}],"macro":true,"notes":null,"arglists":["v f"],"doc":"Check a predicate against the value logic var. Non-relational.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/pred"},{"ns":"clojure.core.logic","name":"sync-eset","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":455,"examples":null,"notes":null,"arglists":["s v seenset f"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/sync-eset"},{"ns":"clojure.core.logic","name":"is","file":"clojure/core/logic.clj","type":"macro","column":1,"see-alsos":null,"line":1344,"examples":[{"updated-at":1668939955671,"created-at":1668939955671,"author":{"login":"claj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/353113?v=4"},"body":";; assign v == 3, q == v * 10 (and, really, use clojure.core.logic.fd for this particular operation)\n\n(run* [q v]\n (== v 3)\n (is q v (fn [a] (* a 10))))","_id":"637a00b3e4b0b1e3652d7688"}],"macro":true,"notes":null,"arglists":["u v op"],"doc":"Set the value of a var to value of another var with the operation\n applied. Non-relational.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/is"},{"ns":"clojure.core.logic","name":"->LCons","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":755,"examples":null,"notes":null,"arglists":["a d cache meta"],"doc":"Positional factory function for class clojure.core.logic.LCons.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/->LCons"},{"ns":"clojure.core.logic","name":"umi","file":"clojure/core/logic.clj","type":"macro","column":1,"see-alsos":null,"line":741,"examples":null,"macro":true,"notes":null,"arglists":["& args"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/umi"},{"ns":"clojure.core.logic","name":"assoc-meta","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":24,"examples":null,"notes":null,"arglists":["x k v"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/assoc-meta"},{"ns":"clojure.core.logic","name":"conda","file":"clojure/core/logic.clj","type":"macro","column":1,"see-alsos":[{"created-at":1468922820940,"author":{"login":"freaxmind","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/3929438?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"condu","ns":"clojure.core.logic"},"_id":"578dfbc4e4b0bafd3e2a04a9"},{"created-at":1468922827794,"author":{"login":"freaxmind","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/3929438?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"conde","ns":"clojure.core.logic"},"_id":"578dfbcbe4b0bafd3e2a04aa"},{"created-at":1468922837244,"author":{"login":"freaxmind","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/3929438?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"defna","ns":"clojure.core.logic"},"_id":"578dfbd5e4b0bafd3e2a04ab"},{"created-at":1468922843584,"author":{"login":"freaxmind","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/3929438?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"fna","ns":"clojure.core.logic"},"_id":"578dfbdbe4b0bafd3e2a04ac"}],"line":1417,"examples":[{"updated-at":1468925514081,"created-at":1468925514081,"author":{"login":"freaxmind","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/3929438?v=3"},"body":";; Mind the order:\n\n(defn logic-test-1 []\n (run* [q r]\n (membero q [\"linux\" \"windows\" \"mac\" \"android\" \"\"])\n (conda\n [(membero q [\"linux\" \"windows\"]) (== r 1)]\n [(== q \"mac\") (== r 2)]\n [succeed (== q \"\") (== r 3)])))\n;; => ([\"linux\" 1] [\"windows\" 1] [\"mac\" 2] [\"\" 3])\n;; conda takes ground values and matches them one by one against its clauses. \n\n(defn logic-test-2 []\n (run* [q r]\n (conda\n [(membero q [\"linux\" \"windows\"]) (== r 1)]\n [(== q \"mac\") (== r 2)]\n [succeed (== q \"\") (== r 3)])\n (membero q [\"linux\" \"windows\" \"mac\" \"android\" \"\"])))\n;; ([\"linux\" 1] [\"windows\" 1])\n;; conda takes a fresh variable and associates it to the head of its first clause.\n;; only the rest of the first clause (== r 1) is considered","_id":"578e064ae4b0bafd3e2a04ad"},{"updated-at":1651392808446,"created-at":1651392808446,"author":{"login":"shenlebantongying","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/20123683?v=4"},"body":";; The order of \"cond\"s matters\n\n(run* [q]\n (conda\n [(membero 1 [q 2 3])]\n [(membero q [4 5 6])]))\n;; => (1)\n\n\n(run* [q]\n (conda\n [(membero q [4 5 6])]\n [(membero 1 [q 2 3])]))\n;; => (4 5 6)","_id":"626e4128e4b0b1e3652d75de"}],"macro":true,"notes":null,"arglists":["& clauses"],"doc":"Soft cut. Once the head of a clause has succeeded\n all other clauses will be ignored. Non-relational.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/conda"},{"ns":"clojure.core.logic","name":"run-constraints*","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":2115,"examples":null,"notes":null,"arglists":["xs cs ws"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/run-constraints*"},{"ns":"clojure.core.logic","name":"let-dom","file":"clojure/core/logic.clj","type":"macro","column":1,"see-alsos":null,"line":2211,"examples":null,"macro":true,"notes":null,"arglists":["a vars & body"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/let-dom"},{"ns":"clojure.core.logic","name":"-reify","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":263,"examples":null,"notes":null,"arglists":["s v","s v r"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/-reify"},{"ns":"clojure.core.logic","name":"run-constraint","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":2070,"examples":null,"notes":null,"arglists":["c"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/run-constraint"},{"ns":"clojure.core.logic","name":"->ConstraintStore","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":109,"examples":null,"notes":null,"arglists":["km cm cid running"],"doc":"Positional factory function for class clojure.core.logic.ConstraintStore.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/->ConstraintStore"},{"ns":"clojure.core.logic","name":"make-suspended-stream","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":1854,"examples":null,"notes":null,"arglists":["cache ansv* f"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/make-suspended-stream"},{"ns":"clojure.core.logic","name":"tree-term?","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":884,"examples":null,"notes":null,"arglists":["x"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/tree-term_q"},{"ns":"clojure.core.logic","name":"fna","file":"clojure/core/logic.clj","type":"macro","column":1,"see-alsos":null,"line":1718,"examples":null,"macro":true,"notes":null,"arglists":["& rest"],"doc":"Define an anonymous soft cut goal. See conda.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/fna"},{"ns":"clojure.core.logic","name":"*locals*","file":"clojure/core/logic.clj","type":"var","column":1,"see-alsos":null,"dynamic":true,"line":17,"examples":null,"notes":null,"arglists":[],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/*locals*"},{"ns":"clojure.core.logic","name":"unbound-names","file":"clojure/core/logic.clj","type":"var","column":1,"see-alsos":null,"line":249,"examples":null,"notes":null,"arglists":[],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/unbound-names"},{"ns":"clojure.core.logic","name":"member1o","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":1762,"examples":null,"notes":null,"arglists":["x l"],"doc":"Like membero but uses to disequality further constraining\n the results. For example, if x and l are ground and x occurs\n multiple times in l, member1o will succeed only once.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/member1o"},{"ns":"clojure.core.logic","name":"pair","file":"clojure/core/logic.clj","type":"var","column":1,"see-alsos":null,"line":214,"examples":null,"notes":null,"arglists":[],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/pair"},{"ns":"clojure.core.logic","name":"walk-record-term","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":969,"examples":null,"notes":null,"arglists":["v f"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/walk-record-term"},{"ns":"clojure.core.logic","name":"lvaro","file":"clojure/core/logic.clj","type":"macro","column":1,"see-alsos":null,"line":1448,"examples":null,"macro":true,"notes":null,"arglists":["v"],"doc":"A goal that succeeds if the argument is fresh. v must be a logic\n variable. Non-relational.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/lvaro"},{"ns":"clojure.core.logic","name":"map->PMap","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":2518,"examples":null,"notes":null,"arglists":["m__8001__auto__"],"doc":"Factory function for class clojure.core.logic.PMap, taking a map of keywords to field values.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/map->PMap"},{"ns":"clojure.core.logic","name":"annotate","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":547,"examples":null,"notes":null,"arglists":["k v"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/annotate"},{"ns":"clojure.core.logic","name":"empty-f","file":"clojure/core/logic.clj","type":"var","column":1,"see-alsos":null,"line":538,"examples":null,"notes":null,"arglists":[],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/empty-f"},{"ns":"clojure.core.logic","name":"->LVar","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":621,"examples":null,"notes":null,"arglists":["id unique name oname hash meta"],"doc":"Positional factory function for class clojure.core.logic.LVar.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/->LVar"},{"ns":"clojure.core.logic","name":"update-pvars!","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":1492,"examples":null,"notes":null,"arglists":["x vars"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/update-pvars!"},{"ns":"clojure.core.logic","name":"tabled","file":"clojure/core/logic.clj","type":"macro","column":1,"see-alsos":null,"line":1997,"examples":null,"macro":true,"notes":null,"arglists":["args & grest"],"doc":"Macro for defining a tabled goal. Prefer ^:tabled with the\n defne/a/u forms over using this directly.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/tabled"},{"ns":"clojure.core.logic","name":"resto","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":[{"created-at":1490671466023,"author":{"login":"tkocmathla","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/183459?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"firsto","ns":"clojure.core.logic"},"_id":"58d9d76ae4b01f4add58fe7a"}],"line":1671,"examples":null,"notes":null,"arglists":["l d"],"doc":"A relation where l is a collection, such that d is the rest of l","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/resto"},{"ns":"clojure.core.logic","name":"ifu*","file":"clojure/core/logic.clj","type":"macro","column":1,"see-alsos":null,"line":1369,"examples":null,"macro":true,"notes":null,"arglists":["","[e & gs] & grest"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/ifu*"},{"ns":"clojure.core.logic","name":"unify-with-sequential*","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":893,"examples":null,"notes":null,"arglists":["u v s"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/unify-with-sequential*"},{"ns":"clojure.core.logic","name":"add-attr","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":432,"examples":null,"notes":null,"arglists":["s x attr attrv"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/add-attr"},{"ns":"clojure.core.logic","name":"walk*","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":227,"examples":null,"notes":null,"arglists":["s v"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/walk*"},{"ns":"clojure.core.logic","name":"->AnswerCache","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":1818,"examples":null,"notes":null,"arglists":["ansl anss _meta"],"doc":"Positional factory function for class clojure.core.logic.AnswerCache.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/->AnswerCache"},{"ns":"clojure.core.logic","name":"enforceable-constrained","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":2140,"examples":null,"notes":null,"arglists":["a"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/enforceable-constrained"},{"ns":"clojure.core.logic","name":"bindable?","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":732,"examples":null,"notes":null,"arglists":["x"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/bindable_q"},{"ns":"clojure.core.logic","name":"->Choice","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":1084,"examples":null,"notes":null,"arglists":["a f"],"doc":"Positional factory function for class clojure.core.logic.Choice.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/->Choice"},{"ns":"clojure.core.logic","name":"defne","file":"clojure/core/logic.clj","type":"macro","column":1,"see-alsos":[{"created-at":1460136376057,"author":{"login":"freckletonj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8399149?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"defna","ns":"clojure.core.logic"},"_id":"5707e9b8e4b0fc95a97eab36"},{"created-at":1460136395724,"author":{"login":"freckletonj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8399149?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"defnu","ns":"clojure.core.logic"},"_id":"5707e9cbe4b075f5b2c864d3"},{"created-at":1460136407118,"author":{"login":"freckletonj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8399149?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"defnc","ns":"clojure.core.logic"},"_id":"5707e9d7e4b0fc95a97eab37"},{"created-at":1460143705697,"author":{"login":"freckletonj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8399149?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"fne","ns":"clojure.core.logic"},"_id":"57080659e4b0fc95a97eab3f"},{"created-at":1490672610441,"author":{"login":"tkocmathla","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/183459?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"conde","ns":"clojure.core.logic"},"_id":"58d9dbe2e4b01f4add58fe7d"}],"line":1699,"examples":[{"updated-at":1444345575973,"created-at":1444345575973,"author":{"login":"stewSquared","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/4022813?v=3"},"body":"(defne match1 [x y]\n ([:foo :bar])\n ([:baz :qux]))\n\n(run* [x y] (match1 x y)) ;; => ([:foo :bar] [:baz :qux])\n\n(defne match2 [x y]\n ([[a b . tail] [b a . tail]]))\n\n(run* [r] (match2 '(a b c d) r)) ;; => ((b a c d))\n\n(defne match3 [x y]\n ([[a . _] [a . _]]))\n\n(run* [r] (match3 [3 2 1] [3 4 5])) ;; => (_0)","_id":"5616f6e7e4b084e61c76ecbe"},{"editors":[{"login":"freckletonj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8399149?v=3"}],"body":";; adapted from:\n;; http://stackoverflow.com/questions/11964055/constraining-two-vectors-to-be-in-the-same-domain-but-not-be-members-of-each-ot\n\n(defne not-membero [x l]\n ([_ []])\n ([_ [?y . ?r]]\n (!= x ?y)\n (not-membero x ?r)))\n\n(run* [q]\n (not-membero q [:a :b :c])) ;; ((_0 :- (!= (_0 :a)) (!= (_0 :b)) (!= (_0 :c))) \n\n(run* [q]\n (membero q [1 2 3 4 5])\n (not-membero q [2 4])) ;; (1 3 5)","author":{"avatar-url":"https://avatars.githubusercontent.com/u/8399149?v=3","account-source":"github","login":"freckletonj"},"created-at":1460087200380,"updated-at":1460143693913,"_id":"570729a0e4b075f5b2c864d2"}],"macro":true,"notes":null,"arglists":["& rest"],"doc":"Define a goal fn. Supports pattern matching. All\n patterns will be tried. See conde.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/defne"},{"ns":"clojure.core.logic","name":"featurec","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":[{"created-at":1450637745267,"author":{"login":"qneo","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/5214601?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"conjo","ns":"clojure.core.logic"},"_id":"5676f9b1e4b01f598e267e8e"}],"line":2579,"examples":[{"updated-at":1450637709624,"created-at":1450637709624,"author":{"login":"qneo","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/5214601?v=3"},"body":"user> (run 1 [q] (featurec q {1 2}) (== q {2 4}))\n() ;; {2 4} does not cointain k-v 1 2\nuser> (run 1 [q] (featurec q {1 2}) (== q {1 2 2 4}))\n({1 2, 2 4}) ;; {1 2 2 4} does contain k-v 1 2","_id":"5676f98de4b01f598e267e8c"},{"updated-at":1460576267720,"created-at":1460576267720,"author":{"login":"freckletonj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8399149?v=3"},"body":";; http://michaelrbernste.in/2013/05/12/featurec-and-maps.html\n;; http://stackoverflow.com/questions/15821718/how-do-i-de-structure-a-map-in-core-logic\n\n(is (= (run* [q]\n (featurec q {:foo 1})\n (== q {:foo 1 :bar 2}))\n '({:foo 1 :bar 2})))","_id":"570ea00be4b0fc95a97eab4b"},{"updated-at":1596504989470,"created-at":1596503615103,"author":{"login":"owenRiddy","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/8080718?v=4"},"body":";;\n;; Using featurec rather than == can trigger bugs.\n;; \n\n(run* [p]\n (featurec p {:a 1})\n (fresh [m]\n (== p {:a m})))\n;; => Error printing return value (IllegalArgumentException) at \n;; => clojure.lang.RT/seqFrom (RT.java:557).\n;; => Don't know how to create ISeq from: java.lang.Long\n\n(run* [p]\n (== p {:a 1})\n (featurec p {:a 1})\n (fresh [m]\n (== p {:a m})))\n;; => ({:a 1})","editors":[{"avatar-url":"https://avatars0.githubusercontent.com/u/8080718?v=4","account-source":"github","login":"owenRiddy"}],"_id":"5f28b63fe4b0b1e3652d7341"}],"notes":null,"arglists":["x fs"],"doc":"Ensure that a map contains at least the key-value pairs\n in the map fs. fs must be partially instantiated - that is,\n it may contain values which are logic variables to support\n feature extraction.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/featurec"},{"ns":"clojure.core.logic","name":"force-ans","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":2273,"examples":null,"notes":null,"arglists":["x"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/force-ans"},{"ns":"clojure.core.logic","name":"normalize-store","file":"clojure/core/logic.clj","type":"var","column":1,"see-alsos":null,"line":2407,"examples":null,"notes":null,"arglists":[],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/normalize-store"},{"ns":"clojure.core.logic","name":"update-dom","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":480,"examples":null,"notes":null,"arglists":["s x dom f","s x dom f seenset"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/update-dom"},{"ns":"clojure.core.logic","name":"membero","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":1755,"examples":[{"editors":[{"login":"freckletonj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8399149?v=3"}],"body":";; Usage: (membero x l)\n\n(run* [q]\n (membero :a [q :b :c])) ;; :a\n(run* [q]\n (membero q [:a :b :c])) ;; [:a :b :c]\n","author":{"avatar-url":"https://avatars.githubusercontent.com/u/8399149?v=3","account-source":"github","login":"freckletonj"},"created-at":1460065964061,"updated-at":1460139875793,"_id":"5706d6ace4b0fc95a97eab35"},{"updated-at":1654526190348,"created-at":1654526190348,"author":{"login":"zackteo","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7510179?v=4"},"body":" (run* [q]\n (membero q [1 2 3])\n (membero q [2 3 4])) ;;=> (2 3)","_id":"629e10eee4b0b1e3652d75f9"}],"notes":null,"arglists":["x l"],"doc":"A relation where l is a collection, such that l contains x.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/membero"},{"ns":"clojure.core.logic","name":"merge-doms","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":558,"examples":null,"notes":null,"arglists":["s x doms"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/merge-doms"},{"ns":"clojure.core.logic","name":"matchu","file":"clojure/core/logic.clj","type":"macro","column":1,"see-alsos":null,"line":1744,"examples":null,"macro":true,"notes":null,"arglists":["xs & cs"],"doc":"Define a committed choice goal. See condu.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/matchu"},{"ns":"clojure.core.logic","name":"fixc","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":2871,"examples":null,"notes":null,"arglists":["x f reifier","x f runnable reifier"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/fixc"},{"ns":"clojure.core.logic","name":"lvar?","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":726,"examples":null,"notes":null,"arglists":["x"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/lvar_q"},{"ns":"clojure.core.logic","name":"answer-cache","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":1844,"examples":null,"notes":null,"arglists":[""],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/answer-cache"},{"ns":"clojure.core.logic","name":"run-constraints","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":2105,"examples":null,"notes":null,"arglists":["xcs"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/run-constraints"},{"ns":"clojure.core.logic","name":"all","file":"clojure/core/logic.clj","type":"macro","column":1,"see-alsos":[{"created-at":1571658725931,"author":{"login":"svdo","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/4028554?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"fresh","ns":"clojure.core.logic"},"_id":"5dad9be5e4b0ca44402ef7d1"},{"created-at":1680599621892,"author":{"login":"port19x","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/82055622?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"every?","ns":"clojure.core"},"_id":"642bea45e4b08cf8563f4b8c"}],"line":1268,"examples":null,"macro":true,"notes":null,"arglists":["","& goals"],"doc":"Like fresh but does does not create logic variables.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/all"},{"ns":"clojure.core.logic","name":"or*","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":1185,"examples":null,"notes":null,"arglists":["goals"],"doc":"A function version of conde, which takes a list of goals and tries them as if via conde.\n Note that or* only does disjunction, ie (or* [a b c]) is the same as (conde [a] [b] [c]).\n If you need something like (conde [a b] [c]), you can use and*, or all:\n (or* [(and* a b) c]).","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/or*"},{"ns":"clojure.core.logic","name":"->PMap","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":2518,"examples":null,"notes":null,"arglists":[""],"doc":"Positional factory function for class clojure.core.logic.PMap.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/->PMap"},{"ns":"clojure.core.logic","name":"u#","file":"clojure/core/logic.clj","type":"var","column":1,"see-alsos":null,"line":1150,"examples":null,"notes":null,"arglists":[],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/u#"},{"ns":"clojure.core.logic","name":"trace-lvar","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":1302,"examples":null,"notes":null,"arglists":["a lvar"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/trace-lvar"},{"ns":"clojure.core.logic","name":"add-var","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":178,"examples":null,"notes":null,"arglists":["cs x c"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/add-var"},{"ns":"clojure.core.logic","name":"to-s","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":543,"examples":null,"notes":null,"arglists":["v"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/to-s"},{"ns":"clojure.core.logic","name":"waiting-stream?","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":1860,"examples":null,"notes":null,"arglists":["x"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/waiting-stream_q"},{"ns":"clojure.core.logic","name":"-fnm","file":"clojure/core/logic.clj","type":"macro","column":1,"see-alsos":null,"line":1628,"examples":null,"macro":true,"notes":null,"arglists":["fn-gen t as & cs"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/-fnm"},{"ns":"clojure.core.logic","name":"distribute","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":2283,"examples":null,"notes":null,"arglists":["v* strategy"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/distribute"},{"ns":"clojure.core.logic","name":"occurs-check","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":216,"examples":null,"notes":null,"arglists":["s u v"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/occurs-check"},{"ns":"clojure.core.logic","name":"predc","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":2687,"examples":null,"notes":null,"arglists":["x p","x p pform"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/predc"},{"ns":"clojure.core.logic","name":"entailed?","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":2064,"examples":null,"notes":null,"arglists":["c c' a"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/entailed_q"},{"ns":"clojure.core.logic","name":"->SubstValue","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":197,"examples":null,"notes":null,"arglists":["v doms eset"],"doc":"Positional factory function for class clojure.core.logic.SubstValue.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/->SubstValue"},{"ns":"clojure.core.logic","name":"-featurec","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":2549,"examples":null,"notes":null,"arglists":["x fs"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/-featurec"},{"ns":"clojure.core.logic","name":"rem-dom","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":494,"examples":null,"notes":null,"arglists":["s x dom","s x dom seenset"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/rem-dom"},{"ns":"clojure.core.logic","name":"update-eset","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":572,"examples":null,"notes":null,"arglists":["s doms eset"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/update-eset"},{"ns":"clojure.core.logic","name":"conso","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":[{"created-at":1562862235221,"author":{"login":"kannangce","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/8754040?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"cons","ns":"clojure.core"},"_id":"5d27629be4b0ca44402ef780"}],"line":1659,"examples":[{"updated-at":1562862221958,"created-at":1562862221958,"author":{"login":"kannangce","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/8754040?v=4"},"body":";; conso for 1 lvar\n\n(run* [x] (conso 1 x [1 2 3 4]))\n\n;; ((2 3 4))\n\n\n;; conso for 2 lvar\n\n(run* [x y] (conso x y [1 2 3 4]))\n\n;; ([1 (2 3 4)])","_id":"5d27628de4b0ca44402ef77f"}],"notes":null,"arglists":["a d l"],"doc":"A relation where l is a collection, such that a is the first of l\n and d is the rest of l. If ground d must be bound to a proper tail.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/conso"},{"ns":"clojure.core.logic","name":"nilo","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":1649,"examples":null,"notes":null,"arglists":["a"],"doc":"A relation where a is nil","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/nilo"},{"ns":"clojure.core.logic","name":"nonlvaro","file":"clojure/core/logic.clj","type":"macro","column":1,"see-alsos":null,"line":1456,"examples":null,"macro":true,"notes":null,"arglists":["v"],"doc":"A goal that succeeds if the argument is not fresh. v must be a\n logic variable. Non-relational.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/nonlvaro"},{"ns":"clojure.core.logic","name":"uai","file":"clojure/core/logic.clj","type":"macro","column":1,"see-alsos":null,"line":747,"examples":null,"macro":true,"notes":null,"arglists":["& args"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/uai"},{"ns":"clojure.core.logic","name":"fail","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":1144,"examples":null,"notes":null,"arglists":["a"],"doc":"A goal that always fails.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/fail"},{"ns":"clojure.core.logic","name":"get-attr","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":450,"examples":null,"notes":null,"arglists":["s x attr"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/get-attr"},{"ns":"clojure.core.logic","name":"-fixc","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":2843,"examples":null,"notes":null,"arglists":["x f reifier","x f runnable reifier"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/-fixc"},{"ns":"clojure.core.logic","name":"build","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":271,"examples":null,"notes":null,"arglists":["s u"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/build"},{"ns":"clojure.core.logic","name":"everyg","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":1677,"examples":[{"editors":[{"login":"zackteo","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7510179?v=4"}],"body":"\n;; everyg takes a goal and a seq of lvars and \n;; applies the goal for each of the lvars.\n\n;; For ex,\n\n(run* [x y]\n (fd/in x (fd/domain 1 2))\n (fd/in y (fd/domain 1 2)))\n\n;; can be rewritten as \n\n(run* [x y]\n (everyg #(fd/in % (fd/domain 1 2)) [x y]))\n\n;; For O/P\n;; ([1 1] [2 1] [1 2] [2 2])","author":{"avatar-url":"https://avatars0.githubusercontent.com/u/8754040?v=4","account-source":"github","login":"kannangce"},"created-at":1563388435865,"updated-at":1655422626875,"_id":"5d2f6a13e4b0ca44402ef786"}],"notes":null,"arglists":["g coll"],"doc":"A pseudo-relation that takes a coll and ensures that the goal g\n succeeds on every element of the collection.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/everyg"},{"ns":"clojure.core.logic","name":"project","file":"clojure/core/logic.clj","type":"macro","column":1,"see-alsos":null,"line":1327,"examples":[{"editors":[{"login":"originalhat","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/579630?v=4"}],"body":";; convert lvars into values\nuser=> (cl/project [a b] (cl/== % (str a \" proposed to \" b)))\n\"Jack proposed to Mira\"","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/579630?v=4","account-source":"github","login":"originalhat"},"created-at":1605047817834,"updated-at":1605047863927,"_id":"5fab1609e4b0b1e3652d7402"},{"updated-at":1731929702548,"created-at":1731872115969,"author":{"login":"johannesCmayer","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/24253624?v=4"},"body":";; print lvar value\n(run 1 [q]\n (== q 1)\n (project [q] (do (println (str \"hi, q=\" q)) succeed)))\n\n;; hi, q=1\n\n;; => (1)","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/24253624?v=4","account-source":"github","login":"johannesCmayer"}],"_id":"673a457369fbcc0c22617511"},{"editors":[{"login":"johannesCmayer","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/24253624?v=4"}],"body":"(defne interval-0-3 [x]\n ([0])\n ([1])\n ([2]))\n\n(run 1 [q]\n (interval-0-3 q)\n (project [q] (do (println (str \"hi, q=\" q)) succeed)))\n\n;; hi, q=0\n;; hi, q=1\n;; hi, q=2\n\n;; => (1)","author":{"avatar-url":"https://avatars.githubusercontent.com/u/24253624?v=4","account-source":"github","login":"johannesCmayer"},"created-at":1731872309644,"updated-at":1731929772070,"_id":"673a463569fbcc0c22617513"}],"macro":true,"notes":null,"arglists":["[& vars] & goals"],"doc":"Extract the values bound to the specified logic vars. Non-relational.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/project"},{"ns":"clojure.core.logic","name":"-run","file":"clojure/core/logic.clj","type":"macro","column":1,"see-alsos":null,"line":1218,"examples":null,"macro":true,"notes":null,"arglists":["opts [x :as bindings] & goals"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/-run"},{"ns":"clojure.core.logic","name":"get-dom-fd","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":2205,"examples":null,"notes":null,"arglists":["a x"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/get-dom-fd"},{"ns":"clojure.core.logic","name":"-nafc","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":2701,"examples":null,"notes":null,"arglists":["c args"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/-nafc"},{"ns":"clojure.core.logic","name":"ifa*","file":"clojure/core/logic.clj","type":"macro","column":1,"see-alsos":null,"line":1361,"examples":null,"macro":true,"notes":null,"arglists":["","[e & gs] & grest"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/ifa*"},{"ns":"clojure.core.logic","name":"trace-lvars","file":"clojure/core/logic.clj","type":"macro","column":1,"see-alsos":null,"line":1305,"examples":[{"editors":[{"login":"claj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/353113?v=4"}],"body":"(run* [q]\n (fresh [v]\n (conde\n [(trace-lvars \"1:A clause\" q v)\n (== q 1)\n (== v 23)\n (trace-lvars \"1:B clause\" q v)]\n [(== q 2)\n (trace-lvars \"2:A clause\" q v)\n (== q v)\n (trace-lvars \"2:B clause\" q v)])))\n\n\n;; => (1 _0)\n\n1:A clause\n q = _0\n v = _0\n1:B clause\n q = 1\n v = 23\n2:A clause\n q = 2\n v = _0\n2:B clause\n q = 2\n v = 2","author":{"avatar-url":"https://avatars.githubusercontent.com/u/353113?v=4","account-source":"github","login":"claj"},"created-at":1669159763379,"updated-at":1669757615161,"_id":"637d5b53e4b0b1e3652d7690"}],"macro":true,"notes":null,"arglists":["title & lvars"],"doc":"Goal for tracing the values of logic variables.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/trace-lvars"},{"ns":"clojure.core.logic","name":"make-cs","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":188,"examples":null,"notes":null,"arglists":[""],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/make-cs"},{"ns":"clojure.core.logic","name":"-inc","file":"clojure/core/logic.clj","type":"macro","column":1,"see-alsos":null,"line":1077,"examples":null,"macro":true,"notes":null,"arglists":["& rest"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/-inc"},{"ns":"clojure.core.logic","name":"fne","file":"clojure/core/logic.clj","type":"macro","column":1,"see-alsos":null,"line":1693,"examples":[{"editors":[{"login":"freckletonj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8399149?v=3"}],"body":"(run 10 [q]\n ((fne [x y]\n ([[h . t] t]))\n [1 2 3] q)) ; => ((2 3))\n\n(run 10 [q]\n ((fne [x y]\n ([[o? 2 _ 4 5]] (== y o?))\n ([[1 2 _ . o?]] (== y o?)))\n [1 2 3 4 5] q))","author":{"avatar-url":"https://avatars.githubusercontent.com/u/8399149?v=3","account-source":"github","login":"freckletonj"},"created-at":1480021319437,"updated-at":1480023049650,"_id":"58375547e4b0782b632278ca"}],"macro":true,"notes":null,"arglists":["& rest"],"doc":"Define an anonymous goal fn. Supports pattern matching. All\n patterns will be tried. See conde.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/fne"},{"ns":"clojure.core.logic","name":"lvars","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":729,"examples":null,"notes":null,"arglists":["n"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/lvars"},{"ns":"clojure.core.logic","name":"subst?","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":540,"examples":null,"notes":null,"arglists":["x"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/subst_q"},{"ns":"clojure.core.logic","name":"!=","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":[{"created-at":1577762515984,"author":{"login":"yuhan0","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/22216124?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"==","ns":"clojure.core.logic"},"_id":"5e0abed3e4b0ca44402ef802"}],"line":2458,"examples":[{"editors":[{"login":"yuhan0","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/22216124?v=4"}],"body":";; Do not confuse with not= from clojure.core!\n\n(run* [a b]\n (membero a [1 2 3])\n (membero b [1 2 3])\n (!= a b))\n;; => ([1 2] [2 1] [1 3] [3 1] [2 3] [3 2])\n","author":{"avatar-url":"https://avatars.githubusercontent.com/u/7733800?v=3","account-source":"github","login":"clojurehunter"},"created-at":1437906067367,"updated-at":1576168878662,"_id":"55b4b493e4b0080a1b79cdad"}],"notes":null,"arglists":["u v"],"doc":"Disequality constraint. Ensures that u and v will never\n unify. u and v can be complex terms.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/!="},{"ns":"clojure.core.logic","name":"==","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":1156,"examples":[{"updated-at":1648391340255,"created-at":1648391340255,"author":{"login":"vimfun","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/851484?v=4"},"body":"(require '[clojure.core.logic :as logic :refer [run* ==])\n\n(run* [q]\n (== q 1))\n;; (1)\n\n(run* [q]\n (== q [1 2 3]))\n;; ([1 2 3])\n\n(run* [q]\n (== [1 q 3] [1 2 3]))\n;; (2)","_id":"624074ace4b0b1e3652d75c1"}],"notes":[{"author":{"login":"zackteo","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7510179?v=4"},"updated-at":1654864972133,"created-at":1654864972133,"body":"==, or unify","_id":"62a33c4ce4b0b1e3652d75fb"}],"arglists":["u v"],"doc":"A goal that attempts to unify terms u and v.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/=="},{"ns":"clojure.core.logic","name":"env-locals","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":1625,"examples":null,"notes":null,"arglists":["& syms"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/env-locals"},{"ns":"clojure.core.logic","name":"conjo","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":2802,"examples":[{"body":"(use 'clojure.core.logic)\n\n;; Like conj, but result is the last argument\n\n(run* [q] (conjo [1 2 3] 4 q))\n;;=> ([1 2 3 4])\n(run* [q] (conjo [1 2 3] 4 5 6 q))\n;;=> ([1 2 3 4 5 6])\n(run* [q] (conjo {:a 0} {:a 123 :b 345} q))\n;;=> ({:a 123, :b 345})\n\n;; Partially relational:\n(run* [q] (conjo [1 2] q [1 2 3]))\n;;=> (3)\n\n;; but the same doesn't work for maps\n(run* [q] (conjo {} q {:a 1}))\n;; java.lang.IllegalArgumentException: Don't know how to create ISeq from: clojure.core.logic.LVar\n\n;; This case works:\n(run* [q] (conjo {} {:a q} {:a 12345}))\n;;=> (12345)","author":{"login":"kolen","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/24191?v=2"},"created-at":1414160050597,"updated-at":1414160050597,"_id":"544a5eb2e4b0dc573b892fa8"}],"notes":null,"arglists":["coll & args"],"doc":"A constraint version of conj","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/conjo"},{"ns":"clojure.core.logic","name":"remcg","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":2049,"examples":null,"notes":null,"arglists":["c"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/remcg"},{"ns":"clojure.core.logic","name":"dissoc-dom","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":33,"examples":null,"notes":null,"arglists":["x k"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/dissoc-dom"},{"ns":"clojure.core.logic","name":"suspended-stream?","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":1857,"examples":null,"notes":null,"arglists":["x"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/suspended-stream_q"},{"ns":"clojure.core.logic","name":"firsto","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":[{"created-at":1490671476774,"author":{"login":"tkocmathla","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/183459?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"resto","ns":"clojure.core.logic"},"_id":"58d9d774e4b01f4add58fe7b"}],"line":1665,"examples":null,"notes":null,"arglists":["l a"],"doc":"A relation where l is a collection, such that a is the first of l","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/firsto"},{"ns":"clojure.core.logic","name":"map->SuspendedStream","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":1849,"examples":null,"notes":null,"arglists":["m__8001__auto__"],"doc":"Factory function for class clojure.core.logic.SuspendedStream, taking a map of keywords to field values.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/map->SuspendedStream"},{"ns":"clojure.core.logic","name":"entangle","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":609,"examples":null,"notes":null,"arglists":["s x y"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/entangle"},{"ns":"clojure.core.logic","name":"run*","file":"clojure/core/logic.clj","type":"macro","column":1,"see-alsos":null,"line":1242,"examples":[{"updated-at":1593353431525,"created-at":1593353431525,"author":{"login":"ertugrulcetin","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/8271291?v=4"},"body":";; Solves 3X + 2Y + Z = 3 equation\n(let [symbols '[X Y Z]\n vars (repeatedly (count symbols) lvar)\n [x y z] vars\n sum 3]\n (run* [q]\n (everyg #(fd/in % (fd/interval 0 sum)) vars)\n (fresh [pro-x pro-y pro-z sum-x-y]\n (fd/* 3 x pro-x)\n (fd/* 2 y pro-y)\n (fd/* 1 z pro-z)\n (fd/+ pro-x pro-y sum-x-y)\n (fd/+ sum-x-y pro-z sum))\n (== q (zipmap symbols vars))))\n\n;;=> ({X 0, Y 0, Z 3} \n;; {X 1, Y 0, Z 0} \n;; {X 0, Y 1, Z 1})","_id":"5ef8a4d7e4b0b1e3652d7314"}],"macro":true,"notes":null,"arglists":["bindings & goals"],"doc":"Executes goals until results are exhausted.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/run*"},{"ns":"clojure.core.logic","name":"->SuspendedStream","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":1849,"examples":null,"notes":null,"arglists":["cache ansv* f"],"doc":"Positional factory function for class clojure.core.logic.SuspendedStream.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/->SuspendedStream"},{"ns":"clojure.core.logic","name":"run-db","file":"clojure/core/logic.clj","type":"macro","column":1,"see-alsos":null,"line":1247,"examples":null,"macro":true,"notes":null,"arglists":["n db bindings & goals"],"doc":"Executes goals until a maximum of n results are found. Uses a specified logic database.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/run-db"},{"ns":"clojure.core.logic","name":"ground-term?","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":2590,"examples":null,"notes":null,"arglists":["x s"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/ground-term_q"},{"ns":"clojure.core.logic","name":"verify-all-bound","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":2129,"examples":null,"notes":null,"arglists":["a constrained"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/verify-all-bound"},{"ns":"clojure.core.logic","name":"defnm","file":"clojure/core/logic.clj","type":"macro","column":1,"see-alsos":null,"line":1639,"examples":null,"macro":true,"notes":null,"arglists":["t n & rest"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/defnm"},{"ns":"clojure.core.logic","name":"fix-constraints","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":2088,"examples":null,"notes":null,"arglists":["a"],"doc":"A goal to run the constraints in cq until it is empty. Of\n course running a constraint may grow cq so this function\n finds the fixpoint.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/fix-constraints"},{"ns":"clojure.core.logic","name":"subst-val?","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":202,"examples":null,"notes":null,"arglists":["x"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/subst-val_q"},{"ns":"clojure.core.logic","name":"map->SubstValue","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":197,"examples":null,"notes":null,"arglists":["m__8001__auto__"],"doc":"Factory function for class clojure.core.logic.SubstValue, taking a map of keywords to field values.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/map->SubstValue"},{"ns":"clojure.core.logic","name":"partial-map?","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":2542,"examples":null,"notes":null,"arglists":["x"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/partial-map_q"},{"ns":"clojure.core.logic","name":"succeed","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":1140,"examples":null,"notes":null,"arglists":["a"],"doc":"A goal that always succeeds.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/succeed"},{"ns":"clojure.core.logic","name":"subst-val","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":205,"examples":null,"notes":null,"arglists":["x","x doms","x doms _meta","x doms eset _meta"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/subst-val"},{"ns":"clojure.core.logic","name":"composeg","file":"clojure/core/logic.clj","type":"function","column":1,"see-alsos":null,"line":1053,"examples":null,"notes":null,"arglists":["","g0 g1"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic/composeg"},{"ns":"clojure.core.logic.fd","name":"interval","file":"clojure/core/logic/fd.clj","type":"function","column":1,"see-alsos":null,"line":357,"examples":[{"updated-at":1632545550940,"created-at":1632545550940,"author":{"login":"jngbng","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/552977?v=4"},"body":"(cl/run* [x]\n (fd/in x (fd/interval 1 3)))\n;; => (1 2 3)","_id":"614eab0ee4b0b1e3652d7545"}],"notes":null,"arglists":["ub","lb ub"],"doc":"Construct an interval for an assignment to a var. intervals may\n be more efficient that the domain type when the range of possiblities\n is large.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/interval"},{"ns":"clojure.core.logic.fd","name":"domain","file":"clojure/core/logic/fd.clj","type":"function","column":1,"see-alsos":null,"line":155,"examples":[{"updated-at":1596510435368,"created-at":1596510395370,"author":{"login":"owenRiddy","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/8080718?v=4"},"body":";; The docs are truthful but highly misleading. \n;; Although integers can be passed as arguments\n;; a domain can only be constructed over the\n;; Natural numbers.\n\n\ndirect> (fd/domain 1 2 3)\n;; => \ndirect> (fd/domain -1 -2 -3)\n;; => nil\ndirect> (fd/domain -3 -2 -1 0 1 2 3)\n;; => ","editors":[{"avatar-url":"https://avatars0.githubusercontent.com/u/8080718?v=4","account-source":"github","login":"owenRiddy"}],"_id":"5f28d0bbe4b0b1e3652d7346"}],"notes":null,"arglists":["& args"],"doc":"Construct a domain for assignment to a var. Arguments should \n be integers given in sorted order. domains may be more efficient \n than intervals when only a few values are possible.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/domain"},{"ns":"clojure.core.logic.fd","name":"interval?","file":"clojure/core/logic/fd.clj","type":"function","column":1,"see-alsos":null,"line":351,"examples":null,"notes":null,"arglists":["x"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/interval_q"},{"ns":"clojure.core.logic.fd","name":"->FiniteDomain","file":"clojure/core/logic/fd.clj","type":"function","column":1,"see-alsos":null,"line":64,"examples":null,"notes":null,"arglists":["s min max"],"doc":"Positional factory function for class clojure.core.logic.fd.FiniteDomain.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/->FiniteDomain"},{"ns":"clojure.core.logic.fd","name":"!=c","file":"clojure/core/logic/fd.clj","type":"function","column":1,"see-alsos":null,"line":755,"examples":null,"notes":null,"arglists":["u v"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/!=c"},{"ns":"clojure.core.logic.fd","name":"domc","file":"clojure/core/logic/fd.clj","type":"function","column":1,"see-alsos":null,"line":718,"examples":null,"notes":null,"arglists":["x"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/domc"},{"ns":"clojure.core.logic.fd","name":"-member?","type":"function","see-alsos":null,"examples":null,"notes":null,"tag":null,"arglists":["this n"],"doc":null,"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/-member_q"},{"ns":"clojure.core.logic.fd","name":"->MultiIntervalFD","file":"clojure/core/logic/fd.clj","type":"function","column":1,"see-alsos":null,"line":477,"examples":null,"notes":null,"arglists":["min max is"],"doc":"Positional factory function for class clojure.core.logic.fd.MultiIntervalFD.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/->MultiIntervalFD"},{"ns":"clojure.core.logic.fd","name":"<","file":"clojure/core/logic/fd.clj","type":"function","column":1,"see-alsos":null,"line":825,"examples":null,"notes":null,"arglists":["u v"],"doc":"A finite domain constraint. u must be less than v. u and v\n must eventually be given domains if vars.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/<"},{"ns":"clojure.core.logic.fd","name":"get-dom","file":"clojure/core/logic/fd.clj","type":"function","column":1,"see-alsos":null,"line":591,"examples":null,"notes":null,"arglists":["a x"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/get-dom"},{"ns":"clojure.core.logic.fd","name":"expand","file":"clojure/core/logic/fd.clj","type":"function","column":1,"see-alsos":null,"line":1113,"examples":null,"notes":null,"arglists":["form"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/expand"},{"ns":"clojure.core.logic.fd","name":"dom","file":"clojure/core/logic/fd.clj","type":"function","column":1,"see-alsos":null,"line":631,"examples":null,"notes":null,"arglists":["x dom"],"doc":"Assign a var x a domain.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/dom"},{"ns":"clojure.core.logic.fd","name":"->IntervalFD","file":"clojure/core/logic/fd.clj","type":"function","column":1,"see-alsos":null,"line":231,"examples":null,"notes":null,"arglists":["lb ub"],"doc":"Positional factory function for class clojure.core.logic.fd.IntervalFD.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/->IntervalFD"},{"ns":"clojure.core.logic.fd","name":"resolve-storable-dom","file":"clojure/core/logic/fd.clj","type":"function","column":1,"see-alsos":null,"line":607,"examples":null,"notes":null,"arglists":["a x dom domp"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/resolve-storable-dom"},{"ns":"clojure.core.logic.fd","name":"difference*","file":"clojure/core/logic/fd.clj","type":"function","column":1,"see-alsos":null,"line":408,"examples":null,"notes":null,"arglists":["is js"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/difference*"},{"ns":"clojure.core.logic.fd","name":"bounded-listo","file":"clojure/core/logic/fd.clj","type":"function","column":1,"see-alsos":null,"line":1085,"examples":null,"notes":null,"arglists":["l n"],"doc":"Ensure that the list l never grows beyond bound n.\n n must have been assigned a domain.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/bounded-listo"},{"ns":"clojure.core.logic.fd","name":"map-sum","file":"clojure/core/logic/fd.clj","type":"function","column":1,"see-alsos":null,"line":658,"examples":null,"notes":null,"arglists":["f"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/map-sum"},{"ns":"clojure.core.logic.fd","name":"ext-dom-fd","file":"clojure/core/logic/fd.clj","type":"function","column":1,"see-alsos":null,"line":597,"examples":null,"notes":null,"arglists":["a x dom domp"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/ext-dom-fd"},{"ns":"clojure.core.logic.fd","name":"in","file":"clojure/core/logic/fd.clj","type":"macro","column":1,"see-alsos":[{"created-at":1655305783395,"author":{"login":"zackteo","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7510179?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"domain","ns":"clojure.core.logic.fd"},"_id":"62a9f637e4b0b1e3652d7602"},{"created-at":1655305802408,"author":{"login":"zackteo","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7510179?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"interval","ns":"clojure.core.logic.fd"},"_id":"62a9f64ae4b0b1e3652d7603"},{"created-at":1679493250018,"author":{"login":"port19x","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/82055622?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"contains?","ns":"clojure.core"},"_id":"641b0882e4b08cf8563f4b82"}],"line":646,"examples":[{"editors":[{"login":"zackteo","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7510179?v=4"}],"body":"(logic/run* [x y]\n (fd/in x y (fd/interval 0 5))\n (fd/+ x y 5))\n;; => ([0 5] [1 4] [2 3] [3 2] [4 1] [5 0])","author":{"avatar-url":"https://avatars.githubusercontent.com/u/552977?v=4","account-source":"github","login":"jngbng"},"created-at":1632547487519,"updated-at":1655305031162,"_id":"614eb29fe4b0b1e3652d7546"},{"updated-at":1655305396793,"created-at":1655305396793,"author":{"login":"zackteo","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7510179?v=4"},"body":";; Modelling the possible combination of values of 2 coin tosses\n;; heads - 1, tails - 0; or vice-versa\n(logic/run* [coin-1 coin-2]\n (let [coin (fd/domain 0 1)]\n (fd/in coin-1 coin-2 coin)))\n;; => ([0 0] [1 0] [0 1] [1 1])","_id":"62a9f4b4e4b0b1e3652d7600"}],"macro":true,"notes":[{"author":{"login":"port19x","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/82055622?v=4"},"updated-at":1679493347028,"created-at":1679493347028,"body":"If you're looking to do simple membership tests, such a function isn't builtin\n\n`(defn in? [xs el] (some #(= % el) xs))`","_id":"641b08e3e4b08cf8563f4b83"}],"arglists":["& xs-and-dom"],"doc":"Assign vars to domain. The domain must come last.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/in"},{"ns":"clojure.core.logic.fd","name":"distinctc","file":"clojure/core/logic/fd.clj","type":"function","column":1,"see-alsos":null,"line":1042,"examples":null,"notes":null,"arglists":["v*"],"doc":"The real distinct constraint. v* can be seq of logic vars and\n values or it can be a logic var itself. This constraint does not \n run until v* has become ground. When it has become ground we group\n v* into a set of logic vars and a sorted set of known singleton \n values. We then construct the individual constraint for each var.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/distinctc"},{"ns":"clojure.core.logic.fd","name":"multi-interval","file":"clojure/core/logic/fd.clj","type":"function","column":1,"see-alsos":null,"line":573,"examples":null,"notes":null,"arglists":["","i0","i0 i1","i0 i1 & ir"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/multi-interval"},{"ns":"clojure.core.logic.fd","name":"-intervals","type":"function","see-alsos":null,"examples":null,"notes":null,"tag":null,"arglists":["this"],"doc":null,"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/-intervals"},{"ns":"clojure.core.logic.fd","name":"-intersection","type":"function","see-alsos":null,"examples":null,"notes":null,"tag":null,"arglists":["this that"],"doc":null,"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/-intersection"},{"ns":"clojure.core.logic.fd","name":"<=","file":"clojure/core/logic/fd.clj","type":"function","column":1,"see-alsos":null,"line":819,"examples":null,"notes":null,"arglists":["u v"],"doc":"A finite domain constraint. u must be less than or equal to v.\n u and v must eventually be given domains if vars.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/<="},{"ns":"clojure.core.logic.fd","name":"normalize-intervals","file":"clojure/core/logic/fd.clj","type":"function","column":1,"see-alsos":null,"line":561,"examples":null,"notes":null,"arglists":["is"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/normalize-intervals"},{"ns":"clojure.core.logic.fd","name":"intersection*","file":"clojure/core/logic/fd.clj","type":"function","column":1,"see-alsos":null,"line":369,"examples":null,"notes":null,"arglists":["is js"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/intersection*"},{"ns":"clojure.core.logic.fd","name":"*","file":"clojure/core/logic/fd.clj","type":"function","column":1,"see-alsos":[{"created-at":1591806367061,"author":{"login":"jogo3000","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/7455939?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"eq","ns":"clojure.core.logic.fd"},"_id":"5ee1099fe4b0b1e3652d7301"}],"line":976,"examples":[{"editors":[{"login":"jogo3000","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/7455939?v=4"}],"body":";; Solve q in 2 * q = 10\n(use 'clojure.core.logic)\n(require '[clojure.core.logic.fd :as fd])\n\n(run* [q] (fd/* 2 q 10)) ; => (5)\n\n;; Gotcha: it can only really find integer solutions\n(run* [q] (fd/* 2 q 5)) ; => ()","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/7455939?v=4","account-source":"github","login":"jogo3000"},"created-at":1591806163866,"updated-at":1591806328350,"_id":"5ee108d3e4b0b1e3652d72ff"}],"notes":null,"arglists":["x y product"],"doc":"A finite domain constraint for multiplication and\n thus division. x, y & product must be eventually be given \n domains if vars.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/*"},{"ns":"clojure.core.logic.fd","name":"-drop-one","type":"function","see-alsos":null,"examples":null,"notes":null,"tag":null,"arglists":["this"],"doc":null,"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/-drop-one"},{"ns":"clojure.core.logic.fd","name":"interval-<","file":"clojure/core/logic/fd.clj","type":"function","column":1,"see-alsos":null,"line":42,"examples":null,"notes":null,"arglists":["i j"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/interval-<"},{"ns":"clojure.core.logic.fd","name":"-distinct","file":"clojure/core/logic/fd.clj","type":"function","column":1,"see-alsos":null,"line":1028,"examples":null,"notes":null,"arglists":["x y* n*"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/-distinct"},{"ns":"clojure.core.logic.fd","name":"singleton-dom?","file":"clojure/core/logic/fd.clj","type":"function","column":1,"see-alsos":null,"line":604,"examples":null,"notes":null,"arglists":["x"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/singleton-dom_q"},{"ns":"clojure.core.logic.fd","name":"<=c","file":"clojure/core/logic/fd.clj","type":"function","column":1,"see-alsos":null,"line":792,"examples":null,"notes":null,"arglists":["u v"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/<=c"},{"ns":"clojure.core.logic.fd","name":"quot","file":"clojure/core/logic/fd.clj","type":"function","column":1,"see-alsos":null,"line":983,"examples":null,"notes":null,"arglists":["u v w"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/quot"},{"ns":"clojure.core.logic.fd","name":"binops->fd","file":"clojure/core/logic/fd.clj","type":"var","column":1,"see-alsos":null,"line":1099,"examples":null,"notes":null,"arglists":[],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/binops->fd"},{"ns":"clojure.core.logic.fd","name":"eq","file":"clojure/core/logic/fd.clj","type":"macro","column":1,"see-alsos":null,"line":1156,"examples":[{"editors":[{"login":"jngbng","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/552977?v=4"}],"body":";; from https://github.com/clojure/core.logic/wiki/Features#clpfd\n\n;; fd/eq is a macro that allows you to write arithmetic expressions \n;; in normal Lisp syntax which will be expanded into the appropriate\n;; series of CLP(FD) operators. It will create the transient intermediate\n;; vars for you and domain inference will be applied.\n\n(logic/run* [q]\n (logic/fresh [x y]\n (fd/in x y (fd/interval 0 9))\n (fd/eq\n (= (+ x y) 9)\n (= (+ (* x 2) (* y 4)) 24))\n (== q [x y]))) ; => ([6 3])","author":{"avatar-url":"https://avatars.githubusercontent.com/u/552977?v=4","account-source":"github","login":"jngbng"},"created-at":1632547827870,"updated-at":1632553103427,"_id":"614eb3f3e4b0b1e3652d7548"}],"macro":true,"notes":null,"arglists":["& forms"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/eq"},{"ns":"clojure.core.logic.fd","name":"eq-form","file":"clojure/core/logic/fd.clj","type":"function","column":1,"see-alsos":null,"line":1151,"examples":null,"notes":null,"arglists":["form"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/eq-form"},{"ns":"clojure.core.logic.fd","name":">","file":"clojure/core/logic/fd.clj","type":"function","column":1,"see-alsos":null,"line":833,"examples":null,"notes":null,"arglists":["u v"],"doc":"A finite domain constraint. u must be greater than v. u and v\n must eventually be given domains if vars.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/>"},{"ns":"clojure.core.logic.fd","name":"IInterval","file":"clojure/core/logic/fd.clj","type":"var","column":1,"see-alsos":null,"line":16,"examples":null,"notes":null,"arglists":[],"doc":null,"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/IInterval"},{"ns":"clojure.core.logic.fd","name":"eq*","file":"clojure/core/logic/fd.clj","type":"function","column":1,"see-alsos":null,"line":1122,"examples":null,"notes":null,"arglists":["form vars","form vars out"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/eq*"},{"ns":"clojure.core.logic.fd","name":"-drop-before","type":"function","see-alsos":null,"examples":null,"notes":null,"tag":null,"arglists":["this n"],"doc":null,"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/-drop-before"},{"ns":"clojure.core.logic.fd","name":"process-dom","file":"clojure/core/logic/fd.clj","type":"function","column":1,"see-alsos":null,"line":616,"examples":null,"notes":null,"arglists":["x dom domp"],"doc":"If x is a var we update its domain. If it's an integer\n we check that it's a member of the given domain. dom is\n then new domain, it should have already been calculated from\n domp which was the previous domain.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/process-dom"},{"ns":"clojure.core.logic.fd","name":"ISet","file":"clojure/core/logic/fd.clj","type":"var","column":1,"see-alsos":null,"line":28,"examples":null,"notes":null,"arglists":[],"doc":null,"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/ISet"},{"ns":"clojure.core.logic.fd","name":"-","file":"clojure/core/logic/fd.clj","type":"function","column":1,"see-alsos":null,"line":906,"examples":null,"notes":null,"arglists":["u v w"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/-"},{"ns":"clojure.core.logic.fd","name":"sorted-set->domain","file":"clojure/core/logic/fd.clj","type":"function","column":1,"see-alsos":null,"line":148,"examples":null,"notes":null,"arglists":["s"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/sorted-set->domain"},{"ns":"clojure.core.logic.fd","name":"interval-<=","file":"clojure/core/logic/fd.clj","type":"function","column":1,"see-alsos":null,"line":45,"examples":null,"notes":null,"arglists":["i j"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/interval-<="},{"ns":"clojure.core.logic.fd","name":"-domc","file":"clojure/core/logic/fd.clj","type":"function","column":1,"see-alsos":null,"line":692,"examples":null,"notes":null,"arglists":["x"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/-domc"},{"ns":"clojure.core.logic.fd","name":"list-sorted?","file":"clojure/core/logic/fd.clj","type":"function","column":1,"see-alsos":null,"line":1031,"examples":null,"notes":null,"arglists":["pred ls"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/list-sorted_q"},{"ns":"clojure.core.logic.fd","name":"-lb","type":"function","see-alsos":null,"examples":null,"notes":null,"tag":null,"arglists":["this"],"doc":null,"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/-lb"},{"ns":"clojure.core.logic.fd","name":"==c","file":"clojure/core/logic/fd.clj","type":"function","column":1,"see-alsos":null,"line":721,"examples":null,"notes":null,"arglists":["u v"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/==c"},{"ns":"clojure.core.logic.fd","name":"extend-to-fd","file":"clojure/core/logic/fd.clj","type":"macro","column":1,"see-alsos":null,"line":169,"examples":null,"macro":true,"notes":null,"arglists":["t"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/extend-to-fd"},{"ns":"clojure.core.logic.fd","name":"-disjoint?","type":"function","see-alsos":null,"examples":null,"notes":null,"tag":null,"arglists":["this that"],"doc":null,"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/-disjoint_q"},{"ns":"clojure.core.logic.fd","name":"disjoint?*","file":"clojure/core/logic/fd.clj","type":"function","column":1,"see-alsos":null,"line":449,"examples":null,"notes":null,"arglists":["is js"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/disjoint_q*"},{"ns":"clojure.core.logic.fd","name":">=","file":"clojure/core/logic/fd.clj","type":"function","column":1,"see-alsos":null,"line":839,"examples":null,"notes":null,"arglists":["u v"],"doc":"A finite domain constraint. u must be greater than or equal to v.\n u and v must eventually be given domains if vars.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/>="},{"ns":"clojure.core.logic.fd","name":"distinct","file":"clojure/core/logic/fd.clj","type":"function","column":1,"see-alsos":null,"line":1077,"examples":[{"editors":[{"login":"ertugrulcetin","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/8271291?v=4"}],"body":"(run* [q]\n (fresh [x y]\n (fd/in x y (fd/interval 1 10))\n (fd/+ x y 10)\n (fd/distinct [x y])\n (== q [x y])))\n\n;;=> ([1 9] [2 8] [3 7] [4 6] [6 4] [7 3] [8 2] [9 1])\n;; because of fd/distinct there is no [5 5] in result list.","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/8271291?v=4","account-source":"github","login":"ertugrulcetin"},"created-at":1593353632149,"updated-at":1593353660081,"_id":"5ef8a5a0e4b0b1e3652d7315"}],"notes":null,"arglists":["v*"],"doc":"A finite domain constraint that will guarantee that \n all vars that occur in v* will be unified with unique \n values. v* need not be ground. Any vars in v* should\n eventually be given a domain.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/distinct"},{"ns":"clojure.core.logic.fd","name":"-distinctc","file":"clojure/core/logic/fd.clj","type":"function","column":1,"see-alsos":null,"line":986,"examples":null,"notes":null,"arglists":["x y* n*"],"doc":"The real *individual* distinct constraint. x is a var that now is bound to\n a single value. y* were the non-singleton bound vars that existed at the\n construction of the constraint. n* is the set of singleton domain values \n that existed at the construction of the constraint. We use categorize to \n determine the current non-singleton bound vars and singleton vlaues. if x\n is in n* or the new singletons we have failed. If not we simply remove \n the value of x from the remaining non-singleton domains bound to vars.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/-distinctc"},{"ns":"clojure.core.logic.fd","name":"bounds","file":"clojure/core/logic/fd.clj","type":"function","column":1,"see-alsos":null,"line":39,"examples":null,"notes":null,"arglists":["i"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/bounds"},{"ns":"clojure.core.logic.fd","name":"interval->=","file":"clojure/core/logic/fd.clj","type":"function","column":1,"see-alsos":null,"line":51,"examples":null,"notes":null,"arglists":["i j"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/interval->="},{"ns":"clojure.core.logic.fd","name":"to-vals","file":"clojure/core/logic/fd.clj","type":"function","column":1,"see-alsos":null,"line":668,"examples":null,"notes":null,"arglists":["dom"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/to-vals"},{"ns":"clojure.core.logic.fd","name":"-difference","type":"function","see-alsos":null,"examples":null,"notes":null,"tag":null,"arglists":["this that"],"doc":null,"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/-difference"},{"ns":"clojure.core.logic.fd","name":"->fd","file":"clojure/core/logic/fd.clj","type":"function","column":1,"see-alsos":null,"line":1147,"examples":null,"notes":null,"arglists":["vars exprs"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/->fd"},{"ns":"clojure.core.logic.fd","name":"interval->","file":"clojure/core/logic/fd.clj","type":"function","column":1,"see-alsos":null,"line":48,"examples":null,"notes":null,"arglists":["i j"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/interval->"},{"ns":"clojure.core.logic.fd","name":"+","file":"clojure/core/logic/fd.clj","type":"function","column":1,"see-alsos":null,"line":900,"examples":[{"updated-at":1582534477216,"created-at":1582534477216,"author":{"login":"mdzaebel","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/415392?v=4"},"body":"(run* [sum] (fd/+ 1 2 sum))\n;;=> (3)","_id":"5e538f4de4b087629b5a18a0"}],"notes":null,"arglists":["x y sum"],"doc":"A finite domain constraint for addition and subtraction.\n x, y & sum must eventually be given domains if vars.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/+"},{"ns":"clojure.core.logic.fd","name":"-ub","type":"function","see-alsos":null,"examples":null,"notes":null,"tag":null,"arglists":["this"],"doc":null,"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/-ub"},{"ns":"clojure.core.logic.fd","name":"binops","file":"clojure/core/logic/fd.clj","type":"var","column":1,"see-alsos":null,"line":1111,"examples":null,"notes":null,"arglists":[],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/binops"},{"ns":"clojure.core.logic.fd","name":"unify-with-domain*","file":"clojure/core/logic/fd.clj","type":"var","column":1,"see-alsos":null,"line":34,"examples":null,"notes":null,"arglists":[],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/unify-with-domain*"},{"ns":"clojure.core.logic.fd","name":"finite-domain?","file":"clojure/core/logic/fd.clj","type":"function","column":1,"see-alsos":null,"line":145,"examples":[{"updated-at":1655306137177,"created-at":1655306137177,"author":{"login":"zackteo","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7510179?v=4"},"body":"(fd/finite-domain? (fd/domain 0 1));; => true\n(fd/finite-domain? (fd/interval 0 1));; => false","_id":"62a9f799e4b0b1e3652d7604"}],"notes":null,"arglists":["x"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/finite-domain_q"},{"ns":"clojure.core.logic.fd","name":"!=","file":"clojure/core/logic/fd.clj","type":"function","column":1,"see-alsos":null,"line":786,"examples":null,"notes":null,"arglists":["u v"],"doc":"A finite domain constraint. u and v must not be equal. u and v\n must eventually be given domains if vars.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/!="},{"ns":"clojure.core.logic.fd","name":"==","file":"clojure/core/logic/fd.clj","type":"function","column":1,"see-alsos":null,"line":749,"examples":null,"notes":null,"arglists":["u v"],"doc":"A finite domain constraint. u and v must be equal. u and v must\n eventually be given domains if vars.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/=="},{"ns":"clojure.core.logic.fd","name":"*c","file":"clojure/core/logic/fd.clj","type":"function","column":1,"see-alsos":null,"line":913,"examples":null,"notes":null,"arglists":["u v w"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/*c"},{"ns":"clojure.core.logic.fd","name":"ISortedDomain","file":"clojure/core/logic/fd.clj","type":"var","column":1,"see-alsos":null,"line":23,"examples":null,"notes":null,"arglists":[],"doc":null,"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/ISortedDomain"},{"ns":"clojure.core.logic.fd","name":"-keep-before","type":"function","see-alsos":null,"examples":null,"notes":null,"tag":null,"arglists":["this n"],"doc":null,"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/-keep-before"},{"ns":"clojure.core.logic.fd","name":"IIntervals","file":"clojure/core/logic/fd.clj","type":"var","column":1,"see-alsos":null,"line":20,"examples":null,"notes":null,"arglists":[],"doc":null,"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/IIntervals"},{"ns":"clojure.core.logic.fd","name":"+c","file":"clojure/core/logic/fd.clj","type":"function","column":1,"see-alsos":null,"line":849,"examples":null,"notes":null,"arglists":["u v w"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.fd/+c"},{"ns":"clojure.core.logic.pldb","name":"with-dbs","file":"clojure/core/logic/pldb.clj","type":"macro","column":1,"see-alsos":null,"line":8,"examples":null,"macro":true,"notes":null,"arglists":["dbs & body"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.pldb/with-dbs"},{"ns":"clojure.core.logic.pldb","name":"db","file":"clojure/core/logic/pldb.clj","type":"function","column":1,"see-alsos":null,"line":125,"examples":null,"notes":null,"arglists":["& facts"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.pldb/db"},{"ns":"clojure.core.logic.pldb","name":"index-for-query","file":"clojure/core/logic/pldb.clj","type":"function","column":1,"see-alsos":null,"line":41,"examples":null,"notes":null,"arglists":["s q indexes"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.pldb/index-for-query"},{"ns":"clojure.core.logic.pldb","name":"indexed?","file":"clojure/core/logic/pldb.clj","type":"function","column":1,"see-alsos":null,"line":31,"examples":null,"notes":null,"arglists":["v"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.pldb/indexed_q"},{"ns":"clojure.core.logic.pldb","name":"db-facts","file":"clojure/core/logic/pldb.clj","type":"function","column":1,"see-alsos":null,"line":122,"examples":null,"notes":null,"arglists":["base-db & facts"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.pldb/db-facts"},{"ns":"clojure.core.logic.pldb","name":"facts-for","file":"clojure/core/logic/pldb.clj","type":"function","column":1,"see-alsos":null,"line":16,"examples":null,"notes":null,"arglists":["dbs kname"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.pldb/facts-for"},{"ns":"clojure.core.logic.pldb","name":"contains-lvar?","file":"clojure/core/logic/pldb.clj","type":"function","column":1,"see-alsos":null,"line":35,"examples":null,"notes":null,"arglists":["x"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.pldb/contains-lvar_q"},{"ns":"clojure.core.logic.pldb","name":"empty-db","file":"clojure/core/logic/pldb.clj","type":"var","column":1,"see-alsos":null,"line":6,"examples":null,"notes":null,"arglists":[],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.pldb/empty-db"},{"ns":"clojure.core.logic.pldb","name":"ground?","file":"clojure/core/logic/pldb.clj","type":"function","column":1,"see-alsos":null,"line":38,"examples":null,"notes":null,"arglists":["s term"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.pldb/ground_q"},{"ns":"clojure.core.logic.pldb","name":"rel-key","file":"clojure/core/logic/pldb.clj","type":"function","column":1,"see-alsos":null,"line":23,"examples":null,"notes":null,"arglists":["rel"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.pldb/rel-key"},{"ns":"clojure.core.logic.pldb","name":"db-rel","file":"clojure/core/logic/pldb.clj","type":"macro","column":1,"see-alsos":null,"line":48,"examples":[{"updated-at":1616351269886,"created-at":1616351269886,"author":{"login":"brown131","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2651342?v=4"},"body":";; To defined an indexed argument for a relation.\n\n(db-rel direction ^:index d p)\n","_id":"60579025e4b0b1e3652d74a7"}],"macro":true,"notes":null,"arglists":["name & args"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.pldb/db-rel"},{"ns":"clojure.core.logic.pldb","name":"rel-indexes","file":"clojure/core/logic/pldb.clj","type":"function","column":1,"see-alsos":null,"line":28,"examples":null,"notes":null,"arglists":["rel"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.pldb/rel-indexes"},{"ns":"clojure.core.logic.pldb","name":"facts-using-index","file":"clojure/core/logic/pldb.clj","type":"function","column":1,"see-alsos":null,"line":19,"examples":null,"notes":null,"arglists":["dbs kname index val"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.pldb/facts-using-index"},{"ns":"clojure.core.logic.pldb","name":"db-retractions","file":"clojure/core/logic/pldb.clj","type":"function","column":1,"see-alsos":null,"line":128,"examples":null,"notes":null,"arglists":["base-db & retractions"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.pldb/db-retractions"},{"ns":"clojure.core.logic.pldb","name":"db-fact","file":"clojure/core/logic/pldb.clj","type":"function","column":1,"see-alsos":null,"line":79,"examples":null,"notes":null,"arglists":["db rel & args"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.pldb/db-fact"},{"ns":"clojure.core.logic.pldb","name":"with-db","file":"clojure/core/logic/pldb.clj","type":"macro","column":1,"see-alsos":null,"line":12,"examples":null,"macro":true,"notes":null,"arglists":["db & body"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.pldb/with-db"},{"ns":"clojure.core.logic.pldb","name":"db-retraction","file":"clojure/core/logic/pldb.clj","type":"function","column":1,"see-alsos":[{"created-at":1515676308690,"author":{"login":"fhur","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/6452323?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"db-fact","ns":"clojure.core.logic.pldb"},"_id":"5a576294e4b0a08026c48cef"}],"line":100,"examples":[{"updated-at":1515676270032,"created-at":1515676270032,"author":{"login":"fhur","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/6452323?v=4"},"body":"; db-retraction is the reverse operation to db-fact. \n; You can think of db-rel as learning a fact and db-retraction as unlearning it.\n\n; Step 1: define a relation\n(db-rel user x)\n\n; Step 2: create a simple DB\n(def my-db (-> empty-db\n (db-fact user \"me\")\n (db-fact user \"you\")))\n;; => {\"user/user_1\" {:clojure.core.logic.pldb/unindexed #{(\"you\") (\"me\")}}}\n\n;; Step 3: retract from \"me\" being a user.\n(db-retraction my-db user \"me\")\n;; => {\"user/user_1\" {:clojure.core.logic.pldb/unindexed #{(\"you\")}}}","_id":"5a57626ee4b0a08026c48cee"}],"notes":null,"arglists":["db rel & args"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.logic.pldb/db-retraction"},{"ns":"clojure.core.protocols","name":"IKVReduce","file":"clojure/core/protocols.clj","type":"var","column":1,"see-alsos":null,"line":174,"examples":null,"notes":null,"arglists":[],"doc":"Protocol for concrete associative types that can reduce themselves\n via a function of key and val faster than first/next recursion over map\n entries. Called by clojure.core/reduce-kv, and has same\n semantics (just different arg order).","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.protocols/IKVReduce"},{"ns":"clojure.core.protocols","name":"Navigable","file":"clojure/core/protocols.clj","type":"var","column":1,"see-alsos":null,"line":193,"examples":null,"notes":null,"arglists":[],"doc":null,"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.protocols/Navigable"},{"ns":"clojure.core.protocols","name":"nav","type":"function","see-alsos":null,"examples":null,"notes":null,"tag":null,"arglists":["coll k v"],"doc":"return (possibly transformed) v in the context of coll and k (a key/index or nil),\ndefaults to returning v.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.protocols/nav"},{"ns":"clojure.core.protocols","name":"Datafiable","file":"clojure/core/protocols.clj","type":"var","column":1,"see-alsos":null,"line":181,"examples":null,"notes":null,"arglists":[],"doc":null,"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.protocols/Datafiable"},{"ns":"clojure.core.protocols","name":"CollReduce","file":"clojure/core/protocols.clj","type":"var","column":1,"see-alsos":null,"line":13,"examples":null,"notes":null,"arglists":[],"doc":"Protocol for collection types that can implement reduce faster than\n first/next recursion. Called by clojure.core/reduce. Baseline\n implementation defined in terms of Iterable.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.protocols/CollReduce"},{"ns":"clojure.core.protocols","name":"datafy","type":"function","see-alsos":null,"examples":null,"notes":[{"author":{"login":"claj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/353113?v=4"},"updated-at":1729694305877,"created-at":1641131137516,"body":"Sean Corfield gives an overview of the usage of `datafy` and `nav` in the blog post [Clojure 1.10's datafy and nav](https://corfield.org/blog/2018/12/03/datafy-nav/) (3 december 2018).","_id":"61d1ac81e4b0b1e3652d7594"},{"author":{"login":"claj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/353113?v=4"},"updated-at":1641131282256,"created-at":1641131282256,"body":"Stuart Halloway gives an example of `datafy` usage in the [Cognitect REBL](https://docs.datomic.com/cloud/other-tools/REBL.html).","_id":"61d1ad12e4b0b1e3652d7595"},{"author":{"login":"claj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/353113?v=4"},"updated-at":1641132127831,"created-at":1641132127831,"body":"A full example of a datafy application is [jedi-time](https://github.com/jimpil/jedi-time), which adds datafy- and navigation on the `java.time` objects.","_id":"61d1b05fe4b0b1e3652d7596"}],"tag":null,"arglists":["o"],"doc":"return a representation of o as data (default identity)","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.protocols/datafy"},{"ns":"clojure.core.protocols","name":"coll-reduce","type":"function","see-alsos":null,"examples":null,"notes":null,"tag":null,"arglists":["coll f","coll f val"],"doc":null,"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.protocols/coll-reduce"},{"ns":"clojure.core.protocols","name":"internal-reduce","type":"function","see-alsos":null,"examples":null,"notes":null,"tag":null,"arglists":["seq f start"],"doc":null,"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.protocols/internal-reduce"},{"ns":"clojure.core.protocols","name":"iterator-reduce!","file":"clojure/core/protocols.clj","type":"function","column":1,"see-alsos":null,"line":34,"examples":null,"notes":null,"arglists":["iter f","iter f val"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.protocols/iterator-reduce!"},{"ns":"clojure.core.protocols","name":"InternalReduce","file":"clojure/core/protocols.clj","type":"var","column":1,"see-alsos":null,"line":19,"examples":null,"notes":[{"updated-at":1386465477000,"body":"http://muhammadkhojaye.blogspot.com","created-at":1386465477000,"author":{"login":"peternortan","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/c7d95a3a7a7090ffdc29428a2c424b17?r=PG&default=identicon"},"_id":"542692edf6e94c6970522014"}],"arglists":[],"doc":"Protocol for concrete seq types that can reduce themselves\n faster than first/next recursion. Called by clojure.core/reduce.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.protocols/InternalReduce"},{"ns":"clojure.core.protocols","name":"kv-reduce","type":"function","see-alsos":null,"examples":null,"notes":null,"tag":null,"arglists":["amap f init"],"doc":null,"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.protocols/kv-reduce"},{"ns":"clojure.core.reducers","name":"reduce","file":"clojure/core/reducers.clj","type":"function","column":1,"see-alsos":[{"created-at":1706179140743,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"reduce","ns":"clojure.core"},"_id":"65b23a4469fbcc0c2261748c"}],"line":38,"examples":[{"updated-at":1697489195761,"created-at":1697489195761,"author":{"login":"ericclack","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/903568?v=4"},"body":"(+ 1 2 3 4)\n;;=> 10\n\nuser> (reduce + (range 1 5))\n;;=> 10\n\n(reduce + (range 1 13))\n;;=> 78\n\n(reduce + (range 1 101))\n;;=> 5050\n\n","_id":"652da12be4b08cf8563f4c00"},{"editors":[{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"}],"body":";; core/reduce applies f to the first 2 elements of coll if init isn't provided…\n\n(clojure.core/reduce conj '(1 2 3))\n;; => Execution error (ClassCastException) at…\n;; class java.lang.Long cannot be cast to class clojure.lang.IPersistentCollection…\n\n\n;; reducers/reduce calls (f) to produce an initial value, if init isn't provided…\n\n(clojure.core.reducers/reduce conj '(1 2 3))\n;; => [1 2 3]","author":{"avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4","account-source":"github","login":"tomdl89"},"created-at":1706179132711,"updated-at":1706181209505,"_id":"65b23a3c69fbcc0c2261748b"}],"notes":null,"arglists":["f coll","f init coll"],"doc":"Like core/reduce except:\n When init is not provided, (f) is used.\n Maps are reduced with reduce-kv","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.reducers/reduce"},{"added":"1.5","ns":"clojure.core.reducers","name":"take","file":"clojure/core/reducers.clj","type":"function","column":1,"see-alsos":null,"line":201,"examples":null,"notes":null,"arglists":["n","n coll"],"doc":"Ends the reduction of coll after consuming n values.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.reducers/take"},{"added":"1.5","ns":"clojure.core.reducers","name":"map","file":"clojure/core/reducers.clj","type":"function","column":1,"see-alsos":[{"created-at":1493965139204,"author":{"login":"chbrown","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/360279?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"mapcat","ns":"clojure.core.reducers"},"_id":"590c1953e4b01f4add58feae"}],"line":128,"examples":null,"notes":null,"arglists":["f","f coll"],"doc":"Applies f to every value in the reduction of coll. Foldable.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.reducers/map"},{"added":"1.5","ns":"clojure.core.reducers","name":"foldcat","file":"clojure/core/reducers.clj","type":"function","column":1,"see-alsos":[{"created-at":1493963884640,"author":{"login":"chbrown","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/360279?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"fold","ns":"clojure.core.reducers"},"_id":"590c146ce4b01f4add58feac"}],"line":281,"examples":[{"editors":[{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"}],"body":";; Worth remembering that parallel fold in Clojure is enabled for: \n;; vectors, maps and clojure.core.reducers.Cat objects.\n;; r/foldcat returns a \"Cat\", so it can be parallel folded again:\n\n(r/fold + \n (r/foldcat \n (r/filter even? \n (r/foldcat \n (r/map inc (into [] (range 100000)))))))\n;; 2500050000","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"},"created-at":1510328583520,"updated-at":1510328990875,"_id":"5a05c907e4b0a08026c48cac"},{"updated-at":1522594338253,"created-at":1522594338253,"author":{"login":"glts","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/1483271?v=4"},"body":";; One non-obvious thing about clojure.core.reducers/foldcat is its return type,\n;; which is either clojure.core.reducers.Cat or java.util.ArrayList (!)\n;; depending on the size of the source collection.\n\n(require '[clojure.core.reducers :as r])\n\n(def small-vector (vec (range 10)))\n(def big-vector (vec (range 100000)))\n\n(type (r/foldcat (r/filter odd? small-vector))) ;;=> java.util.ArrayList\n(type (r/foldcat (r/filter odd? big-vector))) ;;=> clojure.core.reducers.Cat\n\n;; Both return types are suited for further reduce-like processing, but they are\n;; not general-purpose data types like proper Clojure collections.\n","_id":"5ac0f222e4b045c27b7fac2d"}],"notes":null,"arglists":["coll"],"doc":"Equivalent to (fold cat append! coll)","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.reducers/foldcat"},{"added":"1.5","ns":"clojure.core.reducers","name":"reducer","file":"clojure/core/reducers.clj","type":"function","column":1,"see-alsos":null,"line":67,"examples":null,"notes":[{"body":";;Beware of this bug\n\n;;These two suppose to be the same:\n\n(transduce (comp (take 10) (partition-all 3)) conj (range))\n;; => [[0 1 2] [3 4 5] [6 7 8] [9]]\n\n\n(reduce conj (r/reducer (range) (comp (take 10) (partition-all 3))))\n;; => [[0 1 2] [3 4 5] [6 7 8]]\n\n;;See https://dev.clojure.org/jira/browse/CLJ-2338\n","created-at":1521749493579,"updated-at":1522047651605,"author":{"avatar-url":"https://avatars0.githubusercontent.com/u/132936?v=4","account-source":"github","login":"gzmask"},"_id":"5ab40df5e4b045c27b7fac1e"},{"author":{"login":"glts","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/1483271?v=4"},"updated-at":1522096119969,"created-at":1522096119969,"body":"As far as I can see, `clojure.core.reducers/reducer` (since 1.5) is made obsolete by `eduction` (since 1.7), which can do the same and more.","_id":"5ab957f7e4b045c27b7fac26"}],"arglists":["coll xf"],"doc":"Given a reducible collection, and a transformation function xf,\n returns a reducible collection, where any supplied reducing\n fn will be transformed by xf. xf is a function of reducing fn to\n reducing fn.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.reducers/reducer"},{"added":"1.5","ns":"clojure.core.reducers","name":"mapcat","file":"clojure/core/reducers.clj","type":"function","column":1,"see-alsos":[{"created-at":1493965130702,"author":{"login":"chbrown","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/360279?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"map","ns":"clojure.core.reducers"},"_id":"590c194ae4b01f4add58fead"}],"line":138,"examples":null,"notes":null,"arglists":["f","f coll"],"doc":"Applies f to every value in the reduction of coll, concatenating the result\n colls of (f val). Foldable.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.reducers/mapcat"},{"added":"1.5","ns":"clojure.core.reducers","name":"cat","file":"clojure/core/reducers.clj","type":"function","column":1,"see-alsos":[{"created-at":1462880260219,"author":{"login":"achesnais","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/6626105?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"cat","ns":"clojure.core"},"_id":"5731c804e4b0b27c121b2154"},{"created-at":1510328149020,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"foldcat","ns":"clojure.core.reducers"},"_id":"5a05c755e4b0a08026c48cab"},{"created-at":1685378209827,"author":{"login":"mars0i","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1836941?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"concat","ns":"clojure.core"},"_id":"6474d4a1e4b08cf8563f4bc2"}],"line":255,"examples":[{"updated-at":1705932358940,"created-at":1510096162999,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"body":";; The example showcase use of r/cat to build HashSets (instead \n;; of the default ArrayList) of distinct words in parallel \n;; and then merge all together walking the binary tree produced by r/fold.\n(require '[clojure.core.reducers :as r])\n(require '[clojure.string :refer [lower-case blank? split split-lines]])\n(import 'java.util.HashSet)\n\n(def book\n (-> \"https://www.gutenberg.org/files/2600/2600-0.txt\"\n slurp\n split-lines))\n\n(def r-word\n (comp\n (r/map lower-case)\n (r/remove blank?)\n (r/map #(re-find #\"\\w+\" %))\n (r/mapcat #(split % #\"\\s+\"))))\n\n(def btree\n (r/fold (r/cat #(HashSet.))\n r/append!\n (r-word book)))\n\n(defn merge-tree [root res]\n (cond\n (instance? clojure.core.reducers.Cat root)\n (do (merge-tree (.left root) res) (merge-tree (.right root) res))\n (instance? HashSet root)\n (doto res (.addAll root))\n :else res))\n\n(def distinct-words (merge-tree btree (HashSet.)))\n(count distinct-words)\n;; 17200","editors":[{"avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"},{"avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4","account-source":"github","login":"tomdl89"}],"_id":"5a023d22e4b0a08026c48c99"}],"notes":null,"arglists":["","ctor","left right"],"doc":"A high-performance combining fn that yields the catenation of the\n reduced values. The result is reducible, foldable, seqable and\n counted, providing the identity collections are reducible, seqable\n and counted. The single argument version will build a combining fn\n with the supplied identity constructor. Tests for identity\n with (zero? (count x)). See also foldcat.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.reducers/cat"},{"added":"1.5","ns":"clojure.core.reducers","name":"take-while","file":"clojure/core/reducers.clj","type":"function","column":1,"see-alsos":null,"line":189,"examples":null,"notes":null,"arglists":["pred","pred coll"],"doc":"Ends the reduction of coll when (pred val) returns logical false.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.reducers/take-while"},{"added":"1.5","ns":"clojure.core.reducers","name":"remove","file":"clojure/core/reducers.clj","type":"function","column":1,"see-alsos":null,"line":167,"examples":null,"notes":null,"arglists":["pred","pred coll"],"doc":"Removes values in the reduction of coll for which (pred val)\n returns logical true. Foldable.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.reducers/remove"},{"ns":"clojure.core.reducers","name":"pool","file":"clojure/core/reducers.clj","type":"var","column":1,"see-alsos":null,"line":22,"examples":null,"notes":null,"arglists":[],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.reducers/pool"},{"ns":"clojure.core.reducers","name":"CollFold","file":"clojure/core/reducers.clj","type":"var","column":1,"see-alsos":null,"line":48,"examples":null,"notes":null,"arglists":[],"doc":null,"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.reducers/CollFold"},{"added":"1.5","ns":"clojure.core.reducers","name":"folder","file":"clojure/core/reducers.clj","type":"function","column":1,"see-alsos":null,"line":81,"examples":[{"editors":[{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"}],"body":"(require '[clojure.core.reducers :as r])\n(r/fold\n (r/monoid merge (constantly {}))\n (fn [m k v] (assoc m k (+ 3 v)))\n (r/folder\n (zipmap (range 100) (range 100))\n (fn [rf] (fn [m k v] (if (zero? (mod k 10)) (rf m k v) m)))))\n;; {0 3, 70 73, 20 23, 60 63, 50 53, 40 43, 90 93, 30 33, 10 13, 80 83}","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"},"created-at":1505064428954,"updated-at":1505064553043,"_id":"59b575ece4b09f63b945ac6e"}],"notes":null,"arglists":["coll xf"],"doc":"Given a foldable collection, and a transformation function xf,\n returns a foldable collection, where any supplied reducing\n fn will be transformed by xf. xf is a function of reducing fn to\n reducing fn.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.reducers/folder"},{"added":"1.5","ns":"clojure.core.reducers","name":"append!","file":"clojure/core/reducers.clj","type":"function","column":1,"see-alsos":null,"line":275,"examples":null,"notes":null,"arglists":["acc x"],"doc":".adds x to acc and returns acc","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.reducers/append!"},{"ns":"clojure.core.reducers","name":"->Cat","file":"clojure/core/reducers.clj","type":"function","column":1,"see-alsos":null,"line":230,"examples":null,"notes":null,"arglists":["cnt left right"],"doc":"Positional factory function for class clojure.core.reducers.Cat.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.reducers/->Cat"},{"added":"1.5","ns":"clojure.core.reducers","name":"drop","file":"clojure/core/reducers.clj","type":"function","column":1,"see-alsos":null,"line":215,"examples":[{"updated-at":1621653290675,"created-at":1621653290675,"author":{"login":"andreasguther","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/9425214?v=4"},"body":"Clojure 1.10.3\nuser=> (def coll (range 10))\n#'user/coll\nuser=> coll\n(0 1 2 3 4 5 6 7 8 9)\nuser=> (drop 4 coll)\n(4 5 6 7 8 9)","_id":"60a8772ae4b0b1e3652d7503"}],"notes":null,"arglists":["n","n coll"],"doc":"Elides the first n values from the reduction of coll.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.reducers/drop"},{"added":"1.5","ns":"clojure.core.reducers","name":"fold","file":"clojure/core/reducers.clj","type":"function","column":1,"see-alsos":[{"created-at":1505066414445,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"pmap","ns":"clojure.core"},"_id":"59b57daee4b09f63b945ac70"},{"created-at":1514410031569,"author":{"login":"jcburley","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/430319?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"reduce","ns":"clojure.core"},"_id":"5a44102fe4b0a08026c48ce0"}],"line":51,"examples":[{"editors":[{"login":"xfcjscn","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/4743082?v=4"}],"body":"(require '[clojure.core.reducers :as reducers])\n(defn diddly ([xs x] (conj xs x)) ([] []))\n(reducers/fold diddly '(1 2 3 4 5 6)) \n;; [1 2 3 4 5 6] \n\n\n;; CAUTION! This example is buggy, as diddly can NOT be used as combinef\n;; Correct combinef can be `into` as combinef is operating on 2 vectors","author":{"avatar-url":"https://avatars.githubusercontent.com/u/5030667?v=3","account-source":"github","login":"davidsiefert"},"created-at":1463744297516,"updated-at":1524749191933,"_id":"573ef729e4b00a9b70be566a"},{"editors":[{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"}],"body":";; word-frequencies on large text\n(require '[clojure.core.reducers :as r] '[clojure.string :as s])\n\n(defn count-occurrences [words]\n (r/fold\n (r/monoid #(merge-with + %1 %2) (constantly {}))\n (fn [m [k cnt]] (assoc m k (+ cnt (get m k 0))))\n (r/map #(vector % 1) words)))\n\n(defn word-count [s]\n (count-occurrences (s/split s #\"\\s+\")))\n\n(def war-and-peace \"http://www.gutenberg.org/files/2600/2600-0.txt\")\n(def book (slurp war-and-peace))\n\n(def freqs (word-count book))\n(freqs \"Andrew\")\n;; 700","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"},"created-at":1518468936868,"updated-at":1518469083350,"_id":"5a81ff48e4b0316c0f44f8b9"},{"updated-at":1522439008885,"created-at":1522439008885,"author":{"login":"glts","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/1483271?v=4"},"body":";; One pitfall of clojure.core.reducers/fold is that the reducing function must\n;; take either three or two arguments according to whether the foldable\n;; collection is a map or not!\n\n(require '[clojure.core.reducers :as r])\n\n(def my-vector (vec (range 10000)))\n(def my-map (into {} (map (juxt (comp keyword str) identity)) my-vector))\n\n;; Identity folds for vector and map. Notice the differing arities of reducef.\n\n(->> my-vector\n (r/fold (r/monoid into vector)\n (fn [ret v] (conj ret v))) ; <- arity 2\n (= my-vector))\n\n(->> my-map\n (r/fold (r/monoid merge hash-map)\n (fn [ret k v] (assoc ret k v))) ; <- arity 3\n (= my-map))\n\n;; Caution: this behaviour is not documented. It breaks down as soon as you wrap\n;; the map in a reducer/folder.\n","_id":"5abe9360e4b045c27b7fac2b"},{"editors":[{"login":"enforser","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/5402402?v=4"}],"body":";; This example demonstrates how the partition size used to parallelize\n;; fold can be modified. \n(require '[clojure.core.reducers :as r])\n\n(defn simple-fold \n [partition-size]\n (r/fold partition-size\n + ;; function that returns the init value. (x) => 0\n +\n (r/filter odd?\n (r/map inc\n (r/filter number?\n (range 10000))))))\n\n;; Default partition size.\n(simple-fold 512) \n;;=> 25000000\n\n;; Raises the number of elements from coll that will be processed in each partition.\n(simple-fold 1000) \n;; => 25000000\n\n;; Partition each element to be processed separately.\n(simple-fold 1) \n;; =>> 25000000\n\n;; All of the above return the same result, but they utilize different\n;; sized partitions to achieve parallelization.","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/5402402?v=4","account-source":"github","login":"enforser"},"created-at":1537920358727,"updated-at":1537920400365,"_id":"5baacd66e4b00ac801ed9ea8"}],"notes":null,"arglists":["reducef coll","combinef reducef coll","n combinef reducef coll"],"doc":"Reduces a collection using a (potentially parallel) reduce-combine\n strategy. The collection is partitioned into groups of approximately\n n (default 512), each of which is reduced with reducef (with a seed\n value obtained by calling (combinef) with no arguments). The results\n of these reductions are then reduced with combinef (default\n reducef). combinef must be associative, and, when called with no\n arguments, (combinef) must produce its identity element. These\n operations may be performed in parallel, but the results will\n preserve order.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.reducers/fold"},{"added":"1.5","ns":"clojure.core.reducers","name":"flatten","file":"clojure/core/reducers.clj","type":"function","column":1,"see-alsos":null,"line":174,"examples":[{"updated-at":1477678517441,"created-at":1477678517441,"author":{"login":"lifehug","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/689626?v=3"},"body":"user=> (require '[clojure.core.reducers :as r])\n\nuser=> (into [] (r/flatten [1 [2 3 4 5 6 7] 8]))\n[1 2 3 4 5 6 7 8]\n\nuser=> (into [] (r/flatten [0 2 [[2 3] 8 [[100]] nil [[nil]]] -2]))\n[0 2 2 3 8 100 nil nil -2]\n\nuser=> (into [] (r/flatten nil))\n[]\n","_id":"581395b5e4b024b73ca35a1f"}],"notes":null,"arglists":["","coll"],"doc":"Takes any nested combination of sequential things (lists, vectors,\n etc.) and returns their contents as a single, flat foldable\n collection.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.reducers/flatten"},{"added":"1.5","ns":"clojure.core.reducers","name":"filter","file":"clojure/core/reducers.clj","type":"function","column":1,"see-alsos":null,"line":154,"examples":[{"updated-at":1667792431871,"created-at":1667792431871,"author":{"login":"iatenine","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/4423088?v=4"},"body":";; lambda provided as predicate: (fn [n] (< n 4))\n;; collection to filter: [1, 2, 3, 4, 5]\n\n(filter (fn [n] (< n 4)) [1, 2, 3, 4, 5]) ;; => (1 2 3)","_id":"63687e2fe4b0b1e3652d7681"}],"notes":null,"arglists":["pred","pred coll"],"doc":"Retains values in the reduction of coll for which (pred val)\n returns logical true. Foldable.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.reducers/filter"},{"ns":"clojure.core.reducers","name":"fjtask","file":"clojure/core/reducers.clj","type":"function","column":1,"see-alsos":null,"line":24,"examples":null,"notes":null,"arglists":["f"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.reducers/fjtask"},{"added":"1.5","ns":"clojure.core.reducers","name":"monoid","file":"clojure/core/reducers.clj","type":"function","column":1,"see-alsos":null,"line":287,"examples":[{"editors":[{"login":"danielcompton","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/811954?v=3"}],"body":"(require '[clojure.core.reducers :as reducers])\n\n(reducers/fold\n (reducers/monoid + (constantly 0))\n (range 10000))\n;; => 49995000\n\n(reducers/fold\n (reducers/monoid max (constantly Long/MIN_VALUE))\n [1 2 7 10 3 -5])\n;; => 10","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/811954?v=3","account-source":"github","login":"danielcompton"},"created-at":1496113685577,"updated-at":1496113867385,"_id":"592ce215e4b0bebe93300ecb"}],"notes":null,"arglists":["op ctor"],"doc":"Builds a combining fn out of the supplied operator and identity\n constructor. op must be associative and ctor called with no args\n must return an identity value for it.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.reducers/monoid"},{"ns":"clojure.core.reducers","name":"coll-fold","type":"function","see-alsos":null,"examples":null,"notes":null,"tag":null,"arglists":["coll n combinef reducef"],"doc":null,"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.reducers/coll-fold"},{"ns":"clojure.core.server","name":"stop-server","file":"clojure/core/server.clj","type":"function","column":1,"see-alsos":null,"line":126,"examples":null,"notes":null,"arglists":["","name"],"doc":"Stop server with name or use the server-name from *session* if none supplied.\n Returns true if server stopped successfully, nil if not found, or throws if\n there is an error closing the socket.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.server/stop-server"},{"ns":"clojure.core.server","name":"repl-init","file":"clojure/core/server.clj","type":"function","column":1,"see-alsos":null,"line":166,"examples":null,"notes":null,"arglists":[""],"doc":"Initialize repl in user namespace and make standard repl requires.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.server/repl-init"},{"ns":"clojure.core.server","name":"start-server","file":"clojure/core/server.clj","type":"function","column":1,"see-alsos":null,"line":85,"examples":null,"notes":null,"arglists":["opts"],"doc":"Start a socket server given the specified opts:\n :address Host or address, string, defaults to loopback address\n :port Port, integer, required\n :name Name, required\n :accept Namespaced symbol of the accept function to invoke, required\n :args Vector of args to pass to accept function\n :bind-err Bind *err* to socket out stream?, defaults to true\n :server-daemon Is server thread a daemon?, defaults to true\n :client-daemon Are client threads daemons?, defaults to true\n Returns server socket.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.server/start-server"},{"ns":"clojure.core.server","name":"start-servers","file":"clojure/core/server.clj","type":"function","column":1,"see-alsos":null,"line":160,"examples":null,"notes":null,"arglists":["system-props"],"doc":"Start all servers specified in the system properties.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.server/start-servers"},{"ns":"clojure.core.server","name":"stop-servers","file":"clojure/core/server.clj","type":"function","column":1,"see-alsos":null,"line":140,"examples":null,"notes":null,"arglists":[""],"doc":"Stop all servers ignores all errors, and returns nil.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.server/stop-servers"},{"ns":"clojure.core.server","name":"repl-read","file":"clojure/core/server.clj","type":"function","column":1,"see-alsos":null,"line":172,"examples":null,"notes":null,"arglists":["request-prompt request-exit"],"doc":"Enhanced :read hook for repl supporting :repl/quit.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.server/repl-read"},{"ns":"clojure.core.server","name":"*session*","file":"clojure/core/server.clj","type":"var","column":1,"see-alsos":null,"dynamic":true,"line":24,"examples":null,"notes":null,"arglists":[],"library-url":"https://github.com/clojure/clojure","href":"/clojure.core.server/*session*"},{"added":"1.10","ns":"clojure.core.server","name":"io-prepl","file":"clojure/core/server.clj","type":"function","column":1,"see-alsos":null,"line":275,"examples":null,"notes":null,"arglists":["& {:keys [valf], :or {valf pr-str}}"],"doc":"prepl bound to *in* and *out*, suitable for use with e.g. server/repl (socket-repl).\n :ret and :tap vals will be processed by valf, a fn of one argument\n or a symbol naming same (default pr-str)\n\n Alpha, subject to change.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.server/io-prepl"},{"added":"1.10","ns":"clojure.core.server","name":"prepl","file":"clojure/core/server.clj","type":"function","column":1,"see-alsos":null,"line":194,"examples":null,"notes":null,"arglists":["in-reader out-fn & {:keys [stdin]}"],"doc":"a REPL with structured output (for programs)\n reads forms to eval from in-reader (a LineNumberingPushbackReader)\n Closing the input or passing the form :repl/quit will cause it to return\n\n Calls out-fn with data, one of:\n {:tag :ret\n :val val ;;eval result, or Throwable->map data if exception thrown\n :ns ns-name-string\n :ms long ;;eval time in milliseconds\n :form string ;;iff successfully read\n :exception true ;;iff exception thrown\n }\n {:tag :out\n :val string} ;chars from during-eval *out*\n {:tag :err\n :val string} ;chars from during-eval *err*\n {:tag :tap\n :val val} ;values from tap>\n\n You might get more than one :out or :err per eval, but exactly one :ret\n tap output can happen at any time (i.e. between evals)\n If during eval an attempt is made to read *in* it will read from in-reader unless :stdin is supplied\n\n Alpha, subject to change.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.server/prepl"},{"ns":"clojure.core.server","name":"repl","file":"clojure/core/server.clj","type":"function","column":1,"see-alsos":null,"line":183,"examples":null,"notes":null,"arglists":[""],"doc":"REPL with predefined hooks for attachable socket server.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.server/repl"},{"added":"1.10","ns":"clojure.core.server","name":"remote-prepl","file":"clojure/core/server.clj","type":"function","column":1,"see-alsos":null,"line":298,"examples":null,"notes":null,"arglists":["host port in-reader out-fn & {:keys [valf readf], :or {valf read-string, readf (fn* [p1__9123# p2__9124#] (read p1__9123# false p2__9124#))}}"],"doc":"Implements a prepl on in-reader and out-fn by forwarding to a\n remote [io-]prepl over a socket. Messages will be read by readf, a\n fn of a LineNumberingPushbackReader and EOF value or a symbol naming\n same (default #(read %1 false %2)),\n :ret and :tap vals will be processed by valf, a fn of one argument\n or a symbol naming same (default read-string). If that function\n throws, :val will be unprocessed.\n\n Alpha, subject to change.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core.server/remote-prepl"},{"added":"1.3","ns":"clojure.data","name":"diff","file":"clojure/data.clj","type":"function","column":1,"see-alsos":null,"line":124,"examples":[{"author":{"login":"joshrotenberg","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/aa968cafce96d1810cb1014c7545d4a5?r=PG&default=identicon"},"editors":[],"body":"(use 'clojure.data)\n(def uno {:same \"same\", :different \"one\"})\n(def dos {:same \"same\", :different \"two\", :onlyhere \"whatever\"})\n(diff uno dos)\n=> ({:different \"one\"} {:onlyhere \"whatever\", :different \"two\"} {:same \"same\"})\n;; {different in uno} { different or unique in dos } {same in both}\n(diff {:a 1} {:a 1 :b 2})\n=> (nil {:b 2} {:a 1})\n;; the first contains nothing unique, but only the second contains :b\n;; and both contain :a","created-at":1321070124000,"updated-at":1321070124000,"_id":"542692d6c026201cdc3270d7"},{"body":"(diff [1 2 3] [5 9 3 2 3 7]) ;;=> [[1 2] [5 9 nil 2 3 7] [nil nil 3]]\n(diff (set [1 2 3]) (set [5 9 3 2 3 7])) ;;=> [#{1} #{7 9 5} #{3 2}]","author":{"login":"vede1","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8151095?v=2"},"created-at":1414076160639,"updated-at":1414076160639,"_id":"54491700e4b03d20a1024276"},{"updated-at":1455883330938,"created-at":1455883167587,"author":{"login":"zootalures","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/4050521?v=3"},"body":";; To invert a diff you can re-apply diff to its output and then merge this back with the prior state \n;; This works in almost all cases (with the exception of preserving empty maps) \n\n(defn- seqzip\n \"returns a sequence of [[ value-left] [value-right]....] padding with nulls for shorter sequences \"\n [left right]\n (loop [list [] a left b right]\n (if (or (seq a) (seq b))\n (recur (conj list [(first a) (first b)] ) (rest a) (rest b))\n list)))\n\n(defn- recursive-diff-merge\n \" Merge two structures recusively , taking non-nil values from sequences and maps and merging sets\" \n [part-state original-state]\n (cond\n (sequential? part-state) (map (fn [[l r]] (recursive-diff-merge l r)) (seqzip part-state original-state))\n (map? part-state) (merge-with recursive-diff-merge part-state original-state)\n (set? part-state) (set/union part-state original-state)\n (nil? part-state ) original-state\n :default part-state))\n\n(defn undiff\n \"returns the state of x after reversing the changes described by a diff against\n an earlier state (where before and after are the first two elements of the diff)\"\n [x before after]\n (let [[a _ _] (clojure.data/diff x after)]\n (recursive-diff-merge a before)))\n\n;; examples: \n\n;; Simple data types\n(clojure.data/diff :before :after )\n=> [:before :after nil]\n\n(undiff :after :before :after)\n=> :before\n\n;; Lists \n(clojure.data/diff [1 2 3 4] [1 2 3 5] )\n=> [[nil nil nil 4] [nil nil nil 5] [1 2 3]]\n(undiff [1 2 3 5] [nil nil nil 4] [nil nil nil 5] )\n=> (1 2 3 4)\n\n;; Nested complex data structures; \n(clojure.data/diff {:a 1 :b [1 2 3] :c {:d 4}}\n {:a 2 :b [1 2 3 4] :c {:d 3 :e 10}})\n=> ({:c {:d 4}, :a 1} {:c {:d 3, :e 10}, :b [nil nil nil 4], :a 2} {:b [1 2 3]})\n\n(undiff {:a 2 :b [1 2 3 4] :c {:d 3 :e 10}} ; State after diff \n {:c {:d 4}, :a 1} ; first element of diff against previous state\n {:c {:d 3, :e 10}, :b [nil nil nil 4], :a 2}) ; second element of diff \n ; against previous state \n=> {:b [1 2 3], :c {:d 4}, :a 1}\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/4050521?v=3","account-source":"github","login":"zootalures"}],"_id":"56c7039fe4b0b41f39d96cce"},{"updated-at":1589309791553,"created-at":1589309791553,"author":{"login":"Biserkov","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/49756?v=4"},"body":";; Beware that empty maps get turned into nil\n(clojure.data/diff {:a {:b 1} :c 2} {:a {} :c 2})\n=> ({:a {:b 1}} {:a nil} {:c 2})","_id":"5ebaf15fe4b087629b5a190b"},{"editors":[{"login":"marcoslimagon","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8239564?v=4"}],"body":";; The diff also applies for nested structures\n\n;; Example creating a function that evaluates if a given value is subset of a map\n(defn map-subset? [map subset]\n (let [[_ subset_diff _] (clojure.data/diff map subset)]\n (nil? subset_diff)))\n\n(def a {\"KEY\" {\n :kv1 {:nested \"X\"}\n :kv2 \"Y\"\n }} )\n(def b {\"KEY\" {\n :kv1 {:nested \"X\"}\n }})\n(map-subset? a b)\n\n=> true","author":{"avatar-url":"https://avatars.githubusercontent.com/u/8239564?v=4","account-source":"github","login":"marcoslimagon"},"created-at":1674505567719,"updated-at":1674505657687,"_id":"63ceed5fe4b08cf8563f4b6a"}],"notes":[{"author":{"login":"Bost","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/1174677?v=4"},"updated-at":1585396974568,"created-at":1585396974568,"body":"See also https://github.com/lambdaisland/deep-diff2 \"Deep diff Clojure data structures and pretty print the result\"","_id":"5e7f3ceee4b087629b5a18c7"},{"author":{"login":"huahaiy","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/889685?v=4"},"updated-at":1594482387999,"created-at":1594482387999,"body":"See https://github.com/juji-io/editscript \"Editscript is a library designed to extract the differences between two Clojure/Clojurescript data structures as an 'editscript', which represents the minimal modification necessary to transform one to another\"","_id":"5f09ded3e4b0b1e3652d731e"}],"arglists":["a b"],"doc":"Recursively compares a and b, returning a tuple of\n [things-only-in-a things-only-in-b things-in-both].\n Comparison rules:\n\n * For equal a and b, return [nil nil a].\n * Maps are subdiffed where keys match and values differ.\n * Sets are never subdiffed.\n * All sequential things are treated as associative collections\n by their indexes, with results returned as vectors.\n * Everything else (including strings!) is treated as\n an atom and compared for equality.","library-url":"https://github.com/clojure/clojure","href":"/clojure.data/diff"},{"added":"1.3","ns":"clojure.data","name":"equality-partition","type":"function","see-alsos":null,"examples":null,"notes":null,"tag":null,"arglists":["x"],"doc":"Implementation detail. Subject to change.","library-url":"https://github.com/clojure/clojure","href":"/clojure.data/equality-partition"},{"added":"1.3","ns":"clojure.data","name":"EqualityPartition","file":"clojure/data.clj","type":"var","column":1,"see-alsos":null,"line":69,"examples":null,"notes":null,"arglists":[],"doc":"Implementation detail. Subject to change.","library-url":"https://github.com/clojure/clojure","href":"/clojure.data/EqualityPartition"},{"added":"1.3","ns":"clojure.data","name":"diff-similar","type":"function","see-alsos":null,"examples":null,"notes":null,"tag":null,"arglists":["a b"],"doc":"Implementation detail. Subject to change.","library-url":"https://github.com/clojure/clojure","href":"/clojure.data/diff-similar"},{"added":"1.3","ns":"clojure.data","name":"Diff","file":"clojure/data.clj","type":"var","column":1,"see-alsos":null,"line":73,"examples":null,"notes":null,"arglists":[],"doc":"Implementation detail. Subject to change.","library-url":"https://github.com/clojure/clojure","href":"/clojure.data/Diff"},{"ns":"clojure.data.csv","name":"read-csv","file":"clojure/data/csv.clj","type":"function","column":1,"see-alsos":null,"line":87,"examples":[{"updated-at":1767567650699,"created-at":1767567650699,"author":{"login":"sponkurtus2","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/74841175?v=4"},"body":";; To use read-csv, you need to add [org.clojure/data.csv \"1.1.1\"] to your \n;; dependencies and require the namespace.\n(require '[clojure.data.csv :as csv]\n '[clojure.java.io :as io])\n\n;; Assuming a file named \"family.csv\" with the following content:\n;; name|age|happy\n;; *Carlos*|21|true\n;; *Alex*|34|true\n;; *Kevin*|5|false\n\n;; use with-open to ensure the reader closes after the data is read\n(with-open [reader (io/reader \"data/family.csv\")]\n ;; read-csv returns a lazy sequence; use doall to force loading \n ;; of the data before the reader closes.\n (doall\n (csv/read-csv reader\n :separator \\|\n :quote \\*)))\n\n;;=> ([\"name\" \"age\" \"happy\"] \n;; [\"Carlos\" \"21\" \"true\"] \n;; [\"Alex\" \"34\" \"true\"] \n;; [\"Kevin\" \"5\" \"false\"])","_id":"695af122b7956e24e4cb4ecc"}],"notes":null,"arglists":["input & options"],"doc":"Reads CSV-data from input (String or java.io.Reader) into a lazy\n sequence of vectors.\n\n Valid options are\n :separator (default \\,)\n :quote (default \\\")","library-url":"https://github.com/clojure/clojure","href":"/clojure.data.csv/read-csv"},{"ns":"clojure.data.csv","name":"Read-CSV-From","file":"clojure/data/csv.clj","type":"var","column":1,"see-alsos":null,"line":66,"examples":null,"notes":null,"arglists":[],"doc":null,"library-url":"https://github.com/clojure/clojure","href":"/clojure.data.csv/Read-CSV-From"},{"ns":"clojure.data.csv","name":"read-csv-from","type":"function","see-alsos":null,"examples":null,"notes":null,"tag":null,"arglists":["input sep quote"],"doc":null,"library-url":"https://github.com/clojure/clojure","href":"/clojure.data.csv/read-csv-from"},{"ns":"clojure.data.csv","name":"write-csv","file":"clojure/data/csv.clj","type":"function","column":1,"see-alsos":[{"created-at":1699359021793,"author":{"login":"nbardiuk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/381992?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"writer","ns":"clojure.java.io"},"_id":"654a292d69fbcc0c22617425"},{"created-at":1728483574199,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"with-open","ns":"clojure.core"},"_id":"670690f669fbcc0c22617501"}],"line":127,"examples":[{"updated-at":1728483557344,"created-at":1728483557344,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":";; Typical usage, with a header row, and a vector of vectors of strings\n;; Although you might prefer a clojure.java.io/writer to output to a file…\n(with-open [s (java.io.StringWriter.)]\n (csv/write-csv s [[\"col header 1\" \"col header 2\"]\n [\"r1c1\" \"r1c2\"]\n [\"r2c1\" \"r2c2\"]])\n (str s))\n;; => \"col header 1,col header 2\\nr1c1,r1c2\\nr2c1,r2c2\\n\"\n\n;; Non-strings will be stringified\n;; Note that symbols and strings usually look the same…\n(with-open [s (java.io.StringWriter.)]\n (csv/write-csv s [[\"foo\" 42 'foo {:nested :map} \"a \\\"quoted\\\" string\"]])\n (str s))\n;; => \"foo,42,foo,{:nested :map},\\\"a \\\"\\\"quoted\\\"\\\" string\\\"\\n\"\n\n;; With a clojure.java.io/writer, you can write to a file…\n(with-open [w (clojure.java.io/writer \"foo.csv\")]\n (csv/write-csv w [[\"foo\" 42 'foo {:nested :map} \"a \\\"quoted\\\" string\"]]))\n;; => nil","_id":"670690e569fbcc0c22617500"}],"notes":null,"arglists":["writer data & options"],"doc":"Writes data to writer in CSV-format.\n\n Valid options are\n :separator (Default \\,)\n :quote (Default \\\")\n :quote? (A predicate function which determines if a string should be quoted. Defaults to quoting only when necessary.)\n :newline (:lf (default) or :cr+lf)","library-url":"https://github.com/clojure/clojure","href":"/clojure.data.csv/write-csv"},{"ns":"clojure.datafy","name":"nav","file":"clojure/datafy.clj","type":"function","column":1,"see-alsos":null,"line":30,"examples":null,"notes":null,"arglists":["coll k v"],"doc":"Returns (possibly transformed) v in the context of coll and k (a\n key/index or nil). Callers should attempt to provide the key/index\n context k for Indexed/Associative/ILookup colls if possible, but not\n to fabricate one e.g. for sequences (pass nil). nav returns the\n value of clojure.core.protocols/nav.","library-url":"https://github.com/clojure/clojure","href":"/clojure.datafy/nav"},{"ns":"clojure.datafy","name":"datafy","file":"clojure/datafy.clj","type":"function","column":1,"see-alsos":null,"line":15,"examples":[{"updated-at":1641146617559,"created-at":1641146617559,"author":{"login":"claj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/353113?v=4"},"body":";; default impl is the identity\n(datafy {:message \"Hello\"})\n=>\n{:message \"Hello\"}\n\n;; exceptions default datafy impl is `Throwable->map`\n(datafy (ex-info \"An Exception\" {:msg \"something went wrong\"}))\n{:cause \"An Exception\",\n :data {:msg \"something went wrong\"}\n :via\n [{:type clojure.lang.ExceptionInfo,\n :message \"An Exception\",\n :data {:msg \"something went wrong\"},\n :at [user$eval16337 invokeStatic \"form-init3462716552974711523.clj\" 120]}],\n :trace\n [[user$eval16337 invokeStatic \"form-init3462716552974711523.clj\" 120]\n [user$eval16337 invoke \"form-init3462716552974711523.clj\" 120]\n [clojure.lang.Compiler eval \"Compiler.java\" 7181]\n ,,,\n [clojure.lang.AFn run \"AFn.java\" 22]\n [java.lang.Thread run \"Thread.java\" 833]]}","_id":"61d1e8f9e4b0b1e3652d7597"},{"editors":[{"login":"claj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/353113?v=4"}],"body":";; add a (bogus) Datafy implementation for java.util.Date\n\n(require '[clojure.core.protocols :as p])\n(require '[clojure.datafy :as d])\n\n(extend-protocol p/Datafiable\n java.util.Date\n (datafy [d]\n {:type 'Date\n :timestamp (.getTime d)}))\n\n(d/datafy (java.util.Date.))\n;;=> {:type Date, :timestamp 1641145865991}\n","author":{"avatar-url":"https://avatars.githubusercontent.com/u/353113?v=4","account-source":"github","login":"claj"},"created-at":1641147412716,"updated-at":1641219235911,"_id":"61d1ec14e4b0b1e3652d7598"},{"editors":[{"login":"claj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/353113?v=4"},{"avatar-url":"https://avatars.githubusercontent.com/u/6537820?v=4","account-source":"github","login":"siddharthjain-in"},{"login":"SergeyKozachenko","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1427311?v=4"},{"avatar-url":"https://avatars.githubusercontent.com/u/6143833?v=4","account-source":"github","login":"rgkirch"}],"body":";; adding a data representation to a java.io.File\n\n(require '[clojure.core.protocols :as p])\n(require '[clojure.datafy :as d])\n\n(extend-protocol p/Datafiable\n java.io.File\n (datafy [f]\n {:exists (.exists f)\n :length (.length f)\n :last-modified (.lastModified f)\n :path (.toString f)})))\n\n(d/datafy (java.io.File. \"/home/alfred/todo.txt\"))\n;;=> {:exists true,\n;; :length 28850,\n;; :last-modified 1641082627553,\n;; :path \"/home/alfred/todo.txt\"}\n\n;; java.io.File is availiable with (:clojure.datafy/obj (meta ...))","author":{"avatar-url":"https://avatars.githubusercontent.com/u/353113?v=4","account-source":"github","login":"claj"},"created-at":1641147941988,"updated-at":1707414030367,"_id":"61d1ee25e4b0b1e3652d7599"}],"notes":null,"arglists":["x"],"doc":"Attempts to return x as data.\n datafy will return the value of clojure.core.protocols/datafy. If\n the value has been transformed and the result supports\n metadata, :clojure.datafy/obj will be set on the metadata to the\n original value of x, and :clojure.datafy/class to the name of the\n class of x, as a symbol.","library-url":"https://github.com/clojure/clojure","href":"/clojure.datafy/datafy"},{"added":"1.5","ns":"clojure.edn","name":"read","file":"clojure/edn.clj","type":"function","column":1,"see-alsos":[{"created-at":1582146666132,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"read-string","ns":"clojure.edn"},"_id":"5e4da46ae4b0ca44402ef83f"}],"line":14,"examples":[{"editors":[{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/94482?v=3"}],"body":";; See one of the examples for clojure.core/pr for some uncommon Clojure values\n;; that cannot be printed then read back to get the original values (or in\n;; some cases, cannot be read back at all).\n\n;; If you wish to transmit data that may contain such values, one suggestion\n;; is to use the transit library: https://github.com/cognitect/transit-format","author":{"avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3","account-source":"github","login":"jafingerhut"},"created-at":1470508582724,"updated-at":1470754331719,"_id":"57a62e26e4b0bafd3e2a04cb"},{"editors":[{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/94482?v=3"}],"body":";; Note that it is not possible to pass the result of (clojure.java.io/reader) \n;; directly to (clojure.edn/read):\n(require '[clojure.java.io :as io] '[clojure.edn :as edn])\n=> nil\n(edn/read (io/reader (.getBytes \":edn\")))\nClassCastException java.io.BufferedReader cannot be cast to java.io.PushbackReader\n\n;; Instead, you need to construct a java.io.PushbackReader instance\n;; and pass that to (edn/read):\n(edn/read (java.io.PushbackReader. (io/reader (.getBytes \":edn\"))))\n=> :edn\n","author":{"avatar-url":"https://avatars.githubusercontent.com/u/94482?v=3","account-source":"github","login":"timgilbert"},"created-at":1470759663495,"updated-at":1470842100437,"_id":"57aa02efe4b0bafd3e2a04d1"},{"editors":[{"login":"elias94","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8095533?v=4"}],"body":";; If you need to distinguish between I/O errors (permission denied, etc)\n;; and syntax errors in the EDN itself (eg, unbalanced parentheses), you'll\n;; want to catch different exceptions from (edn/read):\n\n(defn load-edn\n \"Load edn from an io/reader source (filename or io/resource).\"\n [source]\n (try\n (with-open [r (io/reader source)]\n (edn/read (java.io.PushbackReader. r)))\n\n (catch java.io.IOException e\n (printf \"Couldn't open '%s': %s\\n\" source (.getMessage e)))\n (catch RuntimeException e\n (printf \"Error parsing edn file '%s': %s\\n\" source (.getMessage e)))))","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/94482?v=4","account-source":"github","login":"timgilbert"},"created-at":1516827524686,"updated-at":1629516163850,"_id":"5a68f384e4b09621d9f53a79"},{"updated-at":1619537620688,"created-at":1619111247295,"author":{"login":"seltzer1717","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1911117?v=4"},"body":";; At some point you'll want to serialize and deserialize java.time.LocalDate.\n;; Here's how:\n\n(defn localdate-rdr\n \"Takes serialized Java object, tests for LocalDate, and returns LocalDate object.\"\n [[clazz _ object-string :as input]] ;; [java.time.LocalDate 861096493 \"2021-04-22\"]\n (if (= 'java.time.LocalDate clazz)\n ;; LocalDate string will be of form yyyy-mm-dd\n ;; which also matches the parse function.\n (java.time.LocalDate/parse object-string)\n ;; just returns input if serialized object is not LocalDate\n input))\n\n(defn test-localdate-rdr\n []\n (let [today (java.time.LocalDate/now)\n ;; seralized -> \"#object[java.time.LocalDate 0x4479783b \\\"2021-04-22\\\"]\"\n serialized (pr-str today)\n deserialized (clojure.edn/read {:readers {'object localdate-rdr}}\n (java.io.PushbackReader.\n (java.io.StringReader. serialized)))]\n (.toString (.plusDays deserialized 1))))\n\nuser=> (test-localdate-rdr) \n\"2021-04-23\" ;; Today was 2021-04-22\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/1911117?v=4","account-source":"github","login":"seltzer1717"}],"_id":"6081ad4fe4b0b1e3652d74cf"}],"notes":[{"author":{"login":"rmoehn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/311879?v=3"},"updated-at":1436251602311,"created-at":1436251602311,"body":"For everyone struggling to provide custom reader functions to\n`clojure.edn/read`: _you cannot do that through `data_readers.clj`_.\n`data_readers.clj` can be used to provide custom reader functions for\n`clojure.core/read` and `clojure.core/read-string`, but not `clojure.edn/read`\nand `clojure.edn/read-string`.\n\nYou look carefully and you'll find that the official documentation does say so:\nif you don't supply a map of `:readers`, ‘only the `default-data-readers` will\nbe used’. But the information from `data_readers.clj` ends up in\n`*data-readers*` not `default-data-readers`. However, you'd have to look\n_very_ carefully to find this out.\n\n(If you're not interested in silly stories, you can skip the following two\nparagraphs and continue with the last.)\n\nNow you might think: ‘then I'll just say `(edn/read-string {:readers\n*data-readers*} )`’. On the first try this will probably fail, because\nyou forgot to `require` the namespaces where the reader functions live. Okay,\nyou've fixed that………\n\nBrowsing from your smartphone now? I know, your home directory just got wiped.\nAnd the external drive with the backups that's always plugged in to your machine\nas well. Why's that? Well, the procedures from `clojure.edn` are supposed to be\nsafe, to not execute any code, so that you can use them with data from untrusted\nsources. If you do want to have code executed (only from trusted sources, of\ncourse), you use the corresponding procedures from `clojure.core`. Now, there\nare people who know about `data_readers.clj` only being used by\n`clojure.core/read` and `clojure.core/read-string`, which aren't safe. So they\ndon't make their reader functions safe either. `guten-tag.core/read-tagged-val`\nis such an example. It calls `eval` on the data it is passed. That means, if you\nuse it with `clojure.edn/read` or `clojure.edn/read-string`, those will become\nas unsafe as their `clojure.core` counterparts.\n\nSorry for the long story. The moral is: have a very careful look at the reader\nfunctions you provide to the procedures from `clojure.edn`. If they execute code\nthat's passed to them, all safety is lost.\n","_id":"559b75d2e4b020189d740549"}],"arglists":["","stream","opts stream"],"doc":"Reads the next object from stream, which must be an instance of\n java.io.PushbackReader or some derivee. stream defaults to the\n current value of *in*.\n\n Reads data in the edn format (subset of Clojure data):\n http://edn-format.org\n\n opts is a map that can include the following keys:\n :eof - value to return on end-of-file. When not supplied, eof throws an exception.\n :readers - a map of tag symbols to data-reader functions to be considered before default-data-readers.\n When not supplied, only the default-data-readers will be used.\n :default - A function of two args, that will, if present and no reader is found for a tag,\n be called with the tag and the value.","library-url":"https://github.com/clojure/clojure","href":"/clojure.edn/read"},{"added":"1.5","ns":"clojure.edn","name":"read-string","file":"clojure/edn.clj","type":"function","column":1,"see-alsos":[{"created-at":1412284709546,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"},"to-var":{"ns":"clojure.edn","name":"read","library-url":"https://github.com/clojure/clojure"},"_id":"542dc125e4b05f4d257a2994"},{"created-at":1412284813516,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"},"to-var":{"ns":"clojure.core","name":"prn-str","library-url":"https://github.com/clojure/clojure"},"_id":"542dc18de4b05f4d257a2998"},{"created-at":1422653108103,"author":{"login":"delonnewman","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10404?v=2"},"to-var":{"ns":"clojure.core","name":"read-string","library-url":"https://github.com/clojure/clojure"},"_id":"54cbf6b4e4b0e2ac61831cf1"},{"created-at":1422653117945,"author":{"login":"delonnewman","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10404?v=2"},"to-var":{"ns":"clojure.main","name":"load-script","library-url":"https://github.com/clojure/clojure"},"_id":"54cbf6bde4b081e022073c3d"},{"created-at":1661550967348,"author":{"login":"djblue","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1986211?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"tagged-literal","ns":"clojure.core"},"_id":"63094177e4b0b1e3652d7657"}],"line":37,"examples":[{"body":";; The following code is a subset of that found at\n;; http://www.compoundtheory.com/clojure-edn-walkthrough\n;; It illustrates the fact that the readers \n;; 'read' and 'read-string' have symmetric writers\n;; 'prn' and 'prn-str'.\n\n(ns edn-example.core\n (require [clojure.edn :as edn]))\n \n(def sample-map {:foo \"bar\" :bar \"foo\"})\n \n;; Here you can see that the 'prn-str' is the writer...\n(defn convert-sample-map-to-edn\n \"Converting a Map to EDN\"\n []\n ;; yep, converting a map to EDN is that simple\"\n (prn-str sample-map))\n \n(println \"Let's convert a map to EDN: \" (convert-sample-map-to-edn))\n;=> Let's convert a map to EDN: {:foo \"bar\", :bar \"foo\"}\n \n;; ...and the reader is 'read-string'\n(println \"Now let's covert the map back: \" (edn/read-string (convert-sample-map-to-edn)))\n;=> Now let's covert the map back: {:foo bar, :bar foo}","author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"},"created-at":1412284690591,"updated-at":1412285328892,"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"}],"_id":"542dc112e4b05f4d257a2993"},{"updated-at":1504691868756,"created-at":1504691868756,"author":{"login":"humorless","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/3061798?v=4"},"body":";; The following demonstrates the use case of edn built-in tagged elements\nuser=> (class (clojure.edn/read-string \"#inst \\\"1985-04-12T23:20:50.52Z\\\"\"))\njava.util.Date\n\n","_id":"59afc69ce4b09f63b945ac60"},{"updated-at":1604505958870,"created-at":1510500744747,"author":{"login":"Atsman","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/3405704?v=4"},"body":";; if you want to specify custom processing of some field add tag and function which process it\n;; let's assume we have edn with some relative paths and want to make them absolute\n\n(def config \"{:k8s-path #path \\\"./infra/k8s\\\"}\")\n\n(defn absolute [path] \"/users/some_user/project/k8s-path\")\n\n(edn/read-string {:readers {'path absolute}} config)\n\n{:k8s-path \"/users/some_user/project/k8s-path\"}","editors":[{"avatar-url":"https://avatars2.githubusercontent.com/u/3405704?v=4","account-source":"github","login":"Atsman"},{"login":"dosbol","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/6149147?v=4"}],"_id":"5a086988e4b0a08026c48cb4"},{"editors":[{"login":"manojarya","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/2968153?v=4"}],"body":";; following example adds a custom data-reader which dynamically resolves value\n;; of a property from a lookup map. Falls back on default value if specified.\n\n(defn lookup-reader [lookup-map]\n (fn [v]\n (let [[k default-value] (if (sequential? v)\n v\n [v nil])]\n (get lookup-map k default-value))))\n\n;; returns readers map of tag symbols and handler functions\n(defn readers [lookup-map]\n {:readers {'prop (lookup-reader lookup-map)}})\n\n;; DB_HOST value is resolved while DB_PORT will be default\n(edn/read-string (readers {\"DB_HOST\" \"db-server1\"}) \"{:host #prop [\\\"DB_HOST\\\" \\\"localhost\\\"] :port #prop [\\\"DB_PORT\\\" 42]}\")\n;; {:host \"db-server1\", :port 42}","author":{"avatar-url":"https://avatars0.githubusercontent.com/u/2968153?v=4","account-source":"github","login":"manojarya"},"created-at":1569410505522,"updated-at":1569568738213,"_id":"5d8b4dc9e4b0ca44402ef7c0"}],"notes":null,"arglists":["s","opts s"],"doc":"Reads one object from the string s. Returns nil when s is nil or empty.\n\n Reads data in the edn format (subset of Clojure data):\n http://edn-format.org\n\n opts is a map as per clojure.edn/read","library-url":"https://github.com/clojure/clojure","href":"/clojure.edn/read-string"},{"added":"1.0","ns":"clojure.inspector","name":"inspect-table","file":"clojure/inspector.clj","type":"function","column":1,"see-alsos":[{"created-at":1331449134000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.pprint","name":"print-table","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521aff"},{"created-at":1331449142000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.inspector","name":"inspect-tree","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b00"}],"line":100,"examples":[{"updated-at":1438202947024,"created-at":1438202947024,"author":{"login":"lildata","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7280019?v=3"},"body":"(use 'clojure.inspector)\n(inspect-table [{:a 1 :b 2 :c 3}{:a 4 :b 5 :c 6}])","_id":"55b93c43e4b03580923b00d8"},{"updated-at":1545395763248,"created-at":1545395763248,"author":{"login":"sanel","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/213914?v=4"},"body":";; display every element type alongside value in table\nuser=> (inspect-table\n (map #(vector (type %) %)\n [1 \"something\" \\c (java.io.File. \"/tmp/x\") 0.12 1234]))","_id":"5c1cde33e4b0ca44402ef5f3"}],"notes":null,"arglists":["data"],"doc":"creates a graphical (Swing) inspector on the supplied regular\n data, which must be a sequential data structure of data structures\n of equal length","library-url":"https://github.com/clojure/clojure","href":"/clojure.inspector/inspect-table"},{"ns":"clojure.inspector","name":"atom?","file":"clojure/inspector.clj","type":"function","column":1,"see-alsos":[{"created-at":1341044327000,"author":{"login":"klauern","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/76c55292df5e9df9042eaf89ac35954b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"isa?","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d24"}],"line":19,"examples":[{"author":{"login":"OnesimusUnbound","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2fa4c391db0d2d1744cc2cd0d787dd3d?r=PG&default=identicon"},"editors":[],"body":";; atom? returns true if the form passed does not \n;; implement IPersistentCollection. The atom referred \n;; here is not the atom used in managing mutable state \n\nuser=> (use `[clojure.inspector :include (atom?)])\n\nuser=> (atom? 1)\ntrue\n\nuser=> (atom? \\a)\ntrue\n\nuser=> (atom? \"hello world\")\ntrue\n\nuser=> (atom? :keyword)\ntrue\n\nuser=> (atom? nil)\ntrue\n\nuser=> (atom? '())\nfalse\n\nuser=> (atom? [1, 3, 5])\nfalse\n\nuser=> (atom? #{\\a \\e \\i \\o \\u})\nfalse\n\nuser=> (atom? {:x 16 :y 25})\nfalse","created-at":1313787533000,"updated-at":1313787533000,"_id":"542692d0c026201cdc326eb1"}],"notes":null,"arglists":["x"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.inspector/atom_q"},{"ns":"clojure.inspector","name":"list-provider","file":"clojure/inspector.clj","type":"var","column":1,"see-alsos":null,"line":112,"examples":null,"notes":null,"arglists":[],"library-url":"https://github.com/clojure/clojure","href":"/clojure.inspector/list-provider"},{"ns":"clojure.inspector","name":"is-leaf","file":"clojure/inspector.clj","type":"var","column":1,"see-alsos":null,"line":31,"examples":null,"notes":null,"arglists":[],"library-url":"https://github.com/clojure/clojure","href":"/clojure.inspector/is-leaf"},{"ns":"clojure.inspector","name":"old-table-model","file":"clojure/inspector.clj","type":"function","column":1,"see-alsos":null,"line":72,"examples":null,"notes":null,"arglists":["data"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.inspector/old-table-model"},{"ns":"clojure.inspector","name":"tree-model","file":"clojure/inspector.clj","type":"function","column":1,"see-alsos":null,"line":56,"examples":null,"notes":null,"arglists":["data"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.inspector/tree-model"},{"added":"1.0","ns":"clojure.inspector","name":"inspect","file":"clojure/inspector.clj","type":"function","column":1,"see-alsos":null,"line":154,"examples":[{"updated-at":1545395525526,"created-at":1545395525526,"author":{"login":"sanel","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/213914?v=4"},"body":";; display Swing table with value and value type\nuser=> (inspect \"something\")\n\n;; display every element (with index) in separate Swing table row\nuser=> (inspect [1 2 3])","_id":"5c1cdd45e4b0ca44402ef5f2"},{"updated-at":1586829405546,"created-at":1586829405546,"author":{"login":"staypufd","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/10730?v=4"},"body":";; display all the attributes of the complex Java object (Swing JFrame in \n;; the example).\nuser=> \n(clojure.inspector/inspect \n (bean \n (javax.swing.JFrame. \"hello\")))\n\n","_id":"5e95185de4b087629b5a18d3"}],"notes":null,"arglists":["x"],"doc":"creates a graphical (Swing) inspector on the supplied object","library-url":"https://github.com/clojure/clojure","href":"/clojure.inspector/inspect"},{"ns":"clojure.inspector","name":"collection-tag","file":"clojure/inspector.clj","type":"function","column":1,"see-alsos":null,"line":22,"examples":[{"updated-at":1477012162986,"created-at":1477012162986,"author":{"login":"dalzony","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/562341?v=3"},"body":"user=> (clojure.inspector/collection-tag (first {:a 1 :b 2}))\n;;=> :entry\nuser=> (clojure.inspector/collection-tag {:a 1})\n;;=> :seqable\nuser=> (clojure.inspector/collection-tag #{:a 1})\n;;=> :seqable\nuser=> (clojure.inspector/collection-tag [1 2])\n;;=> :seq\nuser=> (clojure.inspector/collection-tag :a)\n;;=> :atom\n","_id":"58096ac2e4b001179b66bdd8"}],"notes":null,"arglists":["x"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.inspector/collection-tag"},{"ns":"clojure.inspector","name":"get-child-count","file":"clojure/inspector.clj","type":"var","column":1,"see-alsos":null,"line":33,"examples":null,"notes":null,"arglists":[],"library-url":"https://github.com/clojure/clojure","href":"/clojure.inspector/get-child-count"},{"added":"1.0","ns":"clojure.inspector","name":"inspect-tree","file":"clojure/inspector.clj","type":"function","column":1,"see-alsos":[{"created-at":1331449151000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.inspector","name":"inspect-table","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f47"}],"line":91,"examples":[{"updated-at":1545395305082,"created-at":1545395305082,"author":{"login":"sanel","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/213914?v=4"},"body":";; opens Swing window with interactive tree component\nuser=> (inspect-tree '(a (1 2) b (3 4) c (5 6)))\n\n;; you can also visualize complex nested maps\nuser=> (inspect-tree {:a {:aa [1 2 3]\n :ab 3}\n :b 1\n :c {:ca {:caa [{:foo 1}\n {:foo 2}]}}})\n","_id":"5c1cdc69e4b0ca44402ef5f1"}],"notes":null,"arglists":["data"],"doc":"creates a graphical (Swing) inspector on the supplied hierarchical data","library-url":"https://github.com/clojure/clojure","href":"/clojure.inspector/inspect-tree"},{"ns":"clojure.inspector","name":"get-child","file":"clojure/inspector.clj","type":"var","column":1,"see-alsos":null,"line":32,"examples":null,"notes":null,"arglists":[],"library-url":"https://github.com/clojure/clojure","href":"/clojure.inspector/get-child"},{"ns":"clojure.inspector","name":"list-model","file":"clojure/inspector.clj","type":"function","column":1,"see-alsos":null,"line":129,"examples":null,"notes":null,"arglists":["provider"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.inspector/list-model"},{"ns":"clojure.inspector","name":"table-model","file":"clojure/inspector.clj","type":"var","column":1,"see-alsos":null,"line":139,"examples":null,"notes":null,"arglists":[],"library-url":"https://github.com/clojure/clojure","href":"/clojure.inspector/table-model"},{"ns":"clojure.instant","name":"validated","file":"clojure/instant.clj","type":"function","column":1,"see-alsos":null,"line":139,"examples":null,"notes":null,"arglists":["new-instance"],"doc":"Return a function which constructs an instant by calling constructor\nafter first validating that those arguments are in range and otherwise\nplausible. The resulting function will throw an exception if called\nwith invalid arguments.","library-url":"https://github.com/clojure/clojure","href":"/clojure.instant/validated"},{"ns":"clojure.instant","name":"read-instant-timestamp","file":"clojure/instant.clj","type":"function","column":1,"see-alsos":[{"created-at":1617958817276,"author":{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1334295?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"read-instant-date","ns":"clojure.instant"},"_id":"607017a1e4b0b1e3652d74bd"}],"line":288,"examples":[{"updated-at":1583436804622,"created-at":1583436804622,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"},"body":"(clojure.instant/read-instant-date \"2020-03-23T01:17Z\")\n;=> #inst \"2020-03-23T01:17:00.000-00:00\"","_id":"5e615404e4b087629b5a18ba"}],"notes":null,"arglists":["cs"],"doc":"To read an instant as a java.sql.Timestamp, bind *data-readers* to a\nmap with this var as the value for the 'inst key. Timestamp preserves\nfractional seconds with nanosecond precision. The timezone offset will\nbe used to convert into UTC.","library-url":"https://github.com/clojure/clojure","href":"/clojure.instant/read-instant-timestamp"},{"ns":"clojure.instant","name":"read-instant-calendar","file":"clojure/instant.clj","type":"function","column":1,"see-alsos":null,"line":281,"examples":null,"notes":null,"arglists":["cs"],"doc":"To read an instant as a java.util.Calendar, bind *data-readers* to a map with\nthis var as the value for the 'inst key. Calendar preserves the timezone\noffset.","library-url":"https://github.com/clojure/clojure","href":"/clojure.instant/read-instant-calendar"},{"ns":"clojure.instant","name":"read-instant-date","file":"clojure/instant.clj","type":"function","column":1,"see-alsos":[{"created-at":1587829080311,"author":{"login":"kyptin","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/254619?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"parse-timestamp","ns":"clojure.instant"},"_id":"5ea45958e4b087629b5a18e8"},{"created-at":1617958825769,"author":{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1334295?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"read-instant-timestamp","ns":"clojure.instant"},"_id":"607017a9e4b0b1e3652d74be"}],"line":274,"examples":[{"editors":[{"login":"cassc","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1858231?v=4"}],"body":";; Parse a string with RFC3339-like timestamp to get a java.util.Date object\n\n(use 'clojure.instant)\n(read-instant-date \"2017-08-23T10:22:22\")\n;; #inst \"2017-08-23T10:22:22.000-00:00\"\n\n;; If no timezone info is included in the input string, GMT is assumed.\n;; See clojure.instant/parse-timestamp for the timestamp pattern supported.","author":{"avatar-url":"https://avatars2.githubusercontent.com/u/1858231?v=4","account-source":"github","login":"cassc"},"created-at":1504252223491,"updated-at":1504252436727,"_id":"59a9113fe4b09f63b945ac5c"}],"notes":null,"arglists":["cs"],"doc":"To read an instant as a java.util.Date, bind *data-readers* to a map with\nthis var as the value for the 'inst key. The timezone offset will be used\nto convert into UTC.","library-url":"https://github.com/clojure/clojure","href":"/clojure.instant/read-instant-date"},{"ns":"clojure.instant","name":"parse-timestamp","file":"clojure/instant.clj","type":"function","column":1,"see-alsos":[{"created-at":1583436680072,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"read-instant-timestamp","ns":"clojure.instant"},"_id":"5e615388e4b087629b5a18b8"},{"created-at":1583436695565,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"read-instant-date","ns":"clojure.instant"},"_id":"5e615397e4b087629b5a18b9"}],"line":53,"examples":[{"editors":[{"login":"kyptin","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/254619?v=4"}],"body":"(require '[clojure.instant :as instant])\n(instant/parse-timestamp vector \"2020-04-25T15:09:16.437Z\")\n;; => [2020 4 25 15 9 16 437000000 0 0 0]\n\n;; But the other functions in this namespace might be more convenient, e.g.:\n(instant/read-instant-date \"2020-04-25T15:09:16.437Z\")\n;; => #inst \"2020-04-25T15:09:16.437-00:00\"","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/254619?v=4","account-source":"github","login":"kyptin"},"created-at":1587829024785,"updated-at":1587956901157,"_id":"5ea45920e4b087629b5a18e7"}],"notes":null,"arglists":["new-instant cs"],"doc":"Parse a string containing an RFC3339-like like timestamp.\n\nThe function new-instant is called with the following arguments.\n\n min max default\n --- ------------ -------\n years 0 9999 N/A (s must provide years)\n months 1 12 1\n days 1 31 1 (actual max days depends\n hours 0 23 0 on month and year)\n minutes 0 59 0\n seconds 0 60 0 (though 60 is only valid\n nanoseconds 0 999999999 0 when minutes is 59)\n offset-sign -1 1 0\n offset-hours 0 23 0\n offset-minutes 0 59 0\n\nThese are all integers and will be non-nil. (The listed defaults\nwill be passed if the corresponding field is not present in s.)\n\nGrammar (of s):\n\n date-fullyear = 4DIGIT\n date-month = 2DIGIT ; 01-12\n date-mday = 2DIGIT ; 01-28, 01-29, 01-30, 01-31 based on\n ; month/year\n time-hour = 2DIGIT ; 00-23\n time-minute = 2DIGIT ; 00-59\n time-second = 2DIGIT ; 00-58, 00-59, 00-60 based on leap second\n ; rules\n time-secfrac = '.' 1*DIGIT\n time-numoffset = ('+' / '-') time-hour ':' time-minute\n time-offset = 'Z' / time-numoffset\n\n time-part = time-hour [ ':' time-minute [ ':' time-second\n [time-secfrac] [time-offset] ] ]\n\n timestamp = date-year [ '-' date-month [ '-' date-mday\n [ 'T' time-part ] ] ]\n\nUnlike RFC3339:\n\n - we only parse the timestamp format\n - timestamp can elide trailing components\n - time-offset is optional (defaults to +00:00)\n\nThough time-offset is syntactically optional, a missing time-offset\nwill be treated as if the time-offset zero (+00:00) had been\nspecified.\n","library-url":"https://github.com/clojure/clojure","href":"/clojure.instant/parse-timestamp"},{"added":"1.2","ns":"clojure.java.browse","name":"browse-url","file":"clojure/java/browse.clj","type":"function","column":1,"see-alsos":[{"created-at":1420901028632,"author":{"login":"AeroNotix","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/975962?v=3"},"to-var":{"ns":"clojure.java.browse","name":"*open-url-script*","library-url":"https://github.com/clojure/clojure"},"_id":"54b13aa4e4b081e022073bfe"}],"line":68,"examples":[{"author":{"login":"abhin4v","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/4d29918c109bc75d2a1fd8420660d72b?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":"user=> (use 'clojure.java.browse)\n\nuser=> (browse-url \"http://clojuredocs.org\")\n","created-at":1283270758000,"updated-at":1285494149000,"_id":"542692d0c026201cdc326eb2"},{"body":";;It's funny.... Open bash\n\n(browse-url \"/bin/bash\")","author":{"login":"LMSlay","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8565224?v=3"},"created-at":1427832992939,"updated-at":1427832992939,"_id":"551b00a0e4b056ca16cfecfd"}],"notes":null,"arglists":["url"],"doc":"Open url in a browser","library-url":"https://github.com/clojure/clojure","href":"/clojure.java.browse/browse-url"},{"ns":"clojure.java.browse","name":"*open-url-script*","file":"clojure/java/browse.clj","type":"var","column":1,"see-alsos":[{"created-at":1420901010720,"author":{"login":"AeroNotix","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/975962?v=3"},"to-var":{"ns":"clojure.java.browse","name":"browse-url","library-url":"https://github.com/clojure/clojure"},"_id":"54b13a92e4b081e022073bfd"}],"dynamic":true,"line":42,"examples":[{"body":";; Sets the script used when calling browse-url\n;;\n;; It needs to be an atom because internally the browse-url function\n;; dereferences *open-url-script*\n(binding [clojure.java.browse/*open-url-script* (atom \"/usr/bin/ls\")]\n (clojure.java.browse/browse-url \"http://google.com\"))","author":{"login":"AeroNotix","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/975962?v=3"},"created-at":1420900983542,"updated-at":1420900983542,"_id":"54b13a77e4b0e2ac61831ca4"}],"notes":null,"arglists":[],"library-url":"https://github.com/clojure/clojure","href":"/clojure.java.browse/*open-url-script*"},{"ns":"clojure.java.io","name":"default-streams-impl","file":"clojure/java/io.clj","type":"var","column":1,"see-alsos":null,"line":167,"examples":null,"notes":null,"arglists":[],"library-url":"https://github.com/clojure/clojure","href":"/clojure.java.io/default-streams-impl"},{"added":"1.2","ns":"clojure.java.io","name":"make-output-stream","type":"function","see-alsos":[{"created-at":1435101653324,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"},"to-var":{"ns":"clojure.java.io","name":"writer","library-url":"https://github.com/clojure/clojure"},"_id":"5589e9d5e4b0fad27b85f921"}],"examples":null,"notes":null,"tag":null,"arglists":["x opts"],"doc":"Creates a BufferedOutputStream. See also IOFactory docs.","library-url":"https://github.com/clojure/clojure","href":"/clojure.java.io/make-output-stream"},{"added":"1.2","ns":"clojure.java.io","name":"make-parents","file":"clojure/java/io.clj","type":"function","column":1,"see-alsos":[{"created-at":1507587681180,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"file","ns":"clojure.java.io"},"_id":"59dbf661e4b03026fe14ea59"}],"line":441,"examples":[{"body":"(let [file-name \"path/to/whatever.txt\"]\n (make-parents file-name)\n (spit file-name \"whatever\"))","author":{"login":"mattvvhat","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/367789?v=3"},"created-at":1434030825430,"updated-at":1434030825430,"_id":"557992e9e4b01ad59b65f4f0"}],"notes":null,"arglists":["f & more"],"doc":"Given the same arg(s) as for file, creates all parent directories of\n the file they represent.","library-url":"https://github.com/clojure/clojure","href":"/clojure.java.io/make-parents"},{"added":"1.2","ns":"clojure.java.io","name":"delete-file","file":"clojure/java/io.clj","type":"function","column":1,"see-alsos":[{"created-at":1329988386000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.java.io","name":"file","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cb9"},{"created-at":1329988390000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.java.io","name":"copy","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cba"}],"line":433,"examples":[{"author":{"login":"shockbob","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/16046bb426a0fd26cbc876970fd8f746?r=PG&default=identicon"},"editors":[],"body":";; create a file using spit, then show its contents using slurp\n;; delete it and verify that it has been deleted by trying to print its\n;; contents again\n\nuser=> (require '[clojure.java.io :as io])\nnil\nuser=> (spit \"stuff.txt\" \"blurp\")\nnil\nuser=> (println (slurp \"stuff.txt\"))\nblurp\nnil\nuser=> (io/delete-file \"stuff.txt\")\ntrue\nuser=> (println (slurp \"stuff.txt\"))\njava.io.FileNotFoundException: stuff.txt (The system cannot find the file specif\nied) (NO_SOURCE_FILE:0)\nuser=>","created-at":1313906436000,"updated-at":1313906436000,"_id":"542692d0c026201cdc326eb9"},{"editors":[{"login":"zjliu1984","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1556007?v=3"}],"body":"(require '[clojure.java.io :as io])\n\nuser> (io/delete-file \"d:/code/python/file-which-does-not-exist.py\")\nIOException Couldn't delete d:/code/python/exist.py \nclojure.java.io/delete-file (io.clj:426)\n\nuser> (io/delete-file \"d:/code/python/file-which-does-not-exist.py\" true)\ntrue","author":{"avatar-url":"https://avatars.githubusercontent.com/u/1556007?v=3","account-source":"github","login":"zjliu1984"},"created-at":1482289924813,"updated-at":1482289948834,"_id":"5859f304e4b004d3a355e2d2"}],"notes":null,"arglists":["f & [silently]"],"doc":"Delete file f. If silently is nil or false, raise an exception on failure, else return the value of silently.","library-url":"https://github.com/clojure/clojure","href":"/clojure.java.io/delete-file"},{"added":"1.2","ns":"clojure.java.io","name":"input-stream","file":"clojure/java/io.clj","type":"function","column":1,"see-alsos":[{"created-at":1329988244000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.java.io","name":"reader","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521a9b"},{"created-at":1329988273000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.java.io","name":"output-stream","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521a9c"},{"created-at":1329988761000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.java.io","name":"IOFactory","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521a9d"},{"created-at":1331903198000,"author":{"login":"Pierre","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/dc0590890ca22fee047f8e2598c2568d?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"with-open","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521a9e"},{"created-at":1331903424000,"author":{"login":"Pierre","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/dc0590890ca22fee047f8e2598c2568d?r=PG&default=identicon"},"to-var":{"ns":"clojure.java.io","name":"make-input-stream","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521a9f"}],"line":124,"examples":[{"editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3","account-source":"github","login":"phreed"}],"updated-at":1507926708504,"created-at":1430431281427,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3","account-source":"github","login":"phreed"},"body":"(require '(clojure.java [io :as io]))\n\n;; A common task it to load a file into a byte array.\n(defn file->bytes [file]\n (with-open [xin (io/input-stream file)\n xout (java.io.ByteArrayOutputStream.)]\n (io/copy xin xout)\n (.toByteArray xout)))\n;=> #'boot.user/file->bytes\n\n(file->bytes (io/file \"/foo-pc\" \"junk.txt\"))\n;=> #object[\"[B\" 0x7813db81 \"[B@7813db81\"]\n\n\n","_id":"5542a631e4b01bb732af0a8f"},{"updated-at":1458914936478,"created-at":1458914936478,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10583730?v=3"},"body":"(require '[clojure.java.io :as io])\n\n;; these return a java.io.BufferedInputStream for a local file:\n(io/input-stream \"file.txt\")\n(io/input-stream \"/home/user/file.txt\")\n(io/input-stream \"file:///home/user/file.txt\")\n(io/input-stream (java.io.File. \"/home/user/file.txt\"))\n(io/input-stream (java.io.FileInputStream. \"file.txt\"))\n(io/input-stream (java.net.URL. \"file:///home/user/file.txt\"))\n(io/input-stream (java.net.URI. \"file:///home/user/file.txt\"))\n\n;; these return a java.io.BufferedInputStream for a remote resource:\n(io/input-stream \"http://clojuredocs.org/\")\n(io/input-stream (java.net.URL. \"http://clojuredocs.org\"))\n(io/input-stream (java.net.URI. \"http://clojuredocs.org\"))\n(let [socket (java.net.Socket. \"clojuredocs.org\" 80)\n out (java.io.PrintStream. (.getOutputStream socket))]\n (.println out \"GET /index.html HTTP/1.0\")\n (.println out \"Host: clojuredocs.org\\n\\n\")\n (io/input-stream socket))\n\n;; these return a java.io.BufferedInputStream from an in-memory source:\n(io/input-stream (.getBytes \"text\"))\n(io/input-stream (java.io.ByteArrayInputStream. (.getBytes \"text\")))\n(io/input-stream (byte-array [116 101 120 116]))\n","_id":"56f54678e4b09295d75dbf3f"}],"notes":null,"tag":"java.io.InputStream","arglists":["x & opts"],"doc":"Attempts to coerce its argument into an open java.io.InputStream.\n Default implementations always return a java.io.BufferedInputStream.\n\n Default implementations are defined for InputStream, File, URI, URL,\n Socket, byte array, and String arguments.\n\n If the argument is a String, it tries to resolve it first as a URI, then\n as a local file name. URIs with a 'file' protocol are converted to\n local file names.\n\n Should be used inside with-open to ensure the InputStream is properly\n closed.","library-url":"https://github.com/clojure/clojure","href":"/clojure.java.io/input-stream"},{"added":"1.2","ns":"clojure.java.io","name":"make-writer","type":"function","see-alsos":[{"created-at":1435099993554,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"},"to-var":{"ns":"clojure.java.io","name":"writer","library-url":"https://github.com/clojure/clojure"},"_id":"5589e359e4b05f167dcf2342"}],"examples":null,"notes":null,"tag":null,"arglists":["x opts"],"doc":"Creates a BufferedWriter. See also IOFactory docs.","library-url":"https://github.com/clojure/clojure","href":"/clojure.java.io/make-writer"},{"added":"1.2","ns":"clojure.java.io","name":"as-relative-path","file":"clojure/java/io.clj","type":"function","column":1,"see-alsos":null,"line":411,"examples":[{"editors":[{"login":"zjliu1984","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1556007?v=3"}],"body":"(require '[clojure.java.io :as io])\n\n; on windows\nuser> (io/as-relative-path \"this/is\")\n\"this\\\\is\n\nuser> (io/as-relative-path \"c:/code\")\nIllegalArgumentException c:\\code is not a relative path clojure.java.io/as-relative-path (io.clj:405)","author":{"avatar-url":"https://avatars.githubusercontent.com/u/1556007?v=3","account-source":"github","login":"zjliu1984"},"created-at":1482288709426,"updated-at":1482288737304,"_id":"5859ee45e4b004d3a355e2d0"}],"notes":null,"tag":"java.lang.String","arglists":["x"],"doc":"Take an as-file-able thing and return a string if it is\n a relative path, else IllegalArgumentException.","library-url":"https://github.com/clojure/clojure","href":"/clojure.java.io/as-relative-path"},{"added":"1.2","ns":"clojure.java.io","name":"copy","file":"clojure/java/io.clj","type":"function","column":1,"see-alsos":[{"created-at":1329988342000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.java.io","name":"file","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ccd"}],"line":394,"examples":[{"updated-at":1561584738124,"created-at":1306503567000,"body":"(ns your-project\n (:require [clojure.java.io :as io]))\n\n(defn copy-file [source-path dest-path]\n (io/copy (io/file source-path) (io/file dest-path)))\n\n(copy-file \"/home/username/squirrel.txt\" \"/home/username/burt-reynolds.txt\")\n\n;; Or, after extending the related multimethod:\n\n(defmethod @#'io/do-copy [String String] [in out opts]\n (apply io/copy (io/file in) (io/file out) opts))\n\n(io/copy \"/home/username/squirrel.txt\" \"/home/username/burt-reynolds.txt\")","editors":[{"avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon","account-source":"clojuredocs","login":"boxie"},{"avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon","account-source":"clojuredocs","login":"boxie"},{"avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3","account-source":"github","login":"devn"},"_id":"542692d0c026201cdc326eb4"},{"updated-at":1577094940425,"created-at":1577094940425,"author":{"login":"Hindol","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/705227?v=4"},"body":";; Can be used to save a URL to disk. See: https://stackoverflow.com/a/19297746/1019491\n\n(defn copy-uri-to-file [uri file]\n (with-open [in (clojure.java.io/input-stream uri)\n out (clojure.java.io/output-stream file)]\n (clojure.java.io/copy in out)))","_id":"5e008f1ce4b0ca44402ef7fe"},{"updated-at":1676155296789,"created-at":1676155296789,"author":{"login":"wedesoft","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/28663?v=4"},"body":";; Concatenate two files.\n\n(with-open [out (clojure.java.io/output-stream \"output.txt\")]\n (clojure.java.io/copy (clojure.java.io/file \"input1.txt\") out)\n (clojure.java.io/copy (clojure.java.io/file \"input2.txt\") out))","_id":"63e819a0e4b08cf8563f4b6d"}],"notes":null,"arglists":["input output & opts"],"doc":"Copies input to output. Returns nil or throws IOException.\n Input may be an InputStream, Reader, File, byte[], char[], or String.\n Output may be an OutputStream, Writer, or File.\n\n Options are key/value pairs and may be one of\n\n :buffer-size buffer size to use, default is 1024.\n :encoding encoding to use if converting between\n byte and char streams. \n\n Does not close any streams except those it opens itself \n (on a File).","library-url":"https://github.com/clojure/clojure","href":"/clojure.java.io/copy"},{"added":"1.2","ns":"clojure.java.io","name":"as-file","type":"function","see-alsos":[{"created-at":1332830735000,"author":{"login":"eric","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2b0c9ae6f1da9716451e7c86bc87230b?r=PG&default=identicon"},"to-var":{"ns":"clojure.java.io","name":"file","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521eb4"}],"examples":[{"updated-at":1482262177780,"created-at":1285050867000,"body":"; It returns a java.io.File object\n> (require '[clojure.java.io :as io] )\n> (class (io/as-file \".\"))\njava.io.File\n\n; You can call java methods such as File/exists\n> (.exists (io/as-file \"dummy.txt\"))\nfalse\n> (.exists (io/as-file \"project.clj\"))\ntrue\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3","account-source":"github","login":"jafingerhut"},{"login":"cloojure","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7083783?v=3"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon","account-source":"clojuredocs","login":"gstamp"},"_id":"542692d0c026201cdc326eba"}],"notes":[{"author":{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/94482?v=4"},"updated-at":1516410057934,"created-at":1516410057934,"body":"This is a low-level function for getting a file object from a single string.\nIn contrast, `(clojure.java.io/file)` is a higher-level API that will let you do \nthings like construct paths to files using strings and other file objects, \nas in `(io/file root-dir \"subdir\" \"filename.ext\")`.","_id":"5a6294c9e4b0a08026c48d08"}],"tag":"java.io.File","arglists":["x"],"doc":"Coerce argument to a file.","library-url":"https://github.com/clojure/clojure","href":"/clojure.java.io/as-file"},{"added":"1.2","ns":"clojure.java.io","name":"output-stream","file":"clojure/java/io.clj","type":"function","column":1,"see-alsos":[{"created-at":1329988282000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.java.io","name":"writer","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b21"},{"created-at":1329988289000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.java.io","name":"input-stream","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b22"},{"created-at":1329988768000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.java.io","name":"IOFactory","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b23"},{"created-at":1418120263796,"author":{"login":"alilee","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/16739?v=3"},"to-var":{"ns":"clojure.java.io","name":"make-output-stream","library-url":"https://github.com/clojure/clojure"},"_id":"5486cc47e4b09260f767ca74"}],"line":141,"examples":[{"updated-at":1619977096473,"created-at":1338273014000,"body":"(:use [clojure.java.io :as io])\n\n(defn use-output-stream []\n (with-open [o (io/output-stream \"test.txt\")]\n (.write o 65))) ; Writes 'A'","editors":[{"avatar-url":"https://www.gravatar.com/avatar/dae0f434afde5246ccb030cdec81fb71?r=PG&default=identicon","account-source":"clojuredocs","login":"Omer"},{"login":"drewverlee","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1130688?v=4"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/dae0f434afde5246ccb030cdec81fb71?r=PG&default=identicon","account-source":"clojuredocs","login":"Omer"},"_id":"542692d6c026201cdc3270d9"}],"notes":null,"tag":"java.io.OutputStream","arglists":["x & opts"],"doc":"Attempts to coerce its argument into an open java.io.OutputStream.\n Default implementations always return a java.io.BufferedOutputStream.\n\n Default implementations are defined for OutputStream, File, URI, URL,\n Socket, and String arguments.\n\n If the argument is a String, it tries to resolve it first as a URI, then\n as a local file name. URIs with a 'file' protocol are converted to\n local file names.\n\n Should be used inside with-open to ensure the OutputStream is\n properly closed.","library-url":"https://github.com/clojure/clojure","href":"/clojure.java.io/output-stream"},{"added":"1.2","ns":"clojure.java.io","name":"make-reader","type":"function","see-alsos":null,"examples":null,"notes":[{"updated-at":1393559963000,"body":"Don't use this. You probably want [reader](reader) instead.","created-at":1393559963000,"author":{"login":"TheAlchemist","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/43b98f8119f22e58791a57950145b051?r=PG&default=identicon"},"_id":"542692edf6e94c697052201e"}],"tag":null,"arglists":["x opts"],"doc":"Creates a BufferedReader. See also IOFactory docs.","library-url":"https://github.com/clojure/clojure","href":"/clojure.java.io/make-reader"},{"added":"1.2","ns":"clojure.java.io","name":"Coercions","file":"clojure/java/io.clj","type":"var","column":1,"see-alsos":null,"line":38,"examples":null,"notes":null,"arglists":[],"doc":"Coerce between various 'resource-namish' things.","library-url":"https://github.com/clojure/clojure","href":"/clojure.java.io/Coercions"},{"added":"1.2","ns":"clojure.java.io","name":"file","file":"clojure/java/io.clj","type":"function","column":1,"see-alsos":[{"created-at":1329988433000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.core","name":"file-seq","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521dfc"},{"created-at":1329988641000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.java.io","name":"reader","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521dfd"},{"created-at":1329988645000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.java.io","name":"writer","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521dfe"},{"created-at":1330337356000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.java.io","name":"delete-file","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521dff"},{"created-at":1507587660510,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"make-parents","ns":"clojure.java.io"},"_id":"59dbf64ce4b03026fe14ea58"},{"created-at":1550262589878,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"as-file","ns":"clojure.java.io"},"_id":"5c67213de4b0ca44402ef686"},{"created-at":1550262611875,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"load-file","ns":"clojure.core"},"_id":"5c672153e4b0ca44402ef687"}],"line":421,"examples":[{"author":{"login":"dakrone","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bcacd00a7f05c4772329cf9f446c7987?r=PG&default=identicon"},"editors":[],"body":"user> (clojure.java.io/file \"/tmp/foo\")\n#\n\nuser> (clojure.java.io/file \"http://asdf.com\")\n#\n\nuser> (clojure.java.io/file \"/tmp/foo\" \"bar\")\n#","created-at":1293673542000,"updated-at":1293673542000,"_id":"542692d0c026201cdc326eb7"},{"updated-at":1462995759891,"created-at":1399010194000,"body":"; Use clojure.java.io to read in resources from the classpath\n\n(ns rescue.core\n (:require [clojure.java.io :as io] ))\n\n; Populate the file on the command line: \n; echo \"Hello Resources!\" > resources/hello.txt\n(def data-file (io/resource \n \"hello.txt\" ))\n(defn -main []\n (println (slurp data-file)) )\n; When do \"lein run\"\n; => Hello Resources!","editors":[{"login":"slipset","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/5894926?v=3"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/1ad3de25d00d953de6e8c82f554cdbf5?r=PG&default=identicon","account-source":"clojuredocs","login":"cloojure"},"_id":"542692d6c026201cdc3270d8"},{"body":"; slurp can be used directly on value of io/resource\n\n(ns rescue.core\n (require [clojure.java.io :as io]))\n\n; echo \"hello world\" > resources/hello.txt\n(def data (io/resource \"hello.txt\"))\n\n(defn -main []\n (println (slurp data-file))\n; when do \"lein run\"\n; => hello world","author":{"login":"m00nlight","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/5475472?v=3"},"created-at":1422524528923,"updated-at":1422524528923,"_id":"54ca0070e4b0e2ac61831ce8"}],"notes":null,"tag":"java.io.File","arglists":["arg","parent child","parent child & more"],"doc":"Returns a java.io.File, passing each arg to as-file. Multiple-arg\n versions treat the first argument as parent and subsequent args as\n children relative to the parent.","library-url":"https://github.com/clojure/clojure","href":"/clojure.java.io/file"},{"added":"1.2","ns":"clojure.java.io","name":"make-input-stream","type":"function","see-alsos":[{"created-at":1331903445000,"author":{"login":"Pierre","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/dc0590890ca22fee047f8e2598c2568d?r=PG&default=identicon"},"to-var":{"ns":"clojure.java.io","name":"IOFactory","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d61"}],"examples":null,"notes":null,"tag":null,"arglists":["x opts"],"doc":"Creates a BufferedInputStream. See also IOFactory docs.","library-url":"https://github.com/clojure/clojure","href":"/clojure.java.io/make-input-stream"},{"added":"1.2","ns":"clojure.java.io","name":"IOFactory","file":"clojure/java/io.clj","type":"var","column":1,"see-alsos":[{"created-at":1329988722000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.java.io","name":"reader","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bdc"},{"created-at":1329988725000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.java.io","name":"writer","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bdd"},{"created-at":1329988729000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.java.io","name":"input-stream","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bde"},{"created-at":1329988733000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.java.io","name":"output-stream","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bdf"}],"line":72,"examples":null,"notes":null,"arglists":[],"doc":"Factory functions that create ready-to-use, buffered versions of\n the various Java I/O stream types, on top of anything that can\n be unequivocally converted to the requested kind of stream.\n\n Common options include\n \n :append true to open stream in append mode\n :encoding string name of encoding to use, e.g. \"UTF-8\".\n\n Callers should generally prefer the higher level API provided by\n reader, writer, input-stream, and output-stream.","library-url":"https://github.com/clojure/clojure","href":"/clojure.java.io/IOFactory"},{"added":"1.2","ns":"clojure.java.io","name":"resource","file":"clojure/java/io.clj","type":"function","column":1,"see-alsos":[{"created-at":1529009753028,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"slurp","ns":"clojure.core"},"_id":"5b22d659e4b00ac801ed9e15"},{"created-at":1529010567539,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"reader","ns":"clojure.java.io"},"_id":"5b22d987e4b00ac801ed9e17"},{"created-at":1529010728887,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"line-seq","ns":"clojure.core"},"_id":"5b22da28e4b00ac801ed9e18"}],"line":449,"examples":[{"author":{"login":"cloojure","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1ad3de25d00d953de6e8c82f554cdbf5?r=PG&default=identicon"},"editors":[{"login":"cloojure","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1ad3de25d00d953de6e8c82f554cdbf5?r=PG&default=identicon"},{"avatar-url":"https://avatars.githubusercontent.com/u/11081351?v=3","account-source":"github","login":"rauhs"},{"login":"flyboarder","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/147004?v=3"}],"body":"; Use clojure.java.io/resource to read resources from the classpath:\n\n(ns rescue.core\n (:require [clojure.java.io :as io] ))\n\n; Populate the file on the command line: \n; echo \"Hello Resources!\" > resources/hello.txt\n(def data-file (io/resource \n \"hello.txt\" ))\n(defn -main []\n (println (slurp data-file)) )\n; When do \"lein run\"\n; => Hello Resources!","created-at":1399010149000,"updated-at":1494456807781,"_id":"542692d6c026201cdc3270dc"},{"body":"(require '(clojure.java.io :as io))\n\n;; If the resource does not exist on the classpath a nil is returned.\n(io/resource \"I_do_not_exist.txt\")\n;;=> nil","author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"},"created-at":1435094542239,"updated-at":1435094573241,"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"_id":"5589ce0ee4b0fad27b85f91e"}],"notes":[{"body":"If you need to `slurp` a file from a JAR file, don't call `io/file` on the result of calling `io/resource`, or you will get an exception that says the resource is \"not a file\". Instead, call `slurp` directly on the result of `io/resource`.","created-at":1435260445537,"updated-at":1435260445537,"author":{"login":"kyptin","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/254619?v=3"},"_id":"558c561de4b0fad27b85f927"},{"author":{"login":"benwhorwood","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/17282487?v=3"},"updated-at":1469616475473,"created-at":1469616313988,"body":"If you need to copy a **binary** file from a running JAR (or WAR), don't call `slurp` as it will try and decode the file. Instead, extract similarily to:\n\n
    \n(with-open [in (io/input-stream (io/resource \"file.dat\"))] ;; resources/file.dat\n    (io/copy in (io/file \"/path/to/extract/file.dat\"))))\n
    ","_id":"579890b9e4b0bafd3e2a04be"}],"tag":"java.net.URL","arglists":["n","n loader"],"doc":"Returns the URL for a named resource. Use the context class loader\n if no loader is specified.","library-url":"https://github.com/clojure/clojure","href":"/clojure.java.io/resource"},{"added":"1.2","ns":"clojure.java.io","name":"writer","file":"clojure/java/io.clj","type":"function","column":1,"see-alsos":[{"created-at":1324516890000,"author":{"login":"cgray","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/7fe6255dbe4806a588cc06a5ba4a5d82?r=PG&default=identicon"},"to-var":{"ns":"clojure.java.io","name":"reader","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e40"},{"created-at":1329988746000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.java.io","name":"IOFactory","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e41"},{"created-at":1330170599000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.java.io","name":"output-stream","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e42"},{"created-at":1334795963000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.core","name":"spit","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e43"}],"line":107,"examples":[{"author":{"login":"weiyongqing123","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8341059515e9e257bbb8da3c9fc158c2?r=PG&default=identicon"},"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"body":";; This example shows the use of the ':append' option\n(defn write-file []\n (with-open [w (clojure.java.io/writer \"f:/w.txt\" :append true)]\n (.write w (str \"hello\" \"world\"))))","created-at":1329302480000,"updated-at":1434481428515,"_id":"542692d6c026201cdc3270de"},{"body":";; This example shows the use of the ':encoding' option.\n(require '(clojure.data.xml :as xml))\n\n(let [tags (xml/element :foo {:foo-attr \"foo value\"}\n (xml/element :bar {:bar-attr \"bar value\"}\n (xml/element :baz {} \"The baz value\")))]\n (with-open [out-file (clojure.java.io/writer \"/temp/bar.xml\" :encoding \"UTF-8\")]\n (xml/emit tags out-file))\n (with-open [input (clojure.java.io/reader \"/temp/bar.xml\")]\n (xml/parse input)))\n;;=> #clojure.data.xml.Element{:tag :foo, :attrs {:foo-attr \"foo value\"}, \n;; :content \n;; (#clojure.data.xml.Element{:tag :bar, :attrs {:bar-attr \"bar value\"},\n;; :content \n;; (#clojure.data.xml.Element{:tag :baz, :attrs {}, :content (\"The baz value\")})})}","author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"},"created-at":1434481387584,"updated-at":1434481476334,"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"}],"_id":"558072ebe4b01ad59b65f4fa"},{"updated-at":1495636148152,"created-at":1495636148152,"author":{"login":"jasonmm","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/2171623?v=3"},"body":";; When a Writer is created from a Socket using `with-open`, the \n;; underlying Socket is closed along with the Writer.\n\n;; Create the Socket.\n(require '[clojure.java.io :as io])\n(def socket (java.net.Socket.))\n(.connect socket (java.net.InetSocketAddress. \"www.google.com\" 80))\n(.isClosed socket)\n;;=> false\n\n;; Write to the Socket.\n(with-open [w (io/writer socket)]\n (.write w \"GET / HTTP/1.0\\n\\n\")\n (.flush w))\n(.isClosed socket)\n;;=> true\n\n;; Attempt to read from the Socket.\n(with-open [r (io/reader socket)\n s (java.io.StringWriter.)]\n (io/copy r s))\n;;=> java.net.SocketException: Socket is closed\n","_id":"592598b4e4b093ada4d4d722"}],"notes":null,"tag":"java.io.Writer","arglists":["x & opts"],"doc":"Attempts to coerce its argument into an open java.io.Writer.\n Default implementations always return a java.io.BufferedWriter.\n\n Default implementations are provided for Writer, BufferedWriter,\n OutputStream, File, URI, URL, Socket, and String.\n\n If the argument is a String, it tries to resolve it first as a URI, then\n as a local file name. URIs with a 'file' protocol are converted to\n local file names.\n\n Should be used inside with-open to ensure the Writer is properly\n closed.","library-url":"https://github.com/clojure/clojure","href":"/clojure.java.io/writer"},{"added":"1.2","ns":"clojure.java.io","name":"as-url","type":"function","see-alsos":[{"created-at":1561545843452,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"file","ns":"clojure.java.io"},"_id":"5d134c73e4b0ca44402ef76b"}],"examples":[{"updated-at":1561545860751,"created-at":1306270061000,"body":"(use '[clojure.java.io :only (as-url)])\n(import 'java.io.File)\n\nuser=> (as-url nil)\nnil\n\nuser=> (as-url (File. \"/tmp\"))\n#\n\nuser=> (as-url \"http://clojuredocs.org\")\n#\n\nuser=> (as-url \"http://clojuredocs.org:8080\")\n#\n\nuser=> (as-url \"clojuredocs.org\")\n#","editors":[{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/567898c496278341be69087507d5ed24?r=PG&default=identicon","account-source":"clojuredocs","login":"Jeff Rose"},"_id":"542692d0c026201cdc326ebc"},{"updated-at":1561545787852,"created-at":1561545787852,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"body":";; How to extend \"io/as-url\" or \"io/file\" to handle additional types,\n;; for example \"java.nio.file.Path\":\n\n(require '[clojure.java.io :as io])\n(import '[java.nio.file Path FileSystems])\n\n(extend-protocol io/Coercions\n Path\n (as-file [path] (io/file (.toUri path)))\n (as-url [path] (io/as-url (.toUri path))))\n\n(def path\n (.. FileSystems\n getDefault\n (getPath \"/usr\" \n (into-array String [\"share\" \"dict\" \"words\"]))))\n\n(io/as-url path)\n;; #object[java.net.URL 0x1255fa42 \"file:\"/usr/share/dict/words\"]\n\n(io/file path)\n;; #object[java.io.File 0x1c80a235 \"/usr/share/dict/words\"]","_id":"5d134c3be4b0ca44402ef76a"}],"notes":null,"tag":"java.net.URL","arglists":["x"],"doc":"Coerce argument to a URL.","library-url":"https://github.com/clojure/clojure","href":"/clojure.java.io/as-url"},{"added":"1.2","ns":"clojure.java.io","name":"reader","file":"clojure/java/io.clj","type":"function","column":1,"see-alsos":[{"created-at":1324516916000,"author":{"login":"cgray","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/7fe6255dbe4806a588cc06a5ba4a5d82?r=PG&default=identicon"},"to-var":{"ns":"clojure.java.io","name":"writer","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cce"},{"created-at":1329988254000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.java.io","name":"input-stream","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ccf"},{"created-at":1329988703000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.java.io","name":"IOFactory","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cd0"},{"created-at":1334796117000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.core","name":"slurp","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cd1"}],"line":89,"examples":[{"updated-at":1729694197703,"created-at":1290297729000,"body":"(with-open [rdr (clojure.java.io/reader \"/tmp/foo.txt\")]\n (into [] (line-seq rdr)))","editors":[{"login":"claj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/353113?v=4"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/d28543d134185d12d4006a74738d233e?r=PG&default=identicon","account-source":"clojuredocs","login":"steveminer"},"_id":"542692d0c026201cdc326eb8"},{"updated-at":1507915508004,"created-at":1324315042000,"body":"(with-open [rdr (clojure.java.io/reader \"http://www.google.com\")]\n (printf \"%s\\n\" (clojure.string/join \"\\n\" (line-seq rdr))))\n;; nil","editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3","account-source":"github","login":"jafingerhut"},"_id":"542692d6c026201cdc3270db"},{"updated-at":1561057591570,"created-at":1561057591570,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"body":";; Sometimes it's useful to create a reader from a string, but strings\n;; are locations for \"reader\", so we turn them into char-arrays first:\n\n(require '[clojure.java.io :as io])\n\n(with-open [r (io/reader (char-array \"hello\"))] (slurp r))\n;; \"hello\"","_id":"5d0bd937e4b0ca44402ef75a"}],"notes":[{"updated-at":1387185171000,"body":"Java documentation links for the listed argument types that have “default implementationsâ€�:\r\n\r\n* [`Reader`](http://docs.oracle.com/javase/7/docs/api/java/io/Reader.html)\r\n* [`BufferedReader`](http://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html)\r\n* [`InputStream`](http://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html)\r\n* [`File`](http://docs.oracle.com/javase/7/docs/api/java/io/File.html)\r\n* [`URI`](http://docs.oracle.com/javase/7/docs/api/java/net/URI.html)\r\n* [`URL`](http://docs.oracle.com/javase/7/docs/api/java/net/URL.html)\r\n* [`Socket`](http://docs.oracle.com/javase/7/docs/api/java/net/Socket.html)\r\n* byte arrays (`byte[]`)\r\n* character arrays (`char[]`)\r\n* [`String`](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html) (resolved as a URI or a local file name)","created-at":1387185171000,"author":{"login":"roryokane","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5b2b185c814bb25f2f95a1152e58f033?r=PG&default=identicon"},"_id":"542692edf6e94c6970522016"},{"author":{"login":"jakubholynet","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/624958?v=3"},"updated-at":1436102372053,"created-at":1436102372053,"body":"`opts` depend on the type of the reader but [common ones include](https://github.com/clojure/clojure/blob/cc69d19bd471c48d441071fff43e768ffa7eb8e5/src/clj/clojure/java/io.clj) `:encoding` and, where applicable, `:buffer-size`.","_id":"55992ee4e4b020189d740547"},{"author":{"login":"KingMob","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/946421?v=4"},"updated-at":1718020769924,"created-at":1718020769924,"body":"Warning, it does not work with `java.nio.file.Path` (as of 1.11.1).","_id":"6666eaa169fbcc0c226174d3"}],"tag":"java.io.Reader","arglists":["x & opts"],"doc":"Attempts to coerce its argument into an open java.io.Reader.\n Default implementations always return a java.io.BufferedReader.\n\n Default implementations are provided for Reader, BufferedReader,\n InputStream, File, URI, URL, Socket, byte arrays, character arrays,\n and String.\n\n If argument is a String, it tries to resolve it first as a URI, then\n as a local file name. URIs with a 'file' protocol are converted to\n local file names.\n\n Should be used inside with-open to ensure the Reader is properly\n closed.","library-url":"https://github.com/clojure/clojure","href":"/clojure.java.io/reader"},{"added":"1.2","ns":"clojure.java.javadoc","name":"javadoc","file":"clojure/java/javadoc.clj","type":"function","column":1,"see-alsos":[{"created-at":1332796364000,"author":{"login":"Olivenmann","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d5b1703fb08dd81e4cb2f653a3aaf10b?r=PG&default=identicon"},"to-var":{"ns":"clojure.repl","name":"doc","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cb0"},{"created-at":1619379527003,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/20086?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"*local-javadocs*","ns":"clojure.java.javadoc"},"_id":"6085c547e4b0b1e3652d74e8"},{"created-at":1619379537456,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/20086?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"*remote-javadocs*","ns":"clojure.java.javadoc"},"_id":"6085c551e4b0b1e3652d74e9"}],"line":92,"examples":[{"author":{"login":"abhin4v","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/4d29918c109bc75d2a1fd8420660d72b?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":"user=> (use 'clojure.java.javadoc)\nnil\n\nuser=> (javadoc String)\n\"http://java.sun.com/javase/6/docs/api/java/lang/String.html\"\n\nuser=> (javadoc (java.util.Date.))\n\"http://java.sun.com/javase/6/docs/api/java/util/Date.html\"\n","created-at":1283270938000,"updated-at":1285492232000,"_id":"542692d0c026201cdc326ebd"},{"author":{"login":"ryo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3f7913b563c72083c74030d928ba407e?r=PG&default=identicon"},"editors":[],"body":"user> (javadoc 1)\n\"http://java.sun.com/javase/7/docs/api/java/lang/Long.html\"\n\n(javadoc \"abc\")\n\"http://java.sun.com/javase/7/docs/api/java/lang/String.html\"","created-at":1397981916000,"updated-at":1397981916000,"_id":"542692d6c026201cdc3270e0"},{"author":{"login":"ryo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3f7913b563c72083c74030d928ba407e?r=PG&default=identicon"},"editors":[],"body":"user> (javadoc org.joda.time.DateTime)\n\"http://www.google.com/search?btnI=I%27m%20Feeling%20Lucky&q=allinurl:org/joda/time/DateTime.html\"","created-at":1397981945000,"updated-at":1397981945000,"_id":"542692d6c026201cdc3270e1"}],"notes":null,"arglists":["class-or-object"],"doc":"Opens a browser window displaying the javadoc for the argument.\n Tries *local-javadocs* first, then *remote-javadocs*.","library-url":"https://github.com/clojure/clojure","href":"/clojure.java.javadoc/javadoc"},{"added":"1.2","ns":"clojure.java.javadoc","name":"add-local-javadoc","file":"clojure/java/javadoc.clj","type":"function","column":1,"see-alsos":[{"created-at":1619379450941,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/20086?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"javadoc","ns":"clojure.java.javadoc"},"_id":"6085c4fae4b0b1e3652d74e6"},{"created-at":1619379489484,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/20086?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"*local-javadocs*","ns":"clojure.java.javadoc"},"_id":"6085c521e4b0b1e3652d74e7"}],"line":47,"examples":[{"updated-at":1619379433450,"created-at":1619379433450,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/20086?v=4"},"body":"(require '[clojure.java.javadoc :as javadoc])\n\n;; After extracting JDK 11 Javadocs into ~/javadocs/jdk11\n(javadoc/add-local-javadoc \n (str (System/getProperty \"user.home\")\n \"/javadocs/jdk11/api/java.base\"))\n\n;; Open default browser showing java.io.PrintStream\n(javadoc/javadoc System/out)\n","_id":"6085c4e9e4b0b1e3652d74e5"}],"notes":null,"arglists":["path"],"doc":"Adds to the list of local Javadoc paths.","library-url":"https://github.com/clojure/clojure","href":"/clojure.java.javadoc/add-local-javadoc"},{"ns":"clojure.java.javadoc","name":"*core-java-api*","file":"clojure/java/javadoc.clj","type":"var","column":1,"see-alsos":null,"dynamic":true,"line":21,"examples":null,"notes":[{"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/20086?v=4"},"updated-at":1619367585052,"created-at":1619367585052,"body":"Effectively read-only. `*core-java.api*` returns the JDK 7 version of Javadoc by default (unless you run Clojure with the JDK 6). This is the version of the documentation that the rest of `clojure.java.javadoc` uses for the Java core API.","_id":"608596a1e4b0b1e3652d74e4"}],"arglists":[],"library-url":"https://github.com/clojure/clojure","href":"/clojure.java.javadoc/*core-java-api*"},{"ns":"clojure.java.javadoc","name":"*feeling-lucky-url*","file":"clojure/java/javadoc.clj","type":"var","column":1,"see-alsos":[{"created-at":1534516213976,"author":{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"*feeling-lucky*","ns":"clojure.java.javadoc"},"_id":"5b76dbf5e4b00ac801ed9e67"}],"dynamic":true,"line":16,"examples":[{"updated-at":1534515944915,"created-at":1534515944915,"author":{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"},"body":";; If `clojure.java.javadoc/*feeling-lucky*` is true,\n;; clojure.java.javadoc/javadoc opens a browser with this URL if it can’t\n;; find the proper documentation URL (e.g. if it’s a custom class).\n\n;; Default value\n*feeling-lucky-url*\n; => \"http://www.google.com/search?btnI=I%27m%20Feeling%20Lucky&q=allinurl:\"\n\n;; Use DuckDuckGo instead of Google\n(binding [clojure.java.javadoc/*feeling-lucky-url* \"https://duckduckgo.com/?q=\\\\\"]\n (clojure.java.javadoc/javadoc your-class))","_id":"5b76dae8e4b00ac801ed9e65"}],"notes":null,"arglists":[],"library-url":"https://github.com/clojure/clojure","href":"/clojure.java.javadoc/*feeling-lucky-url*"},{"ns":"clojure.java.javadoc","name":"*local-javadocs*","file":"clojure/java/javadoc.clj","type":"var","column":1,"see-alsos":[{"created-at":1619365716926,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/20086?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"add-local-javadoc","ns":"clojure.java.javadoc"},"_id":"60858f54e4b0b1e3652d74e0"}],"dynamic":true,"line":19,"examples":[{"updated-at":1619365889369,"created-at":1619365824236,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/20086?v=4"},"body":"(require '[clojure.java.javadoc :as javadoc])\n\n;; Assuming \"~/javadocs/jdk11/api/java.base\" exists:\n\n(def jdk11-javadoc\n (str (System/getProperty \"user.home\")\n \"/javadocs/jdk11/api/java.base\"))\n\n;; Alter the local Javadoc folders for the current thread.\n;; Use javadoc/add-local-javadoc to alter permanently.\n;; Opens java.lang.Object.html for Java 11 instead of 7 (default).\n\n(binding [javadoc/*local-javadocs* (ref [jdk11-javadoc])]\n (javadoc/javadoc (Object.)))\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"}],"_id":"60858fc0e4b0b1e3652d74e1"}],"notes":null,"arglists":[],"library-url":"https://github.com/clojure/clojure","href":"/clojure.java.javadoc/*local-javadocs*"},{"added":"1.2","ns":"clojure.java.javadoc","name":"add-remote-javadoc","file":"clojure/java/javadoc.clj","type":"function","column":1,"see-alsos":[{"created-at":1561982333040,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"add-local-javadoc","ns":"clojure.java.javadoc"},"_id":"5d19f57de4b0ca44402ef77d"}],"line":53,"examples":[{"author":{"login":"linxiangyu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2c7492645426ece4ae86fde83d61bd03?r=PG&default=identicon"},"editors":[{"avatar-url":"https://avatars1.githubusercontent.com/u/109629?v=3","account-source":"github","login":"jafingerhut"}],"body":"user=> (use 'clojure.java.javadoc)\nnil\n\nuser=> (add-remote-javadoc \"org.apache.commons.csv.\"\n \"http://commons.apache.org/proper/commons-csv/apidocs/index.html\")\n{\"java.\" \"http://java.sun.com/javase/6/docs/api/\",\n \"javax.\" \"http://java.sun.com/javase/6/docs/api/\",\n \"org.apache.commons.codec.\" \"http://commons.apache.org/codec/api-release/\",\n \"org.apache.commons.csv.\" \"http://commons.apache.org/proper/commons-csv/apidocs/index.html\",\n \"org.apache.commons.io.\" \"http://commons.apache.org/io/api-release/\",\n \"org.apache.commons.lang.\" \"http://commons.apache.org/lang/api-release/\",\n \"org.ietf.jgss.\" \"http://java.sun.com/javase/6/docs/api/\",\n \"org.omg.\" \"http://java.sun.com/javase/6/docs/api/\",\n \"org.w3c.dom.\" \"http://java.sun.com/javase/6/docs/api/\",\n \"org.xml.sax.\" \"http://java.sun.com/javase/6/docs/api/\"}","created-at":1369812981000,"updated-at":1497949372886,"_id":"542692d6c026201cdc3270df"},{"updated-at":1561982312102,"created-at":1561982312102,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"body":";; Replace the JavaDoc URLs for the current JDK version.\n\n(require '[clojure.java.javadoc :as browse])\n\n(def java-version\n (let [jsv (System/getProperty \"java.specification.version\")]\n (if-let [single-digit (last (re-find #\"^\\d\\.(\\d+).*\" jsv))]\n single-digit jsv)))\n\n(def jdocs-template\n (format \"https://docs.oracle.com/javase/%s/docs/api/\" java-version))\n\n(def known-prefix\n [\"java.\" \"javax.\" \"org.ietf.jgss.\" \"org.omg.\"\n \"org.w3c.dom.\" \"org.xml.sax.\"])\n\n(doseq [prefix known-prefix]\n (browse/add-remote-javadoc prefix jdocs-template))","_id":"5d19f568e4b0ca44402ef77c"}],"notes":null,"arglists":["package-prefix url"],"doc":"Adds to the list of remote Javadoc URLs. package-prefix is the\n beginning of the package name that has docs at this URL.","library-url":"https://github.com/clojure/clojure","href":"/clojure.java.javadoc/add-remote-javadoc"},{"ns":"clojure.java.javadoc","name":"*remote-javadocs*","file":"clojure/java/javadoc.clj","type":"var","column":1,"see-alsos":[{"created-at":1619365573969,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/20086?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"add-remote-javadoc","ns":"clojure.java.javadoc"},"_id":"60858ec5e4b0b1e3652d74de"}],"dynamic":true,"line":33,"examples":[{"editors":[{"login":"reborg","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/20086?v=4"}],"body":"(require '[clojure.java.javadoc :as javadoc])\n\n(def clojure-javadoc\n \"https://javadoc.io/doc/org.clojure/clojure/latest/\")\n\n;; Altering the Javadoc remote locations for the current thread.\n;; Use javadoc/add-remote-javadoc to alter permanently.\n\n(binding [javadoc/*remote-javadocs*\n (ref {\"clojure.\" clojure-javadoc})]\n (javadoc/javadoc []))","author":{"avatar-url":"https://avatars.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"},"created-at":1619365561620,"updated-at":1619365626070,"_id":"60858eb9e4b0b1e3652d74dd"}],"notes":null,"arglists":[],"library-url":"https://github.com/clojure/clojure","href":"/clojure.java.javadoc/*remote-javadocs*"},{"ns":"clojure.java.javadoc","name":"*feeling-lucky*","file":"clojure/java/javadoc.clj","type":"var","column":1,"see-alsos":[{"created-at":1534516222829,"author":{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"*feeling-lucky-url*","ns":"clojure.java.javadoc"},"_id":"5b76dbfee4b00ac801ed9e68"}],"dynamic":true,"line":17,"examples":[{"updated-at":1534516142907,"created-at":1534516142907,"author":{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"},"body":";; If true, clojure.java.javadoc/javadoc opens a browser using\n;; *feeling-lucky-url* when it can’t find the proper documentation URL\n;; for a class.\n\n;; opens a browser with *feeling-lucky-url*\n(clojure.java.javadoc/javadoc inc)\n\n;; prints \"Could not find Javadoc for clojure.core$inc\"\n(binding [clojure.java.javadoc/*feeling-lucky* false] \n (clojure.java.javadoc/javadoc inc))","_id":"5b76dbaee4b00ac801ed9e66"}],"notes":null,"arglists":[],"library-url":"https://github.com/clojure/clojure","href":"/clojure.java.javadoc/*feeling-lucky*"},{"added":"1.12","ns":"clojure.java.process","name":"stderr","file":"clojure/java/process.clj","type":"function","column":1,"see-alsos":null,"line":108,"examples":null,"notes":null,"arglists":["process"],"doc":"Given a process, return the stderr of the external process (an InputStream)","library-url":"https://github.com/clojure/clojure","href":"/clojure.java.process/stderr"},{"added":"1.12","ns":"clojure.java.process","name":"from-file","file":"clojure/java/process.clj","type":"function","column":1,"see-alsos":null,"line":46,"examples":null,"notes":null,"arglists":["f"],"doc":"Coerce f to a file per clojure.java.io/file and return a ProcessBuilder.Redirect reading from the file.\n This can be passed to 'start' in :in.","library-url":"https://github.com/clojure/clojure","href":"/clojure.java.process/from-file"},{"added":"1.12","ns":"clojure.java.process","name":"stdout","file":"clojure/java/process.clj","type":"function","column":1,"see-alsos":null,"line":102,"examples":null,"notes":null,"arglists":["process"],"doc":"Given a process, return the stdout of the external process (an InputStream)","library-url":"https://github.com/clojure/clojure","href":"/clojure.java.process/stdout"},{"added":"1.12","ns":"clojure.java.process","name":"stdin","file":"clojure/java/process.clj","type":"function","column":1,"see-alsos":null,"line":96,"examples":null,"notes":null,"arglists":["process"],"doc":"Given a process, return the stdin of the external process (an OutputStream)","library-url":"https://github.com/clojure/clojure","href":"/clojure.java.process/stdin"},{"added":"1.12","ns":"clojure.java.process","name":"exit-ref","file":"clojure/java/process.clj","type":"function","column":1,"see-alsos":null,"line":114,"examples":null,"notes":null,"arglists":["process"],"doc":"Given a Process (the output of 'start'), return a reference that can be\n used to wait for process completion then returns the exit value.","library-url":"https://github.com/clojure/clojure","href":"/clojure.java.process/exit-ref"},{"added":"1.12","ns":"clojure.java.process","name":"exec","file":"clojure/java/process.clj","type":"function","column":1,"see-alsos":null,"line":163,"examples":null,"notes":null,"arglists":["& opts+args"],"doc":"Execute a command and on successful exit, return the captured output,\n else throw RuntimeException. Args are the same as 'start' and options\n if supplied override the default 'exec' settings.","library-url":"https://github.com/clojure/clojure","href":"/clojure.java.process/exec"},{"added":"1.12","ns":"clojure.java.process","name":"start","file":"clojure/java/process.clj","type":"function","column":1,"see-alsos":null,"line":53,"examples":null,"notes":null,"arglists":["& opts+args"],"doc":"Start an external command, defined in args.\n The process environment vars are inherited from the parent by\n default (use :clear-env to clear them).\n\n If needed, provide options in map as first arg:\n :in - a ProcessBuilder.Redirect (default = :pipe) or :inherit\n :out - a ProcessBuilder.Redirect (default = :pipe) or :inherit :discard\n :err - a ProcessBuilder.Redirect (default = :pipe) or :inherit :discard :stdout\n :dir - current directory when the process runs (default=\".\")\n :clear-env - if true, remove all inherited parent env vars\n :env - {env-var value} of environment variables to set (all strings)\n\n Returns the java.lang.Process.","library-url":"https://github.com/clojure/clojure","href":"/clojure.java.process/start"},{"added":"1.12","ns":"clojure.java.process","name":"to-file","file":"clojure/java/process.clj","type":"function","column":1,"see-alsos":null,"line":36,"examples":null,"notes":null,"arglists":["f & {:keys [append], :as opts}"],"doc":"Coerce f to a file per clojure.java.io/file and return a ProcessBuilder.Redirect writing to the file.\n Set ':append' in opts to append. This can be passed to 'start' in :out or :err.","library-url":"https://github.com/clojure/clojure","href":"/clojure.java.process/to-file"},{"ns":"clojure.java.process","name":"io-task","file":"clojure/java/process.clj","type":"function","skip-wiki":true,"column":1,"see-alsos":null,"line":142,"examples":null,"notes":null,"arglists":["f"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.java.process/io-task"},{"added":"1.2","ns":"clojure.java.shell","name":"sh","file":"clojure/java/shell.clj","type":"function","column":1,"see-alsos":[{"created-at":1332915179000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.java.shell","name":"with-sh-dir","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e1b"},{"created-at":1332915183000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.java.shell","name":"with-sh-env","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e1c"},{"created-at":1336536810000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.core","name":"future","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e1d"},{"created-at":1661552183304,"author":{"login":"djblue","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1986211?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"shutdown-agents","ns":"clojure.core"},"_id":"63094637e4b0b1e3652d765c"}],"line":79,"examples":[{"author":{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},"editors":[{"login":"juergenhoetzel","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2736dfffc803c704dcf25b45ff63cede?r=PG&default=identicon"},{"login":"Chouser","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/7a0192050ed6488670acfd3f59405c10?r=PG&default=identicon"},{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":"user=> (use '[clojure.java.shell :only [sh]])\n\n;; Note: The actual output you see from a command like this will look messier.\n;; The output below has had all newline characters replaced with line\n;; breaks. You would see a big long string with \\n characters in the middle.\nuser=> (sh \"ls\" \"-aul\")\n\n{:exit 0, \n :out \"total 64\ndrwxr-xr-x 11 zkim staff 374 Jul 5 13:21 .\ndrwxr-xr-x 25 zkim staff 850 Jul 5 13:02 ..\ndrwxr-xr-x 12 zkim staff 408 Jul 5 13:02 .git\n-rw-r--r-- 1 zkim staff 13 Jul 5 13:02 .gitignore\n-rw-r--r-- 1 zkim staff 12638 Jul 5 13:02 LICENSE.html\n-rw-r--r-- 1 zkim staff 4092 Jul 5 13:02 README.md\ndrwxr-xr-x 2 zkim staff 68 Jul 5 13:15 classes\ndrwxr-xr-x 5 zkim staff 170 Jul 5 13:15 lib\n-rw-r--r--@ 1 zkim staff 3396 Jul 5 13:03 pom.xml\n-rw-r--r--@ 1 zkim staff 367 Jul 5 13:15 project.clj\ndrwxr-xr-x 4 zkim staff 136 Jul 5 13:15 src\n\", :err \"\"}","created-at":1278383022000,"updated-at":1332916119000,"_id":"542692d0c026201cdc326ebf"},{"author":{"login":"secondplanet","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/6c3417477c007600db59c4a94718ee43?r=PG&default=identicon"},"editors":[],"body":"user=> (use '[clojure.java.shell :only [sh]])\n\nuser=> (println (:out (sh \"cowsay\" \"Printing a command-line output\")))\n\n _________________________________ \n< Printing a command-line output. >\n --------------------------------- \n \\ ^__^\n \\ (oo)\\_______\n (__)\\ )\\/\\\n ||----w |\n || ||\n\nnil","created-at":1313622736000,"updated-at":1313622736000,"_id":"542692d0c026201cdc326ec4"},{"author":{"login":"franks42","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/b3ee701dd6c481e5d310467ddfe62c48?r=PG&default=identicon"},"editors":[{"login":"franks42","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/b3ee701dd6c481e5d310467ddfe62c48?r=PG&default=identicon"},{"login":"franks42","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/b3ee701dd6c481e5d310467ddfe62c48?r=PG&default=identicon"},{"login":"franks42","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/b3ee701dd6c481e5d310467ddfe62c48?r=PG&default=identicon"},{"login":"franks42","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/b3ee701dd6c481e5d310467ddfe62c48?r=PG&default=identicon"}],"body":"user=> (use '[clojure.java.shell :only [sh]])\nnil\n\n;; note that the options, like :in, have to go at the end of arglist\n;; advantage of piping-in thru stdin is less need for quoting/escaping\nuser=> (println (:out (sh \"cat\" \"-\" :in \"Printing input from stdin with funny chars like ' \\\" $@ & \")))\nPrinting input from stdin with funny chars like ' \" $@ & \nnil","created-at":1331269027000,"updated-at":1331270505000,"_id":"542692d6c026201cdc3270e2"},{"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":";; sh is implemented using Clojure futures. See examples for 'future'\n;; for discussion of an undesirable 1-minute wait that can occur before\n;; your standalone Clojure program exits if you do not use shutdown-agents.","created-at":1336536805000,"updated-at":1336536828000,"_id":"542692d6c026201cdc3270e7"},{"author":{"login":"octopusgrabbus","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/fd31b8bcea99fa7b0711fbc424587774?r=PG&default=identicon"},"editors":[],"body":"(sh \"pwd\" :dir \"/home/ics/icsdev\")\n{:exit 0, :out \"/home/ics/icsdev\\n\", :err \"\"}","created-at":1398214606000,"updated-at":1398214606000,"_id":"542692d6c026201cdc3270e9"},{"author":{"login":"octopusgrabbus","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/fd31b8bcea99fa7b0711fbc424587774?r=PG&default=identicon"},"editors":[],"body":"(require '[clojure.java.shell :as shell])\n(shell/sh \"sh\" \"-c\" \"cd /etc; pwd\")\n{:exit 0, :out \"/etc\\n\", :err \"\"}","created-at":1398221530000,"updated-at":1398221530000,"_id":"542692d6c026201cdc3270ea"},{"updated-at":1510403291191,"created-at":1510403291191,"author":{"login":"Atsman","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/3405704?v=4"},"body":";; note that you have to split you script by whitespace \n;; that was confusing for me \n;; for example script: \n;; \"terraform plan -var param1=value1 -var param2=value2 -var-file=/etc/var.tfvars\"\n\n(shell/sh \"terraform\" \"plan\" \"-var\" \"param=value\" \"-var\" \"param2=value2\" \"-var-file=/etc/var.tfvars\")","_id":"5a06ecdbe4b0a08026c48cae"},{"updated-at":1539183276794,"created-at":1539183276794,"author":{"login":"claj","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/353113?v=4"},"body":";; feed the sh with environment variables\n;; (note that $HELLO in our command line wouldn't work since we act as the shell here)\n\n(require '[clojure.java.shell :as shell])\n(shell/sh \"printenv\" \"HELLO\" :env {\"HELLO\" \"Hello, World!\"})\n{:exit 0, :out \"Hello, World!\\n\", :err \"\"}\n\n","_id":"5bbe12ace4b00ac801ed9ece"},{"updated-at":1539186762145,"created-at":1539186710931,"author":{"login":"claj","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/353113?v=4"},"body":";; override environment variables\n;; BAD EXAMPLE since i guess lein uses a lot of env vars for coordination\n;; but anyway\n\n(require '[clojure.java.shell :as shell])\n\n(sh/sh \"lein\" \"compile\")\n{:exit 0,\n :out\n \"WARNING: You have $CLASSPATH set, probably by accident.\n It is strongly recommended to unset this before proceeding.\",\n :err \"\"}\n\n;; note that\n(sh/sh \"lein\" \"compile\" :env {})\n;; will make lein quite confused.\n\n;; we better modify the current env:\n\n(let [current-env (into {} (System/getenv))]\n (sh/sh \"lein\" \"compile\" :env (dissoc current-env \"CLASSPATH\"))\n{:exit 0, :out \"\", :err \"\"}\n\n\n;; (into {} ...) is needed because System/getenv returns a map of type\n;; java.util.Collections$UnmodifiableMap","editors":[{"avatar-url":"https://avatars1.githubusercontent.com/u/353113?v=4","account-source":"github","login":"claj"}],"_id":"5bbe2016e4b00ac801ed9ecf"},{"updated-at":1618300543742,"created-at":1618300543742,"author":{"login":"Saikyun","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2477927?v=4"},"body":";; on windows, the above examples won't work. try with an exe instead :)\n(require '[clojure.java.shell :as shell])\n(shell/sh \"notepad.exe\")\n;; now notepad should be open!","_id":"60754e7fe4b0b1e3652d74c5"},{"editors":[{"login":"Crowbrammer","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/19522656?v=4"}],"body":";; On Windows, the Java shell needs to execute a program \n;; that executes the command: usually PowerShell, Bash, or cmd. \n\n;; So your `sh` function should invoke \"powershell\" OR \"bash\" and -c\" \n;; OR \"cmd and \"/c\" before your command. \n\n;; Instead of \n(clojure.java.shell/sh \"ls\")\n\n;; you would do this\n\n(clojure.java.shell/sh \"powershell\" \"ls\")\n\n;; or this\n\n(clojure.java.shell/sh \"bash\" \"-c\" \"ls\")\n\n;; or this\n\n(clojure.java.shell/sh \"cmd\" \"/c\" \"dir\") ;; No `ls` or `pwd` in cmd. \n\n;; (I first learned about the need for command flags like \"/c\" here: \n;; https://stackoverflow.com/a/4031412/2596132\n\n;; These Microsoft docs explain the \"/c\" flag: \n;; https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/cmd\n\n;; I learned of bash's \"-c\" flag after finding `exec` in `bash -c help` as suggested\n;; from `bash --help. I didn't know that `-c` was the command flag at the time.)","author":{"avatar-url":"https://avatars.githubusercontent.com/u/19522656?v=4","account-source":"github","login":"Crowbrammer"},"created-at":1673135391810,"updated-at":1673136173848,"_id":"63ba051fe4b08cf8563f4b5e"},{"updated-at":1724316597380,"created-at":1724316597380,"author":{"login":"avocade","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8943?v=4"},"body":";; To use pipes and whatnot, a simple way is to run eg `bash -c` as the command\n;; and the rest as a single string\n(clojure.java.shell/sh \"/bin/bash\" \"-c\" \"ls -la | grep foo\")","_id":"66c6fbb569fbcc0c226174f0"}],"notes":[{"author":{"login":"ejschoen","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/10605666?v=3"},"updated-at":1493923269271,"created-at":1493923269271,"body":"It's worth noting that sh begins interpreting arguments starting with the first non-string (not just keywords!) as key-value pairs, as in the example above with pwd. This means that even if an argument's type has a trivial conversion to a string, such as an integer or boolean, it must be stringified. If not, it'll be passed as an argument to hash-map, and you might see an IllegalArgumentException if there are an odd number of arguments beginning with the first non-string.","_id":"590b75c5e4b01f4add58feab"},{"author":{"login":"geokon-gh","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/21017379?v=4"},"updated-at":1550146015552,"created-at":1550146015552,"body":"As noted in the [4th example](http://clojuredocs.org/clojure.java.shell/sh#example-542692d6c026201cdc3270e7), `sh` uses futures. This means that if your program uses `sh` and then finishes its execution it will unexpectedly hang and not terminate/exit. The `sh` future will still be alive in the background and will be holding up the program. \n\nThis is a bit confusing when you first try to use Clojure for scripting as it looks like your script doesn't exit naturally. Furthermore, when you run `sh` in the REPL the background futures aren't apparent to the user and everything works as-expected\n\nTo fix the situation you can either run `(System/exit 0)` to terminate your program explicitly. Or you can run `(shutdown-agents)` to kill the background future and then the program will exit naturally\n\nFor a discussion of this strange behavior see: https://clojureverse.org/t/why-doesnt-my-program-exit/3754/2","_id":"5c6559dfe4b0ca44402ef684"}],"arglists":["& args"],"doc":"Passes the given strings to Runtime.exec() to launch a sub-process.\n\n Options are\n\n :in may be given followed by any legal input source for\n clojure.java.io/copy, e.g. InputStream, Reader, File, byte[],\n or String, to be fed to the sub-process's stdin.\n :in-enc option may be given followed by a String, used as a character\n encoding name (for example \"UTF-8\" or \"ISO-8859-1\") to\n convert the input string specified by the :in option to the\n sub-process's stdin. Defaults to UTF-8.\n If the :in option provides a byte array, then the bytes are passed\n unencoded, and this option is ignored.\n :out-enc option may be given followed by :bytes or a String. If a\n String is given, it will be used as a character encoding\n name (for example \"UTF-8\" or \"ISO-8859-1\") to convert\n the sub-process's stdout to a String which is returned.\n If :bytes is given, the sub-process's stdout will be stored\n in a byte array and returned. Defaults to UTF-8.\n :env override the process env with a map (or the underlying Java\n String[] if you are a masochist).\n :dir override the process dir with a String or java.io.File.\n\n You can bind :env or :dir for multiple operations using with-sh-env\n and with-sh-dir.\n\n sh returns a map of\n :exit => sub-process's exit code\n :out => sub-process's stdout (as byte[] or String)\n :err => sub-process's stderr (String via platform default encoding)","library-url":"https://github.com/clojure/clojure","href":"/clojure.java.shell/sh"},{"ns":"clojure.java.shell","name":"*sh-dir*","file":"clojure/java/shell.clj","type":"var","column":1,"see-alsos":null,"dynamic":true,"line":18,"examples":null,"notes":null,"arglists":[],"library-url":"https://github.com/clojure/clojure","href":"/clojure.java.shell/*sh-dir*"},{"added":"1.2","ns":"clojure.java.shell","name":"with-sh-dir","file":"clojure/java/shell.clj","type":"macro","column":1,"see-alsos":[{"created-at":1332915149000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.java.shell","name":"sh","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f48"}],"line":21,"examples":[{"updated-at":1560006443938,"created-at":1560006443938,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"body":"(require '[clojure.java.shell :as shell :refer [sh]])\n\n(shell/with-sh-dir \"/usr/share\"\n (sh \"pwd\"))\n\n;; {:exit 0, :out \"/usr/share\\n\", :err \"\"}\n","_id":"5cfbcf2be4b0ca44402ef751"}],"macro":true,"notes":null,"arglists":["dir & forms"],"doc":"Sets the directory for use with sh, see sh for details.","library-url":"https://github.com/clojure/clojure","href":"/clojure.java.shell/with-sh-dir"},{"ns":"clojure.java.shell","name":"*sh-env*","file":"clojure/java/shell.clj","type":"var","column":1,"see-alsos":null,"dynamic":true,"line":19,"examples":null,"notes":null,"arglists":[],"library-url":"https://github.com/clojure/clojure","href":"/clojure.java.shell/*sh-env*"},{"added":"1.2","ns":"clojure.java.shell","name":"with-sh-env","file":"clojure/java/shell.clj","type":"macro","column":1,"see-alsos":[{"created-at":1332915161000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.java.shell","name":"sh","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f58"}],"line":28,"examples":[{"updated-at":1560006506866,"created-at":1560006506866,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"body":"(require '[clojure.java.shell :as shell :refer [sh]])\n\n(shell/with-sh-env {:debug \"true\"}\n (sh \"env\"))\n\n;; {:exit 0, :out \"debug=true\\n\", :err \"\"}\n","_id":"5cfbcf6ae4b0ca44402ef752"}],"macro":true,"notes":null,"arglists":["env & forms"],"doc":"Sets the environment for use with sh, see sh for details.","library-url":"https://github.com/clojure/clojure","href":"/clojure.java.shell/with-sh-env"},{"ns":"clojure.main","name":"main","file":"clojure/main.clj","type":"function","column":1,"see-alsos":null,"line":617,"examples":[{"body":"java -cp clojure-1.6.0.jar clojure.main hey.clj","author":{"login":"ganeshskm","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2527539?v=3"},"created-at":1418110038171,"updated-at":1418110038171,"_id":"5486a456e4b04e93c519ff9f"}],"notes":null,"arglists":["& args"],"doc":"Usage: java -cp clojure.jar clojure.main [init-opt*] [main-opt] [arg*]\n\n With no options or args, runs an interactive Read-Eval-Print Loop\n\n init options:\n -i, --init path Load a file or resource\n -e, --eval string Evaluate expressions in string; print non-nil values\n --report target Report uncaught exception to \"file\" (default), \"stderr\",\n or \"none\", overrides System property clojure.main.report\n\n main options:\n -m, --main ns-name Call the -main function from a namespace with args\n -r, --repl Run a repl\n path Run a script from a file or resource\n - Run a script from standard input\n -h, -?, --help Print this help message and exit\n\n operation:\n\n - Establishes thread-local bindings for commonly set!-able vars\n - Enters the user namespace\n - Binds *command-line-args* to a seq of strings containing command line\n args that appear after any main option\n - Runs all init options in order\n - Calls a -main function or runs a repl or script if requested\n\n The init options may be repeated and mixed freely, but must appear before\n any main option. The appearance of any eval option before running a repl\n suppresses the usual repl greeting message: \"Clojure ~(clojure-version)\".\n\n Paths may be absolute or relative in the filesystem or relative to\n classpath. Classpath-relative paths have prefix of @ or @/","library-url":"https://github.com/clojure/clojure","href":"/clojure.main/main"},{"ns":"clojure.main","name":"with-bindings","file":"clojure/main.clj","type":"macro","column":1,"see-alsos":[{"created-at":1374149313000,"author":{"login":"alilee","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2fb0196dc5a7cd3a5cc73f1b9941c209?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"binding","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521a83"},{"created-at":1374149334000,"author":{"login":"alilee","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2fb0196dc5a7cd3a5cc73f1b9941c209?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"with-local-vars","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521a84"},{"created-at":1374149343000,"author":{"login":"alilee","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2fb0196dc5a7cd3a5cc73f1b9941c209?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"with-redefs-fn","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521a85"}],"line":76,"examples":null,"macro":true,"notes":null,"arglists":["& body"],"doc":"Executes body in the context of thread-local bindings for several vars\n that often need to be set!: *ns* *warn-on-reflection* *math-context*\n *print-meta* *print-length* *print-level* *compile-path*\n *command-line-args* *1 *2 *3 *e","library-url":"https://github.com/clojure/clojure","href":"/clojure.main/with-bindings"},{"added":"1.3","ns":"clojure.main","name":"stack-element-str","file":"clojure/main.clj","type":"function","column":1,"see-alsos":null,"line":62,"examples":null,"notes":null,"arglists":["el"],"doc":"Returns a (possibly unmunged) string representation of a StackTraceElement","library-url":"https://github.com/clojure/clojure","href":"/clojure.main/stack-element-str"},{"ns":"clojure.main","name":"repl-caught","file":"clojure/main.clj","type":"function","column":1,"see-alsos":null,"line":347,"examples":null,"notes":null,"arglists":["e"],"doc":"Default :caught hook for repl","library-url":"https://github.com/clojure/clojure","href":"/clojure.main/repl-caught"},{"ns":"clojure.main","name":"repl-exception","file":"clojure/main.clj","type":"function","column":1,"see-alsos":null,"line":171,"examples":null,"notes":null,"arglists":["throwable"],"doc":"Returns the root cause of throwables","library-url":"https://github.com/clojure/clojure","href":"/clojure.main/repl-exception"},{"ns":"clojure.main","name":"err->msg","file":"clojure/main.clj","type":"function","column":1,"see-alsos":null,"line":342,"examples":null,"notes":null,"arglists":["e"],"doc":"Helper to return an error message string from an exception.","library-url":"https://github.com/clojure/clojure","href":"/clojure.main/err->msg"},{"ns":"clojure.main","name":"repl-read","file":"clojure/main.clj","type":"function","column":1,"see-alsos":null,"line":153,"examples":null,"notes":null,"arglists":["request-prompt request-exit"],"doc":"Default :read hook for repl. Reads from *in* which must either be an\n instance of LineNumberingPushbackReader or duplicate its behavior of both\n supporting .unread and collapsing all of CR, LF, and CRLF into a single\n \\newline. repl-read:\n - skips whitespace, then\n - returns request-prompt on start of line, or\n - returns request-exit on end of stream, or\n - reads an object from the input stream, then\n - skips the next input character if it's end of line, then\n - returns the object.","library-url":"https://github.com/clojure/clojure","href":"/clojure.main/repl-read"},{"ns":"clojure.main","name":"load-script","file":"clojure/main.clj","type":"function","column":1,"see-alsos":[{"created-at":1422652999747,"author":{"login":"delonnewman","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10404?v=2"},"to-var":{"ns":"clojure.core","name":"read-string","library-url":"https://github.com/clojure/clojure"},"_id":"54cbf647e4b0e2ac61831cee"},{"created-at":1422653011235,"author":{"login":"delonnewman","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10404?v=2"},"to-var":{"ns":"clojure.edn","name":"read-string","library-url":"https://github.com/clojure/clojure"},"_id":"54cbf653e4b081e022073c3c"}],"line":469,"examples":[{"body":";; In file /some/path/to-script.clj\n;; (ns test)\n;; \n;; (defn greet [name]\n;; (str \"Hello \" name))\n\n;; from repl\nuser=> (clojure.main/load-script \"/some/path/to-script.clj\")\n#'test/greet\nuser=> (greet \"Peter\")\n\"Hello Peter\"\n\n;; to load hello.clj from current directory\nuser=> (clojure.main/load-script \"hello.clj\")\n\n;; to load some-code.clj from class path\nuser=> (clojure.main/load-script \"@some-code.clj\")\n","author":{"login":"delonnewman","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10404?v=2"},"created-at":1422652901571,"updated-at":1422652901571,"_id":"54cbf5e5e4b0e2ac61831ced"}],"notes":null,"arglists":["path"],"doc":"Loads Clojure source from a file or resource given its path. Paths\n beginning with @ or @/ are considered relative to classpath.","library-url":"https://github.com/clojure/clojure","href":"/clojure.main/load-script"},{"ns":"clojure.main","name":"skip-if-eol","file":"clojure/main.clj","type":"function","column":1,"see-alsos":null,"line":107,"examples":null,"notes":null,"arglists":["s"],"doc":"If the next character on stream s is a newline, skips it, otherwise\n leaves the stream untouched. Returns :line-start, :stream-end, or :body\n to indicate the relative location of the next character on s. The stream\n must either be an instance of LineNumberingPushbackReader or duplicate\n its behavior of both supporting .unread and collapsing all of CR, LF, and\n CRLF to a single \\newline.","library-url":"https://github.com/clojure/clojure","href":"/clojure.main/skip-if-eol"},{"ns":"clojure.main","name":"skip-whitespace","file":"clojure/main.clj","type":"function","column":1,"see-alsos":null,"line":121,"examples":[{"editors":[{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"}],"body":";; Use while reading characters from a LineNumberingPushbackReader\n;; to jump to the next available \":body\", skipping whites spaces \n;; line starts, comment lines, until \":stream-end\".\n\n(require '[clojure.main :as main])\n\n(defn string-reader [s] \n (-> (java.io.StringReader. s)\n (clojure.lang.LineNumberingPushbackReader.)))\n\n(def r \n (string-reader \n \" A\\n B\\n; comment\\n C\"))\n\n(char (.read r)) ;; \\space\n(main/skip-whitespace r) ;; :body\n(char (.read r)) ;; \\A\n(main/skip-whitespace r) ;; :line-start\n(main/skip-whitespace r) ;; :body\n(char (.read r)) ;; \\B\n(main/skip-whitespace r) ;; :line-start\n(main/skip-whitespace r) ;; :line-start\n(main/skip-whitespace r) ;; :body\n(char (.read r)) ;; \\C\n(main/skip-whitespace r) ;; :stream-end","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"},"created-at":1559643650513,"updated-at":1559647605018,"_id":"5cf64602e4b0ca44402ef749"}],"notes":null,"arglists":["s"],"doc":"Skips whitespace characters on stream s. Returns :line-start, :stream-end,\n or :body to indicate the relative location of the next character on s.\n Interprets comma as whitespace and semicolon as comment to end of line.\n Does not interpret #! as comment to end of line because only one\n character of lookahead is available. The stream must either be an\n instance of LineNumberingPushbackReader or duplicate its behavior of both\n supporting .unread and collapsing all of CR, LF, and CRLF to a single\n \\newline.","library-url":"https://github.com/clojure/clojure","href":"/clojure.main/skip-whitespace"},{"ns":"clojure.main","name":"report-error","file":"clojure/main.clj","type":"function","column":1,"see-alsos":null,"line":585,"examples":null,"notes":null,"arglists":["t & {:keys [target], :or {target \"file\"}, :as opts}"],"doc":"Create and output an exception report for a Throwable to target.\n\n Options:\n :target - \"file\" (default), \"stderr\", \"none\"\n\n If file is specified but cannot be written, falls back to stderr.","library-url":"https://github.com/clojure/clojure","href":"/clojure.main/report-error"},{"added":"1.3","ns":"clojure.main","name":"root-cause","file":"clojure/main.clj","type":"function","column":1,"see-alsos":null,"line":35,"examples":null,"notes":null,"arglists":["t"],"doc":"Returns the initial cause of an exception or error by peeling off all of\n its wrappers","library-url":"https://github.com/clojure/clojure","href":"/clojure.main/root-cause"},{"ns":"clojure.main","name":"repl-requires","file":"clojure/main.clj","type":"var","column":1,"see-alsos":null,"line":354,"examples":null,"notes":null,"arglists":[],"doc":"A sequence of lib specs that are applied to `require`\nby default when a new command-line REPL is started.","library-url":"https://github.com/clojure/clojure","href":"/clojure.main/repl-requires"},{"added":"1.3","ns":"clojure.main","name":"demunge","file":"clojure/main.clj","type":"function","column":1,"see-alsos":null,"line":28,"examples":[{"author":{"login":"Claj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5fd658a8d2ef549071cb5286b1b874aa?r=PG&default=identicon"},"editors":[],"body":"(use 'clojure.main)\n\n(demunge \"clojure.core$println\")\n=>\"clojure.core/println\"","created-at":1325041264000,"updated-at":1325041264000,"_id":"542692d6c026201cdc3270eb"}],"notes":null,"arglists":["fn-name"],"doc":"Given a string representation of a fn class,\n as in a stack trace element, returns a readable version.","library-url":"https://github.com/clojure/clojure","href":"/clojure.main/demunge"},{"ns":"clojure.main","name":"with-read-known","file":"clojure/main.clj","type":"macro","column":1,"see-alsos":null,"line":361,"examples":null,"macro":true,"notes":null,"arglists":["& body"],"doc":"Evaluates body with *read-eval* set to a \"known\" value,\n i.e. substituting true for :unknown if necessary.","library-url":"https://github.com/clojure/clojure","href":"/clojure.main/with-read-known"},{"added":"1.10","ns":"clojure.main","name":"ex-str","file":"clojure/main.clj","type":"function","column":1,"see-alsos":null,"line":268,"examples":null,"notes":null,"arglists":["{:clojure.error/keys [phase source path line column symbol class cause spec], :as triage-data}"],"doc":"Returns a string from exception data, as produced by ex-triage.\n The first line summarizes the exception phase and location.\n The subsequent lines describe the cause.","library-url":"https://github.com/clojure/clojure","href":"/clojure.main/ex-str"},{"added":"1.10","ns":"clojure.main","name":"renumbering-read","file":"clojure/main.clj","type":"function","column":1,"see-alsos":null,"line":139,"examples":null,"notes":null,"arglists":["opts reader line-number"],"doc":"Reads from reader, which must be a LineNumberingPushbackReader, while capturing\n the read string. If the read is successful, reset the line number and re-read.\n The line number on re-read is the passed line-number unless :line or\n :clojure.core/eval-file meta are explicitly set on the read value.","library-url":"https://github.com/clojure/clojure","href":"/clojure.main/renumbering-read"},{"ns":"clojure.main","name":"repl","file":"clojure/main.clj","type":"function","column":1,"see-alsos":null,"line":368,"examples":[{"updated-at":1559663740765,"created-at":1559663133898,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"body":";; Create a REPL for a small toy language. A simple calculator \n;; evaluates the 4 arithmetic operators with infix notation.\n\n(require '[clojure.main :as main])\n\n(def repl-options\n [:prompt #(printf \"enter expression :> \")\n :read (fn [request-prompt request-exit]\n (or ({:line-start request-prompt :stream-end request-exit}\n (main/skip-whitespace *in*))\n (re-find #\"^(\\d+)([\\+\\-\\*\\/])(\\d+)$\" (read-line))))\n :eval (fn [[_ x op y]]\n (({\"+\" + \"-\" - \"*\" * \"/\" /} op)\n (Integer. x)\n (Integer. y)))])\n\n;; This enters a new REPL loop that shows a new prompt.\n;; Type ctrl+d to exit the nested REPL and go back to normal.\n(apply main/repl repl-options)\n\n;; An example interaction:\n;; enter expression :> 2*3\n;; 6\n\n\n","editors":[{"avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"}],"_id":"5cf6921de4b0ca44402ef74d"}],"notes":null,"arglists":["& options"],"doc":"Generic, reusable, read-eval-print loop. By default, reads from *in*,\n writes to *out*, and prints exception summaries to *err*. If you use the\n default :read hook, *in* must either be an instance of\n LineNumberingPushbackReader or duplicate its behavior of both supporting\n .unread and collapsing CR, LF, and CRLF into a single \\newline. Options\n are sequential keyword-value pairs. Available options and their defaults:\n\n - :init, function of no arguments, initialization hook called with\n bindings for set!-able vars in place.\n default: #()\n\n - :need-prompt, function of no arguments, called before each\n read-eval-print except the first, the user will be prompted if it\n returns true.\n default: (if (instance? LineNumberingPushbackReader *in*)\n #(.atLineStart *in*)\n #(identity true))\n\n - :prompt, function of no arguments, prompts for more input.\n default: repl-prompt\n\n - :flush, function of no arguments, flushes output\n default: flush\n\n - :read, function of two arguments, reads from *in*:\n - returns its first argument to request a fresh prompt\n - depending on need-prompt, this may cause the repl to prompt\n before reading again\n - returns its second argument to request an exit from the repl\n - else returns the next object read from the input stream\n default: repl-read\n\n - :eval, function of one argument, returns the evaluation of its\n argument\n default: eval\n\n - :print, function of one argument, prints its argument to the output\n default: prn\n\n - :caught, function of one argument, a throwable, called when\n read, eval, or print throws an exception or error\n default: repl-caught","library-url":"https://github.com/clojure/clojure","href":"/clojure.main/repl"},{"ns":"clojure.main","name":"repl-prompt","file":"clojure/main.clj","type":"function","column":1,"see-alsos":null,"line":102,"examples":null,"notes":null,"arglists":[""],"doc":"Default :prompt hook for repl","library-url":"https://github.com/clojure/clojure","href":"/clojure.main/repl-prompt"},{"added":"1.10","ns":"clojure.main","name":"ex-triage","file":"clojure/main.clj","type":"function","column":1,"see-alsos":null,"line":207,"examples":null,"notes":null,"arglists":["datafied-throwable"],"doc":"Returns an analysis of the phase, error, cause, and location of an error that occurred\n based on Throwable data, as returned by Throwable->map. All attributes other than phase\n are optional:\n :clojure.error/phase - keyword phase indicator, one of:\n :read-source :compile-syntax-check :compilation :macro-syntax-check :macroexpansion\n :execution :read-eval-result :print-eval-result\n :clojure.error/source - file name (no path)\n :clojure.error/path - source path\n :clojure.error/line - integer line number\n :clojure.error/column - integer column number\n :clojure.error/symbol - symbol being expanded/compiled/invoked\n :clojure.error/class - cause exception class symbol\n :clojure.error/cause - cause exception message\n :clojure.error/spec - explain-data for spec error","library-url":"https://github.com/clojure/clojure","href":"/clojure.main/ex-triage"},{"added":"1.11","ns":"clojure.math","name":"next-after","file":"clojure/math.clj","type":"function","column":1,"see-alsos":[{"created-at":1699545541284,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"next-up","ns":"clojure.math"},"_id":"654d01c569fbcc0c22617435"},{"created-at":1699545546664,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"next-down","ns":"clojure.math"},"_id":"654d01ca69fbcc0c22617436"}],"line":469,"examples":[{"updated-at":1699545532554,"created-at":1699545532554,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":";; The frequency of \"strange\" numbers increases as we get bigger.\n;; The strangeness is a consequence of using binary to store decimal numbers…\n\n(take 20 (iterate #(math/next-after % 6.0) 5.0))\n;; => (5.0\n;; 5.000000000000001\n;; 5.000000000000002\n;; 5.000000000000003\n;; 5.0000000000000036 ; <- strange\n;; 5.000000000000004\n;; 5.000000000000005\n;; 5.000000000000006\n;; 5.000000000000007\n;; 5.000000000000008\n;; 5.000000000000009\n;; 5.00000000000001\n;; 5.000000000000011\n;; 5.0000000000000115 ; <- strange\n;; 5.000000000000012\n;; 5.000000000000013\n;; 5.000000000000014\n;; 5.000000000000015\n;; 5.000000000000016\n;; 5.000000000000017)\n\n(take 20 (iterate #(math/next-after % 6.0) 5.0e200))\n;; => (5.0E200\n;; 4.9999999999999995E200 ; <- strange\n;; 4.999999999999999E200\n;; 4.999999999999998E200\n;; 4.9999999999999975E200 ; <- strange\n;; 4.999999999999997E200\n;; 4.999999999999996E200\n;; 4.9999999999999954E200 ; <- strange\n;; 4.999999999999995E200\n;; 4.999999999999994E200\n;; 4.9999999999999934E200 ; <- strange\n;; 4.999999999999993E200\n;; 4.999999999999992E200\n;; 4.9999999999999914E200 ; <- strange\n;; 4.999999999999991E200\n;; 4.99999999999999E200\n;; 4.999999999999989E200\n;; 4.9999999999999886E200 ; <- strange\n;; 4.999999999999988E200\n;; 4.999999999999987E200)","_id":"654d01bc69fbcc0c22617434"}],"notes":null,"arglists":["start direction"],"doc":"Returns the adjacent floating point number to start in the direction of\n the second argument. If the arguments are equal, the second is returned.\n If either arg is #NaN => #NaN\n If both arguments are signed zeros => direction\n If start is +-Double/MIN_VALUE and direction would cause a smaller magnitude\n => zero with sign matching start\n If start is ##Inf or ##-Inf and direction would cause a smaller magnitude\n => Double/MAX_VALUE with same sign as start\n If start is equal to +=Double/MAX_VALUE and direction would cause a larger magnitude\n => ##Inf or ##-Inf with sign matching start\n See: https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#nextAfter-double-double-","library-url":"https://github.com/clojure/clojure","href":"/clojure.math/next-after"},{"added":"1.11","ns":"clojure.math","name":"to-radians","file":"clojure/math.clj","type":"function","column":1,"see-alsos":[{"created-at":1701708988952,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"to-degrees","ns":"clojure.math"},"_id":"656e04bc69fbcc0c22617477"}],"line":106,"examples":[{"updated-at":1701708976644,"created-at":1701708976644,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":"(== math/PI (math/to-radians 180))\n;; => true\n\n(math/to-radians -0.0)\n;; => -0.0\n\n;; Bascially the same as:\n(def ^:const deg->rad (/ math/PI 180.0))\n(fn [x] (* x deg->rad))","_id":"656e04b069fbcc0c22617476"}],"notes":null,"arglists":["deg"],"doc":"Converts an angle in degrees to an approximate equivalent angle in radians.\n See: https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#toRadians-double-","library-url":"https://github.com/clojure/clojure","href":"/clojure.math/to-radians"},{"added":"1.11","ns":"clojure.math","name":"log","file":"clojure/math.clj","type":"function","column":1,"see-alsos":[{"created-at":1699484398699,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"log10","ns":"clojure.math"},"_id":"654c12ee69fbcc0c2261742b"}],"line":136,"examples":[{"updated-at":1698965827966,"created-at":1698965827966,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":";; Let's find out how long it would take my $5000 savings to grow to $6000 at an\n;; annual interest rate of 5.25%, compounded continuously…\n(let [initial 5000\n goal 6000\n annual-rate 0.0525]\n (/ (math/log (/ goal initial))\n annual-rate))\n;; => 3.4727915579800874\n;; …about 3 years, 5½ months\n\n;; Let's find out how much carbon-14 we'd have after 100yrs if we start with 1kg…\n(let [c14-half-life-yrs 5730\n initial-mass 1000\n time-yrs 100\n ;; First we need the decay constant, which is defined as λ = ln(2) / t(½)…\n λ (/ (math/log 2.0) c14-half-life-yrs)]\n ;; Lastly, we use the radioactive decay formula: N(t) = N₀⋅e^-λt\n (* initial-mass (math/exp (- (* λ time-yrs)))))\n;; => 987.9760628287868\n;; …most of it actually","_id":"6544294369fbcc0c22617424"}],"notes":null,"arglists":["a"],"doc":"Returns the natural logarithm (base e) of a.\n If a is ##NaN or negative => ##NaN\n If a is ##Inf => ##Inf\n If a is zero => ##-Inf\n See: https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#log-double-","library-url":"https://github.com/clojure/clojure","href":"/clojure.math/log"},{"added":"1.11","ns":"clojure.math","name":"acos","file":"clojure/math.clj","type":"function","column":1,"see-alsos":[{"created-at":1698314040636,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"cos","ns":"clojure.math"},"_id":"653a373869fbcc0c226173e4"}],"line":85,"examples":[{"updated-at":1698314029031,"created-at":1698314029031,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":";; Let's find the angles of a triangle with sides 11,17,23\n;; We'll label those side a,b,c respectively,\n;; and the angles opposite them A,B,C respectively\n(let [a 11, b 17, c 23\n ;; The formula for A is: cos(A) = (b²+c²-a²) / 2bc)\n ;; Or in Clojure:\n cos-A (/ (- (+ (* b b) (* c c)) (* a a)) (* 2 b c))\n ;; and for the other angles:\n cos-B (/ (- (+ (* a a) (* c c)) (* b b)) (* 2 a c))\n cos-C (/ (- (+ (* a a) (* b b)) (* c c)) (* 2 a b))\n ;; We can use acos to give us the angles in radians:\n A (math/acos cos-A)\n B (math/acos cos-B)\n C (math/acos cos-C)]\n ;; And convert to degrees if we like…\n {:A (math/to-degrees A)\n :B (math/to-degrees B)\n :C (math/to-degrees C)})\n;; => {:A 26.96238899747977, :B 44.48460646749956, :C 108.55300453502066}\n\n;; And let's check that those angles sum to ~180°…\n(let [{A :A B :B C :C} *1] (+ A B C))\n;; => 180.0","_id":"653a372d69fbcc0c226173e3"}],"notes":null,"arglists":["a"],"doc":"Returns the arc cosine of a, in the range 0.0 to pi.\n If a is ##NaN or |a|>1 => ##NaN\n See: https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#acos-double-","library-url":"https://github.com/clojure/clojure","href":"/clojure.math/acos"},{"added":"1.11","ns":"clojure.math","name":"to-degrees","file":"clojure/math.clj","type":"function","column":1,"see-alsos":[{"created-at":1701708996197,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"to-radians","ns":"clojure.math"},"_id":"656e04c469fbcc0c22617478"}],"line":115,"examples":[{"updated-at":1701708033174,"created-at":1701708033174,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":"(math/to-degrees math/PI)\n;; => 180.0\n\n(math/to-degrees (- math/PI))\n;; => -180.0\n\n(math/to-degrees -0.0)\n;; => -0.0\n\n;; Bascially the same as:\n(def ^:const rad->deg (/ 180.0 math/PI))\n(fn [x] (* x rad->deg))","_id":"656e010169fbcc0c22617475"}],"notes":null,"arglists":["r"],"doc":"Converts an angle in radians to an approximate equivalent angle in degrees.\n See: https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#toDegrees-double-","library-url":"https://github.com/clojure/clojure","href":"/clojure.math/to-degrees"},{"added":"1.11","ns":"clojure.math","name":"floor","file":"clojure/math.clj","type":"function","column":1,"see-alsos":null,"line":210,"examples":[{"updated-at":1698676452051,"created-at":1698676452051,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":"(math/floor 42.1)\n;; => 42.0\n\n(math/floor 42.8)\n;; => 42.0\n\n(math/floor -42.1)\n;; => -43.0\n\n(math/floor -42.8)\n;; => -43.0","_id":"653fbee469fbcc0c22617409"}],"notes":null,"arglists":["a"],"doc":"Returns the largest double less than or equal to a, and equal to a\n mathematical integer.\n If a is ##NaN or ##Inf or ##-Inf or already equal to an integer => a\n If a is less than zero but greater than -1.0 => -0.0\n See: https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#floor-double-","library-url":"https://github.com/clojure/clojure","href":"/clojure.math/floor"},{"added":"1.11","ns":"clojure.math","name":"atan2","file":"clojure/math.clj","type":"function","column":1,"see-alsos":[{"created-at":1698336077674,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"hypot","ns":"clojure.math"},"_id":"653a8d4d69fbcc0c226173ea"},{"created-at":1698336085400,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"atan","ns":"clojure.math"},"_id":"653a8d5569fbcc0c226173eb"}],"line":233,"examples":[{"updated-at":1698335954264,"created-at":1698335954264,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":";; Converting Cartesian to polar coordinates…\n\n;; The parameters are listed as `y x` rather than `x y`,\n;; encouraging an East-Counterclockwise Convention, as favored in pure maths:\n(let [x 7.0, y 9.0]\n {:angle (math/to-degrees (math/atan2 y x))\n :radius (math/hypot x y)})\n;; => {:angle 52.1250163489018, :radius 11.40175425099138}\n\n;; To get the North-Clockwise Convention, which may be a little more intuitive,\n;; swap the argument order:\n(let [x 7.0, y 9.0]\n {:angle (math/to-degrees (math/atan2 x y))\n :radius (math/hypot x y)})\n;; => {:angle 37.8749836510982, :radius 11.40175425099138}","_id":"653a8cd269fbcc0c226173e9"},{"editors":[{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"}],"body":";; If x>0, then θ = atan2(y, x) = atan(y/x)…\n(math/atan (/ 4.0 3.0))\n;; => 0.9272952180016121\n(math/atan2 4.0 3.0)\n;; => 0.9272952180016122 ; n.b. atan2 is slightly more accurate too\n\n;; If x<0, then θ = atan2(y, x) = atan(y/x)±π…\n(+ (math/atan (/ 4.0 -3.0)) math/PI)\n;; => 2.214297435588181\n(math/atan2 4.0 -3.0)\n;; => 2.214297435588181\n\n;; i.e. atan2 handles the possible need for this correction","author":{"avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4","account-source":"github","login":"tomdl89"},"created-at":1698533743946,"updated-at":1698752635892,"_id":"653d916f69fbcc0c226173fe"}],"notes":null,"arglists":["y x"],"doc":"Returns the angle theta from the conversion of rectangular coordinates (x, y) to polar coordinates (r, theta).\n Computes the phase theta by computing an arc tangent of y/x in the range of -pi to pi.\n For more details on special cases, see:\n https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#atan2-double-double-","library-url":"https://github.com/clojure/clojure","href":"/clojure.math/atan2"},{"added":"1.11","ns":"clojure.math","name":"hypot","file":"clojure/math.clj","type":"function","column":1,"see-alsos":null,"line":410,"examples":[{"updated-at":1698340983527,"created-at":1698340983527,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":";; Have you ever wanted to calculate the hypotenuse of a triangle with\n;; sides way bigger than the diameter of the universe measured in plank lengths?\n;; Me neither, but this is what happens when you try it the \"normal\" way…\n(math/sqrt (+ (* 2E307 2E307) (* 3E307 3E307)))\n;; => ##Inf\n\n;; Whereas hypot still has you covered…\n(math/hypot 2E307 3E307)\n;; => 3.605551275463989E307\n\n;; The intermediate underflow and overflow avoidance is rarely useful,\n;; but the syntactic brevity is nice","_id":"653aa07769fbcc0c226173ef"}],"notes":null,"arglists":["x y"],"doc":"Returns sqrt(x^2 + y^2) without intermediate underflow or overflow.\n If x or y is ##Inf or ##-Inf => ##Inf\n If x or y is ##NaN and neither is ##Inf or ##-Inf => ##NaN\n See: https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#hypot-double-double-","library-url":"https://github.com/clojure/clojure","href":"/clojure.math/hypot"},{"added":"1.11","ns":"clojure.math","name":"tanh","file":"clojure/math.clj","type":"function","column":1,"see-alsos":[{"created-at":1701704634722,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"cosh","ns":"clojure.math"},"_id":"656df3ba69fbcc0c22617472"},{"created-at":1701704640354,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"sinh","ns":"clojure.math"},"_id":"656df3c069fbcc0c22617473"}],"line":397,"examples":[{"updated-at":1701704626501,"created-at":1701704626501,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":";; For a cable hanging between two points, with a \"sag parameter\" of 2.8m, let's\n;; calculate the slope of the cable 2m from the center (lowest point)…\n(let [a 2.8 ; a rough estimate, under ideal conditions\n offset 2\n ;; dy/dx = tanh(x/a) or in Clojure:\n slope (math/tanh (/ offset a))]\n ;; Let's convert to an angle (from horizontal, counterclockwise)\n (math/to-degrees (math/atan slope)))\n;; => 31.523173415331186","_id":"656df3b269fbcc0c22617471"},{"updated-at":1701705287427,"created-at":1701705287427,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":";; java.lang.Math, and therefore clojure.math, doesn't have a hyperbolic\n;; arctangent function, but we can implement a simple version like so…\n(defn atanh\n \"atanh(x) = 0.5 * log(1 + (2x / 1-x)\"\n [x]\n (* 0.5 (math/log1p (* 2 (/ x (- 1 x))))))","_id":"656df64769fbcc0c22617474"}],"notes":null,"arglists":["x"],"doc":"Returns the hyperbolic tangent of x, sinh(x)/cosh(x).\n If x is ##NaN => ##NaN\n If x is zero => zero, with same sign\n If x is ##Inf => +1.0\n If x is ##-Inf => -1.0\n See: https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#tanh-double-","library-url":"https://github.com/clojure/clojure","href":"/clojure.math/tanh"},{"added":"1.11","ns":"clojure.math","name":"floor-mod","file":"clojure/math.clj","type":"function","column":1,"see-alsos":[{"created-at":1698709066268,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"mod","ns":"clojure.core"},"_id":"65403e4a69fbcc0c22617411"},{"created-at":1698709072157,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"rem","ns":"clojure.core"},"_id":"65403e5069fbcc0c22617412"}],"line":341,"examples":[{"editors":[{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"}],"body":";; For integers, floor-mod is the same as mod…\n(every? true?\n (for [x (range -100 100)\n y (remove zero? (range -100 100))]\n (== (mod x y)\n (math/floor-mod x y))))\n;; => true\n\n;; Things differ with floats and doubles…\n\n(mod 7.4 -3.2)\n;; => -2.2\n\n(math/floor-mod 7.4 -3.2)\n;; => -2\n\n;; math/floor-mod coerces to longs before dividing, so is the same as:\n(mod (long 7.4) (long -3.2))\n;; => -2","author":{"avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4","account-source":"github","login":"tomdl89"},"created-at":1698708275106,"updated-at":1698709142235,"_id":"65403b3369fbcc0c2261740f"}],"notes":null,"arglists":["x y"],"doc":"Integer modulus x - (floorDiv(x, y) * y). Sign matches y and is in the\n range -|y| < r < |y|.\n See: https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#floorMod-long-long-","library-url":"https://github.com/clojure/clojure","href":"/clojure.math/floor-mod"},{"added":"1.11","ns":"clojure.math","name":"ceil","file":"clojure/math.clj","type":"function","column":1,"see-alsos":null,"line":199,"examples":[{"editors":[{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"}],"body":"(math/ceil 42.8)\n;; => 43.0\n\n(math/ceil 42.1)\n;; => 43.0\n\n(math/ceil -42.8)\n;; => -42.0\n\n(math/ceil -42.1)\n;; => -42.0\n\n(math/ceil -0.3)\n;; => -0.0","author":{"avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4","account-source":"github","login":"tomdl89"},"created-at":1698396371681,"updated-at":1698677515140,"_id":"653b78d369fbcc0c226173f1"}],"notes":null,"arglists":["a"],"doc":"Returns the smallest double greater than or equal to a, and equal to a\n mathematical integer.\n If a is ##NaN or ##Inf or ##-Inf or already equal to an integer => a\n See: https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#ceil-double-","library-url":"https://github.com/clojure/clojure","href":"/clojure.math/ceil"},{"added":"1.11","ns":"clojure.math","name":"atan","file":"clojure/math.clj","type":"function","column":1,"see-alsos":[{"created-at":1698333543370,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"tan","ns":"clojure.math"},"_id":"653a836769fbcc0c226173e8"}],"line":95,"examples":[{"updated-at":1698333537155,"created-at":1698333537155,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":";; Given the opposite and adjacent sides of a right-angled triangle…\n(let [opp 7 adj 19\n ;; The angle betwwen adjacent and hypotenuse is given by:\n tanθ (/ opp adj)\n ;; So we can calculate θ by using atan:\n θ (math/atan tanθ)]\n ;; And return it in degrees…\n (math/to-degrees θ))\n;; => 20.224859431168078","_id":"653a836169fbcc0c226173e7"}],"notes":null,"arglists":["a"],"doc":"Returns the arc tangent of a, in the range of -pi/2 to pi/2.\n If a is ##NaN => ##NaN\n If a is zero => zero with the same sign as a\n See: https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#atan-double-","library-url":"https://github.com/clojure/clojure","href":"/clojure.math/atan"},{"added":"1.11","ns":"clojure.math","name":"multiply-exact","file":"clojure/math.clj","type":"function","column":1,"see-alsos":[{"created-at":1699540867611,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"*","ns":"clojure.core"},"_id":"654cef8369fbcc0c22617431"}],"line":295,"examples":[{"updated-at":1699540836105,"created-at":1699540836105,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":";; `*` uses multiplyExact for longs under the hood, so these are the same:\n(* Long/MAX_VALUE 7)\n(math/multiply-exact Long/MAX_VALUE 7)\n;; => Execution error (ArithmeticException) at java.lang.Math/multiplyExact (Math.java:1004).\n;; long overflow\n\n;; However, doubles are treated differently…\n(* Double/MAX_VALUE Double/MAX_VALUE)\n;; => ##Inf\n\n;; Whereas multiply-exact coerces to longs…\n(math/multiply-exact Double/MAX_VALUE Double/MAX_VALUE)\n;; => Execution error (IllegalArgumentException) at…\n;; Value out of range for long: 1.7976931348623157E308\n\n;; Basically the same as:\n(* (long Double/MAX_VALUE) (long Double/MAX_VALUE))\n;; => Execution error (IllegalArgumentException) at…\n;; Value out of range for long: 1.7976931348623157E308","_id":"654cef6469fbcc0c22617430"}],"notes":null,"arglists":["x y"],"doc":"Returns the product of x and y, throws ArithmeticException on overflow.\n See: https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#multiplyExact-long-long-","library-url":"https://github.com/clojure/clojure","href":"/clojure.math/multiply-exact"},{"added":"1.11","ns":"clojure.math","name":"expm1","file":"clojure/math.clj","type":"function","column":1,"see-alsos":[{"created-at":1698668040519,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"exp","ns":"clojure.math"},"_id":"653f9e0869fbcc0c22617405"},{"created-at":1699484523543,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"log1p","ns":"clojure.math"},"_id":"654c136b69fbcc0c2261742c"}],"line":421,"examples":[{"editors":[{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"}],"body":";; Let's work out how much extra money I'll have after day 1 if I deposit the\n;; entire GDP of the USA in an account with a daily interest rate of 0.0001%,\n;; compounded continuously…\n\n;; Using expm1:\n(let [principal-ammount 26.949e12\n daily-interest-rate 1e-6]\n (format \"$%,.3f\"\n (* principal-ammount (math/expm1 daily-interest-rate))))\n;; => \"26,949,013.475\"\n\n;; Using exp and subtracting 1:\n(let [principal-ammount 26.949e12\n daily-interest-rate 1e-6]\n (format \"$%,.3f\"\n (* principal-ammount (dec (math/exp daily-interest-rate)))))\n;; => \"$26,949,013.473\"\n\n;; There's two tenths of a cent in it.\n;; An unlikely scenario, but it illustrates where expm1 provides better accuracy","author":{"avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4","account-source":"github","login":"tomdl89"},"created-at":1698668131159,"updated-at":1698668268796,"_id":"653f9e6369fbcc0c22617406"}],"notes":null,"arglists":["x"],"doc":"Returns e^x - 1. Near 0, expm1(x)+1 is more accurate to e^x than exp(x).\n If x is ##NaN => ##NaN\n If x is ##Inf => #Inf\n If x is ##-Inf => -1.0\n If x is zero => x\n See: https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#expm1-double-","library-url":"https://github.com/clojure/clojure","href":"/clojure.math/expm1"},{"added":"1.11","ns":"clojure.math","name":"get-exponent","file":"clojure/math.clj","type":"function","column":1,"see-alsos":null,"line":458,"examples":[{"updated-at":1698709005213,"created-at":1698709005213,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":"(take 16 (map (juxt identity math/get-exponent) (iterate #(* 2 %) 2)))\n;; => ([2 1]\n;; [4 2]\n;; [8 3]\n;; [16 4]\n;; [32 5]\n;; [64 6]\n;; [128 7]\n;; [256 8]\n;; [512 9]\n;; [1024 10]\n;; [2048 11]\n;; [4096 12]\n;; [8192 13]\n;; [16384 14]\n;; [32768 15]\n;; [65536 16])\n\n(take 16 (map (juxt identity math/get-exponent) (iterate #(/ % 2) 1)))\n;; => ([1 0]\n;; [1/2 -1]\n;; [1/4 -2]\n;; [1/8 -3]\n;; [1/16 -4]\n;; [1/32 -5]\n;; [1/64 -6]\n;; [1/128 -7]\n;; [1/256 -8]\n;; [1/512 -9]\n;; [1/1024 -10]\n;; [1/2048 -11]\n;; [1/4096 -12]\n;; [1/8192 -13]\n;; [1/16384 -14]\n;; [1/32768 -15])","_id":"65403e0d69fbcc0c22617410"}],"notes":null,"arglists":["d"],"doc":"Returns the exponent of d.\n If d is ##NaN, ##Inf, ##-Inf => Double/MAX_EXPONENT + 1\n If d is zero or subnormal => Double/MIN_EXPONENT - 1\n See: https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#getExponent-double-","library-url":"https://github.com/clojure/clojure","href":"/clojure.math/get-exponent"},{"added":"1.11","ns":"clojure.math","name":"add-exact","file":"clojure/math.clj","type":"function","column":1,"see-alsos":[{"created-at":1698338849227,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"+","ns":"clojure.core"},"_id":"653a982169fbcc0c226173ec"},{"created-at":1698338855575,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"+'","ns":"clojure.core"},"_id":"653a982769fbcc0c226173ed"}],"line":277,"examples":[{"updated-at":1698340122661,"created-at":1698340122661,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":";; `+` uses addExact for longs under the hood, so these are the same:\n(+ Long/MAX_VALUE 7)\n(math/add-exact Long/MAX_VALUE 7)\n;; => Execution error (ArithmeticException) at java.lang.Math/addExact (Math.java:903).\n;; long overflow\n\n;; However, doubles are treated differently…\n(+ Double/MAX_VALUE Double/MAX_VALUE)\n;; => ##Inf\n\n;; Whereas add-exact coerces to longs…\n(math/add-exact Double/MAX_VALUE Double/MAX_VALUE)\n;; => Execution error (IllegalArgumentException) at…\n;; Value out of range for long: 1.7976931348623157E308\n\n;; Basically the same as:\n(+ (long Double/MAX_VALUE) (long Double/MAX_VALUE))\n;; => Execution error (IllegalArgumentException) at…\n;; Value out of range for long: 1.7976931348623157E308","_id":"653a9d1a69fbcc0c226173ee"}],"notes":null,"arglists":["x y"],"doc":"Returns the sum of x and y, throws ArithmeticException on overflow.\n See: https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#addExact-long-long-","library-url":"https://github.com/clojure/clojure","href":"/clojure.math/add-exact"},{"added":"1.11","ns":"clojure.math","name":"cos","file":"clojure/math.clj","type":"function","column":1,"see-alsos":[{"created-at":1699793838389,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"sin","ns":"clojure.math"},"_id":"6550cbae69fbcc0c22617452"},{"created-at":1699793843429,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"tan","ns":"clojure.math"},"_id":"6550cbb369fbcc0c22617453"}],"line":53,"examples":[{"updated-at":1698400997534,"created-at":1698400997534,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":";; Let's find the other side lengths of a right-angled triangle, where we\n;; know an acute angle, O and one side, a…\n(let [O (math/to-radians 29.0)\n a 17.0\n ;; The formula we need for the hypotenuse is h = a/cos(O), or in Clojure:\n h (/ a (math/cos O))\n ;; We can use o = cos(A)·h to get the 3rd side length:\n A (- (/ math/PI 2) O)\n o (* (math/cos A) h)]\n ;; And return the dimensions, and the angles in degrees:\n {:o o, :h h, :a a\n :O 29.0, :H 90.0 :A (math/to-degrees A)})\n;; => {:o 9.423253874697075,\n;; :h 19.437019153846443,\n;; :a 17.0,\n;; :O 29.0,\n;; :H 90.0,\n;; :A 61.0}","_id":"653b8ae569fbcc0c226173f3"}],"notes":null,"arglists":["a"],"doc":"Returns the cosine of an angle.\n If a is ##NaN, ##-Inf, ##Inf => ##NaN\n See: https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#cos-double-","library-url":"https://github.com/clojure/clojure","href":"/clojure.math/cos"},{"added":"1.11","ns":"clojure.math","name":"log10","file":"clojure/math.clj","type":"function","column":1,"see-alsos":[{"created-at":1699484389364,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"log","ns":"clojure.math"},"_id":"654c12e569fbcc0c2261742a"}],"line":148,"examples":[{"updated-at":1699484379751,"created-at":1699484379751,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":";; Let's calculate the pH when 1g of hydrochloric acid is added to 2L of water…\n(let [HCl-grams 1\n H2O-litres 2\n HCl-molar-mass 36.46\n HCl-moles (/ HCl-grams HCl-molar-mass)\n ;; HCl is a strong acid, so dissociates completely in water\n molarity (/ HCl-moles H2O-litres)]\n ;; pH is calculated as pH = -log₁₀([H⁺])\n (- (math/log10 molarity)))\n;; => 1.8628466599829387","_id":"654c12db69fbcc0c22617429"}],"notes":null,"arglists":["a"],"doc":"Returns the logarithm (base 10) of a.\n If a is ##NaN or negative => ##NaN\n If a is ##Inf => ##Inf\n If a is zero => ##-Inf\n See: https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#log10-double-","library-url":"https://github.com/clojure/clojure","href":"/clojure.math/log10"},{"added":"1.11","ns":"clojure.math","name":"tan","file":"clojure/math.clj","type":"function","column":1,"see-alsos":[{"created-at":1701687121259,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"cos","ns":"clojure.math"},"_id":"656daf5169fbcc0c2261746f"},{"created-at":1701687126983,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"sin","ns":"clojure.math"},"_id":"656daf5669fbcc0c22617470"}],"line":63,"examples":[{"updated-at":1701687111590,"created-at":1701687111590,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":";; Let's find the other side lengths of a right-angled triangle, where we\n;; know an acute angle, O and the \"adjacent\" side…\n(let [O (math/to-radians 29.0)\n a 19\n ;; The formula we need for the opposite is o = a/tan(O), or in Clojure:\n o (/ a (math/tan O))\n ;; We can use h = a/sin(O) to get the hypotenuse length:\n h (/ a (math/sin O))\n ;; And the angle sum property of triangles for A:\n A (- (/ math/PI 2) O)]\n ;; And return the dimensions, and the angles in degrees:\n {:o o, :h h, :a a\n :O 29.0, :H 90.0 :A (math/to-degrees A)})\n;; => {:o 34.27690735015705\n;; :h 39.19064145291897\n;; :a 19\n;; :O 29.0\n;; :H 90.0\n;; :A 61.0}","_id":"656daf4769fbcc0c2261746e"}],"notes":null,"arglists":["a"],"doc":"Returns the tangent of an angle.\n If a is ##NaN, ##-Inf, ##Inf => ##NaN\n If a is zero => zero with the same sign as a\n See: https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#tan-double-","library-url":"https://github.com/clojure/clojure","href":"/clojure.math/tan"},{"added":"1.11","ns":"clojure.math","name":"cbrt","file":"clojure/math.clj","type":"function","column":1,"see-alsos":null,"line":172,"examples":[{"updated-at":1698396277196,"created-at":1698396277196,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":";; There's always a real-valued odd root for real arguments…\n(math/cbrt -27)\n;; => -3.0\n\n;; So this function is particularly handy for negative numbers\n;; as you'd need to negate the root of the negated argument if using pow instead…\n(- (math/pow 27 (/ 1 3)))\n;; => -3.0\n\n;; because raising negative numbers to fractional powers takes us into the complex realm…\n(math/pow -27 (/ 1 3))\n;; => ##NaN","_id":"653b787569fbcc0c226173f0"}],"notes":null,"arglists":["a"],"doc":"Returns the cube root of a.\n If a is ##NaN => ##NaN\n If a is ##Inf or ##-Inf => a\n If a is zero => zero with sign matching a\n See: https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#cbrt-double-","library-url":"https://github.com/clojure/clojure","href":"/clojure.math/cbrt"},{"added":"1.11","ns":"clojure.math","name":"sqrt","file":"clojure/math.clj","type":"function","column":1,"see-alsos":[{"created-at":1701448966416,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"pow","ns":"clojure.math"},"_id":"656a0d0669fbcc0c22617467"}],"line":160,"examples":[{"editors":[{"login":"kvedula70","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/35220619?v=4"}],"body":";; Given power (in Watts) and resistance (in Ohms), let's find the\n;; current in an electric circuit…\n(let [P 25\n R 100]\n ;; The formula is P = I²R or rearranged, I = √P/R\n (Math/sqrt (/ P R)))\n;; => 0.5","author":{"avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4","account-source":"github","login":"tomdl89"},"created-at":1701448922144,"updated-at":1726829960524,"_id":"656a0cda69fbcc0c22617466"}],"notes":null,"arglists":["a"],"doc":"Returns the positive square root of a.\n If a is ##NaN or negative => ##NaN\n If a is ##Inf => ##Inf\n If a is zero => a\n See: https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#sqrt-double-","library-url":"https://github.com/clojure/clojure","href":"/clojure.math/sqrt"},{"added":"1.11","ns":"clojure.math","name":"decrement-exact","file":"clojure/math.clj","type":"function","column":1,"see-alsos":[{"created-at":1698532749493,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"dec","ns":"clojure.core"},"_id":"653d8d8d69fbcc0c226173fc"},{"created-at":1698532760286,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"increment-exact","ns":"clojure.math"},"_id":"653d8d9869fbcc0c226173fd"}],"line":313,"examples":[{"updated-at":1698532742248,"created-at":1698532742248,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":";; `dec` uses decrementExact for longs under the hood, so these are the same:\n(dec Long/MIN_VALUE)\n(math/decrement-exact Long/MIN_VALUE)\n;; => Execution error (ArithmeticException) at java.lang.Math/decrementExact (Math.java:1080).\n;; long overflow\n\n;; Doubles and floats are coerced to longs…\n(math/decrement-exact (- Double/MAX_VALUE)) ; n.b. Double/MIN_VALUE is not negative\n;; => Execution error (IllegalArgumentException) at…\n;; Value out of range for long: -1.7976931348623157E308\n\n;; Basically the same as:\n(dec (long (- Double/MAX_VALUE)))\n;; => Execution error (IllegalArgumentException) at…\n;; Value out of range for long: -1.7976931348623157E308\n\n;; Unlike dec alone, which exhibits this curious (but well documented) behaviour…\n(dec (- Double/MAX_VALUE))\n;; => -1.7976931348623157E308","_id":"653d8d8669fbcc0c226173fb"}],"notes":null,"arglists":["a"],"doc":"Returns a decremented by 1, throws ArithmeticException on overflow.\n See: https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#decrementExact-long-","library-url":"https://github.com/clojure/clojure","href":"/clojure.math/decrement-exact"},{"added":"1.11","ns":"clojure.math","name":"PI","file":"clojure/math.clj","type":"var","column":1,"see-alsos":null,"line":33,"examples":[{"updated-at":1699549100879,"created-at":1699549100879,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":"(defn circle-area [radius]\n (* math/PI radius radius))\n(circle-area 50)\n;; => 7853.981633974483\n\n(defn sphere-volume [radius]\n (* math/PI 4/3 (math/pow radius 3.0)))\n(sphere-volume 50)\n;; => 523598.7755982987\n\n(defn deg->rad [deg]\n (* deg (/ math/PI 180)))\n(== (deg->rad 45.0) (math/to-radians 45.0))\n;; => true\n\n(math/sin (/ math/PI 2))\n;; => 1.0\n\n(math/cos math/PI)\n;; => -1.0","_id":"654d0fac69fbcc0c2261743d"}],"notes":null,"tag":"double","arglists":[],"doc":"Constant for pi, the ratio of the circumference of a circle to its diameter.\n See: https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#PI","library-url":"https://github.com/clojure/clojure","href":"/clojure.math/PI"},{"added":"1.11","ns":"clojure.math","name":"next-down","file":"clojure/math.clj","type":"function","column":1,"see-alsos":[{"created-at":1699545568547,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"next-up","ns":"clojure.math"},"_id":"654d01e069fbcc0c22617439"},{"created-at":1699545574720,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"next-after","ns":"clojure.math"},"_id":"654d01e669fbcc0c2261743a"}],"line":499,"examples":[{"updated-at":1699547393524,"created-at":1699547393524,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":";; Longs are coerced to doubles:\n(math/next-down Long/MIN_VALUE)\n;; => -9.223372036854778E18\n\n;; Infinity is just the next thing above the biggest double:\n(== Double/MAX_VALUE (math/next-down ##Inf))\n;; => true\n\n;; Negative infninty is the next thing below the smallest:\n(math/next-down (- Double/MAX_VALUE)) ; n.b. Double/MIN_VALUE is not negative\n;; => ##-Inf\n\n;; The direction we're coming from dictates the sign for zero:\n(math/next-down 4.9E-324)\n;; => 0.0\n(math/next-up -4.9E-324)\n;; => -0.0","_id":"654d090169fbcc0c2261743b"}],"notes":null,"arglists":["d"],"doc":"Returns the adjacent double of d in the direction of ##-Inf.\n If d is ##NaN => ##NaN\n If d is ##-Inf => ##-Inf\n If d is zero => -Double/MIN_VALUE\n See: https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#nextDown-double-","library-url":"https://github.com/clojure/clojure","href":"/clojure.math/next-down"},{"added":"1.11","ns":"clojure.math","name":"pow","file":"clojure/math.clj","type":"function","column":1,"see-alsos":null,"line":244,"examples":[{"editors":[{"login":"seancorfield","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/43875?v=4"}],"body":"(require '[clojure.math :as math])\n;; Let's calculate how much I'd have after a year if I invested $5000 at an\n;; annual rate of 5%, compounded monthly…\n(let [principal 5000\n annual-rate 0.05\n years 1\n compounding-periods 12]\n ;; Formula: A = P * (1 + r/k)^(n * k)\n (->> (* principal (math/pow (inc (/ annual-rate compounding-periods))\n (* years compounding-periods)))\n (format \"$%,.2f\")))\n;; => \"$5,255.81\"","author":{"avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4","account-source":"github","login":"tomdl89"},"created-at":1699630063200,"updated-at":1762279848791,"_id":"654e4bef69fbcc0c2261743f"}],"notes":[{"body":"If you need a positive integer to a positive integer power, try the following\n\n```clojure\n(defn power [b p]\n (cond (= p 0)\n 1\n\n (= p 1)\n b\n\n (even? p)\n (recur (* b b) (quot p 2))\n\n :else\n (* b (power b (dec p)))))\n\n;; e.g. (power 10N 20) => 100000000000000000000N with 20 zeros\n```\n\n","created-at":1738760497471,"updated-at":1738769568788,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/6414129?v=4","account-source":"github","login":"jimka2001"},"_id":"67a36131cd84df5de54e2076"}],"arglists":["a b"],"doc":"Returns the value of a raised to the power of b.\n For more details on special cases, see:\n https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#pow-double-double-","library-url":"https://github.com/clojure/clojure","href":"/clojure.math/pow"},{"added":"1.11","ns":"clojure.math","name":"next-up","file":"clojure/math.clj","type":"function","column":1,"see-alsos":[{"created-at":1699545555672,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"next-after","ns":"clojure.math"},"_id":"654d01d369fbcc0c22617437"},{"created-at":1699545560820,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"next-down","ns":"clojure.math"},"_id":"654d01d869fbcc0c22617438"}],"line":487,"examples":[{"updated-at":1699547616341,"created-at":1699547616341,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":";; Longs are coerced to doubles:\n(math/next-up Long/MAX_VALUE)\n;; => 9.223372036854778E18\n\n;; Negative infinity is just the next thing below the smallest double:\n(== (- Double/MAX_VALUE) (math/next-up ##-Inf)) ; n.b. Double/MIN_VALUE is not negative\n;; => true\n\n;; Infinity is the next thing above the biggest:\n(math/next-up Double/MAX_VALUE)\n;; => ##Inf\n\n;; The direction we're coming from dictates the sign for zero:\n(math/next-up -4.9E-324)\n;; => -0.0\n(math/next-down 4.9E-324)\n;; => 0.0","_id":"654d09e069fbcc0c2261743c"}],"notes":null,"arglists":["d"],"doc":"Returns the adjacent double of d in the direction of ##Inf.\n If d is ##NaN => ##NaN\n If d is ##Inf => ##Inf\n If d is zero => Double/MIN_VALUE\n See: https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#nextUp-double-","library-url":"https://github.com/clojure/clojure","href":"/clojure.math/next-up"},{"added":"1.11","ns":"clojure.math","name":"exp","file":"clojure/math.clj","type":"function","column":1,"see-alsos":[{"created-at":1698668028896,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"expm1","ns":"clojure.math"},"_id":"653f9dfc69fbcc0c22617404"}],"line":124,"examples":[{"updated-at":1698666219998,"created-at":1698666219998,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":";; Let's work out how much money I'll have after 10yrs if I deposit $10,000 in\n;; an account with an annual interest rate of 5%, compounded continuously…\n(let [principal-ammount 10e3\n annual-interest-rate 0.05\n years 10]\n (format \"$%,.2f\"\n (* principal-ammount (math/exp (* annual-interest-rate years)))))\n;; => \"$16,487.21\"","_id":"653f96eb69fbcc0c22617402"}],"notes":null,"arglists":["a"],"doc":"Returns Euler's number e raised to the power of a.\n If a is ##NaN => ##NaN\n If a is ##Inf => ##Inf\n If a is ##-Inf => +0.0\n See: https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#exp-double-","library-url":"https://github.com/clojure/clojure","href":"/clojure.math/exp"},{"added":"1.11","ns":"clojure.math","name":"subtract-exact","file":"clojure/math.clj","type":"function","column":1,"see-alsos":[{"created-at":1701683594935,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"-","ns":"clojure.core"},"_id":"656da18a69fbcc0c2261746c"},{"created-at":1701683601467,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"-'","ns":"clojure.core"},"_id":"656da19169fbcc0c2261746d"}],"line":286,"examples":[{"updated-at":1701683372122,"created-at":1701683372122,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":";; `-` uses subtractExact for longs under the hood, so these are the same:\n(- Long/MIN_VALUE 7)\n(math/subtract-exact Long/MIN_VALUE 7)\n;; => Execution error (ArithmeticException) at java.lang.Math/subtractExact (Math.java:973).\n;; long overflow\n\n;; However, doubles are treated differently…\n(- (- Double/MAX_VALUE) Double/MAX_VALUE) ; n.b. Double/MIN_VALUE is not negative\n;; => ##-Inf\n\n;; Whereas subtract-exact coerces to longs…\n(math/subtract-exact (- Double/MAX_VALUE) Double/MAX_VALUE)\n;; => Execution error (IllegalArgumentException) at…\n;; Value out of range for long: -1.7976931348623157E308\n\n;; Basically the same as:\n(- (long (- Double/MAX_VALUE)) (long Double/MAX_VALUE))\n;; => Execution error (IllegalArgumentException) at…\n;; Value out of range for long: -1.7976931348623157E308","_id":"656da0ac69fbcc0c2261746b"}],"notes":null,"arglists":["x y"],"doc":"Returns the difference of x and y, throws ArithmeticException on overflow.\n See: https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#subtractExact-long-long-","library-url":"https://github.com/clojure/clojure","href":"/clojure.math/subtract-exact"},{"added":"1.11","ns":"clojure.math","name":"cosh","file":"clojure/math.clj","type":"function","column":1,"see-alsos":[{"created-at":1699793880924,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"sinh","ns":"clojure.math"},"_id":"6550cbd869fbcc0c22617454"},{"created-at":1699793885040,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"tanh","ns":"clojure.math"},"_id":"6550cbdd69fbcc0c22617455"}],"line":385,"examples":[{"editors":[{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"}],"body":";; For a 6m cable freely hanging between two points, 5m apart, let's find the\n;; vertical distance between the level of the hanging points and the lowest\n;; point of the cable. This is given by y = (a⋅cosh(x/a)) - a, where x is the\n;; horizontal offset (which will be 2.5m, halfway between the points), and a is\n;; the \"sag parameter\", which can be iteratively approximated.\n(let [cable-length 6\n hanging-span 5\n a (iterative-solve (fn [a] (* 2 a (math/sinh (/ hanging-span (* 2 a)))))\n cable-length\n 1e-9)]\n (- (* a (math/cosh (/ 2.5 a))) a))\n;; => 1.4617189875858645\n\n;; Where iterative-solve is defined below. It's necessary to take an approach\n;; like this, as L = 2a⋅sinh(x/2a) is a transcendental equation.\n(defn iterative-solve\n \"Greedy algorithm, assuming f is monotonic.\"\n ([f target initial-tol] (iterative-solve f target target initial-tol))\n ([f init target initial-tol]\n (loop [n init\n tol init] ; Just get n within init of target to start with\n (let [diff (- (f n) target)]\n (cond (<= (abs diff) initial-tol) n\n (<= (abs diff) tol) (recur n (* 0.1 tol))\n :else (recur (+ n (math/copy-sign tol diff)) tol))))))\n","author":{"avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4","account-source":"github","login":"tomdl89"},"created-at":1698448687180,"updated-at":1698497691658,"_id":"653c452f69fbcc0c226173f9"},{"updated-at":1700832987493,"created-at":1700832987493,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":";; java.lang.Math, and therefore clojure.math, doesn't have a hyperbolic\n;; arccosine function, but we can implement a simple version like so…\n(defn acosh\n \"acosh(x) = log(2⋅x - 1/(x + √(x² - 1)))\"\n [x]\n (math/log (- (* 2 x)\n (/ 1 (+ x (math/sqrt (dec (* x x))))))))","_id":"6560a6db69fbcc0c2261745e"}],"notes":null,"arglists":["x"],"doc":"Returns the hyperbolic cosine of x, (e^x + e^-x)/2.\n If x is ##NaN => ##NaN\n If x is ##Inf or ##-Inf => ##Inf\n If x is zero => 1.0\n See: https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#cosh-double-","library-url":"https://github.com/clojure/clojure","href":"/clojure.math/cosh"},{"added":"1.11","ns":"clojure.math","name":"scalb","file":"clojure/math.clj","type":"function","column":1,"see-alsos":null,"line":511,"examples":[{"updated-at":1717413265271,"created-at":1699709419052,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":";; SCALe Binary:\n(map #(math/scalb 1.0 %) (range 10))\n;; => (1.0 2.0 4.0 8.0 16.0 32.0 64.0 128.0 256.0 512.0)\n\n(== (* 12345678.9 32.0) (math/scalb 12345678.9 5))\n;; => true\n\n;; and for integers:\n(== (* 12345678 32.0) (math/scalb 12345678 5) (bit-shift-left 12345678 5))\n;; => true","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4","account-source":"github","login":"tomdl89"}],"_id":"654f81eb69fbcc0c22617448"}],"notes":null,"arglists":["d scaleFactor"],"doc":"Returns d * 2^scaleFactor, scaling by a factor of 2. If the exponent\n is between Double/MIN_EXPONENT and Double/MAX_EXPONENT, the answer is exact.\n If d is ##NaN => ##NaN\n If d is ##Inf or ##-Inf => ##Inf or ##-Inf respectively\n If d is zero => zero of same sign as d\n See: https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#nextDown-double-","library-url":"https://github.com/clojure/clojure","href":"/clojure.math/scalb"},{"added":"1.11","ns":"clojure.math","name":"log1p","file":"clojure/math.clj","type":"function","column":1,"see-alsos":[{"created-at":1699485151612,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"expm1","ns":"clojure.math"},"_id":"654c15df69fbcc0c2261742d"}],"line":434,"examples":[{"updated-at":1699487934245,"created-at":1699487934245,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":";; If I have an effective interest rate of 5%, what's the equivalent nominal,\n;; continuously compounded rate?\n(math/log1p 0.05)\n;; => 0.04879016416943201\n\n;; Let's check that for 3 compounding periods\n(== (math/exp (* 3 0.04879016416943201))\n (math/pow 1.05 3.0))\n;; => true\n\n;; In terms of accuracy, this function is more useful than log(1+x) when rates\n;; are very small…\n(math/log1p 5e-15)\n;; => 4.999999999999987E-15\n(math/log (inc 5e-15))\n;; => 5.107025913275707E-15","_id":"654c20be69fbcc0c2261742e"}],"notes":null,"arglists":["x"],"doc":"Returns ln(1+x). For small values of x, log1p(x) is more accurate than\n log(1.0+x).\n If x is ##NaN or < -1 => ##NaN\n If x is ##Inf => ##Inf\n If x is -1 => ##-Inf\n If x is 0 => 0 with sign matching x\n See: https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#log1p-double-","library-url":"https://github.com/clojure/clojure","href":"/clojure.math/log1p"},{"added":"1.11","ns":"clojure.math","name":"asin","file":"clojure/math.clj","type":"function","column":1,"see-alsos":[{"created-at":1698322959549,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"sin","ns":"clojure.math"},"_id":"653a5a0f69fbcc0c226173e6"}],"line":74,"examples":[{"updated-at":1698322951369,"created-at":1698322951369,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":";; asin is particularly useful for \"SSA\" (side-side-angle) triangles\n;; That's when you know 2 side lengths, plus an angle not \"included\" between them\n;; (when the angle you know is included between the sides, it's an SAS triangle\n;; and that can be solved more directly using acos)\n\n;; Let's find the angles of a triangle with sides 11 & 7, and an \"excluded\" angle of 30°\n;; We'll label the sides a & b respectively, and the angle A\n(let [a 11, b 7, A (math/to-radians 30.0)\n ;; The formula for B is: sin(B) = b⋅sin(A) / a\n ;; Or in Clojure:\n sin-B (/ (* b (math/sin A)) a)\n B (math/asin sin-B)\n ;; We can use the angle sum property of triangles for C:\n C (- math/PI A B)]\n ;; And convert to degrees if we like…\n {:A 30.0\n :B (math/to-degrees B)\n :C (math/to-degrees C)})\n;; => {:A 30.0, :B 18.553004535020655, :C 131.44699546497935}\n\n;; Note that if b⋅sin(A) < a < b, then it's an ambiguous case…\n(let [a 11, b 17, A (math/to-radians 30.0)\n sin-B (/ (* b (math/sin A)) a)\n B1 (math/asin sin-B)\n B2 (- math/PI B1)\n C1 (- math/PI A B1)\n C2 (- math/PI A B2)]\n {:A 30.0\n :B1 (math/to-degrees B1)\n :B2 (math/to-degrees B2)\n :C1 (math/to-degrees C1)\n :C2 (math/to-degrees C2)})\n;; => {:A 30.0,\n;; :B1 50.59943124626228,\n;; :B2 129.40056875373773,\n;; :C1 99.40056875373773,\n;; :C2 20.599431246262288}","_id":"653a5a0769fbcc0c226173e5"}],"notes":null,"arglists":["a"],"doc":"Returns the arc sine of an angle, in the range -pi/2 to pi/2.\n If a is ##NaN or |a|>1 => ##NaN\n If a is zero => zero with the same sign as a\n See: https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#asin-double-","library-url":"https://github.com/clojure/clojure","href":"/clojure.math/asin"},{"added":"1.11","ns":"clojure.math","name":"copy-sign","file":"clojure/math.clj","type":"function","column":1,"see-alsos":null,"line":448,"examples":[{"updated-at":1698396425283,"created-at":1698396425283,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":"(math/copy-sign 42 -7)\n;; => -42.0\n\n(math/copy-sign -42 7)\n;; => 42.0","_id":"653b790969fbcc0c226173f2"}],"notes":null,"arglists":["magnitude sign"],"doc":"Returns a double with the magnitude of the first argument and the sign of\n the second.\n See: https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#copySign-double-double-","library-url":"https://github.com/clojure/clojure","href":"/clojure.math/copy-sign"},{"added":"1.11","ns":"clojure.math","name":"round","file":"clojure/math.clj","type":"function","column":1,"see-alsos":[{"created-at":1698761805689,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"with-precision","ns":"clojure.core"},"_id":"65410c4d69fbcc0c2261741d"},{"created-at":1699632304313,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"rint","ns":"clojure.math"},"_id":"654e54b069fbcc0c22617444"}],"line":254,"examples":[{"updated-at":1699707783596,"created-at":1699707783596,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":"(math/round 43.5)\n;; => 44\n\n(math/round -43.5)\n;; => -43\n\n;; Compare with `rint`…\n(math/rint 43.5)\n;; => 44.0\n\n(math/rint -43.5)\n;; => -44.0","_id":"654f7b8769fbcc0c22617447"}],"notes":null,"arglists":["a"],"doc":"Returns the closest long to a. If equally close to two values, return the one\n closer to ##Inf.\n If a is ##NaN => 0\n If a is ##-Inf or < Long/MIN_VALUE => Long/MIN_VALUE\n If a is ##Inf or > Long/MAX_VALUE => Long/MAX_VALUE\n See: https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#round-double-","library-url":"https://github.com/clojure/clojure","href":"/clojure.math/round"},{"added":"1.11","ns":"clojure.math","name":"negate-exact","file":"clojure/math.clj","type":"function","column":1,"see-alsos":[{"created-at":1699541604922,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"-","ns":"clojure.core"},"_id":"654cf26469fbcc0c22617433"}],"line":322,"examples":[{"updated-at":1699541586812,"created-at":1699541586812,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":";; `-` uses negateExact for a single long under the hood, so these are the same:\n(- Long/MIN_VALUE)\n(math/negate-exact Long/MIN_VALUE)\n;; => Execution error (ArithmeticException) at java.lang.Math/negateExact (Math.java:1118).\n;; long overflow\n\n;; However, doubles are treated differently…\n(- (- Double/MAX_VALUE)) ; n.b. Double/MIN_VALUE is not negative\n;; => 1.7976931348623157E308\n\n;; Whereas negate-exact coerces to longs…\n(math/negate-exact (- Double/MAX_VALUE))\n;; => Execution error (IllegalArgumentException) at…\n;; Value out of range for long: -1.7976931348623157E308\n\n;; Basically the same as:\n(- (long Double/MAX_VALUE))\n;; => Execution error (IllegalArgumentException) at…\n;; Value out of range for long: 1.7976931348623157E308","_id":"654cf25269fbcc0c22617432"}],"notes":null,"arglists":["a"],"doc":"Returns the negation of a, throws ArithmeticException on overflow.\n See: https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#negateExact-long-","library-url":"https://github.com/clojure/clojure","href":"/clojure.math/negate-exact"},{"added":"1.11","ns":"clojure.math","name":"E","file":"clojure/math.clj","type":"var","column":1,"see-alsos":[{"created-at":1698657448595,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"exp","ns":"clojure.math"},"_id":"653f74a869fbcc0c226173ff"},{"created-at":1698657456682,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"log","ns":"clojure.math"},"_id":"653f74b069fbcc0c22617400"}],"line":24,"examples":[{"updated-at":1699436018250,"created-at":1698662560674,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":"(defn calculate-e [n]\n (letfn [(mid [a b] (math/floor-div (+ a b) 2))\n (p [a b] (if (== b (inc a))\n 1\n (+ (*' (p a (mid a b)) (q (mid a b) b))\n (p (mid a b) b))))\n (q [a b] (if (== b (inc a))\n b\n (*' (q a (mid a b)) (q (mid a b) b))))]\n (double (+ 1 (/ (p 0 n) (q 0 n))))))\n\n(== math/E (calculate-e 20))\n;; => true\n\n;; e is nearly always the base of exponentials or natural logarithms, for which\n;; we have math/exp and math/log respectively. Direct applications of e without\n;; involving an exponent or logarithm are rare","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4","account-source":"github","login":"tomdl89"}],"_id":"653f88a069fbcc0c22617401"}],"notes":null,"tag":"double","arglists":[],"doc":"Constant for e, the base for natural logarithms.\n See: https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#E","library-url":"https://github.com/clojure/clojure","href":"/clojure.math/E"},{"added":"1.11","ns":"clojure.math","name":"IEEE-remainder","file":"clojure/math.clj","type":"function","column":1,"see-alsos":[{"created-at":1698743896319,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"mod","ns":"clojure.core"},"_id":"6540c65869fbcc0c22617414"},{"created-at":1698743900936,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"rem","ns":"clojure.core"},"_id":"6540c65c69fbcc0c22617415"}],"line":184,"examples":[{"updated-at":1698750554870,"created-at":1698750554870,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":";; Example of the rule in the docstring, for x=10, y=4:\n(/ 10.0 4.0)\n;; => 2.5\n\n;; 2 and 3 are both equally close to 2.5\n;; IEEE 754 chooses 2 because it is even\n\n(- 10.0 (* 4.0 2.0))\n;; => 2.0\n\n(math/IEEE-remainder 10.0 4.0)\n;; => 2.0","_id":"6540e05a69fbcc0c22617416"},{"editors":[{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"}],"body":";; You can think of IEEE-remainder as \"what is the least (in magnitude) I have\n;; to subtract from the dividend to make this divide exactly?\"…\n\n(math/IEEE-remainder 10 6)\n;; => -2.0\n(math/IEEE-remainder (- 10 -2.0) 6)\n;; => 0.0\n\n(math/IEEE-remainder -10.5 6)\n;; => 1.5\n(math/IEEE-remainder (- -10.5 1.5) 6)\n;; => -0.0\n\n(math/IEEE-remainder 10 -6.7)\n;; => 3.3\n(math/IEEE-remainder (- 10 3.3) -6.7)\n;; => 0.0\n\n;; Note how it returns the smallest magnitude result, rather than -3.4…\n(mod 10 -6.7)\n;; => -3.4000000000000004\n\n;; …which would also work:\n(math/IEEE-remainder (- 10 -3.4) -6.7)\n;; => 0.0\n\n;; In that way, it's helpful for cicular or periodic operations, where finding\n;; the \"shortest distance\" to exact division is needed","author":{"avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4","account-source":"github","login":"tomdl89"},"created-at":1698751358605,"updated-at":1698751395689,"_id":"6540e37e69fbcc0c22617417"}],"notes":null,"arglists":["dividend divisor"],"doc":"Returns the remainder per IEEE 754 such that\n remainder = dividend - divisor * n\n where n is the integer closest to the exact value of dividend / divisor.\n If two integers are equally close, then n is the even one.\n If the remainder is zero, sign will match dividend.\n If dividend or divisor is ##NaN, or dividend is ##Inf or ##-Inf, or divisor is zero => ##NaN\n If dividend is finite and divisor is infinite => dividend\n See: https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#IEEEremainder-double-double-","library-url":"https://github.com/clojure/clojure","href":"/clojure.math/IEEE-remainder"},{"added":"1.11","ns":"clojure.math","name":"sinh","file":"clojure/math.clj","type":"function","column":1,"see-alsos":[{"created-at":1699793892511,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"cosh","ns":"clojure.math"},"_id":"6550cbe469fbcc0c22617456"},{"created-at":1699793897626,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"tanh","ns":"clojure.math"},"_id":"6550cbe969fbcc0c22617457"}],"line":374,"examples":[{"updated-at":1701446861487,"created-at":1701446861487,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":";; ;; For a cable hanging between two points, 5m apart, let's calculate the\n;; ;; length of that cable. We also need to know the \"sag parameter\", which is\n;; ;; mainly determined by the tension in the cable and its density. The formula\n;; ;; is L = 2a⋅sinh(x/2a), where L is cable length, a is the sag parameter, and\n;; ;; x is the the distance between the points…\n(let [hanging-span 5\n a 2.8] ; a rough estimate, under ideal conditions\n (* 2 a (math/sinh (/ hanging-span (* 2 a)))))\n;; => 5.691316366972261","_id":"656a04cd69fbcc0c22617464"},{"updated-at":1701446911771,"created-at":1701446911771,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":";; java.lang.Math, and therefore clojure.math, doesn't have a hyperbolic\n;; arcsine function, but we can implement a simple version like so…\n(defn asinh\n \"asinh(x) = log(2⋅x + 1/(√(x² + 1) + x))\"\n [x]\n (math/log (+ (* 2 x)\n (/ 1 (+ x (math/sqrt (inc (* x x))))))))","_id":"656a04ff69fbcc0c22617465"}],"notes":null,"arglists":["x"],"doc":"Returns the hyperbolic sine of x, (e^x - e^-x)/2.\n If x is ##NaN => ##NaN\n If x is ##Inf or ##-Inf or zero => x\n See: https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#sinh-double-","library-url":"https://github.com/clojure/clojure","href":"/clojure.math/sinh"},{"added":"1.11","ns":"clojure.math","name":"rint","file":"clojure/math.clj","type":"function","column":1,"see-alsos":[{"created-at":1699632297676,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"round","ns":"clojure.math"},"_id":"654e54a969fbcc0c22617443"}],"line":222,"examples":[{"updated-at":1699632289908,"created-at":1699632289908,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":";; The `r` in `rint` stands for \"round\" not \"random\"\n;; and it returns a double, not an int…\n\n(math/rint 10.5)\n;; => 10.0\n\n(math/rint 11.5)\n;; => 12.0","_id":"654e54a169fbcc0c22617442"}],"notes":null,"arglists":["a"],"doc":"Returns the double closest to a and equal to a mathematical integer.\n If two values are equally close, return the even one.\n If a is ##NaN or ##Inf or ##-Inf or zero => a\n See: https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#rint-double-","library-url":"https://github.com/clojure/clojure","href":"/clojure.math/rint"},{"added":"1.11","ns":"clojure.math","name":"ulp","file":"clojure/math.clj","type":"function","column":1,"see-alsos":null,"line":351,"examples":[{"updated-at":1701711050440,"created-at":1701711050440,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":"(def a (/ 3.0 10.0))\na ;; => 0.3\n(def b (+ 0.1 0.2))\nb ;; => 0.30000000000000004\n;; This is famous enough to have its own website: 0.30000000000000004.com\n\n(defn close-enough? [a b]\n (<= (abs (- a b))\n (math/ulp a)))\n\n(close-enough? a b)\n;; => true\n\n;; I.e. it's a useful way to determine if differences are within the bounds of\n;; floating-point precision.","_id":"656e0cca69fbcc0c22617479"}],"notes":null,"arglists":["d"],"doc":"Returns the size of an ulp (unit in last place) for d.\n If d is ##NaN => ##NaN\n If d is ##Inf or ##-Inf => ##Inf\n If d is zero => Double/MIN_VALUE\n If d is +/- Double/MAX_VALUE => 2^971\n See: https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#ulp-double-","library-url":"https://github.com/clojure/clojure","href":"/clojure.math/ulp"},{"added":"1.11","ns":"clojure.math","name":"sin","file":"clojure/math.clj","type":"function","column":1,"see-alsos":[{"created-at":1699793823077,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"cos","ns":"clojure.math"},"_id":"6550cb9f69fbcc0c22617450"},{"created-at":1699793831152,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"tan","ns":"clojure.math"},"_id":"6550cba769fbcc0c22617451"}],"line":42,"examples":[{"updated-at":1699793817293,"created-at":1699793817293,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":";; Let's find the other side lengths of a right-angled triangle, where we\n;; know an acute angle, O and the hypotenuse, h…\n(let [O (math/to-radians 29.0)\n h 19\n ;; The formula we need for the opposite is o = sin(O)⋅h, or in Clojure:\n o (* (math/sin O) h)\n ;; We can use a = sin(A)·h to get the 3rd side length:\n A (- (/ math/PI 2) O)\n a (* (math/sin A) h)]\n ;; And return the dimensions, and the angles in degrees:\n {:o o, :h h, :a a\n :O 29.0, :H 90.0 :A (math/to-degrees A)})\n;; => {:o 9.211382784680405,\n;; :h 19,\n;; :a 16.61777443564852,\n;; :O 29.0,\n;; :H 90.0,\n;; :A 61.0}","_id":"6550cb9969fbcc0c2261744f"}],"notes":null,"arglists":["a"],"doc":"Returns the sine of an angle.\n If a is ##NaN, ##-Inf, ##Inf => ##NaN\n If a is zero => zero with the same sign as a\n See: https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#sin-double-","library-url":"https://github.com/clojure/clojure","href":"/clojure.math/sin"},{"added":"1.11","ns":"clojure.math","name":"increment-exact","file":"clojure/math.clj","type":"function","column":1,"see-alsos":[{"created-at":1698942984370,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"inc","ns":"clojure.core"},"_id":"6543d00869fbcc0c22617422"},{"created-at":1698942992022,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"decrement-exact","ns":"clojure.math"},"_id":"6543d01069fbcc0c22617423"}],"line":304,"examples":[{"updated-at":1698942970145,"created-at":1698942970145,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":";; `inc` uses incrementExact for longs under the hood, so these are the same:\n(inc Long/MAX_VALUE)\n(math/increment-exact Long/MAX_VALUE)\n;; => Execution error (ArithmeticException) at java.lang.Math/incrementExact (Math.java:1042).\n;; long overflow\n\n;; Doubles and floats are coerced to longs…\n(math/increment-exact Double/MAX_VALUE)\n;; => Execution error (IllegalArgumentException) at…\n;; Value out of range for long: 1.7976931348623157E308\n\n;; Basically the same as:\n(inc (long Double/MAX_VALUE))\n;; => Execution error (IllegalArgumentException) at…\n;; Value out of range for long: 1.7976931348623157E308\n\n;; Unlike inc alone, which exhibits this curious (but well documented) behaviour…\n(inc Double/MAX_VALUE)\n;; => 1.7976931348623157E308","_id":"6543cffa69fbcc0c22617421"}],"notes":null,"arglists":["a"],"doc":"Returns a incremented by 1, throws ArithmeticException on overflow.\n See: https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#incrementExact-long-","library-url":"https://github.com/clojure/clojure","href":"/clojure.math/increment-exact"},{"added":"1.11","ns":"clojure.math","name":"random","file":"clojure/math.clj","type":"function","column":1,"see-alsos":[{"created-at":1699631056056,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"rand","ns":"clojure.core"},"_id":"654e4fd069fbcc0c22617441"}],"line":267,"examples":[{"updated-at":1699631049630,"created-at":1699631049630,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":";; clojure.core/rand calls this directly with no args, so…\n(rand)\n;; => 0.20968475424191757\n;; …and…\n(math/random)\n;; => 0.02184624324577189\n;; …are exactly the same, although you couldn't know that emperically\n\n;; So I can't think of a single reason you would ever use this","_id":"654e4fc969fbcc0c22617440"}],"notes":null,"arglists":[""],"doc":"Returns a positive double between 0.0 and 1.0, chosen pseudorandomly with\n approximately random distribution.\n See: https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#random--","library-url":"https://github.com/clojure/clojure","href":"/clojure.math/random"},{"added":"1.11","ns":"clojure.math","name":"floor-div","file":"clojure/math.clj","type":"function","column":1,"see-alsos":[{"created-at":1698706192455,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"quot","ns":"clojure.core"},"_id":"6540331069fbcc0c2261740d"}],"line":331,"examples":[{"updated-at":1698706184775,"created-at":1698706184775,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":";; Docstring's mention of \"as opposed to zero\" is comparing with integer division\n\n;; Looks the same for args with the same sign:\n(math/floor-div 10 3)\n;; => 3\n(quot 10 3)\n;; => 3\n\n;; But shows the difference between rounding towards ##-Inf, and truncating\n;; (towards zero) when signs differ:\n(math/floor-div 10 -3)\n;; => -4\n(quot 10 -3)\n;; => -3\n\n;; Note, floor-div expects (and coerces to) longs before division, whereas quot\n;; casts afterwards…\n(math/floor-div 10 3.8)\n;; => 3\n(quot 10 3.8)\n;; => 2.0","_id":"6540330869fbcc0c2261740c"}],"notes":null,"arglists":["x y"],"doc":"Integer division that rounds to negative infinity (as opposed to zero).\n The special case (floorDiv Long/MIN_VALUE -1) overflows and returns Long/MIN_VALUE.\n See: https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#floorDiv-long-long-","library-url":"https://github.com/clojure/clojure","href":"/clojure.math/floor-div"},{"added":"1.11","ns":"clojure.math","name":"signum","file":"clojure/math.clj","type":"function","column":1,"see-alsos":null,"line":364,"examples":[{"updated-at":1699709892510,"created-at":1699709892510,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":"(math/signum 42.0)\n;; => 1.0\n\n(math/signum -42.0)\n;; => -1.0\n\n(math/signum 0.0)\n;; => 0.0\n\n(math/signum -0.0)\n;; => -0.0\n\n(math/signum ##NaN)\n;; => ##NaN","_id":"654f83c469fbcc0c2261744a"}],"notes":null,"arglists":["d"],"doc":"Returns the signum function of d - zero for zero, 1.0 if >0, -1.0 if <0.\n If d is ##NaN => ##NaN\n See: https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#signum-double-","library-url":"https://github.com/clojure/clojure","href":"/clojure.math/signum"},{"added":"1.2","ns":"clojure.pprint","name":"pprint","file":"clojure/pprint/pprint_base.clj","type":"function","column":1,"see-alsos":[{"created-at":1329988989000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.pprint","name":"pp","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e21"},{"created-at":1331448999000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.pprint","name":"print-table","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e22"},{"created-at":1486959495016,"author":{"login":"delonnewman","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10404?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"prn","ns":"clojure.core"},"_id":"58a13387e4b01f4add58fe4e"},{"created-at":1486959503388,"author":{"login":"delonnewman","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10404?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"prn-str","ns":"clojure.core"},"_id":"58a1338fe4b01f4add58fe4f"},{"created-at":1486959509922,"author":{"login":"delonnewman","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10404?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"pr","ns":"clojure.core"},"_id":"58a13395e4b01f4add58fe50"},{"created-at":1486959527438,"author":{"login":"delonnewman","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10404?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"pr-str","ns":"clojure.core"},"_id":"58a133a7e4b01f4add58fe51"},{"created-at":1518042875271,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"pprint-tab","ns":"clojure.pprint"},"_id":"5a7b7efbe4b0316c0f44f8ae"},{"created-at":1694190228276,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"*print-miser-width*","ns":"clojure.pprint"},"_id":"64fb4a94e4b08cf8563f4bf4"},{"created-at":1694190322152,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"*print-right-margin*","ns":"clojure.pprint"},"_id":"64fb4af2e4b08cf8563f4bf5"}],"line":241,"examples":[{"author":{"login":"nipra","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/142529?v=3"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"geofffilippi","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/caad97b26450a04c6925249cda76fd74?r=PG&default=identicon"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"},{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"}],"body":"(def big-map (zipmap \n [:a :b :c :d :e] \n (repeat \n (zipmap [:a :b :c :d :e] \n (take 5 (range))))))\n;;=> #'user/big-map\n\nbig-map\n;;=> {:a {:a 0, :b 1, :c 2, :d 3, :e 4}, :b {:a 0, :b 1, :c 2, :d 3, :e 4}, :c {:a 0, :b 1, :c 2, :d 3, :e 4}, :d {:a 0, :b 1, :c 2, :d 3, :e 4}, :e {:a 0, :b 1, :c 2, :d 3, :e 4}}\n\n(clojure.pprint/pprint big-map)\n;; {:e {:e 4, :d 3, :c 2, :b 1, :a 0},\n;; :d {:e 4, :d 3, :c 2, :b 1, :a 0},\n;; :c {:e 4, :d 3, :c 2, :b 1, :a 0},\n;; :b {:e 4, :d 3, :c 2, :b 1, :a 0},\n;; :a {:e 4, :d 3, :c 2, :b 1, :a 0}}\n;; nil","created-at":1279160964000,"updated-at":1536169383689,"_id":"542692d0c026201cdc326ec5"},{"body":";; suppose you want to pretty print to a file.\n(clojure.pprint/pprint *map* (clojure.java.io/writer \"foo.txt\"))\n;; writes the contents of *map* to a file named 'foo.txt'","author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"},"created-at":1435609992368,"updated-at":1435609992368,"_id":"5591ab88e4b05f167dcf2345"},{"updated-at":1449436011404,"created-at":1449436011404,"author":{"login":"mrzor","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/54230?v=3"},"body":";; pprint into a string using with-out-str\n(with-out-str (clojure.pprint/pprint {:x 1 :y -1}))\n;; => \"{:x 1, :y -1}\\n\"\n\n;; pprint into a string using StringWriter\n(let [out (java.io.StringWriter.)]\n (clojure.pprint/pprint {:a 1 :b 2} out)\n (clojure.pprint/pprint {:c 3 :d 4} out)\n (.toString out))\n;; => \"{:a 1, :b 2}\\n{:c 3, :d 4}\\n\"\n","_id":"5664a36be4b09a2675a0ba71"},{"updated-at":1510915362495,"created-at":1510915362495,"author":{"login":"ibercode","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/31028993?v=4"},"body":";;how to use it with :require and :use\n\n;; :require \n(ns example.pprinter\n (:require [clojure.pprint :as pp]))\n\n(def myname \"John Smith\")\n(pp/pprint myname)\n\n--------------\n\n;;:use\n(ns example.pprinter\n (:use clojure.pprint))\n\n(def myname \"John Smith\")\n(pprint myname)","_id":"5a0ebd22e4b0a08026c48cbb"},{"editors":[{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"}],"body":";; get Clojure snippets to print nicely\n(require '[clojure.pprint :as p])\n\n(def lost-formatting \n \"(defn op [sel] (condp = sel :plus + :minus - :mult * \n :div / :rem rem :quot quot :mod mod))\")\n\n(p/with-pprint-dispatch\n p/code-dispatch\n (p/pprint \n (clojure.edn/read-string lost-formatting)))\n\n;; (defn op [sel]\n;; (condp = sel\n;; :plus +\n;; :minus -\n;; :mult *\n;; :div /\n;; :rem rem\n;; :quot quot\n;; :mod mod))","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"},"created-at":1536495212985,"updated-at":1536495430265,"_id":"5b950e6ce4b00ac801ed9e8a"},{"updated-at":1662581080334,"created-at":1662581080334,"author":{"login":"djblue","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1986211?v=4"},"body":";; pprint with metadata, requires Clojure >= 1.10.2\n(require '[clojure.pprint :as p])\n(binding [*print-meta* true]\n (p/pprint ^{:hello :world} {}))","_id":"6318f958e4b0b1e3652d765f"}],"notes":[{"body":"When using Clojure from the REPL, you don't need to specify `clojure.pprint` to use `pprint` or `pp`. At the REPL `(clojure.pprint x)` is equivalent to `(pprint x)`.","created-at":1536169564110,"updated-at":1536494583495,"author":{"avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"},"_id":"5b90165ce4b00ac801ed9e88"}],"arglists":["object","object writer"],"doc":"Pretty print object to the optional output writer. If the writer is not provided, \nprint the object to the currently bound value of *out*.","library-url":"https://github.com/clojure/clojure","href":"/clojure.pprint/pprint"},{"added":"1.2","ns":"clojure.pprint","name":"simple-dispatch","file":"clojure/pprint/dispatch.clj","type":"function","column":1,"see-alsos":[{"created-at":1683111333271,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"set-pprint-dispatch","ns":"clojure.pprint"},"_id":"64523da5e4b08cf8563f4bb1"},{"created-at":1683111339705,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"with-pprint-dispatch","ns":"clojure.pprint"},"_id":"64523dabe4b08cf8563f4bb2"}],"line":174,"examples":null,"notes":null,"arglists":["object"],"doc":"The pretty print dispatch function for simple data structure format.","library-url":"https://github.com/clojure/clojure","href":"/clojure.pprint/simple-dispatch"},{"added":"1.2","ns":"clojure.pprint","name":"get-pretty-writer","file":"clojure/pprint/cl_format.clj","type":"function","column":1,"see-alsos":null,"line":1203,"examples":null,"notes":null,"arglists":["writer"],"doc":"Returns the java.io.Writer passed in wrapped in a pretty writer proxy, unless it's \nalready a pretty writer. Generally, it is unnecessary to call this function, since pprint,\nwrite, and cl-format all call it if they need to. However if you want the state to be \npreserved across calls, you will want to wrap them with this. \n\nFor example, when you want to generate column-aware output with multiple calls to cl-format, \ndo it like in this example:\n\n (defn print-table [aseq column-width]\n (binding [*out* (get-pretty-writer *out*)]\n (doseq [row aseq]\n (doseq [col row]\n (cl-format true \"~4D~7,vT\" col column-width))\n (prn))))\n\nNow when you run:\n\n user> (print-table (map #(vector % (* % %) (* % % %)) (range 1 11)) 8)\n\nIt prints a table of squares and cubes for the numbers from 1 to 10:\n\n 1 1 1 \n 2 4 8 \n 3 9 27 \n 4 16 64 \n 5 25 125 \n 6 36 216 \n 7 49 343 \n 8 64 512 \n 9 81 729 \n 10 100 1000","library-url":"https://github.com/clojure/clojure","href":"/clojure.pprint/get-pretty-writer"},{"added":"1.2","ns":"clojure.pprint","name":"*print-suppress-namespaces*","file":"clojure/pprint/pprint_base.clj","type":"var","column":1,"see-alsos":null,"dynamic":true,"line":72,"examples":[{"author":{"login":"philos99","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1de5617efb013ca7c9cf8e5646818ffa?r=PG&default=identicon"},"editors":[{"login":"philos99","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1de5617efb013ca7c9cf8e5646818ffa?r=PG&default=identicon"}],"body":"(require '[clojure.pprint :as pp])\n\n(defmacro plus [n1 n2]\n `(+ ~n1 ~n2))\n\n(macroexpand-1 '(plus 3 4))\n;=> (clojure.core/+ 3 4)\n\n\n(alter-var-root #'pp/*print-suppress-namespaces* (constantly true))\n\n(macroexpand-1 '(plus 3 4))\n;=> (clojure.core/+ 3 4)\n\n;; comes into effect only in pprint.\n(pp/pprint (macroexpand-1 '(plus 3 4)))\n;=> (+ 3 4)\n","created-at":1397944252000,"updated-at":1397944707000,"_id":"542692d6c026201cdc3270ec"}],"notes":null,"arglists":[],"doc":"Don't print namespaces with symbols. This is particularly useful when \npretty printing the results of macro expansions","library-url":"https://github.com/clojure/clojure","href":"/clojure.pprint/*print-suppress-namespaces*"},{"added":"1.2","ns":"clojure.pprint","name":"*print-pretty*","file":"clojure/pprint/pprint_base.clj","type":"var","column":1,"see-alsos":null,"dynamic":true,"line":30,"examples":[{"updated-at":1533810134347,"created-at":1533810134347,"author":{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"},"body":"(binding [clojure.pprint/*print-right-margin* 5]\n\n ;; Compare the two outputs below:\n\n (binding [clojure.pprint/*print-pretty* true]\n (clojure.pprint/write (range 3)))\n ; Prints:\n ; (0\n ; 1\n ; 2)\n\n (binding [clojure.pprint/*print-pretty* false]\n (clojure.pprint/write (range 3)))\n ; Prints:\n ; (0 1 2)\n)","_id":"5b6c15d6e4b00ac801ed9e48"}],"notes":[{"author":{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"},"updated-at":1533810194451,"created-at":1533810194451,"body":"`clojure.pprint/pprint` always sets `*print-pretty*` to `true` internally, so changing it has no effect if you only use `pprint` and not `write`.","_id":"5b6c1612e4b00ac801ed9e49"}],"arglists":[],"doc":"Bind to true if you want write to use pretty printing","library-url":"https://github.com/clojure/clojure","href":"/clojure.pprint/*print-pretty*"},{"added":"1.2","ns":"clojure.pprint","name":"*print-pprint-dispatch*","file":"clojure/pprint/pprint_base.clj","type":"var","column":1,"see-alsos":[{"created-at":1619968276432,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/20086?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"with-pprint-dispatch","ns":"clojure.pprint"},"_id":"608ec114e4b0b1e3652d74ee"}],"dynamic":true,"line":34,"examples":[{"updated-at":1619968239057,"created-at":1619968239057,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/20086?v=4"},"body":"(require '[clojure.pprint :as pprint])\n\n(def condp-statement\n '(condp = x\n 1 \"one\" 2 \"two\" 3 \"three\"\n 4 \"four\" 5 \"five\" 6 \"six\" :else :none))\n\n(binding [pprint/*print-pprint-dispatch* pprint/code-dispatch]\n (pprint/pprint condp-statement))\n;; (condp = x\n;; 1 \"one\"\n;; 2 \"two\"\n;; 3 \"three\"\n;; 4 \"four\"\n;; 5 \"five\"\n;; 6 \"six\"\n;; :else :none)\n","_id":"608ec0efe4b0b1e3652d74ed"}],"notes":null,"arglists":[],"doc":"The pretty print dispatch function. Use with-pprint-dispatch or set-pprint-dispatch\nto modify.","library-url":"https://github.com/clojure/clojure","href":"/clojure.pprint/*print-pprint-dispatch*"},{"added":"1.2","ns":"clojure.pprint","name":"pprint-newline","file":"clojure/pprint/pprint_base.clj","type":"function","column":1,"see-alsos":null,"line":329,"examples":null,"notes":null,"arglists":["kind"],"doc":"Print a conditional newline to a pretty printing stream. kind specifies if the \nnewline is :linear, :miser, :fill, or :mandatory. \n\nThis function is intended for use when writing custom dispatch functions.\n\nOutput is sent to *out* which must be a pretty printing writer.","library-url":"https://github.com/clojure/clojure","href":"/clojure.pprint/pprint-newline"},{"added":"1.2","ns":"clojure.pprint","name":"code-dispatch","file":"clojure/pprint/dispatch.clj","type":"function","column":1,"see-alsos":[{"created-at":1683111298261,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"set-pprint-dispatch","ns":"clojure.pprint"},"_id":"64523d82e4b08cf8563f4baf"},{"created-at":1683111307405,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"with-pprint-dispatch","ns":"clojure.pprint"},"_id":"64523d8be4b08cf8563f4bb0"}],"line":476,"examples":null,"notes":null,"arglists":["object"],"doc":"The pretty print dispatch function for pretty printing Clojure code.","library-url":"https://github.com/clojure/clojure","href":"/clojure.pprint/code-dispatch"},{"added":"1.3","ns":"clojure.pprint","name":"print-length-loop","file":"clojure/pprint/pprint_base.clj","type":"macro","column":1,"see-alsos":null,"line":391,"examples":[{"updated-at":1682635931128,"created-at":1682635931128,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":"(set! *print-length* 5)\n\n(print-length-loop [a 0]\n (pprint a)\n (recur (inc a)))\n;; 0\n;; 1\n;; 2\n;; 3\n;; 4\n;; ...\n;; => nil","_id":"644afc9be4b08cf8563f4ba2"}],"macro":true,"notes":null,"arglists":["bindings & body"],"doc":"A version of loop that iterates at most *print-length* times. This is designed \nfor use in pretty-printer dispatch functions.","library-url":"https://github.com/clojure/clojure","href":"/clojure.pprint/print-length-loop"},{"added":"1.2","ns":"clojure.pprint","name":"pprint-tab","file":"clojure/pprint/pprint_base.clj","type":"function","column":1,"see-alsos":null,"line":356,"examples":null,"notes":null,"arglists":["kind colnum colinc"],"doc":"Tab at this point in the pretty printing stream. kind specifies whether the tab\nis :line, :section, :line-relative, or :section-relative. \n\nColnum and colinc specify the target column and the increment to move the target\nforward if the output is already past the original target.\n\nThis function is intended for use when writing custom dispatch functions.\n\nOutput is sent to *out* which must be a pretty printing writer.\n\nTHIS FUNCTION IS NOT YET IMPLEMENTED.","library-url":"https://github.com/clojure/clojure","href":"/clojure.pprint/pprint-tab"},{"added":"1.2","ns":"clojure.pprint","name":"pprint-logical-block","file":"clojure/pprint/pprint_base.clj","type":"macro","column":1,"see-alsos":null,"line":302,"examples":null,"macro":true,"notes":null,"arglists":["options* body"],"doc":"Execute the body as a pretty printing logical block with output to *out* which \nmust be a pretty printing writer. When used from pprint or cl-format, this can be \nassumed. \n\nThis function is intended for use when writing custom dispatch functions.\n\nBefore the body, the caller can optionally specify options: :prefix, :per-line-prefix, \nand :suffix.","library-url":"https://github.com/clojure/clojure","href":"/clojure.pprint/pprint-logical-block"},{"added":"1.3","ns":"clojure.pprint","name":"print-table","file":"clojure/pprint/print_table.clj","type":"function","column":1,"see-alsos":[{"created-at":1331448986000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.pprint","name":"pprint","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e86"},{"created-at":1331449122000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.inspector","name":"inspect-table","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e87"}],"line":11,"examples":[{"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4","account-source":"github","login":"phreed"},{"login":"bkovitz","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/4142015?v=4"}],"body":"(use 'clojure.pprint)\n;=> nil\n\n;; By default, columns are in the order returned by (keys (first rows))\n(print-table [{:a 1 :b 2 :c 3} {:b 5 :a 7 :c \"dog\"}])\n;; =============\n;; :a | :c | :b\n;; =============\n;; 1 | 3 | 2 \n;; 7 | dog | 5 \n;; =============\n;=> nil\n\n;; If there are keys not in the first row, and/or you want to specify only\n;; some, or in a particular order, give the desired keys as the first arg.\n(print-table [:b :a] [{:a 1 :b 2 :c 3} {:b 5 :a 7 :c \"dog\"}])\n;; =======\n;; :b | :a\n;; =======\n;; 2 | 1 \n;; 5 | 7 \n;; =======\n;=> nil\n","created-at":1329889278000,"updated-at":1516548290588,"_id":"542692d6c026201cdc3270f1"},{"updated-at":1507762324788,"created-at":1329889427000,"body":"(use 'clojure.pprint 'clojure.reflect)\n;=> nil\n(def x (:members (reflect clojure.lang.BigInt)))\n;=> #'user/x\n(print-table [:name :type :flags] (sort-by :name x))\n;; ======================================================================\n;; :name | :type | :flags \n;; ======================================================================\n;; ONE | clojure.lang.BigInt | #{:static :public :final}\n;; ZERO | clojure.lang.BigInt | #{:static :public :final}\n;; add | | #{:public} \n;; bipart | java.math.BigInteger | #{:public :final} \n;; bitLength | | #{:public} \n;; byteValue | | #{:public} \n;; clojure.lang.BigInt | | #{:private} \n;; doubleValue | | #{:public} \n;; equals | | #{:public} \n;; floatValue | | #{:public} \n;; fromBigInteger | | #{:static :public} \n;; fromLong | | #{:static :public} \n;; hashCode | | #{:public} \n;; intValue | | #{:public} \n;; longValue | | #{:public} \n;; lpart | long | #{:public :final} \n;; lt | | #{:public} \n;; multiply | | #{:public} \n;; quotient | | #{:public} \n;; remainder | | #{:public} \n;; shortValue | | #{:public} \n;; toBigInteger | | #{:public} \n;; toString | | #{:public} \n;; valueOf | | #{:static :public} \n;; ======================================================================\n;=> nil\n","editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3","account-source":"github","login":"jafingerhut"},"_id":"542692d6c026201cdc3270f3"},{"updated-at":1573569597228,"created-at":1573569597228,"author":{"login":"l3nz","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/1101849?v=4"},"body":"; Redirect print-table to a string.\n\n(binding [*out* (java.io.StringWriter.)]\n (clojure.pprint/print-table [{:a 1 :b 2}])\n (.toString *out*))\n\n\n=> \"\\n| :a | :b |\\n|----+----|\\n| 1 | 2 |\\n\"\n\n","_id":"5dcac43de4b0ca44402ef7db"},{"updated-at":1579276290470,"created-at":1579276290470,"author":{"login":"malesch","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/114063?v=4"},"body":"; Another way to redirect print-table to a string\n\n(with-out-str (clojure.pprint/print-table [{:a 1 :b 2}]))\n\n=> \"\\n| :a | :b |\\n|----+----|\\n| 1 | 2 |\\n\"","_id":"5e21d802e4b0ca44402ef819"},{"updated-at":1731496497140,"created-at":1731496497140,"author":{"login":"Biserkov","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/49756?v=4"},"body":"; Redirect print-table to a file.\n\n(binding [*out* (clojure.java.io/writer \"foo.txt\")]\n (clojure.pprint/print-table [{:a 1 :b 2}]))","_id":"67348a3169fbcc0c22617510"}],"notes":null,"arglists":["ks rows","rows"],"doc":"Prints a collection of maps in a textual table. Prints table headings\n ks, and then a line of output for each row, corresponding to the keys\n in ks. If ks are not specified, use the keys of the first item in rows.","library-url":"https://github.com/clojure/clojure","href":"/clojure.pprint/print-table"},{"added":"1.2","ns":"clojure.pprint","name":"pp","file":"clojure/pprint/pprint_base.clj","type":"macro","column":1,"see-alsos":[{"created-at":1518042853743,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"pprint","ns":"clojure.pprint"},"_id":"5a7b7ee5e4b0316c0f44f8ad"}],"line":254,"examples":[{"updated-at":1285501102000,"created-at":1279160860000,"body":"user=> (zipmap \n [:a :b :c :d :e] \n (repeat \n (zipmap \n [:a :b :c :d :e] \n (take 5 (range)))))\n{:e {:e 4, :d 3, :c 2, :b 1, :a 0}, :d {:e 4, :d 3, :c 2, :b 1, :a 0}, :c {:e 4, :d 3, :c 2, :b 1, :a 0}, :b {:e 4, :d 3, :c 2, :b 1, :a 0}, :a {:e 4, :d 3, :c 2, :b 1, :a 0}}\n\nuser=> (clojure.pprint/pp)\n{:e {:e 4, :d 3, :c 2, :b 1, :a 0},\n :d {:e 4, :d 3, :c 2, :b 1, :a 0},\n :c {:e 4, :d 3, :c 2, :b 1, :a 0},\n :b {:e 4, :d 3, :c 2, :b 1, :a 0},\n :a {:e 4, :d 3, :c 2, :b 1, :a 0}}\nnil\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/142529?v=3","account-source":"github","login":"nipra"},"_id":"542692d0c026201cdc326ec8"}],"macro":true,"notes":[{"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"updated-at":1536169628718,"created-at":1536169628718,"body":"When using Clojure from the REPL, you don't need to specify `clojure.pprint` to use `pp` or `pprint`. So at the REPL `(clojure.pp)` is equivalent to `(pp)`.","_id":"5b90169ce4b00ac801ed9e89"}],"arglists":[""],"doc":"A convenience macro that pretty prints the last thing output. This is\nexactly equivalent to (pprint *1).","library-url":"https://github.com/clojure/clojure","href":"/clojure.pprint/pp"},{"added":"1.2","ns":"clojure.pprint","name":"set-pprint-dispatch","file":"clojure/pprint/pprint_base.clj","type":"function","column":1,"see-alsos":[{"created-at":1683111037007,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"*print-pprint-dispatch*","ns":"clojure.pprint"},"_id":"64523c7de4b08cf8563f4bad"}],"line":260,"examples":[{"updated-at":1683111221732,"created-at":1683111221732,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":"(require '[clojure.pprint :as pprint])\n\n(def condp-statement\n '(condp = x\n 1 \"one\" 2 \"two\" 3 \"three\"\n 4 \"four\" 5 \"five\" 6 \"six\" :else :none))\n\n(pprint/pprint condp-statement)\n;; (condp\n;; =\n;; x\n;; 1\n;; \"one\"\n;; 2\n;; \"two\"\n;; 3\n;; \"three\"\n;; 4\n;; \"four\"\n;; 5\n;; \"five\"\n;; 6\n;; \"six\"\n;; :else\n;; :none)\n\n(pprint/set-pprint-dispatch pprint/code-dispatch)\n\n(pprint/pprint condp-statement)\n;; (condp = x\n;; 1 \"one\"\n;; 2 \"two\"\n;; 3 \"three\"\n;; 4 \"four\"\n;; 5 \"five\"\n;; 6 \"six\"\n;; :else :none)","_id":"64523d35e4b08cf8563f4bae"}],"notes":null,"arglists":["function"],"doc":"Set the pretty print dispatch function to a function matching (fn [obj] ...)\nwhere obj is the object to pretty print. That function will be called with *out* set\nto a pretty printing writer to which it should do its printing.\n\nFor example functions, see simple-dispatch and code-dispatch in \nclojure.pprint.dispatch.clj.","library-url":"https://github.com/clojure/clojure","href":"/clojure.pprint/set-pprint-dispatch"},{"added":"1.2","ns":"clojure.pprint","name":"fresh-line","file":"clojure/pprint/cl_format.clj","type":"function","column":1,"see-alsos":null,"line":1245,"examples":null,"notes":null,"arglists":[""],"doc":"Make a newline if *out* is not already at the beginning of the line. If *out* is\nnot a pretty writer (which keeps track of columns), this function always outputs a newline.","library-url":"https://github.com/clojure/clojure","href":"/clojure.pprint/fresh-line"},{"added":"1.2","ns":"clojure.pprint","name":"formatter-out","file":"clojure/pprint/cl_format.clj","type":"macro","column":1,"see-alsos":[{"created-at":1683117747988,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"formatter","ns":"clojure.pprint"},"_id":"645256b3e4b08cf8563f4bb6"}],"line":1936,"examples":[{"updated-at":1683117741775,"created-at":1683117741775,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":"(def my-formatter (pprint/formatter-out \"~:d\"))\n\n(my-formatter 123456)\n;; 123,456\n;; => nil","_id":"645256ade4b08cf8563f4bb5"}],"macro":true,"notes":null,"arglists":["format-in"],"doc":"Makes a function which can directly run format-in. The function is\nfn [& args] ... and returns nil. This version of the formatter macro is\ndesigned to be used with *out* set to an appropriate Writer. In particular,\nthis is meant to be used as part of a pretty printer dispatch method.\n\nformat-in can be either a control string or a previously compiled format.","library-url":"https://github.com/clojure/clojure","href":"/clojure.pprint/formatter-out"},{"added":"1.2","ns":"clojure.pprint","name":"formatter","file":"clojure/pprint/cl_format.clj","type":"macro","column":1,"see-alsos":[{"created-at":1683117686117,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"formatter-out","ns":"clojure.pprint"},"_id":"64525676e4b08cf8563f4bb4"},{"created-at":1683389093912,"author":{"login":"josuesantos1","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/43919440?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"pprint","ns":"clojure.pprint"},"_id":"64567aa5e4b08cf8563f4bba"}],"line":1916,"examples":[{"updated-at":1683117677315,"created-at":1683117677315,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":"(def my-formatter (pprint/formatter \"~:d\"))\n\n(with-open [stream (java.io.StringWriter.)]\n (my-formatter stream 123456)\n (str stream))\n;; => \"123,456\"","_id":"6452566de4b08cf8563f4bb3"},{"updated-at":1683490074327,"created-at":1683128227191,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":";; Compiling the control string can have significant performance benefits…\n\n(time\n (with-open [stream (java.io.StringWriter.)]\n (doseq [x (range 1e5)]\n (pprint/cl-format stream \"Number is ~:d \" x))))\n;; Elapsed time: 5100.348801 msecs\n\n(def my-formatter (pprint/formatter \"Number is ~:d \"))\n\n(time\n (with-open [stream (java.io.StringWriter.)]\n (doseq [x (range 1e5)]\n (my-formatter stream x))))\n;; Elapsed time: 3620.067511 msecs\n\n;; But still not a patch on `format` for this example…\n\n(time\n (with-open [stream (java.io.StringWriter.)]\n (doseq [x (range 1e5)]\n (.write stream (format \"Number is %,d \" x)))))\n;; \"Elapsed time: 444.501672 msecs\"","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4","account-source":"github","login":"tomdl89"}],"_id":"64527fa3e4b08cf8563f4bb8"}],"macro":true,"notes":null,"arglists":["format-in"],"doc":"Makes a function which can directly run format-in. The function is\nfn [stream & args] ... and returns nil unless the stream is nil (meaning \noutput to a string) in which case it returns the resulting string.\n\nformat-in can be either a control string or a previously compiled format.","library-url":"https://github.com/clojure/clojure","href":"/clojure.pprint/formatter"},{"added":"1.2","ns":"clojure.pprint","name":"pprint-indent","file":"clojure/pprint/pprint_base.clj","type":"function","column":1,"see-alsos":null,"line":341,"examples":null,"notes":null,"arglists":["relative-to n"],"doc":"Create an indent at this point in the pretty printing stream. This defines how \nfollowing lines are indented. relative-to can be either :block or :current depending \nwhether the indent should be computed relative to the start of the logical block or\nthe current column position. n is an offset. \n\nThis function is intended for use when writing custom dispatch functions.\n\nOutput is sent to *out* which must be a pretty printing writer.","library-url":"https://github.com/clojure/clojure","href":"/clojure.pprint/pprint-indent"},{"added":"1.2","ns":"clojure.pprint","name":"*print-radix*","file":"clojure/pprint/pprint_base.clj","type":"var","column":1,"see-alsos":[{"created-at":1664286342316,"author":{"login":"sreekanthb","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1254569?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"*print-base*","ns":"clojure.pprint"},"_id":"6332fe86e4b0b1e3652d7668"}],"dynamic":true,"line":80,"examples":[{"editors":[{"login":"reborg","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/20086?v=4"}],"body":"(require '[clojure.pprint :as pprint])\n\n(binding [pprint/*print-base* 16\n pprint/*print-radix* true]\n (pprint/pprint 3405691582))\n;; #xcafebabe\n","author":{"avatar-url":"https://avatars.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"},"created-at":1620057785572,"updated-at":1620333810711,"_id":"60901eb9e4b0b1e3652d74f3"}],"notes":null,"arglists":[],"doc":"Print a radix specifier in front of integers and rationals. If *print-base* is 2, 8, \nor 16, then the radix specifier used is #b, #o, or #x, respectively. Otherwise the \nradix specifier is in the form #XXr where XX is the decimal value of *print-base* ","library-url":"https://github.com/clojure/clojure","href":"/clojure.pprint/*print-radix*"},{"added":"1.2","ns":"clojure.pprint","name":"cl-format","file":"clojure/pprint/cl_format.clj","type":"function","column":1,"see-alsos":[{"created-at":1330170813000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.core","name":"printf","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f44"},{"created-at":1330170818000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.core","name":"format","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f45"}],"line":27,"examples":[{"updated-at":1627687397697,"created-at":1332481954000,"body":";; Formatting integers, with options, in one of many bases.\n\n;; Basic Example\nuser=> (cl-format nil \"~:d\" 1234567)\n\"1,234,567\"\n\n;; First arg true sends formatted output to *out*\nuser=> (cl-format true \"~5d\\n\" 3)\n 3\nnil\n\n;; First arg nil or false causes formatted output to be returned as string\nuser=> (cl-format nil \"~5d\" 3)\n\" 3\"\n\nuser=> (cl-format nil \"Pad with leading zeros ~5,'0d\" 3)\n\"Pad with leading zeros 00003\"\n\nuser=> (cl-format nil \"Pad with leading asterisks ~5,'*d\" 3)\n\"Pad with leading asterisks ****3\"\n\n;; If there is a way to specify left-justifying a number in a single\n;; format string, please add it here. It can be done by using one\n;; cl-format invocation to get a formatted number as a string, and\n;; then use the ~a specifier on the result.\nuser=> (cl-format nil \"~15a\" (cl-format nil \"~:d\" 1234567))\n\"1,234,567 \"\n\n;; To specify left-justifying a number in a single format string, you can use:\nuser=> (cl-format nil \"~15@<~:d~>\" 1234567)\n\"1,234,567 \"\n\nuser=> (cl-format nil \"Always print the sign ~5@d\" 3)\n\"Always print the sign +3\"\n\nuser=> (cl-format nil \"Use comma group-separator every 3 digits ~12:d\" 1234567)\n\"Use comma group-separator every 3 digits 1,234,567\"\n\nuser=> (cl-format nil \"decimal ~d binary ~b octal ~o hex ~x\" 63 63 63 63)\n\"decimal 63 binary 111111 octal 77 hex 3f\"\n\nuser=> (cl-format nil \"base 7 ~7r with width and zero pad ~7,15,'0r\" 63 63)\n\"base 7 120 with width and zero pad 000000000000120\"\n\n;; No need for you to do any conversions to use cl-format with BigInt,\n;; BigInteger, or BigDecimal.\nuser=> (cl-format nil \"cl-format handles BigInts ~15d\" 12345678901234567890)\n\"cl-format handles BigInts 12345678901234567890\"\n\nuser=> (cl-format nil \"Be aware of auto-conversion ~8,'0d ~8,'0d\" 2.4 -5/4)\n\"Be aware of auto-conversion 000002.4 0000-5/4\"\n\n;; This might look like a bug, but it is actually behavior specified by the\n;; Common Lisp HyperSpec mentioned in the docs above. If you don't want that\n;; behavior (format \"%08d\" -2) might suit your purposes better.\nuser=> (cl-format nil \"~8,'0d\" -2)\n\"000000-2\"","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3","account-source":"github","login":"jafingerhut"},{"avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3","account-source":"github","login":"jafingerhut"},{"login":"coldnew","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/39703?v=3"},{"avatar-url":"https://avatars.githubusercontent.com/u/16775439?v=4","account-source":"github","login":"Okwori"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3","account-source":"github","login":"jafingerhut"},"_id":"542692d6c026201cdc3270ee"},{"body":"(let [examples [[]\n [\"Alice\"]\n [\"Alice\" \"Bob\"]\n [\"Alice\" \"Bob\" \"Charlie\"]]]\n (doseq [users examples]\n (cljs.pprint/cl-format true \"~1{~#[none~;~a~;~a and ~a~:;~@{~#[~;and ~]~a~^, ~}~]~:} ~:*~1{~#[are~;is~:;are~]~:} online\" users)))\n\n;; Prints the following:\n\nnone are online\nAlice is online\nAlice and Bob are online\nAlice, Bob, and Charlie are online\n\n;; The following guide for Common Lisp format is available here. The examples applies to Clojure as well:\n;; http://www.gigamonkeys.com/book/a-few-format-recipes.html","author":{"login":"lokedhs","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1028755?v=3"},"created-at":1432169914857,"updated-at":1432169914857,"_id":"555d2dbae4b01ad59b65f4d7"},{"editors":[{"login":"mars0i","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1836941?v=3"}],"body":";; cl-format knows what nil should look like:\nuser=> (cl-format nil \"~s\" nil)\n\"nil\"\n;; format doesn't:\nuser=> (format \"%s\" nil)\n\"null\"\n","author":{"avatar-url":"https://avatars.githubusercontent.com/u/1836941?v=3","account-source":"github","login":"mars0i"},"created-at":1437886988750,"updated-at":1437887125187,"_id":"55b46a0ce4b0080a1b79cdac"},{"updated-at":1535748237199,"created-at":1535748237199,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"body":"(def word-wrap\n [\"This\" \"sentence\" \"is\" \"too\" \"long\" \"for\" \"a\" \"small\" \"screen\"\n \"and\" \"should\" \"appear\" \"in\" \"multiple\" \"lines\" \"no\" \"longer\"\n \"than\" \"20\" \"characters\" \"each\" \".\"])\n\n(println (cl-format nil \"~{~<~%~1,20:;~A~> ~}\" word-wrap))\n;; This sentence is too\n;; long for a small\n;; screen and should\n;; appear in multiple\n;; lines no longer than\n;; 20 characters each.","_id":"5b89a88de4b00ac801ed9e7b"},{"updated-at":1586704521298,"created-at":1586704521298,"author":{"login":"jimka2001","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/6414129?v=4"},"body":"user=> (cl-format true \"~R~%\" 63)\nsixty-three\nnil\nuser=> (cl-format false \"~R\" 635464)\n\"six hundred thirty-five thousand, four hundred sixty-four\"","_id":"5e933089e4b087629b5a18d2"},{"editors":[{"login":"jimka2001","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/6414129?v=4"}],"body":";; ~ followed by newline and white space, ignores the newline and the white space\n;; it is used simply to align code.\n;; ~@ followed by newline and white space outputs the newline \n;; but ignores the white space\n;; ~& outputs a newline unless already at beginning of line\n\n;; The following (using clojure.test) formats 5 lines of output\n;; each starting at the left margin. \n;; The initial ~&~ starts a newline if necessary and outputs \"expected\"\n;; at the left margin (without the quotes of course)\n;; The first argument, false, of cl-format, simply indicates to print\n;; to a string and return the string.\n(deftest t-type-subtypep-randomized-2\n (testing \"type subtype of union\"\n (doseq [depth (range 5)\n reps (range 200)\n :let [t1 (gns/gen-type depth)\n t2 (gns/gen-type depth)]]\n (is (= true (bdd/type-subtype? t1 (gns/create-or [t1 t2])))\n (cl-format false\n \"~&~\n expecting t1 <: (or t1 t2)~@\n t1=~A~@\n t2=~A~@\n depth=~A~@\n reps=~A\"\n t1 t2\n depth reps)))))","author":{"avatar-url":"https://avatars.githubusercontent.com/u/6414129?v=4","account-source":"github","login":"jimka2001"},"created-at":1626965634556,"updated-at":1628090795457,"_id":"60f98682e4b0b1e3652d751b"},{"editors":[{"login":"jimka2001","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/6414129?v=4"}],"body":";; cl-format can be used to force lazy sequences to be unwound.\n\n;; returns a string such as \"hello clojure.lang.LazySeq@3874d01 world\\n\"\n(format \"hello %s world\\n\" (map list '(1 2 3 4 5)))\n\n;; returns the string \"hello ((1) (2) (3) (4) (5)) world\\n\u0010\"\n(cl-format false \"hello ~A world~%\" (map list '(1 2 3 4 5)))\n","author":{"avatar-url":"https://avatars.githubusercontent.com/u/6414129?v=4","account-source":"github","login":"jimka2001"},"created-at":1627544071732,"updated-at":1627544168523,"_id":"61025a07e4b0b1e3652d7521"}],"notes":null,"arglists":["writer format-in & args"],"doc":"An implementation of a Common Lisp compatible format function. cl-format formats its\narguments to an output stream or string based on the format control string given. It \nsupports sophisticated formatting of structured data.\n\nWriter is an instance of java.io.Writer, true to output to *out* or nil to output \nto a string, format-in is the format control string and the remaining arguments \nare the data to be formatted.\n\nThe format control string is a string to be output with embedded 'format directives' \ndescribing how to format the various arguments passed in.\n\nIf writer is nil, cl-format returns the formatted result string. Otherwise, cl-format \nreturns nil.\n\nFor example:\n (let [results [46 38 22]]\n (cl-format true \"There ~[are~;is~:;are~]~:* ~d result~:p: ~{~d~^, ~}~%\" \n (count results) results))\n\nPrints to *out*:\n There are 3 results: 46, 38, 22\n\nDetailed documentation on format control strings is available in the \"Common Lisp the \nLanguage, 2nd edition\", Chapter 22 (available online at:\nhttp://www.cs.cmu.edu/afs/cs.cmu.edu/project/ai-repository/ai/html/cltl/clm/node200.html#SECTION002633000000000000000) \nand in the Common Lisp HyperSpec at \nhttp://www.lispworks.com/documentation/HyperSpec/Body/22_c.htm\n","library-url":"https://github.com/clojure/clojure","href":"/clojure.pprint/cl-format"},{"added":"1.2","ns":"clojure.pprint","name":"*print-miser-width*","file":"clojure/pprint/pprint_base.clj","type":"var","column":1,"see-alsos":[{"created-at":1620036444882,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/20086?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"write","ns":"clojure.pprint"},"_id":"608fcb5ce4b0b1e3652d74f2"},{"created-at":1694190193679,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"pprint","ns":"clojure.pprint"},"_id":"64fb4a71e4b08cf8563f4bf3"}],"dynamic":true,"line":47,"examples":[{"updated-at":1620036422897,"created-at":1620036422897,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/20086?v=4"},"body":"(require '[clojure.pprint :as pprint])\n\n;; Simple example to keep it readable, but this could\n;; be much more nested code coming from some large Clojure file\n(def nested-statement\n '(condp = x\n 1 \"one\" 2 \"two\" 3 \"three\"\n 4 \"four\" 5 \"five\" 6 \"six\"\n :else (condp = x\n 1 \"one\" 2 \"two\" 3 \"three\"\n 4 \"four\" 5 \"five\" 6 \"six\"\n :else :none)))\n\n;; Forcing a narrow right margin at 30 to illustrate the point.\n;; In reality the nesting would accumulate close to a larger margin\n;; with similar effects, leaving a lot of white space on the left.\n(binding [pprint/*print-pprint-dispatch* pprint/code-dispatch\n pprint/*print-right-margin* 30]\n (pprint/pprint nested-statement))\n\n;; (condp\n;; =\n;; x\n;; 1 \"one\"\n;; 2 \"two\"\n;; 3 \"three\"\n;; 4 \"four\"\n;; 5 \"five\"\n;; 6 \"six\"\n;; :else\n;; (condp\n;; =\n;; x\n;; 1 \"one\"\n;; 2 \"two\"\n;; 3 \"three\"\n;; 4 \"four\"\n;; 5 \"five\"\n;; 6 \"six\"\n;; :else :none))\n\n;; changing the miser width relax the pretty printer allowing to \n;; use the space better.\n(binding [pprint/*print-pprint-dispatch* pprint/code-dispatch\n pprint/*print-right-margin* 30\n pprint/*print-miser-width* 20]\n (pprint/pprint nested-statement))\n\n;; (condp = x\n;; 1 \"one\"\n;; 2 \"two\"\n;; 3 \"three\"\n;; 4 \"four\"\n;; 5 \"five\"\n;; 6 \"six\"\n;; :else (condp = x\n;; 1 \"one\"\n;; 2 \"two\"\n;; 3 \"three\"\n;; 4 \"four\"\n;; 5 \"five\"\n;; 6 \"six\"\n;; :else :none))","_id":"608fcb46e4b0b1e3652d74f1"}],"notes":null,"arglists":[],"doc":"The column at which to enter miser style. Depending on the dispatch table, \nmiser style add newlines in more places to try to keep lines short allowing for further \nlevels of nesting.","library-url":"https://github.com/clojure/clojure","href":"/clojure.pprint/*print-miser-width*"},{"added":"1.2","ns":"clojure.pprint","name":"write","file":"clojure/pprint/pprint_base.clj","type":"function","column":1,"see-alsos":[{"created-at":1536497648303,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"pprint","ns":"clojure.pprint"},"_id":"5b9517f0e4b00ac801ed9e8f"}],"line":197,"examples":[{"updated-at":1536497633749,"created-at":1536497633749,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"body":";; Same as pprint but taking configuration directives.\n(require '[clojure.pprint :as p])\n\n;; Prints the number in binary with indication of the base as \"#b\".\n(p/write 20/3 :base 2 :radix true) \n;; #b10100/11\n\n;; Pretty looking truncation of lists longer than 3.\n(p/write (range 100) :length 3) \n;; (0 1 2 ...)\n\n;; Removes namespaces from symbols when printing.\n(p/write 'clojure.core/+ :suppress-namespaces true) \n;; +\n\n;; Avoids anything beyond 10 right margin.\n(p/write [:a :b :c :d] :right-margin 10)\n;; [:a\n;; :b\n;; :c\n;; :d]\n","_id":"5b9517e1e4b00ac801ed9e8e"}],"notes":null,"arglists":["object & kw-args"],"doc":"Write an object subject to the current bindings of the printer control variables.\nUse the kw-args argument to override individual variables for this call (and any \nrecursive calls). Returns the string result if :stream is nil or nil otherwise.\n\nThe following keyword arguments can be passed with values:\n Keyword Meaning Default value\n :stream Writer for output or nil true (indicates *out*)\n :base Base to use for writing rationals Current value of *print-base*\n :circle* If true, mark circular structures Current value of *print-circle*\n :length Maximum elements to show in sublists Current value of *print-length*\n :level Maximum depth Current value of *print-level*\n :lines* Maximum lines of output Current value of *print-lines*\n :miser-width Width to enter miser mode Current value of *print-miser-width*\n :dispatch The pretty print dispatch function Current value of *print-pprint-dispatch*\n :pretty If true, do pretty printing Current value of *print-pretty*\n :radix If true, prepend a radix specifier Current value of *print-radix*\n :readably* If true, print readably Current value of *print-readably*\n :right-margin The column for the right margin Current value of *print-right-margin*\n :suppress-namespaces If true, no namespaces in symbols Current value of *print-suppress-namespaces*\n\n * = not yet supported\n","library-url":"https://github.com/clojure/clojure","href":"/clojure.pprint/write"},{"added":"1.2","ns":"clojure.pprint","name":"*print-right-margin*","file":"clojure/pprint/pprint_base.clj","type":"var","column":1,"see-alsos":[{"created-at":1694190332995,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"pprint","ns":"clojure.pprint"},"_id":"64fb4afce4b08cf8563f4bf6"}],"dynamic":true,"line":40,"examples":[{"updated-at":1533810720443,"created-at":1533810720443,"author":{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"},"body":";; Compare the two outputs below. Note how pprint puts the map on two lines\n;; in the second snippet to avoid having a line longer than 5 characters.\n\n(binding [clojure.pprint/*print-right-margin* 15]\n (clojure.pprint/pprint {:foo \"bar\"}))\n; Prints:\n; {:foo \"bar\"}\n\n(binding [clojure.pprint/*print-right-margin* 5]\n (clojure.pprint/pprint {:foo \"bar\"}))\n; Prints:\n; {:foo\n; \"bar\"}","_id":"5b6c1820e4b00ac801ed9e4a"}],"notes":null,"arglists":[],"doc":"Pretty printing will try to avoid anything going beyond this column.\nSet it to nil to have pprint let the line be arbitrarily long. This will ignore all \nnon-mandatory newlines.","library-url":"https://github.com/clojure/clojure","href":"/clojure.pprint/*print-right-margin*"},{"added":"1.2","ns":"clojure.pprint","name":"write-out","file":"clojure/pprint/pprint_base.clj","type":"function","column":1,"see-alsos":null,"line":171,"examples":null,"notes":null,"arglists":["object"],"doc":"Write an object to *out* subject to the current bindings of the printer control \nvariables. Use the kw-args argument to override individual variables for this call (and \nany recursive calls).\n\n*out* must be a PrettyWriter if pretty printing is enabled. This is the responsibility\nof the caller.\n\nThis method is primarily intended for use by pretty print dispatch functions that \nalready know that the pretty printer will have set up their environment appropriately.\nNormal library clients should use the standard \"write\" interface. ","library-url":"https://github.com/clojure/clojure","href":"/clojure.pprint/write-out"},{"added":"1.2","ns":"clojure.pprint","name":"with-pprint-dispatch","file":"clojure/pprint/pprint_base.clj","type":"macro","column":1,"see-alsos":[{"created-at":1683110543113,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"*print-pprint-dispatch*","ns":"clojure.pprint"},"_id":"64523a8fe4b08cf8563f4bac"}],"line":274,"examples":[{"updated-at":1619968380698,"created-at":1619968380698,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/20086?v=4"},"body":"(require '[clojure.pprint :as pprint])\n\n(def condp-statement\n '(condp = x\n 1 \"one\" 2 \"two\" 3 \"three\"\n 4 \"four\" 5 \"five\" 6 \"six\" :else :none))\n\n(pprint/with-pprint-dispatch \n pprint/code-dispatch\n (pprint/pprint condp-statement))\n;; (condp = x\n;; 1 \"one\"\n;; 2 \"two\"\n;; 3 \"three\"\n;; 4 \"four\"\n;; 5 \"five\"\n;; 6 \"six\"\n;; :else :none)","_id":"608ec17ce4b0b1e3652d74ef"}],"macro":true,"notes":null,"arglists":["function & body"],"doc":"Execute body with the pretty print dispatch function bound to function.","library-url":"https://github.com/clojure/clojure","href":"/clojure.pprint/with-pprint-dispatch"},{"added":"1.2","ns":"clojure.pprint","name":"*print-base*","file":"clojure/pprint/pprint_base.clj","type":"var","column":1,"see-alsos":[{"created-at":1664286279673,"author":{"login":"sreekanthb","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1254569?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"*print-radix*","ns":"clojure.pprint"},"_id":"6332fe47e4b0b1e3652d7667"}],"dynamic":true,"line":87,"examples":[{"updated-at":1533810848478,"created-at":1533810848478,"author":{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"},"body":"(binding [clojure.pprint/*print-base* 10]\n (clojure.pprint/pprint 42))\n; Prints:\n; 42\n\n(binding [clojure.pprint/*print-base* 2]\n (clojure.pprint/pprint 42))\n; Prints:\n; 101010","_id":"5b6c18a0e4b00ac801ed9e4b"},{"updated-at":1664799578948,"created-at":1664286031216,"author":{"login":"sreekanthb","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1254569?v=4"},"body":";; Prints list of hexadecimals with radix specifier: #x\nuser> (with-bindings {#'clojure.pprint/*print-base* 16\n #'clojure.pprint/*print-radix* true}\n (clojure.pprint/pprint (range 16)))\n;;=> (#x0 #x1 #x2 #x3 #x4 #x5 #x6 #x7 #x8 #x9 #xa #xb #xc #xd #xe #xf)\n\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/1254569?v=4","account-source":"github","login":"sreekanthb"}],"_id":"6332fd4fe4b0b1e3652d7666"}],"notes":null,"arglists":[],"doc":"The base to use for printing integers and rationals.","library-url":"https://github.com/clojure/clojure","href":"/clojure.pprint/*print-base*"},{"ns":"clojure.reflect","name":"->Field","file":"clojure/reflect/java.clj","type":"function","column":1,"see-alsos":null,"line":154,"examples":null,"notes":null,"arglists":["name type declaring-class flags"],"doc":"Positional factory function for class clojure.reflect.Field.","library-url":"https://github.com/clojure/clojure","href":"/clojure.reflect/->Field"},{"ns":"clojure.reflect","name":"->Method","file":"clojure/reflect/java.clj","type":"function","column":1,"see-alsos":null,"line":134,"examples":null,"notes":null,"arglists":["name return-type declaring-class parameter-types exception-types flags"],"doc":"Positional factory function for class clojure.reflect.Method.","library-url":"https://github.com/clojure/clojure","href":"/clojure.reflect/->Method"},{"ns":"clojure.reflect","name":"TypeReference","file":"clojure/reflect.clj","type":"var","column":1,"see-alsos":null,"line":48,"examples":null,"notes":null,"arglists":[],"doc":"A TypeReference can be unambiguously converted to a type name on\n the host platform.\n\n All typerefs are normalized into symbols. If you need to\n normalize a typeref yourself, call typesym.","library-url":"https://github.com/clojure/clojure","href":"/clojure.reflect/TypeReference"},{"added":"1.3","ns":"clojure.reflect","name":"reflect","file":"clojure/reflect.clj","type":"function","column":1,"see-alsos":[{"created-at":1332916378000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.pprint","name":"print-table","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e88"},{"created-at":1465943137399,"author":{"login":"bkovitz","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/4142015?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"type-reflect","ns":"clojure.reflect"},"_id":"57608461e4b0bafd3e2a0487"}],"line":115,"examples":[{"updated-at":1507758581210,"created-at":1329989405000,"body":"(use 'clojure.reflect 'clojure.pprint)\n;;=> nil\n(def r (reflect *in*))\n;;=> #'user/r\n(count (:members r))\n;;=> 9\n(pprint (map class (:members r)))\n;; (clojure.reflect.Constructor\n;; clojure.reflect.Method\n;; clojure.reflect.Field\n;; clojure.reflect.Field\n;; clojure.reflect.Method\n;; clojure.reflect.Method\n;; clojure.reflect.Method\n;; clojure.reflect.Method\n;; clojure.reflect.Field)\n;;=> nil\n(pprint r)\n;; {:bases #{java.io.PushbackReader},\n;; :flags #{:public},\n;; :members\n;; #{{:name clojure.lang.LineNumberingPushbackReader,\n;; :declaring-class clojure.lang.LineNumberingPushbackReader,\n;; :parameter-types [java.io.Reader],\n;; :exception-types [],\n;; :flags #{:public}}\n;; {:name read,\n;; :return-type int,\n;; :declaring-class clojure.lang.LineNumberingPushbackReader,\n;; :parameter-types [],\n;; :exception-types [java.io.IOException],\n;; :flags #{:public}}\n;; {:name _atLineStart,\n;; :type boolean,\n;; :declaring-class clojure.lang.LineNumberingPushbackReader,\n;; :flags #{:private}}\n;; {:name newline,\n;; :type int,\n;; :declaring-class clojure.lang.LineNumberingPushbackReader,\n;; :flags #{:private :static :final}}\n;; {:name unread,\n;; :return-type void,\n;; :declaring-class clojure.lang.LineNumberingPushbackReader,\n;; :parameter-types [int],\n;; :exception-types [java.io.IOException],\n;; :flags #{:public}}\n;; {:name readLine,\n;; :return-type java.lang.String,\n;; :declaring-class clojure.lang.LineNumberingPushbackReader,\n;; :parameter-types [],\n;; :exception-types [java.io.IOException],\n;; :flags #{:public}}\n;; {:name atLineStart,\n;; :return-type boolean,\n;; :declaring-class clojure.lang.LineNumberingPushbackReader,\n;; :parameter-types [],\n;; :exception-types [],\n;; :flags #{:public}}\n;; {:name getLineNumber,\n;; :return-type int,\n;; :declaring-class clojure.lang.LineNumberingPushbackReader,\n;; :parameter-types [],\n;; :exception-types [],\n;; :flags #{:public}}\n;; {:name _prev,\n;; :type boolean,\n;; :declaring-class clojure.lang.LineNumberingPushbackReader,\n;; :flags #{:private}}}}\n;;=> nil\n","editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3","account-source":"github","login":"jafingerhut"},"_id":"542692d6c026201cdc3270f4"},{"body":"(require '[clojure.reflect :as cr])\n(require '[clojure.pprint :as pp])\n\n;; Here we have a simple function that prints the\n;; important bits of the class definition in a table.\n(->> String \n cr/reflect \n :members \n pp/print-table))\n;;=> [produces a large table the next example filters it down.\n\n;; In order to reduce the rows to just :public methods a filter can be used.\n(->> String \n cr/reflect \n :members \n (filter #(contains? (:flags %) :public)) \n pp/print-table)\n;;=> | :name | :return-type | :declaring-class | \n;; |------------------------+------------------+------------------+------->\n;; | replaceAll | java.lang.String | java.lang.String | \n;; | CASE_INSENSITIVE_ORDER | | java.lang.String | \n;; | codePointCount | int | java.lang.String |\n;; | getChars | void | java.lang.String | \n;; etc.\n\n;; Print methods that contain \"to\", as a way of code completion.\n;; Combine with above example ``#(contains? (:flags %) :public)`` to get \n;; matching callable methods (public & with \"to\")\n(->> String \n cr/reflect \n :members \n (filter #(.contains (str (:name %)) \"to\"))\n pp/print-table)\n\n;; => | :name | :return-type | :declaring-class | \n;; |-------------+------------------+------------------+---\n;; | toString | java.lang.String | java.lang.String | \n;; | toLowerCase | java.lang.String | java.lang.String | \n;; | toUpperCase | java.lang.String | java.lang.String | \n;; | toUpperCase | java.lang.String | java.lang.String | \n;; | toCharArray | char<> | java.lang.String | \n;; | toLowerCase | java.lang.String | java.lang.String | ","author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"},"created-at":1424120412909,"updated-at":1507759169913,"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"},{"avatar-url":"https://avatars.githubusercontent.com/u/4199136?v=3","account-source":"github","login":"alvarogarcia7"}],"_id":"54e25a5ce4b0b716de7a6528"},{"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"}],"body":"(require '[clojure.reflect :as cr])\n(import '(clojure.reflect.JavaReflector))\n\n;; Let us see what is available in the JavaReflector\n(->> clojure.reflect.JavaReflector \n cr/reflect\n :members\n (sort-by :name)\n (pp/print-table [:name :flags :parameter-types])\n;; | :name | :flags | :parameter-types |\n;; |-------------------------------+---------------------------+--------------------|\n;; | __cached_class__0 | #{:private :static} | |\n;; | classloader | #{:public :final} | |\n;; | clojure.reflect.JavaReflector | #{:public} | [java.lang.Object] |\n;; | const__0 | #{:public :static :final} | |\n;; | const__1 | #{:public :static :final} | |\n;; | const__10 | #{:public :static :final} | |\n;; | const__5 | #{:public :static :final} | |\n;; | const__7 | #{:public :static :final} | |\n;; | const__9 | #{:public :static :final} | |\n;; | do_reflect | #{:public} | [java.lang.Object] |\n;; | getBasis | #{:public :static} | [] |\n;;=> nil","author":{"avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4","account-source":"github","login":"phreed"},"created-at":1507760580365,"updated-at":1507761553527,"_id":"59de99c4e4b03026fe14ea68"}],"notes":null,"arglists":["obj & options"],"doc":"Alpha - subject to change.\n Reflect on the type of obj (or obj itself if obj is a class).\n Return value and options are the same as for type-reflect. ","library-url":"https://github.com/clojure/clojure","href":"/clojure.reflect/reflect"},{"ns":"clojure.reflect","name":"map->Field","file":"clojure/reflect/java.clj","type":"function","column":1,"see-alsos":[{"created-at":1507762821609,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"map->Constructor","ns":"clojure.reflect"},"_id":"59dea285e4b03026fe14ea6e"},{"created-at":1507762840684,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"map->Method","ns":"clojure.reflect"},"_id":"59dea298e4b03026fe14ea6f"}],"line":154,"examples":[{"updated-at":1507762803236,"created-at":1507762803236,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"},"body":"(require '[clojure.reflect :as cr])\n\n;; I have no idea what this is for but here is what it does.\n(cr/map->Field {}) \n;=> #clojure.reflect.Field{:name nil, :type nil, :declaring-class nil, :flags nil}","_id":"59dea273e4b03026fe14ea6d"}],"notes":null,"arglists":["m__8001__auto__"],"doc":"Factory function for class clojure.reflect.Field, taking a map of keywords to field values.","library-url":"https://github.com/clojure/clojure","href":"/clojure.reflect/map->Field"},{"ns":"clojure.reflect","name":"map->Method","file":"clojure/reflect/java.clj","type":"function","column":1,"see-alsos":[{"created-at":1507762922151,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"map->Constructor","ns":"clojure.reflect"},"_id":"59dea2eae4b03026fe14ea71"},{"created-at":1507762942594,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"map->Field","ns":"clojure.reflect"},"_id":"59dea2fee4b03026fe14ea72"}],"line":134,"examples":[{"updated-at":1507762895850,"created-at":1507762895850,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"},"body":"(require '[clojure.reflect :as cr])\n\n;; I have no idea what this is for but here is what it does.\n(cr/map->Method {}) \n;=> #clojure.reflect.Method{:name nil, :return-type nil, \n;; :declaring-class nil, :parameter-types nil,\n;; :exception-types nil, :flags nil}","_id":"59dea2cfe4b03026fe14ea70"}],"notes":null,"arglists":["m__8001__auto__"],"doc":"Factory function for class clojure.reflect.Method, taking a map of keywords to field values.","library-url":"https://github.com/clojure/clojure","href":"/clojure.reflect/map->Method"},{"ns":"clojure.reflect","name":"typename","type":"function","see-alsos":[{"created-at":1507759637967,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"reflect","ns":"clojure.reflect"},"_id":"59de9615e4b03026fe14ea65"},{"created-at":1507759650019,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"do-reflect","ns":"clojure.reflect"},"_id":"59de9622e4b03026fe14ea66"},{"created-at":1507759666391,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"type-reflect","ns":"clojure.reflect"},"_id":"59de9632e4b03026fe14ea67"}],"examples":[{"updated-at":1507759616018,"created-at":1507759616018,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"},"body":"(require '[clojure.reflect :as cr])\n\n;; It returns the class name as a string. \n(->> java.lang.Integer \n cr/typename)\n;;=> \"java.lang.Integer\"","_id":"59de9600e4b03026fe14ea64"}],"notes":null,"tag":null,"arglists":["o"],"doc":"Returns Java name as returned by ASM getClassName, e.g. byte[], java.lang.String[]","library-url":"https://github.com/clojure/clojure","href":"/clojure.reflect/typename"},{"ns":"clojure.reflect","name":"->JavaReflector","file":"clojure/reflect/java.clj","type":"function","column":1,"see-alsos":null,"line":178,"examples":[{"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"}],"body":"(require '[clojure.reflect :as cr])\n(import '(clojure.reflect.JavaReflector))\n\n;; Let us see what is available in the JavaReflector\n(->> clojure.reflect.JavaReflector \n cr/reflect\n :members\n (sort-by :name)\n (pp/print-table [:name :flags :parameter-types]))\n; | :name | :flags | :parameter-types |\n; |-------------------------------+---------------------------+--------------------|\n; | __cached_class__0 | #{:private :static} | |\n; | classloader | #{:public :final} | |\n; | clojure.reflect.JavaReflector | #{:public} | [java.lang.Object] |\n; | const__0 | #{:public :static :final} | |\n; | const__1 | #{:public :static :final} | |\n; | const__10 | #{:public :static :final} | |\n; | const__5 | #{:public :static :final} | |\n; | const__7 | #{:public :static :final} | |\n; | const__9 | #{:public :static :final} | |\n; | do_reflect | #{:public} | [java.lang.Object] |\n; | getBasis | #{:public :static} | [] |\n;;=> nil\n","author":{"avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4","account-source":"github","login":"phreed"},"created-at":1507763250502,"updated-at":1507763276867,"_id":"59dea432e4b03026fe14ea73"}],"notes":null,"arglists":["classloader"],"doc":"Positional factory function for class clojure.reflect.JavaReflector.","library-url":"https://github.com/clojure/clojure","href":"/clojure.reflect/->JavaReflector"},{"ns":"clojure.reflect","name":"->AsmReflector","file":"clojure/reflect/java.clj","type":"function","column":1,"see-alsos":null,"line":208,"examples":[{"updated-at":1507763433355,"created-at":1507763433355,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"},"body":"(require '[clojure.reflect :as cr])\n(import '(clojure.reflect.AsmReflector))\n\n;; Let us see what is available in the AsmReflector\n(->> clojure.reflect.AsmReflector \n cr/reflect\n :members\n (sort-by :name)\n (pp/print-table [:name :flags :parameter-types]))\n\n; | :name | :flags | :parameter-types |\n; |------------------------------+---------------------------+--------------------|\n; | __cached_class__0 | #{:private :static} | |\n; | class_resolver | #{:public :final} | |\n; | clojure.reflect.AsmReflector | #{:public} | [java.lang.Object] |\n; | const__0 | #{:public :static :final} | |\n; | const__3 | #{:public :static :final} | |\n; | const__4 | #{:public :static :final} | |\n; | const__5 | #{:public :static :final} | |\n; | do_reflect | #{:public} | [java.lang.Object] |\n; | getBasis | #{:public :static} | [] |\n;;=> nil\n","_id":"59dea4e9e4b03026fe14ea75"}],"notes":null,"arglists":["class-resolver"],"doc":"Positional factory function for class clojure.reflect.AsmReflector.","library-url":"https://github.com/clojure/clojure","href":"/clojure.reflect/->AsmReflector"},{"ns":"clojure.reflect","name":"resolve-class","type":"function","see-alsos":null,"examples":[{"author":{"login":"weakreference","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/86146f8bd5207b97701c0f16f0017334?r=PG&default=identicon"},"editors":[{"avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4","account-source":"github","login":"phreed"}],"body":";;Check if class c exists on the classpath\n(require '[clojure.reflect :refer [resolve-class]])\n\n(defn class-exists? [c] \n (resolve-class (.getContextClassLoader (Thread/currentThread)) c))\n\n(class-exists? 'org.joda.time.DateTime) \n;;=> nil","created-at":1351132479000,"updated-at":1508166357885,"_id":"542692d6c026201cdc3270f5"},{"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"}],"body":";; Obtaining a suitable class loader is an important consideration.\n;; to a large degree the class loader used by default is the\n;; context class loader which is controlled by \n*use-context-classloader*\n;=> true\n\n;; the following helper function shows the \n(require '[clojure.java.classpath :as cp])\n;=> nil\n\n;; the context class loader\n(def ccl (.getContextClassLoader (Thread/currentThread)))\n;=> #'boot.user/ccl\n(cp/classpath ccl)\n;=> (#object[java.io.File 0x709e8101 ...\n\n;; the system class loader\n(def scl (java.lang.ClassLoader/getSystemClassLoader)) \n;=> #'boot.user/scl\n(cp/classpath scl)\n;=> (#object[java.io.File 0x709e8101 ...\n\n;; the class loader used to load a particular class instance.\n(deftype Foo [bar])\n;=> boot.user.Foo\n(def icl (.getClassLoader (class (Foo. 4))))\n;=> #'boot.user/icl\n(cp/classpath icl)\n;=> (#object[java.io.File 0x709e8101 ...\n\n;; I recommend you use the DynamicClassLoader \n;; for cases when 'import' does not do it.\n;; https://github.com/clojure/clojure\n(def dcl (clojure.lang.DynamicClassLoader.))\n;=> #'boot.user/dcl\n(cp/classpath dcl)\n;=> (#object[java.io.File 0x709e8101 ...\n","author":{"avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4","account-source":"github","login":"phreed"},"created-at":1507306884656,"updated-at":1508168226939,"_id":"59d7ad84e4b03026fe14ea54"}],"notes":null,"tag":"java.io.InputStream","arglists":["this name"],"doc":"Given a class name, return that typeref's class bytes as an InputStream.","library-url":"https://github.com/clojure/clojure","href":"/clojure.reflect/resolve-class"},{"ns":"clojure.reflect","name":"flag-descriptors","file":"clojure/reflect/java.clj","type":"var","column":1,"see-alsos":null,"line":77,"examples":[{"updated-at":1495736937803,"created-at":1495736937803,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"body":"(use 'clojure.reflect)\n\n(pprint clojure.reflect/flag-descriptors)\n;;=> [{:name :public, :flag 1, :contexts #{:method :field :class}}\n;; {:name :private, :flag 2, :contexts #{:method :field :class}}\n;; {:name :protected, :flag 4, :contexts #{:method :field :class}}\n;; {:name :static, :flag 8, :contexts #{:method :field}}\n;; {:name :final, :flag 16, :contexts #{:method :field :class}}\n;; {:name :synchronized, :flag 32, :contexts #{:method}}\n;; {:name :volatile, :flag 64, :contexts #{:field}}\n;; {:name :bridge, :flag 64, :contexts #{:method}}\n;; {:name :varargs, :flag 128, :contexts #{:method}}\n;; {:name :transient, :flag 128, :contexts #{:field}}\n;; {:name :native, :flag 256, :contexts #{:method}}\n;; {:name :interface, :flag 512, :contexts #{:class}}\n;; {:name :abstract, :flag 1024, :contexts #{:method :class}}\n;; {:name :strict, :flag 2048, :contexts #{:method}}\n;; {:name :synthetic, :flag 4096, :contexts #{:method :field :class}}\n;; {:name :annotation, :flag 8192, :contexts #{:class}}\n;; {:name :enum, :flag 16384, :contexts #{:field :inner :class}}]","_id":"59272269e4b093ada4d4d770"}],"notes":[{"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"updated-at":1495736792080,"created-at":1495736792080,"body":"The value of the `:flag` field for each modifier is identical to the value of the constant representing the modifier in [`java.lang.reflect.Modifier`](https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Modifier.html#field.summary), which in turn is taken from [Table 4.1-A](https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.1-200-E.1), [Table 4.5-A](https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.5-200-A.1), [Table 4.6-A](https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.6-200-A.1) and [Table 4.7.6-A](https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.7.6-300-D.1-D.1) of *The Java™ Virtual Machine Specification.*\n","_id":"592721d8e4b093ada4d4d76f"}],"arglists":[],"doc":"The Java access bitflags, along with their friendly names and\nthe kinds of objects to which they can apply.","library-url":"https://github.com/clojure/clojure","href":"/clojure.reflect/flag-descriptors"},{"ns":"clojure.reflect","name":"do-reflect","type":"function","see-alsos":null,"examples":null,"notes":null,"tag":null,"arglists":["reflector typeref"],"doc":null,"library-url":"https://github.com/clojure/clojure","href":"/clojure.reflect/do-reflect"},{"ns":"clojure.reflect","name":"ClassResolver","file":"clojure/reflect/java.clj","type":"var","column":1,"see-alsos":[{"created-at":1507763760914,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"resolve-class","ns":"clojure.reflect"},"_id":"59dea630e4b03026fe14ea77"}],"line":196,"examples":[{"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"}],"body":"(require '[clojure.reflect :as cr]) \n\n;; Let us see what is available in the JavaReflector\n(->> clojure.reflect.ClassResolver \n cr/reflect\n :members\n (sort-by :name)\n (pp/print-table [:name :flags :parameter-types])\n; | :name | :flags | :parameter-types |\n; |---------------+----------------------+--------------------|\n; | resolve_class | #{:public :abstract} | [java.lang.Object] |\n;;=> nil\n","author":{"avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4","account-source":"github","login":"phreed"},"created-at":1507763657006,"updated-at":1507763804408,"_id":"59dea5c9e4b03026fe14ea76"}],"notes":null,"arglists":[],"doc":null,"library-url":"https://github.com/clojure/clojure","href":"/clojure.reflect/ClassResolver"},{"ns":"clojure.reflect","name":"Reflector","file":"clojure/reflect.clj","type":"var","column":1,"see-alsos":null,"line":44,"examples":null,"notes":[{"body":";; not to be confused with the Reflector class\n```\n (import '(clojure.lang DynamicClassLoader Reflector))\n``` \n;;=> clojure.lang.Reflector\n```\n(let [class-loader (DynamicClassLoader.) \n a-class (.loadClass class-loader \"java.lang.Long\")] \n (Reflector/invokeConstructor a-class (into-array String [\"2\"])))\n```\n;;=> 2","created-at":1507758825536,"updated-at":1507758968544,"author":{"avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4","account-source":"github","login":"phreed"},"_id":"59de92e9e4b03026fe14ea62"}],"arglists":[],"doc":"Protocol for reflection implementers.","library-url":"https://github.com/clojure/clojure","href":"/clojure.reflect/Reflector"},{"ns":"clojure.reflect","name":"->Constructor","file":"clojure/reflect/java.clj","type":"function","column":1,"see-alsos":null,"line":115,"examples":null,"notes":null,"arglists":["name declaring-class parameter-types exception-types flags"],"doc":"Positional factory function for class clojure.reflect.Constructor.","library-url":"https://github.com/clojure/clojure","href":"/clojure.reflect/->Constructor"},{"ns":"clojure.reflect","name":"map->Constructor","file":"clojure/reflect/java.clj","type":"function","column":1,"see-alsos":null,"line":115,"examples":[{"updated-at":1507762666011,"created-at":1507762666011,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"},"body":"(require '[clojure.reflect :as cr])\n\n;; I have no idea what this is for but here is what it does.\n(cr/map->Constructor {:name \"do_reflect\" \n :declaring-class \"clojure.reflect.JavaReflector\"\n :parameter-types [\"java.lang.Object\"]\n :exception-types []\n :flags #{:public}}) \n;=> #clojure.reflect.Constructor{:name \"do_reflect\", \n;; :declaring-class \"clojure.reflect.JavaReflector\",\n;; :parameter-types [\"java.lang.Object\"],\n;; :exception-types [],\n;; :flags #{:public}}","_id":"59dea1eae4b03026fe14ea6c"}],"notes":null,"arglists":["m__8001__auto__"],"doc":"Factory function for class clojure.reflect.Constructor, taking a map of keywords to field values.","library-url":"https://github.com/clojure/clojure","href":"/clojure.reflect/map->Constructor"},{"added":"1.3","ns":"clojure.reflect","name":"type-reflect","file":"clojure/reflect.clj","type":"function","column":1,"see-alsos":[{"created-at":1495744758522,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"reflect","ns":"clojure.reflect"},"_id":"592740f6e4b093ada4d4d773"}],"line":58,"examples":[{"updated-at":1495738204071,"created-at":1495738204071,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"body":";;;; Alphabetically list all public static fields in java.lang.Integer\n\n(use 'clojure.reflect)\n\n(->> java.lang.Integer \n clojure.reflect/type-reflect\n :members \n (filter #(instance? clojure.reflect.Field %)) \n (filter #(:public (:flags %)))\n (filter #(:static (:flags %)))\n (map #(vector (:name %) (:type %)))\n (sort)\n (pprint))\n\n;;=> ([BYTES int]\n;; [MAX_VALUE int]\n;; [MIN_VALUE int]\n;; [SIZE int]\n;; [TYPE java.lang.Class])","_id":"5927275ce4b093ada4d4d771"},{"updated-at":1495743210185,"created-at":1495743210185,"author":{"login":"svenschoenung","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10583730?v=3"},"body":";;;; List class hierarchy for a particular class \n\n(defn class-hierarchy [clazz]\n (let [refl (fn [c] (assoc (clojure.reflect/type-reflect c) :name c))]\n (loop [type (refl clazz) hierarchy '()]\n (let [parent (->> type\n :bases\n (map refl)\n (remove #(:interface (:flags %)))\n first)]\n (if parent\n (recur parent (conj hierarchy (:name type)))\n (conj hierarchy java.lang.Object))))))\n\n(pprint (class-hierarchy javax.security.auth.login.CredentialNotFoundException))\n;;=> (java.lang.Object\n;; java.lang.Throwable\n;; java.lang.Exception\n;; java.security.GeneralSecurityException\n;; javax.security.auth.login.LoginException\n;; javax.security.auth.login.CredentialException\n;; javax.security.auth.login.CredentialNotFoundException)\n\n(pprint (class-hierarchy javax.swing.JPasswordField$AccessibleJPasswordField))\n;;=> (java.lang.Object\n;; javax.accessibility.AccessibleContext\n;; java.awt.Component$AccessibleAWTComponent\n;; java.awt.Container$AccessibleAWTContainer\n;; javax.swing.JComponent$AccessibleJComponent\n;; javax.swing.text.JTextComponent$AccessibleJTextComponent\n;; javax.swing.JTextField$AccessibleJTextField\n;; javax.swing.JPasswordField$AccessibleJPasswordField)\n","_id":"59273aeae4b093ada4d4d772"},{"updated-at":1508197724829,"created-at":1508197724829,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"},"body":"(require '(clojure [reflect :as cr] [pprint :as pp]))\n\n;; Let us see what is available in the DynamicClassLoader\n(->> clojure.lang.DynamicClassLoader \n cr/type-reflect\n :members\n (sort-by :name)\n (pp/print-table [:name :flags :parameter-types]))\n;| :name | :flags | :parameter-types |\n;|---------------------------------+-----------------------------+--------------------------------------------|\n;| EMPTY_URLS | #{:static :final} | |\n;| addURL | #{:public} | [java.net.URL] |\n;| classCache | #{:static} | |\n;| clojure.lang.DynamicClassLoader | #{:public} | [java.lang.ClassLoader] |\n;| clojure.lang.DynamicClassLoader | #{:public} | [] |\n;| constantVals | #{} | |\n;| defineClass | #{:public} | [java.lang.String byte<> java.lang.Object] |\n;| findClass | #{:protected} | [java.lang.String] |\n;| findInMemoryClass | #{:static} | [java.lang.String] |\n;| getConstants | #{:public} | [int] |\n;| loadClass | #{:synchronized :protected} | [java.lang.String boolean] |\n;| registerConstants | #{:public} | [int java.lang.Object<>] |\n;| rq | #{:static :final} | |","_id":"59e5455ce4b03026fe14ea91"}],"notes":null,"arglists":["typeref & options"],"doc":"Alpha - subject to change.\n Reflect on a typeref, returning a map with :bases, :flags, and\n :members. In the discussion below, names are always Clojure symbols.\n\n :bases a set of names of the type's bases\n :flags a set of keywords naming the boolean attributes\n of the type.\n :members a set of the type's members. Each member is a map\n and can be a constructor, method, or field.\n\n Keys common to all members:\n :name name of the type \n :declaring-class name of the declarer\n :flags keyword naming boolean attributes of the member\n\n Keys specific to constructors:\n :parameter-types vector of parameter type names\n :exception-types vector of exception type names\n\n Key specific to methods:\n :parameter-types vector of parameter type names\n :exception-types vector of exception type names\n :return-type return type name\n\n Keys specific to fields:\n :type type name\n\n Options:\n\n :ancestors in addition to the keys described above, also\n include an :ancestors key with the entire set of\n ancestors, and add all ancestor members to\n :members.\n :reflector implementation to use. Defaults to JavaReflector,\n AsmReflector is also an option.","library-url":"https://github.com/clojure/clojure","href":"/clojure.reflect/type-reflect"},{"ns":"clojure.repl","name":"source-fn","file":"clojure/repl.clj","type":"function","column":1,"see-alsos":[{"created-at":1353815572000,"author":{"login":"franks42","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/b3ee701dd6c481e5d310467ddfe62c48?r=PG&default=identicon"},"to-var":{"ns":"clojure.repl","name":"source","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e83"}],"line":147,"examples":[{"updated-at":1481465114444,"created-at":1481465114444,"author":{"login":"ertugrulcetin","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8271291?v=3"},"body":"(source-fn 'max)\n\n;;=> \"(defn max\n \\\"Returns the greatest of the nums.\\\"\n {:added \\\"1.0\\\"\n :inline-arities >1?\n :inline (nary-inline 'max)}\n ([x] x)\n ([x y] (. clojure.lang.Numbers (max x y)))\n ([x y & more]\n (reduce1 max (max x y) more)))\"\n","_id":"584d5d1ae4b0782b632278dc"},{"updated-at":1695188276728,"created-at":1695188276728,"author":{"login":"burinc","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/19825136?v=4"},"body":";; Capturing result of `source` via `with-out-str` removing the last new-line char\n;; is the same as the output from `source-fn`\n\n(require '[clojure.repl :as repl]\n '[clojure.string :as str])\n\n(= (repl/source-fn 'max)\n (-> (repl/source max)\n with-out-str\n str/trim-newline)) \n;;=> true\n\n(= (repl/source-fn 'map)\n (-> (repl/source map)\n with-out-str\n str/trim-newline)) \n;;=> true\n","_id":"650a8534e4b08cf8563f4bfa"}],"notes":null,"arglists":["x"],"doc":"Returns a string of the source code for the given symbol, if it can\n find it. This requires that the symbol resolve to a Var defined in\n a namespace for which the .clj is in the classpath. Returns nil if\n it can't find the source. For most REPL usage, 'source' is more\n convenient.\n\n Example: (source-fn 'filter)","library-url":"https://github.com/clojure/clojure","href":"/clojure.repl/source-fn"},{"added":"1.0","ns":"clojure.repl","name":"doc","file":"clojure/repl.clj","type":"macro","column":1,"see-alsos":[{"to-var":{"library-url":"https://github.com/clojure/clojure","name":"source","ns":"clojure.repl"},"author":{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},"created-at":1342639092000,"_id":"542692eaf6e94c6970521af5"},{"to-var":{"library-url":"https://github.com/clojure/clojure","name":"dir","ns":"clojure.repl"},"author":{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},"created-at":1342639183000,"_id":"542692eaf6e94c6970521af6"},{"to-var":{"library-url":"https://github.com/clojure/clojure","name":"apropos","ns":"clojure.repl"},"author":{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},"created-at":1342639337000,"_id":"542692eaf6e94c6970521af7"}],"line":131,"examples":[{"updated-at":1342639164000,"created-at":1342639164000,"body":"=> (doc map)\n;; prints in console:\n-------------------------\nclojure.core/map\n([f coll] [f c1 c2] [f c1 c2 c3] [f c1 c2 c3 & colls])\n Returns a lazy sequence consisting of the result of applying f to the\n set of first items of each coll, followed by applying f to the set\n of second items in each coll, until any one of the colls is\n exhausted. Any remaining items in other colls are ignored. Function\n f should accept number-of-colls arguments.","editors":[],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},"_id":"542692d6c026201cdc3270f7"},{"author":{"login":"ryo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3f7913b563c72083c74030d928ba407e?r=PG&default=identicon"},"editors":[],"body":"user> (doc clojure.core)\n-------------------------\nclojure.core\n Fundamental library of the Clojure language\n","created-at":1398682749000,"updated-at":1398682749000,"_id":"542692d6c026201cdc3270f8"}],"macro":true,"notes":[{"updated-at":1350125867000,"body":"Note that the clojure.repl namespace which contains doc is not loaded by default in Emacs' SLIME mode, because SLIME provides its own doc function via C-c C-d d.","created-at":1350125867000,"author":{"login":"pjlegato","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/4ce55cfd8b3ae2f63f5ecbc8fc1c05d4?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fed"}],"arglists":["name"],"doc":"Prints documentation for a var or special form given its name,\n or for a spec if given a keyword","library-url":"https://github.com/clojure/clojure","href":"/clojure.repl/doc"},{"added":"1.3","ns":"clojure.repl","name":"stack-element-str","file":"clojure/repl.clj","type":"function","column":1,"see-alsos":[{"created-at":1559582539068,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"demunge","ns":"clojure.repl"},"_id":"5cf5574be4b0ca44402ef746"}],"line":227,"examples":[{"updated-at":1559582523950,"created-at":1559582310173,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"body":"(ns my-namespace)\n\n(require '[clojure.repl :refer [stack-element-str]])\n\n(defn my-funct! [] (throw (ex-info \"error\" {})))\n\n(def stack-trace \n (try (my-funct!) (catch Exception e (.getStackTrace e))))\n\n;; This stack trace element shows a Java compatible class name,\n;; but is not very readable.\n(str (nth stack-trace 2))\n;; \"my_namespace$my_funct_BANG_.invokeStatic(form-init417155.clj:1)\"\n\n;; Use stack-element-str to transform it back into idiomatic Clojure\n(stack-element-str (nth stack-trace 2))\n;; \"my-namespace/my-funct! (form-init417155.clj:1)\"\n","editors":[{"avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"}],"_id":"5cf55666e4b0ca44402ef743"}],"notes":null,"arglists":["el"],"doc":"Returns a (possibly unmunged) string representation of a StackTraceElement","library-url":"https://github.com/clojure/clojure","href":"/clojure.repl/stack-element-str"},{"added":"1.0","ns":"clojure.repl","name":"find-doc","file":"clojure/repl.clj","type":"function","column":1,"see-alsos":null,"line":115,"examples":[{"author":{"login":"pimgeek","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/fa1bf77254fb5c14b4fd5afd1c11fe53?r=PG&default=identicon"},"editors":[{"login":"pimgeek","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/fa1bf77254fb5c14b4fd5afd1c11fe53?r=PG&default=identicon"}],"body":"user=> (find-doc \"data structure\")\n\n-------------------------\nclojure.core/eval\n([form])\n Evaluates the form data structure (not text!) and returns the result.\n-------------------------\nclojure.core/ifn?\n([x])\n Returns true if x implements IFn. Note that many data structures\n (e.g. sets and maps) implement IFn\n","created-at":1365967175000,"updated-at":1365967933000,"_id":"542692d6c026201cdc3270f9"}],"notes":null,"arglists":["re-string-or-pattern"],"doc":"Prints documentation for any var whose documentation or name\n contains a match for re-string-or-pattern","library-url":"https://github.com/clojure/clojure","href":"/clojure.repl/find-doc"},{"ns":"clojure.repl","name":"dir","file":"clojure/repl.clj","type":"macro","column":1,"see-alsos":[{"to-var":{"library-url":"https://github.com/clojure/clojure","name":"doc","ns":"clojure.repl"},"author":{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},"created-at":1342639192000,"_id":"542692eaf6e94c6970521b24"},{"to-var":{"library-url":"https://github.com/clojure/clojure","name":"source","ns":"clojure.repl"},"author":{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},"created-at":1342639197000,"_id":"542692eaf6e94c6970521b25"},{"to-var":{"library-url":"https://github.com/clojure/clojure","name":"apropos","ns":"clojure.repl"},"author":{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},"created-at":1342639317000,"_id":"542692eaf6e94c6970521b26"}],"line":201,"examples":[{"author":{"login":"teyc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bd6e62afb4881ab0f617611b8b65d003?r=PG&default=identicon"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":"user=> (require 'clojure.string 'clojure.repl)\n\nuser=> (clojure.repl/dir clojure.string)\nblank?\ncapitalize\nescape\njoin\nlower-case\nreplace\nreplace-first\nreverse\nsplit\nsplit-lines\ntrim\ntrim-newline\ntriml\ntrimr\nupper-case","created-at":1283977504000,"updated-at":1332953035000,"_id":"542692d0c026201cdc326ecf"}],"macro":true,"notes":null,"arglists":["nsname"],"doc":"Prints a sorted directory of public vars in a namespace","library-url":"https://github.com/clojure/clojure","href":"/clojure.repl/dir"},{"added":"1.3","ns":"clojure.repl","name":"pst","file":"clojure/repl.clj","type":"function","column":1,"see-alsos":[{"created-at":1334156025000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.core","name":"*e","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f5f"}],"line":240,"examples":[{"author":{"login":"pimgeek","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/fa1bf77254fb5c14b4fd5afd1c11fe53?r=PG&default=identicon"},"editors":[],"body":"user=> (pst)\nnil\n\nuser=> (/ 1 0)\nArithmeticException Divide by zero clojure.lang.Numbers.divide (Numbers.java:156)\n\nuser=> (pst)\nArithmeticException Divide by zero\n\tclojure.lang.Numbers.divide (Numbers.java:156)\n\tclojure.lang.Numbers.divide (Numbers.java:3691)\n\tuser/eval13 (NO_SOURCE_FILE:7)\n\tclojure.lang.Compiler.eval (Compiler.java:6619)\n\tclojure.lang.Compiler.eval (Compiler.java:6582)\n\tclojure.core/eval (core.clj:2852)\n\tclojure.main/repl/read-eval-print--6588/fn--6591 (main.clj:259)\n\tclojure.main/repl/read-eval-print--6588 (main.clj:259)\n\tclojure.main/repl/fn--6597 (main.clj:277)\n\tclojure.main/repl (main.clj:277)\n\tclojure.main/repl-opt (main.clj:343)\n\tclojure.main/main (main.clj:441)\nnil\n","created-at":1365968672000,"updated-at":1365968672000,"_id":"542692d6c026201cdc3270fb"}],"notes":null,"arglists":["","e-or-depth","e depth"],"doc":"Prints a stack trace of the exception, to the depth requested. If none supplied, uses the root cause of the\n most recent repl exception (*e), and a depth of 12.","library-url":"https://github.com/clojure/clojure","href":"/clojure.repl/pst"},{"ns":"clojure.repl","name":"dir-fn","file":"clojure/repl.clj","type":"function","column":1,"see-alsos":[{"created-at":1545998336322,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"dir","ns":"clojure.repl"},"_id":"5c261000e4b0ca44402ef600"}],"line":195,"examples":[{"updated-at":1559571596051,"created-at":1283977379000,"body":"(require 'clojure.repl 'clojure.string)\n\nuser=> (pprint (clojure.repl/dir-fn 'clojure.string))\n(blank?\n capitalize\n escape\n join\n lower-case\n replace\n replace-first\n reverse\n split\n split-lines\n trim\n trim-newline\n triml\n trimr\n upper-case)\nnil\n\n;; Or the same with \"dir\" at the REPL:\n\nuser=> (dir clojure.string)\n(blank?\n capitalize\n escape\n join\n lower-case\n[...]","editors":[{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/bd6e62afb4881ab0f617611b8b65d003?r=PG&default=identicon","account-source":"clojuredocs","login":"teyc"},"_id":"542692d0c026201cdc326ed1"}],"notes":null,"arglists":["ns"],"doc":"Returns a sorted seq of symbols naming public vars in\n a namespace or namespace alias. Looks for aliases in *ns*","library-url":"https://github.com/clojure/clojure","href":"/clojure.repl/dir-fn"},{"ns":"clojure.repl","name":"source","file":"clojure/repl.clj","type":"macro","column":1,"see-alsos":[{"to-var":{"library-url":"https://github.com/clojure/clojure","name":"doc","ns":"clojure.repl"},"author":{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},"created-at":1342639074000,"_id":"542692ebf6e94c6970521db6"},{"to-var":{"library-url":"https://github.com/clojure/clojure","name":"dir","ns":"clojure.repl"},"author":{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},"created-at":1342639176000,"_id":"542692ebf6e94c6970521db7"},{"to-var":{"library-url":"https://github.com/clojure/clojure","name":"apropos","ns":"clojure.repl"},"author":{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},"created-at":1342639308000,"_id":"542692ebf6e94c6970521db8"},{"created-at":1502136782003,"author":{"login":"ertugrulcetin","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/8271291?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"source-fn","ns":"clojure.repl"},"_id":"5988c9cee4b0d19c2ce9d710"}],"line":172,"examples":[{"author":{"login":"dakrone","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bcacd00a7f05c4772329cf9f446c7987?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":"user=> (source max)\n;; prints in console:\n(defn max\n \"Returns the greatest of the nums.\"\n {:added \"1.0\"}\n ([x] x)\n ([x y] (if (> x y) x y))\n ([x y & more]\n (reduce max (max x y) more)))\n","created-at":1279775890000,"updated-at":1285497544000,"_id":"542692d0c026201cdc326ecb"}],"macro":true,"notes":null,"arglists":["n"],"doc":"Prints the source code for the given symbol, if it can find it.\n This requires that the symbol resolve to a Var defined in a\n namespace for which the .clj is in the classpath.\n\n Example: (source filter)","library-url":"https://github.com/clojure/clojure","href":"/clojure.repl/source"},{"ns":"clojure.repl","name":"set-break-handler!","file":"clojure/repl.clj","type":"function","column":1,"see-alsos":null,"line":279,"examples":null,"notes":null,"arglists":["","f"],"doc":"Register INT signal handler. After calling this, Ctrl-C will cause\n the given function f to be called with a single argument, the signal.\n Uses thread-stopper if no function given.","library-url":"https://github.com/clojure/clojure","href":"/clojure.repl/set-break-handler!"},{"added":"1.3","ns":"clojure.repl","name":"root-cause","file":"clojure/repl.clj","type":"function","column":1,"see-alsos":null,"line":214,"examples":[{"updated-at":1559582779428,"created-at":1559576151369,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"body":"(require '[clojure.repl :refer [root-cause]])\n\n(def chained-exceptions \n (ex-info \"Problem.\" {:status :surprise} \n (try (/ 1 0) \n (catch Exception e \n (ex-info \"What happened?\" {:status :unknown} e)))))\n\n;; Only shows the first 3 items from the stack trace \n;; of the root-cause exception in chained-exceptions.\n\n(pst (root-cause chained-exceptions) 3)\n\n;; ArithmeticException Divide by zero\n;; clojure.lang.Numbers.divide (Numbers.java:158)\n;; clojure.lang.Numbers.divide (Numbers.java:3808)\n;; user/fn--2169 (form-init4179141376169992155.clj:3)\n\n","editors":[{"avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"}],"_id":"5cf53e57e4b0ca44402ef741"}],"notes":null,"arglists":["t"],"doc":"Returns the initial cause of an exception or error by peeling off all of\n its wrappers","library-url":"https://github.com/clojure/clojure","href":"/clojure.repl/root-cause"},{"added":"1.3","ns":"clojure.repl","name":"demunge","file":"clojure/repl.clj","type":"function","column":1,"see-alsos":[{"created-at":1559571453087,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"munge","ns":"clojure.core"},"_id":"5cf52bfde4b0ca44402ef73d"}],"line":207,"examples":[{"author":{"login":"devn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3"},"editors":[{"login":"devn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10421?v=4"}],"body":"user=> (require '[clojure.repl :as repl])\nnil\n\nuser=> (-> + class str)\n\"class clojure.core$_PLUS_\"\n\nuser=> (-> + class str repl/demunge)\n\"class clojure.core/+\"","created-at":1335431555000,"updated-at":1647645337838,"_id":"542692d6c026201cdc3270f6"}],"notes":null,"arglists":["fn-name"],"doc":"Given a string representation of a fn class,\n as in a stack trace element, returns a readable version.","library-url":"https://github.com/clojure/clojure","href":"/clojure.repl/demunge"},{"ns":"clojure.repl","name":"thread-stopper","file":"clojure/repl.clj","type":"function","column":1,"see-alsos":null,"line":273,"examples":null,"notes":null,"arglists":["","thread"],"doc":"Returns a function that takes one arg and uses that as an exception message\n to stop the given thread. Defaults to the current thread","library-url":"https://github.com/clojure/clojure","href":"/clojure.repl/thread-stopper"},{"ns":"clojure.repl","name":"apropos","file":"clojure/repl.clj","type":"function","column":1,"see-alsos":[{"to-var":{"library-url":"https://github.com/clojure/clojure","name":"source","ns":"clojure.repl"},"author":{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},"created-at":1342639345000,"_id":"542692ebf6e94c6970521e1e"},{"to-var":{"library-url":"https://github.com/clojure/clojure","name":"doc","ns":"clojure.repl"},"author":{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},"created-at":1342639350000,"_id":"542692ebf6e94c6970521e1f"},{"to-var":{"library-url":"https://github.com/clojure/clojure","name":"dir","ns":"clojure.repl"},"author":{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},"created-at":1342639354000,"_id":"542692ebf6e94c6970521e20"}],"line":181,"examples":[{"author":{"login":"teyc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bd6e62afb4881ab0f617611b8b65d003?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":"user=> (apropos \"temp\")\n()\n\nuser=> (require 'clojure.template)\nnil\n\nuser=> (apropos \"temp\")\n(apply-template do-template)\n","created-at":1283977701000,"updated-at":1285487332000,"_id":"542692d0c026201cdc326ecd"},{"updated-at":1611953795226,"created-at":1611953795226,"author":{"login":"sanel","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/213914?v=4"},"body":";; apropos can accept regex patterns. E.g. find only definitions\n;; ending with \"reduce\"\nuser=> (apropos #\".+?reduce\")\n(clojure.core/areduce clojure.core/ensure-reduced clojure.core/unreduced ...)\n\n;; get all public definitions from all currently-loaded namespaces\nuser=> (apropos #\"^+?\")\n(clojure.core/* clojure.core/*' clojure.core/*1 ...)","_id":"60147683e4b0b1e3652d7445"}],"notes":null,"arglists":["str-or-pattern"],"doc":"Given a regular expression or stringable thing, return a seq of all\npublic definitions in all currently-loaded namespaces that match the\nstr-or-pattern.","library-url":"https://github.com/clojure/clojure","href":"/clojure.repl/apropos"},{"added":"1.12","ns":"clojure.repl.deps","name":"add-libs","file":"clojure/repl/deps.clj","type":"function","column":1,"see-alsos":null,"line":35,"examples":null,"notes":null,"arglists":["lib-coords"],"doc":"Given lib-coords, a map of lib to coord, will resolve all transitive deps for the libs\n together and add them to the repl classpath, unlike separate calls to add-lib.","library-url":"https://github.com/clojure/clojure","href":"/clojure.repl.deps/add-libs"},{"added":"1.12","ns":"clojure.repl.deps","name":"sync-deps","file":"clojure/repl/deps.clj","type":"function","column":1,"see-alsos":null,"line":85,"examples":null,"notes":null,"arglists":["& {:as opts}"],"doc":"Calls add-libs with any libs present in deps.edn but not yet present on the classpath.\n\n :aliases - coll of alias keywords to use during the sync","library-url":"https://github.com/clojure/clojure","href":"/clojure.repl.deps/sync-deps"},{"added":"1.12","ns":"clojure.repl.deps","name":"add-lib","file":"clojure/repl/deps.clj","type":"function","column":1,"see-alsos":null,"line":59,"examples":null,"notes":null,"arglists":["lib coord","lib"],"doc":"Given a lib that is not yet on the repl classpath, make it available by\n downloading the library if necessary and adding it to the classloader.\n Libs already on the classpath are not updated. Requires a valid parent\n DynamicClassLoader.\n\n lib - symbol identifying a library, for Maven: groupId/artifactId\n coord - optional map of location information specific to the procurer,\n or latest if not supplied\n\n Returns coll of libs loaded, including transitive (or nil if none).\n\n For info on libs, coords, and versions, see:\n https://clojure.org/reference/deps_and_cli","library-url":"https://github.com/clojure/clojure","href":"/clojure.repl.deps/add-lib"},{"added":"1.0","ns":"clojure.set","name":"union","file":"clojure/set.clj","type":"function","column":1,"see-alsos":[{"created-at":1318523783000,"author":{"login":"mmwaikar","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/29d36f4c9f39c9f8ff61c07033b13118?r=PG&default=identicon"},"to-var":{"ns":"clojure.set","name":"intersection","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b57"},{"created-at":1318525824000,"author":{"login":"mmwaikar","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/29d36f4c9f39c9f8ff61c07033b13118?r=PG&default=identicon"},"to-var":{"ns":"clojure.set","name":"difference","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b58"},{"created-at":1318525832000,"author":{"login":"mmwaikar","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/29d36f4c9f39c9f8ff61c07033b13118?r=PG&default=identicon"},"to-var":{"ns":"clojure.set","name":"superset?","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b59"}],"line":20,"examples":[{"author":{"login":"Brian Marick","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a523012f661f603806ab1c22d855216f?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":"user=> (union)\n#{}\n\nuser=> (union #{1 2})\n#{1 2}\n\nuser=> (union #{1 2} #{2 3})\n#{1 2 3}\n\nuser=> (union #{1 2} #{2 3} #{3 4})\n#{1 2 3 4}\n","created-at":1278994901000,"updated-at":1412048733230,"_id":"542692d0c026201cdc326ed9"},{"editors":[{"login":"sleyzerzon","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/528932?v=3"},{"avatar-url":"https://avatars.githubusercontent.com/u/200617?v=3","account-source":"github","login":"bsima"}],"body":"(reduce (fn [flattened [key val]]\n (conj flattened val))\n #{}\n {:e #{:m :f}, :c #{:f}, :b #{:c :f}, :d #{:m :f}, :a #{:c :f}})\n\n;;=> #{#{:m :f} #{:c :f} #{:f}}\n\n\n(reduce (fn [flattened [key val]]\n (clojure.set/union flattened val))\n #{}\n {:e #{:m :f}, :c #{:f}, :b #{:c :f}, :d #{:m :f}, :a #{:c :f}})\n\n;;=> #{:m :c :f}","author":{"avatar-url":"https://avatars.githubusercontent.com/u/528932?v=3","account-source":"github","login":"sleyzerzon"},"created-at":1471130818331,"updated-at":1485272654530,"_id":"57afacc2e4b02d8da95c26f8"},{"updated-at":1471131322046,"created-at":1471131322046,"author":{"login":"sleyzerzon","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/528932?v=3"},"body":"(defn flatten-dpdnts [dpdnts-map]\n (apply set/union (vals dpdnts-map)))\n\n(flatten-dpdnts {:e #{:m :f}, :c #{:f}, :b #{:c :f}, :d #{:m :f}, :a #{:c :f}})\n;;=> #{:m :c :f}","_id":"57afaebae4b02d8da95c26fb"},{"updated-at":1532995894885,"created-at":1532655671091,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/109629?v=4"},"body":";; Advice: Do not call union with non-set arguments. If you are\n;; concerned that you may be unintentionally doing so, and want an\n;; exception to be thrown if you do, consider using the library\n;; funjible (https://github.com/jafingerhut/funjible) which provides\n;; its own definition of union that is identical to Clojure's, except\n;; it checks the types of its arguments.\n\n;; union might or might not return what you expect if you give it\n;; values that are not sets. The implementation of union _does not\n;; check_ whether you are actually giving it values that are sets. It\n;; _assumes_ so.\n\n;; This looks like what someone might expect. It _happens_ to give\n;; back the same answer as if you coerced the second argument to a\n;; set.\nuser=> (union #{1 2 3} [4 5])\n#{1 4 3 2 5}\n\n;; Wait, this returned a vector, not a set!\nuser=> (union #{1 2} [3 4 5])\n[3 4 5 1 2]\n\n;; This also returned a vector, and some elements are duplicates of\n;; each other!\nuser=> (union #{1 2} [3 4 5] #{4 5})\n[3 4 5 1 2 4 5]\n\n;; Why not change the definition of union so it throws an exception if\n;; you give it a non-set argument? I would guess that the primary\n;; reason is that the extra run-time type checks would slow union down\n;; by an amount that the Clojure core team does not want everyone to\n;; have to pay on every such call.\n\n;; Related Clojure tickets: \n;; https://dev.clojure.org/jira/browse/CLJ-1953\n;; https://dev.clojure.org/jira/browse/CLJ-2287\n","editors":[{"avatar-url":"https://avatars2.githubusercontent.com/u/109629?v=4","account-source":"github","login":"jafingerhut"}],"_id":"5b5a7837e4b00ac801ed9e2e"},{"updated-at":1545071198416,"created-at":1545071198416,"author":{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/94482?v=4"},"body":";; (set/union) treats nil as the empty set, as you'd probably expect.\n(clojure.set/union nil #{1 2} nil)\n;;=> #{1 2}\n\n;; This makes it handy to use as an accumulator in combination with (update-in):\n(update-in {} [:a :b :c] clojure.set/union #{333})\n;;=> {:a {:b {:c #{333}}}}\n","_id":"5c17ea5ee4b0ca44402ef5eb"},{"updated-at":1583387308326,"created-at":1583387308326,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"body":";; The \"powerset\" is the set of all the combinations of \"items\"\n(require '[clojure.set :refer [union]])\n\n(defn powerset [items]\n (reduce\n (fn [s x]\n (union s (map #(conj % x) s)))\n (hash-set #{})\n items))\n\n(powerset #{1 2 3})\n;; #{#{} #{3} #{2} #{1} #{1 3 2} #{1 3} #{1 2} #{3 2}}","_id":"5e6092ace4b087629b5a18b6"}],"notes":null,"arglists":["","s1","s1 s2","s1 s2 & sets"],"doc":"Return a set that is the union of the input sets","library-url":"https://github.com/clojure/clojure","href":"/clojure.set/union"},{"added":"1.0","ns":"clojure.set","name":"map-invert","file":"clojure/set.clj","type":"function","column":1,"see-alsos":null,"line":106,"examples":[{"author":{"login":"Brian Marick","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a523012f661f603806ab1c22d855216f?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":";; Despite being in clojure.set, this has nothing to do with sets. \n\nuser=> (map-invert {:a 1, :b 2})\n{2 :b, 1 :a}\n\n;; If there are duplicate keys, one is chosen:\n\nuser=> (map-invert {:a 1, :b 1})\n{1 :b}\n\n;; I suspect it'd be unwise to depend on which key survives the clash.","created-at":1278995220000,"updated-at":1285502749000,"_id":"542692d0c026201cdc326ee9"},{"updated-at":1483716604767,"created-at":1483716604767,"author":{"login":"bruno-oliveira","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/4722412?v=3"},"body":";; The inverted map of an empty map is also an empty map.\nuser=> (map-invert {})\n{}\n\n;; Using complex values (which serve as keys in the inverted map) is possible.\nuser=> ((map-invert {:a {:c 5}}) {:c 5})\n:a","_id":"586fb7fce4b09108c8545a49"},{"updated-at":1532105186014,"created-at":1532105186014,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"body":";; simple text obfuscation and back, with map-invert\n\n(def scramble-key\n {\\a \\t \\b \\m \\c \\o \\d \\l\n \\e \\z \\f \\i \\g \\b \\h \\u\n \\i \\h \\j \\n \\k \\s \\l \\r\n \\m \\a \\n \\q \\o \\d \\p \\e\n \\q \\k \\r \\y \\s \\f \\t \\c\n \\u \\p \\v \\w \\w \\x \\x \\j\n \\y \\g \\z \\v \\space \\space})\n\n(defn scramble [text scramble-key]\n (apply str (map scramble-key text)))\n\n(defn unscramble [text scramble-key]\n (apply str (map (map-invert scramble-key) text)))\n\n(scramble \"try to read this if you can\" scramble-key)\n;; \"cyg cd yztl cuhf hi gdp otq\"\n\n(unscramble \"cyg cd yztl cuhf hi gdp otq\" scramble-key)\n;; \"try to read this if you can\"","_id":"5b5211e2e4b00ac801ed9e29"}],"notes":[{"author":{"login":"optevo","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/1281179?v=4"},"updated-at":1573544646653,"created-at":1573544406399,"body":"If you have the possibility of duplicate values, in your map, the invert-map function will only preserve one of them. An alternative which doesn't eliminate values is to ensure all values are sets then use the following function:\n
    (defn invert-map-of-sets [m]\n   (reduce (fn [a [k v]] (assoc a k (conj (get a k #{}) v))) {} (for [[k s] m v s] [v k]))))
    \nThis will work as follows:\n
    ;; From\n{1 #{:a :b :c} 2 #{:b :c :d}}
    \n\n
    ;; To\n{:c #{1 2}, :b #{1 2}, :a #{1}, :d #{2}}
    \n\n\n\n\n","_id":"5dca61d6e4b0ca44402ef7da"}],"arglists":["m"],"doc":"Returns the map with the vals mapped to the keys.","library-url":"https://github.com/clojure/clojure","href":"/clojure.set/map-invert"},{"added":"1.0","ns":"clojure.set","name":"join","file":"clojure/set.clj","type":"function","column":1,"see-alsos":[{"created-at":1533910568303,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"rename","ns":"clojure.set"},"_id":"5b6d9e28e4b00ac801ed9e50"}],"line":115,"examples":[{"updated-at":1493911041846,"created-at":1278825825000,"body":";; This simple example shows each element of the first relation joined\n;; with each element of the second (because they have no columns in common):\n\nuser=> (def first-relation #{ {:a 1} {:a 2} })\nuser=> (def second-relation #{ {:b 1} {:b 2} })\nuser=> (join first-relation second-relation)\n#{{:b 1, :a 1} \n {:b 2, :a 1} \n {:b 1, :a 2} \n {:b 2, :a 2}}\n\n\n;; Here's a larger example, in which a relation mainly about animal ownership\n;; is joined with a relation about animal personality. The join is used to \n;; produce a relation joining information about an animal's personality to \n;; that animal.\n\nuser=> (def animals #{{:name \"betsy\" :owner \"brian\" :kind \"cow\"}\n {:name \"jake\" :owner \"brian\" :kind \"horse\"}\n {:name \"josie\" :owner \"dawn\" :kind \"cow\"}})\n\nuser=> (def personalities #{{:kind \"cow\" :personality \"stoic\"}\n {:kind \"horse\" :personality \"skittish\"}})\n#'user/personalities\nuser=> (join animals personalities)\n\n#{{:owner \"dawn\", :name \"josie\", :kind \"cow\", :personality \"stoic\"}\n {:owner \"brian\", :name \"betsy\", :kind \"cow\", :personality \"stoic\"}\n {:owner \"brian\", :name \"jake\", :kind \"horse\", :personality \"skittish\"}}\n\n\n;; (If cows had two personalities, instead of one, each cow would have \n;; two rows in the output.)\n\n;; Suppose `personalities` used `:species` instead of `:kind`:\n\nuser=> (def personalities #{{:species \"cow\" :personality \"stoic\"}\n {:species \"horse\" :personality \"skittish\"}})\n\n\n;; A simple join would produce results like this:\n\nuser=> (join animals personalities)\n#{{:kind \"horse\", :owner \"brian\", :name \"jake\", :species \"cow\", :personality \"stoic\"}\n {:kind \"cow\", :owner \"dawn\", :name \"josie\", :species \"cow\", :personality \"stoic\"}\n {:kind \"horse\", :owner \"brian\", :name \"jake\", :species \"horse\", :personality \"skittish\"}\n {:kind \"cow\", :owner \"brian\", :name \"betsy\", :species \"cow\", :personality \"stoic\"}\n {:kind \"cow\", :owner \"dawn\", :name \"josie\", :species \"horse\", :personality \"skittish\"}\n {:kind \"cow\", :owner \"brian\", :name \"betsy\", :species \"horse\", :personality \"skittish\"}}\n\n\n;; Notice that \"Jake\" is both a horse and a cow in the first line. That's \n;; likely not what you want. You can tell `join` to only produce output \n;; where the `:kind` value is the same as the `:species` value like this:\n\nuser=> (join animals personalities {:kind :species})\n#{{:kind \"cow\", :owner \"dawn\", :name \"josie\", :species \"cow\", :personality \"stoic\"}\n {:kind \"horse\", :owner \"brian\", :name \"jake\", :species \"horse\", :personality \"skittish\"}\n {:kind \"cow\", :owner \"brian\", :name \"betsy\", :species \"cow\", :personality \"stoic\"}}\n\n\n;; Notice that the `:kind` and `:species` keys both appear in each output map.\n","editors":[{"avatar-url":"https://www.gravatar.com/avatar/a523012f661f603806ab1c22d855216f?r=PG&default=identicon","account-source":"clojuredocs","login":"Brian Marick"},{"avatar-url":"https://www.gravatar.com/avatar/a523012f661f603806ab1c22d855216f?r=PG&default=identicon","account-source":"clojuredocs","login":"Brian Marick"},{"avatar-url":"https://www.gravatar.com/avatar/a523012f661f603806ab1c22d855216f?r=PG&default=identicon","account-source":"clojuredocs","login":"Brian Marick"},{"avatar-url":"https://www.gravatar.com/avatar/a523012f661f603806ab1c22d855216f?r=PG&default=identicon","account-source":"clojuredocs","login":"Brian Marick"},{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"avatar-url":"https://www.gravatar.com/avatar/90ffa70a579c3e0c398b7523ecdc6a87?r=PG&default=identicon","account-source":"clojuredocs","login":"morphling"},{"login":"tomaskulich","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/4833191?v=3"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/a523012f661f603806ab1c22d855216f?r=PG&default=identicon","account-source":"clojuredocs","login":"Brian Marick"},"_id":"542692d0c026201cdc326edf"},{"updated-at":1493911081751,"created-at":1493911081751,"author":{"login":"tomaskulich","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/4833191?v=3"},"body":"\n;; If you don't specify `km`, `join` has to 'guess' on which attributes to join.\n;; Sometimes, result may surprise you:\n\nuser=> (join [{:a 1 :b 2}] [{:c 3 :d 4} {:a 5 :b 6}]) \n;#{{:a 5, :b 6} {:a 1, :b 2, :c 3, :d 4}}","_id":"590b4629e4b01f4add58feaa"},{"updated-at":1631961178190,"created-at":1533911386656,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"body":";; join with rename of (otherwise clashing) keys. Note that in the following\n;; relations, we have \"user.type\" and \"account.type\"\n\n(def users\n #{{:user-id 1 :name \"john\" :age 22 :type \"personal\"}\n {:user-id 2 :name \"jake\" :age 28 :type \"company\"}\n {:user-id 3 :name \"amanda\" :age 63 :type \"personal\"}})\n\n(def accounts\n #{{:acc-id 1 :user-id 1 :amount 300.45 :type \"saving\"}\n {:acc-id 2 :user-id 2 :amount 1200.0 :type \"saving\"}\n {:acc-id 3 :user-id 1 :amount 850.1 :type \"debit\"}})\n\n(require '[clojure.set :as s])\n\n;; Clojure equivalent of the SQL:\n;; SELECT users.user-id, accounts.acc-id, \n;; users.type as type, accounts.type as atype\n;; FROM users\n;; INNER JOIN accounts ON users.user-id = accounts.user-id;\n\n(s/project\n (s/join users (s/rename accounts {:type :atype}))\n [:user-id :acc-id :type :atype])\n\n;; #{{:user-id 1, :acc-id 1, :type \"personal\", :atype \"saving\"}\n;; {:user-id 2, :acc-id 2, :type \"company\", :atype \"saving\"}\n;; {:user-id 1, :acc-id 3, :type \"personal\", :atype \"debit\"}}\n\n","editors":[{"avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"},{"login":"marckoch","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/20969375?v=4"}],"_id":"5b6da15ae4b00ac801ed9e51"}],"notes":null,"arglists":["xrel yrel","xrel yrel km"],"doc":"When passed 2 rels, returns the rel corresponding to the natural\n join. When passed an additional keymap, joins on the corresponding\n keys.","library-url":"https://github.com/clojure/clojure","href":"/clojure.set/join"},{"added":"1.0","ns":"clojure.set","name":"select","file":"clojure/set.clj","type":"function","column":1,"see-alsos":[{"created-at":1321756919000,"author":{"login":"alimoeeny","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9e8dd06976ead4082d2181f3807117e1?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"filter","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d82"},{"created-at":1687507624559,"author":{"login":"daveliepmann","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/974443?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"project","ns":"clojure.set"},"_id":"649552a8e4b08cf8563f4bca"},{"created-at":1687507661784,"author":{"login":"daveliepmann","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/974443?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"join","ns":"clojure.set"},"_id":"649552cde4b08cf8563f4bcb"}],"line":65,"examples":[{"author":{"login":"Brian Marick","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a523012f661f603806ab1c22d855216f?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"kimh","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/924390?v=3"},{"avatar-url":"https://avatars.githubusercontent.com/u/8908139?v=3","account-source":"github","login":"bsifou"}],"body":"(clojure.set/select odd? #{1 2 3})\n;;=> #{1 3}\n","created-at":1278822406000,"updated-at":1486787976866,"_id":"542692d0c026201cdc326edb"}],"notes":null,"arglists":["pred xset"],"doc":"Returns a set of the elements for which pred is true","library-url":"https://github.com/clojure/clojure","href":"/clojure.set/select"},{"added":"1.0","ns":"clojure.set","name":"intersection","file":"clojure/set.clj","type":"function","column":1,"see-alsos":[{"created-at":1318523876000,"author":{"login":"mmwaikar","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/29d36f4c9f39c9f8ff61c07033b13118?r=PG&default=identicon"},"to-var":{"ns":"clojure.set","name":"union","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521aab"},{"created-at":1318525852000,"author":{"login":"mmwaikar","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/29d36f4c9f39c9f8ff61c07033b13118?r=PG&default=identicon"},"to-var":{"ns":"clojure.set","name":"difference","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521aac"},{"created-at":1318525861000,"author":{"login":"mmwaikar","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/29d36f4c9f39c9f8ff61c07033b13118?r=PG&default=identicon"},"to-var":{"ns":"clojure.set","name":"superset?","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521aad"},{"created-at":1366429268000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.set","name":"project","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521aae"}],"line":33,"examples":[{"updated-at":1447239876245,"created-at":1278994500000,"body":"user=> (clojure.set/intersection #{1})\n#{1}\nuser=> (clojure.set/intersection #{1 2} #{2 3})\n#{2}\nuser=> (clojure.set/intersection #{1 2} #{2 3} #{3 4})\n#{}\nuser=> (clojure.set/intersection #{1 :a} #{:a 3} #{:a})\n#{:a}\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"login":"edipofederle","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/50778?v=3"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/a523012f661f603806ab1c22d855216f?r=PG&default=identicon","account-source":"clojuredocs","login":"Brian Marick"},"_id":"542692d0c026201cdc326ee7"},{"updated-at":1698848372616,"created-at":1474101854124,"author":{"login":"mhmdsalem1993","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10787314?v=3"},"body":"(defn find-divisors [x]\n (->> (range 1 (inc x))\n (into #{} (filter #(zero? (mod x %))))))\n\n(find-divisors 10)\n;; => #{1 2 5 10}\n\n;; Greatest common divisor\n(defn gcd [x y]\n (let [x-div (find-divisors x)\n y-div (find-divisors y)]\n (apply max (clojure.set/intersection y-div x-div))))\n\n(gcd 10 5)\n;; => 5\n\n;; Lowest common multiple\n(defn lcm [x y]\n (/ (Math/abs (* x y)) (gcd x y)))\n\n(lcm 13 11)\n;; => 143","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/10787314?v=3","account-source":"github","login":"mhmdsalem1993"},{"avatar-url":"https://avatars.githubusercontent.com/u/29694576?v=4","account-source":"github","login":"cstml"}],"_id":"57dd025ee4b0709b524f04fc"},{"updated-at":1494919958612,"created-at":1494919958612,"author":{"login":"abhilater","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/1904958?v=3"},"body":"(clojure.set/intersection #{:a :b :c} #{:d :c :b})\n;=> #{:b :c}\n\n(clojure.set/intersection #{:a :e :i :o :u}\n\t\t\t #{:a :u :r}\n\t\t\t #{:r :u :s})\n;=> #{:u}","_id":"591aab16e4b01920063ee05e"},{"updated-at":1532996003370,"created-at":1532676926792,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/109629?v=4"},"body":";; Advice: Do not call intersection with non-set arguments. If you\n;; are concerned that you may be unintentionally doing so, and want an\n;; exception to be thrown if you do, consider using the library\n;; funjible (https://github.com/jafingerhut/funjible) which provides\n;; its own definition of intersection that is identical to Clojure's,\n;; except it checks the types of its arguments.\n\n;; intersection might or might not return what you expect if you give it\n;; values that are not sets. The implementation of intersection _does not\n;; check_ whether you are actually giving it values that are sets. It\n;; _assumes_ so.\n\n;; It is possible that intersection _might_ throw an exception if you\n;; give it a non-set as an argument:\nuser=> (intersection #{1 3 5} [2 4])\nClassCastException clojure.lang.PersistentVector cannot be cast to clojure.lang.IPersistentSet clojure.core/disj (core.clj:1517)\n\n;; But it can also simply return an answer that is not the\n;; intersection of the two collections:\nuser=> (intersection #{1 3 5} [2 4 6 8])\n#{1 3}\n\n;; In the previous case, it includes elements in the returned set that\n;; you would not expect. It can also leave out elements in the\n;; returned set that you would expect to find there.\nuser=> (intersection #{\"1\" \"3\" \"5\"} [\"1\" \"3\" \"5\" \"7\"])\n#{}\n\n;; Why not change the definition of intersection so it always throws\n;; an exception if you give it a non-set argument? I would guess that\n;; the primary reason is that the extra run-time type checks would\n;; slow intersection down by an amount that the Clojure core team does\n;; not want everyone to have to pay on every such call.\n\n;; Related Clojure tickets: \n;; https://dev.clojure.org/jira/browse/CLJ-1953\n;; https://dev.clojure.org/jira/browse/CLJ-2287\n","editors":[{"avatar-url":"https://avatars2.githubusercontent.com/u/109629?v=4","account-source":"github","login":"jafingerhut"}],"_id":"5b5acb3ee4b00ac801ed9e35"},{"updated-at":1729534452333,"created-at":1729534452333,"author":{"login":"claj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/353113?v=4"},"body":";; using clojure.set operations as query optimization:\n;; given a vector of map items:\n\n(def data [{:gender \"male\", :age-group \"child\", :origin \"Germany\", :prename \"Hans\"}\n\t {:gender \"male\", :age-group \"adult\", :origin \"France\", :prename \"Jacques\"}\n\t {:gender \"male\", :age-group \"senior\", :origin \"Estonia\", :prename \"Rasmus\"}\n\t {:gender \"male\", :age-group \"adult\", :origin \"Poland\", :prename \"Jakub\"}\n\t {:gender \"male\", :age-group \"senior\", :origin \"Germany\", :prename \"Uwe\"}\n\t {:gender \"female\", :age-group \"adult\", :origin \"France\", :prename \"Amélie\"}\n\t {:gender \"female\", :age-group \"child\", :origin \"Estonia\", :prename \"Sofia\"}\n\t {:gender \"female\", :age-group \"child\", :origin \"Germany\", :prename \"Emma\"}\n\t {:gender \"female\", :age-group \"child\", :origin \"Estonia\", :prename \"Alisa\"}\n\t {:gender \"female\", :age-group \"senior\", :origin \"Poland\", :prename \"Anna\"}])\n\n;; we can create key -> \"value\" -> set of idx pointers \n;; note: (reduce-kv calls aggregator fn with [aggregate index-in-vector value] when using vectors as the key-value collection.\n\n(def db-index\n (reduce-kv\n (fn [db idx item]\n (reduce\n (fn [db index-on]\n (update db index-on update (get item index-on) (fnil conj #{}) idx)) \n db [:gender :age-group :origin :prename]))\n {} data))\n\n;; results in this key - val -> #{indexes} in vector\n\n{:gender {\"male\" #{0 1 4 3 2},\n \"female\" #{7 6 9 5 8}},\n \n :age-group {\"child\" #{0 7 6 8},\n \"adult\" #{1 3 5},\n \"senior\" #{4 2 9}},\n \n :origin {\"Germany\" #{0 7 4},\n \"France\" #{1 5},\n \"Estonia\" #{6 2 8},\n \"Poland\" #{3 9}},\n \n :prename {\"Sofia\" #{6}, \"Rasmus\" #{2}, \"Hans\" #{0}, \"Amélie\" #{5}, \"Jakub\" #{3},\n \"Jacques\" #{1}, \"Emma\" #{7}, \"Alisa\" #{8}, \"Uwe\" #{4}, \"Anna\" #{9}}}\n\n;; by using intersection on two different key-values indexes we get the items\n;; with these properties, for instance \"find all men from Germany\"\n\n(def all-men-from-germany-idxs\n (clojure.set/intersection\n (get-in db-index [:gender \"male\"])\n (get-in db-index [:origin \"Germany\"])))\n\n;; \n\n(map data (sort all-men-from-germany-idxs))\n","_id":"671699f469fbcc0c22617506"}],"notes":null,"arglists":["s1","s1 s2","s1 s2 & sets"],"doc":"Return a set that is the intersection of the input sets","library-url":"https://github.com/clojure/clojure","href":"/clojure.set/intersection"},{"added":"1.2","ns":"clojure.set","name":"superset?","file":"clojure/set.clj","type":"function","column":1,"see-alsos":[{"created-at":1338064940000,"author":{"login":"jasonrudolph.com","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/c4e34ac0818591402a41b2e9cfb4747b?r=PG&default=identicon"},"to-var":{"ns":"clojure.set","name":"subset?","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d31"},{"created-at":1338064955000,"author":{"login":"jasonrudolph.com","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/c4e34ac0818591402a41b2e9cfb4747b?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"set","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d32"}],"line":154,"examples":[{"author":{"login":"jasonrudolph.com","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/c4e34ac0818591402a41b2e9cfb4747b?r=PG&default=identicon"},"editors":[],"body":"(use '[clojure.set :only [superset?]])\n\nuser=> (superset? #{0} #{0})\ntrue\n\nuser=> (superset? #{0 1} #{0})\ntrue\n\nuser=> (superset? #{0} #{0 1}) \nfalse\n","created-at":1338064647000,"updated-at":1338064647000,"_id":"542692d6c026201cdc3270fc"},{"updated-at":1543865081521,"created-at":1532677432379,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/109629?v=4"},"body":";; Advice: Do not call superset? with non-set arguments. If you are\n;; concerned that you may be unintentionally doing so, and want an\n;; exception to be thrown if you do, consider using the library\n;; funjible (https://github.com/jafingerhut/funjible) which provides\n;; its own definition of superset? that is identical to Clojure's,\n;; except it checks the types of its arguments.\n\n;; superset? might or might not return what you expect if you give it\n;; values that are not sets. The implementation of superset? _does not\n;; check_ whether you are actually giving it values that are sets. It\n;; _assumes_ so.\n\n;; If the first argument were a set with the same elements, you would\n;; expect the return value false here.\nuser=> (superset? [2 4 6 8] #{1 3})\ntrue\n\n;; Here, if the first argument were a set with the same elements as\n;; the vector, you would expect the return value true.\nuser=> (superset? [1 3 5] #{1 3 5})\nfalse\n\n;; And similarly here:\nuser=> (superset? [\"1\" \"3\" \"5\"] #{\"1\" \"3\"})\nfalse\n\n;; Switching to considering cases where the second argument is not a set, this\n;; appears to do what one would hope:\nuser=> (superset? #{1 2 3 4 5} [1 2 3 4])\ntrue\n\n;; ... but this does not (at least up until Clojure 1.10 this behavior is\n;; because of how superset? is implemented, first comparing the count of the\n;; two collections to make it possible to quickly return false when the second\n;; collection is larger):\nuser=> (subset? #{1 2 3 4 5} [1 2 3 4 1 2 3 4])\nfalse\n\n;; Why not change the definition of superset? so it always throws\n;; an exception if you give it a non-set argument? I would guess that\n;; the primary reason is that the extra run-time type checks would\n;; slow superset? down by an amount that the Clojure core team does\n;; not want everyone to have to pay on every such call.\n\n;; Related Clojure tickets: \n;; https://dev.clojure.org/jira/browse/CLJ-1953\n;; https://dev.clojure.org/jira/browse/CLJ-2287\n","editors":[{"avatar-url":"https://avatars2.githubusercontent.com/u/109629?v=4","account-source":"github","login":"jafingerhut"}],"_id":"5b5acd38e4b00ac801ed9e39"}],"notes":null,"tag":"java.lang.Boolean","arglists":["set1 set2"],"doc":"Is set1 a superset of set2?","library-url":"https://github.com/clojure/clojure","href":"/clojure.set/superset_q"},{"added":"1.0","ns":"clojure.set","name":"index","file":"clojure/set.clj","type":"function","column":1,"see-alsos":[{"created-at":1290275867000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"hash-map","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b48"},{"created-at":1290275888000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"get","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b49"}],"line":95,"examples":[{"author":{"login":"Brian Marick","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a523012f661f603806ab1c22d855216f?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"login":"taylor.sando","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/c127297f5548f7275ded1428aa5518bb?r=PG&default=identicon"},{"login":"taylor.sando","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/c127297f5548f7275ded1428aa5518bb?r=PG&default=identicon"},{"login":"taylor.sando","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/c127297f5548f7275ded1428aa5518bb?r=PG&default=identicon"},{"avatar-url":"https://avatars0.githubusercontent.com/u/7083783?v=4","account-source":"github","login":"cloojure"},{"login":"conan","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/3037019?v=4"}],"body":"(use '[clojure.set :only (index)])\n\n;; Suppose you have a set of descriptions of the weights of animals:\n\nuser=> (def weights #{ {:name 'betsy :weight 1000}\n {:name 'jake :weight 756}\n {:name 'shyq :weight 1000} })\n\n\n; You want the names of all the animals that weigh 1000. One way to do \n; that uses `index`. First, you can group the set elements (the maps) so\n; that those with the same weights are in the same group.\nuser=> (def by-weight (index weights [:weight]))\n#'user/by-weight\n\n; index returns a map. The keys are maps themselves, where {:weight 756} \n; and {:weight 1000} are taken from the maps in the weights set. \n; The values in the map returned by index are sets that contain map \n; entries from the above weights set.\nuser=> by-weight\n{{:weight 756} #{{:name jake, :weight 756}}, \n {:weight 1000} #{{:name shyq, :weight 1000} \n {:name betsy, :weight 1000}}}\n\n; To better visualize the by-weight map that is returned by index, \n; you can query it using get, using {:weight 756} as the key. This \n; will return all the maps (animals) that contain a weight of 756. \n; In this case, there is only one result, which is a set containing \n; a single map. \nuser=> (get by-weight {:weight 756})\n#{{:name jake, :weight 756}}\n\n; To see that there are two animals with a weight of 1000, you can \n; query by-weight with the key {:weight 1000}. This returns a set \n; containing two maps.\nuser=> (get by-weight {:weight 1000})\n#{{:name shyq, :weight 1000} {:name betsy :weight 1000}}\n\n; You can verify by using count\nuser=> (count (get by-weight {:weight 1000}))\n2\n\n; To get the names of those two animals we can map a name-extracting function\n; over the set of two maps. Since a keyword in a map is also a function that\n; returns its corresponding value, we can just use `:name` as our function:\nuser=> (map :name (get by-weight {:weight 1000}))\n(shyq betsy)\n","created-at":1278996864000,"updated-at":1612200146773,"_id":"542692d0c026201cdc326ef1"},{"updated-at":1601047527682,"created-at":1523214100238,"author":{"login":"statcompute","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/4590938?v=4"},"body":";; You can do a join using 'index'\n(require '[clojure.set :as s]\n '[clojure.core.reducers :as r])\n \n(def ds1 [{:id 1 :name \"name1\"}\n {:id 2 :name \"name2\"}\n {:id 3 :name \"name3\"}])\n \n(def ds2 [{:id 2 :address \"addr2\"}\n {:id 3 :address \"addr3\"}\n {:id 4 :address \"addr4\"}])\n\n(into () (r/map #(r/reduce merge %) (vals (s/index (s/union ds2 ds1) [:id]))))\n;; ({:id 1, :name \"name1\"}\n;; {:id 4, :address \"addr4\"}\n;; {:id 3, :name \"name3\", :address \"addr3\"}\n;; {:id 2, :address \"addr2\", :name \"name2\"})\n","editors":[{"avatar-url":"https://avatars3.githubusercontent.com/u/11434205?v=4","account-source":"github","login":"dijonkitchen"},{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"}],"_id":"5aca6714e4b045c27b7fac3a"},{"updated-at":1729534651029,"created-at":1729534651029,"author":{"login":"claj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/353113?v=4"},"body":";; use index to query a data set\n\n(def data [{:gender \"male\", :age-group \"child\", :origin \"Germany\", :prename \"Hans\"}\n\t {:gender \"male\", :age-group \"adult\", :origin \"France\", :prename \"Jacques\"}\n\t {:gender \"male\", :age-group \"senior\", :origin \"Estonia\", :prename \"Rasmus\"}\n\t {:gender \"male\", :age-group \"adult\", :origin \"Poland\", :prename \"Jakub\"}\n\t {:gender \"male\", :age-group \"senior\", :origin \"Germany\", :prename \"Uwe\"}\n\t {:gender \"female\", :age-group \"adult\", :origin \"France\", :prename \"Amélie\"}\n\t {:gender \"female\", :age-group \"child\", :origin \"Estonia\", :prename \"Sofia\"}\n\t {:gender \"female\", :age-group \"child\", :origin \"Germany\", :prename \"Emma\"}\n\t {:gender \"female\", :age-group \"child\", :origin \"Estonia\", :prename \"Alisa\"}\n\t {:gender \"female\", :age-group \"senior\", :origin \"Poland\", :prename \"Anna\"}])\n\n(def the-index (clojure.set/index data [:gender :origin]))\n\n;; find all men originating from Germany:\n\n(get the-index {:gender \"male\" :origin \"Germany\"})\n\n;; =>\n\n#{{:gender \"male\", :age-group \"child\", :origin \"Germany\", :prename \"Hans\"}\n {:gender \"male\", :age-group \"senior\", :origin \"Germany\", :prename \"Uwe\"}}","_id":"67169abb69fbcc0c22617507"}],"notes":null,"arglists":["xrel ks"],"doc":"Returns a map of the distinct values of ks in the xrel mapped to a\n set of the maps in xrel with the corresponding values of ks.","library-url":"https://github.com/clojure/clojure","href":"/clojure.set/index"},{"added":"1.2","ns":"clojure.set","name":"subset?","file":"clojure/set.clj","type":"function","column":1,"see-alsos":[{"created-at":1293674668000,"author":{"login":"dakrone","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bcacd00a7f05c4772329cf9f446c7987?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"set?","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521a98"},{"created-at":1293674671000,"author":{"login":"dakrone","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bcacd00a7f05c4772329cf9f446c7987?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"set","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521a99"},{"created-at":1338064920000,"author":{"login":"jasonrudolph.com","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/c4e34ac0818591402a41b2e9cfb4747b?r=PG&default=identicon"},"to-var":{"ns":"clojure.set","name":"superset?","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521a9a"},{"created-at":1512076531871,"author":{"login":"chbrown","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/360279?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"every?","ns":"clojure.core"},"_id":"5a2074f3e4b0a08026c48cc9"}],"line":146,"examples":[{"author":{"login":"dakrone","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bcacd00a7f05c4772329cf9f446c7987?r=PG&default=identicon"},"editors":[],"body":"user> (clojure.set/subset? #{2 3} #{1 2 3 4})\ntrue\n\nuser> (clojure.set/subset? #{2 4} #{1 2 3 4})\ntrue\n\nuser> (clojure.set/subset? #{2 5} #{1 2 3 4})\nfalse","created-at":1293674661000,"updated-at":1293674661000,"_id":"542692d0c026201cdc326ee6"},{"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/109629?v=4"}],"body":";; Advice: Do not call subset? with non-set arguments. If you are\n;; concerned that you may be unintentionally doing so, and want an\n;; exception to be thrown if you do, consider using the library\n;; funjible (https://github.com/jafingerhut/funjible) which provides\n;; its own definition of subset? that is identical to Clojure's,\n;; except it checks the types of its arguments.\n\n;; subset? might or might not return what you expect if you give it\n;; values that are not sets. The implementation of subset? _does not\n;; check_ whether you are actually giving it values that are sets. It\n;; _assumes_ so.\n\n;; If the second argument were a set with the same elements, you would\n;; expect the return value false here.\nuser=> (subset? #{1 3} [2 4 6 8])\ntrue\n\n;; Here, if the second argument were a set with the same elements as\n;; the vector, you would expect the return value true.\nuser=> (subset? #{1 3 5} [1 3 5])\nfalse\n\n;; And similarly here:\nuser=> (subset? #{\"1\" \"3\"} [\"1\" \"3\" \"5\"])\nfalse\n\n;; Switching to considering cases where the first argument is not a set, this\n;; appears to do what one would hope:\nuser=> (subset? [1 2 3 4] #{1 2 3 4 5})\ntrue\n\n;; ... but this does not (at least up until Clojure 1.10 this behavior is\n;; because of how subset? is implemented, first comparing the count of the\n;; two collections to make it possible to quickly return false when the first\n;; collection is larger):\nuser=> (subset? [1 2 3 4 1 2 3 4] #{1 2 3 4 5})\nfalse\n\n;; Why not change the definition of subset? so it always throws\n;; an exception if you give it a non-set argument? I would guess that\n;; the primary reason is that the extra run-time type checks would\n;; slow subset? down by an amount that the Clojure core team does\n;; not want everyone to have to pay on every such call.\n\n;; Related Clojure tickets: \n;; https://dev.clojure.org/jira/browse/CLJ-1953\n;; https://dev.clojure.org/jira/browse/CLJ-2287\n","author":{"avatar-url":"https://avatars2.githubusercontent.com/u/109629?v=4","account-source":"github","login":"jafingerhut"},"created-at":1532677195231,"updated-at":1543865004707,"_id":"5b5acc4be4b00ac801ed9e37"},{"updated-at":1732626156742,"created-at":1732626156742,"author":{"login":"wxnn08","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/26045915?v=4"},"body":"user=> (subset? #{1 2 3} {1 2})\nfalse","_id":"6745c6ec69fbcc0c2261751d"}],"notes":[{"body":"Do note that this will only work as expected for sets. subset? uses contains? in it's implementation. The functionality in contains? for vectors can be slightly unintuitive at first, and causes functions like this to perform in completely unexpected ways when using vectors instead of sets. For example,\n\n```\nuser> (clojure.set/subset? [0 1] [2 3])\ntrue\nuser> (clojure.set/subset? [2 3] [2 3])\nfalse\n```\n\nIt is slightly more intuitive with maps, as it checks whether every item in the first collection is a key in the map passed in as the 2nd parameter, but still is probably a bit confusing to someone reading your code.\n\n```\nuser> (clojure.set/subset? '(7 8) {8 1 7 3})\ntrue\nuser> (clojure.set/subset? '(9 10) {8 1 7 3})\nfalse\n```\n\nLong story short, if you're using functions from the clojure.set namespace, make sure you're passing in sets. ","created-at":1422419407728,"updated-at":1422422014024,"author":{"login":"arkdrag","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1578334?v=3"},"_id":"54c865cfe4b0e2ac61831ce5"}],"tag":"java.lang.Boolean","arglists":["set1 set2"],"doc":"Is set1 a subset of set2?","library-url":"https://github.com/clojure/clojure","href":"/clojure.set/subset_q"},{"added":"1.0","ns":"clojure.set","name":"rename","file":"clojure/set.clj","type":"function","column":1,"see-alsos":[{"created-at":1313707898000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.set","name":"rename-keys","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e1a"}],"line":89,"examples":[{"author":{"login":"Brian Marick","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a523012f661f603806ab1c22d855216f?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":";; Here's a relation with two keys (think \"column names\" in SQL), :a and :b\n\nuser=> (def relation #{ {:a 1, :b 1} {:a 2, :b 2} })\n\n\n;; I decide that :a is a stupid name and that :new-a would be better. \n;; Here's how I make a new relation with the renamed key:\n\nuser=> (rename relation {:a :new-a})\n#{{:new-a 1, :b 1} {:new-a 2, :b 2}}\n\n","created-at":1278824834000,"updated-at":1285503801000,"_id":"542692d0c026201cdc326eef"}],"notes":null,"arglists":["xrel kmap"],"doc":"Returns a rel of the maps in xrel with the keys in kmap renamed to the vals in kmap","library-url":"https://github.com/clojure/clojure","href":"/clojure.set/rename"},{"added":"1.0","ns":"clojure.set","name":"rename-keys","file":"clojure/set.clj","type":"function","column":1,"see-alsos":[{"created-at":1313707906000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.set","name":"rename","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d90"}],"line":78,"examples":[{"author":{"login":"Brian Marick","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a523012f661f603806ab1c22d855216f?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"Stathis Sideris","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/299a3fab7a1a2d6644455dedae9fce0a?r=PG&default=identicon"}],"body":"user=> (rename-keys {:a 1, :b 2} {:a :new-a, :b :new-b})\n{:new-a 1, :new-b 2}\n\n\n;; The behavior when the second map contains a key not in the first is interesting.\n;; I suspect you shouldn't depend on it. (Clojure 1.1 - no longer happens in 1.2.1)\n\nuser=> (rename-keys {:a 1} {:b :new-b})\n{ :a 1, :new-b nil}\n","created-at":1278824415000,"updated-at":1350332324000,"_id":"542692d0c026201cdc326ed2"},{"author":{"login":"steveminer","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d28543d134185d12d4006a74738d233e?r=PG&default=identicon"},"editors":[{"login":"steveminer","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d28543d134185d12d4006a74738d233e?r=PG&default=identicon"},{"login":"steveminer","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d28543d134185d12d4006a74738d233e?r=PG&default=identicon"},{"login":"steveminer","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d28543d134185d12d4006a74738d233e?r=PG&default=identicon"},{"avatar-url":"https://avatars1.githubusercontent.com/u/28267638?v=4","account-source":"github","login":"mrkam2"},{"login":"dijonkitchen","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/11434205?v=4"}],"body":";; You need to be careful about key collisions. You probably shouldn't \n;; depend on the exact behavior.\nuser=> (rename-keys {:a 1 :b 2} {:a :b})\n{:b 1}\n","created-at":1305262334000,"updated-at":1576884199874,"_id":"542692d0c026201cdc326ed5"},{"updated-at":1548872180983,"created-at":1548872180983,"author":{"login":"mrkam2","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/28267638?v=4"},"body":";; Key collisions no longer reproducible in Clojure 1.10.0\nuser=> (rename-keys {:a 1 :b 2} {:a :b :b :a})\n{:b 1, :a 2}","_id":"5c51e9f4e4b0ca44402ef65d"},{"editors":[{"login":"Jeel-Shah","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/4922694?v=4"}],"body":";; Note that rename-keys in the clojure.set namespace. In order to use it, you\n;; must require the namespace\n\nuser=> (require '[clojure.set :as set])\nuser=> (set/rename-keys {:a 1 :b 2} {:a :new-a})\n=> {:new-a 1 :b 2}\n\n;; Alternatively, you can use rename-keys by simply doing clojure.set/rename-keys","author":{"avatar-url":"https://avatars2.githubusercontent.com/u/4922694?v=4","account-source":"github","login":"Jeel-Shah"},"created-at":1580344960284,"updated-at":1580589650671,"_id":"5e322680e4b0ca44402ef828"},{"editors":[{"login":"shegeley","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8594472?v=4"}],"body":"doesn't works on nested (as one might expect)\nuser=> \n(rename-keys\n {:user {:name \"john\"}}\n {:user {:name :nickname}}) => {{:name :nickname} {:name \"john\"}}","author":{"avatar-url":"https://avatars.githubusercontent.com/u/8594472?v=4","account-source":"github","login":"shegeley"},"created-at":1621365421644,"updated-at":1621365442781,"_id":"60a412ade4b0b1e3652d7501"}],"notes":null,"arglists":["map kmap"],"doc":"Returns the map with the keys in kmap renamed to the vals in kmap","library-url":"https://github.com/clojure/clojure","href":"/clojure.set/rename-keys"},{"added":"1.0","ns":"clojure.set","name":"project","file":"clojure/set.clj","type":"function","column":1,"see-alsos":null,"line":72,"examples":[{"author":{"login":"Brian Marick","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a523012f661f603806ab1c22d855216f?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":";; `project` strips out unwanted key/value pairs from a set of maps. \n;; Suppose you have these descriptions of cows:\n\nuser=> (def cows #{ {:name \"betsy\" :id 33} {:name \"panda\" :id 34} })\n#'user/cows\n\n;; You care only about the names. So you can get them like this:\n\nuser=> (project cows [:name])\n#{{:name \"panda\"} {:name \"betsy\"}}\n","created-at":1278995532000,"updated-at":1285502725000,"_id":"542692d0c026201cdc326edd"},{"updated-at":1476954849358,"created-at":1476954849358,"author":{"login":"dalzony","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/562341?v=3"},"body":";; also worked from vector of maps.\n\nuser=> (def sample [{:name \"Minsun\" :device \"iphone6\"}\n {:name \"hogle\" :device \"iphone7 matte black\"}])\n;;=> #'user/sample\n\nuser=> (clojure.set/project sample [:name])\n;;=> #{{:name \"hogle\"} {:name \"Minsun\"}}\n","_id":"58088ae1e4b001179b66bdd5"}],"notes":[{"updated-at":1320358713000,"body":"is there a function that is like project, but returns a set of hash-maps with with all the keys but the ones project was given?","created-at":1320358713000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fd1"},{"updated-at":1349530376000,"body":"This doesn't exist in clojure.set, but I think it would be what you wanted.\r\n\r\n
    \r\n(defn project-not [xrel ks]\r\n  ;; convert the given key sequence into a hash-set\r\n  ;; This represents keys that you don't want included\r\n  (let [ks-set (into #{} ks)]\r\n    ;; Do a projection on the keys that are not in ks\r\n    (clojure.set/project xrel\r\n                         ;; Assumes xrel is a set of maps\r\n                         ;; Grab the first map and extract the keys\r\n                         ;; Then remove any keys that are in ks-set\r\n                         ;; This will leave the remaining keys for\r\n                         ;; projection\r\n                         (remove #(ks-set %) (keys (first xrel))))))\r\n\r\nuser> (project-not cows [:id])\r\n#{{:name \"panda\" {:name \"betsy\"}}\r\n
    ","created-at":1349530376000,"author":{"login":"taylor.sando","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/c127297f5548f7275ded1428aa5518bb?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fe9"},{"updated-at":1366672505000,"body":"it strikes me as being very odd that the key set is a vector as opposed to vargs\r\n","created-at":1366672505000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"_id":"542692edf6e94c6970522001"},{"body":"An alternate version of `project-not` that doesn't assume the first map in xrel has all the possible keys:\n\n
    \n(defn project-not\n  \"Returns a rel of the elements of xrel with keys in ks dissoced\"\n  [xrel ks]\n  (with-meta (set (map #(apply dissoc % ks) xrel)) (meta xrel)))\n
    ","created-at":1444156923198,"updated-at":1444156940978,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/938655?v=3","account-source":"github","login":"yanatan16"},"_id":"561415fbe4b084e61c76ecbc"}],"arglists":["xrel ks"],"doc":"Returns a rel of the elements of xrel with only the keys in ks","library-url":"https://github.com/clojure/clojure","href":"/clojure.set/project"},{"added":"1.0","ns":"clojure.set","name":"difference","file":"clojure/set.clj","type":"function","column":1,"see-alsos":[{"created-at":1318525779000,"author":{"login":"mmwaikar","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/29d36f4c9f39c9f8ff61c07033b13118?r=PG&default=identicon"},"to-var":{"ns":"clojure.set","name":"union","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ce2"},{"created-at":1318525788000,"author":{"login":"mmwaikar","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/29d36f4c9f39c9f8ff61c07033b13118?r=PG&default=identicon"},"to-var":{"ns":"clojure.set","name":"intersection","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ce3"},{"created-at":1318525910000,"author":{"login":"mmwaikar","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/29d36f4c9f39c9f8ff61c07033b13118?r=PG&default=identicon"},"to-var":{"ns":"clojure.set","name":"superset?","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ce4"},{"created-at":1366429247000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.set","name":"project","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ce5"},{"created-at":1533849200342,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"disj","ns":"clojure.core"},"_id":"5b6cae70e4b00ac801ed9e4c"}],"line":49,"examples":[{"author":{"login":"Brian Marick","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a523012f661f603806ab1c22d855216f?r=PG&default=identicon"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":"user=> (difference #{1 2 3})\n#{1 2 3}\nuser=> (difference #{1 2} #{2 3})\n#{1}\nuser=> (difference #{1 2 3} #{1} #{1 4} #{3})\n#{2}","created-at":1278822538000,"updated-at":1332952529000,"_id":"542692d0c026201cdc326eeb"},{"author":{"login":"devijvers","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/81018e4231ac1ce8b7a9e6d377092656?r=PG&default=identicon"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":"user=> (difference (set (keys {:1 1 :2 2 :3 3})) (set (keys {:1 1 :2 2})))\n#{:3}\nuser=> (difference (set (keys {:1 1 :2 2})) (set (keys {:1 1 :2 2 :3 3})))\n#{}","created-at":1279384603000,"updated-at":1332952542000,"_id":"542692d0c026201cdc326eed"},{"updated-at":1457518056250,"created-at":1457518056250,"author":{"login":"ertugrulcetin","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8271291?v=3"},"body":"user=> (difference #{:a :b :c :d} (difference #{:a :b :c :d} #{:c :e :a :f :d}))\n#{:a :c :d}","_id":"56dff5e8e4b0119038be0211"},{"editors":[{"login":"tdg5","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/2316989?v=4"},{"avatar-url":"https://avatars2.githubusercontent.com/u/109629?v=4","account-source":"github","login":"jafingerhut"}],"body":";; Advice: Do not call difference with non-set arguments. If you are\n;; concerned that you may be unintentionally doing so, and want an\n;; exception to be thrown if you do, consider using the library\n;; funjible (https://github.com/jafingerhut/funjible) which provides\n;; its own definition of difference that is identical to Clojure's,\n;; except it checks the types of its arguments.\n\n;; difference might or might not return what you expect if you give it\n;; values that are not sets. The implementation of difference _does not\n;; check_ whether you are actually giving it values that are sets. It\n;; _assumes_ so.\n\n;; This looks like what someone might expect. It _happens_ to give\n;; back the same answer as if you coerced the second argument to a\n;; set.\nuser=> (difference #{1 3 5} [1 2 3 4 5 6])\n#{}\n\n;; This is not the difference between the two collections (if they\n;; were both sets) at all!\nuser=> (difference #{1 3 5} [2 4 6 8 10 12])\n#{}\n\n;; Give it only sets, and it returns the correct answer.\nuser=> (set/difference #{1 3 5} #{2 4 6 8 10 12})\n#{1 3 5}\n\n;; Also not the correct set difference, because the second arg is a\n;; vector, not a set.\nuser=> (difference #{-1 10 20 30} [-1 10 20 30 40])\n#{20 -1 30 10}\n\n;; This is correct.\nuser=> (difference #{-1 10 20 30} #{-1 10 20 30 40})\n#{}\n\n;; Why not change the definition of difference so it throws an exception if\n;; you give it a non-set argument? I would guess that the primary\n;; reason is that the extra run-time type checks would slow difference down\n;; by an amount that the Clojure core team does not want everyone to\n;; have to pay on every such call.\n\n;; Related Clojure tickets: \n;; https://dev.clojure.org/jira/browse/CLJ-1953\n;; https://dev.clojure.org/jira/browse/CLJ-2287\n","author":{"avatar-url":"https://avatars2.githubusercontent.com/u/2316989?v=4","account-source":"github","login":"tdg5"},"created-at":1505239113099,"updated-at":1532995953611,"_id":"59b82049e4b09f63b945ac71"},{"editors":[{"login":"loeschzwerg","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/24317401?v=4"}],"body":";; difference subtracts the trailing sets\n(def s1 #{1 2})\n(def s2 #{2 3})\n(set/difference s1 s2)\n;;=> #{1}\n\n;; to get the exclusive union #{1 3} (or \"XOR\"):\n(set/difference\n (set/union s1 s2)\n (set/intersection s1 s2))\n;;=> #{1 3}\n\n;; You can extend this to maps:\n(defn- map-xor [m1 m2]\n (map (juxt (fn [[k1 _] _] k1)\n (fn [[_ v1] [_ v2]]\n (set/difference\n (set/union (set v1) (set v2))\n (set/intersection (set v1) (set v2)))))\n m1\n m2))\n(map-xor \n {:a [1 2] :b [2 3]}\n {:a [2 3] :b [3]})\n;;=> ([:a #{1 3}] \n [:b #{2}])","author":{"avatar-url":"https://avatars.githubusercontent.com/u/24317401?v=4","account-source":"github","login":"loeschzwerg"},"created-at":1655477240416,"updated-at":1655477266625,"_id":"62ac93f8e4b0b1e3652d7606"}],"notes":null,"arglists":["s1","s1 s2","s1 s2 & sets"],"doc":"Return a set that is the first set without elements of the remaining sets","library-url":"https://github.com/clojure/clojure","href":"/clojure.set/difference"},{"ns":"clojure.spec.alpha","name":"form","file":"clojure/spec/alpha.clj","type":"function","column":1,"see-alsos":null,"line":180,"examples":null,"notes":null,"arglists":["spec"],"doc":"returns the spec as data","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/form"},{"ns":"clojure.spec.alpha","name":"&","file":"clojure/spec/alpha.clj","type":"macro","column":1,"see-alsos":null,"line":658,"examples":[{"editors":[{"login":"holyjak","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/624958?v=4"}],"body":"(require '[clojure.spec.alpha :as s])\n\n(s/conform\n (s/cat :tag keyword? :children (s/& (s/+ integer?) #(-> % count (>= 2))))\n [:a 3])\n;=> :clojure.spec.alpha/invalid\n(s/conform\n (s/cat :tag keyword? :children (s/& (s/+ integer?) #(-> % count (>= 2))))\n [:a 3 4 5])\n;=> {:tag :a, :children [3 4 5]}\n","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/624958?v=4","account-source":"github","login":"holyjak"},"created-at":1561635215512,"updated-at":1561635233952,"_id":"5d14a98fe4b0ca44402ef771"}],"macro":true,"notes":null,"arglists":["re & preds"],"doc":"takes a regex op re, and predicates. Returns a regex-op that consumes\n input as per re but subjects the resulting value to the\n conjunction of the predicates, and any conforming they might perform.","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/&"},{"ns":"clojure.spec.alpha","name":"nilable-impl","file":"clojure/spec/alpha.clj","type":"function","skip-wiki":true,"column":1,"see-alsos":null,"line":1834,"examples":null,"notes":null,"arglists":["form pred gfn"],"doc":"Do not call this directly, use 'nilable'","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/nilable-impl"},{"ns":"clojure.spec.alpha","name":"*recursion-limit*","file":"clojure/spec/alpha.clj","type":"var","column":1,"see-alsos":null,"dynamic":true,"line":26,"examples":[{"editors":[{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"}],"body":";; Limit the recursion to 1\n(binding [s/*recursion-limit* 1]\n (gen/generate (s/gen my-spec)))","author":{"avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4","account-source":"github","login":"bfontaine"},"created-at":1542797640693,"updated-at":1542797667795,"_id":"5bf53948e4b00ac801ed9f02"}],"notes":null,"arglists":[],"doc":"A soft limit on how many times a branching spec (or/alt/*/opt-keys/multi-spec)\n can be recursed through during generation. After this a\n non-recursive branch will be chosen.","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/*recursion-limit*"},{"ns":"clojure.spec.alpha","name":"*coll-error-limit*","file":"clojure/spec/alpha.clj","type":"var","column":1,"see-alsos":null,"dynamic":true,"line":40,"examples":null,"notes":null,"arglists":[],"doc":"The number of errors reported by explain in a collection spec'ed with 'every'","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/*coll-error-limit*"},{"ns":"clojure.spec.alpha","name":"fspec","file":"clojure/spec/alpha.clj","type":"macro","column":1,"see-alsos":null,"line":674,"examples":null,"macro":true,"notes":null,"arglists":["& {:keys [args ret fn gen], :or {ret (quote clojure.core/any?)}}"],"doc":"takes :args :ret and (optional) :fn kwargs whose values are preds\n and returns a spec whose conform/explain take a fn and validates it\n using generative testing. The conformed value is always the fn itself.\n\n See 'fdef' for a single operation that creates an fspec and\n registers it, as well as a full description of :args, :ret and :fn\n\n fspecs can generate functions that validate the arguments and\n fabricate a return value compliant with the :ret spec, ignoring\n the :fn spec if present.\n\n Optionally takes :gen generator-fn, which must be a fn of no args\n that returns a test.check generator.","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/fspec"},{"ns":"clojure.spec.alpha","name":"explain-printer","file":"clojure/spec/alpha.clj","type":"function","column":1,"see-alsos":null,"line":234,"examples":null,"notes":null,"arglists":["ed"],"doc":"Default printer for explain-data. nil indicates a successful validation.","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/explain-printer"},{"ns":"clojure.spec.alpha","name":"Specize","file":"clojure/spec/alpha.clj","type":"var","column":1,"see-alsos":null,"line":128,"examples":null,"notes":null,"arglists":[],"doc":null,"library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/Specize"},{"ns":"clojure.spec.alpha","name":"every","file":"clojure/spec/alpha.clj","type":"macro","column":1,"see-alsos":null,"line":520,"examples":null,"macro":true,"notes":null,"arglists":["pred & {:keys [into kind count max-count min-count distinct gen-max gen], :as opts}"],"doc":"takes a pred and validates collection elements against that pred.\n\n Note that 'every' does not do exhaustive checking, rather it samples\n *coll-check-limit* elements. Nor (as a result) does it do any\n conforming of elements. 'explain' will report at most *coll-error-limit*\n problems. Thus 'every' should be suitable for potentially large\n collections.\n\n Takes several kwargs options that further constrain the collection:\n\n :kind - a pred that the collection type must satisfy, e.g. vector?\n (default nil) Note that if :kind is specified and :into is\n not, this pred must generate in order for every to generate.\n :count - specifies coll has exactly this count (default nil)\n :min-count, :max-count - coll has count (<= min-count count max-count) (defaults nil)\n :distinct - all the elements are distinct (default nil)\n\n And additional args that control gen\n\n :gen-max - the maximum coll size to generate (default 20)\n :into - one of [], (), {}, #{} - the default collection to generate into\n (default: empty coll as generated by :kind pred if supplied, else [])\n \n Optionally takes :gen generator-fn, which must be a fn of no args that\n returns a test.check generator\n\n See also - coll-of, every-kv\n","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/every"},{"ns":"clojure.spec.alpha","name":"keys*","file":"clojure/spec/alpha.clj","type":"macro","column":1,"see-alsos":[{"created-at":1549644522869,"author":{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"keys","ns":"clojure.spec.alpha"},"_id":"5c5db2eae4b0ca44402ef66a"}],"line":1794,"examples":null,"macro":true,"notes":null,"arglists":["& kspecs"],"doc":"takes the same arguments as spec/keys and returns a regex op that matches sequences of key/values,\n converts them into a map, and conforms that map with a corresponding\n spec/keys call:\n\n user=> (s/conform (s/keys :req-un [::a ::c]) {:a 1 :c 2})\n {:a 1, :c 2}\n user=> (s/conform (s/keys* :req-un [::a ::c]) [:a 1 :c 2])\n {:a 1, :c 2}\n\n the resulting regex op can be composed into a larger regex:\n\n user=> (s/conform (s/cat :i1 integer? :m (s/keys* :req-un [::a ::c]) :i2 integer?) [42 :a 1 :c 2 :d 4 99])\n {:i1 42, :m {:a 1, :c 2, :d 4}, :i2 99}","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/keys*"},{"ns":"clojure.spec.alpha","name":"alt-impl","file":"clojure/spec/alpha.clj","type":"function","skip-wiki":true,"column":1,"see-alsos":null,"line":1447,"examples":null,"notes":null,"arglists":["ks ps forms"],"doc":"Do not call this directly, use 'alt'","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/alt-impl"},{"ns":"clojure.spec.alpha","name":"def-impl","file":"clojure/spec/alpha.clj","type":"function","skip-wiki":true,"column":1,"see-alsos":null,"line":327,"examples":null,"notes":null,"arglists":["k form spec"],"doc":"Do not call this directly, use 'def'","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/def-impl"},{"ns":"clojure.spec.alpha","name":"*explain-out*","file":"clojure/spec/alpha.clj","type":"var","column":1,"see-alsos":null,"dynamic":true,"line":259,"examples":null,"notes":null,"arglists":[],"library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/*explain-out*"},{"ns":"clojure.spec.alpha","name":"regex-spec-impl","file":"clojure/spec/alpha.clj","type":"function","skip-wiki":true,"column":1,"see-alsos":null,"line":1697,"examples":null,"notes":null,"arglists":["re gfn"],"doc":"Do not call this directly, use 'spec' with a regex op argument","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/regex-spec-impl"},{"ns":"clojure.spec.alpha","name":"merge-spec-impl","file":"clojure/spec/alpha.clj","type":"function","skip-wiki":true,"column":1,"see-alsos":null,"line":1195,"examples":null,"notes":null,"arglists":["forms preds gfn"],"doc":"Do not call this directly, use 'merge'","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/merge-spec-impl"},{"ns":"clojure.spec.alpha","name":"explain-data*","file":"clojure/spec/alpha.clj","type":"function","column":1,"see-alsos":null,"line":218,"examples":null,"notes":null,"arglists":["spec path via in x"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/explain-data*"},{"ns":"clojure.spec.alpha","name":"check-asserts","file":"clojure/spec/alpha.clj","type":"function","column":1,"see-alsos":[{"created-at":1725986416558,"author":{"login":"abrooks","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/69976?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"assert","ns":"clojure.spec.alpha"},"_id":"66e0767069fbcc0c226174f2"}],"line":1955,"examples":null,"notes":[{"author":{"login":"allmonty","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/4502764?v=4"},"updated-at":1678998355863,"created-at":1678998355863,"body":"You can also **enable check-asserts globally** using deps.edn you can add it to a profile. It is a jvm option. In your **deps.edn** you can add this:\n\n```\n:aliases {:dev {:jvm-opts [\"-Dclojure.spec.check-asserts=true\"]}}\n```","_id":"64137b53e4b08cf8563f4b7e"}],"arglists":["flag"],"doc":"Enable or disable spec asserts that have been compiled\nwith '*compile-asserts*' true. See 'assert'.\n\nInitially set to boolean value of clojure.spec.check-asserts\nsystem property. Defaults to false.","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/check-asserts"},{"ns":"clojure.spec.alpha","name":"assert*","file":"clojure/spec/alpha.clj","type":"function","column":1,"see-alsos":null,"line":1964,"examples":null,"notes":null,"arglists":["spec x"],"doc":"Do not call this directly, use 'assert'.","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/assert*"},{"ns":"clojure.spec.alpha","name":"inst-in-range?","file":"clojure/spec/alpha.clj","type":"function","column":1,"see-alsos":null,"line":1889,"examples":null,"notes":null,"arglists":["start end inst"],"doc":"Return true if inst at or after start and before end","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/inst-in-range_q"},{"ns":"clojure.spec.alpha","name":"nilable","file":"clojure/spec/alpha.clj","type":"macro","column":1,"see-alsos":null,"line":1860,"examples":[{"editors":[{"login":"escherize","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/343288?v=4"}],"body":"(def ::my-spec (nilable int?))\n\n(valid? ::my-spec 2)\n;;=> true\n\n(valid ::my-spec 3.3)\n;;=> false\n\n(valid? ::my-spec nil)\n;;=> true","author":{"avatar-url":"https://avatars2.githubusercontent.com/u/343288?v=4","account-source":"github","login":"escherize"},"created-at":1521476741313,"updated-at":1521476829553,"_id":"5aafe485e4b0316c0f44f92f"}],"macro":true,"notes":null,"arglists":["pred"],"doc":"returns a spec that accepts nil and values satisfying pred","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/nilable"},{"ns":"clojure.spec.alpha","name":"and-spec-impl","file":"clojure/spec/alpha.clj","type":"function","skip-wiki":true,"column":1,"see-alsos":null,"line":1151,"examples":null,"notes":null,"arglists":["forms preds gfn"],"doc":"Do not call this directly, use 'and'","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/and-spec-impl"},{"ns":"clojure.spec.alpha","name":"describe*","type":"function","see-alsos":null,"examples":null,"notes":null,"tag":null,"arglists":["spec"],"doc":null,"library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/describe*"},{"ns":"clojure.spec.alpha","name":"map-spec-impl","file":"clojure/spec/alpha.clj","type":"function","skip-wiki":true,"column":1,"see-alsos":null,"line":822,"examples":null,"notes":null,"arglists":["{:keys [req-un opt-un keys-pred pred-exprs opt-keys req-specs req req-keys opt-specs pred-forms opt gfn], :as argm}"],"doc":"Do not call this directly, use 'spec' with a map argument","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/map-spec-impl"},{"ns":"clojure.spec.alpha","name":"coll-of","file":"clojure/spec/alpha.clj","type":"macro","column":1,"see-alsos":[{"created-at":1535112883796,"author":{"login":"maiwald","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/355026?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"map-of","ns":"clojure.spec.alpha"},"_id":"5b7ff6b3e4b00ac801ed9e71"},{"created-at":1535112895156,"author":{"login":"maiwald","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/355026?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"every","ns":"clojure.spec.alpha"},"_id":"5b7ff6bfe4b00ac801ed9e72"}],"line":579,"examples":[{"updated-at":1535329349336,"created-at":1535329349336,"author":{"login":"veix","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/31626014?v=4"},"body":"(def suit? #{:heart :diamond :club :spade})\n(def rank?\n (into #{:ace :king :queen :jack} (range 2 11)))\n\n(def deck (for [s suit? r rank?] [s r])) \n\n(s/def ::card (s/tuple suit? rank?)) \n(s/def ::deck (s/coll-of ::card :distinct true :into [] :count 52)))\n","_id":"5b834445e4b00ac801ed9e7a"}],"macro":true,"notes":null,"arglists":["pred & opts"],"doc":"Returns a spec for a collection of items satisfying pred. Unlike\n 'every', coll-of will exhaustively conform every value.\n\n Same options as 'every'. conform will produce a collection\n corresponding to :into if supplied, else will match the input collection,\n avoiding rebuilding when possible.\n\n See also - every, map-of","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/coll-of"},{"ns":"clojure.spec.alpha","name":"cat","file":"clojure/spec/alpha.clj","type":"macro","column":1,"see-alsos":null,"line":642,"examples":[{"updated-at":1553623784678,"created-at":1553623784678,"author":{"login":"yanisurbis","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/9294910?v=4"},"body":"(require '[clojure.spec.alpha :as s])\n\n(let [spec (s/cat :e even? :o odd?)]\n [(s/conform spec [22 11])\n (s/conform spec [22])\n (s/conform spec [22 11 22])\n (s/conform spec 22)\n (s/conform spec \"22\")])\n;; => [{:e 22, :o 11}\n;; :clojure.spec.alpha/invalid\n;; :clojure.spec.alpha/invalid\n;; :clojure.spec.alpha/invalid\n;; :clojure.spec.alpha/invalid]","_id":"5c9a6ae8e4b0ca44402ef6cc"}],"macro":true,"notes":null,"arglists":["& key-pred-forms"],"doc":"Takes key+pred pairs, e.g.\n\n (s/cat :e even? :o odd?)\n\n Returns a regex op that matches (all) values in sequence, returning a map\n containing the keys of each pred and the corresponding value.","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/cat"},{"ns":"clojure.spec.alpha","name":"*","file":"clojure/spec/alpha.clj","type":"macro","column":1,"see-alsos":[{"created-at":1549644413188,"author":{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"+","ns":"clojure.spec.alpha"},"_id":"5c5db27de4b0ca44402ef667"},{"created-at":1549644433319,"author":{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"?","ns":"clojure.spec.alpha"},"_id":"5c5db291e4b0ca44402ef668"}],"line":607,"examples":null,"macro":true,"notes":null,"arglists":["pred-form"],"doc":"Returns a regex op that matches zero or more values matching\n pred. Produces a vector of matches iff there is at least one match","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/*"},{"ns":"clojure.spec.alpha","name":"explain","file":"clojure/spec/alpha.clj","type":"function","column":1,"see-alsos":[{"created-at":1628867588311,"author":{"login":"ferdinand-beyer","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/23474334?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"explain-data","ns":"clojure.spec.alpha"},"_id":"61168c04e4b0b1e3652d752f"}],"line":267,"examples":[{"editors":[{"login":"yanisurbis","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/9294910?v=4"}],"body":"(require '[clojure.spec.alpha :as s])\n\n(s/def ::oop-languages #{\"java\" \"python\" \"ruby\" \"c++\" \"smalltalk\" \"simula\"})\n\n(s/explain ::oop-languages \"clojure\")\n;; val: \"clojure\" fails spec: :user/oop-languages predicate:\n;; #{\"simula\" \"java\" \"c++\" \"smalltalk\" \"ruby\" \"python\"}\n;; => nil\n\n(s/explain ::oop-languages \"python\")]\n;; Success!\n;; => nil\n\n;; read more at https://clojure.org/guides/spec#_explain","author":{"avatar-url":"https://avatars0.githubusercontent.com/u/9294910?v=4","account-source":"github","login":"yanisurbis"},"created-at":1553627032812,"updated-at":1553627141914,"_id":"5c9a7798e4b0ca44402ef6cd"}],"notes":null,"arglists":["spec x"],"doc":"Given a spec and a value that fails to conform, prints an explanation to *out*.","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/explain"},{"ns":"clojure.spec.alpha","name":"with-gen*","type":"function","see-alsos":null,"examples":null,"notes":null,"tag":null,"arglists":["spec gfn"],"doc":null,"library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/with-gen*"},{"ns":"clojure.spec.alpha","name":"or-spec-impl","file":"clojure/spec/alpha.clj","type":"function","skip-wiki":true,"column":1,"see-alsos":[{"created-at":1549644601886,"author":{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"or","ns":"clojure.spec.alpha"},"_id":"5c5db339e4b0ca44402ef66b"}],"line":1061,"examples":null,"notes":null,"arglists":["keys forms preds gfn"],"doc":"Do not call this directly, use 'or'","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/or-spec-impl"},{"ns":"clojure.spec.alpha","name":"*fspec-iterations*","file":"clojure/spec/alpha.clj","type":"var","column":1,"see-alsos":null,"dynamic":true,"line":32,"examples":null,"notes":null,"arglists":[],"doc":"The number of times an anonymous fn specified by fspec will be (generatively) tested during conform","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/*fspec-iterations*"},{"ns":"clojure.spec.alpha","name":"Spec","file":"clojure/spec/alpha.clj","type":"var","column":1,"see-alsos":null,"line":44,"examples":null,"notes":null,"arglists":[],"doc":null,"library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/Spec"},{"ns":"clojure.spec.alpha","name":"unform","file":"clojure/spec/alpha.clj","type":"function","column":1,"see-alsos":[{"created-at":1524219315965,"author":{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"conform","ns":"clojure.spec.alpha"},"_id":"5ad9bdb3e4b045c27b7fac47"},{"created-at":1588732338488,"author":{"login":"jdf-id-au","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/9016301?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"conformer","ns":"clojure.spec.alpha"},"_id":"5eb221b2e4b087629b5a1902"}],"line":173,"examples":[{"updated-at":1560617844690,"created-at":1560617844690,"author":{"login":"enocom","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/1175430?v=4"},"body":"(require '[clojure.spec.alpha :as s])\n\n;; define spec as a sequential concatenation of two more specs:\n;; pos? and one of possible units (:meters :miles)\n;; :amount and :unit are the names we are giving to each position\n(s/def ::distance (s/cat :amount (s/and number? pos?)\n :unit #{:meters :miles}))\n\n(s/conform ::distance [3 :meters])\n;; => {:amount 3, :unit :meters}\n\n(s/unform ::distance {:amount 3, :unit :meters})\n;; => (3 :meters)\n\n(s/unform ::distance {:amount 3, :unit :foo})\n;; => (3 :foo)\n\n(s/unform ::distance {:amount 3, :foo :miles})\n;; => (3)\n\n(s/unform ::distance {:bar 3, :foo :miles})\n;; => ()\n","_id":"5d052374e4b0ca44402ef759"}],"notes":null,"arglists":["spec x"],"doc":"Given a spec and a value created by or compliant with a call to\n 'conform' with the same spec, returns a value with all conform\n destructuring undone.","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/unform"},{"ns":"clojure.spec.alpha","name":"valid?","file":"clojure/spec/alpha.clj","type":"function","column":1,"see-alsos":null,"line":770,"examples":[{"updated-at":1549644718642,"created-at":1549644718642,"author":{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"},"body":"(s/def ::ok boolean?)\n\n(s/valid? ::ok true) ; true\n(s/valid? ::ok false) ; true\n(s/valid? ::ok 42) ; false\n(s/valid? ::ok \"true\") ; false","_id":"5c5db3aee4b0ca44402ef66f"}],"notes":null,"arglists":["spec x","spec x form"],"doc":"Helper function that returns true when x is valid for spec.","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/valid_q"},{"ns":"clojure.spec.alpha","name":"gen","file":"clojure/spec/alpha.clj","type":"function","column":1,"see-alsos":[{"created-at":1579285770113,"author":{"login":"yuhan0","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/22216124?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"with-gen","ns":"clojure.spec.alpha"},"_id":"5e21fd0ae4b0ca44402ef81a"}],"line":292,"examples":[{"updated-at":1593619687739,"created-at":1593619687739,"author":{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"},"body":";; get a generator for the spec 'int?' and generate a sample from it\n(gen/sample (s/gen int?))\n; => (-1 0 0 -1 7 2 1 0 59 -6)","_id":"5efcb4e7e4b0b1e3652d731d"},{"updated-at":1602570052630,"created-at":1602570052630,"author":{"login":"deadghost","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1156996?v=4"},"body":";; Generator override example\n(s/def :foo/bar\n (s/keys :req [:biz/baz]))\n\n(s/def :biz/baz int?)\n\n(comment\n (gen/sample\n (s/gen :foo/bar {:biz/baz #(s/gen #{1 10 100})}) 5)\n ;; Example Result\n (#:biz{:baz 100}\n #:biz{:baz 100}\n #:biz{:baz 1}\n #:biz{:baz 10}\n #:biz{:baz 10}))\n\n;; Note that \"Spec does not trust custom generators and any values they produce\n;; will also be checked by their associated spec to guarantee they pass\n;; conformance.\"\n;; See: https://clojure.org/guides/spec#_custom_generators\n","_id":"5f854744e4b0b1e3652d73d8"}],"notes":null,"arglists":["spec","spec overrides"],"doc":"Given a spec, returns the generator for it, or throws if none can\n be constructed. Optionally an overrides map can be provided which\n should map spec names or paths (vectors of keywords) to no-arg\n generator-creating fns. These will be used instead of the generators at those\n names/paths. Note that parent generator (in the spec or overrides\n map) will supersede those of any subtrees. A generator for a regex\n op must always return a sequential collection (i.e. a generator for\n s/? should return either an empty sequence/vector or a\n sequence/vector with one item in it)","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/gen"},{"ns":"clojure.spec.alpha","name":"every-kv","file":"clojure/spec/alpha.clj","type":"macro","column":1,"see-alsos":[{"created-at":1549873931835,"author":{"login":"pieterbreed","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/448604?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"map-of","ns":"clojure.spec.alpha"},"_id":"5c61330be4b0ca44402ef676"},{"created-at":1549873947107,"author":{"login":"pieterbreed","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/448604?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"every","ns":"clojure.spec.alpha"},"_id":"5c61331be4b0ca44402ef677"}],"line":568,"examples":[{"updated-at":1697254037104,"created-at":1697254037104,"author":{"login":"felipearmat","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10645204?v=4"},"body":";; Define a ::person spec for a map with string keys and string values\n(s/def ::person\n (s/every-kv string? string?))\n\n;; Validate a person map with an 'int' age (fails)\n(s/valid? ::person {\"name\" \"Alice\" \"age\" 30 \"city\" \"New York\"})\n;; => false\n\n;; Validate a person map with 'string' values and keys (success)\n(s/valid? ::person {\"name\" \"Alice\" \"age\" \"30\" \"city\" \"New York\"})\n;; => true\n\n","_id":"652a0a95e4b08cf8563f4bff"}],"macro":true,"notes":null,"arglists":["kpred vpred & opts"],"doc":"like 'every' but takes separate key and val preds and works on associative collections.\n\n Same options as 'every', :into defaults to {}\n\n See also - map-of","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/every-kv"},{"ns":"clojure.spec.alpha","name":"int-in","file":"clojure/spec/alpha.clj","type":"macro","column":1,"see-alsos":[{"created-at":1549644745851,"author":{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"int-in-range?","ns":"clojure.spec.alpha"},"_id":"5c5db3c9e4b0ca44402ef671"},{"created-at":1549644762559,"author":{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"double-in","ns":"clojure.spec.alpha"},"_id":"5c5db3dae4b0ca44402ef672"}],"line":1914,"examples":null,"macro":true,"notes":null,"arglists":["start end"],"doc":"Returns a spec that validates fixed precision integers in the\n range from start (inclusive) to end (exclusive).","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/int-in"},{"ns":"clojure.spec.alpha","name":"alt","file":"clojure/spec/alpha.clj","type":"macro","column":1,"see-alsos":[{"created-at":1534374735387,"author":{"login":"ryoakg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/23413?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"or","ns":"clojure.spec.alpha"},"_id":"5b74b34fe4b00ac801ed9e5d"}],"line":625,"examples":[{"updated-at":1534374875088,"created-at":1534374875088,"author":{"login":"ryoakg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/23413?v=4"},"body":"(require '[clojure.spec.alpha :as s])\n\n(let [spec (s/alt :n number? :b boolean?)]\n [(s/conform spec [1])\n (s/conform spec [true])\n (s/conform spec [\"str\"])])\n;; => [[:n 1] [:b true] :clojure.spec.alpha/invalid]","_id":"5b74b3dbe4b00ac801ed9e5f"},{"editors":[{"login":"rgkirch","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/6143833?v=4"}],"body":"(require '[clojure.spec.alpha :as s])\n\n(s/def ::type-hinted-destructure\n (s/* (s/alt :hinted (s/cat :symbol symbol?\n :separator #(= :- %)\n :schema any?)\n :not-hinted (s/cat :symbol symbol?))))\n\n(s/conform ::type-hinted-destructure\n '[first :- string? ; `first :- string?` not `[first :- string?]`\n last])\n;; [[:hinted {:symbol first, :separator :-, :schema string?}] [:not-hinted {:symbol last}]]\n","author":{"avatar-url":"https://avatars.githubusercontent.com/u/6143833?v=4","account-source":"github","login":"rgkirch"},"created-at":1651545031079,"updated-at":1651545677032,"_id":"627093c7e4b0b1e3652d75e0"}],"macro":true,"notes":null,"arglists":["& key-pred-forms"],"doc":"Takes key+pred pairs, e.g.\n\n (s/alt :even even? :small #(< % 42))\n\n Returns a regex op that returns a map entry containing the key of the\n first matching pred and the corresponding value. Thus the\n 'key' and 'val' functions can be used to refer generically to the\n components of the tagged return","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/alt"},{"ns":"clojure.spec.alpha","name":"nonconforming","file":"clojure/spec/alpha.clj","type":"function","skip-wiki":true,"column":1,"see-alsos":null,"line":1813,"examples":null,"notes":null,"arglists":["spec"],"doc":"takes a spec and returns a spec that has the same properties except\n 'conform' returns the original (not the conformed) value. Note, will specize regex ops.","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/nonconforming"},{"ns":"clojure.spec.alpha","name":"unform*","type":"function","see-alsos":null,"examples":null,"notes":null,"tag":null,"arglists":["spec y"],"doc":null,"library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/unform*"},{"ns":"clojure.spec.alpha","name":"abbrev","file":"clojure/spec/alpha.clj","type":"function","column":1,"see-alsos":null,"line":186,"examples":null,"notes":null,"arglists":["form"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/abbrev"},{"ns":"clojure.spec.alpha","name":"regex?","file":"clojure/spec/alpha.clj","type":"function","column":1,"see-alsos":null,"line":85,"examples":null,"notes":null,"arglists":["x"],"doc":"returns x if x is a (clojure.spec) regex op, else logical false","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/regex_q"},{"ns":"clojure.spec.alpha","name":"int-in-range?","file":"clojure/spec/alpha.clj","type":"function","column":1,"see-alsos":[{"created-at":1549644736832,"author":{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"int-in","ns":"clojure.spec.alpha"},"_id":"5c5db3c0e4b0ca44402ef670"}],"line":1908,"examples":null,"notes":null,"arglists":["start end val"],"doc":"Return true if start <= val, val < end and val is a fixed\n precision integer.","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/int-in-range_q"},{"ns":"clojure.spec.alpha","name":"or","file":"clojure/spec/alpha.clj","type":"macro","column":1,"see-alsos":[{"created-at":1534374718106,"author":{"login":"ryoakg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/23413?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"alt","ns":"clojure.spec.alpha"},"_id":"5b74b33ee4b00ac801ed9e5c"},{"created-at":1542797828176,"author":{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"*recursion-limit*","ns":"clojure.spec.alpha"},"_id":"5bf53a04e4b00ac801ed9f04"},{"created-at":1549644313245,"author":{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"and","ns":"clojure.spec.alpha"},"_id":"5c5db219e4b0ca44402ef666"}],"line":476,"examples":[{"updated-at":1534374833278,"created-at":1534374833278,"author":{"login":"ryoakg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/23413?v=4"},"body":"(require '[clojure.spec.alpha :as s])\n\n(let [spec (s/or :n number? :b boolean?)]\n [(s/conform spec 1)\n (s/conform spec true)\n (s/conform spec \"str\")])\n;; => [[:n 1] [:b true] :clojure.spec.alpha/invalid]","_id":"5b74b3b1e4b00ac801ed9e5e"},{"editors":[{"login":"rgkirch","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/6143833?v=4"}],"body":"(require '[clojure.spec.alpha :as s])\n\n(s/def ::type-hinted-destructure\n (s/coll-of (s/or :hinted (s/cat :symbol symbol?\n :separator #(= :- %)\n :schema any?)\n :not-hinted (s/cat :symbol symbol?))\n :kind vector?))\n\n(s/conform ::type-hinted-destructure\n '[[first :- string?] ; `[first :- string?]` not `first :- string?`\n [last]])\n;; [[:hinted {:symbol first, :separator :-, :schema string?}] [:not-hinted {:symbol last}]]","author":{"avatar-url":"https://avatars.githubusercontent.com/u/6143833?v=4","account-source":"github","login":"rgkirch"},"created-at":1651545098589,"updated-at":1651963713471,"_id":"6270940ae4b0b1e3652d75e1"}],"macro":true,"notes":null,"arglists":["& key-pred-forms"],"doc":"Takes key+pred pairs, e.g.\n\n (s/or :even even? :small #(< % 42))\n\n Returns a destructuring spec that returns a map entry containing the\n key of the first matching pred and the corresponding value. Thus the\n 'key' and 'val' functions can be used to refer generically to the\n components of the tagged return.","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/or"},{"ns":"clojure.spec.alpha","name":"spec?","file":"clojure/spec/alpha.clj","type":"function","column":1,"see-alsos":null,"line":79,"examples":null,"notes":null,"arglists":["x"],"doc":"returns x if x is a spec object, else logical false","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/spec_q"},{"ns":"clojure.spec.alpha","name":"registry","file":"clojure/spec/alpha.clj","type":"function","column":1,"see-alsos":null,"line":356,"examples":null,"notes":null,"arglists":[""],"doc":"returns the registry map, prefer 'get-spec' to lookup a spec by name","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/registry"},{"ns":"clojure.spec.alpha","name":"rep+impl","file":"clojure/spec/alpha.clj","type":"function","skip-wiki":true,"column":1,"see-alsos":[{"created-at":1549644629139,"author":{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"+","ns":"clojure.spec.alpha"},"_id":"5c5db355e4b0ca44402ef66d"}],"line":1413,"examples":null,"notes":null,"arglists":["form p"],"doc":"Do not call this directly, use '+'","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/rep+impl"},{"ns":"clojure.spec.alpha","name":"exercise-fn","file":"clojure/spec/alpha.clj","type":"function","column":1,"see-alsos":null,"line":1875,"examples":null,"notes":null,"arglists":["sym","sym n","sym-or-f n fspec"],"doc":"exercises the fn named by sym (a symbol) by applying it to\n n (default 10) generated samples of its args spec. When fspec is\n supplied its arg spec is used, and sym-or-f can be a fn. Returns a\n sequence of tuples of [args ret]. ","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/exercise-fn"},{"ns":"clojure.spec.alpha","name":"exercise","file":"clojure/spec/alpha.clj","type":"function","column":1,"see-alsos":null,"line":1866,"examples":[{"updated-at":1548441490507,"created-at":1548441490507,"author":{"login":"Activeghost","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10783037?v=4"},"body":"(...ns declaration...\n(:require [clojure.spec.alpha :as s]\n [clojure.spec.gen.alpha :as gen]))\n\n;; function spec\n;;\n(s/fdef map-to-tags\n :args (s/cat :record ::tag-record)\n :ret ::tag-model\n :fn (fn [{:keys [args ret]}]\n (s/valid? ::tag-model ret)))\n\n\n;; the actual fn\n;; extract a tag model from RDF query results\n;;\n(defn map-to-tags\n [record]\n {:pre [(s/valid? ::tag-record record)]\n :post [(s/valid? ::tag-model %)]}\n (log/infof \"[map-to-tags] mapping record: %s\" (pr-str record))\n (let [{:keys [type class name relevance]} record]\n (let [new-record {:tag-type (type :value)\n :tag-class (class :value)\n :tag-name (name :value)\n :tag-relevance (relevance :value)}]\n (log/debugf \"[map-to-tags] extracted record: %s\" new-record)\n new-record)))\n\nIn REPL:\n\n=> (s/exercise 'calais-response-processor.rdf-core/map-to-tags)\n([#object[clojure.spec.alpha$fspec_impl$reify__2451$fn__2454 0x22251fa \"clojure.spec.alpha$fspec_impl$reify__2451$fn__2454@22251fa\"] #object[clojure.spec.alpha$fspec_impl$reify__2451$fn__2454 0x22251fa \"clojure.spec.alpha$fspec_impl$reify__2451$fn__2454@22251fa\"]] [#object[clojure.spec.alpha$fspec_impl$reify__2451$fn__2454 0x22251fa \"clojure.spec.alpha$fspec_impl$reify__2451$fn__2454@22251fa\"] #object[clojure.spec.alpha$fspec_impl$reify__2451$fn__2454 0x22251fa \"clojure.spec.alpha$fspec_impl$reify__2451$fn__2454@22251fa\"]] [#object[clojure.spec.alpha$fspec_impl$reify__2451$fn__2454 0x22251fa \"clojure.spec.alpha$fspec_impl$reify__2451$fn__2454@22251fa\"] #object[clojure.spec.alpha$fspec_impl$reify__2451$fn__2454 0x22251fa \"clojure.spec.alpha$fspec_impl$reify__2451$fn__2454@22251fa\"]] [#object[clojure.spec.alpha$fspec_impl$reify__2451$fn__2454 0x22251fa \"clojure.spec.alpha$fspec_impl$reify__2451$fn__2454@22251fa\"] #object[clojure.spec.alpha$fspec_impl$reify__2451$fn__2454 0x22251fa \"clojure.spec.alpha$fspec_impl$reify__2451$fn__2454@22251fa\"]] [#object[clojure.spec.alpha$fspec_impl$reify__2451$fn__2454 0x22251fa \"clojure.spec.alpha$fspec_impl$reify__2451$fn__2454@22251fa\"] #object[clojure.spec.alpha$fspec_impl$reify__2451$fn__2454 0x22251fa \"clojure.spec.alpha$fspec_impl$reify__2451$fn__2454@22251fa\"]] [#object[clojure.spec.alpha$fspec_impl$reify__2451$fn__2454 0x22251fa \"clojure.spec.alpha$fspec_impl$reify__2451$fn__2454@22251fa\"] #object[clojure.spec.alpha$fspec_impl$reify__2451$fn__2454 0x22251fa \"clojure.spec.alpha$fspec_impl$reify__2451$fn__2454@22251fa\"]] [#object[clojure.spec.alpha$fspec_impl$reify__2451$fn__2454 0x22251fa \"clojure.spec.alpha$fspec_impl$reify__2451$fn__2454@22251fa\"] #object[clojure.spec.alpha$fspec_impl$reify__2451$fn__2454 0x22251fa \"clojure.spec.alpha$fspec_impl$reify__2451$fn__2454@22251fa\"]] [#object[clojure.spec.alpha$fspec_impl$reify__2451$fn__2454 0x22251fa \"clojure.spec.alpha$fspec_impl$reify__2451$fn__2454@22251fa\"] #object[clojure.spec.alpha$fspec_impl$reify__2451$fn__2454\n0x22251fa \"clojure.spec.alpha$fspec_impl$reify__2451$fn__2454@22251fa\"]] [#object[clojure.spec.alpha$fspec_impl$reify__2451$fn__2454 0x22251fa \"clojure.spec.alpha$fspec_impl$reify__2451$fn__2454@22251fa\"] #object[clojure.spec.alpha$fspec_impl$reify__2451$fn__2454 0x22251fa \"clojure.spec.alpha$fspec_impl$reify__2451$fn__2454@22251fa\"]] [#object[clojure.spec.alpha$fspec_impl$reify__2451$fn__2454 0x22251fa \"clojure.spec.alpha$fspec_impl$reify__2451$fn__2454@22251fa\"] #object[clojure.spec.alpha$fspec_impl$reify__2451$fn__2454 0x22251fa \"clojure.spec.alpha$fspec_impl$reify__2451$fn__2454@22251fa\"]])","_id":"5c4b5792e4b0ca44402ef62a"}],"notes":null,"arglists":["spec","spec n","spec n overrides"],"doc":"generates a number (default 10) of values compatible with spec and maps conform over them,\n returning a sequence of [val conformed-val] tuples. Optionally takes\n a generator overrides map as per gen","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/exercise"},{"ns":"clojure.spec.alpha","name":"multi-spec","file":"clojure/spec/alpha.clj","type":"macro","column":1,"see-alsos":null,"line":385,"examples":[{"updated-at":1534398043992,"created-at":1534398043992,"author":{"login":"jdf-id-au","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/9016301?v=4"},"body":"Use retag function to allow generative testing of multi-spec whose\nmultimethod has a :default dispatch method.\n\n(require '[clojure.spec.alpha :as s]\n '[clojure.spec.gen.alpha :as gen])\n\n(s/def ::tag #{:a :b :c :d})\n(s/def ::example-key keyword?)\n(s/def ::different-key keyword?)\n\n(defmulti tagmm :tag)\n(defmethod tagmm :a [_] (s/keys :req-un [::tag ::example-key]))\n(defmethod tagmm :default [_] (s/keys :req-un [::tag ::different-key]))\n\n(s/def ::example (s/multi-spec tagmm :tag))\n(gen/sample (s/gen ::example))\n;=> only get examples with :tag :a\n\n(s/def ::example (s/multi-spec tagmm (fn retag [gen-v dispatch-tag] gen-v)))\n(gen/sample (s/gen ::example))\n;=> get examples with all :tag options","_id":"5b750e5be4b00ac801ed9e60"},{"updated-at":1584169164619,"created-at":1584169164619,"author":{"login":"Activeghost","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10783037?v=4"},"body":"(def create-playlist (s/cat :command ::commands :type ::types :data (s/coll-of ::playlist)))\n(def create-song (s/cat :command ::commands :type ::types :data (s/coll-of ::song)))\n(def create-user (s/cat :command ::commands :type ::types :data (s/coll-of ::user)))\n\n(defmulti create-spec? second)\n(defmethod create-spec? :playlist [_] create-playlist)\n(defmethod create-spec? :song [_] create-song)\n(defmethod create-spec? :user [_] create-user)\n\n(def update-playlist (s/cat :command ::commands :type ::types :data (s/coll-of ::playlist-update)))\n(def update-song (s/cat :command ::commands :type ::types :data (s/coll-of ::song-update)))\n(def update-user (s/cat :command ::commands :type ::types :data (s/coll-of ::user-update)))\n\n(defmulti update-spec? second)\n(defmethod update-spec? :playlist [_] update-playlist)\n(defmethod update-spec? :song [_] update-song)\n(defmethod update-spec? :user [_] update-user)\n\n;; [:create :user [{:name \"bobby\"} {:name \"sally\"}{:name \"fred\"}]]\n(s/def ::create-action\n (s/with-gen #(s/multi-spec create-spec? %)\n #(gen/fmap vec (s/gen create-action-pattern))))\n\n;; [:update :user [\"1\"] [{:name \"bobby minerva\"}]]\n(s/def ::update-action\n (s/with-gen #(s/multi-spec update-spec? %)\n #(gen/fmap vec (s/gen update-action-pattern))))\n\n;; examples\n=> (s/explain ::create-action [:create :user [{:name \"bobby\"} {:name \"sally\"}{:name \"fred\"}]])\nSuccess!\nnil\n\n=> (s/explain ::update-action [:update :user [\"1\"] [{:name \"bobby minerva\"}]])\nSuccess!\nnil","_id":"5e6c80cce4b087629b5a18bb"}],"macro":true,"notes":null,"arglists":["mm retag"],"doc":"Takes the name of a spec/predicate-returning multimethod and a\n tag-restoring keyword or fn (retag). Returns a spec that when\n conforming or explaining data will pass it to the multimethod to get\n an appropriate spec. You can e.g. use multi-spec to dynamically and\n extensibly associate specs with 'tagged' data (i.e. data where one\n of the fields indicates the shape of the rest of the structure).\n\n (defmulti mspec :tag)\n\n The methods should ignore their argument and return a predicate/spec:\n (defmethod mspec :int [_] (s/keys :req-un [::tag ::i]))\n\n retag is used during generation to retag generated values with\n matching tags. retag can either be a keyword, at which key the\n dispatch-tag will be assoc'ed, or a fn of generated value and\n dispatch-tag that should return an appropriately retagged value.\n\n Note that because the tags themselves comprise an open set,\n the tag key spec cannot enumerate the values, but can e.g.\n test for keyword?.\n\n Note also that the dispatch values of the multimethod will be\n included in the path, i.e. in reporting and gen overrides, even\n though those values are not evident in the spec.\n","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/multi-spec"},{"ns":"clojure.spec.alpha","name":"explain-data","file":"clojure/spec/alpha.clj","type":"function","column":1,"see-alsos":[{"created-at":1591253326213,"author":{"login":"fredsh2k","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/38362977?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"explain","ns":"clojure.spec.alpha"},"_id":"5ed8994ee4b087629b5a1924"},{"created-at":1591253335898,"author":{"login":"fredsh2k","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/38362977?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"explain-str","ns":"clojure.spec.alpha"},"_id":"5ed89957e4b087629b5a1925"}],"line":225,"examples":[{"editors":[{"login":"fredsh2k","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/38362977?v=4"},{"avatar-url":"https://avatars.githubusercontent.com/u/4986865?v=4","account-source":"github","login":"nvseenu"}],"body":"(require '[clojure.spec.alpha :as spec])\n\n(spec/def ::name string?)\n;;=> :ns/name\n\n(spec/explain-data ::name \"n0\")\n;;=> nil\n\n(spec/explain-data ::name 0)\n;;=>\n;;#:clojure.spec.alpha{:problems [{:path [],\n;; :pred clojure.core/string?,\n;; :val 0,\n;; :via [:ns/name],\n;; :in []}],\n;; :spec :ns.ns/name,\n;; :value 0\n\n\n;; To extract :problems alone \n(:clojure.spec.alpha/problems (spec/explain-data ::name 0)) \n;; => [{:path [],:pred clojure.core/string?,:val 0,:via [:ns/name],:in []}]","author":{"avatar-url":"https://avatars2.githubusercontent.com/u/38362977?v=4","account-source":"github","login":"fredsh2k"},"created-at":1591253258331,"updated-at":1665035425045,"_id":"5ed8990ae4b087629b5a1923"}],"notes":null,"arglists":["spec x"],"doc":"Given a spec and a value x which ought to conform, returns nil if x\n conforms, else a map with at least the key ::problems whose value is\n a collection of problem-maps, where problem-map has at least :path :pred and :val\n keys describing the predicate and the value that failed at that\n path.","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/explain-data"},{"ns":"clojure.spec.alpha","name":"tuple-impl","file":"clojure/spec/alpha.clj","type":"function","skip-wiki":true,"column":1,"see-alsos":null,"line":996,"examples":null,"notes":null,"arglists":["forms preds","forms preds gfn"],"doc":"Do not call this directly, use 'tuple'","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/tuple-impl"},{"ns":"clojure.spec.alpha","name":"multi-spec-impl","file":"clojure/spec/alpha.clj","type":"function","skip-wiki":true,"column":1,"see-alsos":[{"created-at":1549644612774,"author":{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"multi-spec","ns":"clojure.spec.alpha"},"_id":"5c5db344e4b0ca44402ef66c"}],"line":946,"examples":null,"notes":null,"arglists":["form mmvar retag","form mmvar retag gfn"],"doc":"Do not call this directly, use 'multi-spec'","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/multi-spec-impl"},{"ns":"clojure.spec.alpha","name":"tuple","file":"clojure/spec/alpha.clj","type":"macro","column":1,"see-alsos":null,"line":694,"examples":null,"macro":true,"notes":null,"arglists":["& preds"],"doc":"takes one or more preds and returns a spec for a tuple, a vector\n where each element conforms to the corresponding pred. Each element\n will be referred to in paths using its ordinal.","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/tuple"},{"ns":"clojure.spec.alpha","name":"conform","file":"clojure/spec/alpha.clj","type":"function","column":1,"see-alsos":[{"created-at":1524130477189,"author":{"login":"anler","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/83847?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"unform","ns":"clojure.spec.alpha"},"_id":"5ad862ade4b045c27b7fac40"},{"created-at":1524130485944,"author":{"login":"anler","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/83847?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"explain","ns":"clojure.spec.alpha"},"_id":"5ad862b5e4b045c27b7fac41"},{"created-at":1524130495988,"author":{"login":"anler","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/83847?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"gen","ns":"clojure.spec.alpha"},"_id":"5ad862bfe4b045c27b7fac42"}],"line":167,"examples":[{"updated-at":1560617617276,"created-at":1524130497300,"author":{"login":"anler","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/83847?v=4"},"body":"(require '[clojure.spec.alpha :as s])\n\n;; define spec as a sequential concatenation of two more specs:\n;; number? and pos? and one of possible units (:meters :miles)\n;; :amount and :unit are the names we are giving to each position\n(s/def ::distance (s/cat :amount (s/and number? pos?)\n :unit #{:meters :miles}))\n\n(s/conform ::distance [3 :meters])\n;; => {:amount 3, :unit :meters}\n\n(s/conform ::distance [3 :steps])\n;; => :clojure.spec.alpha/invalid","editors":[{"avatar-url":"https://avatars1.githubusercontent.com/u/1175430?v=4","account-source":"github","login":"enocom"}],"_id":"5ad862c1e4b045c27b7fac43"}],"notes":null,"arglists":["spec x"],"doc":"Given a spec and a value, returns :clojure.spec.alpha/invalid \n\tif value does not match spec, else the (possibly destructured) value.","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/conform"},{"ns":"clojure.spec.alpha","name":"gen*","type":"function","see-alsos":null,"examples":null,"notes":null,"tag":null,"arglists":["spec overrides path rmap"],"doc":null,"library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/gen*"},{"ns":"clojure.spec.alpha","name":"fspec-impl","file":"clojure/spec/alpha.clj","type":"function","skip-wiki":true,"column":1,"see-alsos":null,"line":1745,"examples":null,"notes":null,"arglists":["argspec aform retspec rform fnspec fform gfn"],"doc":"Do not call this directly, use 'fspec'","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/fspec-impl"},{"ns":"clojure.spec.alpha","name":"assert","file":"clojure/spec/alpha.clj","type":"macro","column":1,"see-alsos":[{"created-at":1538056781941,"author":{"login":"witek","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/209520?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"assert","ns":"clojure.core"},"_id":"5bace24de4b00ac801ed9eab"},{"created-at":1725986435145,"author":{"login":"abrooks","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/69976?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"check-asserts","ns":"clojure.spec.alpha"},"_id":"66e0768369fbcc0c226174f3"},{"created-at":1725986467648,"author":{"login":"abrooks","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/69976?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"*compile-asserts*","ns":"clojure.spec.alpha"},"_id":"66e076a369fbcc0c226174f4"},{"created-at":1725986480682,"author":{"login":"abrooks","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/69976?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"check-asserts?","ns":"clojure.spec.alpha"},"_id":"66e076b069fbcc0c226174f5"}],"line":1975,"examples":[{"updated-at":1548971359388,"created-at":1548971359388,"author":{"login":"fhur","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/6452323?v=4"},"body":"; Notice that if you try to execute assert it will always return the given value:\n\n(require ['clojure.spec.alpha :as 's])\n\n(s/assert even? 1)\n=> 1\n\n; This is because asserts are turned off by default:\n(s/check-asserts?)\n=> false\n\n; To enable asserts, run this\n(s/check-asserts true)\n=> true\n\n; Now your asserts will properly fail\n(s/assert even? 3)\n; ExceptionInfo Spec assertion failed...\n\n```","_id":"5c536d5fe4b0ca44402ef661"}],"macro":true,"notes":null,"arglists":["spec x"],"doc":"spec-checking assert expression. Returns x if x is valid? according\nto spec, else throws an ex-info with explain-data plus ::failure of\n:assertion-failed.\n\nCan be disabled at either compile time or runtime:\n\nIf *compile-asserts* is false at compile time, compiles to x. Defaults\nto value of 'clojure.spec.compile-asserts' system property, or true if\nnot set.\n\nIf (check-asserts?) is false at runtime, always returns x. Defaults to\nvalue of 'clojure.spec.check-asserts' system property, or false if not\nset. You can toggle check-asserts? with (check-asserts bool).","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/assert"},{"ns":"clojure.spec.alpha","name":"?","file":"clojure/spec/alpha.clj","type":"macro","column":1,"see-alsos":[{"created-at":1549644449353,"author":{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"+","ns":"clojure.spec.alpha"},"_id":"5c5db2a1e4b0ca44402ef669"}],"line":619,"examples":[{"updated-at":1542798236106,"created-at":1542798236106,"author":{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"},"body":";; Think of this as a regex like \"ab?\"\n(s/def ::ab (s/cat :a #{:a}\n :b (s/? #{:b})))\n\n(s/valid? ::ab [:a :b])\n; => true\n\n(s/valid? ::ab [:a])\n; => true\n\n(s/valid? ::ab [:a :c])\n; => false","_id":"5bf53b9ce4b00ac801ed9f05"}],"macro":true,"notes":null,"arglists":["pred-form"],"doc":"Returns a regex op that matches zero or one value matching\n pred. Produces a single value (not a collection) if matched.","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/_q"},{"ns":"clojure.spec.alpha","name":"*coll-check-limit*","file":"clojure/spec/alpha.clj","type":"var","column":1,"see-alsos":null,"dynamic":true,"line":36,"examples":null,"notes":null,"arglists":[],"doc":"The number of elements validated in a collection spec'ed with 'every'","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/*coll-check-limit*"},{"ns":"clojure.spec.alpha","name":"merge","file":"clojure/spec/alpha.clj","type":"macro","column":1,"see-alsos":null,"line":503,"examples":[{"editors":[{"login":"manawardhana","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/1821789?v=4"}],"body":"\n(s/def ::fname string?)\n(s/def ::lname string?)\n(s/def ::street string?)\n(s/def ::city string?)\n\n(s/def ::person (s/keys :req [::fname ::lname]))\n(s/def ::address (s/keys :req [::street ::city]))\n\n;; Merging...\n(s/def ::contact (s/merge ::person ::address))\n\n(s/valid? ::contact {::fname \"Rich\" ::lname \"Hickey\"\n ::street \"Some Street\" ::city \"New York\"})\n;;=> true","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/1821789?v=4","account-source":"github","login":"manawardhana"},"created-at":1527764482905,"updated-at":1527765280946,"_id":"5b0fd602e4b045c27b7fac87"}],"macro":true,"notes":null,"arglists":["& pred-forms"],"doc":"Takes map-validating specs (e.g. 'keys' specs) and\n returns a spec that returns a conformed map satisfying all of the\n specs. Unlike 'and', merge can generate maps satisfying the\n union of the predicates.","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/merge"},{"ns":"clojure.spec.alpha","name":"get-spec","file":"clojure/spec/alpha.clj","type":"function","column":1,"see-alsos":null,"line":361,"examples":null,"notes":null,"arglists":["k"],"doc":"Returns spec registered for keyword/symbol/var k, or nil.","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/get-spec"},{"ns":"clojure.spec.alpha","name":"conformer","file":"clojure/spec/alpha.clj","type":"macro","column":1,"see-alsos":[{"created-at":1588732306293,"author":{"login":"jdf-id-au","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/9016301?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"unform","ns":"clojure.spec.alpha"},"_id":"5eb22192e4b087629b5a1901"}],"line":666,"examples":[{"editors":[{"login":"glts","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/1483271?v=4"}],"body":";; One use of clojure.spec.alpha/conformer is to convert inputs to a data\n;; structure more suitable for further conforming. In this sketch we use a regex\n;; spec to describe a string representing a binary number.\n\n(require '[clojure.spec.alpha :as s]\n '[clojure.spec.gen.alpha :as gen])\n\n(s/def ::str->chars (s/conformer seq #(apply str %)))\n\n(s/def ::binary-digits (s/cat :initial #{\\1}, :more (s/* #{\\0 \\1})))\n\n;; Look, no \"re-matches\"!\n(s/def ::binary-string\n (s/with-gen (s/and string? ::str->chars ::binary-digits)\n (fn []\n (gen/fmap #(s/unform ::str->chars %) (s/gen ::binary-digits)))))\n\n(s/conform ::binary-string \"1011\")\n;;=> {:initial \\1, :more [\\0 \\1 \\1]}\n\n(gen/sample (s/gen ::binary-string))\n;;=> (\"1\" \"1\" \"11\" \"1\" \"1001\" \"11\" \"1100\" \"110011\" \"111111\" \"10\")\n","author":{"avatar-url":"https://avatars3.githubusercontent.com/u/1483271?v=4","account-source":"github","login":"glts"},"created-at":1526667363901,"updated-at":1568125324402,"_id":"5aff1863e4b045c27b7fac6f"},{"updated-at":1592829288019,"created-at":1592829288019,"author":{"login":"ertugrulcetin","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/8271291?v=4"},"body":"(s/conform map? {:a 1})\n;;=> {:a 1}\n\n(s/conform (s/conformer map?) {:a 1})\n;;=> true\n\n-------------------------------\n\n(s/conform second [:a :b :c])\n;;=> [:a :b :c]\n\n(s/conform (s/conformer second) [:a :b :c])\n;;=> :b","_id":"5ef0a568e4b0b1e3652d730b"}],"macro":true,"notes":null,"arglists":["f","f unf"],"doc":"takes a predicate function with the semantics of conform i.e. it should return either a\n (possibly converted) value or :clojure.spec.alpha/invalid, and returns a\n spec that uses it as a predicate/conformer. Optionally takes a\n second fn that does unform of result of first","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/conformer"},{"ns":"clojure.spec.alpha","name":"every-impl","file":"clojure/spec/alpha.clj","type":"function","skip-wiki":true,"column":1,"see-alsos":null,"line":1245,"examples":null,"notes":null,"arglists":["form pred opts","form pred {conform-into :into, describe-form :clojure.spec.alpha/describe, :keys [kind :clojure.spec.alpha/kind-form count max-count min-count distinct gen-max :clojure.spec.alpha/kfn :clojure.spec.alpha/cpred conform-keys :clojure.spec.alpha/conform-all], :or {gen-max 20}, :as opts} gfn"],"doc":"Do not call this directly, use 'every', 'every-kv', 'coll-of' or 'map-of'","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/every-impl"},{"ns":"clojure.spec.alpha","name":"spec","file":"clojure/spec/alpha.clj","type":"macro","column":1,"see-alsos":null,"line":366,"examples":[{"updated-at":1548443679521,"created-at":1548443679521,"author":{"login":"Activeghost","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10783037?v=4"},"body":"(ns ... some namespace declaration \n (:require [clojure.spec.alpha :as s]\n [clojure.spec.gen.alpha :as gen]))\n\n;; for more info see https://clojure.org/guides/spec#_getting_started\n\n;; different types of specs\n\n;; data spec defining a custom generator\n(s/def ::significant-string (s/with-gen \n (s/and string? #(not= % nil?) #(not= % \"\"))\n (fn [] (gen/such-that #(not= % \"\")\n (gen/string-alphanumeric)))))\n\n=> (gen/sample (s/gen '::significant-string))\n;(\"u\" \"p\" \"XG\" \"63\" \"3\" \"HI\" \"e0Ksv\" \"wr9sj3J\" \"600343\" \"D1n9Vz8v\")\n\n;; data spec referring to another spec as a definition\n(s/def ::value ::significant-string)\n\n;; a spec using (s/and ...) with another spec and regex matching\n(s/def ::file-location (s/and ::significant-string #(re-matches constants/filename-regex %)))\n\n;; a map spec asserting required keys (the keys are also specs you would have to define)\n(s/def ::tag-record (s/keys :req-un [::type ::class ::name ::relevance]))\n\n=> (gen/sample (s/gen '::tag-record))\n;({:type {:value \"g\"}, :class {:value \"7X\"}, :name {:value \"3\"}, :relevance {:value \"h\"}} ... many more})\n\n;; defining a spec that is a collection of tag models\n;; see https://clojure.org/guides/spec#_collections \n(s/def ::tag-models (s/coll-of ::tag-model))\n\n=> (gen/sample (s/gen '::tag-models))\n;({[{:tag-type \"G\", :tag-class \"FVrYDZcS\", :tag-name \"7t5u\", :tag-relevance \"1EZ7I32\"} {:tag-type \"Ax0\", :tag-class \"6hfP\", :tag-name \"9Z7v7\", :tag-relevance \"eG\"} {:tag-type \"Tb\", :tag-class \"9EVg46p\", :tag-name \"n1E5Nsl84\", :tag-relevance \"34Q4F\"}] [{:tag-type \"2\", :tag-class \"gy\", :tag-name \"xY9Pmhd43\", :tag-relevance \"QqA1k1G5\"} {:tag-type \"81j\", :tag-class \"52\", :tag-name \"3BrXji\", :tag-relevance \"o6A3t\"} {:tag-type \"Pm2t\", :tag-class \"sW9FH\", :tag-name \"wI2kt\", :tag-relevance \"B\"} {:tag-type \"6p17s\", :tag-class \"4\", :tag-name \"wuV63bjo4\", :tag-relevance \"l77Suzj\"}] ... removed ... })\n\n;; a function spec\n;; see https://clojure.org/guides/spec#_specing_functions \n(s/fdef string->stream\n :args (s/cat :s ::significant-string)\n :ret ::byte-stream\n :fn (fn [{:keys [args ret]}]\n (instance? java.io.ByteArrayInputStream ret)))\n\n;; for this function\n (defn string->stream\n \"Given a string, return a java.io.ByteArrayInputStream\"\n ([s] {:pre [(s/valid? ::significant-string s)]\n :post [(s/valid? ::byte-stream %)]}\n (string->stream s \"UTF-8\"))\n ([s encoding]\n (-> s\n (.getBytes encoding)\n (java.io.ByteArrayInputStream.))))\n","_id":"5c4b601fe4b0ca44402ef62b"}],"macro":true,"notes":null,"arglists":["form & {:keys [gen]}"],"doc":"Takes a single predicate form, e.g. can be the name of a predicate,\n like even?, or a fn literal like #(< % 42). Note that it is not\n generally necessary to wrap predicates in spec when using the rest\n of the spec macros, only to attach a unique generator\n\n Can also be passed the result of one of the regex ops -\n cat, alt, *, +, ?, in which case it will return a regex-conforming\n spec, useful when nesting an independent regex.\n ---\n\n Optionally takes :gen generator-fn, which must be a fn of no args that\n returns a test.check generator.\n\n Returns a spec.","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/spec"},{"ns":"clojure.spec.alpha","name":"keys","file":"clojure/spec/alpha.clj","type":"macro","column":1,"see-alsos":null,"line":414,"examples":[{"editors":[{"login":"penguin2774","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/22309?v=4"}],"body":"(s/def ::id integer?)\n(s/def ::name string?)\n\n(s/def ::user (s/keys :req-un [::id ::name]))\n\n(s/valid? ::user {}) ; false\n(s/valid? ::user {:id 0}) ; false\n(s/valid? ::user {:name \"bob\"}) ; false\n(s/valid? ::user {:id 1 :name \"bob\"}) ; true","author":{"avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4","account-source":"github","login":"bfontaine"},"created-at":1549644274548,"updated-at":1595098386693,"_id":"5c5db1f2e4b0ca44402ef664"},{"updated-at":1582243144778,"created-at":1582243144778,"author":{"login":"robertfw","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/814818?v=4"},"body":";; Demonstrating validation of *all* namespace-qualified keys\n\n(s/def ::id integer?)\n(s/def ::name string?)\n\n(s/def ::user (s/keys))\n\n(s/valid? ::user {}) ; true\n(s/valid? ::user {::id \"bob\"}) ; false\n(s/valid? ::user {::name 1}) ; false\n(s/valid? ::user {::id 1 ::name \"bob\"}) ; true","_id":"5e4f1d48e4b087629b5a189d"}],"macro":true,"notes":null,"arglists":["& {:keys [req req-un opt opt-un gen]}"],"doc":"Creates and returns a map validating spec. :req and :opt are both\n vectors of namespaced-qualified keywords. The validator will ensure\n the :req keys are present. The :opt keys serve as documentation and\n may be used by the generator.\n\n The :req key vector supports 'and' and 'or' for key groups:\n\n (s/keys :req [::x ::y (or ::secret (and ::user ::pwd))] :opt [::z])\n\n There are also -un versions of :req and :opt. These allow\n you to connect unqualified keys to specs. In each case, fully\n qualified keywords are passed, which name the specs, but unqualified\n keys (with the same name component) are expected and checked at\n conform-time, and generated during gen:\n\n (s/keys :req-un [:my.ns/x :my.ns/y])\n\n The above says keys :x and :y are required, and will be validated\n and generated by specs (if they exist) named :my.ns/x :my.ns/y \n respectively.\n\n In addition, the values of *all* namespace-qualified keys will be validated\n (and possibly destructured) by any registered specs. Note: there is\n no support for inline value specification, by design.\n\n Optionally takes :gen generator-fn, which must be a fn of no args that\n returns a test.check generator.","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/keys"},{"ns":"clojure.spec.alpha","name":"spec-impl","file":"clojure/spec/alpha.clj","type":"function","skip-wiki":true,"column":1,"see-alsos":null,"line":913,"examples":null,"notes":null,"arglists":["form pred gfn cpred?","form pred gfn cpred? unc"],"doc":"Do not call this directly, use 'spec'","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/spec-impl"},{"ns":"clojure.spec.alpha","name":"+","file":"clojure/spec/alpha.clj","type":"macro","column":1,"see-alsos":null,"line":613,"examples":null,"macro":true,"notes":null,"arglists":["pred-form"],"doc":"Returns a regex op that matches one or more values matching\n pred. Produces a vector of matches","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/+"},{"ns":"clojure.spec.alpha","name":"invalid?","file":"clojure/spec/alpha.clj","type":"function","column":1,"see-alsos":null,"line":162,"examples":null,"notes":null,"arglists":["ret"],"doc":"tests the validity of a conform return value","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/invalid_q"},{"ns":"clojure.spec.alpha","name":"amp-impl","file":"clojure/spec/alpha.clj","type":"function","skip-wiki":true,"column":1,"see-alsos":null,"line":1418,"examples":null,"notes":null,"arglists":["re re-form preds pred-forms"],"doc":"Do not call this directly, use '&'","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/amp-impl"},{"ns":"clojure.spec.alpha","name":"map-of","file":"clojure/spec/alpha.clj","type":"macro","column":1,"see-alsos":[{"created-at":1549873907812,"author":{"login":"pieterbreed","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/448604?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"every-kv","ns":"clojure.spec.alpha"},"_id":"5c6132f3e4b0ca44402ef675"},{"created-at":1549874043452,"author":{"login":"pieterbreed","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/448604?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"every","ns":"clojure.spec.alpha"},"_id":"5c61337be4b0ca44402ef679"},{"created-at":1549874097531,"author":{"login":"pieterbreed","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/448604?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"coll-of","ns":"clojure.spec.alpha"},"_id":"5c6133b1e4b0ca44402ef67a"}],"line":592,"examples":[{"updated-at":1555060942358,"created-at":1555060942358,"author":{"login":"codxse","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/5813694?v=4"},"body":"(require '[clojure.spec.alpha :as spec])\n\n(spec/def ::animals (spec/map-of #{:duck :cat :chicken} (spec/and int? #(> % 1))))\n\n(spec/valid? ::animals {:duck 2})\n\n;;=> true\n\n(spec/valid? ::animals {:duck 1})\n\n;;=> false","_id":"5cb058cee4b0ca44402ef707"},{"updated-at":1557337699513,"created-at":1557337699513,"author":{"login":"funkrider","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/12958644?v=4"},"body":";; Validating that the value of a map is related to the key \n;; can not normally be done with map-of as the predicates \n;; are applied independently.\n\n(require '[clojure.spec.alpha :as s])\n(require '[clojure.spec.gen.alpha :as gen])\n\n(s/def ::id pos-int?)\n(s/def ::name string?)\n\n(s/def ::tag (s/keys :req-un [::id ::name]))\n(s/def ::tags (s/map-of ::id ::tag))\n\n(gen/sample (s/gen ::tags))\n;; => ({1 {:id 2, :name \"\"}, 2 {:id 3, :name \"\"}}...)\n\n;; The key has no relation to the value.\n\n;; Lets try again and add in another spec that validates the key and value\n(s/def ::tags (s/and \n (s/map-of ::id ::tag) \n (s/every (fn [[k v]] (= (:id v) k)))))\n\n(s/valid? ::tags {101 {:id 101 :name \"foo\"}})\n;; => true\n(s/valid? ::tags {33 {:id 101 :name \"foo\"}})\n;; => false\n\n(s/explain ::tags {33 {:id 101 :name \"foo\"}})\n;; => [33 {:id 101, :name \"foo\"}] - failed: (fn [[k v]] (= (:id v) k)) in: [0] ;; ;; => spec: :user/tags\n\n;; Spec seems good - lets try generators\n\n(gen/sample (s/gen ::tags))\n;; => #error {:message \"Couldn't satisfy such-that predicate after 100 tries.\", :data {}}...\n\n;; Dang, must create a generator ourselves.\n\n(s/def ::tags (s/with-gen\n (s/and\n (s/map-of ::id ::tag)\n (s/every (fn [[k v]](= (:id v) k))))\n #(gen/fmap (fn [c]\n ;; Create a map from the collection\n (apply hash-map (->> c\n (map (juxt :id identity))\n (flatten))))\n ;; Generates a collection of the generated vals\n (s/gen (s/coll-of ::tag))))) \n\n(gen/sample (s/gen ::tags))\n;; =>({2 {:id 2, :name \"wx3p3BPir\"},\n;; => 3 {:id 3, :name \"jq8\"},\n;; => 4 {:id 4, :name \"q3I\"},\n;; => 38 {:id 38, :name \"dhPlIf4\"},\n;; => 7 {:id 7, :name \"t\"},\n;; => 67 {:id 167, :name \"KS9uDEYS\"},\n;; => 11 {:id 11, :name \"\"}, \n;; => 147 {:id 147, :name \"hmSAKGpZ\"}}...)","_id":"5cd31663e4b0ca44402ef71c"}],"macro":true,"notes":null,"arglists":["kpred vpred & opts"],"doc":"Returns a spec for a map whose keys satisfy kpred and vals satisfy\n vpred. Unlike 'every-kv', map-of will exhaustively conform every\n value.\n\n Same options as 'every', :kind defaults to map?, with the addition of:\n\n :conform-keys - conform keys as well as values (default false)\n\n See also - every-kv","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/map-of"},{"ns":"clojure.spec.alpha","name":"cat-impl","file":"clojure/spec/alpha.clj","type":"function","skip-wiki":true,"column":1,"see-alsos":null,"line":1397,"examples":null,"notes":null,"arglists":["ks ps forms"],"doc":"Do not call this directly, use 'cat'","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/cat-impl"},{"ns":"clojure.spec.alpha","name":"explain-str","file":"clojure/spec/alpha.clj","type":"function","column":1,"see-alsos":[{"created-at":1591273515390,"author":{"login":"fredsh2k","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/38362977?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"explain","ns":"clojure.spec.alpha"},"_id":"5ed8e82be4b087629b5a1928"},{"created-at":1591273531958,"author":{"login":"fredsh2k","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/38362977?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"explain-data","ns":"clojure.spec.alpha"},"_id":"5ed8e83be4b087629b5a1929"}],"line":272,"examples":[{"updated-at":1591273493420,"created-at":1591273493420,"author":{"login":"fredsh2k","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/38362977?v=4"},"body":"(require '[clojure.spec.alpha :as spec])\n\n(spec/def ::name string?)\n;;=> :ns/name\n\n(spec/explain-str ::name \"0\")\n;;=> \"Success!\\n\"\n\n(spec/explain-str ::name 0)\n;; => \"0 - failed: string? spec: :ns/name\\n\"","_id":"5ed8e815e4b087629b5a1927"}],"notes":null,"arglists":["spec x"],"doc":"Given a spec and a value that fails to conform, returns an explanation as a string.","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/explain-str"},{"ns":"clojure.spec.alpha","name":"*compile-asserts*","file":"clojure/spec/alpha.clj","type":"var","column":1,"see-alsos":null,"dynamic":true,"line":1939,"examples":null,"notes":null,"arglists":[],"doc":"If true, compiler will enable spec asserts, which are then\nsubject to runtime control via check-asserts? If false, compiler\nwill eliminate all spec assert overhead. See 'assert'.\n\nInitially set to boolean value of clojure.spec.compile-asserts\nsystem property. Defaults to true.","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/*compile-asserts*"},{"ns":"clojure.spec.alpha","name":"with-gen","file":"clojure/spec/alpha.clj","type":"function","column":1,"see-alsos":[{"created-at":1524133491325,"author":{"login":"anler","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/83847?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"gen","ns":"clojure.spec.alpha"},"_id":"5ad86e73e4b045c27b7fac44"}],"line":210,"examples":[{"updated-at":1524133985001,"created-at":1524133985001,"author":{"login":"anler","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/83847?v=4"},"body":"(require '[clojure.spec.alpha :as s]\n '[clojure.spec.gen.alpha :as g])\n\n;; generator for int? includes positive and negative integers\n(-> int?\n s/gen\n g/generate)\n;; => -31\n;; => -177\n;; => 7\n\n;; there's a pos-int? generator that generates only positive integers, but\n;; for the sake of this example let's pretend it doesn't exist\n(-> pos-int?\n s/gen\n g/generate)\n;; => 848961\n;; => 11767\n;; => 3479479\n\n;; let's attach a new generator to int? so it generates only positive integers\n(require '[clojure.test.check.generators :as test.g])\n\n(defn abs [^long v] (Math/abs v))\n\n;; let's generate only positive int? values\n(-> int?\n (s/with-gen #(test.g/fmap abs (s/gen int?)))\n s/gen\n g/generate)\n;; => 299578\n;; => 438034\n;; => 315023\n;; => 31\n\n","_id":"5ad87061e4b045c27b7fac45"},{"editors":[{"login":"holyjak","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/624958?v=4"},{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"}],"body":"(require '[clojure.spec.alpha :as s]\n '[clojure.spec.gen.alpha :as g])\n\n;; How to add a generator to a named spec\n;; Remember that spec expects a fn returning a generator,\n;; not the generator directly!\n(def gen-rand-digit (g/elements (range 10)))\n(s/def ::small-num (s/with-gen\n (s/int-in 0 10)\n (constantly gen-rand-digit)))","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/624958?v=4","account-source":"github","login":"holyjak"},"created-at":1557576794355,"updated-at":1593619477647,"_id":"5cd6bc5ae4b0ca44402ef71f"}],"notes":null,"arglists":["spec gen-fn"],"doc":"Takes a spec and a no-arg, generator-returning fn and returns a version of that spec that uses that generator","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/with-gen"},{"ns":"clojure.spec.alpha","name":"conform*","type":"function","see-alsos":null,"examples":null,"notes":null,"tag":null,"arglists":["spec x"],"doc":null,"library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/conform*"},{"ns":"clojure.spec.alpha","name":"check-asserts?","file":"clojure/spec/alpha.clj","type":"function","column":1,"see-alsos":null,"line":1950,"examples":null,"notes":null,"arglists":[""],"doc":"Returns the value set by check-asserts.","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/check-asserts_q"},{"ns":"clojure.spec.alpha","name":"rep-impl","file":"clojure/spec/alpha.clj","type":"function","skip-wiki":true,"column":1,"see-alsos":null,"line":1409,"examples":null,"notes":null,"arglists":["form p"],"doc":"Do not call this directly, use '*'","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/rep-impl"},{"ns":"clojure.spec.alpha","name":"double-in","file":"clojure/spec/alpha.clj","type":"macro","column":1,"see-alsos":[{"created-at":1549644769131,"author":{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"int-in","ns":"clojure.spec.alpha"},"_id":"5c5db3e1e4b0ca44402ef673"}],"line":1921,"examples":null,"macro":true,"notes":null,"arglists":["& {:keys [infinite? NaN? min max], :or {infinite? true, NaN? true}, :as m}"],"doc":"Specs a 64-bit floating point number. Options:\n\n :infinite? - whether +/- infinity allowed (default true)\n :NaN? - whether NaN allowed (default true)\n :min - minimum value (inclusive, default none)\n :max - maximum value (inclusive, default none)","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/double-in"},{"ns":"clojure.spec.alpha","name":"inst-in","file":"clojure/spec/alpha.clj","type":"macro","column":1,"see-alsos":null,"line":1896,"examples":null,"macro":true,"notes":null,"arglists":["start end"],"doc":"Returns a spec that validates insts in the range from start\n(inclusive) to end (exclusive).","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/inst-in"},{"ns":"clojure.spec.alpha","name":"describe","file":"clojure/spec/alpha.clj","type":"function","column":1,"see-alsos":null,"line":205,"examples":null,"notes":null,"arglists":["spec"],"doc":"returns an abbreviated description of the spec as data","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/describe"},{"ns":"clojure.spec.alpha","name":"explain-out","file":"clojure/spec/alpha.clj","type":"function","column":1,"see-alsos":null,"line":261,"examples":null,"notes":null,"arglists":["ed"],"doc":"Prints explanation data (per 'explain-data') to *out* using the printer in *explain-out*,\n by default explain-printer.","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/explain-out"},{"ns":"clojure.spec.alpha","name":"and","file":"clojure/spec/alpha.clj","type":"macro","column":1,"see-alsos":[{"created-at":1549644301185,"author":{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"or","ns":"clojure.spec.alpha"},"_id":"5c5db20de4b0ca44402ef665"}],"line":493,"examples":[{"updated-at":1586209849180,"created-at":1586209849180,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"body":"(require '[clojure.spec.alpha :as s])\n\n(s/conform (s/and int? pos?) 3) ;=> 3","_id":"5e8ba439e4b087629b5a18cd"}],"macro":true,"notes":null,"arglists":["& pred-forms"],"doc":"Takes predicate/spec-forms, e.g.\n\n (s/and even? #(< % 42))\n\n Returns a spec that returns the conformed value. Successive\n conformed values propagate through rest of predicates.","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/and"},{"ns":"clojure.spec.alpha","name":"specize*","type":"function","see-alsos":null,"examples":null,"notes":null,"tag":null,"arglists":["_","_ form"],"doc":null,"library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/specize*"},{"ns":"clojure.spec.alpha","name":"def","file":"clojure/spec/alpha.clj","type":"macro","column":1,"see-alsos":null,"line":347,"examples":[{"updated-at":1659267005892,"created-at":1659267005892,"author":{"login":"m1nhtu99-hoan9","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/19143075?v=4"},"body":"```clojure\n(ns my-app.entry \n (:require [clojure.spec.alpha :as s]\n [clojure.repl :refer [doc]]))\n\n;; the :: macro will automatically prepend current namespace into \n;; the qualified :entry-state spec keyword\n(s/def ::entry-state #{:entered :exited})\n\n;; check it out:\n(doc :my-app.entry/entry-state)\n;; -------------------------\n;; :my-app.entry/entry-state\n;; Spec\n;; #{:entered :exited}\n```","_id":"62e667bde4b0b1e3652d7635"}],"macro":true,"notes":null,"arglists":["k spec-form"],"doc":"Given a namespace-qualified keyword or resolvable symbol k, and a\n spec, spec-name, predicate or regex-op makes an entry in the\n registry mapping k to the spec. Use nil to remove an entry in\n the registry for k.","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/def"},{"ns":"clojure.spec.alpha","name":"maybe-impl","file":"clojure/spec/alpha.clj","type":"function","skip-wiki":true,"column":1,"see-alsos":[{"created-at":1549644646995,"author":{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"?","ns":"clojure.spec.alpha"},"_id":"5c5db366e4b0ca44402ef66e"}],"line":1451,"examples":null,"notes":null,"arglists":["p form"],"doc":"Do not call this directly, use '?'","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/maybe-impl"},{"ns":"clojure.spec.alpha","name":"explain*","type":"function","see-alsos":null,"examples":null,"notes":null,"tag":null,"arglists":["spec path via in x"],"doc":null,"library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/explain*"},{"ns":"clojure.spec.alpha","name":"fdef","file":"clojure/spec/alpha.clj","type":"macro","column":1,"see-alsos":null,"line":714,"examples":[{"updated-at":1531338068729,"created-at":1531337930997,"author":{"login":"pianostringquartet","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/18562836?v=4"},"body":";; Example from Clojure.org spec guide:\n;; https://clojure.org/guides/spec\n\n(require '[clojure.spec.alpha :as s])\n\n(s/fdef ranged-rand\n :args (s/and (s/cat :start int? :end int?)\n #(< (:start %) (:end %)))\n :ret int?\n :fn (s/and #(>= (:ret %) (-> % :args :start))\n #(< (:ret %) (-> % :args :end))))","editors":[{"avatar-url":"https://avatars0.githubusercontent.com/u/18562836?v=4","account-source":"github","login":"pianostringquartet"}],"_id":"5b465ccae4b00ac801ed9e25"},{"updated-at":1548440412226,"created-at":1548440412226,"author":{"login":"Activeghost","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/10783037?v=4"},"body":"(...ns declaration...\n(:require [clojure.spec.alpha :as s]\n [clojure.spec.gen.alpha :as gen]))\n\n;; lets say I created a set of specs to build up the fn.\n;;\n(s/def ::significant-string (s/with-gen \n (s/and string? #(not (nil? %)))\n (fn [] (gen/such-that #(not= % \"\")\n (gen/string-alphanumeric)))))\n\n(s/def ::byte-stream \n (s/with-gen #(instance? java.io.ByteArrayInputStream %)\n (gen/fmap #(string->stream %) (gen/string-alphanumeric))))\n\n;; :args spec is invoked with an argument list\n;; using cat to reach into the argument list and test conformity to the\n;; ::significant-string spec.\n;; :ret is invoked with the return value (testing conformity to a ::byte-stream)\n;; :fn spec is invoked with a map of the input and return values. (not using args here)\n(s/fdef string->stream\n :args (s/cat :s ::significant-string)\n :ret ::byte-stream\n :fn (fn [{:keys [args ret]}]\n (instance? java.io.ByteArrayInputStream ret)))\n\n;;\n;; the actual fn\n;;\n(defn string->stream\n \"Given a string, return a java.io.ByteArrayInputStream\"\n ([s] {:pre [(s/valid? ::significant-string s)]\n :post [(s/valid? ::byte-stream %)]}\n (string->stream s \"UTF-8\"))\n ([s encoding]\n (-> s\n (.getBytes encoding)\n (java.io.ByteArrayInputStream.))))\n\n;; note, the post condition in this example is redundant with the :fn spec.\n;; and given we aren't using the args value in the :fn spec I would drop that one \n;; in practical use.\n\n","_id":"5c4b535ce4b0ca44402ef629"}],"macro":true,"notes":null,"arglists":["fn-sym & specs"],"doc":"Takes a symbol naming a function, and one or more of the following:\n\n :args A regex spec for the function arguments as they were a list to be\n passed to apply - in this way, a single spec can handle functions with\n multiple arities\n :ret A spec for the function's return value\n :fn A spec of the relationship between args and ret - the\n value passed is {:args conformed-args :ret conformed-ret} and is\n expected to contain predicates that relate those values\n\n Qualifies fn-sym with resolve, or using *ns* if no resolution found.\n Registers an fspec in the global registry, where it can be retrieved\n by calling get-spec with the var or fully-qualified symbol.\n\n Once registered, function specs are included in doc, checked by\n instrument, tested by the runner clojure.spec.test.alpha/check, and (if\n a macro) used to explain errors during macroexpansion.\n\n Note that :fn specs require the presence of :args and :ret specs to\n conform values, and so :fn specs will be ignored if :args or :ret\n are missing.\n\n Returns the qualified fn-sym.\n\n For example, to register function specs for the symbol function:\n\n (s/fdef clojure.core/symbol\n :args (s/alt :separate (s/cat :ns string? :n string?)\n :str string?\n :sym symbol?)\n :ret symbol?)","library-url":"https://github.com/clojure/clojure","href":"/clojure.spec.alpha/fdef"},{"added":"1.1","ns":"clojure.stacktrace","name":"print-stack-trace","file":"clojure/stacktrace.clj","type":"function","column":1,"see-alsos":[{"created-at":1518042239168,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"catch","ns":"clojure.core"},"_id":"5a7b7c7fe4b0316c0f44f8a5"},{"created-at":1518042247997,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"ex-info","ns":"clojure.core"},"_id":"5a7b7c87e4b0316c0f44f8a6"}],"line":50,"examples":[{"updated-at":1508791426015,"created-at":1374649676000,"body":"(clojure.stacktrace/print-stack-trace (Exception. \"foo\"))\n; java.lang.Exception: foo\n; at user$eval112.invoke (NO_SOURCE_FILE:1)\n; clojure.lang.Compiler.eval (Compiler.java:6619)\n; clojure.lang.Compiler.eval (Compiler.java:6582)\n; clojure.core$eval.invoke (core.clj:2852)\n; clojure.main$repl$read_eval_print__6588$fn__6591.invoke (main.clj:259)\n; clojure.main$repl$read_eval_print__6588.invoke (main.clj:259)\n; clojure.main$repl$fn__6597.invoke (main.clj:277)\n; clojure.main$repl.doInvoke (main.clj:277)\n; clojure.lang.RestFn.invoke (RestFn.java:1096)\n; clojure.tools.nrepl.middleware.interruptible_eval$evaluate$fn__3615.invoke (interruptible_eval.clj:56)\n; clojure.lang.AFn.applyToHelper (AFn.java:159)\n; clojure.lang.AFn.applyTo (AFn.java:151)\n; clojure.core$apply.invoke (core.clj:617)\n; clojure.core$with_bindings_STAR_.doInvoke (core.clj:1788)\n; clojure.lang.RestFn.invoke (RestFn.java:425)\n; clojure.tools.nrepl.middleware.interruptible_eval$evaluate.invoke (interruptible_eval.clj:41)\n; clojure.tools.nrepl.middleware.interruptible_eval$interruptible_eval$fn__3656$fn__3659.invoke (interruptible_eval.clj:171)\n; clojure.core$comp$fn__4154.invoke (core.clj:2330)\n; clojure.tools.nrepl.middleware.interruptible_eval$run_next$fn__3649.invoke (interruptible_eval.clj:138)\n; clojure.lang.AFn.run (AFn.java:24)\n; java.util.concurrent.ThreadPoolExecutor.runWorker (:-1)\n; java.util.concurrent.ThreadPoolExecutor$Worker.run (:-1)\n; java.lang.Thread.run (:-1)\n;=> nil\n\n(clojure.stacktrace/print-stack-trace (Exception. \"foo\") 4)\n; java.lang.Exception: foo\n; at user$eval124.invoke (NO_SOURCE_FILE:1)\n; clojure.lang.Compiler.eval (Compiler.java:6619)\n; clojure.lang.Compiler.eval (Compiler.java:6582)\n; clojure.core$eval.invoke (core.clj:2852)\n;=> nil","editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/627acfa99fdd2a4e0c5aab58825b6ffd?r=PG&default=identicon","account-source":"clojuredocs","login":"sjm"},"_id":"542692d7c026201cdc3270fd"},{"updated-at":1508791292657,"created-at":1508791292657,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"},"body":";; if you need to capture the stack trace in a string.\n(with-out-str (clojure.stacktrace/print-stack-trace (Exception. \"foo\") 4))\n;; \"\\n clojure.core/eval core.clj: 3211\\n ... \\n boot.user$eval1726.invoke : 1\\nboot.user$eval1726.invokeStatic : 1\\njava.lang.Exception: foo\\n\"","_id":"59ee53fce4b03026fe14ea94"}],"notes":null,"arglists":["tr","tr n"],"doc":"Prints a Clojure-oriented stack trace of tr, a Throwable.\n Prints a maximum of n stack frames (default: unlimited).\n Does not print chained exceptions (causes).","library-url":"https://github.com/clojure/clojure","href":"/clojure.stacktrace/print-stack-trace"},{"added":"1.1","ns":"clojure.stacktrace","name":"print-trace-element","file":"clojure/stacktrace.clj","type":"function","column":1,"see-alsos":null,"line":28,"examples":[{"updated-at":1508791733815,"created-at":1508791733815,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"},"body":"(clojure.stacktrace/print-trace-element (Exception. \"foo\"))\n; \n;=> nil","_id":"59ee55b5e4b03026fe14ea98"}],"notes":null,"arglists":["e"],"doc":"Prints a Clojure-oriented view of one element in a stack trace.","library-url":"https://github.com/clojure/clojure","href":"/clojure.stacktrace/print-trace-element"},{"added":"1.1","ns":"clojure.stacktrace","name":"print-cause-trace","file":"clojure/stacktrace.clj","type":"function","column":1,"see-alsos":[{"created-at":1433792931008,"author":{"login":"JarredLHumphrey","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/2120888?v=3"},"to-var":{"ns":"clojure.stacktrace","name":"print-stack-trace","library-url":"https://github.com/clojure/clojure"},"_id":"5575f1a3e4b03e2132e7d18a"}],"line":72,"examples":[{"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"}],"body":"(clojure.stacktrace/print-cause-trace (Exception. \"foo\") 4)\n; clojure.core/eval core.clj: 3211\n; ... \n; boot.user$eval1731.invoke : 1\n; boot.user$eval1731.invokeStatic : 1\n; java.lang.Exception: foo\n;=> nil\n","author":{"avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4","account-source":"github","login":"phreed"},"created-at":1508791543258,"updated-at":1508791574495,"_id":"59ee54f7e4b03026fe14ea96"}],"notes":null,"arglists":["tr","tr n"],"doc":"Like print-stack-trace but prints chained exceptions (causes).","library-url":"https://github.com/clojure/clojure","href":"/clojure.stacktrace/print-cause-trace"},{"added":"1.1","ns":"clojure.stacktrace","name":"e","file":"clojure/stacktrace.clj","type":"function","column":1,"see-alsos":null,"line":82,"examples":[{"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"}],"body":"(/ 1 0)\n\n;;ArithmeticException Divide by zero clojure.lang.Numbers.divide (Numbers.java:156)\n\n(clojure.stacktrace/e)\n\n;;java.lang.ArithmeticException: Divide by zero\n;; at clojure.lang.Numbers.divide (Numbers.java:156)\n;; clojure.lang.Numbers.divide (Numbers.java:3731)\n;; user$eval11696.invoke (form-init813878306514169279.clj:1)\n;; clojure.lang.Compiler.eval (Compiler.java:6703)\n;; clojure.lang.Compiler.eval (Compiler.java:6666)\n;; clojure.core$eval.invoke (core.clj:2927)\n;; clojure.main$repl$read_eval_print__6625$fn__6628.invoke (main.clj:239)\n;; clojure.main$repl$read_eval_print__6625.invoke (main.clj:239)\n\n;; => nil","author":{"avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3","account-source":"github","login":"devn"},"created-at":1443937645032,"updated-at":1508791980228,"_id":"5610bd6de4b0686557fcbd52"}],"notes":null,"arglists":[""],"doc":"REPL utility. Prints a brief stack trace for the root cause of the\n most recent exception.","library-url":"https://github.com/clojure/clojure","href":"/clojure.stacktrace/e"},{"added":"1.1","ns":"clojure.stacktrace","name":"root-cause","file":"clojure/stacktrace.clj","type":"function","column":1,"see-alsos":null,"line":20,"examples":[{"updated-at":1508792641035,"created-at":1508792641035,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"},"body":";; make an exception\n(def anex (try (/ 1 0) (catch Exception ex ex)))\n\n;; get the root cause\n(clojure.stacktrace/root-cause anex)\n;;=> #error {\n;; :cause \"Divide by zero\"\n;; :via\n;; [{:type java.lang.ArithmeticException\n;; :message \"Divide by zero\"\n;; :at [clojure.lang.Numbers divide \"Numbers.java\" 163]}]\n;; :trace\n;; [[clojure.lang.Numbers divide \"Numbers.java\" 163]\n;; [clojure.lang.Numbers divide \"Numbers.java\" 3833]\n;; ...\n;; [java.lang.Thread run \"Thread.java\" 748]]}\n","_id":"59ee5941e4b03026fe14ea9e"}],"notes":null,"arglists":["tr"],"doc":"Returns the last 'cause' Throwable in a chain of Throwables.","library-url":"https://github.com/clojure/clojure","href":"/clojure.stacktrace/root-cause"},{"added":"1.1","ns":"clojure.stacktrace","name":"print-throwable","file":"clojure/stacktrace.clj","type":"function","column":1,"see-alsos":[{"created-at":1508792399533,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"print-stack-trace","ns":"clojure.stacktrace"},"_id":"59ee584fe4b03026fe14ea9c"},{"created-at":1508792411207,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"print-cause-trace","ns":"clojure.stacktrace"},"_id":"59ee585be4b03026fe14ea9d"}],"line":40,"examples":[{"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"}],"body":";; let's make an exception\n(def anex (try (/ 1 0) (catch Exception ex ex)))\n\n;; now print the exception\n(clojure.stacktrace/print-throwable anex)\n;; java.lang.ArithmeticException: Divide by zero\n;=> nil\n\n;; and catch it in a string\n(def msg (with-out-str (clojure.stacktrace/print-throwable anex)))\n;=> #'boot.user/msg\n\nmsg\n;=> \"java.lang.ArithmeticException: Divide by zero\"\n\n","author":{"avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4","account-source":"github","login":"phreed"},"created-at":1508792234572,"updated-at":1508792362516,"_id":"59ee57aae4b03026fe14ea9a"}],"notes":null,"arglists":["tr"],"doc":"Prints the class and message of a Throwable. Prints the ex-data map\n if present.","library-url":"https://github.com/clojure/clojure","href":"/clojure.stacktrace/print-throwable"},{"added":"1.8","ns":"clojure.string","name":"ends-with?","file":"clojure/string.clj","type":"function","column":1,"see-alsos":[{"created-at":1543591000911,"author":{"login":"iGEL","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/36442?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"starts-with?","ns":"clojure.string"},"_id":"5c015458e4b0ca44402ef5d4"},{"created-at":1676935186431,"author":{"login":"oakmac","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/98485?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"includes?","ns":"clojure.string"},"_id":"63f40012e4b08cf8563f4b70"}],"line":367,"examples":[{"updated-at":1476954122056,"created-at":1476954122056,"author":{"login":"dalzony","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/562341?v=3"},"body":"(use 'clojure.string)\n\n(ends-with? \"Minsun\" \"sun\")\n;;=> true\n(ends-with? \"Minsun\" \"suns\")\n;;=> false\n(ends-with? \"Minsun\" \"un\")\n;;=> true","_id":"5808880ae4b001179b66bdd4"},{"updated-at":1779491120474,"created-at":1779491120474,"author":{"login":"RezendeComZ","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/52981329?v=4"},"body":"(use 'clojure.string)\n\n;; The first parameter will be converted to a string.\n\n(ends-with? :abc \"c\")\n;;=> true\n(ends-with? 1 \"1\")\n;;=> true\n(ends-with? 2/2 \"1\")\n;;=> true\n\n","_id":"6a10e1306e24dd1705cf9035"}],"notes":null,"arglists":["s substr"],"doc":"True if s ends with substr.","library-url":"https://github.com/clojure/clojure","href":"/clojure.string/ends-with_q"},{"added":"1.2","ns":"clojure.string","name":"capitalize","file":"clojure/string.clj","type":"function","column":1,"see-alsos":[{"created-at":1330171018000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.string","name":"upper-case","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b62"},{"created-at":1330171022000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.string","name":"lower-case","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b63"}],"line":196,"examples":[{"author":{"login":"pkolloch","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/10b2fd3c0a4cc46dc241a48468dc551?r=PG&default=identicon"},"editors":[{"login":"teyc","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bd6e62afb4881ab0f617611b8b65d003?r=PG&default=identicon"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":"user=> (require 'clojure.string)\nnil\n\nuser=> (clojure.string/capitalize \"MiXeD cAsE\")\n\"Mixed case\"\n\nuser=> (clojure.string/capitalize \"mIxEd CaSe\")\n\"Mixed case\"\n","created-at":1282324695000,"updated-at":1285487692000,"_id":"542692d1c026201cdc326f12"},{"editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/40753?v=2","account-source":"github","login":"sir-pinecone"},{"avatar-url":"https://avatars.githubusercontent.com/u/99447?v=3","account-source":"github","login":"olivergeorge"}],"updated-at":1452219646078,"created-at":1415122766154,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/40753?v=2","account-source":"github","login":"sir-pinecone"},"body":"(defn capitalize-words \n \"Capitalize every word in a string\"\n [s]\n (->> (string/split (str s) #\"\\b\") \n (map string/capitalize)\n string/join))\n\n(capitalize-words \"a bunch of words/text\")\n;;=> \"A Bunch Of Words/Text\"","_id":"54590f4ee4b0dc573b892fb8"},{"updated-at":1518738391882,"created-at":1518738391882,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/109629?v=4"},"body":";; Warning: If you deal with Unicode characters often, note that some do not\n;; fit into a single 16-bit Java char. Yes, such Unicode characters exist.\n;; The JVM encodes them in strings in memory using UTF-16, as 2 consecutive\n;; 16-bit values, each with their own separate index in the string's array\n;; of chars.\n\n;; https://en.wikipedia.org/wiki/UTF-16\n\n;; clojure.string/capitalize should not be used for such strings, as it\n;; operates by feeding the first 16-bit Java char for capitalization, and the rest\n;; of the Java chars for converting to lower case.\n\n;; I wouldn't bother filing (another) bug on Clojure for this, since it is\n;; unlikely to change in this regard. If you are dealing with many languages\n;; in the Unicode character set on a regular basis, then you likely\n;; want to use a library like ICU4J, which is much more sophisticated in its\n;; capabilities than anything built into Clojure.\n\n;; ICU4J (also ICU4C): http://site.icu-project.org","_id":"5a861bd7e4b0316c0f44f8c4"}],"notes":null,"tag":"java.lang.String","arglists":["s"],"doc":"Converts first character of the string to upper-case, all other\n characters to lower-case.","library-url":"https://github.com/clojure/clojure","href":"/clojure.string/capitalize"},{"added":"1.2","ns":"clojure.string","name":"reverse","file":"clojure/string.clj","type":"function","column":1,"see-alsos":null,"line":48,"examples":[{"updated-at":1557853754276,"created-at":1291916345000,"body":";; This demonstrates clojure.core/reverse, and not clojure.string/reverse, to be clear.\n\nuser> (reverse \"foo\")\n(\\o \\o \\f)\n\nuser> (apply str (reverse \"foo\"))\n\"oof\"","editors":[{"avatar-url":"https://www.gravatar.com/avatar/73dfb1eb77844f0dbae599ff9b81e78f?r=PG&default=identicon","account-source":"clojuredocs","login":"mudge"},{"avatar-url":"https://avatars3.githubusercontent.com/u/13070019?v=4","account-source":"github","login":"krizk"},{"login":"bpringe","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/12722744?v=4"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3","account-source":"github","login":"devn"},"_id":"542692d1c026201cdc326f10"},{"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"editors":[],"body":";; clojure.string/reverse correctly treats UTF-16 surrogate pairs\n;; as a unit, and does not reverse the 2 Java chars of the pair. Good!\nuser=> (def s \"smily \\ud83d\\ude03.\")\n#'user/s\nuser=> (def x (str/reverse s))\n#'user/x\nuser=> (map #(format \"%04X\" (int %)) s)\n(\"0073\" \"006D\" \"0069\" \"006C\" \"0079\" \"0020\" \"D83D\" \"DE03\" \"002E\")\nuser=> (map #(format \"%04X\" (int %)) x)\n(\"002E\" \"D83D\" \"DE03\" \"0020\" \"0079\" \"006C\" \"0069\" \"006D\" \"0073\")\n","created-at":1329876696000,"updated-at":1329876696000,"_id":"542692d7c026201cdc32710b"}],"notes":null,"tag":"java.lang.String","arglists":["s"],"doc":"Returns s with its characters reversed.","library-url":"https://github.com/clojure/clojure","href":"/clojure.string/reverse"},{"added":"1.2","ns":"clojure.string","name":"join","file":"clojure/string.clj","type":"function","column":1,"see-alsos":[{"created-at":1314291144000,"author":{"login":"Havvy","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e799a79441c7543be48562403411cd13?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"split-at","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d3a"},{"created-at":1314291148000,"author":{"login":"Havvy","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e799a79441c7543be48562403411cd13?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"split-with","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d3b"},{"created-at":1334733670000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.core","name":"interpose","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e48"},{"created-at":1627950208675,"author":{"login":"Okwori","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/16775439?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"apply","ns":"clojure.core"},"_id":"61088c80e4b0b1e3652d752b"}],"line":180,"examples":[{"author":{"login":"pkolloch","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/10b2fd3c0a4cc46dc241a48468dc551?r=PG&default=identicon"},"editors":[{"login":"morty","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/3272?v=3"}],"body":"user=> (clojure.string/join \", \" [1 2 3])\n\"1, 2, 3\"","created-at":1282320829000,"updated-at":1416262356224,"_id":"542692d0c026201cdc326f00"},{"author":{"login":"Santosh","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/851ccd369a1501c72f5e08af19ff9dc1?r=PG&default=identicon"},"editors":[{"login":"Santosh","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/851ccd369a1501c72f5e08af19ff9dc1?r=PG&default=identicon"},{"login":"Santosh","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/851ccd369a1501c72f5e08af19ff9dc1?r=PG&default=identicon"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":";; Splits a string on space character and joins \n;; the resulting collection with a line feed character\n\n(use '[clojure.string :only (join split)])\n\nuser=> (println\n (join \"\\n\"\n (split \"The Quick Brown Fox\" #\"\\s\")))\nThe\nQuick\nBrown\nFox\nnil","created-at":1286103547000,"updated-at":1286115114000,"_id":"542692d0c026201cdc326f01"},{"updated-at":1442089276535,"created-at":1442089276535,"author":{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/94482?v=3"},"body":";; Note that empty strings and nils will appear as blank items\n;; in the result:\n\n(require '[clojure.string :as string])\n\n(string/join \", \" [\"spam\" nil \"eggs\" \"\" \"spam\"])\n;;=> \"spam, , eggs, , spam\"\n\n;; If you'd like to avoid this, you might do something like this:\n\n(string/join \", \" (remove string/blank? [\"spam\" nil \"eggs\" \"\" \"spam\"]))\n;;=> \"spam, eggs, spam\"","_id":"55f4893ce4b06a9ffaad4fbc"},{"editors":[{"login":"timjimsmith","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/23392266?v=4"}],"body":"(require '[clojure.string :as string])\n\n;; No separator means no separation\n(string/join [1 2 3])\n;; => \"123\"","author":{"avatar-url":"https://avatars3.githubusercontent.com/u/23392266?v=4","account-source":"github","login":"timjimsmith"},"created-at":1551217121626,"updated-at":1551217186482,"_id":"5c75b1e1e4b0ca44402ef6a8"},{"editors":[{"login":"Kaspazza","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/36607370?v=4"}],"body":"(require '[clojure.string :as string])\n\n;; One element coll returns just that element\n(string/join \", \" [\"single\"])\n;; => \"single\"","author":{"avatar-url":"https://avatars.githubusercontent.com/u/36607370?v=4","account-source":"github","login":"Kaspazza"},"created-at":1701356607470,"updated-at":1701356620182,"_id":"6568a43f69fbcc0c22617462"}],"notes":null,"tag":"java.lang.String","arglists":["coll","separator coll"],"doc":"Returns a string of all elements in coll, as returned by (seq coll),\n separated by an optional separator.","library-url":"https://github.com/clojure/clojure","href":"/clojure.string/join"},{"added":"1.2","ns":"clojure.string","name":"replace-first","file":"clojure/string.clj","type":"function","column":1,"see-alsos":[{"created-at":1323919307000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.string","name":"replace","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c57"},{"created-at":1324450151000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.core","name":"re-pattern","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c58"},{"created-at":1379040099000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.core","name":"subs","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c59"},{"created-at":1534291088264,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"re-quote-replacement","ns":"clojure.string"},"_id":"5b736c90e4b00ac801ed9e57"}],"line":138,"examples":[{"updated-at":1497950006591,"created-at":1323919917000,"body":"user=> (use '[clojure.string :only (replace-first)])\n\n;; Only replace the first match.\nuser=> (replace-first \"A good day to you, sir. Good day.\" #\"day\" \"night\")\n\"A good night to you, sir. Good day.\"\n\n;; If there are no matches, return the original string.\nuser=> (replace-first \"A good day to you, sir.\" #\"madam\" \"master\")\n\"A good day to you, sir.\"\n\n;; (?i) at the beginning of a pattern makes the entire thing match\n;; case-insensitively, at least for US ASCII characters. (?u) does\n;; the corresponding thing for Unicode.\nuser=> (replace-first \"Day need not be SHOUTED.\" #\"(?i)day\" \"night\")\n\"night need not be SHOUTED.\"\n\n;; See here for many details on regex patterns:\n;; http://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html\n;; Also the book \"Mastering Regular Expressions\" by Jeffrey Friedl.\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3","account-source":"github","login":"jafingerhut"},{"avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3","account-source":"github","login":"jafingerhut"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3","account-source":"github","login":"jafingerhut"},"_id":"542692d7c026201cdc327104"},{"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"editors":[],"body":"user=> (use '[clojure.string :only (replace-first)])\n\n;; Pattern matches from beginning of string (signified by ^) up to the\n;; last occurrence of /, because by default * is greedy, i.e. it\n;; matches as much as possible.\nuser=> (replace-first \"/path/to/file/name\" #\"^.*/\" \"\")\n\"name\"\n\n;; Use *? to match as little as possible.\nuser=> (replace-first \"/path/to/file/name\" #\"^.*?/\" \"\")\n\"path/to/file/name\"\n","created-at":1323919934000,"updated-at":1323919934000,"_id":"542692d7c026201cdc327107"},{"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":";; Note: When replace-first or replace have a regex pattern as their\n;; match argument, dollar sign ($) and backslash (\\) characters in\n;; the replacement string are treated specially.\n\n;; Example: pattern matches string \"fodder\", with (o+) matching \"o\"\n;; and (\\S+) matching \"dder\". Replacement string says to replace the\n;; entire match \"fodder\" with $2, the string matched by the second\n;; parenthesized group, \"dder\", followed by $1, \"o\".\nuser=> (str/replace-first \"fabulous fodder foo food\" #\"f(o+)(\\S+)\" \"$2$1\")\n\"fabulous ddero foo food\"\n\n;; To avoid this special treatment of $ and \\, you must escape them with\n;; \\. Because it is in a Clojure string, to get one \\ we must escape\n;; *that* with its own \\.\nuser=> (str/replace-first \"fabulous fodder foo food\" #\"f(o+)(\\S+)\" \"\\\\$2\\\\$1\")\n\"fabulous $2$1 foo food\"\n\n;; To ensure the replacement is treated literally, call\n;; java.util.regex.Matcher/quoteReplacement on it. A shorter name\n;; like re-qr can be handy.\nuser=> (import '(java.util.regex Matcher))\njava.util.regex.Matcher\n\nuser=> (defn re-qr [replacement]\n (Matcher/quoteReplacement replacement))\n#'user/re-qr\n\nuser=> (str/replace-first \"fabulous fodder foo food\" #\"f(o+)(\\S+)\" (re-qr \"$2$1\"))\n\"fabulous $2$1 foo food\"\n","created-at":1324449916000,"updated-at":1325401081000,"_id":"542692d7c026201cdc327108"},{"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"editors":[],"body":";; Note: See clojure.core/subs for discussion of behavior of substrings\n;; holding onto references of the original strings, which can\n;; significantly affect your memory usage in some cases.","created-at":1379040092000,"updated-at":1379040092000,"_id":"542692d7c026201cdc32710a"}],"notes":null,"tag":"java.lang.String","arglists":["s match replacement"],"doc":"Replaces the first instance of match with replacement in s.\n\n match/replacement can be:\n\n char / char\n string / string\n pattern / (string or function of match).\n\n See also replace.\n\n The replacement is literal (i.e. none of its characters are treated\n specially) for all cases above except pattern / string.\n\n For pattern / string, $1, $2, etc. in the replacement string are\n substituted with the string that matched the corresponding\n parenthesized group in the pattern. If you wish your replacement\n string r to be used literally, use (re-quote-replacement r) as the\n replacement argument. See also documentation for\n java.util.regex.Matcher's appendReplacement method.\n\n Example:\n (clojure.string/replace-first \"swap first two words\"\n #\"(\\w+)(\\s+)(\\w+)\" \"$3$2$1\")\n -> \"first swap two words\"","library-url":"https://github.com/clojure/clojure","href":"/clojure.string/replace-first"},{"added":"1.8","ns":"clojure.string","name":"starts-with?","file":"clojure/string.clj","type":"function","column":1,"see-alsos":[{"created-at":1676935139053,"author":{"login":"oakmac","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/98485?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"ends-with?","ns":"clojure.string"},"_id":"63f3ffe3e4b08cf8563f4b6e"},{"created-at":1676935157532,"author":{"login":"oakmac","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/98485?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"includes?","ns":"clojure.string"},"_id":"63f3fff5e4b08cf8563f4b6f"}],"line":361,"examples":[{"editors":[{"login":"elias94","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8095533?v=4"}],"body":"(ns tst.xyz.core\n (:use clojure.test )\n (:require [clojure.string :as string] ))\n\n(deftest t-starts-with?\n (is (string/starts-with? \"abcde\" \"a\"))\n (is (string/starts-with? \"abcde\" \"ab\"))\n (is (string/starts-with? \"abcde\" \"abc\"))\n\n (is (not (string/starts-with? \"abcde\" \"b\")))\n (is (not (string/starts-with? \"abcde\" \"bc\")))\n\n (is (not (string/starts-with? \"a\" \"ab\")))\n (is (not (string/starts-with? \"ab\" \"abc\"))))","author":{"avatar-url":"https://avatars.githubusercontent.com/u/7083783?v=3","account-source":"github","login":"cloojure"},"created-at":1472592967082,"updated-at":1635628021204,"_id":"57c5fc47e4b0709b524f04dd"},{"updated-at":1779496735572,"created-at":1779496735572,"author":{"login":"RezendeComZ","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/52981329?v=4"},"body":"(use 'clojure.string)\n\n;; The first parameter will be converted to a string.\n\n(starts-with? :some-keyword \":\")\n;;=> true\n(starts-with? 1 \"1\")\n;;=> true\nuser=> (starts-with? 2/2 \"1\")\n;;=> true\n","_id":"6a10f71f6e24dd1705cf9036"}],"notes":[{"author":{"login":"oivulf","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/3288506?v=4"},"updated-at":1638567826166,"created-at":1638567826166,"body":"why not support toffset as java does?","_id":"61aa8f92e4b0b1e3652d757e"}],"arglists":["s substr"],"doc":"True if s starts with substr.","library-url":"https://github.com/clojure/clojure","href":"/clojure.string/starts-with_q"},{"added":"1.2","ns":"clojure.string","name":"escape","file":"clojure/string.clj","type":"function","column":1,"see-alsos":null,"line":301,"examples":[{"updated-at":1451890503592,"created-at":1298559035000,"body":";; There should be no space between the \\ and the &, but I don't know how\n;; to create that in an example yet.\nuser=> (clojure.string/escape \"I want 1 < 2 as HTML, & other good things.\"\n {\\< \"<\", \\> \">\", \\& \"&\"})\n\"I want 1 < 2 as HTML, & other good things.\"","editors":[{"avatar-url":"https://www.gravatar.com/avatar/e1237fa7ee270ace2ebb53c8cab91a6b?r=PG&default=identicon","account-source":"clojuredocs","login":"dyba"},{"login":"pho-coder","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/6576686?v=3"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3","account-source":"github","login":"jafingerhut"},"_id":"542692d1c026201cdc326f15"},{"editors":[{"login":"educoutinho","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/3706894?v=4"}],"body":"(ns test1.core\n (:require [clojure.string :as str]))\n\n(def text1 \"Hello Clojure World!\")\n\n;; Escape each character '!'\n(str/escape text1 {\\! \"!!!\"})\n;; => \"Hello Clojure World!!!\"\n\n;; Escape each space character\n(str/escape text1 {\\ \"-\"})\n;; => \"Hello-Clojure-World!\"\n\n;; Escape each characters '!' or space\n(str/escape text1 {\\! \"!!!\" \\ \"-\"})\n;; => \"Hello-Clojure-World!!!\"","author":{"avatar-url":"https://avatars3.githubusercontent.com/u/3706894?v=4","account-source":"github","login":"educoutinho"},"created-at":1516793634961,"updated-at":1516793653706,"_id":"5a686f22e4b09621d9f53a77"},{"updated-at":1531760345824,"created-at":1531760345824,"author":{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"},"body":";; Note it correctly handles the case where a replacement string contains\n;; a char that’s in the replacement map:\n\n(clojure.string/escape \"123\" {\\1 \"2\" \\2 \"3\" \\3 \"4\"})\n;; => \"234\"\n\n(clojure.string/escape \"ab\" {\\a \"b\" \\b \"a\"})\n;; => \"ba\"","_id":"5b4cced9e4b00ac801ed9e28"},{"updated-at":1598459216961,"created-at":1598459216961,"author":{"login":"GSvensk","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/17110145?v=4"},"body":";; Escape can be called with a function as the second argument.\n\n(defn convert [val]\n (case val\n \\a \\B\n \\b \\A\n \\C))\n\n(clojure.string/escape \"ab\" convert)\n;; => \"BA\"\n\n(clojure.string/escape \"ak\" convert)\n;; => BC","_id":"5f468d50e4b0b1e3652d73ae"}],"notes":null,"tag":"java.lang.String","arglists":["s cmap"],"doc":"Return a new string, using cmap to escape each character ch\n from s as follows:\n \n If (cmap ch) is nil, append ch to the new string.\n If (cmap ch) is non-nil, append (str (cmap ch)) instead.","library-url":"https://github.com/clojure/clojure","href":"/clojure.string/escape"},{"added":"1.8","ns":"clojure.string","name":"last-index-of","file":"clojure/string.clj","type":"function","column":1,"see-alsos":[{"created-at":1472459225244,"author":{"login":"hatappo","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1096084?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"index-of","ns":"clojure.string"},"_id":"57c3f1d9e4b0709b524f04db"}],"line":340,"examples":[{"editors":[{"login":"dalzony","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/562341?v=3"}],"body":";; 1. Just find index of char\n\nuser=> (last-index-of \"aaaaaa\" \"a\")\n5\nuser=> (last-index-of \"abcde\" \"c\")\n2\n\n;; 2. Optionally searching example\n\nuser=> (last-index-of \"abcde\" \"e\" 0)\n;;=> nil\nuser=> (last-index-of \"abcde\" \"e\" 1)\n;;=> nil\nuser=> (last-index-of \"abcde\" \"e\" 2)\n;;=> nil\nuser=> (last-index-of \"abcde\" \"e\" 3)\n;;=> nil\nuser=> (last-index-of \"abcde\" \"e\" 4)\n;;=> 4\nuser=> (last-index-of \"abcde\" \"e\" 5)\n;;=> 4\n","author":{"avatar-url":"https://avatars.githubusercontent.com/u/562341?v=3","account-source":"github","login":"dalzony"},"created-at":1476955531813,"updated-at":1476955666691,"_id":"58088d8be4b001179b66bdd6"}],"notes":null,"arglists":["s value","s value from-index"],"doc":"Return last index of value (string or char) in s, optionally\n searching backward from from-index. Return nil if value not found.","library-url":"https://github.com/clojure/clojure","href":"/clojure.string/last-index-of"},{"added":"1.5","ns":"clojure.string","name":"re-quote-replacement","file":"clojure/string.clj","type":"function","column":1,"see-alsos":[{"created-at":1534291404302,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"replace","ns":"clojure.string"},"_id":"5b736dcce4b00ac801ed9e59"}],"line":54,"examples":[{"body":";; Special characters are escaped\n\n(use '[clojure.string :only (re-quote-replacement)])\n\nuser=> (re-quote-replacement \"string \\\\ $\")\n\"string \\\\\\\\ \\\\$\"","author":{"login":"mzenzie","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1862891?v=3"},"created-at":1433165381448,"updated-at":1433165381448,"_id":"556c5e45e4b03e2132e7d182"},{"editors":[{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"}],"body":";; Use with s/replace to prevent unwanted reference\n;; to matching groups (i.e. $1, $2 etc.)\n\n(require '[clojure.string :as s])\n(def s \"May 2018, June 2019\")\n(s/replace s #\"May|June\" \"10$\") ;; IllegalArgumentException\n(s/replace s #\"May|June\" (s/re-quote-replacement \"10$ in\"))\n;; \"10$ in 2018, 10$ in 2019\"","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"},"created-at":1534291388494,"updated-at":1656679988330,"_id":"5b736dbce4b00ac801ed9e58"}],"notes":null,"tag":"java.lang.String","arglists":["replacement"],"doc":"Given a replacement string that you wish to be a literal\n replacement for a pattern match in replace or replace-first, do the\n necessary escaping of special characters in the replacement.","library-url":"https://github.com/clojure/clojure","href":"/clojure.string/re-quote-replacement"},{"added":"1.8","ns":"clojure.string","name":"includes?","file":"clojure/string.clj","type":"function","column":1,"see-alsos":[{"created-at":1552344296239,"author":{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"re-matches","ns":"clojure.core"},"_id":"5c86e4e8e4b0ca44402ef6b2"},{"created-at":1552344313247,"author":{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"index-of","ns":"clojure.string"},"_id":"5c86e4f9e4b0ca44402ef6b3"}],"line":373,"examples":[{"editors":[{"login":"fasiha","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/37649?v=3"},{"login":"tanrax","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/4553672?v=4"}],"body":";; String-oriented alternative to regular-expression functions in core\n(clojure.string/includes? \"clojure\" \"cl\")\n;;=> true\n\n;; Does *not* work with regular expressions!\n(clojure.string/includes? \"clojure\" #\"cl\")\n;;=> java.util.regex.Pattern cannot be cast to java.lang.CharSequence\n;; (java.lang.ClassCastException)","author":{"avatar-url":"https://avatars.githubusercontent.com/u/37649?v=3","account-source":"github","login":"fasiha"},"created-at":1481745619651,"updated-at":1583219409606,"_id":"5851a4d3e4b004d3a355e2b7"},{"updated-at":1670311423805,"created-at":1670311423805,"author":{"login":"Yacobh","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/9374390?v=4"},"body":"\n;; Be careful when you uses with maps \n(includes? (str (:name {})) \"Bob Alice\")\n;;=> false\n\n(includes? (:name {}) \"Bob Alice\")\n;;=> Execution error (NullPointerException) at user/eval63454 (REPL:1).\n;;Cannot invoke \"Object.toString()\" because \"s\" is null","_id":"638eedffe4b0b1e3652d7694"}],"notes":null,"arglists":["s substr"],"doc":"True if s includes substr.","library-url":"https://github.com/clojure/clojure","href":"/clojure.string/includes_q"},{"added":"1.2","ns":"clojure.string","name":"replace","file":"clojure/string.clj","type":"function","column":1,"see-alsos":[{"created-at":1318625174000,"author":{"login":"mmwaikar","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/29d36f4c9f39c9f8ff61c07033b13118?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"subs","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e64"},{"created-at":1318625263000,"author":{"login":"mmwaikar","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/29d36f4c9f39c9f8ff61c07033b13118?r=PG&default=identicon"},"to-var":{"ns":"clojure.string","name":"split","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e65"},{"created-at":1323919331000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.string","name":"replace-first","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e66"},{"created-at":1534289083122,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"re-quote-replacement","ns":"clojure.string"},"_id":"5b7364bbe4b00ac801ed9e54"}],"line":75,"examples":[{"updated-at":1507930108317,"created-at":1284347892000,"body":"(clojure.string/replace \"The color is red\" #\"red\" \"blue\")\n;=> \"The color is blue\"","editors":[{"avatar-url":"https://www.gravatar.com/avatar/e2051c4ebaaa8c22fa9c0bb2f32f64fd?r=PG&default=identicon","account-source":"clojuredocs","login":"rustem.suniev"},{"avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3","account-source":"github","login":"jafingerhut"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/e2051c4ebaaa8c22fa9c0bb2f32f64fd?r=PG&default=identicon","account-source":"clojuredocs","login":"rustem.suniev"},"_id":"542692d1c026201cdc326f0b"},{"author":{"login":"JD Huntington","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a3d6887041bc564a5d60cdc811ae4ef9?r=PG&default=identicon"},"editors":[{"login":"Domon","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3fe8ae238c14d716a9fc16734a70765b?r=PG&default=identicon"},{"avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4","account-source":"github","login":"phreed"},{"login":"Panthevm","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/43318093?v=4"}],"body":"(clojure.string/replace \"The color is red.\" #\"[aeiou]\" #(str %1 %1))\n;=> \"Thee cooloor iis reed.\"\n","created-at":1295092425000,"updated-at":1604318073825,"_id":"542692d1c026201cdc326f0e"},{"updated-at":1534289397632,"created-at":1324450115000,"body":";; Note: When replace-first or replace have a regex pattern as their\n;; match argument, dollar sign ($) and backslash (\\) characters in\n;; the replacement string are treated specially.\n\n;; Example: first substring that the pattern matches is \"fodder\", with\n;; (o+) matching \"o\" and (\\S+) matching \"dder\". Replacement string\n;; says to replace the entire match \"fodder\" with $2, the string\n;; matched by the second parenthesized group, \"dder\", followed by $1,\n;; \"o\".\n(str/replace \"fabulous fodder foo food\" #\"f(o+)(\\S+)\" \"$2$1\")\n;=> \"fabulous ddero oo doo\"\n\n;; To avoid this special treatment of $ and \\, you must escape them with\n;; \\. Because it is in a Clojure string, to get one \\ we must escape\n;; *that* with its own \\.\n(str/replace \"fabulous fodder foo food\" #\"f(o+)(\\S+)\" \"\\\\$2\\\\$1\")\n;=> \"fabulous $2$1 $2$1 $2$1\"\n\n;; To ensure the replacement is treated literally, call\n;; java.util.regex.Matcher/quoteReplacement on it. A shorter name\n;; like re-qr can be handy.\n(import '(java.util.regex Matcher))\n;=> java.util.regex.Matcher\n\n(defn re-qr [replacement]\n (Matcher/quoteReplacement replacement))\n;=> #'user/re-qr\n\n(str/replace \"fabulous fodder foo food\" #\"f(o+)(\\S+)\" (re-qr \"$2$1\"))\n;=> \"fabulous $2$1 $2$1 $2$1\"\n\n;; Since 1.5, re-qr can be replaced by clojure.string/re-quote-replacement\n(str/replace \"fabulous fodder foo food\" #\"f(o+)(\\S+)\" (str/re-quote-replacement \"$2$1\"))\n;=> \"fabulous $2$1 $2$1 $2$1\"","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3","account-source":"github","login":"jafingerhut"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"},{"avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3","account-source":"github","login":"jafingerhut"},"_id":"542692d7c026201cdc3270fe"},{"updated-at":1507930204780,"created-at":1344740223000,"body":";; replaces all a's with 1 and all b's with 2\n(clojure.string/replace \"a b a\" #\"a|b\" {\"a\" \"1\" \"b\" \"2\"})\n;=> \"1 2 1\"","editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/e33ee460f5f61bc5ba9b598934766215?r=PG&default=identicon","account-source":"clojuredocs","login":"dansalmo"},"_id":"542692d7c026201cdc327100"},{"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"editors":[],"body":";; Note: See clojure.core/subs for discussion of behavior of substrings\n;; holding onto references of the original strings, which can\n;; significantly affect your memory usage in some cases.","created-at":1379040065000,"updated-at":1379040065000,"_id":"542692d7c026201cdc327101"},{"author":{"login":"Corin","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/58ca01bfad092685652c8ea2b7bb3008?r=PG&default=identicon"},"editors":[{"login":"Corin","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/58ca01bfad092685652c8ea2b7bb3008?r=PG&default=identicon"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":";; To title case\n(clojure.string/replace \"hello world\" #\"\\b.\" #(.toUpperCase %1))\n\"Hello World\"\n\n;; Note that a vector is passed to your replacement function\n;; when pattern contains capturing groups (see re-groups)\n(clojure.string/replace \"hello world\" #\"\\b(.)\" #(.toUpperCase (%1 1)))\n\"Hello World\"\n","created-at":1397250241000,"updated-at":1412843380347,"_id":"542692d7c026201cdc327102"},{"updated-at":1464723944272,"created-at":1464723944272,"author":{"login":"alexbispo","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/6197542?v=3"},"body":";; Note that the s \"Vegeta\" is returned as is, because there is no matching.\n(clojure.string/replace \"Vegeta\" #\"Goku\" \"Gohan\")\n\"Vegeta\"","_id":"574de9e8e4b0bafd3e2a046c"},{"updated-at":1636733826696,"created-at":1636733826696,"author":{"login":"wdhowe","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/4631165?v=4"},"body":";; Removing characters, while ignoring case.\n(clojure.string/replace \"Hello hello!\" #\"(?i)[h!]\" \"\")\n\n;=> \"ello ello\"","_id":"618e9382e4b0b1e3652d7572"},{"updated-at":1767193359147,"created-at":1767193359147,"author":{"login":"wdhowe","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/4631165?v=4"},"body":";; Remove the last character in a string\n(clojure.string/replace \"/my/dir/path/\" #\".$\" \"\")\n\n;=> \"/my/dir/path\"","_id":"69553b0fb7956e24e4cb4ec6"}],"notes":[{"updated-at":1351132541000,"body":"How can i replace \".\" with #\"\\s\"","created-at":1351132541000,"author":{"login":"TejasBhatt","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2953c9d9a1566f643e6910c4aa392525?r=PG&default=identicon"},"_id":"542692edf6e94c6970521ff2"}],"tag":"java.lang.String","arglists":["s match replacement"],"doc":"Replaces all instance of match with replacement in s.\n\n match/replacement can be:\n\n string / string\n char / char\n pattern / (string or function of match).\n\n See also replace-first.\n\n The replacement is literal (i.e. none of its characters are treated\n specially) for all cases above except pattern / string.\n\n For pattern / string, $1, $2, etc. in the replacement string are\n substituted with the string that matched the corresponding\n parenthesized group in the pattern. If you wish your replacement\n string r to be used literally, use (re-quote-replacement r) as the\n replacement argument. See also documentation for\n java.util.regex.Matcher's appendReplacement method.\n\n Example:\n (clojure.string/replace \"Almost Pig Latin\" #\"\\b(\\w)(\\w+)\\b\" \"$2$1ay\")\n -> \"lmostAay igPay atinLay\"","library-url":"https://github.com/clojure/clojure","href":"/clojure.string/replace"},{"added":"1.2","ns":"clojure.string","name":"split-lines","file":"clojure/string.clj","type":"function","column":1,"see-alsos":[{"created-at":1329986651000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.string","name":"split","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bce"}],"line":229,"examples":[{"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":"user=> (clojure.string/split-lines \"test \\n string\")\n[\"test \" \" string\"]","created-at":1281617355000,"updated-at":1332953156000,"_id":"542692d0c026201cdc326f08"},{"updated-at":1470989747427,"created-at":1470989747427,"author":{"login":"mdemare","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/4588?v=3"},"body":"; ignores trailing newlines\nuser=> (clojure.string/split-lines \"test\\n\\n\")\n[\"test\"]","_id":"57ad85b3e4b0bafd3e2a04e6"},{"editors":[{"login":"PEZ","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/30010?v=4"}],"body":";; About ignoring trailing newlines: split-lines is implemented something like:\nuser=> (clojure.string/split s #\"\\r?\\n\")\n\n;; To always get all the lines, you need to use split instead,\n;; and supply a negative third argument:\nuser=> (clojure.string/split \"\\ntest\\n\\n\" #\"\\r?\\n\" -1)\n;;=> [\"\" \"test\" \"\" \"\"]","author":{"avatar-url":"https://avatars2.githubusercontent.com/u/30010?v=4","account-source":"github","login":"PEZ"},"created-at":1530254196315,"updated-at":1530254213480,"_id":"5b35d374e4b00ac801ed9e21"}],"notes":null,"arglists":["s"],"doc":"Splits s on \\n or \\r\\n. Trailing empty lines are not returned.","library-url":"https://github.com/clojure/clojure","href":"/clojure.string/split-lines"},{"added":"1.2","ns":"clojure.string","name":"lower-case","file":"clojure/string.clj","type":"function","column":1,"see-alsos":[{"created-at":1330171039000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.string","name":"upper-case","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f4d"},{"created-at":1330171043000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.string","name":"capitalize","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f4e"}],"line":213,"examples":[{"author":{"login":"pkolloch","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/10b2fd3c0a4cc46dc241a48468dc551?r=PG&default=identicon"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":"user=> (clojure.string/lower-case \"MiXeD cAsE\")\n\"mixed case\"","created-at":1282324622000,"updated-at":1332951955000,"_id":"542692d0c026201cdc326ef9"}],"notes":null,"tag":"java.lang.String","arglists":["s"],"doc":"Converts string to all lower-case.","library-url":"https://github.com/clojure/clojure","href":"/clojure.string/lower-case"},{"added":"1.2","ns":"clojure.string","name":"trim-newline","file":"clojure/string.clj","type":"function","column":1,"see-alsos":[{"created-at":1285923216000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.string","name":"trim","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521de8"},{"created-at":1285923222000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.string","name":"triml","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521de9"},{"created-at":1285923228000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.string","name":"trimr","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521dea"}],"line":275,"examples":[{"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"editors":[],"body":"
    \r\nuser=> (clojure.string/trim-newline \"test\\n\\r\")\r\n\"test\"\r\n
    ","created-at":1280737509000,"updated-at":1280737509000,"_id":"542692d1c026201cdc326f18"},{"editors":[{"login":"Kaspazza","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/36607370?v=4"},{"avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4","account-source":"github","login":"tomdl89"}],"body":";; Just like trim, it works only on the end of the string\n(str/trim-newline \"a\\nb\")\n;; => \"a\\nb\"\n\n(str/trim-newline \"a\\nb\\n\")\n;; => \"a\\nb\"\n(str/trim-newline \"ab\\n\")\n;; => \"ab\"","author":{"avatar-url":"https://avatars.githubusercontent.com/u/36607370?v=4","account-source":"github","login":"Kaspazza"},"created-at":1706196770322,"updated-at":1706275228165,"_id":"65b27f2269fbcc0c2261748e"}],"notes":null,"tag":"java.lang.String","arglists":["s"],"doc":"Removes all trailing newline \\n or return \\r characters from\n string. Similar to Perl's chomp.","library-url":"https://github.com/clojure/clojure","href":"/clojure.string/trim-newline"},{"added":"1.2","ns":"clojure.string","name":"upper-case","file":"clojure/string.clj","type":"function","column":1,"see-alsos":[{"created-at":1330171029000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.string","name":"lower-case","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521af0"},{"created-at":1330171033000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.string","name":"capitalize","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521af1"}],"line":207,"examples":[{"author":{"login":"pkolloch","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/10b2fd3c0a4cc46dc241a48468dc551?r=PG&default=identicon"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":"user=> (clojure.string/upper-case \"MiXeD cAsE\")\n\"MIXED CASE\"","created-at":1282324576000,"updated-at":1332951710000,"_id":"542692d0c026201cdc326f05"},{"author":{"login":"nickzam","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/89377?v=2"},"editors":[],"body":";; Non-character symbols will be returned back\nuser=> (clojure.string/upper-case \",.!@#$%^&*()\")\n\",.!@#$%^&*()\"","created-at":1386881910000,"updated-at":1386881910000,"_id":"542692d7c026201cdc327113"},{"updated-at":1520347173061,"created-at":1520347173061,"author":{"login":"lov3machine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/13834519?v=4"},"body":";; upper-case can't handle nil \nuser=> (clojure.string/upper-case nil) ;;=> NullPointerException ","_id":"5a9ea825e4b0316c0f44f90c"}],"notes":null,"tag":"java.lang.String","arglists":["s"],"doc":"Converts string to all upper-case.","library-url":"https://github.com/clojure/clojure","href":"/clojure.string/upper-case"},{"added":"1.2","ns":"clojure.string","name":"split","file":"clojure/string.clj","type":"function","column":1,"see-alsos":[{"created-at":1318625222000,"author":{"login":"mmwaikar","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/29d36f4c9f39c9f8ff61c07033b13118?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"subs","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f59"},{"created-at":1318625227000,"author":{"login":"mmwaikar","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/29d36f4c9f39c9f8ff61c07033b13118?r=PG&default=identicon"},"to-var":{"ns":"clojure.string","name":"replace","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f5a"},{"created-at":1318625367000,"author":{"login":"mmwaikar","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/29d36f4c9f39c9f8ff61c07033b13118?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"re-seq","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f5b"},{"created-at":1329986664000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.string","name":"split-lines","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521f5c"},{"created-at":1519238766963,"author":{"login":"cljlc","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/36645452?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"trim","ns":"clojure.string"},"_id":"5a8dbe6ee4b0316c0f44f8da"},{"created-at":1612477021984,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"join","ns":"clojure.string"},"_id":"601c725de4b0b1e3652d7447"}],"line":219,"examples":[{"updated-at":1727886597157,"created-at":1279388024000,"body":"user=> (require '[clojure.string :as str])\n\nuser=> (str/split \"Clojure is awesome!\" #\" \")\n[\"Clojure\" \"is\" \"awesome!\"]\n\nuser=> (str/split \"q1w2e3r4t5y6u7i8o9p0\" #\"\\d+\")\n[\"q\" \"w\" \"e\" \"r\" \"t\" \"y\" \"u\" \"i\" \"o\" \"p\"]\n\n;; Note that the 'limit' arg is the maximum number of strings to\n;; return (not the number of splits)\nuser=> (str/split \"q1w2e3r4t5y6u7i8o9p0\" #\"\\d+\" 5)\n[\"q\" \"w\" \"e\" \"r\" \"t5y6u7i8o9p0\"]\n\n;; to get back all the characters of a string, as a vector of strings:\nuser=> (str/split \" q1w2 \" #\"\")\n[\" \" \"q\" \"1\" \"w\" \"2\" \" \"]\n;; Note: sequence, in contrast, would return characters.\n\n;; Using lookarounds (lookahead, lookbehind) one can keep the matching characters (aka delimiters or splitters):\nuser=> (str/split \" something and ACamelName \" #\"(?=[A-Z])\")\n[\" something and \" \"A\" \"Camel\" \"Name \"]\n\n;; If the pattern is not found, we get back the original string untouched:\nuser=> (str/split \"a\" #\"b\")\n[\"a\"]\n\nuser=> (str/split \" \" #\"b\")\n[\" \"]\n\nuser=> (str/split \"\" #\"b\")\n[\"\"]\n\n;; If everything matches, an empty vector is returned!\nuser=> (str/split \"a\" #\"a\")\n[]\n\nuser=> (str/split \"aaa\" #\"a\")\n[]\n\n;; but:\nuser=> (str/split \"\" #\"\")\n[\"\"]","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"avatar-url":"https://www.gravatar.com/avatar/1ad3de25d00d953de6e8c82f554cdbf5?r=PG&default=identicon","account-source":"clojuredocs","login":"cloojure"},{"login":"cloojure","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7083783?v=3"},{"login":"cljlc","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/36645452?v=4"},{"login":"daveliepmann","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/974443?v=4"}],"author":{"login":"nipra","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/142529?v=3"},"_id":"542692d0c026201cdc326efb"},{"author":{"login":"Santosh","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/851ccd369a1501c72f5e08af19ff9dc1?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":";; Splits a string on space character and joins \n;; the resulting collection with a line feed character\n\n(use '[clojure.string :only (join split)])\n\nuser=> (println\n (join \"\\n\"\n (split \"The Quick Brown Fox\" #\"\\s\")))\nThe\nQuick\nBrown\nFox\nnil","created-at":1286103685000,"updated-at":1286115074000,"_id":"542692d0c026201cdc326efe"},{"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":"(use '[clojure.string :only (split triml)])\n\n;; Splitting on whitespace is a common desire.\nuser=> (split \"Some words to split\" #\"\\s+\")\n[\"Some\" \"words\" \"to\" \"split\"]\n\n;; By using the pattern #\"\\s+\", we split on all occurrences of one or\n;; more consecutive whitespace characters.\nuser=> (split \"Some words with\\tother whitespace \\n\" #\"\\s+\")\n[\"Some\" \"words\" \"with\" \"other\" \"whitespace\"]\n\n;; If you are used to Perl's special behavior of split(' ', $str),\n;; where it ignores leading whitespace in the string to be split, this\n;; does not quite do it.\nuser=> (split \" Leading whitespace causes empty first string\" #\"\\s+\")\n[\"\" \"Leading\" \"whitespace\" \"causes\" \"empty\" \"first\" \"string\"]\n\n;; This will do it.\nuser=> (defn perl-split-on-space [s]\n (split (triml s) #\"\\s+\"))\n#'user/perl-split-on-space\nuser=> (perl-split-on-space \" This is often what you want \")\n[\"This\" \"is\" \"often\" \"what\" \"you\" \"want\"]\n\n;; There might be cases where you want this instead.\nuser=> (split \"Some words with\\tother whitespace \\n\" #\"\\s\")\n[\"Some\" \"\" \"\" \"\" \"words\" \"\" \"\" \"with\" \"other\" \"whitespace\"]\n","created-at":1323918291000,"updated-at":1324028976000,"_id":"542692d7c026201cdc32710c"},{"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"editors":[],"body":"(use '[clojure.string :only (split)])\n\n;; Split on every occurrence of : character\nuser=> (split \"root:*:0:0:admin:/var/root:/bin/sh\" #\":\")\n[\"root\" \"*\" \"0\" \"0\" \"admin\" \"/var/root\" \"/bin/sh\"]\n\n;; Empty strings are returned when two colons appear consecutively in\n;; the string to be split.\nuser=> (split \"root::0:0::/var/root:/bin/sh\" #\":\")\n[\"root\" \"\" \"0\" \"0\" \"\" \"/var/root\" \"/bin/sh\"]\n\n;; Without specifying a limit, any empty strings at the end are\n;; omitted.\nuser=> (split \"root::0:0:admin:/var/root:\" #\":\")\n[\"root\" \"\" \"0\" \"0\" \"admin\" \"/var/root\"]\nuser=> (split \"root::0:0:admin::\" #\":\")\n[\"root\" \"\" \"0\" \"0\" \"admin\"]\n\n;; If you want all of the fields, even trailing empty ones, use a\n;; negative limit.\nuser=> (split \"root::0:0:admin:/var/root:\" #\":\" -1)\n[\"root\" \"\" \"0\" \"0\" \"admin\" \"/var/root\" \"\"]\nuser=> (split \"root::0:0:admin::\" #\":\" -1)\n[\"root\" \"\" \"0\" \"0\" \"admin\" \"\" \"\"]\n\n;; Use a positive limit of n to limit the maximum number of strings in\n;; the return value to n. If it returns exactly n strings, the last\n;; contains everything left over after splitting off the n-1 earlier\n;; strings.\nuser=> (split \"root::0:0:admin:/var/root:\" #\":\" 2)\n[\"root\" \":0:0:admin:/var/root:\"]\nuser=> (split \"root::0:0:admin:/var/root:\" #\":\" 3)\n[\"root\" \"\" \"0:0:admin:/var/root:\"]\nuser=> (split \"root::0:0:admin:/var/root:\" #\":\" 4)\n[\"root\" \"\" \"0\" \"0:admin:/var/root:\"]\nuser=> (split \"root::0:0:admin:/var/root:\" #\":\" 15)\n[\"root\" \"\" \"0\" \"0\" \"admin\" \"/var/root\" \"\"]\n","created-at":1323918517000,"updated-at":1323918517000,"_id":"542692d7c026201cdc327110"},{"author":{"login":"octopusgrabbus","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/fd31b8bcea99fa7b0711fbc424587774?r=PG&default=identicon"},"editors":[],"body":"(:require [clojure.string :as cstr])\n\n(def legal-ref \"1321-61\")\n\n(cstr/split legal-ref #\"-\")\n[\"1321\" \"61\"]","created-at":1358660615000,"updated-at":1358660615000,"_id":"542692d7c026201cdc327111"},{"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"editors":[],"body":";; Note: See clojure.core/subs for discussion of behavior of substrings\n;; holding onto references of the original strings, which can\n;; significantly affect your memory usage in some cases.","created-at":1379040081000,"updated-at":1379040081000,"_id":"542692d7c026201cdc327112"},{"updated-at":1519238946118,"created-at":1519238946118,"author":{"login":"cljlc","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/36645452?v=4"},"body":";; Note: see clojure.string/trim for an example where\n;; (split ... #\"\\s\") might not do what you expect!","_id":"5a8dbf22e4b0316c0f44f8db"},{"updated-at":1601051069239,"created-at":1601051069239,"author":{"login":"themustafabasit","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/24441401?v=4"},"body":"(let [response {:headers {\"authorization\" \"Token /VwzFIKzVgFOZUeykendtzbKRS/uUvBtfF+LjYB0XRI=\"\n \"host\" \"localhost:7000\"}}]\n (-> response\n :headers\n (get \"authorization\")\n (clojure.string/split #\"\\s\")\n second))\n;; => /VwzFIKzVgFOZUeykendtzbKRS/uUvBtfF+LjYB0XRI=","_id":"5f6e19bde4b0b1e3652d73c1"}],"notes":[{"updated-at":1280043062000,"body":"user=> (clojure.string/split \"foo bar\")\r\njava.lang.ClassNotFoundException: clojure.string\r\n\r\nDo I need to require / use anything?","created-at":1280043062000,"author":{"login":"Jacolyte","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1703a0c3ed358b787f4b1bf3b2799472?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521f89"},{"updated-at":1284342879000,"body":"You need to add a namespace:\r\nuser => (use 'clojure.string)","created-at":1284342879000,"author":{"login":"rustem.suniev","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e2051c4ebaaa8c22fa9c0bb2f32f64fd?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521f95"},{"updated-at":1306110858000,"body":"I 've a doubt...in ruby if I've this:\r\n\r\nbignumber=\"2938434\"\r\n\r\nI can do this\r\n\r\nbignumber.split(\"\") \r\n\r\nand get\r\n(\"2\", \"9\", \"3\", \"8\" .....)\r\n\r\nHow can I do this with clojure?...thanks","created-at":1306110858000,"author":{"login":"cocoOS","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/8be1592fe29f2a7ac4e9e6ad683baaa1?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fbc"},{"updated-at":1315397601000,"body":"Hi, cocoOS. You may want to do it like this:\r\n\r\n
    user=> (use '[clojure.string :only (split)])\r\nnil\r\nuser=> (def bignumber \"2938434\")\r\n#'user/bignumber\r\nuser=> (split bignumber #\"\")\r\n[\"\" \"2\" \"9\" \"3\" \"8\" \"4\" \"3\" \"4\"]\r\n
    \r\n\r\nYou will have to filter out the empty string.\r\n\r\n
    \r\n\r\nBut there are other ways, like:\r\n
    user=> (map str (vec bignumber))\r\n(\"2\" \"9\" \"3\" \"8\" \"4\" \"3\" \"4\")\r\n
    ","created-at":1315395310000,"author":{"login":"Domon","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3fe8ae238c14d716a9fc16734a70765b?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fc9"},{"updated-at":1338786357000,"body":"
    \r\nuser=> (seq \"2938434\")\r\n(\\2 \\9 \\3 \\8 \\4 \\3 \\4)\r\n
    \r\n\r\nmight also be what you want.","created-at":1338786357000,"author":{"login":"Iceland_jack","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/c889e0a95a3bb07f90ab28ad442f1127?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fe2"},{"updated-at":1365500709000,"body":"Thanks for the help Domon and Iceland_jack, one more question:\r\n\r\nSay I have used sequence in the way:\r\n\r\nuser=> (seq \"2938434\")\r\n(\\2 \\9 \\3 \\8 \\4 \\3 \\4)\r\n\r\nIf I only wanted to access the 4th item in the sequence (which is 8), how would I do so? Aside from using (next (next (next ...))) ? Just trying to index it giving that I want position 4","created-at":1365500563000,"author":{"login":"Instinct212","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2f71c013847ef7da0e6cf8ea7a2dec62?r=PG&default=identicon"},"_id":"542692edf6e94c6970522000"},{"body":"When limit=1 the original string is returned\n\n
    \n(clojure.string/split \"abcd\" #\"a\" 1)\n=> [\"abcd\"]\n\n(clojure.string/split \"abcd\" #\"a\" 2)\n=> [\"\" \"bcd\"]\n
    ","created-at":1419810351540,"updated-at":1419810380767,"author":{"login":"olivergeorge","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/99447?v=3"},"_id":"54a0962fe4b09260f767ca81"},{"body":"@Instinct212\n
    \n(nth (seq \"2938434\") 3)\n=> \\8\n
    ","created-at":1448240477083,"updated-at":1448240508295,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/1740215?v=3","account-source":"github","login":"Yuhta"},"_id":"5652655de4b0538444398274"},{"author":{"login":"rux","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/11169?v=3"},"updated-at":1489061703747,"created-at":1489061357001,"body":"There is a change in behaviour between Java 7 and Java 8 that can affect the returned values. \"When there is a positive-width match at the beginning of this string then an empty leading substring is included at the beginning of the resulting array. A zero-width match at the beginning however never produces such empty leading substring.\" was added to the docs for split().\n\nBoth run with Clojure 1.8, the code below splits a string based on capital letters, but...\n\nin Java 7\n\n
    (clojure.string/split \"PrimaryEmailAddr\" #\"(?=[A-Z])\")\n=> [\"\" \"Primary\" \"Email\" \"Addr\"]
    \n\n⁠⁠⁠in Java 8\n\n
    (clojure.string/split \"PrimaryEmailAddr\" #\"(?=[A-Z])\")\n=> [\"Primary\" \"Email\" \"Addr\"]
    ","_id":"58c145ede4b01f4add58fe71"}],"arglists":["s re","s re limit"],"doc":"Splits string on a regular expression. Optional argument limit is\n the maximum number of parts. Not lazy. Returns vector of the parts.\n Trailing empty strings are not returned - pass limit of -1 to return all.","library-url":"https://github.com/clojure/clojure","href":"/clojure.string/split"},{"added":"1.2","ns":"clojure.string","name":"trimr","file":"clojure/string.clj","type":"function","column":1,"see-alsos":[{"created-at":1289214850000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.string","name":"trim","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521ad1"},{"created-at":1289214855000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.string","name":"triml","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521ad2"}],"line":264,"examples":[{"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"editors":[],"body":"(use 'clojure.string)\n(trimr \" my string \")\n=> \" my string\"","created-at":1289214835000,"updated-at":1289214835000,"_id":"542692d0c026201cdc326f07"},{"editors":[{"login":"cljlc","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/36645452?v=4"}],"body":";; Note: see an example at trim for the differences between\n;; \"whitespace\" for trim/trimr/triml and \n;; \"whitespace\" for regex (\\s)","author":{"avatar-url":"https://avatars0.githubusercontent.com/u/36645452?v=4","account-source":"github","login":"cljlc"},"created-at":1519239707456,"updated-at":1519240323449,"_id":"5a8dc21be4b0316c0f44f8de"}],"notes":null,"tag":"java.lang.String","arglists":["s"],"doc":"Removes whitespace from the right side of string.","library-url":"https://github.com/clojure/clojure","href":"/clojure.string/trimr"},{"added":"1.8","ns":"clojure.string","name":"index-of","file":"clojure/string.clj","type":"function","column":1,"see-alsos":[{"created-at":1472459205219,"author":{"login":"hatappo","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1096084?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"last-index-of","ns":"clojure.string"},"_id":"57c3f1c5e4b0709b524f04da"}],"line":319,"examples":[{"updated-at":1472460796969,"created-at":1472458615566,"author":{"login":"hatappo","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1096084?v=3"},"body":"(use '[clojure.string :only [index-of]])\n\n(index-of \"ababc\" \"\")\n;;=> 0\n\n(index-of \"ababc\" \"a\")\n;;=> 0\n\n(index-of \"ababc\" \"ab\")\n;;=> 0\n\n(index-of \"ababc\" \"ab\" 1)\n;;=> 2\n\n(index-of \"ababc\" \"abc\")\n;;=> 2\n\n(index-of \"ababc\" \"abcd\")\n;;=> nil\n\n(index-of \"ababc\" \\c)\n;;=> 4\n\n\n;; same as .indexOf method\n\n(.indexOf \"ababc\" \"ab\")\n;;=> 0\n\n(.indexOf \"ababc\" \"ab\" 1)\n;;=> 2\n\n\n;; different from .indexOf method\n\n(.indexOf \"ababc\" \"abcd\")\n;;=> -1\n\n(.indexOf \"ababc\" \\c)\n;;=> IllegalArgumentException No matching method found: indexOf for class java.lang.String clojure.lang.Reflector.invokeMatchingMethod (Reflector.java:80)\n\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/1096084?v=3","account-source":"github","login":"hatappo"}],"_id":"57c3ef77e4b0709b524f04d7"},{"updated-at":1535012531564,"created-at":1535012531564,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"body":";; Also works with other java.lang.CharSequence impls:\n\n(import 'java.lang.StringBuffer)\n(require '[clojure.string :as s])\n\n(s/index-of (StringBuffer. \"Bonjure Clojure\") \\j)\n;; 3","_id":"5b7e6eb3e4b00ac801ed9e6d"}],"notes":[{"body":"If you want do something similar with Clojure sequences, you can sometimes use Java's `.indexOf`:\n```\n(.indexOf [:a :b :c :d :e] :d) ;=> 3\n(.indexOf [:a :b :c :d :e] :z) ;=> -1\n(.indexOf (list :a :b :c :d :e) :d) ;=> 3\n(.indexOf (range 10) 5) ;=> 5\n```\nNote that failure is indicated with -1.\n\n(It works with strings too, but we already have `index-of` for that.)","created-at":1699933270886,"updated-at":1699933294490,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/1836941?v=4","account-source":"github","login":"mars0i"},"_id":"6552ec5669fbcc0c2261745a"}],"arglists":["s value","s value from-index"],"doc":"Return index of value (string or char) in s, optionally searching\n forward from from-index. Return nil if value not found.","library-url":"https://github.com/clojure/clojure","href":"/clojure.string/index-of"},{"added":"1.2","ns":"clojure.string","name":"trim","file":"clojure/string.clj","type":"function","column":1,"see-alsos":[{"created-at":1285923170000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.string","name":"triml","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521de0"},{"created-at":1285923176000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.string","name":"trimr","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521de1"},{"created-at":1285923182000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.string","name":"trim-newline","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521de2"}],"line":235,"examples":[{"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"editors":[{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},{"login":"biggert","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/4029296?v=3"}],"body":";; Trim basically does what you'd expect. What the doc string\n;; does not tell you however is that:\n;; - null will cause an error\n;; - non-string parameters will cause an error\n\n(use 'clojure.string)\nuser=> (trim \" a \")\n\"a\"\nuser=> (trim nil) \njava.lang.NullPointerException (NO_SOURCE_FILE:0)\nuser=> (trim 1.1)\njava.lang.Double cannot be cast to java.lang.CharSequence\nuser=> (trim [1 2 3])\nclojure.lang.PersistentVector cannot be cast to java.lang.CharSequence\n","created-at":1285923161000,"updated-at":1428428016646,"_id":"542692d0c026201cdc326ef7"},{"editors":[{"login":"cljlc","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/36645452?v=4"}],"body":";; trim might not do what you expect\n;; if your string starts/ends with 'separator' ascii control codes.\n\n;; This is because these characters are treated as\n;; whitespace in trim (and trimr and triml), but\n;; non-whitespace in the regex #\"\\s\" (and \\S).\n\n;; In other words either you believe they are whitespaces or not whitespaces,\n;; you can be surprised when using trim/trimr/triml or when using #\"\\s\" or #\"\\S\":\n;; \"whitespace\" for trim is NOT the same as\n;; \"whitespace\" for \\s.\n\n(use 'clojure.string)\n\n(trim \"a \\u001F\")\n=> \"a\"\n\nbut\n\n(split \"a \\u001F\" #\"\\s+\")\n=> [\"a\" \"\\u001F\"]\n;; instead of [\"a\"], that could be expected based on trim's behaviour\n\n;; The exact list of these special \"characters\":\n;; Dec Hex (UTF-8) Unicode (UTF-16BE) Clojure Name Abbreviation\n;; 28 1C U+001C '\\u001C' File separator FS\n;; 29 1D U+001D '\\u001D' Group separator GS\n;; 30 1E U+001E '\\u001E' Record separator RS\n;; 31 1F U+001F '\\u001F' Unit separator US\n\n;; Background: Clojure's trim uses Java Character's isWhitespace,\n;; that has its own definition of whitespace,\n;; that differs from the definition of whitespace in the \\s\n;; \"whitespace character class\" of Java regex.\n\n;; References:\n;; Clojure trim's source: \n;; https://clojure.github.io/clojure/clojure.string-api.html#clojure.string/trim\n;; Java Character's isWhitespace: \n;; https://docs.oracle.com/javase/8/docs/api/java/lang/Character.html#isWhitespace-char-\n;; Java's \\s whitespace character class: \n;; https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html\n","author":{"avatar-url":"https://avatars0.githubusercontent.com/u/36645452?v=4","account-source":"github","login":"cljlc"},"created-at":1519238263932,"updated-at":1519240206703,"_id":"5a8dbc77e4b0316c0f44f8d9"},{"editors":[{"login":"saitouena","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/40712240?v=4"}],"body":";; No-Break Space \\u00a0 will not be trimmed.\n;; str/replace can be used for No-Break Space\n(str/replace s \"\\u00a0\" \"\")\n\n;; for inspection of codepoint for i-th char of string\n(int (nth (seq s) i))","author":{"avatar-url":"https://avatars3.githubusercontent.com/u/40712240?v=4","account-source":"github","login":"saitouena"},"created-at":1573620092287,"updated-at":1573620157344,"_id":"5dcb897ce4b0ca44402ef7dc"}],"notes":null,"tag":"java.lang.String","arglists":["s"],"doc":"Removes whitespace from both ends of string.","library-url":"https://github.com/clojure/clojure","href":"/clojure.string/trim"},{"added":"1.2","ns":"clojure.string","name":"triml","file":"clojure/string.clj","type":"function","column":1,"see-alsos":[{"created-at":1285923245000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.string","name":"trim","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d6c"},{"created-at":1285923254000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.string","name":"trim-newline","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d6d"},{"created-at":1285923266000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"to-var":{"ns":"clojure.string","name":"trimr","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d6e"}],"line":252,"examples":[{"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"editors":[],"body":"(use 'clojure.string)\n(triml \" my string \")\n=> \"my string \"\n","created-at":1289214918000,"updated-at":1289214918000,"_id":"542692d0c026201cdc326f0a"},{"updated-at":1519240299402,"created-at":1519239323396,"author":{"login":"cljlc","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/36645452?v=4"},"body":";; Note: see an example at trim for the differences between\n;; \"whitespace\" for trim/trimr/triml and \n;; \"whitespace\" for regex (\\s)","editors":[{"avatar-url":"https://avatars0.githubusercontent.com/u/36645452?v=4","account-source":"github","login":"cljlc"}],"_id":"5a8dc09be4b0316c0f44f8dc"}],"notes":null,"tag":"java.lang.String","arglists":["s"],"doc":"Removes whitespace from the left side of string.","library-url":"https://github.com/clojure/clojure","href":"/clojure.string/triml"},{"added":"1.2","ns":"clojure.string","name":"blank?","file":"clojure/string.clj","type":"function","column":1,"see-alsos":[{"created-at":1462633178615,"author":{"login":"cloojure","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7083783?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"trim","ns":"clojure.string"},"_id":"572e02dae4b0b27c121b214e"},{"created-at":1462633189164,"author":{"login":"cloojure","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7083783?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"triml","ns":"clojure.string"},"_id":"572e02e5e4b0b27c121b214f"},{"created-at":1462633194787,"author":{"login":"cloojure","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7083783?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"trimr","ns":"clojure.string"},"_id":"572e02eae4b0b27c121b2150"}],"line":288,"examples":[{"updated-at":1496318959321,"created-at":1293672606000,"body":"user> (clojure.string/blank? nil)\ntrue\n\nuser> (clojure.string/blank? \"\")\ntrue\n\nuser> (clojure.string/blank? \" \")\ntrue\n\nuser> (clojure.string/blank? \" a \")\nfalse\n\nuser> (clojure.string/blank? false)\ntrue\n\nuser> (clojure.string/blank? \"\\n\")\ntrue","editors":[{"login":"cloojure","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7083783?v=3"},{"login":"Azd325","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/426541?v=3"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/bcacd00a7f05c4772329cf9f446c7987?r=PG&default=identicon","account-source":"clojuredocs","login":"dakrone"},"_id":"542692d1c026201cdc326f17"},{"editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"}],"body":";; A way to remove blanks from a string.\n(def astr \"This contains blanks \\n \\t \\r and other whitespace\")\n(->> astr \n (#(clojure.string/split % #\"\\s\")) \n (remove clojure.string/blank?) \n (clojure.string/join \" \"))\n\n;;=> \"This contains blanks and other whitespace\"\n\n;; Of course the task can be better performed other ways.\n;; The goal here is just to show how blank? works.\n(clojure.string/replace (clojure.string/trim astr) #\"\\s{2,}\" \" \")","author":{"avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4","account-source":"github","login":"phreed"},"created-at":1526574308467,"updated-at":1526574971727,"_id":"5afdace4e4b045c27b7fac69"},{"updated-at":1535021760000,"created-at":1535019305646,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"body":";; The list of the 25 whitespace chars in UTF-16. Using the \\uNNNN hex code\n;; when another representation is not available or not printable.\n;; \\u0020 is the common white space, AKA \" \" or '\\space' as a single char.\n\n(require '[clojure.string :as s])\n\n(s/blank? \"\\t \\n \\u000b \\f \\r \\u001c \\u001d \\u001e \\u001f\") ;; true\n(s/blank? \"\\u0020 \\u1680 \\u2000 \\u2001 \\u2002 \\u2003\") ;; true\n(s/blank? \"\\u2004 \\u2005 \\u2006 \\u2008 \\u2009\") ;; true\n(s/blank? \"\\u200a \\u2028 \\u2029 \\u205f \\u3000\") ;; true","editors":[{"avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"}],"_id":"5b7e8929e4b00ac801ed9e6e"}],"notes":null,"arglists":["s"],"doc":"True if s is nil, empty, or contains only whitespace.","library-url":"https://github.com/clojure/clojure","href":"/clojure.string/blank_q"},{"ns":"clojure.template","name":"do-template","file":"clojure/template.clj","type":"macro","column":1,"see-alsos":[{"created-at":1705390128113,"author":{"login":"green-coder","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/598193?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"apply-template","ns":"clojure.template"},"_id":"65a6303069fbcc0c22617481"}],"line":45,"examples":[{"updated-at":1339250655000,"created-at":1280117904000,"body":";; Because it is expanded at compile time, you can also use special \n;; forms as in full blown macros:\n\nuser=> (use 'clojure.template)\nuser=> (do-template [a b] (def a b) d 1 e 2 f 3)\n#'user/f\nuser=> d\n1\nuser=> e\n2\nuser=> f\n3\n\n;; and if you are curious why\nuser=> (use 'clojure.walk)\nuser=> (macroexpand-all '(do-template [a b] (def a b) d 1 e 2 f 3))\n(do (def d 1) (def e 2) (def f 3))\n\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/10b2fd3c0a4cc46dc241a48468dc551?r=PG&default=identicon","account-source":"clojuredocs","login":"pkolloch"},"_id":"542692d1c026201cdc326f19"}],"macro":true,"notes":null,"arglists":["argv expr & values"],"doc":"Repeatedly copies expr (in a do block) for each group of arguments\n in values. values are automatically partitioned by the number of\n arguments in argv, an argument vector as in defn.\n\n Example: (macroexpand '(do-template [x y] (+ y x) 2 4 3 5))\n ;=> (do (+ 4 2) (+ 5 3))","library-url":"https://github.com/clojure/clojure","href":"/clojure.template/do-template"},{"ns":"clojure.template","name":"apply-template","file":"clojure/template.clj","type":"function","column":1,"see-alsos":[{"created-at":1347013502000,"author":{"login":"siteshen","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/a50fd1fe168786443e5fe62560ed03e8?r=PG&default=identicon"},"to-var":{"ns":"clojure.template","name":"do-template","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521dc1"}],"line":30,"examples":[{"author":{"login":"sunil.nandihalli","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3b7fcae9384271fb8ca8cd0c612bebf3?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":"user=> (apply-template '[a b c d e] '[d a b e c e b a d] '(1 2 3 4 5))\n[4 1 2 5 3 5 2 1 4] \n\nuser=> (apply-template '[a b c d e] '[d a b e c e b a d] '(1 [2 3] [4 5]))\n[d 1 [2 3] e [4 5] e [2 3] 1 d]","created-at":1287072285000,"updated-at":1287673447000,"_id":"542692d1c026201cdc326f1c"}],"notes":null,"arglists":["argv expr values"],"doc":"For use in macros. argv is an argument list, as in defn. expr is\n a quoted expression using the symbols in argv. values is a sequence\n of values to be used for the arguments.\n\n apply-template will recursively replace argument symbols in expr\n with their corresponding values, returning a modified expr.\n\n Example: (apply-template '[x] '(+ x x) '[2])\n ;=> (+ 2 2)","library-url":"https://github.com/clojure/clojure","href":"/clojure.template/apply-template"},{"added":"1.1","ns":"clojure.test","name":"are","file":"clojure/test.clj","type":"macro","column":1,"see-alsos":[{"created-at":1281856914000,"author":{"login":"looselytyped","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9bfc2e772db334c8b8516c86b9da7a0c?r=PG&default=identicon"},"to-var":{"ns":"clojure.test","name":"is","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c6f"},{"created-at":1330170936000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.test","name":"deftest","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c70"},{"created-at":1541172463126,"author":{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/94482?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"do-template","ns":"clojure.template"},"_id":"5bdc6cefe4b00ac801ed9eeb"}],"line":572,"examples":[{"author":{"login":"looselytyped","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/9bfc2e772db334c8b8516c86b9da7a0c?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":";; An alternate to the example in the documentation is \n\nuser=> (are [result arg-map] (= result (+ (:x arg-map) (:y arg-map)))\n 5 {:x 2 :y 3},\n 10 {:x 6 :y 4})\n\n\n","created-at":1281856669000,"updated-at":1285494663000,"_id":"542692d1c026201cdc326f27"}],"macro":true,"notes":null,"arglists":["argv expr & args"],"doc":"Checks multiple assertions with a template expression.\n See clojure.template/do-template for an explanation of\n templates.\n\n Example: (are [x y] (= x y) \n 2 (+ 1 1)\n 4 (* 2 2))\n Expands to: \n (do (is (= 2 (+ 1 1)))\n (is (= 4 (* 2 2))))\n\n Note: This breaks some reporting features, such as line numbers.","library-url":"https://github.com/clojure/clojure","href":"/clojure.test/are"},{"added":"1.1","ns":"clojure.test","name":"test-all-vars","file":"clojure/test.clj","type":"function","column":1,"see-alsos":null,"line":737,"examples":null,"notes":null,"arglists":["ns"],"doc":"Calls test-vars on every var interned in the namespace, with fixtures.","library-url":"https://github.com/clojure/clojure","href":"/clojure.test/test-all-vars"},{"added":"1.1","ns":"clojure.test","name":"test-var","file":"clojure/test.clj","type":"function","column":1,"see-alsos":null,"dynamic":true,"line":708,"examples":null,"notes":null,"arglists":["v"],"doc":"If v has a function in its :test metadata, calls that function,\n with *testing-vars* bound to (conj *testing-vars* v).","library-url":"https://github.com/clojure/clojure","href":"/clojure.test/test-var"},{"added":"1.2","ns":"clojure.test","name":"do-report","file":"clojure/test.clj","type":"function","column":1,"see-alsos":null,"line":351,"examples":null,"notes":null,"arglists":["m"],"doc":"Add file and line information to a test result and call report.\n If you are writing a custom assert-expr method, call this function\n to pass test results to report.","library-url":"https://github.com/clojure/clojure","href":"/clojure.test/do-report"},{"added":"1.1","ns":"clojure.test","name":"run-all-tests","file":"clojure/test.clj","type":"function","column":1,"see-alsos":[{"created-at":1417800372343,"author":{"login":"fordsfords","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7671908?v=3"},"to-var":{"ns":"clojure.test","name":"run-tests","library-url":"https://github.com/clojure/clojure"},"_id":"5481eab4e4b0dc573b892fec"},{"created-at":1418219288042,"author":{"login":"fordsfords","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7671908?v=3"},"to-var":{"ns":"clojure.core","name":"re-matches","library-url":"https://github.com/clojure/clojure"},"_id":"54884f18e4b04e93c519ffa2"},{"created-at":1737372327117,"author":{"login":"victorb","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/459764?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"run-test","ns":"clojure.test"},"_id":"678e32a7cd84df5de54e206c"},{"created-at":1737372332113,"author":{"login":"victorb","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/459764?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"run-test-var","ns":"clojure.test"},"_id":"678e32accd84df5de54e206d"}],"line":780,"examples":[{"body":";; assuming current namespace is user\n(use 'clojure.test)\n(deftest eg-tests (is (= 1 1)))\n(run-all-tests)\n;;=> ... visits very many namespaces looking for tests to run\n;;=> {:type :summary, :fail 0, :error 0, :pass 1, :test 1}\n\n(run-all-tests #\"us.*\") ; only matches \"user\"\n;;=> Testing user\n;;=> Ran 1 tests containing 1 assertions.\n;;=> 0 failures, 0 errors.\n;;=> {:type :summary, :fail 0, :error 0, :pass 1, :test 1}\n","author":{"login":"fordsfords","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7671908?v=3"},"created-at":1417800504449,"updated-at":1417800504449,"_id":"5481eb38e4b0dc573b892fed"}],"notes":[{"author":{"login":"PEZ","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/30010?v=4"},"updated-at":1605766888964,"created-at":1605766888964,"body":"In ClojureScript this is a macro. The optional regular expression must be a literal.\n\n```clojure\n(let [rp (re-pattern \"foo\")] (cljs.test/run-all-tests rp))\n;;=> clojure.lang.ExceptionInfo: clojure.lang.Symbol cannot be cast to java.util.regex.Pattern\n```","_id":"5fb60ee8e4b0b1e3652d740e"}],"arglists":["","re"],"doc":"Runs all tests in all namespaces; prints results.\n Optional argument is a regular expression; only namespaces with\n names matching the regular expression (with re-matches) will be\n tested.","library-url":"https://github.com/clojure/clojure","href":"/clojure.test/run-all-tests"},{"added":"1.1","ns":"clojure.test","name":"assert-any","file":"clojure/test.clj","type":"function","column":1,"see-alsos":null,"line":455,"examples":null,"notes":null,"arglists":["msg form"],"doc":"Returns generic assertion code for any test, including macros, Java\n method calls, or isolated symbols.","library-url":"https://github.com/clojure/clojure","href":"/clojure.test/assert-any"},{"added":"1.1","ns":"clojure.test","name":"testing-contexts-str","file":"clojure/test.clj","type":"function","column":1,"see-alsos":null,"line":307,"examples":null,"notes":null,"arglists":[""],"doc":"Returns a string representation of the current test context. Joins\n strings in *testing-contexts* with spaces.","library-url":"https://github.com/clojure/clojure","href":"/clojure.test/testing-contexts-str"},{"added":"1.1","ns":"clojure.test","name":"file-position","file":"clojure/test.clj","type":"function","column":1,"see-alsos":null,"line":282,"examples":[{"updated-at":1534514881886,"created-at":1534514881886,"author":{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/1334295?v=4"},"body":"(clojure.test/file-position 0)\n; => [\"test.clj\" 282]\n\n(take 5 (map clojure.test/file-position (range)))\n; => ([\"test.clj\" 282]\n; [\"test.clj\" 282]\n; [\"core.clj\" 2747]\n; [\"LazySeq.java\" 40]\n; [\"LazySeq.java\" 49])\n","_id":"5b76d6c1e4b00ac801ed9e64"}],"deprecated":"1.2","notes":null,"arglists":["n"],"doc":"Returns a vector [filename line-number] for the nth call up the\n stack.\n\n Deprecated in 1.2: The information needed for test reporting is\n now on :file and :line keys in the result map.","library-url":"https://github.com/clojure/clojure","href":"/clojure.test/file-position"},{"added":"1.1","ns":"clojure.test","name":"testing","file":"clojure/test.clj","type":"macro","column":1,"see-alsos":[{"created-at":1289286950000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.test","name":"is","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c2c"},{"created-at":1330170963000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.test","name":"deftest","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c2d"}],"line":597,"examples":[{"updated-at":1567775824694,"created-at":1289286946000,"body":"(:use 'clojure.test)\n\n; nest within `deftest` in source file\n(testing \"Arithmetic\"\n (testing \"with positive integers\"\n (is (= 4 (+ 2 2)))\n (is (= 7 (+ 3 4))))\n (testing \"with negative integers\"\n (is (= -4 (+ -2 -2)))\n (is (= -1 (+ 3 -4)))))\n=> true\n\n\n---------------------------------------------------------------------------\n\n; nest within `deftest` in source file\n(testing \"Arithmetic\"\n (testing \"with positive integers\"\n (is (= 4 (+ 2 2)))\n (is (= 7 (+ 3 4))))\n (testing \"with negative integers\"\n (is (= -5 (+ -2 -2))) ;error here\n (is (= -1 (+ 3 -4)))))\n\n=> FAIL in clojure.lang.PersistentList$EmptyList@1 (NO_SOURCE_FILE:641)\nArithmetic with negative integers ;bread crumb trail\nexpected: (= -5 (+ -2 -2))\n actual: (not (= -5 -4))\ntrue","editors":[{"avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon","account-source":"clojuredocs","login":"boxie"},{"avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon","account-source":"clojuredocs","login":"boxie"},{"login":"cloojure","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/7083783?v=4"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon","account-source":"clojuredocs","login":"boxie"},"_id":"542692d1c026201cdc326f23"},{"updated-at":1477945021201,"created-at":1477945021201,"author":{"login":"freckletonj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8399149?v=3"},"body":";; this is also valid:\n\n(deftest alternate-use\n (testing \"test a vector of `is`\"\n [(is true)\n (is true)\n (is true)]))\n\n;; which is useful in the following example:\n(defn with-resource [f]\n (setup)\n (f \"expected\")\n (breakdown))\n\n(deftest alternate-use\n (testing \"test a vector of `is`\"\n (with-resource\n (fn [resource]\n [(is (= \"expected\" resource))]))))","_id":"5817a6bde4b024b73ca35a20"}],"macro":true,"notes":null,"arglists":["string & body"],"doc":"Adds a new string to the list of testing contexts. May be nested,\n but must occur inside a test function (deftest).","library-url":"https://github.com/clojure/clojure","href":"/clojure.test/testing"},{"added":"1.1","ns":"clojure.test","name":"join-fixtures","file":"clojure/test.clj","type":"function","column":1,"see-alsos":[{"created-at":1339790151000,"author":{"login":"mnicky","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/be261a601929eaf8eda9e1420b4781f9?r=PG&default=identicon"},"to-var":{"ns":"clojure.test","name":"use-fixtures","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c69"},{"created-at":1339790157000,"author":{"login":"mnicky","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/be261a601929eaf8eda9e1420b4781f9?r=PG&default=identicon"},"to-var":{"ns":"clojure.test","name":"compose-fixtures","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c6a"}],"line":696,"examples":null,"notes":null,"arglists":["fixtures"],"doc":"Composes a collection of fixtures, in order. Always returns a valid\n fixture function, even if the collection is empty.","library-url":"https://github.com/clojure/clojure","href":"/clojure.test/join-fixtures"},{"added":"1.1","ns":"clojure.test","name":"set-test","file":"clojure/test.clj","type":"macro","column":1,"see-alsos":null,"line":648,"examples":null,"macro":true,"notes":null,"arglists":["name & body"],"doc":"Experimental.\n Sets :test metadata of the named var to a fn with the given body.\n The var must already exist. Does not modify the value of the var.\n\n When *load-tests* is false, set-test is ignored.","library-url":"https://github.com/clojure/clojure","href":"/clojure.test/set-test"},{"added":"1.1","ns":"clojure.test","name":"get-possibly-unbound-var","file":"clojure/test.clj","type":"function","column":1,"see-alsos":null,"line":416,"examples":null,"notes":null,"arglists":["v"],"doc":"Like var-get but returns nil if the var is unbound.","library-url":"https://github.com/clojure/clojure","href":"/clojure.test/get-possibly-unbound-var"},{"ns":"clojure.test","name":"assert-expr","file":"clojure/test.clj","type":"var","column":1,"see-alsos":[{"created-at":1561677525480,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"report","ns":"clojure.test"},"_id":"5d154ed5e4b0ca44402ef776"}],"line":476,"examples":[{"updated-at":1561677432836,"created-at":1561676459536,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"body":";; \"assert-expr\" is a multimethod that can be used \n;; to register additional predicates for assert expression.\n;; The following adds a \"roughly\" predicate to check\n;; for numeric equivalence with some tolerance of decimal digits.\n\n(require '[clojure.test :refer [is deftest] :as t])\n\n(defmethod t/assert-expr 'roughly [msg form]\n `(let [op1# ~(nth form 1)\n op2# ~(nth form 2)\n tolerance# (if (= 4 ~(count form)) ~(last form) 2)\n decimals# (/ 1. (Math/pow 10 tolerance#))\n result# (< (Math/abs (- op1# op2#)) decimals#)]\n (t/do-report \n {:type (if result# :pass :fail)\n :message ~msg\n :expected (format \"%s should be roughly %s with %s tolerance\" \n op1# op2# decimals#)\n :actual result#})\n result#))\n\n(deftest PI-test\n (is (roughly 3.14 Math/PI 2))\n (is (roughly 3.14 Math/PI 3)))\n\n(t/test-var #'PI-test)\n\nFAIL in (PI-test)\nexpected: \"3.14 should be roughly 3.141592653589793 with 0.001 tolerance\"\n actual: false","editors":[{"avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"}],"_id":"5d154aabe4b0ca44402ef773"}],"notes":null,"arglists":[],"library-url":"https://github.com/clojure/clojure","href":"/clojure.test/assert-expr"},{"added":"1.1","ns":"clojure.test","name":"report","file":"clojure/test.clj","type":"var","column":1,"see-alsos":null,"dynamic":true,"line":324,"examples":null,"notes":null,"arglists":[],"doc":"Generic reporting function, may be overridden to plug in\n different report formats (e.g., TAP, JUnit). Assertions such as\n 'is' call 'report' to indicate results. The argument given to\n 'report' will be a map with a :type key. See the documentation at\n the top of test_is.clj for more information on the types of\n arguments for 'report'.","library-url":"https://github.com/clojure/clojure","href":"/clojure.test/report"},{"added":"1.1","ns":"clojure.test","name":"compose-fixtures","file":"clojure/test.clj","type":"function","column":1,"see-alsos":[{"created-at":1515206621681,"author":{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/94482?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"join-fixtures","ns":"clojure.test"},"_id":"5a5037dde4b0a08026c48cea"}],"line":689,"examples":null,"notes":null,"arglists":["f1 f2"],"doc":"Composes two fixture functions, creating a new fixture function\n that combines their behavior.","library-url":"https://github.com/clojure/clojure","href":"/clojure.test/compose-fixtures"},{"added":"1.1","ns":"clojure.test","name":"with-test","file":"clojure/test.clj","type":"macro","column":1,"see-alsos":[{"created-at":1289287480000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"test","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bb6"},{"created-at":1289287493000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"meta","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bb7"},{"created-at":1355984959000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.test","name":"deftest","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bb8"}],"line":609,"examples":[{"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/14966?v=4","account-source":"github","login":"gerdint"}],"body":";with-test is the same as using {:test #(do (is...) (is...))} in the meta data of the function.\n\n(:use 'clojure.test)\n\n(with-test\n (defn my-function [x y]\n (+ x y))\n (is (= 4 (my-function 2 2)))\n (is (= 7 (my-function 3 4))))\n\n(test #'my-function) ;(test (var my-function))\n=> :ok","created-at":1289287473000,"updated-at":1745146966286,"_id":"542692d1c026201cdc326f29"}],"macro":true,"notes":null,"arglists":["definition & body"],"doc":"Takes any definition form (that returns a Var) as the first argument.\n Remaining body goes in the :test metadata function for that Var.\n\n When *load-tests* is false, only evaluates the definition, ignoring\n the tests.","library-url":"https://github.com/clojure/clojure","href":"/clojure.test/with-test"},{"added":"1.1","ns":"clojure.test","name":"*stack-trace-depth*","file":"clojure/test.clj","type":"var","column":1,"see-alsos":null,"dynamic":true,"line":252,"examples":null,"notes":null,"arglists":[],"doc":"The maximum depth of stack traces to print when an Exception\n is thrown during a test. Defaults to nil, which means print the \n complete stack trace.","library-url":"https://github.com/clojure/clojure","href":"/clojure.test/*stack-trace-depth*"},{"added":"1.1","ns":"clojure.test","name":"is","file":"clojure/test.clj","type":"macro","column":1,"see-alsos":[{"created-at":1330170895000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.test","name":"are","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bef"},{"created-at":1330170928000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.test","name":"deftest","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521bf0"},{"created-at":1595376872402,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"testing","ns":"clojure.test"},"_id":"5f1784e8e4b0b1e3652d7324"}],"line":554,"examples":[{"author":{"login":"JonNeale","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/52f685bf4240b827b1486b6551cfcd56?r=PG&default=identicon"},"editors":[{"login":"JonNeale","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/52f685bf4240b827b1486b6551cfcd56?r=PG&default=identicon"}],"body":"(use '[clojure.test :only [is]])\n\nuser=> (is (true? true))\ntrue\n\n;; false assertions print a message and evaluate to false\n\nuser=> (is (true? false))\nFAIL in clojure.lang.PersistentList$EmptyList@1 (NO_SOURCE_FILE:1)\nexpected: (true? false)\n actual: (not (true? false))\nfalse\n\n","created-at":1350425559000,"updated-at":1350488982000,"_id":"542692d7c026201cdc327114"},{"author":{"login":"Alan Thompson","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5b677647e3c6fb2bc89fa2f481461b11?r=PG&default=identicon"},"editors":[],"body":"; Testing for thrown exceptions\n\n; Verifies that the specified exception is thrown\nuser=> (is (thrown? ArithmeticException (/ 1 0)))\n#\n\n; Verified that the exception is thrown, and that the error message matches the specified regular expression.\nuser=> (is (thrown-with-msg? ArithmeticException #\"Divide by zero\"\n #_=> (/ 1 0)))\n#\nuser=> \n\n","created-at":1398819305000,"updated-at":1398819305000,"_id":"542692d7c026201cdc327116"}],"macro":true,"notes":[{"author":{"login":"jimka2001","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/6414129?v=4"},"updated-at":1719229515366,"created-at":1719229439111,"body":"Even though the doc string of `is` claims this is a *generic assertion macro* the behavior is critically different from that of `assert`. When the expression within the `is` is falsey, the test is marked as failing, but the test continues to run.\n\nThe following expression will cause two different failures within the same test. I.e., the test will not abort when the first `is` finds a falsey value.\n```\n(do (is (= :yes (throw (ex-info \"test error\" {:test 1}))))\n (is (= :no (ex-info \"test error\" {:test 2}))))\n```\n\nMoreover, the following code will record 1 million failures and fill the log file (output) with some 30 million lines of text.\n\n```\n(doseq [x (range 1000000)]\n (is (< x 0)))\n```","_id":"66795bff69fbcc0c226174d8"},{"body":"WARNING, the message given as the second argument to `is` is not innocuous. \nIt DOES NOT work like the second argument to `assert`. The second argument to `is` is evaluated even if the assertion succeeds. This evaluation can lead to performance problems and even out-of-memory errors.\n\nIf I run the following code using `lein test homework.mwe-test` it runs for several minutes and eventually fails with `Execution error (OutOfMemoryError) at (REPL:1). Java heap space`.\nBut if I replace `is` with `assert` it runs fine and finishes in just a few seconds.\n\n```\n(ns homework.mwe-test\n (:require [clojure.test :refer [deftest is testing]]))\n\n\n\n(deftest t-mwe\n (testing \"mwe\"\n (doseq [a (range 1000)\n b (range 1000)\n :let [data-1 (map (constantly b) (range a))\n data-2 (map (constantly b) (range a))]]\n (is (= data-1 data-2)\n (format \"%s of length %s differs from %s of length %s\"\n data-1 (count data-1)\n data-2 (count data-2))))))\n```","created-at":1742835529378,"updated-at":1742837514127,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/6414129?v=4","account-source":"github","login":"jimka2001"},"_id":"67e18f49cd84df5de54e2082"}],"arglists":["form","form msg"],"doc":"Generic assertion macro. 'form' is any predicate test.\n 'msg' is an optional message to attach to the assertion.\n \n Example: (is (= 4 (+ 2 2)) \"Two plus two should be 4\")\n\n Special forms:\n\n (is (thrown? c body)) checks that an instance of c is thrown from\n body, fails if not; then returns the thing thrown.\n\n (is (thrown-with-msg? c re body)) checks that an instance of c is\n thrown AND that the message on the exception matches (with\n re-find) the regular expression re.","library-url":"https://github.com/clojure/clojure","href":"/clojure.test/is"},{"ns":"clojure.test","name":"*report-counters*","file":"clojure/test.clj","type":"var","column":1,"see-alsos":null,"dynamic":true,"line":262,"examples":null,"notes":null,"arglists":[],"library-url":"https://github.com/clojure/clojure","href":"/clojure.test/*report-counters*"},{"added":"1.1","ns":"clojure.test","name":"*load-tests*","file":"clojure/test.clj","type":"var","column":1,"see-alsos":null,"dynamic":true,"line":245,"examples":[{"updated-at":1619041908533,"created-at":1619041908533,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/20086?v=4"},"body":";; Assuming \"mynamespace\" is available from the classpath and\n;; contains a mix of production and test code, the following prevents\n;; macros like \"deftest\" from producing test functions,\n;; removing them from any compiled AOT artifact:\n\n(require '[clojure.test :as t])\n(binding [t/*load-tests* false]\n (compile 'mynamespace))\n","_id":"60809e74e4b0b1e3652d74cd"}],"notes":[{"body":"In modern times, `*load-tests*` is almost never required, as build tools such as Leiningen or `clojure.tools.deps` enforce a conventional separation of tests from production code, preventing their presence in production artifacts.","created-at":1619041938259,"updated-at":1619041967134,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"},"_id":"60809e92e4b0b1e3652d74ce"}],"arglists":[],"doc":"True by default. If set to false, no test functions will\n be created by deftest, set-test, or with-test. Use this to omit\n tests when compiling or loading production code.","library-url":"https://github.com/clojure/clojure","href":"/clojure.test/*load-tests*"},{"added":"1.1","ns":"clojure.test","name":"deftest","file":"clojure/test.clj","type":"macro","column":1,"see-alsos":[{"created-at":1289287593000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.test","name":"run-all-tests","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e90"},{"created-at":1289288265000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.test","name":"run-tests","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e91"},{"created-at":1330170918000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.test","name":"is","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e92"},{"created-at":1330170920000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.test","name":"are","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e93"},{"created-at":1330170973000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"to-var":{"ns":"clojure.test","name":"testing","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e94"},{"created-at":1366152324000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.test","name":"test-var","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e95"}],"line":622,"examples":[{"author":{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},{"avatar-url":"https://avatars.githubusercontent.com/u/365247?v=4","account-source":"github","login":"nackjicholson"}],"body":";successful test example\n(ns testing)\n(use 'clojure.test)\n\n\n(deftest addition\n (is (= 4 (+ 2 2)))\n (is (= 7 (+ 3 4))))\n=> #'testing/addition\n\n(deftest subtraction\n (is (= 1 (- 4 3)))\n (is (= 3 (- 7 4))))\n=> #'testing/subtraction\n\n;composing tests\n(deftest arithmetic\n (addition)\n (subtraction))\n=> #'testing/arithmetic\n\n(run-tests 'testing)\n\n=> Testing testing\n\nRan 5 tests containing 8 assertions.\n0 failures, 0 errors.\n{:type :summary, :test 5, :pass 8, :fail 0, :error 0}","created-at":1280985983000,"updated-at":1740005348018,"_id":"542692d1c026201cdc326f1e"},{"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"editors":[{"login":"mikebridge","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/517ea04cf362ddc08f107f6ef98a12d9?r=PG&default=identicon"}],"body":";failure test example\n\n;there is nesting, so when a leaf test fails so does its parents, in this example 2 tests fail, though there was only one real error.\n\n(ns testing)\n(use 'clojure.test)\n\n\n(deftest addition\n (is (= 4 (+ 2 2)))\n (is (= 7 (+ 3 4))))\n=> #'testing/addition\n\n(deftest subtraction\n (is (= 1 (- 4 3)))\n (is (= 6 (- 7 4)))) ;error\n=> #'testing/subtraction\n\n;composing tests\n(deftest arithmetic\n (addition)\n (subtraction))\n=> #'testing/arithmetic\n\n(run-tests 'testing)\n\n=> Testing testing\n\nFAIL in (arithmetic subtraction) (NO_SOURCE_FILE:669)\nexpected: (= 6 (- 7 4))\n actual: (not (= 6 3))\n\nFAIL in (subtraction) (NO_SOURCE_FILE:669)\nexpected: (= 6 (- 7 4))\n actual: (not (= 6 3))\n\nRan 6 tests containing 10 assertions.\n2 failures, 0 errors.\n{:type :summary, :test 6, :pass 8, :fail 2, :error 0}","created-at":1289288235000,"updated-at":1332332244000,"_id":"542692d1c026201cdc326f21"}],"macro":true,"notes":null,"arglists":["name & body"],"doc":"Defines a test function with no arguments. Test functions may call\n other tests, so tests may be composed. If you compose tests, you\n should also define a function named test-ns-hook; run-tests will\n call test-ns-hook instead of testing all vars.\n\n Note: Actually, the test body goes in the :test metadata on the var,\n and the real function (the value of the var) calls test-var on\n itself.\n\n When *load-tests* is false, deftest is ignored.","library-url":"https://github.com/clojure/clojure","href":"/clojure.test/deftest"},{"added":"1.1","ns":"clojure.test","name":"assert-predicate","file":"clojure/test.clj","type":"function","column":1,"see-alsos":null,"line":436,"examples":null,"notes":null,"arglists":["msg form"],"doc":"Returns generic assertion code for any functional predicate. The\n 'expected' argument to 'report' will contains the original form, the\n 'actual' argument will contain the form with all its sub-forms\n evaluated. If the predicate returns false, the 'actual' form will\n be wrapped in (not...).","library-url":"https://github.com/clojure/clojure","href":"/clojure.test/assert-predicate"},{"added":"1.1","ns":"clojure.test","name":"with-test-out","file":"clojure/test.clj","type":"macro","column":1,"see-alsos":null,"line":273,"examples":null,"macro":true,"notes":null,"arglists":["& body"],"doc":"Runs body with *out* bound to the value of *test-out*.","library-url":"https://github.com/clojure/clojure","href":"/clojure.test/with-test-out"},{"added":"1.1","ns":"clojure.test","name":"function?","file":"clojure/test.clj","type":"function","column":1,"see-alsos":[{"created-at":1494538047673,"author":{"login":"timgilbert","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/94482?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"fn?","ns":"clojure.core"},"_id":"5914d73fe4b01f4add58feb6"}],"line":424,"examples":[{"author":{"login":"dakrone","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bcacd00a7f05c4772329cf9f446c7987?r=PG&default=identicon"},"editors":[],"body":"user> (defn foo [] (println \"foo\"))\n#'user/foo\n\nuser> (def bar \"bar\")\n#'user/bar\n\nuser> (clojure.test/function? foo)\ntrue\n\nuser> (clojure.test/function? bar)\nfalse","created-at":1293673262000,"updated-at":1293673262000,"_id":"542692d1c026201cdc326f26"}],"notes":null,"arglists":["x"],"doc":"Returns true if argument is a function or a symbol that resolves to\n a function (not a macro).","library-url":"https://github.com/clojure/clojure","href":"/clojure.test/function_q"},{"added":"1.1","ns":"clojure.test","name":"deftest-","file":"clojure/test.clj","type":"macro","column":1,"see-alsos":[{"created-at":1289287570000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.test","name":"deftest","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b08"}],"line":639,"examples":[{"updated-at":1589047680452,"created-at":1589047680452,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"body":";; Create normal test functions which are not public in the current\n;; namespace, but evaluates normally when running tests.\n\n(in-ns 'user)\n(require '[clojure.test :refer :all])\n\n(deftest- this-is-not-public\n (is (= 2 (+ 1 1))))\n\n(ns-publics *ns*)\n;; {}\n\n(run-tests)\n;; Testing user\n;; Ran 1 tests containing 1 assertions.\n;; 0 failures, 0 errors.\n;; {:test 1, :pass 1, :fail 0, :error 0, :type :summary}","_id":"5eb6f180e4b087629b5a1909"}],"macro":true,"notes":null,"arglists":["name & body"],"doc":"Like deftest but creates a private var.","library-url":"https://github.com/clojure/clojure","href":"/clojure.test/deftest-"},{"added":"1.6","ns":"clojure.test","name":"test-vars","file":"clojure/test.clj","type":"function","column":1,"see-alsos":null,"line":723,"examples":[{"editors":[{"login":"fdhenard","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/884972?v=4"}],"body":"(clojure.test/test-vars [#'the-ns/the-test])\n\n;; credit to this SO answer by Alex Miller: https://stackoverflow.com/a/24974841/59439","author":{"avatar-url":"https://avatars2.githubusercontent.com/u/884972?v=4","account-source":"github","login":"fdhenard"},"created-at":1527161820493,"updated-at":1527161857196,"_id":"5b06a3dce4b045c27b7fac77"}],"notes":null,"arglists":["vars"],"doc":"Groups vars by their namespace and runs test-var on them with\n appropriate fixtures applied.","library-url":"https://github.com/clojure/clojure","href":"/clojure.test/test-vars"},{"added":"1.11","ns":"clojure.test","name":"run-test-var","file":"clojure/test.clj","type":"function","column":1,"see-alsos":[{"created-at":1737372350635,"author":{"login":"victorb","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/459764?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"run-test","ns":"clojure.test"},"_id":"678e32becd84df5de54e2070"},{"created-at":1737372356218,"author":{"login":"victorb","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/459764?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"run-tests","ns":"clojure.test"},"_id":"678e32c4cd84df5de54e2071"}],"line":797,"examples":null,"notes":null,"arglists":["v"],"doc":"Runs the tests for a single Var, with fixtures executed around the test, and summary output after.","library-url":"https://github.com/clojure/clojure","href":"/clojure.test/run-test-var"},{"added":"1.1","ns":"clojure.test","name":"try-expr","file":"clojure/test.clj","type":"macro","column":1,"see-alsos":[{"created-at":1289460897000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.test","name":"is","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cf6"}],"line":538,"examples":[{"editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/200617?v=3","account-source":"github","login":"bsima"}],"updated-at":1437772493560,"created-at":1415383686022,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/200617?v=3","account-source":"github","login":"bsima"},"body":"(try-expr \"Can I call this function?\" (= 1 1))\n;; => \"No! I said you don't call this.\" - Rich Hickey","_id":"545d0a86e4b03d20a10242a0"}],"macro":true,"notes":null,"arglists":["msg form"],"doc":"Used by the 'is' macro to catch unexpected exceptions.\n You don't call this.","library-url":"https://github.com/clojure/clojure","href":"/clojure.test/try-expr"},{"added":"1.1","ns":"clojure.test","name":"successful?","file":"clojure/test.clj","type":"function","column":1,"see-alsos":null,"line":789,"examples":null,"notes":null,"arglists":["summary"],"doc":"Returns true if the given test summary indicates all tests\n were successful, false otherwise.","library-url":"https://github.com/clojure/clojure","href":"/clojure.test/successful_q"},{"added":"1.1","ns":"clojure.test","name":"use-fixtures","file":"clojure/test.clj","type":"var","column":1,"see-alsos":[{"created-at":1339790120000,"author":{"login":"mnicky","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/be261a601929eaf8eda9e1420b4781f9?r=PG&default=identicon"},"to-var":{"ns":"clojure.test","name":"join-fixtures","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ceb"},{"created-at":1339790135000,"author":{"login":"mnicky","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/be261a601929eaf8eda9e1420b4781f9?r=PG&default=identicon"},"to-var":{"ns":"clojure.test","name":"compose-fixtures","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cec"}],"line":670,"examples":[{"author":{"login":"benkay","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/21acd4a2c781a436afdb28fead34b76a?r=PG&default=identicon"},"editors":[{"login":"cloojure","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1ad3de25d00d953de6e8c82f554cdbf5?r=PG&default=identicon"},{"login":"cloojure","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1ad3de25d00d953de6e8c82f554cdbf5?r=PG&default=identicon"}],"body":"; See https://clojure.github.io/clojure/clojure.test-api.html for details\n\n; my-test-fixture will be passed a fn that will call all your tests \n; (e.g. test-using-db). Here you perform any required setup \n; (e.g. create-db), then call the passed function f, then perform \n; any required teardown (e.g. destroy-db).\n(defn my-test-fixture [f]\n (create-db)\n (f)\n (destroy-db))\n\n; Here we register my-test-fixture to be called once, wrapping ALL tests \n; in the namespace\n(use-fixtures :once my-test-fixture)\n \n; This is a regular test function, which is to be wrapped using my-test-fixture\n(deftest test-using-db\n (is ... \n))","created-at":1375349400000,"updated-at":1405042589000,"_id":"542692d7c026201cdc327117"},{"author":{"login":"cloojure","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1ad3de25d00d953de6e8c82f554cdbf5?r=PG&default=identicon"},"editors":[{"login":"cloojure","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1ad3de25d00d953de6e8c82f554cdbf5?r=PG&default=identicon"},{"login":"cloojure","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1ad3de25d00d953de6e8c82f554cdbf5?r=PG&default=identicon"}],"body":"; This fixture is intended to perform setup/teardown for each individual test in the namespace. Note that it assumes the :once fixture will handle creating/destroying the DB, while we only create/drop tables within the DB.\n(defn another-fixture [f]\n (create-db-table)\n (f)\n (drop-db-table))\n\n; Here we register another-fixture to wrap each test in the namespace\n(use-fixtures :each another-fixture)","created-at":1405042717000,"updated-at":1405043050000,"_id":"542692d7c026201cdc32711a"},{"updated-at":1456028182727,"created-at":1456028130697,"author":{"login":"charlespwd","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/4990691?v=3"},"body":";; `use-fixtures` supports multiples arguments. \n;; They wrap the tests in order (left-to-right).\n\n;; We define some fixtures that are to be run in order\n(defn with-db [f] \n (start-db)\n (f)\n (stop-db))\n\n(defn with-data [f] \n (fill-db)\n (f)\n (empty-db))\n\n;; Here we register them\n(use-fixtures :once with-db with-data)","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/4990691?v=3","account-source":"github","login":"charlespwd"}],"_id":"56c939e2e4b0b41f39d96cd0"}],"notes":null,"arglists":[],"doc":"Wrap test runs in a fixture function to perform setup and\n teardown. Using a fixture-type of :each wraps every test\n individually, while :once wraps the whole run in a single function.","library-url":"https://github.com/clojure/clojure","href":"/clojure.test/use-fixtures"},{"added":"1.1","ns":"clojure.test","name":"inc-report-counter","file":"clojure/test.clj","type":"function","column":1,"see-alsos":null,"line":314,"examples":null,"notes":null,"arglists":["name"],"doc":"Increments the named counter in *report-counters*, a ref to a map.\n Does nothing if *report-counters* is nil.","library-url":"https://github.com/clojure/clojure","href":"/clojure.test/inc-report-counter"},{"added":"1.1","ns":"clojure.test","name":"testing-vars-str","file":"clojure/test.clj","type":"function","column":1,"see-alsos":null,"line":294,"examples":null,"notes":null,"arglists":["m"],"doc":"Returns a string representation of the current test. Renders names\n in *testing-vars* as a list, then the source file and line of\n current assertion.","library-url":"https://github.com/clojure/clojure","href":"/clojure.test/testing-vars-str"},{"ns":"clojure.test","name":"*testing-contexts*","file":"clojure/test.clj","type":"var","column":1,"see-alsos":null,"dynamic":true,"line":269,"examples":null,"notes":null,"arglists":[],"library-url":"https://github.com/clojure/clojure","href":"/clojure.test/*testing-contexts*"},{"added":"1.1","ns":"clojure.test","name":"test-ns","file":"clojure/test.clj","type":"function","column":1,"see-alsos":null,"line":743,"examples":[{"editors":[{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"}],"body":";; Executes all tests in a namespace. \n;; One possible use of test-ns-hook is to temporary run a single test\n;; without having to comment all others out\n\n(ns lot-of-tests)\n(require '[clojure.test :refer [is deftest]])\n\n(deftest fail-a (is (= 1 (+ 2 2))))\n(deftest fail-b (is (= 1 (+ 2 2))))\n(deftest fail-c (is (= 1 (+ 2 2))))\n\n(defn test-ns-hook [] (fail-a))\n\n(ns user)\n(require '[clojure.test :refer [test-ns]])\n\n(t/test-ns 'lot-of-tests)\n;; Testing lot-of-tests\n\n;; FAIL in (fail-a) (NO_SOURCE_FILE:1)\n;; expected: (= 1 (+ 2 2))\n;; actual: (not (= 1 4))\n;; {:test 1, :pass 0, :fail 1, :error 0}","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"},"created-at":1561721878563,"updated-at":1561721929000,"_id":"5d15fc16e4b0ca44402ef779"}],"notes":null,"arglists":["ns"],"doc":"If the namespace defines a function named test-ns-hook, calls that.\n Otherwise, calls test-all-vars on the namespace. 'ns' is a\n namespace object or a symbol.\n\n Internally binds *report-counters* to a ref initialized to\n *initial-report-counters*. Returns the final, dereferenced state of\n *report-counters*.","library-url":"https://github.com/clojure/clojure","href":"/clojure.test/test-ns"},{"added":"1.11","ns":"clojure.test","name":"run-test","file":"clojure/test.clj","type":"macro","column":1,"see-alsos":[{"created-at":1737372339467,"author":{"login":"victorb","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/459764?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"run-tests","ns":"clojure.test"},"_id":"678e32b3cd84df5de54e206e"},{"created-at":1737372343836,"author":{"login":"victorb","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/459764?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"run-test-var","ns":"clojure.test"},"_id":"678e32b7cd84df5de54e206f"}],"line":813,"examples":null,"macro":true,"notes":null,"arglists":["test-symbol"],"doc":"Runs a single test.\n\n Because the intent is to run a single test, there is no check for the namespace test-ns-hook.","library-url":"https://github.com/clojure/clojure","href":"/clojure.test/run-test"},{"added":"1.1","ns":"clojure.test","name":"run-tests","file":"clojure/test.clj","type":"function","column":1,"see-alsos":[{"created-at":1417800283222,"author":{"login":"fordsfords","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7671908?v=3"},"to-var":{"ns":"clojure.test","name":"run-all-tests","library-url":"https://github.com/clojure/clojure"},"_id":"5481ea5be4b03d20a10242c4"},{"created-at":1737372302320,"author":{"login":"victorb","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/459764?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"run-test","ns":"clojure.test"},"_id":"678e328ecd84df5de54e206a"},{"created-at":1737372313262,"author":{"login":"victorb","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/459764?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"run-test-var","ns":"clojure.test"},"_id":"678e3299cd84df5de54e206b"}],"line":768,"examples":[{"body":";; assuming current namespace is user\n(use 'clojure.test)\n(deftest eg-tests (is (= 1 1)))\n(run-tests)\n;;=> Testing user\n;;=> Ran 1 tests containing 1 assertions.\n;;=> 0 failures, 0 errors.\n;;=> {:type :summary, :fail 0, :error 0, :pass 1, :test 1}\n\n(run-tests 'user) ; if supplying a namespace to test, must quote\n;;=> Testing user\n;;=> Ran 1 tests containing 1 assertions.\n;;=> 0 failures, 0 errors.\n;;=> {:type :summary, :fail 0, :error 0, :pass 1, :test 1}","author":{"login":"fordsfords","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7671908?v=3"},"created-at":1417800300379,"updated-at":1417800300379,"_id":"5481ea6ce4b0dc573b892feb"}],"notes":null,"arglists":["","& namespaces"],"doc":"Runs all tests in the given namespaces; prints results.\n Defaults to current namespace if none given. Returns a map\n summarizing test results.","library-url":"https://github.com/clojure/clojure","href":"/clojure.test/run-tests"},{"ns":"clojure.test","name":"*testing-vars*","file":"clojure/test.clj","type":"var","column":1,"see-alsos":null,"dynamic":true,"line":267,"examples":null,"notes":null,"arglists":[],"library-url":"https://github.com/clojure/clojure","href":"/clojure.test/*testing-vars*"},{"ns":"clojure.test","name":"*test-out*","file":"clojure/test.clj","type":"var","column":1,"see-alsos":null,"dynamic":true,"line":271,"examples":null,"notes":null,"arglists":[],"library-url":"https://github.com/clojure/clojure","href":"/clojure.test/*test-out*"},{"ns":"clojure.test","name":"*initial-report-counters*","file":"clojure/test.clj","type":"var","column":1,"see-alsos":null,"dynamic":true,"line":264,"examples":null,"notes":null,"arglists":[],"library-url":"https://github.com/clojure/clojure","href":"/clojure.test/*initial-report-counters*"},{"ns":"clojure.test.junit","name":"junit-report","file":"clojure/test/junit.clj","type":"var","column":1,"see-alsos":null,"dynamic":true,"line":142,"examples":null,"notes":null,"arglists":[],"library-url":"https://github.com/clojure/clojure","href":"/clojure.test.junit/junit-report"},{"ns":"clojure.test.junit","name":"start-case","file":"clojure/test/junit.clj","type":"function","column":1,"see-alsos":null,"line":89,"examples":null,"notes":null,"arglists":["name classname"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.test.junit/start-case"},{"ns":"clojure.test.junit","name":"suite-attrs","file":"clojure/test/junit.clj","type":"function","column":1,"see-alsos":null,"line":97,"examples":null,"notes":null,"arglists":["package classname"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.test.junit/suite-attrs"},{"ns":"clojure.test.junit","name":"start-suite","file":"clojure/test/junit.clj","type":"function","column":1,"see-alsos":null,"line":104,"examples":null,"notes":null,"arglists":["name"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.test.junit/start-suite"},{"ns":"clojure.test.junit","name":"indent","file":"clojure/test/junit.clj","type":"function","column":1,"see-alsos":null,"line":51,"examples":null,"notes":null,"arglists":[""],"library-url":"https://github.com/clojure/clojure","href":"/clojure.test.junit/indent"},{"ns":"clojure.test.junit","name":"finish-suite","file":"clojure/test/junit.clj","type":"function","column":1,"see-alsos":null,"line":109,"examples":null,"notes":null,"arglists":[""],"library-url":"https://github.com/clojure/clojure","href":"/clojure.test.junit/finish-suite"},{"ns":"clojure.test.junit","name":"finish-element","file":"clojure/test/junit.clj","type":"function","column":1,"see-alsos":null,"line":70,"examples":null,"notes":null,"arglists":["tag pretty"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.test.junit/finish-element"},{"ns":"clojure.test.junit","name":"failure-el","file":"clojure/test/junit.clj","type":"function","column":1,"see-alsos":null,"line":128,"examples":null,"notes":null,"arglists":["message expected actual"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.test.junit/failure-el"},{"ns":"clojure.test.junit","name":"message-el","file":"clojure/test/junit.clj","type":"function","column":1,"see-alsos":null,"line":113,"examples":null,"notes":null,"arglists":["tag message expected-str actual-str"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.test.junit/message-el"},{"ns":"clojure.test.junit","name":"*depth*","file":"clojure/test/junit.clj","type":"var","column":1,"see-alsos":null,"dynamic":true,"line":49,"examples":null,"notes":null,"arglists":[],"library-url":"https://github.com/clojure/clojure","href":"/clojure.test.junit/*depth*"},{"ns":"clojure.test.junit","name":"*var-context*","file":"clojure/test/junit.clj","type":"var","column":1,"see-alsos":null,"dynamic":true,"line":48,"examples":null,"notes":null,"arglists":[],"library-url":"https://github.com/clojure/clojure","href":"/clojure.test.junit/*var-context*"},{"added":"1.1","ns":"clojure.test.junit","name":"with-junit-output","file":"clojure/test/junit.clj","type":"macro","column":1,"see-alsos":null,"line":182,"examples":null,"macro":true,"notes":null,"arglists":["& body"],"doc":"Execute body with modified test-is reporting functions that write\n JUnit-compatible XML output.","library-url":"https://github.com/clojure/clojure","href":"/clojure.test.junit/with-junit-output"},{"ns":"clojure.test.junit","name":"start-element","file":"clojure/test/junit.clj","type":"function","column":1,"see-alsos":null,"line":55,"examples":null,"notes":null,"arglists":["tag pretty & [attrs]"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.test.junit/start-element"},{"ns":"clojure.test.junit","name":"package-class","file":"clojure/test/junit.clj","type":"function","column":1,"see-alsos":null,"line":82,"examples":null,"notes":null,"arglists":["name"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.test.junit/package-class"},{"ns":"clojure.test.junit","name":"element-content","file":"clojure/test/junit.clj","type":"function","column":1,"see-alsos":null,"line":66,"examples":null,"notes":null,"arglists":["content"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.test.junit/element-content"},{"ns":"clojure.test.junit","name":"finish-case","file":"clojure/test/junit.clj","type":"function","column":1,"see-alsos":null,"line":93,"examples":null,"notes":null,"arglists":[""],"library-url":"https://github.com/clojure/clojure","href":"/clojure.test.junit/finish-case"},{"ns":"clojure.test.junit","name":"error-el","file":"clojure/test/junit.clj","type":"function","column":1,"see-alsos":null,"line":132,"examples":null,"notes":null,"arglists":["message expected actual"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.test.junit/error-el"},{"ns":"clojure.test.junit","name":"test-name","file":"clojure/test/junit.clj","type":"function","column":1,"see-alsos":null,"line":77,"examples":null,"notes":null,"arglists":["vars"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.test.junit/test-name"},{"added":"1.1","ns":"clojure.test.tap","name":"print-tap-fail","file":"clojure/test/tap.clj","type":"function","column":1,"see-alsos":[{"created-at":1617958686413,"author":{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1334295?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"print-tap-pass","ns":"clojure.test.tap"},"_id":"6070171ee4b0b1e3652d74bb"}],"line":65,"examples":null,"notes":null,"arglists":["msg"],"doc":"Prints a TAP 'not ok' line. msg is a string, with no line breaks","library-url":"https://github.com/clojure/clojure","href":"/clojure.test.tap/print-tap-fail"},{"added":"1.1","ns":"clojure.test.tap","name":"print-tap-pass","file":"clojure/test/tap.clj","type":"function","column":1,"see-alsos":[{"created-at":1617958703255,"author":{"login":"bfontaine","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1334295?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"print-tap-fail","ns":"clojure.test.tap"},"_id":"6070172fe4b0b1e3652d74bc"}],"line":59,"examples":null,"notes":null,"arglists":["msg"],"doc":"Prints a TAP 'ok' line. msg is a string, with no line breaks","library-url":"https://github.com/clojure/clojure","href":"/clojure.test.tap/print-tap-pass"},{"ns":"clojure.test.tap","name":"print-diagnostics","file":"clojure/test/tap.clj","type":"function","column":1,"see-alsos":null,"line":78,"examples":null,"notes":null,"arglists":["data"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.test.tap/print-diagnostics"},{"added":"1.1","ns":"clojure.test.tap","name":"print-tap-plan","file":"clojure/test/tap.clj","type":"function","column":1,"see-alsos":null,"line":45,"examples":null,"notes":null,"arglists":["n"],"doc":"Prints a TAP plan line like '1..n'. n is the number of tests","library-url":"https://github.com/clojure/clojure","href":"/clojure.test.tap/print-tap-plan"},{"added":"1.1","ns":"clojure.test.tap","name":"with-tap-output","file":"clojure/test/tap.clj","type":"macro","column":1,"see-alsos":null,"line":117,"examples":null,"macro":true,"notes":null,"arglists":["& body"],"doc":"Execute body with modified test reporting functions that produce\n TAP output","library-url":"https://github.com/clojure/clojure","href":"/clojure.test.tap/with-tap-output"},{"ns":"clojure.test.tap","name":"tap-report","file":"clojure/test/tap.clj","type":"var","column":1,"see-alsos":null,"dynamic":true,"line":72,"examples":null,"notes":null,"arglists":[],"library-url":"https://github.com/clojure/clojure","href":"/clojure.test.tap/tap-report"},{"added":"1.1","ns":"clojure.test.tap","name":"print-tap-diagnostic","file":"clojure/test/tap.clj","type":"function","column":1,"see-alsos":null,"line":51,"examples":null,"notes":null,"arglists":["data"],"doc":"Prints a TAP diagnostic line. data is a (possibly multi-line)\n string.","library-url":"https://github.com/clojure/clojure","href":"/clojure.test.tap/print-tap-diagnostic"},{"ns":"clojure.tools.build.api","name":"copy-dir","file":"clojure/tools/build/api.clj","type":"function","column":1,"see-alsos":[{"created-at":1772205697616,"author":{"login":"lambduhh","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/47534185?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"copy-file","ns":"clojure.tools.build.api"},"_id":"69a1b68178d10e32f3bf6b9e"},{"created-at":1772205775987,"author":{"login":"lambduhh","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/47534185?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"delete","ns":"clojure.tools.build.api"},"_id":"69a1b6cf78d10e32f3bf6b9f"},{"created-at":1772205798331,"author":{"login":"lambduhh","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/47534185?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"write-pom","ns":"clojure.tools.build.api"},"_id":"69a1b6e678d10e32f3bf6ba0"},{"created-at":1772205820824,"author":{"login":"lambduhh","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/47534185?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"jar","ns":"clojure.tools.build.api"},"_id":"69a1b6fc78d10e32f3bf6ba1"}],"line":109,"examples":[{"updated-at":1772205607078,"created-at":1772205607078,"author":{"login":"lambduhh","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/47534185?v=4"},"body":";; Copy source and resources to a class directory for jar packaging\n(require '[clojure.tools.build.api :as b])\n\n(b/copy-dir {:src-dirs [\"src\" \"resources\"]\n :target-dir \"target/classes\"})\n\n;; With text replacement (e.g., injecting version at build time)\n(b/copy-dir {:src-dirs [\"src\" \"resources\"]\n :target-dir \"target/classes\"\n :replace {\"{{version}}\" \"1.2.3\"}})\n\n;; Selectively copy only .clj files\n(b/copy-dir {:src-dirs [\"src\"]\n :target-dir \"target/classes\"\n :include \"**/*.clj\"})","_id":"69a1b62778d10e32f3bf6b9d"},{"updated-at":1772206952354,"created-at":1772206623526,"author":{"login":"lambduhh","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/47534185?v=4"},"body":"Real-world `build.clj` examples using `copy-dir`:\n\n- **Sean Corfield's honeysql** — Uses `copy-dir` in a minimal library jar pipeline\n (`delete` → `copy-dir` → `write-pom` → `jar`). \nA clean, canonical example of the standard pattern.\nhttps://github.com/seancorfield/honeysql/blob/develop/build.clj\n\n- **Sean Corfield's usermanager-example** — Uses `copy-dir` in both jar and uber\n builds, showing how the same copy step serves different packaging targets. \nAlso demonstrates a CI-oriented build with `compile-clj` before `uber`.\nhttps://github.com/seancorfield/usermanager-example/blob/develop/build.clj\n\n- **Practicalli's clojure-app-template** — Uses `copy-dir` in jar and uberjar \nfunctions, with added safety checks on `delete` \n(guards against deleting `\".\"` or `\"/\"`). \nA good reference for production-ready build scripts.\nhttps://github.com/practicalli/clojure-app-template/blob/main/build.clj","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/47534185?v=4","account-source":"github","login":"lambduhh"}],"_id":"69a1ba1f78d10e32f3bf6ba2"}],"notes":null,"arglists":["params"],"doc":"Copy the contents of the src-dirs to the target-dir, optionally do text replacement.\n Returns nil.\n\n Globs are wildcard patterns for specifying sets of files in a directory\n tree, as specified in the glob syntax of java.nio.file.FileSystem:\n https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/nio/file/FileSystem.html#getPathMatcher(java.lang.String)\n\n Options:\n :target-dir - required, dir to write files, will be created if it doesn't exist\n :src-dirs - required, coll of dirs to copy from\n :include - glob of files to include, default = \"**\"\n :ignores - collection of ignore regex patterns (applied only to file names),\n see clojure.tools.build.tasks.copy/default-ignores for defaults\n :replace - map of source to replacement string in files\n :non-replaced-exts - coll of extensions to skip when replacing (still copied)\n default = [\"jpg\" \"jpeg\" \"png\" \"gif\" \"bmp\"]","library-url":"https://github.com/clojure/clojure","href":"/clojure.tools.build.api/copy-dir"},{"ns":"clojure.tools.build.api","name":"git-count-revs","file":"clojure/tools/build/api.clj","type":"function","column":1,"see-alsos":null,"line":256,"examples":null,"notes":null,"arglists":["{:keys [dir git-command path], :or {git-command \"git\"}, :as params}"],"doc":"Shells out to git and returns count of commits on this branch:\n git rev-list HEAD --count\n\n Options:\n :dir - dir to invoke this command from, default = current directory\n :git-command - git command to use, default = \"git\"\n :path - path to count commits for relative to dir","library-url":"https://github.com/clojure/clojure","href":"/clojure.tools.build.api/git-count-revs"},{"ns":"clojure.tools.build.api","name":"pom-path","file":"clojure/tools/build/api.clj","type":"function","column":1,"see-alsos":null,"line":336,"examples":null,"notes":null,"arglists":["params"],"doc":"Calculate path to pom.xml in jar meta (same path used by write-pom).\n Relative path in jar is:\n META-INF/maven///pom.xml\n\n If :class-dir provided, return path will start with resolved class-dir\n (which may be either absolute or relative), otherwise just relative\n path in jar.\n\n Options:\n :lib - required, used to form the relative path in jar to pom.xml\n :class-dir - optional, if provided will be resolved and form the root of the path","library-url":"https://github.com/clojure/clojure","href":"/clojure.tools.build.api/pom-path"},{"ns":"clojure.tools.build.api","name":"install","file":"clojure/tools/build/api.clj","type":"function","column":1,"see-alsos":null,"line":515,"examples":null,"notes":null,"arglists":["params"],"doc":"Install pom and jar to local Maven repo.\n Returns nil.\n\n Options:\n :basis - required, used for :mvn/local-repo\n :lib - required, lib symbol\n :classifier - classifier string, if needed\n :version - required, string version\n :jar-file - required, path to jar file\n :class-dir - required, used to find the pom file","library-url":"https://github.com/clojure/clojure","href":"/clojure.tools.build.api/install"},{"ns":"clojure.tools.build.api","name":"jar","file":"clojure/tools/build/api.clj","type":"function","column":1,"see-alsos":[{"created-at":1772209677062,"author":{"login":"lambduhh","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/47534185?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"uber","ns":"clojure.tools.build.api"},"_id":"69a1c60d78d10e32f3bf6bb0"},{"created-at":1772209693320,"author":{"login":"lambduhh","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/47534185?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"compile-clj","ns":"clojure.tools.build.api"},"_id":"69a1c61d78d10e32f3bf6bb1"},{"created-at":1772209700960,"author":{"login":"lambduhh","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/47534185?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"create-basis","ns":"clojure.tools.build.api"},"_id":"69a1c62478d10e32f3bf6bb2"},{"created-at":1772209716575,"author":{"login":"lambduhh","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/47534185?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"delete","ns":"clojure.tools.build.api"},"_id":"69a1c63478d10e32f3bf6bb3"}],"line":397,"examples":[{"updated-at":1772209653058,"created-at":1772209653058,"author":{"login":"lambduhh","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/47534185?v=4"},"body":"(require '[clojure.tools.build.api :as b])\n\n;; Build a library jar from a class directory\n;; (assumes sources have already been copied to class-dir)\n(b/jar {:class-dir \"target/classes\"\n :jar-file \"target/my-lib-1.0.0.jar\"})\n;;=> nil\n\n;; Full library jar pipeline — the standard pattern\n(def basis (b/create-basis))\n(def class-dir \"target/classes\")\n(def jar-file \"target/my-lib-1.0.0.jar\")\n\n(defn jar [_]\n (b/delete {:path \"target\"})\n (b/copy-dir {:src-dirs [\"src\" \"resources\"]\n :target-dir class-dir})\n (b/write-pom {:class-dir class-dir\n :lib 'com.example/my-lib\n :version \"1.0.0\"\n :basis basis})\n (b/jar {:class-dir class-dir\n :jar-file jar-file}))\n\n;; Specify a main class in the manifest (less common for libraries)\n(b/jar {:class-dir class-dir\n :jar-file jar-file\n :main 'com.example.main})","_id":"69a1c5f578d10e32f3bf6baf"},{"editors":[{"login":"lambduhh","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/47534185?v=4"}],"body":"Real-world references:\n\nSean Corfield's usermanager-example — Full CI-oriented uber build with compile-clj\n before uber, showing the application uberjar pattern.\nhttps://github.com/seancorfield/usermanager-example/blob/develop/build.clj\n\nPracticalli's clojure-app-template — Uberjar function with compile-clj and \nsafety-guarded clean, demonstrating a production-ready application build.\nhttps://github.com/practicalli/clojure-app-template/blob/main/build.clj\n\nOfficial tools.build guide — Application uberjar walkthrough showing \nthe full [delete → copy-dir → compile-clj → uber] pipeline.\nhttps://clojure.org/guides/tools_build","author":{"avatar-url":"https://avatars.githubusercontent.com/u/47534185?v=4","account-source":"github","login":"lambduhh"},"created-at":1772209749177,"updated-at":1772209812479,"_id":"69a1c65578d10e32f3bf6bb4"}],"notes":null,"arglists":["params"],"doc":"Create jar file containing contents of class-dir. Use main in the manifest\n if provided. Returns nil.\n\n Options:\n :class-dir - required, dir to include in jar\n :jar-file - required, jar to write\n :main - main class symbol\n :manifest - map of manifest attributes, merged last over defaults+:main","library-url":"https://github.com/clojure/clojure","href":"/clojure.tools.build.api/jar"},{"ns":"clojure.tools.build.api","name":"compile-clj","file":"clojure/tools/build/api.clj","type":"function","column":1,"see-alsos":null,"line":277,"examples":null,"notes":null,"arglists":["params"],"doc":"Compile Clojure source to classes in :class-dir.\n\n Clojure source files are found in :basis paths by default, else in :src-dirs.\n\n Namespaces and order of compilation are one of:\n * :ns-compile - compile these namespaces, in this order\n * :sort - find all namespaces in source dirs and use either :topo (default)\n or :bfs to order them for compilation\n\n Options:\n :basis - required, basis to use when compiling\n :class-dir - required, dir to write classes, will be created if needed\n :src-dirs - coll of Clojure source dirs, used to find all Clojure nses to compile\n :ns-compile - coll of specific namespace symbols to compile\n :sort - :topo (default) or :bfs for breadth-first search\n :compile-opts - map of Clojure compiler options:\n {:disable-locals-clearing false\n :elide-meta [:doc :file :line ...]\n :direct-linking false}\n :bindings - map of Var to value to be set during compilation, for example:\n {#'clojure.core/*assert* false}\n :filter-nses - coll of symbols representing a namespace prefix to include\n\n Additional options flow to the forked process doing the compile:\n :java-cmd - Java command, default = $JAVA_CMD or 'java' on $PATH, or $JAVA_HOME/bin/java\n :java-opts - coll of string jvm opts\n :use-cp-file - one of:\n :auto (default) - use only if os=windows && Java >= 9 && command length >= 8k\n :always - always write classpath to temp file and include\n :never - never write classpath to temp file (pass on command line)\n\n Returns nil.","library-url":"https://github.com/clojure/clojure","href":"/clojure.tools.build.api/compile-clj"},{"ns":"clojure.tools.build.api","name":"*project-root*","file":"clojure/tools/build/api.clj","type":"var","column":1,"see-alsos":null,"dynamic":true,"line":16,"examples":null,"notes":null,"arglists":[],"doc":"Project root path, defaults to current directory.\n Use `resolve-path` to resolve relative paths in terms of the *project-root*.\n Use `set-project-root!` to override the default for all tasks.","library-url":"https://github.com/clojure/clojure","href":"/clojure.tools.build.api/*project-root*"},{"ns":"clojure.tools.build.api","name":"write-file","file":"clojure/tools/build/api.clj","type":"function","column":1,"see-alsos":null,"line":89,"examples":null,"notes":null,"arglists":["{:keys [path content string opts], :as params}"],"doc":"Writes a file at path, will create parent dirs if needed. Returns nil.\n File contents may be specified either with :content (for data, that\n will be pr-str'ed) or with :string for the string to write. If\n neither is specified, an empty file is created (like touch).\n\n Options:\n :path - required, file path\n :content - val to write, will pr-str\n :string - string to write\n :opts - coll of writer opts like :append and :encoding (per clojure.java.io)","library-url":"https://github.com/clojure/clojure","href":"/clojure.tools.build.api/write-file"},{"ns":"clojure.tools.build.api","name":"resolve-path","file":"clojure/tools/build/api.clj","type":"function","column":1,"see-alsos":null,"line":32,"examples":null,"notes":null,"arglists":["path"],"doc":"If path is absolute or root-path is nil then return path,\n otherwise resolve relative to *project-root*.","library-url":"https://github.com/clojure/clojure","href":"/clojure.tools.build.api/resolve-path"},{"ns":"clojure.tools.build.api","name":"javac","file":"clojure/tools/build/api.clj","type":"function","column":1,"see-alsos":null,"line":319,"examples":null,"notes":null,"arglists":["params"],"doc":"Compile Java source to classes. Returns nil.\n\n Options:\n :src-dirs - required, coll of Java source dirs\n :class-dir - required, dir to write classes, will be created if needed\n :basis - classpath basis to use when compiling\n :javac-opts - coll of string opts, like [\"-source\" \"8\" \"-target\" \"8\"]","library-url":"https://github.com/clojure/clojure","href":"/clojure.tools.build.api/javac"},{"ns":"clojure.tools.build.api","name":"process","file":"clojure/tools/build/api.clj","type":"function","column":1,"see-alsos":null,"line":190,"examples":null,"notes":null,"arglists":["params"],"doc":"Exec the command made from command-args, redirect out and err as directed,\n and return {:exit exit-code, :out captured-out, :err captured-err}.\n\n Options:\n :command-args - required, coll of string args\n :dir - directory to run the command from, default *project-root*\n :out - one of :inherit :capture :write :append :ignore\n :err - one of :inherit :capture :write :append :ignore\n :out-file - file path to write if :out is :write or :append\n :err-file - file path to write if :err is :write or :append\n :env - map of environment variables to set\n\n The :out and :err input flags take one of the following options:\n :inherit - inherit the stream and write the subprocess io to this process's stream (default)\n :capture - capture the stream to a string and return it\n :write - write to :out-file or :err-file\n :append - append to :out-file or :err-file\n :ignore - ignore the stream","library-url":"https://github.com/clojure/clojure","href":"/clojure.tools.build.api/process"},{"ns":"clojure.tools.build.api","name":"with-project-root","file":"clojure/tools/build/api.clj","type":"macro","column":1,"see-alsos":null,"line":27,"examples":null,"macro":true,"notes":null,"arglists":["path & forms"],"doc":"Execute forms in a bound project path (string) other than the default (\".\")","library-url":"https://github.com/clojure/clojure","href":"/clojure.tools.build.api/with-project-root"},{"ns":"clojure.tools.build.api","name":"git-process","file":"clojure/tools/build/api.clj","type":"function","column":1,"see-alsos":null,"line":219,"examples":null,"notes":null,"arglists":["params"],"doc":"Run git process in the specified dir using git-command with git-args (which should not\n start with \"git\"). git-args may either be a string (split on whitespace) or a vector\n of strings. By default, stdout is captured, trimmed, and returned.\n\n Options:\n :dir - dir to invoke this command from, default = current directory\n :git-command - git command to use, default = \"git\"\n :git-args - required, coll of git-arg strings forming a command line OR\n a string (do not use if args may have embedded spaces)\n :capture - :out (default) or :err, else nothing\n\n Examples:\n (api/git-process {:git-args \"rev-list HEAD --count\"})\n (api/git-process {:git-args \"branch --show-current\"})\n (api/git-process {:git-args \"rev-parse --short HEAD\"})\n (api/git-process {:git-args \"push\", :capture nil})","library-url":"https://github.com/clojure/clojure","href":"/clojure.tools.build.api/git-process"},{"ns":"clojure.tools.build.api","name":"delete","file":"clojure/tools/build/api.clj","type":"function","column":1,"see-alsos":[{"created-at":1772209243597,"author":{"login":"lambduhh","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/47534185?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"copy-dir","ns":"clojure.tools.build.api"},"_id":"69a1c45b78d10e32f3bf6ba8"},{"created-at":1772209253710,"author":{"login":"lambduhh","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/47534185?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"copy-file","ns":"clojure.tools.build.api"},"_id":"69a1c46578d10e32f3bf6ba9"}],"line":62,"examples":[{"updated-at":1772209206284,"created-at":1772209206284,"author":{"login":"lambduhh","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/47534185?v=4"},"body":"(require '[clojure.tools.build.api :as b])\n\n;; Delete the target directory and all its contents recursively\n(b/delete {:path \"target\"})\n;;=> nil\n\n;; If the path doesn't exist, delete is a no-op — no error thrown\n(b/delete {:path \"nonexistent-dir\"})\n;;=> nil\n\n;; The most common pattern: a clean function in build.clj\n(defn clean [_]\n (b/delete {:path \"target\"}))","_id":"69a1c43678d10e32f3bf6ba7"}],"notes":null,"arglists":["{:keys [path], :as params}"],"doc":"Delete file or directory recursively, if it exists. Returns nil.\n\n Options:\n :path - required, path to file or directory","library-url":"https://github.com/clojure/clojure","href":"/clojure.tools.build.api/delete"},{"ns":"clojure.tools.build.api","name":"create-basis","file":"clojure/tools/build/api.clj","type":"function","column":1,"see-alsos":[{"created-at":1772209512963,"author":{"login":"lambduhh","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/47534185?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"jar","ns":"clojure.tools.build.api"},"_id":"69a1c56878d10e32f3bf6bab"},{"created-at":1772209520860,"author":{"login":"lambduhh","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/47534185?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"uber","ns":"clojure.tools.build.api"},"_id":"69a1c57078d10e32f3bf6bac"},{"created-at":1772209546179,"author":{"login":"lambduhh","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/47534185?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"compile-clj","ns":"clojure.tools.build.api"},"_id":"69a1c58a78d10e32f3bf6bad"},{"created-at":1772209557583,"author":{"login":"lambduhh","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/47534185?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"write-pom","ns":"clojure.tools.build.api"},"_id":"69a1c59578d10e32f3bf6bae"}],"line":135,"examples":[{"updated-at":1772209491524,"created-at":1772209491524,"author":{"login":"lambduhh","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/47534185?v=4"},"body":"(require '[clojure.tools.build.api :as b])\n\n;; Create a basis from the project's deps.edn (default behavior).\n;; This is equivalent to the classpath you get from `clj` with no aliases.\n(def basis (b/create-basis))\n\n;; The returned basis map contains resolved libs and classpath info\n(keys basis)\n;;=> (:libs :classpath :classpath-roots :resolve-args :classpath-args ...)\n\n;; Create a basis with specific aliases applied\n(def test-basis (b/create-basis {:aliases [:test]}))\n\n;; A typical build.clj pattern: define basis once, use across tasks\n(def basis (b/create-basis {:project \"deps.edn\"}))\n\n(defn jar [_]\n (b/write-pom {:class-dir \"target/classes\"\n :lib 'my/lib\n :version \"1.0.0\"\n :basis basis})\n (b/copy-dir {:src-dirs [\"src\"] :target-dir \"target/classes\"})\n (b/jar {:class-dir \"target/classes\"\n :jar-file \"target/my-lib.jar\"}))\n\n\nReal-world links:\n\nSean Corfield's honeysql — Defines basis at the top level and reuses it across jar and install tasks.\nhttps://github.com/seancorfield/honeysql/blob/develop/build.clj\n\nOfficial tools.build guide — Shows create-basis in both library and application build examples, including alias usage.\nhttps://clojure.org/guides/tools_build","_id":"69a1c55378d10e32f3bf6baa"}],"notes":null,"arglists":["","params"],"doc":"Create a basis from a set of deps sources and a set of aliases. By default, use\n root, user, and project deps and no aliases (essentially the same classpath you\n get by default from the Clojure CLI).\n\n Each dep source value can be :standard, a string path, a deps edn map, or nil.\n Sources are merged in the order - :root, :user, :project, :extra.\n\n Options (note, paths resolved via *project-root*):\n :root - dep source, default = :standard\n :user - dep source, default = nil (for reproducibility, not included)\n :project - dep source, default = :standard (\"./deps.edn\")\n :extra - dep source, default = nil\n :aliases - coll of aliases of argmaps to apply to subprocesses\n\n Returns a runtime basis, which is the initial merged deps edn map plus these keys:\n :resolve-args - the resolve args passed in, if any\n :classpath-args - the classpath args passed in, if any\n :libs - lib map, per resolve-deps\n :classpath - classpath map per make-classpath-map\n :classpath-roots - vector of paths in classpath order","library-url":"https://github.com/clojure/clojure","href":"/clojure.tools.build.api/create-basis"},{"ns":"clojure.tools.build.api","name":"java-command","file":"clojure/tools/build/api.clj","type":"function","column":1,"see-alsos":null,"line":163,"examples":null,"notes":null,"arglists":["params"],"doc":"Create Java command line args. The classpath will be the combination of\n :cp followed by the classpath from the basis, both are optional.\n\n Note that 'java-command' will NOT resolve any relative paths from basis\n or cp in terms of *project-root*, you will get a classpath with the same\n relative paths. 'process' (if run with this output), will run in the\n context of the *project-root* directory.\n\n Options:\n :java-cmd - Java command, default = $JAVA_CMD or 'java' on $PATH, or $JAVA_HOME/bin/java\n :cp - coll of string classpath entries, used first (if provided)\n :basis - runtime basis used for classpath, used last (if provided)\n :java-opts - coll of string jvm opts\n :main - required, main class symbol\n :main-args - coll of main class args\n :use-cp-file - one of:\n :auto (default) - use only if os=windows && Java >= 9 && command length >= 8k\n :always - always write classpath to temp file and include\n :never - never write classpath to temp file (pass on command line)\n\n Returns map suitable for passing to 'process' with keys:\n :command-args - coll of command arg strings","library-url":"https://github.com/clojure/clojure","href":"/clojure.tools.build.api/java-command"},{"ns":"clojure.tools.build.api","name":"copy-file","file":"clojure/tools/build/api.clj","type":"function","column":1,"see-alsos":null,"line":75,"examples":null,"notes":null,"arglists":["{:keys [src target], :as params}"],"doc":"Copy one file from source to target, creating target dirs if needed.\n Returns nil.\n\n Options:\n :src - required, source path\n :target - required, target path","library-url":"https://github.com/clojure/clojure","href":"/clojure.tools.build.api/copy-file"},{"ns":"clojure.tools.build.api","name":"unzip","file":"clojure/tools/build/api.clj","type":"function","column":1,"see-alsos":null,"line":500,"examples":null,"notes":null,"arglists":["params"],"doc":"Unzip zip file to target-dir. Returns nil.\n\n Options:\n :zip-file - required, zip file to unzip\n :target-dir - required, directory to unzip in","library-url":"https://github.com/clojure/clojure","href":"/clojure.tools.build.api/unzip"},{"ns":"clojure.tools.build.api","name":"zip","file":"clojure/tools/build/api.clj","type":"function","column":1,"see-alsos":null,"line":487,"examples":null,"notes":null,"arglists":["params"],"doc":"Create zip file containing contents of src dirs. Returns nil.\n\n Options:\n :src-dirs - required, coll of source directories to include in zip\n :zip-file - required, zip file to create","library-url":"https://github.com/clojure/clojure","href":"/clojure.tools.build.api/zip"},{"ns":"clojure.tools.build.api","name":"set-project-root!","file":"clojure/tools/build/api.clj","type":"function","column":1,"see-alsos":null,"line":22,"examples":null,"notes":null,"arglists":["root"],"doc":"Set *project-root* dir (default is \".\")","library-url":"https://github.com/clojure/clojure","href":"/clojure.tools.build.api/set-project-root!"},{"ns":"clojure.tools.build.api","name":"write-pom","file":"clojure/tools/build/api.clj","type":"function","column":1,"see-alsos":null,"line":360,"examples":null,"notes":null,"arglists":["params"],"doc":"Write pom.xml and pom.properties files to the class dir under\n META-INF/maven/group-id/artifact-id/ (where Maven typically writes\n these files), or to target (exactly one of :class-dir and :target must\n be provided). The pom deps, dirs, and repos are either synced from\n the src-pom or generated from the basis.\n\n If a repos map is provided it supersedes the repos in the basis.\n\n Returns nil.\n\n Options:\n :basis - required, used to pull deps, repos\n :src-pom - source pom.xml to synchronize from, default = \"./pom.xml\"\n :class-dir - root dir for writing pom files, created if needed\n :target - file path to write pom if no :class-dir specified\n :lib - required, project lib symbol\n :version - required, project version\n :scm - map of scm properties to write in pom\n keys: :connection, :developerConnection, :tag, :url\n See: https://maven.apache.org/pom.html#SCM for details\n :src-dirs - coll of src dirs\n :resource-dirs - coll of resource dirs\n :repos - map of repo name to repo config, replaces repos from deps.edn","library-url":"https://github.com/clojure/clojure","href":"/clojure.tools.build.api/write-pom"},{"ns":"clojure.tools.build.api","name":"uber","file":"clojure/tools/build/api.clj","type":"function","column":1,"see-alsos":null,"line":413,"examples":null,"notes":null,"arglists":["params"],"doc":"Create uberjar file. An uberjar is a self-contained jar file containing\n both the project contents AND the contents of all dependencies.\n\n The project contents are represented by the class-dir. Use other tasks to\n put Clojure source, class files, a pom file, or other resources in the\n class-dir. In particular, see the copy-dir, write-pom, compile-clj, and\n javac tasks.\n\n The dependencies are pulled from the basis. All transitive deps will be\n included. Dependency jars are expanded for inclusion in the uberjar.\n Use :exclude to exclude specific paths from the expanded deps. Use\n conflict-handlers to handle conflicts that may occur if two dependency\n jar files include a file at the same path. See below for more detail.\n\n If a main class or manifest are provided, those are put in the uberjar\n META-INF/MANIFEST.MF file. Providing a main allows the jar to be\n invoked with java -jar.\n\n Returns nil.\n\n Options:\n :uber-file - required, uber jar file to create\n :class-dir - required, local class dir to include\n :basis - used to pull dep jars\n :main - main class symbol\n :manifest - map of manifest attributes, merged last over defaults + :main\n :exclude - coll of string patterns (regex) to exclude from deps\n :conflict-handlers - map of string pattern (regex) to built-in handlers,\n symbols to eval, or function instances\n\n When combining jar files into an uber jar, multiple jars may contain a file\n at the same path. The conflict handlers are a map of string regex pattern\n to:\n a keyword (to use a built-in handler) or\n a symbol (to resolve and invoke) or\n a function instance\n The special key `:default` specifies the default behavior if not matched.\n\n Conflict handler signature (fn [params]) => effect-map:\n params:\n :path - String, path in uber jar, matched by regex\n :in - InputStream to incoming file (see stream->string if needed)\n :existing - File, existing File at path\n :lib - symbol, lib source for incoming conflict\n :state - map, available for retaining state during uberjar process\n\n Handler should return effect-map with optional keys:\n :state - updated state map\n :write - map of string path to map of :string (string) or\n :stream (InputStream) to write and optional :append\n flag. Omit if no files to write.\n\n Available built-in conflict handlers:\n :ignore - don't do anything (default)\n :overwrite - overwrite (replaces prior file)\n :append - append the file with a blank line separator\n :append-dedupe - append the file but dedupe appended sections\n :data-readers - merge data_readers.clj\n :warn - print a warning\n :error - throw an error\n\n Default conflict handlers map:\n {\"^data_readers.clj[c]?$\" :data-readers\n \"^META-INF/services/.*\" :append\n \"(?i)^(META-INF/)?(COPYRIGHT|NOTICE|LICENSE)(\\\\.(txt|md))?$\" :append-dedupe\n :default :ignore}","library-url":"https://github.com/clojure/clojure","href":"/clojure.tools.build.api/uber"},{"added":"1.12","ns":"clojure.tools.deps.interop","name":"invoke-tool","file":"clojure/tools/deps/interop.clj","type":"function","column":1,"see-alsos":null,"dynamic":true,"line":41,"examples":null,"notes":null,"arglists":["{:keys [tool-name tool-alias fn args preserve-envelope], :or {preserve-envelope false}, :as opts}"],"doc":"Invoke tool using Clojure CLI. Args (one of :tool-alias or :tool-name, and :fn\n are required):\n :tool-alias - Tool alias to invoke (keyword)\n :tool-name - Name of installed tool to invoke (string or symbol)\n :fn - Function (symbol)\n :args - map of args to pass to function\n\n Options:\n :preserve-envelope - if true, return the full invocation envelope, default=false","library-url":"https://github.com/clojure/clojure","href":"/clojure.tools.deps.interop/invoke-tool"},{"added":"1.1","ns":"clojure.walk","name":"postwalk","file":"clojure/walk.clj","type":"function","column":1,"see-alsos":[{"created-at":1321428795000,"author":{"login":"srid","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bd3a68d670372cd09876c26270a4299a?r=PG&default=identicon"},"to-var":{"ns":"clojure.walk","name":"prewalk","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521db9"},{"created-at":1348453793000,"author":{"login":"dansalmo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e33ee460f5f61bc5ba9b598934766215?r=PG&default=identicon"},"to-var":{"ns":"clojure.walk","name":"postwalk-demo","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521dba"},{"created-at":1348453807000,"author":{"login":"dansalmo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e33ee460f5f61bc5ba9b598934766215?r=PG&default=identicon"},"to-var":{"ns":"clojure.walk","name":"postwalk-replace","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521dbb"}],"line":53,"examples":[{"author":{"login":"sunil.nandihalli","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3b7fcae9384271fb8ca8cd0c612bebf3?r=PG&default=identicon"},"editors":[{"avatar-url":"https://avatars0.githubusercontent.com/u/382011?v=4","account-source":"github","login":"bolasblack"}],"body":"(require '[clojure.walk :refer [postwalk]])\n(let [counter (atom -1)\n line-counter (atom 0)\n print-touch (fn [x]\n (print (swap! line-counter inc) \":\" (pr-str x) \"→ \"))\n change (fn [x]\n (let [new-x (swap! counter inc)]\n (prn new-x)\n [new-x x]))]\n (postwalk (fn [x]\n (print-touch x)\n (change x))\n {:a 1 :b 2}))\n\n;; printed output:\n\n1 : :a → 0\n2 : 1 → 1\n3 : [[0 :a] [1 1]] → 2\n4 : :b → 3\n5 : 2 → 4\n6 : [[3 :b] [4 2]] → 5\n7 : {2 [[0 :a] [1 1]], 5 [[3 :b] [4 2]]} → 6\n\n;; returned value:\n\n[6 {2 [[0 :a] [1 1]], 5 [[3 :b] [4 2]]}]","created-at":1287073344000,"updated-at":1521646144691,"_id":"542692d1c026201cdc326f2b"},{"updated-at":1672398839535,"created-at":1359706452000,"body":";;example of removing namespaces from all keys in a nested data structure\n(def thing {:page/tags [{:tag/category \"lslsls\"}]})\n(postwalk #(if (keyword? %) (keyword (name %)) %) thing)\n{:tags [{:category \"lslsls\"}]}","editors":[{"avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon","account-source":"clojuredocs","login":"boxie"},{"login":"daveliepmann","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/974443?v=4"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon","account-source":"clojuredocs","login":"boxie"},"_id":"542692d7c026201cdc327122"},{"updated-at":1491425591876,"created-at":1491425591876,"author":{"login":"wmatson","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/3883798?v=3"},"body":"(use 'clojure.walk)\n\n;;example of evaluating an expression tree, starting at the leaves\n(def expression-tree\n {:function +\n :children\n [1 {:function *\n :children [2 6]}]})\n\n(defn evaluate [node]\n (if-let [f (:function node)]\n (apply f (:children node))\n node))\n\n(postwalk evaluate expression-tree)\n\n=> 13","_id":"58e55937e4b01f4add58fe83"},{"editors":[{"login":"cljlc","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/36645452?v=4"}],"body":";; an example to show the differences between postwalk and prewalk\n;; (see the counterpart at prewalk)\n\n(let [counter (atom 0)\n print-touch (fn [x]\n (print (swap! counter inc) \":\" (pr-str x) \"→ \"))\n change-type (fn [x]\n (let [new-x (if (vector? x)\n (apply list x)\n (str x))]\n (prn new-x)\n new-x))]\n (clojure.walk/postwalk (fn [x]\n (print-touch x)\n (change-type x))\n [:a [:ba :bb] :c]))\n\n;; printed output:\n\n1 : :a → \":a\"\n2 : :ba → \":ba\"\n3 : :bb → \":bb\"\n4 : [\":ba\" \":bb\"] → (\":ba\" \":bb\")\n5 : :c → \":c\"\n6 : [\":a\" (\":ba\" \":bb\") \":c\"] → (\":a\" (\":ba\" \":bb\") \":c\")\n\n;; returned value:\n\n=> (\":a\" (\":ba\" \":bb\") \":c\")","author":{"avatar-url":"https://avatars0.githubusercontent.com/u/36645452?v=4","account-source":"github","login":"cljlc"},"created-at":1519076695677,"updated-at":1519084470249,"_id":"5a8b4557e4b0316c0f44f8d0"},{"updated-at":1694176339433,"created-at":1694176339433,"author":{"login":"burinc","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/19825136?v=4"},"body":";; Recursively sort nested map\n(require '[clojure.walk :as w])\n\n(def m {:b 2, :c 3, :a 1, :d {:x 10, :c 3, :a 11, :b 22}})\n\n(w/postwalk (fn [x] (if (map? x) (into (sorted-map) x) x)) m)\n;;=> {:a 1, :b 2, :c 3, :d {:a 11, :b 22, :c 3, :x 10}}","_id":"64fb1453e4b08cf8563f4bf0"},{"updated-at":1766062278814,"created-at":1766062278814,"author":{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"},"body":";; A simpler illustration of the difference between postwalk and prewalk…\n\n(defn walking-fn [x]\n (cond (number? x) (* 10 x)\n (vector? x) (map inc x)))\n\n(walk/postwalk walking-fn [1 2 3])\n;; => (11 21 31)\n\n(walk/prewalk walking-fn [1 2 3])\n;; => (20 30 40)\n","_id":"6943f8c6b7956e24e4cb4ec3"}],"notes":[{"author":{"login":"pesterhazy","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/106328?v=4"},"updated-at":1519696583504,"created-at":1519696583504,"body":"As of 1.9.0, postwalk passes the k/v pairs of a map to `f` not, as one might expect, as type `clojure.lang.MapEntry` but as `clojure.lang.PersistentVector` ([JIRA](https://dev.clojure.org/jira/browse/CLJ-2031)). As a result, `f` cannot distinguish k/v pairs from other two-element vectors.","_id":"5a94bac7e4b0316c0f44f8ff"},{"author":{"login":"finalfantasia","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/2316604?v=4"},"updated-at":1541807954318,"created-at":1541807954318,"body":"Alex Miller's article [\"Tree visitors in Clojure\"](https://www.ibm.com/developerworks/library/j-treevisit/index.html) might be helpful in understanding general tree traversal and the usage of `clojure.walk/postwalk`.\n","_id":"5be61f52e4b00ac801ed9ef1"},{"author":{"login":"leo-ppp","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/72382759?v=4"},"updated-at":1615827306990,"created-at":1615827306990,"body":"> As of 1.9.0, postwalk passes the k/v pairs of a map to f not, as one might expect, as type clojure.lang.MapEntry but as clojure.lang.PersistentVector (JIRA). As a result, f cannot distinguish k/v pairs from other two-element vectors.\n\nThis was [fixed in 1.10.0](https://github.com/clojure/clojure/blob/master/changes.md#42-api), and one can use `(map-entry? v)` to distinguish a k/v pair from a vector when `walk`ing. ","_id":"604f916ae4b0b1e3652d7497"},{"author":{"login":"jeff303","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/3521562?v=4"},"updated-at":1632884419953,"created-at":1632884419953,"body":"Updated link to \"Tree visitors in Clojure\", mentioned above (PDF):\n\nhttps://insideclojure.org/images/j-treevisit-pdf.pdf","_id":"6153d6c3e4b0b1e3652d754a"}],"arglists":["f form"],"doc":"Performs a depth-first, post-order traversal of form. Calls f on\n each sub-form, uses f's return value in place of the original.\n Recognizes all Clojure data structures. Consumes seqs as with doall.","library-url":"https://github.com/clojure/clojure","href":"/clojure.walk/postwalk"},{"added":"1.1","ns":"clojure.walk","name":"keywordize-keys","file":"clojure/walk.clj","type":"function","column":1,"see-alsos":[{"created-at":1429291271248,"author":{"login":"Chort409","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1062637?v=3"},"to-var":{"ns":"clojure.core","name":"keyword","library-url":"https://github.com/clojure/clojure"},"_id":"55314107e4b01bb732af0a84"},{"created-at":1440158846927,"author":{"login":"BernhardBln","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/4759839?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"stringify-keys","ns":"clojure.walk"},"_id":"55d7147ee4b0831e02cddf17"}],"line":94,"examples":[{"updated-at":1457839421545,"created-at":1287070176000,"body":"(require 'clojure.walk)\n(clojure.walk/keywordize-keys {\"a\" 1 \"b\" 2})\n;;=> {:a 1 :b 2}","editors":[{"login":"fasiha","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/37649?v=3"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/3b7fcae9384271fb8ca8cd0c612bebf3?r=PG&default=identicon","account-source":"clojuredocs","login":"sunil.nandihalli"},"_id":"542692d1c026201cdc326f2a"},{"updated-at":1476953810286,"created-at":1476953810286,"author":{"login":"eunmin","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1837478?v=3"},"body":"(use 'clojure.walk)\n\n(keywordize-keys {\"a\" 1, \"b\" {\"c\" {\"d\" 2}}})\n;;=> {:a 1, :b {:c {:d 2}}}","_id":"580886d2e4b001179b66bdd2"},{"updated-at":1610750233661,"created-at":1610750233661,"author":{"login":"Luke1298","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/7078861?v=4"},"body":";; The input object also doesn't have to be a dictionary\n(require 'clojure.walk)\n(clojure.walk/keywordize-keys [{\"hello\" \"goodbye\"}])\n;;=>[{:hello \"goodbye\"}]","_id":"60021919e4b0b1e3652d7432"},{"updated-at":1694176483863,"created-at":1694176483863,"author":{"login":"burinc","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/19825136?v=4"},"body":";; Convert java.util.Map to Clojure map\n(import '[java.util Map HashMap])\n(require '[clojure.walk :as w])\n\n(defn javamap->map\n [^java.util.Map m]\n (->> (seq m)\n (into {})\n w/keywordize-keys))\n\n(let [m (doto (java.util.HashMap.)\n (.put 1 \"one\")\n (.put 2 \"two\")\n (.put 3 \"three\"))]\n (javamap->map m))\n\n;;=> {1 \"one\", 2 \"two\", 3 \"three\"}","_id":"64fb14e3e4b08cf8563f4bf1"}],"notes":null,"arglists":["m"],"doc":"Recursively transforms all map keys from strings to keywords.","library-url":"https://github.com/clojure/clojure","href":"/clojure.walk/keywordize-keys"},{"added":"1.1","ns":"clojure.walk","name":"walk","file":"clojure/walk.clj","type":"function","column":1,"see-alsos":[{"created-at":1337310249000,"author":{"login":"abrooks","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/69976?v=2"},"to-var":{"ns":"clojure.walk","name":"postwalk","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d11"},{"created-at":1337310268000,"author":{"login":"abrooks","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/69976?v=2"},"to-var":{"ns":"clojure.walk","name":"prewalk","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d12"}],"line":35,"examples":[{"updated-at":1519744662463,"created-at":1330654697000,"body":"(use 'clojure.walk)\n\n(walk #(* 2 %) #(apply + %) [1 2 3 4 5])\n;=> 30\n\n(walk second #(apply max %) [ [1 2] [3 4] [5 6] ])\n;=> 6\n\n(walk first #(apply max %) [ [1 2] [3 4] [5 6] ])\n;=> 5\n\n(walk first reverse [ [1 2] [3 4] [5 6] ])\n;=> (5 3 1)","editors":[{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/ef581bba2f97adb539c67a35465b3e1b?r=PG&default=identicon","account-source":"clojuredocs","login":"jjcomer"},"_id":"542692d7c026201cdc327133"},{"updated-at":1519744710013,"created-at":1335333358000,"body":"(require '[clojure.walk :as w])\n\n(w/walk (fn [[k v]] [k (* 10 v)]) identity {:a 1 :b 2 :c 3})\n;=> {:a 10, :c 30, :b 20}\n\n(w/postwalk #(if (number? %) (* 2 %) %) [[1 2 3] [4 7 2] [2 5 2]])\n;=> [[2 4 6] [8 14 4] [4 10 4]]\n\n(let [s [1 '(2 3 [1])]] \n (w/postwalk #(if (seq? %) (vec %) %) s))\n;=> [1 [2 3 [1]]]\n\n(w/walk (comp vec reverse) identity {0 :start 1 :inprogress 2 :end})\n;=> {:start 0, :inprogress 1, :end 2}","editors":[{"login":"devn","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3"},{"login":"phreed","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/211644?v=4"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3","account-source":"github","login":"devn"},"_id":"542692d7c026201cdc327134"}],"notes":null,"arglists":["inner outer form"],"doc":"Traverses form, an arbitrary data structure. inner and outer are\n functions. Applies inner to each element of form, building up a\n data structure of the same type, then applies outer to the result.\n Recognizes all Clojure data structures. Consumes seqs as with doall.","library-url":"https://github.com/clojure/clojure","href":"/clojure.walk/walk"},{"added":"1.1","ns":"clojure.walk","name":"prewalk-replace","file":"clojure/walk.clj","type":"function","column":1,"see-alsos":[{"created-at":1281619206000,"author":{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},"to-var":{"ns":"clojure.walk","name":"postwalk-replace","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521df9"},{"created-at":1281619213000,"author":{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},"to-var":{"ns":"clojure.core","name":"replace","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521dfa"},{"created-at":1348453766000,"author":{"login":"dansalmo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e33ee460f5f61bc5ba9b598934766215?r=PG&default=identicon"},"to-var":{"ns":"clojure.walk","name":"prewalk","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521dfb"}],"line":110,"examples":[{"author":{"login":"Chouser","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/7a0192050ed6488670acfd3f59405c10?r=PG&default=identicon"},"editors":[{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"}],"body":"user=> (clojure.walk/prewalk-replace '{a b} '(c (d a)))\n(c (d b))","created-at":1281563651000,"updated-at":1332953005000,"_id":"542692d1c026201cdc326f2c"},{"author":{"login":"philos99","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1de5617efb013ca7c9cf8e5646818ffa?r=PG&default=identicon"},"editors":[],"body":"(use 'clojure.walk)\n\n(prewalk-replace {:a 1 :b 2} [:a :b])\n;=> [1 2]\n\n(prewalk-replace {:a 1 :b 2} [:a :b :c])\n;=> [1 2 :c]\n\n(prewalk-replace {:a 1 :b 2} [:a :b [:a :b] :c])\n;=> [1 2 [1 2] :c]","created-at":1397943558000,"updated-at":1397943558000,"_id":"542692d7c026201cdc32712f"}],"notes":null,"arglists":["smap form"],"doc":"Recursively transforms form by replacing keys in smap with their\n values. Like clojure/replace but works on any data structure. Does\n replacement at the root of the tree first.","library-url":"https://github.com/clojure/clojure","href":"/clojure.walk/prewalk-replace"},{"added":"1.1","ns":"clojure.walk","name":"stringify-keys","file":"clojure/walk.clj","type":"function","column":1,"see-alsos":[{"created-at":1440158810607,"author":{"login":"BernhardBln","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/4759839?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"keywordize-keys","ns":"clojure.walk"},"_id":"55d7145ae4b072d7f27980e9"}],"line":102,"examples":[{"author":{"login":"philos99","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1de5617efb013ca7c9cf8e5646818ffa?r=PG&default=identicon"},"editors":[{"login":"philos99","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1de5617efb013ca7c9cf8e5646818ffa?r=PG&default=identicon"},{"login":"philos99","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1de5617efb013ca7c9cf8e5646818ffa?r=PG&default=identicon"}],"body":"(use 'clojure.walk)\n\n(stringify-keys {:a 1 :b 2})\n;=> {\"a\" 1, \"b\" 2}","created-at":1397941537000,"updated-at":1397943447000,"_id":"542692d7c026201cdc327130"},{"updated-at":1476953480559,"created-at":1476953480559,"author":{"login":"eunmin","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/1837478?v=3"},"body":"(use 'clojure.walk)\n\n(stringify-keys {:a 1 :b {:c {:d 2}}})\n;=> {\"a\" 1, \"b\" {\"c\" {\"d\" 2}}}","_id":"58088588e4b001179b66bdd1"},{"updated-at":1624571487187,"created-at":1624571487187,"author":{"login":"kevo1ution","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8290559?v=4"},"body":"(use 'clojure.walk)\n\n(stringify-keys {:hello/world 1})\n;=> {\"world\" 1}","_id":"60d4fe5fe4b0b1e3652d750f"}],"notes":[{"body":"Recursively transforms all map keys and values from strings to keywords.\n\n
    \n(use 'clojure.walk)\n(defn stringify-keys-and-vals\n  \"Recursively transforms all map keys and values from keywords to strings.\"\n  [m]\n  (let [kf (fn [[k v]] (if (keyword? k) [(name k) v] [k v]))\n        vf (fn [[k v]] (if (keyword? v) [k (name v)] [k v]))]\n    ;; only apply to maps\n    (postwalk (fn [x] (if (map? x) (into {} (map #(-> % kf vf) x)) x)) m))) \n
    \n\nExample:\n\n
    \n(stringify-keys-and-vals {:a :hello :b :world})\n;=> {\"a\" \"hello\", \"b\" \"world\"}\n(stringify-keys-and-vals {:a {:hello :world} :b [{:love :clojure} {:hate :other}]})\n;=> {\"a\" {\"hello\" \"world\"}, \"b\" [{\"love\" \"clojure\"} {\"hate\" \"other\"}]}\n
    \n\n","created-at":1615188831849,"updated-at":1615189007982,"author":{"avatar-url":"https://avatars.githubusercontent.com/u/278430?v=4","account-source":"github","login":"gongpengjun"},"_id":"6045d35fe4b0b1e3652d7473"}],"arglists":["m"],"doc":"Recursively transforms all map keys from keywords to strings.","library-url":"https://github.com/clojure/clojure","href":"/clojure.walk/stringify-keys"},{"added":"1.1","ns":"clojure.walk","name":"prewalk","file":"clojure/walk.clj","type":"function","column":1,"see-alsos":[{"created-at":1321428775000,"author":{"login":"srid","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bd3a68d670372cd09876c26270a4299a?r=PG&default=identicon"},"to-var":{"ns":"clojure.walk","name":"postwalk","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c84"},{"created-at":1348453563000,"author":{"login":"dansalmo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e33ee460f5f61bc5ba9b598934766215?r=PG&default=identicon"},"to-var":{"ns":"clojure.walk","name":"prewalk-demo","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c85"},{"created-at":1348453577000,"author":{"login":"dansalmo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e33ee460f5f61bc5ba9b598934766215?r=PG&default=identicon"},"to-var":{"ns":"clojure.walk","name":"prewalk-replace","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c86"}],"line":61,"examples":[{"author":{"login":"srid","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bd3a68d670372cd09876c26270a4299a?r=PG&default=identicon"},"editors":[],"body":";; From http://stackoverflow.com/questions/8089074/idiomatically-iterating-over-a-2-or-higher-dimensional-sequence-in-clojure/8091544#8091544\n\n(def matrix [[1 2 3]\n [4 5 6]\n [7 8 9]])\n(use 'clojure.walk :only [prewalk])\n\n(prewalk #(if (number? %) (inc %) %) matrix)\n=> [[2 3 4] [5 6 7] [8 9 10]]","created-at":1321428749000,"updated-at":1321428749000,"_id":"542692d7c026201cdc32712a"},{"editors":[{"login":"cljlc","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/36645452?v=4"}],"body":";; an example to show the differences between postwalk and prewalk\n;; (see the counterpart at postwalk)\n\n(let [counter (atom 0)\n print-touch (fn [x]\n (print (swap! counter inc) \":\" (pr-str x) \"→ \"))\n change-type (fn [x]\n (let [new-x (if (vector? x)\n (apply list x)\n (str x))]\n (prn new-x)\n new-x))]\n (clojure.walk/prewalk (fn [x]\n (print-touch x)\n (change-type x))\n [:a [:ba :bb] :c]))\n\n;; printed output:\n\n1 : [:a [:ba :bb] :c] → (:a [:ba :bb] :c)\n2 : :a → \":a\"\n3 : [:ba :bb] → (:ba :bb)\n4 : :ba → \":ba\"\n5 : :bb → \":bb\"\n6 : :c → \":c\"\n\n;; returned value:\n\n=> (\":a\" (\":ba\" \":bb\") \":c\")","author":{"avatar-url":"https://avatars0.githubusercontent.com/u/36645452?v=4","account-source":"github","login":"cljlc"},"created-at":1519076844559,"updated-at":1519084512666,"_id":"5a8b45ece4b0316c0f44f8d1"},{"updated-at":1766062306564,"created-at":1544197160620,"author":{"login":"dan-f","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/2146312?v=4"},"body":";; A simpler illustration of the difference between postwalk and prewalk…\n\n(defn walking-fn [x]\n (cond (number? x) (* 10 x)\n (vector? x) (map inc x)))\n\n(walk/postwalk walking-fn [1 2 3])\n;; => (11 21 31)\n\n(walk/prewalk walking-fn [1 2 3])\n;; => (20 30 40)\n","editors":[{"avatar-url":"https://avatars3.githubusercontent.com/u/2146312?v=4","account-source":"github","login":"dan-f"},{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"}],"_id":"5c0a9428e4b0ca44402ef5e6"}],"notes":null,"arglists":["f form"],"doc":"Like postwalk, but does pre-order traversal.","library-url":"https://github.com/clojure/clojure","href":"/clojure.walk/prewalk"},{"added":"1.1","ns":"clojure.walk","name":"postwalk-demo","file":"clojure/walk.clj","type":"function","column":1,"see-alsos":[{"created-at":1447033235869,"author":{"login":"cloojure","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7083783?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"postwalk","ns":"clojure.walk"},"_id":"563ff993e4b04b157a6648ed"},{"created-at":1447033255822,"author":{"login":"cloojure","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7083783?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"postwalk-replace","ns":"clojure.walk"},"_id":"563ff9a7e4b0290a56055d23"}],"line":80,"examples":[{"author":{"login":"philos99","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1de5617efb013ca7c9cf8e5646818ffa?r=PG&default=identicon"},"editors":[{"login":"philos99","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1de5617efb013ca7c9cf8e5646818ffa?r=PG&default=identicon"},{"login":"philos99","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1de5617efb013ca7c9cf8e5646818ffa?r=PG&default=identicon"}],"body":"(use 'clojure.walk)\n\nuser> (postwalk-demo [[1 2] [3 4 [5 6]] [7 8]])\nWalked: 1\nWalked: 2\nWalked: [1 2]\nWalked: 3\nWalked: 4\nWalked: 5\nWalked: 6\nWalked: [5 6]\nWalked: [3 4 [5 6]]\nWalked: 7\nWalked: 8\nWalked: [7 8]\nWalked: [[1 2] [3 4 [5 6]] [7 8]]\n[[1 2] [3 4 [5 6]] [7 8]]\n\nuser> (postwalk-demo {:a 1 :b 2})\nWalked: :a\nWalked: 1\nWalked: [:a 1]\nWalked: :b\nWalked: 2\nWalked: [:b 2]\nWalked: {:a 1, :b 2}\n{:a 1, :b 2}","created-at":1397942586000,"updated-at":1397943097000,"_id":"542692d7c026201cdc327124"}],"notes":null,"arglists":["form"],"doc":"Demonstrates the behavior of postwalk by printing each form as it is\n walked. Returns form.","library-url":"https://github.com/clojure/clojure","href":"/clojure.walk/postwalk-demo"},{"added":"1.1","ns":"clojure.walk","name":"prewalk-demo","file":"clojure/walk.clj","type":"function","column":1,"see-alsos":[{"created-at":1348453549000,"author":{"login":"dansalmo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e33ee460f5f61bc5ba9b598934766215?r=PG&default=identicon"},"to-var":{"ns":"clojure.walk","name":"prewalk","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d48"}],"line":87,"examples":[{"author":{"login":"philos99","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1de5617efb013ca7c9cf8e5646818ffa?r=PG&default=identicon"},"editors":[{"login":"philos99","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1de5617efb013ca7c9cf8e5646818ffa?r=PG&default=identicon"},{"login":"philos99","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1de5617efb013ca7c9cf8e5646818ffa?r=PG&default=identicon"},{"login":"philos99","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1de5617efb013ca7c9cf8e5646818ffa?r=PG&default=identicon"}],"body":"(use 'clojure.walk)\n\nuser> (prewalk-demo [[1 2] [3 4 [5 6]] [7 8]])\nWalked: [[1 2] [3 4 [5 6]] [7 8]]\nWalked: [1 2]\nWalked: 1\nWalked: 2\nWalked: [3 4 [5 6]]\nWalked: 3\nWalked: 4\nWalked: [5 6]\nWalked: 5\nWalked: 6\nWalked: [7 8]\nWalked: 7\nWalked: 8\n[[1 2] [3 4 [5 6]] [7 8]]\n\nuser> (prewalk-demo {:a 1 :b 2})\nWalked: {:a 1, :b 2}\nWalked: [:a 1]\nWalked: :a\nWalked: 1\nWalked: [:b 2]\nWalked: :b\nWalked: 2\n{:a 1, :b 2}","created-at":1397942432000,"updated-at":1397943044000,"_id":"542692d7c026201cdc32712b"}],"notes":null,"arglists":["form"],"doc":"Demonstrates the behavior of prewalk by printing each form as it is\n walked. Returns form.","library-url":"https://github.com/clojure/clojure","href":"/clojure.walk/prewalk-demo"},{"added":"1.1","ns":"clojure.walk","name":"macroexpand-all","file":"clojure/walk.clj","type":"function","column":1,"see-alsos":[{"to-var":{"library-url":"https://github.com/clojure/clojure","name":"macroexpand-1","ns":"clojure.core"},"author":{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},"created-at":1339248731000,"_id":"542692ebf6e94c6970521de6"},{"to-var":{"library-url":"https://github.com/clojure/clojure","name":"macroexpand","ns":"clojure.core"},"author":{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},"created-at":1339248761000,"_id":"542692ebf6e94c6970521de7"}],"line":126,"examples":[{"updated-at":1339248698000,"created-at":1339248698000,"body":"user=> (use 'clojure.walk)\nuser=> (macroexpand-all '(-> c (+ 3) (* 2)))\n(* (+ c 3) 2)","editors":[],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/528360?v=3","account-source":"github","login":"BertrandDechoux"},"_id":"542692d7c026201cdc32711d"},{"author":{"login":"Sgeo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bf4e0e4e4f0b1f703b1372a8dd7b0735?r=PG&default=identicon"},"editors":[],"body":"user=> (use 'clojure.walk)\n\n; tryclj.com and lazybot on #clojure get the following wrong\nuser=> (let [-> inc] (-> 5)) \n6\n\n; Below macroexpansion is supposed to result in equivalent code to the above\nuser=> (macroexpand-all '(let [-> inc] (-> 5)))\n(let* [-> inc] 5)\nuser=> (let* [-> inc] 5)\n5\n\n; However, as is clear above, it does not","created-at":1355181392000,"updated-at":1355181392000,"_id":"542692d7c026201cdc32711e"},{"author":{"login":"philos99","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1de5617efb013ca7c9cf8e5646818ffa?r=PG&default=identicon"},"editors":[{"login":"philos99","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1de5617efb013ca7c9cf8e5646818ffa?r=PG&default=identicon"},{"login":"philos99","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1de5617efb013ca7c9cf8e5646818ffa?r=PG&default=identicon"}],"body":";; differences between macroexpand-1, macroexpand and macroexpand-all \n\n(require '[clojure.pprint :as pp]\n '[clojure.walk :as walk])\n\n(alter-var-root #'pp/*print-suppress-namespaces* (constantly true))\n\n\n(defmacro plus [n1 n2]\n `(+ ~n1 ~n2))\n\n(pp/pprint (macroexpand-1 '(plus 3 4))) ;=> (+ 3 4)\n(pp/pprint (macroexpand '(plus 3 4))) ;=> (+ 3 4)\n\n\n(defmacro pl [p1 p2]\n `(plus ~p1 ~p2))\n\n(pp/pprint (macroexpand-1 '(pl 3 4))) ;=> (plus 3 4)\n(pp/pprint (macroexpand '(pl 3 4))) ;=> (+ 3 4)\n\n\n(defmacro minus [m1 m2]\n `(- ~m1 ~m2))\n\n(defmacro calc [c1 c2]\n `(pl ~c1 (minus ~c1 ~c2)))\n\n(pp/pprint (macroexpand-1 '(calc 20 30)))\n;=> (pl 20 (minus 20 30))\n\n(pp/pprint (macroexpand '(calc 20 30)))\n;=> (+ 20 (minus 20 30))\n\n(pp/pprint (walk/macroexpand-all '(calc 20 30)))\n;=> (+ 20 (- 20 30))","created-at":1397943977000,"updated-at":1397944114000,"_id":"542692d7c026201cdc32711f"},{"updated-at":1689437697116,"created-at":1689437656976,"author":{"login":"owenRiddy","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/8080718?v=4"},"body":"; macroexpand-all can give different results to what is generated in a real\n; evaluation. Here is a code sample that should normally evaluates to `dummy`, \n; but `macroexpand-all` generates code that evaluates to `nil`.\n\n(defmacro d []\n (let [probably-dummy# (-> &env keys first)]\n `(quote ~probably-dummy#)))\n\n(letfn [(dummy [] true)]\n (d))\n; => dummy\n\n(clojure.walk/macroexpand-all\n '(letfn [(dummy [] true)]\n (d)))\n; => (letfn* [dummy (fn* dummy ([] true))] (quote nil))\n\n(eval \n (clojure.walk/macroexpand-all\n '(letfn [(dummy [] true)]\n (d))))\n; => nil","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/8080718?v=4","account-source":"github","login":"owenRiddy"}],"_id":"64b2c5d8e4b08cf8563f4bd2"}],"notes":[{"updated-at":1351086771000,"body":"DO NOT USE THIS FUNCTION, it doesn't handle special forms at all, and, as such, does not in fact expand into the ultimate macroexpansion of the form.\r\n\r\nFor example,\r\n
    (require '[clojure.walk :as walk])\r\n(println (walk/macroexpand-all '(quote (let [a 1] a))))\r\n
    \r\nWill print\r\n
    (quote (let* [a 1] a))\r\n
    \r\nWhen the correct answer is\r\n
    (quote (let [a 1] a))\r\n
    \r\nShowing an utter unawareness of proper handling of special forms\r\n\r\nDO NOT USE THIS FUNCTION","created-at":1351086666000,"author":{"login":"Sgeo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bf4e0e4e4f0b1f703b1372a8dd7b0735?r=PG&default=identicon"},"_id":"542692edf6e94c6970521ff0"},{"updated-at":1354211038000,"body":"@Sgeo - `let` is just a macro for `let*`:\r\n\r\n (clojure.repl/source let) =>\r\n\r\n (defmacro let\r\n \"binding => binding-form init-expr\r\n\r\n Evaluates the exprs in a lexical context in which the symbols in\r\n the binding-forms are bound to their respective init-exprs or parts\r\n therein.\"\r\n {:added \"1.0\", :special-form true, :forms '[(let [bindings*] exprs*)]}\r\n [bindings & body]\r\n (assert-args let\r\n (vector? bindings) \"a vector for its binding\"\r\n (even? (count bindings)) \"an even number of forms in binding vector\")\r\n `(let* ~(destructure bindings) ~@body))","created-at":1354211038000,"author":{"login":"Cubic","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/b6678a430a805dd78366d6e135b49f2d?r=PG&default=identicon"},"_id":"542692edf6e94c6970521ff6"},{"updated-at":1354485217000,"body":"(quote (let [a 1] a)) is '(let [a 1] a) which evaluates to a list containing the symbol let, a vector [a 1], and a symbol a. In this context, the (let [a 1] a) is not code, but mere data, and as such, should not be macroexpanded at all, anymore than a string like \"(-> a b c)\" should be macroexpanded into \"(c (b a))\" (and yes, I know that's not the exact macroexpansion).","created-at":1354484499000,"author":{"login":"Sgeo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bf4e0e4e4f0b1f703b1372a8dd7b0735?r=PG&default=identicon"},"_id":"542692edf6e94c6970521ff7"}],"arglists":["form"],"doc":"Recursively performs all possible macroexpansions in form.","library-url":"https://github.com/clojure/clojure","href":"/clojure.walk/macroexpand-all"},{"added":"1.1","ns":"clojure.walk","name":"postwalk-replace","file":"clojure/walk.clj","type":"function","column":1,"see-alsos":[{"created-at":1281619231000,"author":{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},"to-var":{"ns":"clojure.walk","name":"prewalk-replace","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c82"},{"created-at":1281619236000,"author":{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},"to-var":{"ns":"clojure.core","name":"replace","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c83"},{"created-at":1585850917002,"author":{"login":"MicahElliott","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/159047?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"postwalk","ns":"clojure.walk"},"_id":"5e862a25e4b087629b5a18ca"}],"line":118,"examples":[{"author":{"login":"philos99","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1de5617efb013ca7c9cf8e5646818ffa?r=PG&default=identicon"},"editors":[{"login":"philos99","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1de5617efb013ca7c9cf8e5646818ffa?r=PG&default=identicon"},{"login":"philos99","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/1de5617efb013ca7c9cf8e5646818ffa?r=PG&default=identicon"}],"body":"(use 'clojure.walk)\n\n(postwalk-replace {:a 1 :b 2} [:a :b])\n;=> [1 2]\n\n(postwalk-replace {:a 1 :b 2} [:a :b :c])\n;=> [1 2 :c]\n\n(postwalk-replace {:a 1 :b 2} [:a :b [:a :b] :c])\n;=> [1 2 [1 2] :c]","created-at":1397943421000,"updated-at":1397943663000,"_id":"542692d7c026201cdc327127"},{"updated-at":1463496047122,"created-at":1463496047122,"author":{"login":"x","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/693546?v=3"},"body":"(postwalk-replace {nil :NIL} {:a 1, :b nil, :c 3, nil 4})\n;=> {:NIL 4, :a 1, :b :NIL, :c 3}","_id":"573b2d6fe4b05c05173143fb"}],"notes":null,"arglists":["smap form"],"doc":"Recursively transforms form by replacing keys in smap with their\n values. Like clojure/replace but works on any data structure. Does\n replacement at the leaves of the tree first.","library-url":"https://github.com/clojure/clojure","href":"/clojure.walk/postwalk-replace"},{"ns":"clojure.xml","name":"tag","file":"clojure/xml.clj","type":"var","column":1,"see-alsos":null,"line":22,"examples":null,"notes":null,"arglists":[],"library-url":"https://github.com/clojure/clojure","href":"/clojure.xml/tag"},{"added":"1.11","ns":"clojure.xml","name":"sax-parser","file":"clojure/xml.clj","type":"function","column":1,"see-alsos":null,"line":75,"examples":null,"notes":null,"arglists":[""],"doc":"Create a new SAXParser","library-url":"https://github.com/clojure/clojure","href":"/clojure.xml/sax-parser"},{"ns":"clojure.xml","name":"*sb*","file":"clojure/xml.clj","type":"var","column":1,"see-alsos":null,"dynamic":true,"line":18,"examples":null,"notes":null,"arglists":[],"library-url":"https://github.com/clojure/clojure","href":"/clojure.xml/*sb*"},{"ns":"clojure.xml","name":"*state*","file":"clojure/xml.clj","type":"var","column":1,"see-alsos":null,"dynamic":true,"line":17,"examples":null,"notes":null,"arglists":[],"library-url":"https://github.com/clojure/clojure","href":"/clojure.xml/*state*"},{"ns":"clojure.xml","name":"*stack*","file":"clojure/xml.clj","type":"var","column":1,"see-alsos":null,"dynamic":true,"line":15,"examples":null,"notes":null,"arglists":[],"library-url":"https://github.com/clojure/clojure","href":"/clojure.xml/*stack*"},{"ns":"clojure.xml","name":"element","file":"clojure/xml.clj","type":"var","column":1,"see-alsos":[{"created-at":1324592891000,"author":{"login":"Claj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5fd658a8d2ef549071cb5286b1b874aa?r=PG&default=identicon"},"to-var":{"ns":"clojure.xml","name":"emit-element","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ec8"},{"created-at":1324592934000,"author":{"login":"Claj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5fd658a8d2ef549071cb5286b1b874aa?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"struct","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ec9"},{"created-at":1324592937000,"author":{"login":"Claj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5fd658a8d2ef549071cb5286b1b874aa?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"struct-map","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521eca"},{"created-at":1324592944000,"author":{"login":"Claj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5fd658a8d2ef549071cb5286b1b874aa?r=PG&default=identicon"},"to-var":{"ns":"clojure.xml","name":"parse","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ecb"},{"created-at":1324593203000,"author":{"login":"Claj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5fd658a8d2ef549071cb5286b1b874aa?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"with-out-str","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ecc"}],"line":20,"examples":[{"author":{"login":"Claj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5fd658a8d2ef549071cb5286b1b874aa?r=PG&default=identicon"},"editors":[{"login":"Claj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5fd658a8d2ef549071cb5286b1b874aa?r=PG&default=identicon"},{"login":"Claj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5fd658a8d2ef549071cb5286b1b874aa?r=PG&default=identicon"}],"body":"(use 'clojure.zip)\n\n;;using our old friend struct for performance in maps \n(struct element :httplink {:href \"http://clojure.org\"} nil)\n=>\n{:tag :httplink, \n :attrs {:href \"http://clojure.org\"}, \n :content nil}\n\n;;these elements can be output to ordinary xml strings with emit-element\n(emit-element (struct element :httplink {:href \"http://clojure.org\"} nil))\n=>\n\n;;this is printed - can be catched with macro with-out-str\n\n;;make hierarchies:\n(struct element :parent {:name \"Barbara\"} \n [(struct element :children {:name \"Gina\"} nil) \n (struct element :children {:name \"John\"} nil)])\n=>\n{:tag :parent, :attrs {:name \"Barbara\"}, :content \n [{:tag :children, :attrs {:name \"Gina\"}, :content nil} \n {:tag :children, :attrs {:name \"John\"}, :content nil}]}\n\n;;which can be emit-elemented as well\n\n(emit-element {:tag :parent, :attrs {:name \"Barbara\"}, :content [{:tag :children, :attrs {:name \"Gina\"}, :content nil} {:tag :children, :attrs {:name \"John\"}, :content nil}]})\n=>\n\n \n \n","created-at":1324592984000,"updated-at":1324593242000,"_id":"542692d7c026201cdc327136"}],"notes":null,"arglists":[],"library-url":"https://github.com/clojure/clojure","href":"/clojure.xml/element"},{"ns":"clojure.xml","name":"*current*","file":"clojure/xml.clj","type":"var","column":1,"see-alsos":null,"dynamic":true,"line":16,"examples":null,"notes":null,"arglists":[],"library-url":"https://github.com/clojure/clojure","href":"/clojure.xml/*current*"},{"ns":"clojure.xml","name":"content","file":"clojure/xml.clj","type":"var","column":1,"see-alsos":null,"line":24,"examples":null,"notes":null,"arglists":[],"library-url":"https://github.com/clojure/clojure","href":"/clojure.xml/content"},{"ns":"clojure.xml","name":"content-handler","file":"clojure/xml.clj","type":"var","column":1,"see-alsos":null,"line":26,"examples":null,"notes":null,"arglists":[],"library-url":"https://github.com/clojure/clojure","href":"/clojure.xml/content-handler"},{"added":"1.11","ns":"clojure.xml","name":"disable-external-entities","file":"clojure/xml.clj","type":"function","column":1,"see-alsos":null,"line":81,"examples":null,"notes":null,"arglists":["parser"],"doc":"Modifies a SAXParser to disable external entity resolution to prevent XXE attacks","library-url":"https://github.com/clojure/clojure","href":"/clojure.xml/disable-external-entities"},{"added":"1.0","ns":"clojure.xml","name":"parse","file":"clojure/xml.clj","type":"function","column":1,"see-alsos":[{"created-at":1324593911000,"author":{"login":"Claj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5fd658a8d2ef549071cb5286b1b874aa?r=PG&default=identicon"},"to-var":{"ns":"clojure.xml","name":"emit-element","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cf3"},{"created-at":1324593914000,"author":{"login":"Claj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5fd658a8d2ef549071cb5286b1b874aa?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"with-out-str","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cf4"},{"created-at":1324593922000,"author":{"login":"Claj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5fd658a8d2ef549071cb5286b1b874aa?r=PG&default=identicon"},"to-var":{"ns":"clojure.xml","name":"element","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cf5"}],"line":106,"examples":[{"updated-at":1430664126603,"created-at":1324593962000,"body":"(require '[clojure.xml :as xml]\n '[clojure.zip :as zip])\n\n;;convenience function, first seen at nakkaya.com later in clj.zip src\n(defn zip-str [s]\n (zip/xml-zip \n (xml/parse (java.io.ByteArrayInputStream. (.getBytes s)))))\n\n;;parse from xml-strings to internal xml representation\nuser=> (zip-str \"
    \")\n[{:tag :a, :attrs {:href \"nakkaya.com\"}, :content nil} nil]\n\n;;root can be rendered with xml/emit-element\nuser=> (xml/emit-element (zip/root [{:tag :a, :attrs {:href \"nakkaya.com\"}, :content nil} nil]))\n\n\n;;printed (to assure it's not lazy and for performance), can be caught to string variable with with-out-str","editors":[{"avatar-url":"https://www.gravatar.com/avatar/9a562ca6891212ffed05e29cc69c9124?r=PG&default=identicon","account-source":"clojuredocs","login":"balamkej"},{"avatar-url":"https://www.gravatar.com/avatar/6f4c4cb023ca9033b53a6a517ed89153?r=PG&default=identicon","account-source":"clojuredocs","login":"Lowgain"},{"avatar-url":"https://avatars.githubusercontent.com/u/92894?v=3","account-source":"github","login":"rafmagana"},{"avatar-url":"https://avatars.githubusercontent.com/u/353113?v=3","account-source":"github","login":"claj"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/5fd658a8d2ef549071cb5286b1b874aa?r=PG&default=identicon","account-source":"clojuredocs","login":"Claj"},"_id":"542692d7c026201cdc32713c"},{"editors":[{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"}],"body":";; Use the \"startparse\" parameter to disable \n;; validation and network requests for external DTDs\n\n(require '[clojure.xml :as xml]\n '[clojure.java.io :as io])\n(import '[javax.xml.parsers SAXParserFactory])\n\n(def conforming\n \"\n \n \n
    Hello
    \n \")\n\n(defn non-validating [s ch]\n (..\n (doto\n (SAXParserFactory/newInstance)\n (.setFeature \n \"http://apache.org/xml/features/nonvalidating/load-external-dtd\" false))\n (newSAXParser)\n (parse s ch)))\n\n(def xml\n (-> conforming .getBytes io/input-stream (xml/parse non-validating)))\n\n;; {:tag :html,\n;; :attrs {:xmlns \"http://www.w3.org/1999/xhtml\"},\n;; :content [{:tag :article, :attrs nil, :content [\"Hello\"]}]}\n","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"},"created-at":1559323024229,"updated-at":1559334683073,"_id":"5cf16190e4b0ca44402ef73b"}],"notes":null,"arglists":["s","s startparse"],"doc":"Parses and loads the source s, which can be a File, InputStream or\n String naming a URI. Returns a tree of the xml/element struct-map,\n which has the keys :tag, :attrs, and :content. and accessor fns tag,\n attrs, and content. Other parsers can be supplied by passing\n startparse, a fn taking a source and a ContentHandler and returning\n a parser.\n\n Prior to 1.11, used startparse-sax by default. As of 1.11, uses\n startparse-sax-safe, which disables XXE (XML External Entity)\n processing. Pass startparse-sax to revert to prior behavior.","library-url":"https://github.com/clojure/clojure","href":"/clojure.xml/parse"},{"added":"1.0","ns":"clojure.xml","name":"startparse-sax","file":"clojure/xml.clj","type":"function","column":1,"see-alsos":null,"line":92,"examples":null,"notes":null,"arglists":["s ch"],"doc":"A startparse function suitable for use with clojure.xml/parse.\n Note that this function is open to XXE entity attacks, see startparse-sax-safe.","library-url":"https://github.com/clojure/clojure","href":"/clojure.xml/startparse-sax"},{"ns":"clojure.xml","name":"emit","file":"clojure/xml.clj","type":"function","column":1,"see-alsos":[{"created-at":1323923286000,"author":{"login":"Claj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5fd658a8d2ef549071cb5286b1b874aa?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"with-out-str","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e6f"}],"line":143,"examples":[{"body":"(use 'clojure.xml)\n;;attrs stores the attributes of a tag and content contains the children\n(emit {:tag :parent :attrs {:value \"Hello\"} :content[\n\t{:tag :child1 :attrs {:value \"World\"}}\n\t{:tag :child2 :attrs {:value \"Clojure\"}}\n\t]})\n\n;; prints this to *out*:\n\n\n\n\n","author":{"login":"finiterecursion","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/4407459?v=3"},"created-at":1425400719581,"updated-at":1438720830296,"editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/353113?v=3","account-source":"github","login":"claj"}],"_id":"54f5e38fe4b0b716de7a652f"}],"notes":[{"updated-at":1325286942000,"body":"this one have a problem when trying to export xml with string containing & etc (should be escaped). Contribs prxml has this functionality.","created-at":1325286942000,"author":{"login":"Claj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5fd658a8d2ef549071cb5286b1b874aa?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fd5"},{"updated-at":1328074886000,"body":"A 1.3 compatible version of prxml can be found here:\r\n\r\nhttps://github.com/weissjeffm/clojure.prxml","created-at":1328074886000,"author":{"login":"gstamp","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/cd4185cdca53ccdc11cd24ebc0cfb46d?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fd8"}],"arglists":["x"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.xml/emit"},{"added":"1.11","ns":"clojure.xml","name":"startparse-sax-safe","file":"clojure/xml.clj","type":"function","column":1,"see-alsos":null,"line":99,"examples":null,"notes":null,"arglists":["s ch"],"doc":"A startparse function suitable for use with clojure.xml/parse.\n External entity resolution is disabled to prevent XXE entity attacks.","library-url":"https://github.com/clojure/clojure","href":"/clojure.xml/startparse-sax-safe"},{"ns":"clojure.xml","name":"attrs","file":"clojure/xml.clj","type":"var","column":1,"see-alsos":null,"line":23,"examples":null,"notes":null,"arglists":[],"library-url":"https://github.com/clojure/clojure","href":"/clojure.xml/attrs"},{"ns":"clojure.xml","name":"emit-element","file":"clojure/xml.clj","type":"function","column":1,"see-alsos":[{"created-at":1323923092000,"author":{"login":"Claj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5fd658a8d2ef549071cb5286b1b874aa?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"with-out-str","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ed5"},{"created-at":1324592254000,"author":{"login":"Claj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5fd658a8d2ef549071cb5286b1b874aa?r=PG&default=identicon"},"to-var":{"ns":"clojure.xml","name":"element","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ed6"}],"line":127,"examples":[{"author":{"login":"Claj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5fd658a8d2ef549071cb5286b1b874aa?r=PG&default=identicon"},"editors":[{"login":"Claj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5fd658a8d2ef549071cb5286b1b874aa?r=PG&default=identicon"},{"login":"Claj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5fd658a8d2ef549071cb5286b1b874aa?r=PG&default=identicon"},{"login":"dyba","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/296219?v=3"},{"avatar-url":"https://avatars.githubusercontent.com/u/1619912?v=4","account-source":"github","login":"arcanjoaq"}],"body":"(use 'clojure.xml)\n\n;;If just a string it's text inside or something. just print it\n(emit-element \"hello\")\nhello\n\n;;we want a map with a tag\n(emit-element {:tag :hello})\n\n\n;;strings works as well (since we're using the \"name\" function)\n(emit-element {:tag \"hello\"})\n\n\n;;:attrs is for all the attributes\n(emit-element {:tag :hello :attrs {:place \"world\"}})\n\n\n;;:content is for all the children in the element\n(emit-element {:tag :parent :attrs {:id \"22\" :name \"fritz\"} :content [\n {:tag :child :attrs {:id \"56\"}} \n {:tag :child :attrs {:id \"57\"}]}))\n\n\n\n\n\n;; also, look out for not supplying :content with another xml-ish map\n;; or at minimum a vector containing the string you want to put as the content:\n(emit-element {:tag :hello :content \"world\"})\n\njava.lang.NullPointerException (NO_SOURCE_FILE:0)\n\n(emit-element {:tag :hello :content [\"world\"]})\nworld\n\n;; the :content value must be a vector of strings","created-at":1323922631000,"updated-at":1717199475166,"_id":"542692d7c026201cdc327139"}],"notes":[{"updated-at":1323923133000,"body":"you can catch the printed code with the macro
    with-out-str
    if you want to catch it in variables.","created-at":1323923133000,"author":{"login":"Claj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5fd658a8d2ef549071cb5286b1b874aa?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fd2"}],"arglists":["e"],"library-url":"https://github.com/clojure/clojure","href":"/clojure.xml/emit-element"},{"added":"1.0","ns":"clojure.zip","name":"rightmost","file":"clojure/zip.clj","type":"function","column":1,"see-alsos":[{"created-at":1497531575982,"author":{"login":"tkocmathla","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/183459?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"leftmost","ns":"clojure.zip"},"_id":"594284b7e4b06e730307db33"}],"line":157,"examples":null,"notes":null,"arglists":["loc"],"doc":"Returns the loc of the rightmost sibling of the node at this loc, or self","library-url":"https://github.com/clojure/clojure","href":"/clojure.zip/rightmost"},{"added":"1.0","ns":"clojure.zip","name":"insert-child","file":"clojure/zip.clj","type":"function","column":1,"see-alsos":[{"created-at":1329432152000,"author":{"login":"Claj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5fd658a8d2ef549071cb5286b1b874aa?r=PG&default=identicon"},"to-var":{"ns":"clojure.zip","name":"zipper","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521edf"},{"created-at":1357860181000,"author":{"login":"juan.facorro","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d6f59d93cc17c698f16e550034a2d1ad?r=PG&default=identicon"},"to-var":{"ns":"clojure.zip","name":"append-child","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521ee0"}],"line":216,"examples":[{"author":{"login":"Claj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5fd658a8d2ef549071cb5286b1b874aa?r=PG&default=identicon"},"editors":[],"body":"(use 'clojure.zip) ;;warnings OK\n\n(def zp (zipper vector? seq (fn [_ c] c) [[1 2 3] [4 [5 6] 7] [8 9]]) )\n\n(root (insert-child (-> zp down right) 42))\n=>([1 2 3] (42 4 [5 6] 7) [8 9])\n\n\n(def zp2 (zipper vector? seq (fn [_ c] c) [74 75])\n\n(root (insert-right (-> zp down right) zp2))\n=>([1 2 3] [4 [5 6] 7] [[74 75] nil] [8 9])\n\n(root (insert-left (-> zp down right) zp2))\n=>([1 2 3] [[74 75] nil] [4 [5 6] 7] [8 9])\n\n\n\n","created-at":1329432685000,"updated-at":1329432685000,"_id":"542692d7c026201cdc327140"}],"notes":null,"arglists":["loc item"],"doc":"Inserts the item as the leftmost child of the node at this loc,\n without moving","library-url":"https://github.com/clojure/clojure","href":"/clojure.zip/insert-child"},{"added":"1.0","ns":"clojure.zip","name":"left","file":"clojure/zip.clj","type":"function","column":1,"see-alsos":null,"line":166,"examples":null,"notes":null,"arglists":["loc"],"doc":"Returns the loc of the left sibling of the node at this loc, or nil","library-url":"https://github.com/clojure/clojure","href":"/clojure.zip/left"},{"added":"1.0","ns":"clojure.zip","name":"path","file":"clojure/zip.clj","type":"function","column":1,"see-alsos":null,"line":90,"examples":[{"updated-at":1559115788133,"created-at":1534083516071,"author":{"login":"abhi18av","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/12799326?v=4"},"body":"\n(def nested-vecs\n [:foo [:bar :baz [:bork]]])\n\n;; now let's make a zipper\n(def z (zip/vector-zip nested-vecs))\n\n;; \"path\" only returns the \"down nodes\" necessary to reach the destination.\n;; Any other horizontal movement is not collected:\n\n(-> z\n zip/down ;; down1 [:foo [:bar :baz [:bork]]]\n zip/right\n zip/down ;; down2 [:bar :baz [:bork]]\n zip/rightmost\n zip/down ;; down3 [:bork]\n zip/path)\n\n;; [[:foo [:bar :baz [:bork]]] \n;; [:bar :baz [:bork]] \n;; [:bork]]\n\n\n\n","editors":[{"avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"}],"_id":"5b7041bce4b00ac801ed9e53"}],"notes":null,"arglists":["loc"],"doc":"Returns a seq of nodes leading to this loc","library-url":"https://github.com/clojure/clojure","href":"/clojure.zip/path"},{"added":"1.0","ns":"clojure.zip","name":"leftmost","file":"clojure/zip.clj","type":"function","column":1,"see-alsos":[{"created-at":1497531567628,"author":{"login":"tkocmathla","account-source":"github","avatar-url":"https://avatars0.githubusercontent.com/u/183459?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"rightmost","ns":"clojure.zip"},"_id":"594284afe4b06e730307db32"}],"line":174,"examples":null,"notes":null,"arglists":["loc"],"doc":"Returns the loc of the leftmost sibling of the node at this loc, or self","library-url":"https://github.com/clojure/clojure","href":"/clojure.zip/leftmost"},{"added":"1.0","ns":"clojure.zip","name":"append-child","file":"clojure/zip.clj","type":"function","column":1,"see-alsos":[{"created-at":1558985943586,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"insert-child","ns":"clojure.zip"},"_id":"5cec3cd7e4b0ca44402ef72e"}],"line":223,"examples":[{"editors":[{"login":"tomdl89","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/33435574?v=4"}],"body":";; \"append-child\" adds a new child as the rightmost element. \n;; \"insert-child\" does the same, but leftmost. The node needs to be a branch.\n\n(require '[clojure.zip :as zip])\n\n(def vzip\n (zip/vector-zip\n [[1 2]\n [3 4 [5 10 [11 12]]]\n [13 14]])) \n\n(-> vzip zip/down zip/rightmost (zip/append-child 'INS) zip/up zip/node)\n;; [[1 2] [3 4 [5 10 [11 12]]] [13 14 INS]]\n\n(-> vzip zip/down zip/rightmost (zip/insert-child 'INS) zip/up zip/node)\n;; [[1 2] [3 4 [5 10 [11 12]]] [INS 13 14]]\n\n(-> vzip zip/down zip/rightmost zip/down (zip/append-child 'INS))\n;; Exception called children on a leaf node\n","author":{"avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"},"created-at":1558985910358,"updated-at":1683123974927,"_id":"5cec3cb6e4b0ca44402ef72d"},{"updated-at":1574335186052,"created-at":1574335186052,"author":{"login":"loeschzwerg","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/24317401?v=4"},"body":"(use 'clojure.zip)\n;; def a tree struct\n;; .\n;; / \\\n;; . 0\n;; / \\\n;; 1 2\n(def tree\n (vector-zip\n [[1 2] 0]))\n\n(-> tree\n down\n (append-child 3))\n;; .\n;; / \\\n;; x 0\n;; /|\\\n;; 1 2 3\n;;\n;; 3 inserted, location x unchanged","_id":"5dd672d2e4b0ca44402ef7e3"}],"notes":null,"arglists":["loc item"],"doc":"Inserts the item as the rightmost child of the node at this loc,\n without moving","library-url":"https://github.com/clojure/clojure","href":"/clojure.zip/append-child"},{"added":"1.0","ns":"clojure.zip","name":"branch?","file":"clojure/zip.clj","type":"function","column":1,"see-alsos":null,"line":69,"examples":[{"updated-at":1574334564922,"created-at":1574334564922,"author":{"login":"loeschzwerg","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/24317401?v=4"},"body":"(use 'clojure.zip)\n;; def a tree struct\n;; .\n;; / \\\n;; . 0\n;; / \\\n;; 1 2\n(def tree\n (vector-zip\n [[1 2] 0]))\n\n;; #0 #1 #2\n;; x . .\n;; / \\ / \\ / \\\n;; . 0 x 0 . x\n;; / \\ / \\ / \\\n;; 1 2 1 2 1 2\n\n;; #0\n(-> tree\n branch?) ;; => true\n;; #1\n(-> tree\n down\n branch?) ;; => true\n;; #2\n(-> tree\n down\n next\n branch?) ;; => false\n\n;; false for leaves","_id":"5dd67064e4b0ca44402ef7e2"}],"notes":null,"arglists":["loc"],"doc":"Returns true if the node at loc is a branch","library-url":"https://github.com/clojure/clojure","href":"/clojure.zip/branch_q"},{"added":"1.0","ns":"clojure.zip","name":"children","file":"clojure/zip.clj","type":"function","column":1,"see-alsos":[{"created-at":1455292742761,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"zipper","ns":"clojure.zip"},"_id":"56be0146e4b0b0491b9ed178"}],"line":75,"examples":[{"updated-at":1574339327098,"created-at":1574335336603,"author":{"login":"loeschzwerg","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/24317401?v=4"},"body":"(use 'clojure.zip)\n;; def a tree struct\n;; .\n;; / \\\n;; . 0\n;; / \\\n;; 1 2\n(def tree\n (vector-zip\n [[1 2] 0]))\n\n;; #0 #1 #2\n;; x . .\n;; / \\ / \\ / \\\n;; . 0 x 0 . 0\n;; / \\ / \\ / \\\n;; 1 2 1 2 x 2\n\n;; #0\n(-> tree\n children) ;; => ([1 2] 0)\n;; #1\n(-> tree\n down\n children) ;; => (1 2)\n;; #2\n(-> tree\n down\n down\n children) ;; => Exception called children on a leaf node","editors":[{"avatar-url":"https://avatars3.githubusercontent.com/u/24317401?v=4","account-source":"github","login":"loeschzwerg"}],"_id":"5dd67368e4b0ca44402ef7e4"}],"notes":null,"arglists":["loc"],"doc":"Returns a seq of the children of node at loc, which must be a branch","library-url":"https://github.com/clojure/clojure","href":"/clojure.zip/children"},{"added":"1.0","ns":"clojure.zip","name":"remove","file":"clojure/zip.clj","type":"function","column":1,"see-alsos":null,"line":264,"examples":[{"updated-at":1558973394746,"created-at":1558973394746,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"body":"(require '[clojure.zip :as zip])\n\n(def vzip\n (zip/vector-zip\n [[1 2]\n [3 4 [5 10 [11 12]]]\n [13 14]])) ;; target for removal\n\n(-> vzip zip/down zip/rightmost zip/remove zip/root)\n;; [[1 2] [3 4 [5 10 [11 12]]]]","_id":"5cec0bd2e4b0ca44402ef72c"},{"editors":[{"login":"loeschzwerg","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/24317401?v=4"}],"body":"(use 'clojure.zip)\n;; def a tree struct\n;; .\n;; / \\\n;; . 0\n;; / \\\n;; 1 2\n(def tree\n (vector-zip\n [[1 2] 0]))\n\n;; #1 #2\n;; x x\n;; / \\ /|\\\n;; 1 0 1 - 0\n;; / \\\n;; 1 2\n\n;; #1\n(-> tree\n down\n (replace 1)\n up\n node) ;; => [1 0]\n;; #2\n(-> tree\n down\n (insert-left 1)\n remove ;; cut desired node\n up\n node) ;; => [1 0]","author":{"avatar-url":"https://avatars3.githubusercontent.com/u/24317401?v=4","account-source":"github","login":"loeschzwerg"},"created-at":1574337342956,"updated-at":1574337519515,"_id":"5dd67b3ee4b0ca44402ef7e7"}],"notes":null,"arglists":["loc"],"doc":"Removes the node at loc, returning the loc that would have preceded\n it in a depth-first walk.","library-url":"https://github.com/clojure/clojure","href":"/clojure.zip/remove"},{"added":"1.0","ns":"clojure.zip","name":"down","file":"clojure/zip.clj","type":"function","column":1,"see-alsos":[{"created-at":1455292674651,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"zipper","ns":"clojure.zip"},"_id":"56be0102e4b060004fc217c0"}],"line":109,"examples":[{"updated-at":1574335586383,"created-at":1574335586383,"author":{"login":"loeschzwerg","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/24317401?v=4"},"body":"(use 'clojure.zip)\n;; def a tree struct\n;; .\n;; / \\\n;; . 0\n;; / \\\n;; 1 2\n(def tree\n (vector-zip\n [[1 2] 0]))\n\n;; #0 #1 #2\n;; x . .\n;; / \\ / \\ / \\\n;; . 0 x 0 . 0\n;; / \\ / \\ / \\\n;; 1 2 1 2 x 2\n\n;; #0\n(-> tree\n node) ;; => [[1 2] 0]\n;; #1\n(-> tree\n down\n node) ;; => [1 2]\n;; #2\n(-> tree\n down\n down\n node) ;; => 1\n\n;; notice the leftmost child / first element","_id":"5dd67462e4b0ca44402ef7e5"}],"notes":null,"arglists":["loc"],"doc":"Returns the loc of the leftmost child of the node at this loc, or\n nil if no children","library-url":"https://github.com/clojure/clojure","href":"/clojure.zip/down"},{"added":"1.0","ns":"clojure.zip","name":"replace","file":"clojure/zip.clj","type":"function","column":1,"see-alsos":[{"created-at":1357860115000,"author":{"login":"juan.facorro","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d6f59d93cc17c698f16e550034a2d1ad?r=PG&default=identicon"},"to-var":{"ns":"clojure.zip","name":"edit","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521c4b"}],"line":203,"examples":[{"author":{"login":"Claj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5fd658a8d2ef549071cb5286b1b874aa?r=PG&default=identicon"},"editors":[],"body":"(use 'clojure.zip)\n\n(def vz (vector-zip [1 2 [73 88] 4]))\n\n(root (replace (-> vz down right right) 3))\n=>[1 2 3 4]","created-at":1329434106000,"updated-at":1329434106000,"_id":"542692d7c026201cdc327142"}],"notes":[{"author":{"login":"nsadeh","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/15837587?v=4"},"updated-at":1688429049053,"created-at":1688429049053,"body":"This throws an error if you replace the end node btw","_id":"64a361f9e4b08cf8563f4bd1"}],"arglists":["loc node"],"doc":"Replaces the node at this loc, without moving","library-url":"https://github.com/clojure/clojure","href":"/clojure.zip/replace"},{"added":"1.0","ns":"clojure.zip","name":"zipper","file":"clojure/zip.clj","type":"function","column":1,"see-alsos":[{"created-at":1329431493000,"author":{"login":"Claj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5fd658a8d2ef549071cb5286b1b874aa?r=PG&default=identicon"},"to-var":{"ns":"clojure.zip","name":"down","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d93"},{"created-at":1329431497000,"author":{"login":"Claj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5fd658a8d2ef549071cb5286b1b874aa?r=PG&default=identicon"},"to-var":{"ns":"clojure.zip","name":"up","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d94"},{"created-at":1329431508000,"author":{"login":"Claj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5fd658a8d2ef549071cb5286b1b874aa?r=PG&default=identicon"},"to-var":{"ns":"clojure.zip","name":"right","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d95"},{"created-at":1364881252000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.zip","name":"left","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d96"},{"created-at":1364881303000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.zip","name":"children","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d97"},{"created-at":1417358040306,"author":{"login":"abrooks","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/69976?v=2"},"to-var":{"ns":"clojure.zip","name":"node","library-url":"https://github.com/clojure/clojure"},"_id":"547b2ad8e4b0dc573b892fe5"},{"created-at":1455304623314,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"replace","ns":"clojure.zip"},"_id":"56be2fafe4b060004fc217c3"}],"line":18,"examples":[{"updated-at":1406155327000,"created-at":1287950611000,"body":";; Some clojure.zip functions will overwrite clojure.core's definitions\n(use 'clojure.zip)\n\n;; You may wish to require :as in order to avoid the above\n(require '[clojure.zip :as z])\n\n;; For the purposes of keeping the examples that follow clean,\n;; assume we have taken the former route: (use 'clojure.zip)\n\n(use 'clojure.pprint)\n(def p pprint)\n\nuser> (def z [[1 2 3] [4 [5 6] 7] [8 9]])\n#'user/z\n\nuser> (def zp (zipper vector? seq (fn [_ c] c) z))\n#'user/zp\n\nuser> zp\n[[[1 2 3] [4 [5 6] 7] [8 9]] nil]\n\nuser=> (p (-> zp down))\n[[1 2 3]\n {:l [],\n :pnodes [[[1 2 3] [4 [5 6] 7] [8 9]]],\n :ppath nil,\n :r ([4 [5 6] 7] [8 9])}]\n \nuser> (first (-> zp down))\n[1 2 3]\n\nuser=> (p (-> zp down right))\n[[4 [5 6] 7]\n {:l [[1 2 3]],\n :pnodes [[[1 2 3] [4 [5 6] 7] [8 9]]],\n :ppath nil,\n :r ([8 9])}]\n\nuser> (first (-> zp down right))\n[4 [5 6] 7]\n\nuser=> (p (-> zp down right down right))\n[[5 6]\n {:l [4],\n :pnodes [[[1 2 3] [4 [5 6] 7] [8 9]] [4 [5 6] 7]],\n :ppath\n {:l [[1 2 3]],\n :pnodes [[[1 2 3] [4 [5 6] 7] [8 9]]],\n :ppath nil,\n :r ([8 9])},\n :r (7)}]\n\nuser=> (p (-> zp down right down right down))\n[5\n {:l [],\n :pnodes [[[1 2 3] [4 [5 6] 7] [8 9]] [4 [5 6] 7] [5 6]],\n :ppath\n {:l [4],\n :pnodes [[[1 2 3] [4 [5 6] 7] [8 9]] [4 [5 6] 7]],\n :ppath\n {:l [[1 2 3]],\n :pnodes [[[1 2 3] [4 [5 6] 7] [8 9]]],\n :ppath nil,\n :r ([8 9])},\n :r (7)},\n :r (6)}]\n\nuser=> (p (-> zp down right down right (replace \"hello\")))\n[\"hello\"\n {:changed? true,\n :l [4],\n :pnodes [[[1 2 3] [4 [5 6] 7] [8 9]] [4 [5 6] 7]],\n :ppath\n {:l [[1 2 3]],\n :pnodes [[[1 2 3] [4 [5 6] 7] [8 9]]],\n :ppath nil,\n :r ([8 9])},\n :r (7)}]\n\nuser=> (p (-> zp down right down right (replace \"hello\") up))\n[(4 \"hello\" 7)\n {:changed? true,\n :l [[1 2 3]],\n :pnodes [[[1 2 3] [4 [5 6] 7] [8 9]]],\n :ppath nil,\n :r ([8 9])}]\n\nuser=> (p (-> zp down right down right (replace \"hello\") up root))\n([1 2 3] (4 \"hello\" 7) [8 9])","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2","account-source":"github","login":"zk"},{"avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3","account-source":"github","login":"devn"},{"avatar-url":"https://www.gravatar.com/avatar/e21945030cedebfd5b4a4f04ad3843e8?r=PG&default=identicon","account-source":"clojuredocs","login":"elben"}],"author":{"avatar-url":"https://www.gravatar.com/avatar/4bc423f6653d93f9185a5cdc9f5cd84f?r=PG&default=identicon","account-source":"clojuredocs","login":"bhenry"},"_id":"542692d1c026201cdc326f2e"},{"body":"(require '[clojure.zip :as zip])\n\n;; Adds zip support for maps.\n;; (Source: http://stackoverflow.com/a/15020649/42188)\n(defn map-zipper [m]\n (zip/zipper \n (fn [x] (or (map? x) (map? (nth x 1))))\n (fn [x] (seq (if (map? x) x (nth x 1))))\n (fn [x children] \n (if (map? x) \n (into {} children) \n (assoc x 1 (into {} children))))\n m))\n\n(def m {:a 3 :b {:x true :y false} :c 4})\n\n;; Note that hash-maps are not ordered:\n(-> (map-zipper m) zip/down zip/right zip/node)\n;;=> [:b {:y false, :x true}]\n\n;; Treat nodes as [key value] pairs:\n(-> (map-zipper m) \n zip/down\n (zip/edit (fn [[k v]] [k (inc v)]))\n zip/root)\n;;=> {:c 5, :b {:y false, :x true}, :a 3}","author":{"login":"muhuk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/40178?v=3"},"created-at":1423511905733,"updated-at":1423511905733,"_id":"54d91161e4b081e022073c72"},{"updated-at":1481022698534,"created-at":1480941951575,"author":{"login":"PetrGlad","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/124476?v=3"},"body":";; A version of zipper that allows mixing maps and vectors \n;; Note that it traverses map entries too\n(require '[clojure.zip :as z])\n(defn map-vec-zipper [m]\n (z/zipper\n (fn [x] (or (map? x) (sequential? x)))\n seq\n (fn [p xs]\n (if (isa? (type p) clojure.lang.MapEntry)\n (into [] xs)\n (into (empty p) xs)))\n m))\n(-> (map-vec-zipper [{1 [21 22] 3 [4]}])\n z/down\n (z/edit assoc :e 99)\n z/down\n ;; Note that the map does not guarantee particular entries ordering.\n z/down ;; Getting into map entry. \n z/next\n (z/edit conj 77)\n z/root)\n;;=> [{1 [21 22 77], 3 [4], :e 99}]","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/124476?v=3","account-source":"github","login":"PetrGlad"}],"_id":"5845617fe4b0782b632278d3"},{"updated-at":1481023902325,"created-at":1481023619209,"author":{"login":"PetrGlad","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/124476?v=3"},"body":";; Get sequence of all visited nodes\n(require '[clojure.zip :as z])\n(->> (z/vector-zip [[1 2] 3 [[4 5]]])\n (iterate z/next)\n (take-while #(not (z/end? %))) ;; Zipper's \"end of iteration\" condition. \n (map z/node))\n;;=> ([[1 2] 3 [[4 5]]] \n;; [1 2] \n;; 1 2\n;; 3 \n;; [[4 5]] \n;; [4 5]\n;; 4 5)","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/124476?v=3","account-source":"github","login":"PetrGlad"}],"_id":"5846a083e4b0782b632278d9"}],"notes":[{"updated-at":1287977279000,"body":"For more info on zippers:\r\n\r\n* [Brian Marick](http://clojuredocs.org/profile/Brian%20Marick): [“Editingâ€� trees in Clojure with clojure.zip](http://www.exampler.com/blog/2010/09/01/editing-trees-in-clojure-with-clojurezip/)\r\n* Alex Miller: [Zippers with records in Clojure](http://tech.puredanger.com/2010/10/22/zippers-with-records-in-clojure/)","created-at":1287977279000,"author":{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"},"_id":"542692ecf6e94c6970521f9e"},{"updated-at":1333789044000,"body":"Tutorials on zippers:\r\n\r\n* Brian Marick: [\"Editing\" trees in Clojure with clojure.zip](http://www.exampler.com/blog/2010/09/01/editing-trees-in-clojure-with-clojurezip)\r\n\r\n* Alex Miller: [Zippers with records in Clojure](http://tech.puredanger.com/2010/10/22/zippers-with-records-in-clojure/)","created-at":1333787145000,"author":{"login":"jafingerhut","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/109629?v=3"},"_id":"542692ecf6e94c6970521fdd"},{"author":{"login":"PetrGlad","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/124476?v=3"},"updated-at":1480942234308,"created-at":1480942234308,"body":"To work with nested structures you can also use\n* clojure.core/get-in, clojure.core/assoc-in, clojure.core/update-in \n* Balagan library https://github.com/clojurewerkz/balagan\n* Specter library https://github.com/nathanmarz/specter ","_id":"5845629ae4b0782b632278d4"}],"arglists":["branch? children make-node root"],"doc":"Creates a new zipper structure. \n\n branch? is a fn that, given a node, returns true if can have\n children, even if it currently doesn't.\n\n children is a fn that, given a branch node, returns a seq of its\n children.\n\n make-node is a fn that, given an existing node and a seq of\n children, returns a new branch node with the supplied children.\n root is the root node.","library-url":"https://github.com/clojure/clojure","href":"/clojure.zip/zipper"},{"added":"1.0","ns":"clojure.zip","name":"end?","file":"clojure/zip.clj","type":"function","column":1,"see-alsos":[{"created-at":1455299357645,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"zipper","ns":"clojure.zip"},"_id":"56be1b1de4b0b0491b9ed179"}],"line":258,"examples":null,"notes":null,"arglists":["loc"],"doc":"Returns true if loc represents the end of a depth-first walk","library-url":"https://github.com/clojure/clojure","href":"/clojure.zip/end_q"},{"added":"1.0","ns":"clojure.zip","name":"edit","file":"clojure/zip.clj","type":"function","column":1,"see-alsos":[{"created-at":1448013007225,"author":{"login":"damianfijorek","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/963492?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"root","ns":"clojure.zip"},"_id":"564eeccfe4b0be225c0c4797"},{"created-at":1455304694999,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"zipper","ns":"clojure.zip"},"_id":"56be2ff6e4b0b0491b9ed17a"},{"created-at":1574336768778,"author":{"login":"loeschzwerg","account-source":"github","avatar-url":"https://avatars3.githubusercontent.com/u/24317401?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"replace","ns":"clojure.zip"},"_id":"5dd67900e4b0ca44402ef7e6"}],"line":210,"examples":[{"updated-at":1447940484310,"created-at":1447940484310,"author":{"login":"damianfijorek","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/963492?v=3"},"body":"(require '[clojure.xml :as xml]\n '[clojure.zip :as zip])\n\n;; get xml with content added to root child\n(let [root (zip/xml-zip (xml/parse-str \"\"))\n child (zip/down root)\n new-child (zip/edit child #(assoc-in % [:content] \"content\"))\n new-root (zip/root new-child)]\n (xml/emit-str new-root))\n;;=> \"content\"","_id":"564dd184e4b0538444398273"}],"notes":null,"arglists":["loc f & args"],"doc":"Replaces the node at this loc with the value of (f node args)","library-url":"https://github.com/clojure/clojure","href":"/clojure.zip/edit"},{"added":"1.0","ns":"clojure.zip","name":"make-node","file":"clojure/zip.clj","type":"function","column":1,"see-alsos":null,"line":83,"examples":[{"updated-at":1559115957031,"created-at":1559073900810,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"body":";; Useful to perform operations on locations without knowing the\n;; internals of the zipper. For example, here's a generic remove-child to remove\n;; the first children from a node\n(require '[clojure.zip :as zip])\n\n(def vzip\n (zip/vector-zip\n [[1 2]\n [3 4 [5 10 [11 12]]]\n [13 14]]))\n\n(defn remove-child [loc]\n (zip/replace loc \n (zip/make-node loc (zip/node loc) (rest (zip/children loc)))))\n\n(-> vzip zip/down zip/rightmost remove-child zip/root)\n;; [[1 2] [3 4 [5 10 [11 12]]] [14]]","editors":[{"avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4","account-source":"github","login":"reborg"}],"_id":"5ced946ce4b0ca44402ef730"}],"notes":null,"arglists":["loc node children"],"doc":"Returns a new branch node, given an existing node and new\n children. The loc is only used to supply the constructor.","library-url":"https://github.com/clojure/clojure","href":"/clojure.zip/make-node"},{"added":"1.0","ns":"clojure.zip","name":"vector-zip","file":"clojure/zip.clj","type":"function","column":1,"see-alsos":[{"created-at":1283300922000,"author":{"login":"Chouser","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/7a0192050ed6488670acfd3f59405c10?r=PG&default=identicon"},"to-var":{"ns":"clojure.zip","name":"seq-zip","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d72"},{"created-at":1283300949000,"author":{"login":"Chouser","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/7a0192050ed6488670acfd3f59405c10?r=PG&default=identicon"},"to-var":{"ns":"clojure.zip","name":"xml-zip","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d73"},{"created-at":1320037497000,"author":{"login":"Arnoldo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3a60ef262d016a9a38f5268e088ab32?r=PG&default=identicon"},"to-var":{"ns":"clojure.zip","name":"next","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d74"},{"created-at":1320037502000,"author":{"login":"Arnoldo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3a60ef262d016a9a38f5268e088ab32?r=PG&default=identicon"},"to-var":{"ns":"clojure.zip","name":"end?","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521d75"}],"line":44,"examples":[{"author":{"login":"Arnoldo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3a60ef262d016a9a38f5268e088ab32?r=PG&default=identicon"},"editors":[{"login":"Arnoldo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3a60ef262d016a9a38f5268e088ab32?r=PG&default=identicon"},{"login":"Arnoldo","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/3a60ef262d016a9a38f5268e088ab32?r=PG&default=identicon"},{"login":"Jules","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/77c985628bea3a3ff10e76cefcc929c4?r=PG&default=identicon"}],"body":"\n(require '[clojure.zip :as zip])\n\n(defn zip-map [f loc]\n \" Map f over every node of the zipper.\n The function received has the form (f node-value loc),\n the node value and its location\"\n (loop [z loc]\n (if (zip/end? z)\n (zip/root z) ; perhaps you can call zip/seq-zip or zip/vector-zip?\n (recur (zip/next (zip/edit z f z))))))\n\n;; Multiply by 100 every node in the tree\nuser=> (zip-map (fn [n nx] (if (vector? n) n (* n 100) )) (zip/vector-zip '[5 [10 20 30] [1 2 3] ]))\n;; Be careful! the returned result by zip/root is not a zipper anymore!\n[500 [1000 2000 3000] [100 200 300]]\n","created-at":1320036944000,"updated-at":1373138099000,"_id":"542692d7c026201cdc327144"},{"updated-at":1587100167390,"created-at":1587100167390,"author":{"login":"funkrider","account-source":"github","avatar-url":"https://avatars2.githubusercontent.com/u/12958644?v=4"},"body":";; It may not be obvious however it is worth pointing out that \n;; this implementation assumes that all vectors are branches, \n;; and all non vector data is therefore a leaf node. \n\n;; A vector \"Tree\" [5 [10 20 30] [1 2 3]]) can be visualised as\n;;\n;; --- ♦ ---\n;; / | \\\n;; 5 ♦ ♦\n;; / | \\ / | \\\n;; 10 20 30 1 2 3\n\n;; If you want to put data into a branch node for example a binary tree\n;; you can not use the default zip/vector-zip. Rather you need use zip/zipper\n;; and give a new children function to specify where the children are.\n;; See: https://stackoverflow.com/questions/26268098/can-someone-give-an-example-of-how-edit-function-for-clojure-zip-works","_id":"5e993a07e4b087629b5a18d4"}],"notes":null,"arglists":["root"],"doc":"Returns a zipper for nested vectors, given a root vector","library-url":"https://github.com/clojure/clojure","href":"/clojure.zip/vector-zip"},{"added":"1.0","ns":"clojure.zip","name":"node","file":"clojure/zip.clj","type":"function","column":1,"see-alsos":null,"line":64,"examples":[{"author":{"login":"Victor","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bc41ebab54cc0e0fbe99d753876d45ce?r=PG&default=identicon"},"editors":[{"login":"Victor","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bc41ebab54cc0e0fbe99d753876d45ce?r=PG&default=identicon"},{"login":"Victor","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bc41ebab54cc0e0fbe99d753876d45ce?r=PG&default=identicon"}],"body":"user=>(require '[clojure.zip :as zip])\nnil\nuser=> (def original [1 '(a b c) 2])\n#'user/original\nuser=> (def root-loc (zip/seq-zip (seq original)))\n#'user/root-loc\n\nuser=> (zip/node (zip/down root-loc))\n1\n","created-at":1291935344000,"updated-at":1291935456000,"_id":"542692d1c026201cdc326f32"}],"notes":[{"updated-at":1291935491000,"body":"See tutorial of clojure.zip at \r\nhttp://www.exampler.com/blog/2010/09/01/editing-trees-in-clojure-with-clojurezip/","created-at":1291935491000,"author":{"login":"Victor","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bc41ebab54cc0e0fbe99d753876d45ce?r=PG&default=identicon"},"_id":"542692ecf6e94c6970521fad"}],"arglists":["loc"],"doc":"Returns the node at loc","library-url":"https://github.com/clojure/clojure","href":"/clojure.zip/node"},{"added":"1.0","ns":"clojure.zip","name":"up","file":"clojure/zip.clj","type":"function","column":1,"see-alsos":[{"created-at":1283300764000,"author":{"login":"Chouser","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/7a0192050ed6488670acfd3f59405c10?r=PG&default=identicon"},"to-var":{"ns":"clojure.zip","name":"down","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cda"},{"created-at":1283300777000,"author":{"login":"Chouser","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/7a0192050ed6488670acfd3f59405c10?r=PG&default=identicon"},"to-var":{"ns":"clojure.zip","name":"left","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cdb"},{"created-at":1283300781000,"author":{"login":"Chouser","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/7a0192050ed6488670acfd3f59405c10?r=PG&default=identicon"},"to-var":{"ns":"clojure.zip","name":"right","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cdc"},{"created-at":1283300826000,"author":{"login":"Chouser","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/7a0192050ed6488670acfd3f59405c10?r=PG&default=identicon"},"to-var":{"ns":"clojure.zip","name":"next","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cdd"},{"created-at":1283300881000,"author":{"login":"Chouser","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/7a0192050ed6488670acfd3f59405c10?r=PG&default=identicon"},"to-var":{"ns":"clojure.zip","name":"seq-zip","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521cde"},{"created-at":1413255010369,"author":{"login":"tway24","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/9206853?v=2"},"to-var":{"ns":"clojure.zip","name":"zipper","library-url":"https://github.com/clojure/clojure"},"_id":"543c8f62e4b001b88094c7ef"}],"line":123,"examples":null,"notes":null,"arglists":["loc"],"doc":"Returns the loc of the parent of the node at this loc, or nil if at\n the top","library-url":"https://github.com/clojure/clojure","href":"/clojure.zip/up"},{"added":"1.0","ns":"clojure.zip","name":"insert-right","file":"clojure/zip.clj","type":"function","column":1,"see-alsos":null,"line":193,"examples":[{"body":";;; zip is not default required in clj\n(require '[clojure.zip :as zip])\n\n(def root-tree (zip/seq-zip '(:root (:1st-left-child ) (:1st-right-child\n))))\n\n;;; get the location , in this case is the root of the tree\n(def location (-> root-tree zip/next))\n\n\n(zip/insert-right location :inserted)\n\n;; = > [:root\n;; {:changed? true,\n;; :l [],\n;; :pnodes [(:root (:1st-left-child) (:1st-right-child))],\n;; :ppath nil,\n;; :r (:inserted (:1st-left-child) (:1st-right-child))}]","author":{"login":"zacyang","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/898449?v=3"},"created-at":1433170538137,"updated-at":1433170538137,"_id":"556c726ae4b03e2132e7d183"}],"notes":null,"arglists":["loc item"],"doc":"Inserts the item as the right sibling of the node at this loc,\n without moving","library-url":"https://github.com/clojure/clojure","href":"/clojure.zip/insert-right"},{"added":"1.0","ns":"clojure.zip","name":"rights","file":"clojure/zip.clj","type":"function","column":1,"see-alsos":null,"line":102,"examples":null,"notes":null,"arglists":["loc"],"doc":"Returns a seq of the right siblings of this loc","library-url":"https://github.com/clojure/clojure","href":"/clojure.zip/rights"},{"added":"1.0","ns":"clojure.zip","name":"root","file":"clojure/zip.clj","type":"function","column":1,"see-alsos":[{"created-at":1448013056620,"author":{"login":"damianfijorek","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/963492?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"edit","ns":"clojure.zip"},"_id":"564eed00e4b0be225c0c4798"}],"line":137,"examples":[{"updated-at":1729541739548,"created-at":1729540959240,"author":{"login":"claj","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/353113?v=4"},"body":"(ns zipexample (:require [clojure.zip :as z]))\n\n;; Example use of zipper to edit a vector with not so straight-forward rules\n;; (no children/bransches are used in this case!)\n\n;; Lets assume we have some more or less unstructured facts about animals\n;; that we want to put together as some report (maybe as HTML later on).\n\n(def example-data\n [{:header \"Elephants\"\n :text \"Elephants are the only mammals that can’t jump!\"\n :category :elephant\n :original-id 1}\n {:header \"Sloths\"\n :text \"Sloths are so slow that algae can grow on their fur!\"\n :category :sloth\n :original-id 2}\n {:header \"Octopuses\"\n :text \"An octopus has three hearts and blue blood!\"\n :page-break? true\n :category :octopus\n :original-id 3}\n {:header \"Penguins\"\n :text \"Penguins propose to their mates by giving them a pebble!\"\n :category :penguin\n :original-id 4}\n {:type :something-unrelated\n :original-id 5}\n {:image \"elephant.jpg\"\n :category :elephant\n :original-id 6}\n {:text \"Famous octopus monster: Kraken\"\n :category :octopus\n :original-id 7}\n {:text \"Cats\"\n :category :cat\n :original-id 8}])\n\n;; Some arbitrary rules that can be seen in the wild:\n\n;; 1. A :page-break? key in an item should be converted to a\n;; separate page-break entity {:type :page-break} before the item.\n\n;; 2. Everything in the same :category should be placed together,\n;; at the place where the category first occurs.\n\n;; 3. Everything else should be left as is un-touched and in order.\n\n;; Since we are moving a lot of stuff around, it would be nice\n;; if we could move things around and insert stuff in between other items etc.\n\n;; We can do this with zippers:\n\n;; current structure [{ }, { }, { }, { }, { }, { }, { }, { }]\n\n;; The rules above as functions taking and returning a zipper location\n\n(defn maybe-insert-page-break \n \"inserts a pagebreak before an item with :page-break? true.\"\n [loc]\n\n ;; ... {:page-break? true :a :b ...}, ... ->\n ;; ... {:type :page-break}, {:a :b ...}, ...\n\n (let [current-node (z/node loc)]\n (if (:page-break? current-node)\n (-> loc\n (z/insert-left {:type :page-break})\n (z/edit dissoc :page-break?)) ;;important!\n loc)))\n\n(defn maybe-sort-item\n \"If the location has a :category and is not already :sorted?\n search for the latest earlier node with the same category\n and put the item after that node.\n\n NOTE that this sorting has quadratic complexity, which \n means it scales bad for larger collections.\"\n [original-loc]\n (let [current-node (z/node original-loc)\n current-category (:category current-node)]\n \n ;; to avoid eternal loops we add a :sorted? key on\n ;; all items that has been exposed to this sorting process\n (if (or (:sorted? current-node)\n (not current-category))\n ;; do nothing, return original location\n original-loc\n ;; we have some category on current node\n ;; create a new collection where the current item\n ;; is not there\n (loop [loc-back (z/remove original-loc)]\n ;; remove current node and move back one step\n (if (nil? loc-back)\n ;; if loc is nil we are now at the beginning of the collection.\n ;; Abort mission!\n ;; [_*_ { }, ... ] \n ;; return the original loc, but with :sorted? true\n ;; set on the item. All this walk backwards is discarded,\n ;; (thanks to our persistent data structures).\n (z/edit original-loc assoc :sorted? true)\n\n ;; there was some earlier node, compare the category\n (let [compare-node (z/node loc-back)]\n ;; ... {:category :X :prev :node :sorted? true} ...\n (if (= (:category compare-node ::no-category) current-category)\n ;; same category found! insert the current node\n ;; after this found node!\n ;; ... {:category :X :prev :node :sorted? true}, {:category :X :sorted? true} ...\n ;; we continue in the outer loop, where :sorted? true are ignored\n (z/insert-right loc-back (assoc current-node :sorted? true))\n \n ;; else continue the backwards search!\n (recur (z/left loc-back)))))))))\n\n(defn process [data]\n ;; we start here: [ *{ }*, { }, { }, { }, { }, { }, { }, { }] \n (loop [loc (z/down (z/vector-zip data))] \n (let [loc (-> loc\n (maybe-insert-page-break)\n (maybe-sort-item)\n ;; add more rules here!\n ) \n next-loc (z/right loc)]\n\n ;; nil means we are at the end of the collection,\n (if (some? next-loc)\n ;; continue with next location until done.\n (recur next-loc)\n ;; no next location, we have reached the end of the collection:\n ;; run clojure.zip/root which realizes the whole collection with all edits\n (z/root loc)))))\n\n(def end-result (process example-data))\n;;=>\n\n[{:header \"Elephants\",\n :text \"Elephants are the only mammals that can’t jump!\",\n :category :elephant,\n :original-id 1,\n :sorted? true}\n ;;elephant image moved to the first occurence of :elephant.\n {:image \"elephant.jpg\",\n :category :elephant,\n :original-id 6,\n :sorted? true}\n\n {:header \"Sloths\",\n :text \"Sloths are so slow that algae can grow on their fur!\",\n :category :sloth,\n :original-id 2,\n :sorted? true}\n \n {:type :page-break}\n ;; a page break item was inserted before this item:\n {:header \"Octopuses\",\n :text \"An octopus has three hearts and blue blood!\",\n :category :octopus,\n :original-id 3,\n :sorted? true}\n ;; this was moved to it's first :octopus\n {:text \"Famous octopus monster: Kraken\",\n :category :octopus,\n :original-id 7,\n :sorted? true}\n\n ;; untouched \n {:header \"Penguins\",\n :text \"Penguins propose to their mates by giving them a pebble!\",\n :category :penguin,\n :original-id 4,\n :sorted? true}\n ;; untouched\n {:type :something-unrelated, :original-id 5}\n\n ;; ...\n ;; things here was moved\n ;; ...\n\n ;; untouched\n {:text \"Cats\", :category :cat, :original-id 8, :sorted? true}]\n\n\n;; We need to put various markers like :sorted? on items to avoid eternal loops.\n;; This is common in mutable algorithms, but almost never needed \n;; when using functional algoritms on persistent data structures.\n\n;; Apart from this I think it is quite apparent how to add more rules\n;; to the processing while keeping the code not too weird.\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/353113?v=4","account-source":"github","login":"claj"}],"_id":"6716b35f69fbcc0c22617508"}],"notes":null,"arglists":["loc"],"doc":"zips all the way up and returns the root node, reflecting any\n changes.","library-url":"https://github.com/clojure/clojure","href":"/clojure.zip/root"},{"added":"1.0","ns":"clojure.zip","name":"next","file":"clojure/zip.clj","type":"function","column":1,"see-alsos":[{"created-at":1559164398312,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"prev","ns":"clojure.zip"},"_id":"5ceef5eee4b0ca44402ef736"}],"line":230,"examples":[{"updated-at":1559164278848,"created-at":1559164278848,"author":{"login":"reborg","account-source":"github","avatar-url":"https://avatars1.githubusercontent.com/u/20086?v=4"},"body":";; zip-walk takes a transformation function f and a zipper z.\n;; f takes a location and returns location. Applies f\n;; to the nodes in the zipper maintaining the original nesting.\n\n(require '[clojure.zip :as zip])\n\n(defn zip-walk [f z]\n (if (zip/end? z)\n (zip/root z)\n (recur f (zip/next (f z)))))\n\n(zip-walk\n (fn [loc] \n (if (zip/branch? loc) \n loc \n (zip/edit loc * 2)))\n (zip/vector-zip [1 2 [3 4]]))\n\n;; [2 4 [6 8]]\n","_id":"5ceef576e4b0ca44402ef735"}],"notes":null,"arglists":["loc"],"doc":"Moves to the next loc in the hierarchy, depth-first. When reaching\n the end, returns a distinguished loc detectable via end?. If already\n at the end, stays there.","library-url":"https://github.com/clojure/clojure","href":"/clojure.zip/next"},{"added":"1.0","ns":"clojure.zip","name":"seq-zip","file":"clojure/zip.clj","type":"function","column":1,"see-alsos":[{"created-at":1283300897000,"author":{"login":"Chouser","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/7a0192050ed6488670acfd3f59405c10?r=PG&default=identicon"},"to-var":{"ns":"clojure.zip","name":"xml-zip","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e84"},{"created-at":1283300907000,"author":{"login":"Chouser","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/7a0192050ed6488670acfd3f59405c10?r=PG&default=identicon"},"to-var":{"ns":"clojure.zip","name":"vector-zip","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e85"}],"line":35,"examples":[{"author":{"login":"Ljos","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/45b996a79abca465acaf6c0f10b0437?r=PG&default=identicon"},"editors":[],"body":"user=> (require '[clojure.zip :as zip])\r\nnil\r\nuser=> (def zz (zip/seq-zip '(a b (c d e) (f (g h) i) j)))\r\n#'user/zz\r\nuser=> zz\r\n[(a b (c d e) (f (g h) i) j) nil]","created-at":1320013293000,"updated-at":1320013293000,"_id":"542692d7c026201cdc327143"}],"notes":null,"arglists":["root"],"doc":"Returns a zipper for nested sequences, given a root sequence","library-url":"https://github.com/clojure/clojure","href":"/clojure.zip/seq-zip"},{"added":"1.0","ns":"clojure.zip","name":"insert-left","file":"clojure/zip.clj","type":"function","column":1,"see-alsos":[{"created-at":1433170800901,"author":{"login":"zacyang","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/898449?v=3"},"to-var":{"ns":"clojure.zip","name":"insert-right","library-url":"https://github.com/clojure/clojure"},"_id":"556c7370e4b03e2132e7d184"}],"line":183,"examples":[{"body":";;; zip is not default required in clj\n(require '[clojure.zip :as zip])\n\n(def root-tree (zip/seq-zip '(:root (:1st-left-child ) (:1st-right-child\n))))\n\n;;; get the location , in this case is the root of the tree\n(def location (-> root-tree zip/next))\n\n\n(zip/insert-left location :inserted)\n\n;;; then the :inserted is on the left of the original tree\n;;;=>[:root\n;;; {:changed? true,\n;;; :l [:inserted],\n;;; :pnodes [(:root (:1st-left-child) (:1st-right-child))],\n;;; :ppath nil,\n;;; :r ((:1st-left-child) (:1st-right-child))}]","author":{"login":"zacyang","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/898449?v=3"},"created-at":1433170211818,"updated-at":1433170211818,"_id":"556c7123e4b01ad59b65f4ec"}],"notes":null,"arglists":["loc item"],"doc":"Inserts the item as the left sibling of the node at this loc,\n without moving","library-url":"https://github.com/clojure/clojure","href":"/clojure.zip/insert-left"},{"added":"1.0","ns":"clojure.zip","name":"prev","file":"clojure/zip.clj","type":"function","column":1,"see-alsos":null,"line":246,"examples":null,"notes":null,"arglists":["loc"],"doc":"Moves to the previous loc in the hierarchy, depth-first. If already\n at the root, returns nil.","library-url":"https://github.com/clojure/clojure","href":"/clojure.zip/prev"},{"added":"1.0","ns":"clojure.zip","name":"right","file":"clojure/zip.clj","type":"function","column":1,"see-alsos":[{"created-at":1455292718902,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=3"},"to-var":{"library-url":"https://github.com/clojure/clojure","name":"zipper","ns":"clojure.zip"},"_id":"56be012ee4b0b0491b9ed177"}],"line":149,"examples":null,"notes":null,"arglists":["loc"],"doc":"Returns the loc of the right sibling of the node at this loc, or nil","library-url":"https://github.com/clojure/clojure","href":"/clojure.zip/right"},{"added":"1.0","ns":"clojure.zip","name":"lefts","file":"clojure/zip.clj","type":"function","column":1,"see-alsos":[{"created-at":1358376302000,"author":{"login":"juan.facorro","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/d6f59d93cc17c698f16e550034a2d1ad?r=PG&default=identicon"},"to-var":{"ns":"clojure.zip","name":"rights","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b4f"}],"line":96,"examples":[{"author":{"login":"Claj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5fd658a8d2ef549071cb5286b1b874aa?r=PG&default=identicon"},"editors":[],"body":"(def vz (vector-zip [1 2 3 4 5]))\n\n;; root\n;; |________\n;; | | | | |\n;; 1 2[3]4 5\n\n;;go down and then right twice, what's to the left of me now?\n(-> vz down right right lefts)\n=>(1 2)\n\n;;equivalent:\n(-> vz down right right rights)\n=>(4 5)\n\n","created-at":1329433215000,"updated-at":1329433215000,"_id":"542692d7c026201cdc327141"}],"notes":null,"arglists":["loc"],"doc":"Returns a seq of the left siblings of this loc","library-url":"https://github.com/clojure/clojure","href":"/clojure.zip/lefts"},{"added":"1.0","ns":"clojure.zip","name":"xml-zip","file":"clojure/zip.clj","type":"function","column":1,"see-alsos":[{"created-at":1413924240105,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"},"to-var":{"ns":"clojure.xml","name":"parse","library-url":"https://github.com/clojure/clojure"},"_id":"5446c590e4b03d20a1024275"}],"line":53,"examples":[{"author":{"login":"Claj","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/5fd658a8d2ef549071cb5286b1b874aa?r=PG&default=identicon"},"editors":[],"body":"(def xmlzipper (clojure.zip/xml-zip (clojure.xml/parse \"resources/somedata.xml\")))\n\n;;make a zippper pointing at the children to the topnode in somedata.xml\n(clojure.zip/children xmlzipper)\n\n \n\n\n\n\n","created-at":1323729937000,"updated-at":1323729937000,"_id":"542692d7c026201cdc327148"},{"updated-at":1413924196033,"created-at":1335333199000,"body":"(require '[clojure.zip :as z])\n\n;; The following example make use of an xml-tree ...\n;; foo barbar\n;; Notice that the xml-parse will not produce the exact \n;; xml object as the \"foo\" and \"bar\" strings are combined.\n\n;; Travel over the zipper in classic lisp style\n(z/right\n (z/down\n (z/xml-zip \n {:tag :root :content [{:tag :any :content [\"foo\" \"bar\"]} \"bar\"]})))\n\n;;=> [\"bar\" {:l [{:content [\"foo\" \"bar\"], :tag :any}], \n;;+> :pnodes [{:content [{:content [\"foo\" \"bar\"], :tag :any} \"bar\"], :tag :root}],\n;;+> :ppath nil, :r nil}]\n\n;; The above can also be written like this using the thread macro style\n(->{:tag :root :content [{:tag :any :content [\"foo\" \"bar\"]} \"bar\"]}\n z/xml-zip \n z/down \n z/right)\n\n;;=> [\"bar\" {:l [{:content [\"foo\" \"bar\"], :tag :any}], \n;;+> :pnodes [{:content [{:content [\"foo\" \"bar\"], :tag :any} \"bar\"], :tag :root}],\n;;+> :ppath nil, :r nil}]\n","editors":[{"avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2","account-source":"github","login":"phreed"}],"author":{"avatar-url":"https://avatars.githubusercontent.com/u/10421?v=3","account-source":"github","login":"devn"},"_id":"542692d7c026201cdc327149"},{"body":"(require '[clojure.xml :as xml]\n '[clojure.zip :as zip])\n\n;; Looking at the whole zipper is usually not the goal.\n;; Here is a case where the \"bar\" element is extracted.\n;; The following is derived from the following xml.\n;; foobar\n(->{:tag :root :content [{:tag :any :content [\"foo\"]} \"bar\"]}\n zip/xml-zip\n zip/down\n zip/right\n zip/node)\n;;=> \"bar\"\n\n;; The following shows a slightly larger example including the parser.\n(def data\n \"\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \" )\n\n;; Here is an example of the parser in action\n(def xml-tree\n (-> data \n .getBytes \n java.io.ByteArrayInputStream. \n xml/parse ))\n\n;; Traversing the xml using a zipper\n(-> xml-tree\n zip/xml-zip \n zip/down\n zip/down\n zip/down\n zip/node\n )\n;;=> {:tag :geom, :attrs {:name \"ab1x\"}, :content nil}","author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"},"created-at":1413923803557,"updated-at":1413923803557,"_id":"5446c3dbe4b03d20a1024274"}],"notes":[{"body":"There are also other libraries for processing xml that provide additional features.\nhttps://github.com/clojure/data.xml","created-at":1413924401226,"updated-at":1413924401226,"author":{"login":"phreed","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/211644?v=2"},"_id":"5446c631e4b0dc573b892fa4"}],"arglists":["root"],"doc":"Returns a zipper for xml elements (as from xml/parse),\n given a root element","library-url":"https://github.com/clojure/clojure","href":"/clojure.zip/xml-zip"}]} \ No newline at end of file diff --git a/tools/spec_coverage.py b/tools/spec_coverage.py deleted file mode 100644 index 7fe688a..0000000 --- a/tools/spec_coverage.py +++ /dev/null @@ -1,123 +0,0 @@ -#!/usr/bin/env python3 -"""Generate docs/spec/coverage.md — the spec status dashboard. - -Cross-references three sources: - 1. tools/clojuredocs-export.json — the clojure.core var inventory (the surface) - 2. jolt's interned clojure.core mappings (via bin/joltc) - 3. symbols exercised by the conformance corpus + unit cases - -Run from the repo root: python3 tools/spec_coverage.py -""" -import json, re, subprocess, datetime -from collections import Counter - -# --- 1. the surface -------------------------------------------------------- -data = json.load(open('tools/clojuredocs-export.json')) -core = sorted(v['name'] for v in data['vars'] if v['ns'] == 'clojure.core') -examples = {v['name'] for v in data['vars'] - if v['ns'] == 'clojure.core' and v.get('examples')} - -# --- 2. what jolt provides --------------------------------------------------- -# Two notions: INTERNED (in clojure.core's interns — visible to ns -# introspection) and RESOLVABLE (usable in code; some seed fns resolve through -# fallback paths without being interned — itself a conformance finding). -probe = '''(let [names (clojure.string/split-lines (slurp "/tmp/spec-surface-names.txt")) - interned (set (map name (keys (ns-interns (quote clojure.core)))))] - (doseq [n names] - (when (seq n) - (when (contains? interned n) (println "I" n)) - (when (some? (resolve (symbol n))) (println "R" n)))))''' -open('/tmp/spec-surface-names.txt','w').write('\n'.join(core)) -out = subprocess.run(['bin/joltc', '-e', probe], capture_output=True, text=True) -interned = {l[2:] for l in out.stdout.splitlines() if l.startswith('I ')} -resolvable = {l[2:] for l in out.stdout.splitlines() if l.startswith('R ')} -jolt = interned | resolvable - -# --- 3. what the tests exercise -------------------------------------------- -tested = set() -test_text = '' -# A var counts as tested when its name appears as a WHOLE TOKEN anywhere in -# the test sources (assertions live inside strings, so call-position-only -# matching missed *1, +', ., .., /, and bare transducer refs like cat). -SYMCHARS = r"\w*+!?<>=_.'/-" -def token_re(name): - return re.compile('(?','remove-tap','set-error-handler!','set-error-mode!'} -STM = {'dosync','ref','ref-set','alter','commute','ensure','ref-history-count', - 'ref-max-history','ref-min-history','sync','io!'} -JVM = {'class','class?','cast','bases','supers','compile','add-classpath', - 'definline','bean','accessor','create-struct','defstruct','struct', - 'struct-map','amap','areduce','memfn','enumeration-seq','iterator-seq', - 'resultset-seq','print-ctor','print-dup','print-method','print-simple', - 'primitives-classnames','vector-of','PrintWriter-on', - 'StackTraceElement->vec','Throwable->map','Inst','->ArrayChunk','->Vec', - '->VecNode','->VecSeq','-cache-protocol-fn','-reset-methods','EMPTY-NODE', - 'method-sig','proxy-name','gen-class','gen-interface','find-protocol-impl', - 'find-protocol-method','with-loading-context','load','load-file', - 'load-reader','loaded-libs','requiring-resolve','default-data-readers', - '..','.','pcalls','pmap','pvalues','stream-into!','stream-reduce!', - 'stream-seq!','stream-transduce!','mix-collection-hash','iteration', - 'unquote','unquote-splicing'} - -def classify(n): - if n in jolt: - return 'implemented+tested' if token_re(n).search(test_text) else 'implemented-untested' - if re.match(r'^\*.*\*$', n): return 'dynamic-var' - if n in SPECIAL: return 'special-form' - if n in AGENTS: return 'agents-taps' - if n in STM: return 'stm-refs' - if n in JVM: return 'jvm-specific' - return 'missing-portable' - -cls = {n: classify(n) for n in core} -counts = Counter(cls.values()) -stamp = datetime.date.today().isoformat() - -rows = [] -for n in core: - rows.append(f"| `{n}` | {cls[n]} | {'✓' if n in examples else ''} |") - -md = f"""# Appendix A — Coverage Dashboard (generated) - -Generated {stamp} by `tools/spec_coverage.py` — do not edit by hand. - -Surface: **{len(core)}** clojure.core vars (ClojureDocs export; {len(examples)} with -community examples). jolt interns {len(jolt & set(core))} of them. - -| Status | Count | Meaning | -|---|---|---| -| implemented+tested | {counts['implemented+tested']} | in jolt and exercised by spec/conformance | -| implemented-untested | {counts['implemented-untested']} | in jolt, no direct test — spec entries will add them | -| resolvable-not-interned | {len((resolvable - interned) & set(core) - SPECIAL)} | works in code but invisible to ns introspection (conformance finding) | -| missing-portable | {counts['missing-portable']} | portable semantics, jolt lacks it — implementation gap | -| special-form | {counts['special-form']} | specified in §3, not a library var | -| dynamic-var | {counts['dynamic-var']} | classification needed: portable default vs host-dependent | -| agents-taps | {counts['agents-taps']} | out of scope pending concurrency design note | -| stm-refs | {counts['stm-refs']} | out of scope pending concurrency design note | -| jvm-specific | {counts['jvm-specific']} | catalogued, not specified | - -Classifications are initial and mechanical — reclassifying is an ordinary -spec change. A var is *Verified* only when its §9 entry exists and carries no -UNVERIFIED field; that column will be added as entries land. - -## Per-var status - -| Var | Status | ClojureDocs examples | -|---|---|---| -{chr(10).join(rows)} -""" -open('docs/spec/coverage.md', 'w').write(md) -print(f"wrote docs/spec/coverage.md — {len(core)} vars") -for k, v in counts.most_common(): print(f" {k}: {v}") diff --git a/vendor/clojure-test-suite b/vendor/clojure-test-suite index 489b674..e20ea02 160000 --- a/vendor/clojure-test-suite +++ b/vendor/clojure-test-suite @@ -1 +1 @@ -Subproject commit 489b6743e8421687ef96cec557830acf258d1886 +Subproject commit e20ea0289e57fe5c8b78e66865176bb7af42939d diff --git a/vendor/irregex b/vendor/irregex deleted file mode 160000 index c948a70..0000000 --- a/vendor/irregex +++ /dev/null @@ -1 +0,0 @@ -Subproject commit c948a704fc732914a243c1643bfe359913d11c7b diff --git a/vendor/sci b/vendor/sci index 32d62a5..ebd5cfa 160000 --- a/vendor/sci +++ b/vendor/sci @@ -1 +1 @@ -Subproject commit 32d62a5136ad3dc148588752f5bcc4cc30b14752 +Subproject commit ebd5cfacda272eabf91f3168d56d08b64f770a80